@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
@@ -93,14 +93,21 @@ var import_node_forge = __toESM(require("node-forge"));
93
93
  var import_utils = require("./cryptography/utils.js");
94
94
  var import_userManagementClient = require("./external/userManagementClient.js");
95
95
  var mpcComputationClient = __toESM(require("./external/mpcComputationClient.js"));
96
- var import_shareDistribution = require("./shares/shareDistribution.js");
97
96
  var import_types = require("./types/index.js");
98
- var import_recovery = require("./shares/recovery.js");
99
97
  var import_utils2 = require("./utils/index.js");
98
+ var import_stateListener = require("./utils/stateListener.js");
100
99
  var import_errors = require("./errors.js");
101
100
  var constants = __toESM(require("./constants.js"));
102
101
  var import_enclave = require("./shares/enclave.js");
103
- var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, waitForLoginProcess_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
102
+ var import_AuthService = require("./services/AuthService.js");
103
+ var import_PollingService = require("./services/PollingService.js");
104
+ var import_CoreStateManager = require("./state/CoreStateManager.js");
105
+ var import_WalletService = require("./services/WalletService.js");
106
+ var import_PregenWalletService = require("./services/PregenWalletService.js");
107
+ var import_PortalUrlService = require("./services/PortalUrlService.js");
108
+ var import_SessionManagementService = require("./services/SessionManagementService.js");
109
+ var import_ExternalWalletService = require("./services/ExternalWalletService.js");
110
+ 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;
104
111
  if (typeof global !== "undefined") {
105
112
  global.Buffer = global.Buffer || import_buffer.Buffer;
106
113
  } else if (typeof window !== "undefined") {
@@ -114,26 +121,21 @@ const { pki, jsbn } = import_node_forge.default;
114
121
  const _ParaCore = class _ParaCore {
115
122
  constructor(envOrApiKey, apiKeyOrOpts, opts) {
116
123
  __privateAdd(this, _ParaCore_instances);
124
+ __privateAdd(this, _stateManager);
125
+ __privateAdd(this, _authService);
126
+ __privateAdd(this, _walletService);
127
+ __privateAdd(this, _externalWalletService);
128
+ __privateAdd(this, _pregenWalletService);
129
+ __privateAdd(this, _pollingService);
130
+ __privateAdd(this, _portalUrlService);
131
+ __privateAdd(this, _sessionManagementService);
132
+ __privateAdd(this, _debugLogsEnabled);
117
133
  this.popupWindow = null;
118
- __privateAdd(this, _authInfo);
119
134
  this.isSwitchingWallets = false;
120
135
  this.isNativePasskey = false;
121
- this.isReady = false;
136
+ this.isSetup = false;
122
137
  this.accountLinkInProgress = void 0;
123
- this.isEnclaveUser = false;
124
- this.isAwaitingAccountCreation = false;
125
- this.isAwaitingLogin = false;
126
- this.isAwaitingFarcaster = false;
127
- this.isAwaitingOAuth = false;
128
138
  this.isWorkerInitialized = false;
129
- /**
130
- * 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.
131
- */
132
- this.currentWalletIds = {};
133
- /**
134
- * Wallets associated with the `ParaCore` instance.
135
- */
136
- this.externalWallets = {};
137
139
  this.onRampPopup = void 0;
138
140
  this.nonPersistedStorageKeys = [];
139
141
  this.localStorageGetItem = (key) => {
@@ -167,7 +169,8 @@ const _ParaCore = class _ParaCore {
167
169
  return this.platformUtils.sessionStorage.removeItem(key);
168
170
  };
169
171
  this.retrieveSessionCookie = () => {
170
- return this.sessionCookie;
172
+ var _a;
173
+ return (_a = __privateGet(this, _sessionManagementService)) == null ? void 0 : _a.sessionCookie;
171
174
  };
172
175
  this.retrieveEnclaveJwt = () => {
173
176
  return this.enclaveJwt;
@@ -194,6 +197,10 @@ const _ParaCore = class _ParaCore {
194
197
  yield this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
195
198
  }
196
199
  });
200
+ __privateAdd(this, _servicesInitialized, false);
201
+ this.initExternalWalletProvider = (params) => __async(this, null, function* () {
202
+ yield __privateGet(this, _externalWalletService).initExternalWalletProvider(params);
203
+ });
197
204
  this.trackError = (methodName, err) => __async(this, null, function* () {
198
205
  try {
199
206
  yield this.ctx.client.trackError({
@@ -252,7 +259,7 @@ const _ParaCore = class _ParaCore {
252
259
  };
253
260
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
254
261
  }
255
- __privateSet(this, _authInfo, authInfo);
262
+ __privateGet(this, _authService).authInfo = authInfo;
256
263
  };
257
264
  this.updateEnclaveJwtFromStorage = () => {
258
265
  this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
@@ -265,7 +272,7 @@ const _ParaCore = class _ParaCore {
265
272
  }
266
273
  };
267
274
  this.updateUserIdFromStorage = () => {
268
- this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
275
+ __privateGet(this, _authService).userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
269
276
  };
270
277
  this.updateWalletsFromStorage = () => __async(this, null, function* () {
271
278
  var _a;
@@ -306,12 +313,13 @@ const _ParaCore = class _ParaCore {
306
313
  }, {}) : fromJson;
307
314
  })();
308
315
  this.setCurrentWalletIds(currentWalletIds);
309
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
316
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
310
317
  this.findWalletId(void 0, { forbidPregen: true });
311
318
  }
312
319
  };
313
320
  this.updateSessionCookieFromStorage = () => {
314
- this.sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
321
+ __privateGet(this, _sessionManagementService).sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
322
+ __privateGet(this, _sessionManagementService).isImportedSession = this.localStorageGetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION) === "true" || false;
315
323
  };
316
324
  this.updateLoginEncryptionKeyPairFromStorage = () => {
317
325
  const loginEncryptionKey = this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -334,6 +342,25 @@ const _ParaCore = class _ParaCore {
334
342
  }
335
343
  }
336
344
  });
345
+ this.setCurrentWalletIds = (...params) => __async(this, null, function* () {
346
+ const [currentWalletIds, { needsWallet = false, sessionLookupId, newDeviceSessionLookupId } = {}] = params;
347
+ return yield __privateGet(this, _walletService).setCurrentWalletIds(currentWalletIds, {
348
+ needsWallet,
349
+ sessionLookupId,
350
+ newDeviceSessionLookupId
351
+ });
352
+ });
353
+ /**
354
+ * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
355
+ * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
356
+ * @param {string} [walletId] the wallet ID to validate.
357
+ * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
358
+ * @returns {string} the wallet ID originally passed, or the one found.
359
+ */
360
+ this.findWalletId = (...params) => {
361
+ const [walletId, filters = {}] = params;
362
+ return __privateGet(this, _walletService).findWalletId(walletId, filters);
363
+ };
337
364
  /**
338
365
  * Creates several new wallets with the desired types. If no types are provided, this method
339
366
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -343,12 +370,8 @@ const _ParaCore = class _ParaCore {
343
370
  * @deprecated alias for `createWalletPerType`
344
371
  **/
345
372
  this.createWalletPerMissingType = this.createWalletPerType;
346
- __privateAdd(this, _isCreateGuestWalletsPending, false);
347
- this.getWalletBalance = (_0) => __async(this, [_0], function* ({
348
- walletId,
349
- rpcUrl
350
- }) {
351
- return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
373
+ this.addCredential = (params) => __async(this, null, function* () {
374
+ return yield __privateGet(this, _authService).addCredential(params);
352
375
  });
353
376
  let env, apiKey;
354
377
  const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
@@ -379,6 +402,7 @@ const _ParaCore = class _ParaCore {
379
402
  apiKey = apiKeyOrOpts;
380
403
  }
381
404
  if (!opts) opts = {};
405
+ __privateSet(this, _debugLogsEnabled, !!opts.enableDebugLogs);
382
406
  let isE2E = false;
383
407
  if (env === "E2E") {
384
408
  isE2E = true;
@@ -413,7 +437,7 @@ const _ParaCore = class _ParaCore {
413
437
  this.localStorageSetItem = this.sessionStorageSetItem;
414
438
  }
415
439
  this.persistSessionCookie = (cookie) => {
416
- this.sessionCookie = cookie;
440
+ __privateGet(this, _sessionManagementService).sessionCookie = cookie;
417
441
  (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
418
442
  constants.LOCAL_STORAGE_SESSION_COOKIE,
419
443
  cookie
@@ -468,6 +492,7 @@ const _ParaCore = class _ParaCore {
468
492
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
469
493
  return;
470
494
  }
495
+ this.initializeServices();
471
496
  this.initializeFromStorage();
472
497
  import_utils2.setupListeners.bind(this)();
473
498
  (0, import_utils2.autoBind)(this);
@@ -487,71 +512,183 @@ const _ParaCore = class _ParaCore {
487
512
  "signTransaction"
488
513
  ]);
489
514
  }
515
+ __privateGet(this, _stateManager).start();
490
516
  }
491
517
  setModalError(_error) {
492
518
  return;
493
519
  }
520
+ /**
521
+ * The current readiness state.
522
+ */
523
+ get isReady() {
524
+ return __privateGet(this, _stateManager).getSnapshot().isReady;
525
+ }
526
+ /**
527
+ * The current phase of the core flow.
528
+ */
529
+ get corePhase() {
530
+ return __privateGet(this, _stateManager).getSnapshot().phase;
531
+ }
532
+ /**
533
+ * The current phase of the authentication flow.
534
+ */
535
+ get authPhase() {
536
+ return __privateGet(this, _stateManager).getSnapshot().authStatePhase;
537
+ }
538
+ /**
539
+ * The current phase of the wallet flow.
540
+ */
541
+ get walletPhase() {
542
+ return __privateGet(this, _stateManager).getSnapshot().walletStatePhase;
543
+ }
544
+ /**
545
+ * Any error that has occurred in the core flow.
546
+ */
547
+ get error() {
548
+ return __privateGet(this, _stateManager).getSnapshot().error;
549
+ }
550
+ /**
551
+ * Get the current state of the core, auth, and wallet phases.
552
+ * @returns An object containing the current core, auth, and wallet state phases, along with any error.
553
+ */
554
+ getCurrentState() {
555
+ const state = __privateGet(this, _stateManager).getSnapshot();
556
+ return {
557
+ corePhase: state.phase,
558
+ authPhase: state.authStatePhase,
559
+ walletPhase: state.walletStatePhase,
560
+ authStateInfo: state.authStateInfo,
561
+ error: state.error,
562
+ isReady: state.isReady
563
+ };
564
+ }
565
+ /**
566
+ * Subscribe to changes in the core, auth, and wallet state phases.
567
+ *
568
+ * This method immediately calls the callback with the current state, then continues
569
+ * to call it whenever any phase changes. This ensures you never miss the initial state
570
+ * and can react to all subsequent changes.
571
+ *
572
+ * @param callback A function that will be called with the current state phases whenever they change.
573
+ * The callback receives an object containing `corePhase`, `authPhase`, `walletPhase`, and `error`.
574
+ *
575
+ * @returns A function that can be called to unsubscribe from the state changes.
576
+ * Always call this function when your component unmounts or when you no longer need updates
577
+ * to prevent memory leaks.
578
+ *
579
+ * @example
580
+ * ```typescript
581
+ * // React example
582
+ * useEffect(() => {
583
+ * const unsubscribe = paraClient.onStatePhaseChange((snapshot) => {
584
+ * console.log('Core phase:', snapshot.corePhase);
585
+ * console.log('Auth phase:', snapshot.authPhase);
586
+ * console.log('Wallet phase:', snapshot.walletPhase);
587
+ *
588
+ * if (snapshot.error) {
589
+ * console.error('Para error:', snapshot.error.message);
590
+ * }
591
+ * });
592
+ *
593
+ * return unsubscribe; // Cleanup on unmount
594
+ * }, [paraClient]);
595
+ *
596
+ * // Vue example
597
+ * onMounted(() => {
598
+ * const unsubscribe = paraClient.onStatePhaseChange((state) => {
599
+ * phases.value = state;
600
+ * });
601
+ *
602
+ * onUnmounted(unsubscribe);
603
+ * });
604
+ * ```
605
+ */
606
+ onStatePhaseChange(callback) {
607
+ let lastSnapshot = null;
608
+ const fullListener = (state) => {
609
+ const currentSnapshot = {
610
+ corePhase: state.phase,
611
+ authPhase: state.authStatePhase,
612
+ walletPhase: state.walletStatePhase,
613
+ authStateInfo: state.authStateInfo,
614
+ error: state.error,
615
+ isReady: state.isReady
616
+ };
617
+ if (!lastSnapshot || lastSnapshot.corePhase !== currentSnapshot.corePhase || lastSnapshot.authPhase !== currentSnapshot.authPhase || lastSnapshot.walletPhase !== currentSnapshot.walletPhase || lastSnapshot.error !== currentSnapshot.error || lastSnapshot.isReady !== currentSnapshot.isReady) {
618
+ lastSnapshot = currentSnapshot;
619
+ callback(currentSnapshot);
620
+ }
621
+ };
622
+ return __privateGet(this, _stateManager).onStateChange(fullListener);
623
+ }
624
+ /**
625
+ * Subscribe to changes in the readiness state of the ParaCore instance.
626
+ * @param callback A function that will be called with the new readiness state.
627
+ * @returns A function that can be called to unsubscribe from the readiness state changes.
628
+ */
629
+ onReadyStateChange(callback) {
630
+ let lastIsReady = null;
631
+ const unsubscribe = __privateGet(this, _stateManager).onStateChange((state) => {
632
+ if (lastIsReady !== state.isReady) {
633
+ lastIsReady = state.isReady;
634
+ callback(state.isReady);
635
+ }
636
+ });
637
+ return () => unsubscribe();
638
+ }
494
639
  get authInfo() {
495
- return __privateGet(this, _authInfo);
640
+ var _a;
641
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
496
642
  }
497
643
  get email() {
498
644
  var _a;
499
- return (0, import_user_management_client.isEmail)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.email : void 0;
645
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
500
646
  }
501
647
  get phone() {
502
648
  var _a;
503
- return (0, import_user_management_client.isPhone)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.phone : void 0;
649
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
504
650
  }
505
651
  get farcasterUsername() {
506
652
  var _a;
507
- return (0, import_user_management_client.isFarcaster)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.farcasterUsername : void 0;
653
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
508
654
  }
509
655
  get telegramUserId() {
510
656
  var _a;
511
- return (0, import_user_management_client.isTelegram)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.telegramUserId : void 0;
657
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.telegramUserId;
512
658
  }
513
659
  get externalWalletWithParaAuth() {
514
- const externalWallets = Object.values(this.externalWallets);
515
- return externalWallets.find((w) => w.isExternalWithParaAuth);
660
+ return __privateGet(this, _externalWalletService).externalWalletWithParaAuth;
516
661
  }
517
662
  get externalWalletConnectionType() {
518
- if (this.isExternalWalletAuth) {
519
- return "AUTHENTICATED";
520
- } else if (this.isExternalWalletWithVerification) {
521
- return "VERIFICATION";
522
- } else if (!!Object.keys(this.externalWallets).length) {
523
- const hasEmbeddedWallets = Object.keys(this.wallets).some((id) => !this.wallets[id].isExternal);
524
- if (hasEmbeddedWallets) {
525
- return "NONE";
526
- } else {
527
- return "CONNECTION_ONLY";
528
- }
529
- }
530
- return "NONE";
663
+ return __privateGet(this, _externalWalletService).externalWalletConnectionType;
531
664
  }
532
- get isEmail() {
665
+ get userId() {
533
666
  var _a;
534
- return (0, import_user_management_client.isEmail)((_a = this.authInfo) == null ? void 0 : _a.auth);
667
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
668
+ }
669
+ get isEnclaveUser() {
670
+ return __privateGet(this, _authService).isEnclaveUser;
671
+ }
672
+ set isEnclaveUser(value) {
673
+ __privateGet(this, _authService).isEnclaveUser = value;
674
+ }
675
+ get isEmail() {
676
+ return __privateGet(this, _authService).isEmail;
535
677
  }
536
678
  get isPhone() {
537
- var _a;
538
- return (0, import_user_management_client.isPhone)((_a = this.authInfo) == null ? void 0 : _a.auth);
679
+ return __privateGet(this, _authService).isPhone;
539
680
  }
540
681
  get isFarcaster() {
541
- var _a;
542
- return (0, import_user_management_client.isFarcaster)((_a = this.authInfo) == null ? void 0 : _a.auth);
682
+ return __privateGet(this, _authService).isFarcaster;
543
683
  }
544
684
  get isTelegram() {
545
- var _a;
546
- return (0, import_user_management_client.isTelegram)((_a = this.authInfo) == null ? void 0 : _a.auth);
685
+ return __privateGet(this, _authService).isTelegram;
547
686
  }
548
687
  get isExternalWalletAuth() {
549
- var _a, _b, _c;
550
- return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withFullParaAuth);
688
+ return __privateGet(this, _authService).isExternalWalletAuth;
551
689
  }
552
690
  get isExternalWalletWithVerification() {
553
- var _a, _b, _c;
554
- return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withVerification);
691
+ return __privateGet(this, _authService).isExternalWalletWithVerification;
555
692
  }
556
693
  get partnerId() {
557
694
  var _a;
@@ -565,45 +702,42 @@ const _ParaCore = class _ParaCore {
565
702
  var _a;
566
703
  return (_a = this.partner) == null ? void 0 : _a.logoUrl;
567
704
  }
705
+ get currentWalletIds() {
706
+ return __privateGet(this, _walletService).currentWalletIds;
707
+ }
568
708
  get currentWalletIdsArray() {
569
- var _a, _b;
570
- return ((_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
571
- (acc, { type }) => {
572
- var _a2;
573
- return [
574
- ...acc,
575
- ...((_a2 = this.currentWalletIds[type]) != null ? _a2 : []).map((id) => {
576
- return [id, type];
577
- })
578
- ];
579
- },
580
- []
581
- );
709
+ return __privateGet(this, _walletService).currentWalletIdsArray;
582
710
  }
583
711
  get currentWalletIdsUnique() {
584
- return [...new Set(Object.values(this.currentWalletIds).flat())];
712
+ return __privateGet(this, _walletService).currentWalletIdsUnique;
713
+ }
714
+ /**
715
+ * Wallets associated with the `ParaCore` instance. Retrieve a particular wallet using `para.wallets[walletId]`.
716
+ */
717
+ get wallets() {
718
+ var _a;
719
+ return (_a = __privateGet(this, _walletService)) == null ? void 0 : _a.wallets;
720
+ }
721
+ /**
722
+ * Wallets associated with the `ParaCore` instance.
723
+ */
724
+ get externalWallets() {
725
+ var _a;
726
+ return (_a = __privateGet(this, _externalWalletService)) == null ? void 0 : _a.externalWallets;
585
727
  }
586
728
  /**
587
729
  * A map of pre-generated wallet identifiers that can be claimed in the current instance.
588
730
  */
589
731
  get pregenIds() {
590
- return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
591
- var _a, _b;
592
- if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
593
- return acc;
594
- }
595
- return __spreadProps(__spreadValues({}, acc), {
596
- [wallet.pregenIdentifierType]: [
597
- .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
598
- ]
599
- });
600
- }, {}));
732
+ var _a;
733
+ return (_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.pregenIds;
601
734
  }
602
735
  /**
603
736
  * Whether the instance has multiple wallets connected.
604
737
  */
605
738
  get isMultiWallet() {
606
- return this.currentWalletIdsArray.length > 1 || __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 1;
739
+ var _a;
740
+ return this.currentWalletIdsArray.length > 1 || ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 1;
607
741
  }
608
742
  get isNoWalletConfig() {
609
743
  var _a;
@@ -668,60 +802,6 @@ const _ParaCore = class _ParaCore {
668
802
  );
669
803
  }
670
804
  }
671
- isWalletSupported(wallet) {
672
- var _a, _b;
673
- return !((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || (0, import_utils2.isWalletSupported)((_b = this.partner.supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
674
- }
675
- isWalletOwned(wallet) {
676
- 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;
677
- }
678
- isPregenWalletUnclaimed(wallet) {
679
- 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));
680
- }
681
- isPregenWalletClaimable(wallet) {
682
- return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || (0, import_utils2.isPregenIdentifierMatch)(
683
- (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
684
- wallet == null ? void 0 : wallet.pregenIdentifier,
685
- wallet == null ? void 0 : wallet.pregenIdentifierType
686
- ));
687
- }
688
- isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
689
- var _a, _b;
690
- let error;
691
- if ((_a = this.externalWallets) == null ? void 0 : _a[walletId]) {
692
- return true;
693
- }
694
- if (!this.wallets[walletId]) {
695
- error = `wallet with id ${walletId} does not exist`;
696
- } else {
697
- const wallet = this.wallets[walletId];
698
- const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
699
- if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
700
- error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
701
- } else if (!isOwned && !isUnclaimed) {
702
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
703
- } else if (!this.isWalletSupported(wallet)) {
704
- 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(", ")}`;
705
- } else if (types && (!(0, import_utils2.getEquivalentTypes)(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
706
- var _a2, _b2;
707
- return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
708
- }))) {
709
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
710
- } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
711
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
712
- }
713
- }
714
- if (error) {
715
- if (throwError) {
716
- throw new Error(error);
717
- }
718
- return false;
719
- }
720
- return true;
721
- }
722
- truncateAddress(...args) {
723
- return (0, import_utils2.truncateAddress)(args[0], args[1], __spreadValues({ prefix: this.cosmosPrefix }, args[2] || {}));
724
- }
725
805
  /**
726
806
  * Returns the formatted address for the desired wallet ID, depending on your app settings.
727
807
  * @param {string} walletId the ID of the wallet address to display.
@@ -730,32 +810,9 @@ const _ParaCore = class _ParaCore {
730
810
  * @param {TWalletType} options.addressType the type of address to display.
731
811
  * @returns the formatted address
732
812
  */
733
- getDisplayAddress(walletId, options = {}) {
734
- var _a, _b, _c, _d;
735
- if (this.externalWallets[walletId]) {
736
- const wallet2 = this.externalWallets[walletId];
737
- return options.truncate ? (0, import_utils2.truncateAddress)(wallet2.address, wallet2.type, {
738
- prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
739
- targetLength: options.targetLength
740
- }) : wallet2.address;
741
- }
742
- const wallet = this.findWallet(walletId, options.addressType);
743
- if (!wallet) {
744
- return void 0;
745
- }
746
- let str;
747
- let prefix;
748
- switch (wallet.type) {
749
- case "COSMOS":
750
- prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = this.partner) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
751
- str = (0, import_utils2.getCosmosAddress)(wallet.publicKey, prefix);
752
- break;
753
- default:
754
- prefix = this.cosmosPrefix;
755
- str = wallet.address;
756
- break;
757
- }
758
- return options.truncate ? (0, import_utils2.truncateAddress)(str, wallet.type, { prefix, targetLength: options.targetLength }) : str;
813
+ getDisplayAddress(...params) {
814
+ const [walletId, options = {}] = params;
815
+ return __privateGet(this, _walletService).getDisplayAddress(walletId, options);
759
816
  }
760
817
  /**
761
818
  * Returns a unique hash for a wallet suitable for use as an identicon seed.
@@ -763,13 +820,8 @@ const _ParaCore = class _ParaCore {
763
820
  * @param {boolean} options.addressType used to format the hash for another wallet type.
764
821
  * @returns the identicon hash string
765
822
  */
766
- getIdenticonHash(walletId, overrideType) {
767
- if (this.externalWallets[walletId]) {
768
- const wallet2 = this.externalWallets[walletId];
769
- return `${wallet2.id}-${wallet2.address}-${wallet2.type}`;
770
- }
771
- const wallet = this.findWallet(walletId, overrideType);
772
- return wallet ? `${wallet.id}-${wallet.address}-${wallet.type}` : void 0;
823
+ getIdenticonHash(...params) {
824
+ return __privateGet(this, _walletService).getIdenticonHash(...params);
773
825
  }
774
826
  getWallets() {
775
827
  return this.wallets;
@@ -780,192 +832,7 @@ const _ParaCore = class _ParaCore {
780
832
  }
781
833
  constructPortalUrl(_0) {
782
834
  return __async(this, arguments, function* (type, opts = {}) {
783
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
784
- const [
785
- isCreate,
786
- isLogin,
787
- isOnRamp,
788
- isOAuth,
789
- isOAuthCallback,
790
- isTelegramLogin,
791
- isFarcasterLogin,
792
- isAddNewCredential,
793
- isSwitchWallets,
794
- isExportPrivateKey,
795
- isTxReview
796
- ] = [
797
- ["createAuth", "createPassword", "createPIN"].includes(type),
798
- ["loginAuth", "loginPassword", "loginPIN", "loginOTP", "switchWallets", "loginExternalWallet"].includes(type),
799
- type === "onRamp",
800
- type === "oAuth",
801
- type === "oAuthCallback",
802
- ["telegramLogin", "telegramLoginVerify"].includes(type),
803
- type === "loginFarcaster",
804
- type === "addNewCredential",
805
- type === "switchWallets",
806
- type === "exportPrivateKey",
807
- type === "txReview"
808
- ];
809
- if (isOAuth && !opts.oAuthMethod) {
810
- throw new Error("oAuthMethod is required for oAuth portal URLs");
811
- }
812
- if (isCreate || isLogin) {
813
- this.assertIsAuthSet();
814
- }
815
- let sessionId = opts.sessionId;
816
- if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin || isExportPrivateKey || isTxReview) && !sessionId) {
817
- let session = yield this.touchSession(false);
818
- if (!session.sessionId) {
819
- session = yield this.touchSession(true);
820
- }
821
- sessionId = session.sessionId;
822
- }
823
- if (!this.loginEncryptionKeyPair) {
824
- yield this.setLoginEncryptionKeyPair();
825
- }
826
- const shouldUseLegacyPortalUrl = opts.useLegacyUrl || !!opts.addNewCredentialPasskeyId || type === "loginAuth";
827
- const base = type === "onRamp" || isTelegramLogin ? this.ctx.portalUrlOverride || (0, import_utils2.getPortalBaseURL)(this.ctx, isTelegramLogin, false, shouldUseLegacyPortalUrl) : yield this.getPortalURL(shouldUseLegacyPortalUrl);
828
- let path;
829
- switch (type) {
830
- case "createPassword": {
831
- path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
832
- break;
833
- }
834
- case "createPIN": {
835
- path = `/web/users/${this.userId}/pin/${opts.pathId}`;
836
- break;
837
- }
838
- case "createAuth": {
839
- path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
840
- break;
841
- }
842
- case "loginPassword": {
843
- path = "/web/passwords/login";
844
- break;
845
- }
846
- case "loginAuth": {
847
- path = "/web/biometrics/login";
848
- break;
849
- }
850
- case "loginPIN": {
851
- path = "/web/pin/login";
852
- break;
853
- }
854
- case "txReview": {
855
- path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
856
- break;
857
- }
858
- case "onRamp": {
859
- path = `/web/users/${this.userId}/on-ramp-transaction/v2/${opts.pathId}`;
860
- break;
861
- }
862
- case "telegramLoginVerify": {
863
- path = `/auth/telegram/verify`;
864
- break;
865
- }
866
- case "telegramLogin": {
867
- path = `/auth/telegram`;
868
- break;
869
- }
870
- case "oAuth": {
871
- path = `/auth/${opts.oAuthMethod.toLowerCase()}`;
872
- break;
873
- }
874
- case "oAuthCallback": {
875
- path = `/auth/${opts.oAuthMethod.toLowerCase()}/callback`;
876
- break;
877
- }
878
- case "loginOTP": {
879
- path = "/auth/otp";
880
- break;
881
- }
882
- case "loginFarcaster": {
883
- path = "/auth/farcaster";
884
- break;
885
- }
886
- case "switchWallets": {
887
- path = `/auth/wallets`;
888
- break;
889
- }
890
- case "addNewCredential": {
891
- path = "/auth/add-new-credential";
892
- break;
893
- }
894
- case "exportPrivateKey": {
895
- path = `/web/users/${this.userId}/private-key/${opts.pathId}`;
896
- break;
897
- }
898
- case "loginExternalWallet": {
899
- path = "/auth/external-wallet";
900
- break;
901
- }
902
- case "connectExternalWallet": {
903
- path = "/auth/connect-external-wallet";
904
- break;
905
- }
906
- default: {
907
- throw new Error(`invalid URL type ${type}`);
908
- }
909
- }
910
- let partner = void 0;
911
- try {
912
- partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
913
- } catch (e) {
914
- if (this.isPartnerOptional) {
915
- partner = void 0;
916
- } else {
917
- throw e;
918
- }
919
- }
920
- const thisDevice = (_a = opts.thisDevice) != null ? _a : {
921
- encryptionKey: (0, import_utils.getPublicKeyHex)(this.loginEncryptionKeyPair),
922
- sessionId
923
- };
924
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({
925
- apiKey: this.ctx.apiKey,
926
- origin: typeof window !== "undefined" ? window.location.origin : void 0,
927
- partnerId: partner == null ? void 0 : partner.id
928
- }, typeof window !== "undefined" && ((_b = window.location) == null ? void 0 : _b.origin) ? { origin: window.location.origin } : {}), {
929
- portalFont: ((_c = opts.portalTheme) == null ? void 0 : _c.font) || ((_d = this.portalTheme) == null ? void 0 : _d.font) || (partner == null ? void 0 : partner.font),
930
- portalBorderRadius: ((_e = opts.portalTheme) == null ? void 0 : _e.borderRadius) || ((_f = this.portalTheme) == null ? void 0 : _f.borderRadius),
931
- portalThemeMode: ((_g = opts.portalTheme) == null ? void 0 : _g.mode) || ((_h = this.portalTheme) == null ? void 0 : _h.mode) || (partner == null ? void 0 : partner.themeMode),
932
- portalAccentColor: ((_i = opts.portalTheme) == null ? void 0 : _i.accentColor) || ((_j = this.portalTheme) == null ? void 0 : _j.accentColor) || (partner == null ? void 0 : partner.accentColor),
933
- portalForegroundColor: ((_k = opts.portalTheme) == null ? void 0 : _k.foregroundColor) || ((_l = this.portalTheme) == null ? void 0 : _l.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor),
934
- 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,
935
- portalPrimaryButtonColor: this.portalPrimaryButtonColor,
936
- portalTextColor: this.portalTextColor,
937
- portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
938
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
939
- }), this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets || isExportPrivateKey || isTxReview) ? __spreadProps(__spreadValues({
940
- authInfo: JSON.stringify(this.authInfo)
941
- }, (0, import_user_management_client.isPhone)(this.authInfo.auth) ? (0, import_utils2.splitPhoneNumber)(this.authInfo.auth.phone) : this.authInfo.auth), {
942
- pfpUrl: this.authInfo.pfpUrl,
943
- displayName: this.authInfo.displayName,
944
- userId: this.userId
945
- }) : {}), isOnRamp ? { email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin || isAddNewCredential ? __spreadProps(__spreadValues({
946
- sessionId: thisDevice.sessionId,
947
- encryptionKey: thisDevice.encryptionKey
948
- }, opts.newDevice ? {
949
- newDeviceSessionLookupId: opts.newDevice.sessionId,
950
- newDeviceEncryptionKey: opts.newDevice.encryptionKey
951
- } : {}), {
952
- pregenIds: JSON.stringify(this.pregenIds)
953
- }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
954
- appScheme: opts.appScheme
955
- } : {}), 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() }), {
956
- addNewCredentialPasskeyId: opts.addNewCredentialPasskeyId,
957
- addNewCredentialPasswordId: opts.addNewCredentialPasswordId
958
- }) : {}), isLogin && {
959
- // Prior versions won't have this param which will skip the upgrade prompt
960
- isBasicLoginUpgradeVersion: "true"
961
- }), isExportPrivateKey || isTxReview ? {
962
- sessionId: thisDevice.sessionId
963
- } : {});
964
- const url = (0, import_utils2.constructUrl)({ base, path, params });
965
- if (opts.shorten) {
966
- return yield (0, import_utils2.shortenUrl)(this.ctx, url, shouldUseLegacyPortalUrl);
967
- }
968
- return url;
835
+ return yield __privateGet(this, _portalUrlService).constructPortalUrl(type, opts);
969
836
  });
970
837
  }
971
838
  static resolveEnvironment(env, apiKey) {
@@ -987,58 +854,239 @@ const _ParaCore = class _ParaCore {
987
854
  }
988
855
  return env;
989
856
  }
990
- touchSession(regenerate = false) {
991
- return __async(this, null, function* () {
992
- var _a, _b, _c, _d, _e;
993
- if (!this.isWorkerInitialized) {
994
- this.initializeWorker();
995
- }
996
- if (!this.isReady) {
997
- yield this.ready();
857
+ initializeServices() {
858
+ if (__privateGet(this, _servicesInitialized)) return;
859
+ __privateSet(this, _authService, new import_AuthService.AuthService(this));
860
+ __privateSet(this, _walletService, new import_WalletService.WalletService(this));
861
+ __privateSet(this, _externalWalletService, new import_ExternalWalletService.ExternalWalletService(this));
862
+ __privateSet(this, _pregenWalletService, new import_PregenWalletService.PregenWalletService(this));
863
+ __privateSet(this, _pollingService, new import_PollingService.PollingService(this));
864
+ __privateSet(this, _portalUrlService, new import_PortalUrlService.PortalUrlService(this));
865
+ __privateSet(this, _sessionManagementService, new import_SessionManagementService.SessionManagementService(this));
866
+ __privateSet(this, _stateManager, new import_CoreStateManager.CoreStateManager(this));
867
+ __privateGet(this, _authService).init({
868
+ stateManager: __privateGet(this, _stateManager),
869
+ portalUrlService: __privateGet(this, _portalUrlService),
870
+ externalWalletService: __privateGet(this, _externalWalletService),
871
+ sessionManagementService: __privateGet(this, _sessionManagementService),
872
+ pregenWalletService: __privateGet(this, _pregenWalletService),
873
+ walletService: __privateGet(this, _walletService)
874
+ });
875
+ __privateGet(this, _walletService).init({
876
+ authService: __privateGet(this, _authService),
877
+ pollingService: __privateGet(this, _pollingService),
878
+ pregenWalletService: __privateGet(this, _pregenWalletService),
879
+ externalWalletService: __privateGet(this, _externalWalletService)
880
+ });
881
+ __privateGet(this, _externalWalletService).init({
882
+ stateManager: __privateGet(this, _stateManager),
883
+ authService: __privateGet(this, _authService),
884
+ walletService: __privateGet(this, _walletService)
885
+ });
886
+ __privateGet(this, _pollingService).init({
887
+ authService: __privateGet(this, _authService),
888
+ pregenWalletService: __privateGet(this, _pregenWalletService),
889
+ walletService: __privateGet(this, _walletService),
890
+ portalUrlService: __privateGet(this, _portalUrlService),
891
+ sessionManagementService: __privateGet(this, _sessionManagementService)
892
+ });
893
+ __privateGet(this, _pregenWalletService).init({
894
+ stateManager: __privateGet(this, _stateManager),
895
+ authService: __privateGet(this, _authService),
896
+ walletService: __privateGet(this, _walletService),
897
+ pollingService: __privateGet(this, _pollingService)
898
+ });
899
+ __privateGet(this, _portalUrlService).init({
900
+ authService: __privateGet(this, _authService),
901
+ walletService: __privateGet(this, _walletService),
902
+ pregenWalletService: __privateGet(this, _pregenWalletService),
903
+ sessionManagementService: __privateGet(this, _sessionManagementService)
904
+ });
905
+ __privateGet(this, _sessionManagementService).init({
906
+ authService: __privateGet(this, _authService),
907
+ portalUrlService: __privateGet(this, _portalUrlService),
908
+ walletService: __privateGet(this, _walletService),
909
+ pregenWalletService: __privateGet(this, _pregenWalletService),
910
+ externalWalletService: __privateGet(this, _externalWalletService)
911
+ });
912
+ __privateSet(this, _servicesInitialized, true);
913
+ }
914
+ // Create a dedicated interface for #authService
915
+ getAuthServiceInterface() {
916
+ const self2 = this;
917
+ return {
918
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
919
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
920
+ localStorageGetItem: this.localStorageGetItem.bind(this),
921
+ localStorageSetItem: this.localStorageSetItem.bind(this),
922
+ localStorageRemoveItem: this.localStorageRemoveItem.bind(this),
923
+ isPasskeySupported: this.isPasskeySupported.bind(this),
924
+ getVerificationEmailProps: this.getVerificationEmailProps.bind(this),
925
+ displayModalError: this.displayModalError.bind(this),
926
+ isPortal: this.isPortal.bind(this),
927
+ assertIsLinkingAccount: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).bind(this),
928
+ requireApiKey: this.requireApiKey.bind(this),
929
+ get loginEncryptionKeyPair() {
930
+ return self2.loginEncryptionKeyPair;
931
+ },
932
+ get isNativePasskey() {
933
+ return self2.isNativePasskey;
934
+ },
935
+ ctx: this.ctx,
936
+ get accountLinkInProgress() {
937
+ return self2.accountLinkInProgress;
938
+ },
939
+ partnerId: this.partnerId,
940
+ platformUtils: this.platformUtils,
941
+ externalWalletConnectionOnly: !!this.externalWalletConnectionOnly
942
+ };
943
+ }
944
+ // Create a dedicated interface for WalletService
945
+ getWalletServiceInterface() {
946
+ const self2 = this;
947
+ return {
948
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
949
+ requireApiKey: this.requireApiKey.bind(this),
950
+ isPortal: this.isPortal.bind(this),
951
+ localStorageSetItem: this.localStorageSetItem.bind(this),
952
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
953
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
954
+ isParaConnect: this.isParaConnect.bind(this),
955
+ ctx: this.ctx,
956
+ get partner() {
957
+ return self2.partner;
958
+ },
959
+ platformUtils: this.platformUtils,
960
+ cosmosPrefix: this.cosmosPrefix
961
+ };
962
+ }
963
+ // Create a dedicated interface for PregenWalletService
964
+ getPregenWalletServiceInterface() {
965
+ var _a;
966
+ const self2 = this;
967
+ return {
968
+ fetchPregenWalletsOverride: (_a = this.fetchPregenWalletsOverride) == null ? void 0 : _a.bind(this),
969
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
970
+ requireApiKey: this.requireApiKey.bind(this),
971
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
972
+ isPortal: this.isPortal.bind(this),
973
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
974
+ ctx: this.ctx,
975
+ platformUtils: this.platformUtils,
976
+ get partner() {
977
+ return self2.partner;
998
978
  }
999
- let session;
1000
- try {
1001
- session = yield this.ctx.client.touchSession(regenerate);
1002
- } catch (error) {
1003
- this.handleTouchSessionError(error);
1004
- throw error;
979
+ };
980
+ }
981
+ // Create a dedicated interface for PortalUrlService
982
+ getPortalUrlServiceInterface() {
983
+ const self2 = this;
984
+ return {
985
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
986
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
987
+ isPortal: this.isPortal.bind(this),
988
+ isPartnerOptional: this.isPartnerOptional,
989
+ ctx: this.ctx,
990
+ get loginEncryptionKeyPair() {
991
+ return self2.loginEncryptionKeyPair;
992
+ },
993
+ get portalTheme() {
994
+ return self2.portalTheme;
995
+ },
996
+ get portalPrimaryButtonColor() {
997
+ return self2.portalPrimaryButtonColor;
998
+ },
999
+ get portalTextColor() {
1000
+ return self2.portalTextColor;
1001
+ },
1002
+ get portalPrimaryButtonTextColor() {
1003
+ return self2.portalPrimaryButtonTextColor;
1004
+ },
1005
+ get portalBackgroundColor() {
1006
+ return self2.portalBackgroundColor;
1007
+ },
1008
+ get accountLinkInProgress() {
1009
+ return self2.accountLinkInProgress;
1005
1010
  }
1006
- if (!this.partner || ((_a = this.partner) == null ? void 0 : _a.id) !== session.partnerId || !(0, import_utils2.supportedWalletTypesEq)(((_b = this.partner) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = this.partner) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
1007
- if (!session.partnerId && !this.isPortal()) {
1008
- this.displayModalError(
1009
- `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
1010
- );
1011
- console.error(`
1012
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
1013
- \u{1F6A8} PARA SDK CONFIGURATION ERROR \u{1F6A8}
1014
-
1015
- INVALID API KEY FOR CONFIGURED ENVIRONMENT
1016
-
1017
- Your API key does not match the configured environment. This usually means:
1018
-
1019
- 1. You're using a production API key with a development environment
1020
- 2. You're using a development API key with a production environment
1021
- 3. Your API key is invalid or has been regenerated
1022
-
1023
- SOLUTION:
1024
- \u2022 Verify your API key at: https://developer.getpara.com
1025
- \u2022 If your API key doesn't contain an environment prefix, ensure your API key is the correct key for your target environment
1026
-
1027
- Current Environment: ${this.ctx.env}
1028
- API Key Prefix: ${((_e = this.ctx.apiKey) == null ? void 0 : _e.split("_")[0].toUpperCase()) || "None"}
1029
-
1030
- Need help? Visit: https://docs.getpara.com or contact support
1031
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
1032
- `);
1033
- throw new Error("Invalid API Key.");
1034
- } else {
1035
- yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
1036
- }
1011
+ };
1012
+ }
1013
+ // Create a dedicated interface for SessionManagementService
1014
+ getSessionManagementServiceInterface() {
1015
+ const self2 = this;
1016
+ return {
1017
+ displayModalError: this.displayModalError.bind(this),
1018
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
1019
+ initializeWorker: this.initializeWorker.bind(this),
1020
+ isPortal: this.isPortal.bind(this),
1021
+ getPartner: this.getPartner.bind(this),
1022
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
1023
+ platformUtils: this.platformUtils,
1024
+ ctx: this.ctx,
1025
+ get loginEncryptionKeyPair() {
1026
+ return self2.loginEncryptionKeyPair;
1027
+ },
1028
+ get partner() {
1029
+ return self2.partner;
1030
+ },
1031
+ get isWorkerInitialized() {
1032
+ return self2.isWorkerInitialized;
1033
+ },
1034
+ get isReady() {
1035
+ return self2.isReady;
1036
+ },
1037
+ isNoWalletConfig: this.isNoWalletConfig,
1038
+ get isSwitchingWallets() {
1039
+ return self2.isSwitchingWallets;
1037
1040
  }
1038
- if (session.currentWalletIds && !(0, import_utils2.currentWalletIdsEq)(session.currentWalletIds, this.currentWalletIds)) {
1039
- yield this.setCurrentWalletIds(session.currentWalletIds);
1041
+ };
1042
+ }
1043
+ getStateMachineInterface() {
1044
+ const self2 = this;
1045
+ return {
1046
+ setup: this.setup.bind(this),
1047
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
1048
+ isPortal: this.isPortal.bind(this),
1049
+ setupAfterLogin: this.setupAfterLogin.bind(this),
1050
+ devLog: this.devLog.bind(this),
1051
+ authService: __privateGet(this, _authService),
1052
+ walletService: __privateGet(this, _walletService),
1053
+ pregenWalletService: __privateGet(this, _pregenWalletService),
1054
+ pollingService: __privateGet(this, _pollingService),
1055
+ externalWalletService: __privateGet(this, _externalWalletService),
1056
+ sessionManagementService: __privateGet(this, _sessionManagementService),
1057
+ portalUrlService: __privateGet(this, _portalUrlService),
1058
+ get isNoWalletConfig() {
1059
+ return self2.isNoWalletConfig;
1040
1060
  }
1041
- return session;
1061
+ };
1062
+ }
1063
+ // Create a dedicated interface for ExternalWalletService
1064
+ getExternalWalletServiceInterface() {
1065
+ return {
1066
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
1067
+ localStorageSetItem: this.localStorageSetItem.bind(this),
1068
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this)
1069
+ };
1070
+ }
1071
+ // Create a dedicated interface for PollingService
1072
+ getPollingServiceInterface() {
1073
+ const self2 = this;
1074
+ return {
1075
+ isPortal: this.isPortal.bind(this),
1076
+ devLog: this.devLog.bind(this),
1077
+ get popupWindow() {
1078
+ return self2.popupWindow;
1079
+ },
1080
+ set popupWindow(w) {
1081
+ self2.popupWindow = w;
1082
+ },
1083
+ platformUtils: this.platformUtils,
1084
+ ctx: this.ctx
1085
+ };
1086
+ }
1087
+ touchSession(regenerate = false) {
1088
+ return __async(this, null, function* () {
1089
+ return __privateGet(this, _sessionManagementService).touchSession(regenerate);
1042
1090
  });
1043
1091
  }
1044
1092
  getVerificationEmailProps() {
@@ -1071,7 +1119,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1071
1119
  init() {
1072
1120
  return __async(this, null, function* () {
1073
1121
  var _a, _b;
1074
- this.userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1122
+ this.initializeServices();
1123
+ __privateGet(this, _authService).userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1075
1124
  const storageAuthInfo = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_AUTH_INFO)) || void 0;
1076
1125
  const stringExternalWallets = yield this.localStorageGetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS);
1077
1126
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
@@ -1089,7 +1138,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1089
1138
  };
1090
1139
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
1091
1140
  }
1092
- __privateSet(this, _authInfo, authInfo);
1141
+ __privateGet(this, _authService).authInfo = authInfo;
1093
1142
  const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_WALLETS);
1094
1143
  const _wallets = JSON.parse(stringWallets || "{}");
1095
1144
  const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_ED25519_WALLETS);
@@ -1113,8 +1162,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1113
1162
  }, {}) : fromJson;
1114
1163
  })();
1115
1164
  yield this.setCurrentWalletIds(currentWalletIds);
1116
- this.sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1117
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1165
+ __privateGet(this, _sessionManagementService).sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1166
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1118
1167
  this.findWalletId(void 0, { forbidPregen: true });
1119
1168
  }
1120
1169
  const loginEncryptionKey = yield this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -1126,17 +1175,14 @@ Need help? Visit: https://docs.getpara.com or contact support
1126
1175
  this.isEnclaveUser = JSON.parse(storedIsEnclaveUser);
1127
1176
  }
1128
1177
  import_utils2.setupListeners.bind(this)();
1178
+ (0, import_utils2.autoBind)(this);
1179
+ __privateGet(this, _stateManager).start();
1129
1180
  yield this.touchSession();
1130
1181
  });
1131
1182
  }
1132
1183
  setAuth(_0) {
1133
1184
  return __async(this, arguments, function* (auth, { extras = {}, userId } = {}) {
1134
- const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client.extractAuthInfo)(auth, { isRequired: true })), extras || {});
1135
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
1136
- if (!!userId) {
1137
- yield this.setUserId(userId);
1138
- }
1139
- return __privateGet(this, _authInfo);
1185
+ return yield __privateGet(this, _authService).setAuth(auth, { extras, userId });
1140
1186
  });
1141
1187
  }
1142
1188
  /**
@@ -1148,40 +1194,11 @@ Need help? Visit: https://docs.getpara.com or contact support
1148
1194
  this.setModalError(error);
1149
1195
  }
1150
1196
  }
1151
- /**
1152
- * Handle specific touchSession errors with user-friendly messages
1153
- * @private
1154
- */
1155
- handleTouchSessionError(error) {
1156
- const errorStr = String(error);
1157
- const errorMessage = error instanceof Error ? error.message : "";
1158
- if (errorStr.includes("blocked by CORS policy") && errorStr.includes("Access-Control-Allow-Origin")) {
1159
- const message = "Request rate limit reached. Please wait a couple of minutes and try again.";
1160
- console.error(`[Para] ${message}`);
1161
- this.displayModalError(message);
1162
- return;
1163
- }
1164
- if (error.status === 403 && errorMessage.includes("origin not authorized")) {
1165
- this.displayModalError(
1166
- "The current origin is not allowed. Update your allowed origins in the Para developer portal to allow the current origin."
1167
- );
1168
- return;
1169
- }
1170
- }
1171
1197
  assertUserId({ allowGuestMode = false } = {}) {
1172
- if (!this.userId || !allowGuestMode && this.isGuestMode) {
1173
- throw new Error("no userId is set");
1174
- }
1175
- return this.userId;
1198
+ return __privateGet(this, _authService).assertUserId({ allowGuestMode });
1176
1199
  }
1177
1200
  assertIsAuthSet(allowed) {
1178
- if (!__privateGet(this, _authInfo)) {
1179
- throw new Error("auth is not set");
1180
- }
1181
- if (allowed && !allowed.includes(__privateGet(this, _authInfo).authType)) {
1182
- throw new Error(`invalid auth type, expected ${allowed.join(", ")}`);
1183
- }
1184
- return __privateGet(this, _authInfo);
1201
+ return __privateGet(this, _authService).assertIsAuthSet(allowed);
1185
1202
  }
1186
1203
  /**
1187
1204
  * Sets the email associated with the `ParaCore` instance.
@@ -1189,7 +1206,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1189
1206
  */
1190
1207
  setEmail(email) {
1191
1208
  return __async(this, null, function* () {
1192
- yield this.setAuth({ email });
1209
+ yield __privateGet(this, _authService).setAuth({ email });
1193
1210
  });
1194
1211
  }
1195
1212
  /**
@@ -1198,7 +1215,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1198
1215
  */
1199
1216
  setTelegramUserId(telegramUserId) {
1200
1217
  return __async(this, null, function* () {
1201
- yield this.setAuth({ telegramUserId });
1218
+ yield __privateGet(this, _authService).setAuth({ telegramUserId });
1202
1219
  });
1203
1220
  }
1204
1221
  /**
@@ -1208,7 +1225,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1208
1225
  */
1209
1226
  setPhoneNumber(phone, countryCode) {
1210
1227
  return __async(this, null, function* () {
1211
- yield this.setAuth({ phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) });
1228
+ yield __privateGet(this, _authService).setAuth({ phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) });
1212
1229
  });
1213
1230
  }
1214
1231
  /**
@@ -1217,7 +1234,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1217
1234
  */
1218
1235
  setFarcasterUsername(farcasterUsername) {
1219
1236
  return __async(this, null, function* () {
1220
- yield this.setAuth({ farcasterUsername });
1237
+ yield __privateGet(this, _authService).setAuth({ farcasterUsername });
1221
1238
  });
1222
1239
  }
1223
1240
  /**
@@ -1227,75 +1244,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1227
1244
  */
1228
1245
  setExternalWallet(externalWallet) {
1229
1246
  return __async(this, null, function* () {
1230
- const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1231
- this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1232
- (acc, {
1233
- partnerId: wPartnerId,
1234
- address,
1235
- type,
1236
- provider,
1237
- providerId,
1238
- addressBech32,
1239
- withFullParaAuth,
1240
- isConnectionOnly,
1241
- withVerification
1242
- }) => {
1243
- if (partnerId === wPartnerId && supportedWalletTypes.some(({ type: supportedType }) => supportedType === type)) {
1244
- return __spreadProps(__spreadValues({}, acc), {
1245
- [address]: {
1246
- id: address,
1247
- partnerId,
1248
- address: addressBech32 != null ? addressBech32 : address,
1249
- type,
1250
- name: provider,
1251
- isExternal: true,
1252
- isExternalWithParaAuth: withFullParaAuth,
1253
- externalProviderId: providerId,
1254
- signer: "",
1255
- isExternalConnectionOnly: isConnectionOnly,
1256
- isExternalWithVerification: withVerification
1257
- }
1258
- });
1259
- }
1260
- return acc;
1261
- },
1262
- {}
1263
- ), this.setExternalWallets(this.externalWallets);
1264
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1247
+ return yield __privateGet(this, _externalWalletService).setExternalWallet({ externalWallet });
1265
1248
  });
1266
1249
  }
1267
1250
  addExternalWallets(externalWallets) {
1268
1251
  return __async(this, null, function* () {
1269
- const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1270
- this.externalWallets = __spreadValues(__spreadValues({}, Object.entries(this.externalWallets).reduce((acc, [address, wallet]) => {
1271
- if (partnerId === wallet.partnerId && supportedWalletTypes.some(({ type }) => type === wallet.type)) {
1272
- return __spreadProps(__spreadValues({}, acc), {
1273
- [address]: wallet
1274
- });
1275
- }
1276
- return acc;
1277
- }, {})), externalWallets.reduce(
1278
- (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
1279
- return __spreadProps(__spreadValues({}, acc), {
1280
- [address]: {
1281
- id: address,
1282
- partnerId,
1283
- address: addressBech32 != null ? addressBech32 : address,
1284
- type,
1285
- name: provider,
1286
- isExternal: true,
1287
- isExternalWithParaAuth: withFullParaAuth,
1288
- externalProviderId: providerId,
1289
- signer: "",
1290
- isExternalConnectionOnly: isConnectionOnly,
1291
- isExternalWithVerification: withVerification
1292
- }
1293
- });
1294
- },
1295
- {}
1296
- ));
1297
- this.setExternalWallets(this.externalWallets);
1298
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1252
+ return yield __privateGet(this, _externalWalletService).addExternalWallets({ externalWallets });
1299
1253
  });
1300
1254
  }
1301
1255
  /**
@@ -1304,8 +1258,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1304
1258
  */
1305
1259
  setUserId(userId) {
1306
1260
  return __async(this, null, function* () {
1307
- this.userId = userId;
1308
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_USER_ID, userId);
1261
+ return yield __privateGet(this, _authService).setUserId(userId);
1309
1262
  });
1310
1263
  }
1311
1264
  /**
@@ -1314,12 +1267,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1314
1267
  */
1315
1268
  setWallets(wallets) {
1316
1269
  return __async(this, null, function* () {
1317
- this.wallets = wallets;
1318
- if (this.platformUtils.secureStorage) {
1319
- yield this.platformUtils.secureStorage.set(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1320
- return;
1321
- }
1322
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1270
+ return yield __privateGet(this, _walletService).setWallets(wallets);
1323
1271
  });
1324
1272
  }
1325
1273
  /**
@@ -1328,12 +1276,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1328
1276
  */
1329
1277
  setExternalWallets(externalWallets) {
1330
1278
  return __async(this, null, function* () {
1331
- if (typeof externalWallets === "function") {
1332
- this.externalWallets = externalWallets(this.externalWallets);
1333
- } else {
1334
- this.externalWallets = externalWallets;
1335
- }
1336
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(this.externalWallets));
1279
+ return yield __privateGet(this, _externalWalletService).setExternalWallets({ externalWallets });
1337
1280
  });
1338
1281
  }
1339
1282
  /**
@@ -1360,51 +1303,36 @@ Need help? Visit: https://docs.getpara.com or contact support
1360
1303
  * @returns - userId associated with the `ParaCore` instance.
1361
1304
  */
1362
1305
  getUserId() {
1363
- return this.userId;
1306
+ var _a;
1307
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
1364
1308
  }
1365
1309
  getAuthInfo() {
1366
- return this.authInfo;
1310
+ var _a;
1311
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
1367
1312
  }
1368
1313
  /**
1369
1314
  * Gets the email associated with the `ParaCore` instance.
1370
1315
  * @returns - email associated with the `ParaCore` instance.
1371
1316
  */
1372
1317
  getEmail() {
1373
- return this.email;
1318
+ var _a;
1319
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
1374
1320
  }
1375
1321
  /**
1376
1322
  * Gets the formatted phone number associated with the `ParaCore` instance.
1377
1323
  * @returns - formatted phone number associated with the `ParaCore` instance.
1378
1324
  */
1379
1325
  getPhoneNumber() {
1380
- return this.phone;
1326
+ var _a;
1327
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
1381
1328
  }
1382
1329
  /**
1383
1330
  * Gets the farcaster username associated with the `ParaCore` instance.
1384
1331
  * @returns - farcaster username associated with the `ParaCore` instance.
1385
1332
  */
1386
1333
  getFarcasterUsername() {
1387
- return this.farcasterUsername;
1388
- }
1389
- setCurrentWalletIds(_0) {
1390
- return __async(this, arguments, function* (currentWalletIds, {
1391
- needsWallet = false,
1392
- sessionLookupId,
1393
- newDeviceSessionLookupId
1394
- } = {}) {
1395
- this.currentWalletIds = currentWalletIds;
1396
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1397
- if (sessionLookupId) {
1398
- yield this.ctx.client.setCurrentWalletIds(
1399
- this.getUserId(),
1400
- this.currentWalletIds,
1401
- needsWallet,
1402
- sessionLookupId,
1403
- newDeviceSessionLookupId
1404
- );
1405
- }
1406
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.WALLETS_CHANGE_EVENT, null);
1407
- });
1334
+ var _a;
1335
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
1408
1336
  }
1409
1337
  /**
1410
1338
  * Fetches the most recent OAuth account metadata for the signed-in user.
@@ -1422,29 +1350,6 @@ Need help? Visit: https://docs.getpara.com or contact support
1422
1350
  return accountMetadata;
1423
1351
  });
1424
1352
  }
1425
- /**
1426
- * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
1427
- * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1428
- * @param {string} [walletId] the wallet ID to validate.
1429
- * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1430
- * @returns {string} the wallet ID originally passed, or the one found.
1431
- */
1432
- findWalletId(walletId, filter = {}) {
1433
- if (walletId) {
1434
- this.assertIsValidWalletId(walletId, filter);
1435
- } else {
1436
- for (const id of [...this.currentWalletIdsUnique, ...Object.keys(this.wallets)]) {
1437
- if (this.isWalletUsable(id, filter)) {
1438
- walletId = id;
1439
- break;
1440
- }
1441
- }
1442
- if (!walletId) {
1443
- throw new Error(`no valid wallet id found`);
1444
- }
1445
- }
1446
- return walletId;
1447
- }
1448
1353
  /**
1449
1354
  * Retrieves a wallet with the given address, if present.
1450
1355
  * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
@@ -1452,78 +1357,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1452
1357
  * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1453
1358
  * @returns {string} the wallet ID originally passed, or the one found.
1454
1359
  */
1455
- findWalletByAddress(address, filter) {
1456
- if (this.externalWallets[address]) {
1457
- return this.externalWallets[address];
1458
- }
1459
- let wallet;
1460
- Object.entries(this.currentWalletIds).forEach(([type, walletIds]) => {
1461
- const pregenWalletIds = Object.keys(this.wallets).filter(
1462
- (id) => this.wallets[id].type === type && this.isPregenWalletClaimable(this.wallets[id])
1463
- );
1464
- [...walletIds, ...pregenWalletIds].forEach((id) => {
1465
- if (address.toLowerCase() === this.getDisplayAddress(id, { addressType: type }).toLowerCase()) {
1466
- wallet = this.wallets[id];
1467
- }
1468
- });
1469
- });
1470
- if (!wallet) {
1471
- throw new Error(`wallet with address ${address} not found`);
1472
- }
1473
- this.assertIsValidWalletId(wallet.id, filter);
1474
- return wallet;
1475
- }
1476
- findWallet(idOrAddress, overrideType, filter = {}) {
1477
- var _a, _c, _d;
1478
- if (!this.isExternalWalletAuth) {
1479
- if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
1480
- return Object.values(this.externalWallets)[0];
1481
- }
1482
- }
1483
- if ((_a = this.externalWallets) == null ? void 0 : _a[idOrAddress]) {
1484
- return this.externalWallets[idOrAddress];
1485
- }
1486
- try {
1487
- const walletId = this.findWalletId(idOrAddress, filter);
1488
- if (walletId && !!this.wallets[walletId]) {
1489
- const _b = this.wallets[walletId], { signer: _signer } = _b, wallet = __objRest(_b, ["signer"]);
1490
- const type = (_d = overrideType != null ? overrideType : (_c = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _c[1]) != null ? _d : wallet.type;
1491
- return __spreadProps(__spreadValues({}, wallet), {
1492
- type
1493
- });
1494
- }
1495
- } catch (e) {
1496
- return void 0;
1497
- }
1360
+ findWalletByAddress(...params) {
1361
+ return __privateGet(this, _walletService).findWalletByAddress(...params);
1362
+ }
1363
+ findWallet(...params) {
1364
+ const [walletId, walletType, filters = {}] = params;
1365
+ return __privateGet(this, _walletService).findWallet(walletId, walletType, filters);
1498
1366
  }
1499
1367
  get availableWallets() {
1500
- var _a;
1501
- return [
1502
- ...[...this.currentWalletIdsArray, ...__privateGet(this, _ParaCore_instances, guestWalletIdsArray_get)].map(([address, type]) => [address, type, false]).map(([id, type]) => {
1503
- const wallet = this.findWallet(id, type);
1504
- if (!wallet) return null;
1505
- const name = wallet.name;
1506
- const address = this.getDisplayAddress(id, { addressType: type });
1507
- const addressShort = this.getDisplayAddress(id, { addressType: type, truncate: true });
1508
- return {
1509
- id: wallet.id,
1510
- partner: wallet.partner,
1511
- type,
1512
- address,
1513
- name,
1514
- addressShort,
1515
- displayName: name != null ? name : addressShort,
1516
- ensName: wallet.ensName,
1517
- ensAvatar: wallet.ensAvatar
1518
- };
1519
- }).filter((obj) => obj !== null),
1520
- ...Object.values((_a = this.externalWallets) != null ? _a : {}).map((wallet) => {
1521
- return __spreadProps(__spreadValues({}, wallet), {
1522
- addressShort: (0, import_utils2.truncateAddress)(wallet.address, wallet.type, { prefix: this.cosmosPrefix }),
1523
- displayName: wallet.externalProviderId
1524
- });
1525
- })
1526
- ];
1368
+ return __privateGet(this, _walletService).availableWallets;
1527
1369
  }
1528
1370
  /**
1529
1371
  * Retrieves all usable wallets with the provided type (`'EVM' | 'COSMOS' | 'SOLANA'`)
@@ -1531,52 +1373,16 @@ Need help? Visit: https://docs.getpara.com or contact support
1531
1373
  * @returns {Wallet[]} an array of matching wallets.
1532
1374
  */
1533
1375
  getWalletsByType(type) {
1534
- return Object.values(this.wallets).filter((w) => this.isWalletUsable(w.id, { type: [type] }));
1535
- }
1536
- assertIsValidWalletId(walletId, condition = {}) {
1537
- this.isWalletUsable(walletId, condition, true);
1376
+ return __privateGet(this, _walletService).getWalletsByType(type);
1538
1377
  }
1539
- assertIsValidWalletType(type, walletTypes) {
1378
+ getPartner(partnerId) {
1540
1379
  return __async(this, null, function* () {
1541
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1542
- if (!type || !import_user_management_client.WALLET_TYPES.includes(type) || !(walletTypes != null ? walletTypes : supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1543
- throw new Error(`wallet type ${type} is not supported`);
1544
- }
1545
- return type;
1546
- });
1547
- }
1548
- getMissingTypes() {
1549
- return __async(this, null, function* () {
1550
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1551
- return supportedWalletTypes.filter(
1552
- ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !import_utils2.WalletSchemeTypeMap[w.scheme][t])
1553
- ).map(({ type }) => type);
1554
- });
1555
- }
1556
- getTypesToCreate(types) {
1557
- return __async(this, null, function* () {
1558
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1559
- return (0, import_utils2.getSchemes)(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
1560
- switch (scheme) {
1561
- case "ED25519":
1562
- return "SOLANA";
1563
- default:
1564
- return supportedWalletTypes.some(({ type, optional }) => type === "COSMOS" && !optional) ? "COSMOS" : "EVM";
1565
- }
1566
- });
1567
- });
1568
- }
1569
- getPartnerURL() {
1570
- return __async(this, null, function* () {
1571
- try {
1572
- const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1573
- return portalUrl;
1574
- } catch (e) {
1575
- if (this.isPartnerOptional) {
1576
- return void 0;
1577
- }
1578
- throw e;
1380
+ if (this.isPartnerOptional && !partnerId) {
1381
+ return void 0;
1579
1382
  }
1383
+ const res = yield this.ctx.client.getPartner(partnerId);
1384
+ this.partner = res.data.partner;
1385
+ return this.partner;
1580
1386
  });
1581
1387
  }
1582
1388
  /**
@@ -1586,7 +1392,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1586
1392
  */
1587
1393
  getPortalURL(isLegacy) {
1588
1394
  return __async(this, null, function* () {
1589
- return this.ctx.portalUrlOverride || (yield this.getPartnerURL()) || (0, import_utils2.getPortalBaseURL)(this.ctx, false, false, isLegacy);
1395
+ return yield __privateGet(this, _portalUrlService).getPortalURL(isLegacy);
1590
1396
  });
1591
1397
  }
1592
1398
  /**
@@ -1619,33 +1425,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1619
1425
  */
1620
1426
  fetchWallets() {
1621
1427
  return __async(this, null, function* () {
1622
- const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
1623
- return res.data.wallets.filter(
1624
- (wallet) => !!wallet.address && wallet.sharesPersisted && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported((0, import_utils2.entityToWallet)(wallet)))
1625
- );
1428
+ return yield __privateGet(this, _walletService).fetchWallets();
1626
1429
  });
1627
1430
  }
1628
1431
  populateWalletAddresses() {
1629
1432
  return __async(this, null, function* () {
1630
- const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId, true);
1631
- const wallets = res.data.wallets;
1632
- wallets.forEach((entity) => {
1633
- if (this.wallets[entity.id]) {
1634
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, (0, import_utils2.entityToWallet)(entity)), this.wallets[entity.id]);
1635
- }
1636
- });
1637
- yield this.setWallets(this.wallets);
1638
- });
1639
- }
1640
- populatePregenWalletAddresses() {
1641
- return __async(this, null, function* () {
1642
- const res = yield this.getPregenWallets();
1643
- res.forEach((entity) => {
1644
- if (this.wallets[entity.id]) {
1645
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, (0, import_utils2.entityToWallet)(entity)), this.wallets[entity.id]);
1646
- }
1647
- });
1648
- yield this.setWallets(this.wallets);
1433
+ return yield __privateGet(this, _walletService).populateWalletAddresses();
1649
1434
  });
1650
1435
  }
1651
1436
  /**
@@ -1655,86 +1440,34 @@ Need help? Visit: https://docs.getpara.com or contact support
1655
1440
  * @param {TWalletType} opts.type type of external wallet to use for identification.
1656
1441
  * @param {string} opts.provider the name of the provider for the external wallet.
1657
1442
  */
1658
- loginExternalWallet(_a) {
1443
+ loginExternalWallet(params) {
1659
1444
  return __async(this, null, function* () {
1660
- var _b = _a, {
1661
- externalWallet,
1662
- chainId,
1663
- uri
1664
- } = _b, urlOptions = __objRest(_b, [
1665
- "externalWallet",
1666
- "chainId",
1667
- "uri"
1668
- ]);
1669
- const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1670
- try {
1671
- yield this.ctx.client.trackExternalWalletConnections({
1672
- wallets: externalWallets.map((wallet) => ({
1673
- address: wallet.address,
1674
- type: wallet.type,
1675
- provider: wallet.provider
1676
- }))
1677
- });
1678
- } catch (err) {
1679
- console.error("Error tracking external wallet connections:", err);
1680
- }
1681
- if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1682
- yield this.addExternalWallets(
1683
- externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1684
- withFullParaAuth: false
1685
- }))
1686
- );
1687
- return Promise.resolve({
1688
- userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1689
- });
1690
- }
1691
- if (Array.isArray(externalWallet)) {
1692
- throw new Error(
1693
- "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1694
- );
1695
- }
1696
- this.requireApiKey();
1697
- const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet, chainId, uri });
1698
- if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1699
- yield this.touchSession(true);
1700
- }
1701
- if (externalWallet.withFullParaAuth) {
1702
- yield this.ctx.client.sessionAddPortalVerification();
1703
- }
1704
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1445
+ return yield __privateGet(this, _authService).loginExternalWallet(params);
1446
+ });
1447
+ }
1448
+ /**
1449
+ * Connects to an external wallet & logs in to Para (if applicable).
1450
+ * @param {Object} params the params object
1451
+ * @param {Function} params.connect the function called to connect to the external wallet.
1452
+ */
1453
+ connectExternalWallet(params) {
1454
+ return __async(this, null, function* () {
1455
+ return yield __privateGet(this, _authService).connectExternalWallet(params);
1705
1456
  });
1706
1457
  }
1707
1458
  verifyExternalWallet(params) {
1708
1459
  return __async(this, null, function* () {
1709
- var _c;
1710
- let serverAuthState;
1711
- let urlOptions;
1712
- if ("serverAuthState" in params && params.serverAuthState !== void 0) {
1713
- const _a = params, { serverAuthState: optsServerAuthState } = _a, rest = __objRest(_a, ["serverAuthState"]);
1714
- serverAuthState = optsServerAuthState;
1715
- urlOptions = rest;
1716
- } else if ("externalWallet" in params) {
1717
- const _b = params, { externalWallet, signedMessage, cosmosPublicKeyHex, cosmosSigner } = _b, rest = __objRest(_b, ["externalWallet", "signedMessage", "cosmosPublicKeyHex", "cosmosSigner"]);
1718
- const _serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1719
- externalWallet,
1720
- signedMessage,
1721
- cosmosPublicKeyHex,
1722
- cosmosSigner
1723
- });
1724
- serverAuthState = _serverAuthState;
1725
- urlOptions = rest;
1726
- }
1727
- if (serverAuthState.stage === "login" && ((_c = serverAuthState.loginAuthMethods) == null ? void 0 : _c.includes(import_user_management_client.AuthMethod.PIN))) {
1728
- const { sessionLookupId } = yield this.touchSession();
1729
- return yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1730
- }
1731
- let state;
1732
- try {
1733
- state = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1734
- } catch (err) {
1735
- console.error("Error prepping state:", err);
1736
- }
1737
- return state;
1460
+ return yield __privateGet(this, _authService).verifyExternalWallet(params);
1461
+ });
1462
+ }
1463
+ retryVerifyExternalWallet() {
1464
+ return __async(this, null, function* () {
1465
+ return yield __privateGet(this, _authService).retryVerifyExternalWallet();
1466
+ });
1467
+ }
1468
+ signExternalWalletVerification(params) {
1469
+ return __async(this, null, function* () {
1470
+ return yield __privateGet(this, _authService).signExternalWalletVerification(params);
1738
1471
  });
1739
1472
  }
1740
1473
  verifyExternalWalletLink(opts) {
@@ -1757,13 +1490,13 @@ Need help? Visit: https://docs.getpara.com or contact support
1757
1490
  * @param authResponse - the response JSON object received from the Telegram widget.
1758
1491
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1759
1492
  */
1760
- verifyTelegramProcess(_c) {
1493
+ verifyTelegramProcess(_a) {
1761
1494
  return __async(this, null, function* () {
1762
- var _d = _c, {
1495
+ var _b = _a, {
1763
1496
  serverAuthState: optsServerAuthState,
1764
1497
  telegramAuthResponse,
1765
1498
  isLinkAccount
1766
- } = _d, urlOptions = __objRest(_d, [
1499
+ } = _b, urlOptions = __objRest(_b, [
1767
1500
  "serverAuthState",
1768
1501
  "telegramAuthResponse",
1769
1502
  "isLinkAccount"
@@ -1771,12 +1504,10 @@ Need help? Visit: https://docs.getpara.com or contact support
1771
1504
  try {
1772
1505
  switch (isLinkAccount) {
1773
1506
  case false: {
1774
- if (!optsServerAuthState && !telegramAuthResponse) {
1775
- throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1776
- }
1777
- const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1778
- const { sessionLookupId } = yield this.touchSession();
1779
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1507
+ return yield __privateGet(this, _authService).verifyTelegram(__spreadValues({
1508
+ serverAuthState: optsServerAuthState,
1509
+ telegramAuthResponse
1510
+ }, urlOptions));
1780
1511
  }
1781
1512
  case true: {
1782
1513
  if (!telegramAuthResponse) {
@@ -1796,9 +1527,9 @@ Need help? Visit: https://docs.getpara.com or contact support
1796
1527
  }
1797
1528
  });
1798
1529
  }
1799
- verifyTelegram(opts) {
1530
+ verifyTelegram(params) {
1800
1531
  return __async(this, null, function* () {
1801
- return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1532
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
1802
1533
  });
1803
1534
  }
1804
1535
  verifyTelegramLink(opts) {
@@ -1850,35 +1581,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1850
1581
  * Resend a verification email for the current user.
1851
1582
  */
1852
1583
  resendVerificationCode(_0) {
1853
- return __async(this, arguments, function* ({
1854
- type: reason = "SIGNUP"
1855
- }) {
1856
- let type, linkedAccountId;
1857
- switch (reason) {
1858
- case "SIGNUP":
1859
- case "LOGIN":
1860
- {
1861
- const authInfo = this.assertIsAuthSet(["email", "phone"]);
1862
- type = authInfo.authType.toUpperCase();
1863
- }
1864
- break;
1865
- case "LINK_ACCOUNT":
1866
- {
1867
- const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1868
- linkedAccountId = accountLinkInProgress.id;
1869
- type = accountLinkInProgress.type;
1870
- }
1871
- break;
1872
- }
1873
- const userId = this.assertUserId({ allowGuestMode: true });
1874
- if (type !== "EMAIL" && type !== "PHONE") {
1875
- throw new Error("invalid auth type for verification code");
1876
- }
1877
- yield this.ctx.client.resendVerificationCode(__spreadValues({
1878
- userId,
1879
- type,
1880
- linkedAccountId
1881
- }, this.getVerificationEmailProps()));
1584
+ return __async(this, arguments, function* ({ type: reason = "SIGNUP" }) {
1585
+ return yield __privateGet(this, _authService).resendVerificationCode({ type: reason });
1882
1586
  });
1883
1587
  }
1884
1588
  /**
@@ -1887,18 +1591,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1887
1591
  */
1888
1592
  isSessionActive() {
1889
1593
  return __async(this, null, function* () {
1890
- if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1891
- return true;
1892
- }
1893
- const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1894
- if (this.externalWalletConnectionType === "VERIFICATION") {
1895
- if (!verifiedExternalWalletAddresses) {
1896
- return false;
1897
- }
1898
- const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1899
- return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1900
- }
1901
- return !!isAuthenticated;
1594
+ return yield __privateGet(this, _sessionManagementService).isSessionActive();
1902
1595
  });
1903
1596
  }
1904
1597
  /**
@@ -1907,58 +1600,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1907
1600
  **/
1908
1601
  isFullyLoggedIn() {
1909
1602
  return __async(this, null, function* () {
1910
- if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1911
- if (!this.isReady) {
1912
- yield this.ready();
1913
- }
1914
- return true;
1915
- }
1916
- if (this.isGuestMode) {
1917
- return true;
1918
- }
1919
- const isSessionActive = yield this.isSessionActive();
1920
- if (this.externalWalletConnectionType === "VERIFICATION") {
1921
- return isSessionActive;
1922
- }
1923
- if (this.isSwitchingWallets) {
1924
- return isSessionActive;
1925
- }
1926
- if (!isSessionActive) {
1927
- return false;
1928
- }
1929
- if (this.isNoWalletConfig) {
1930
- return true;
1931
- }
1932
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1933
- const requiredWalletTypes = supportedWalletTypes.filter(({ optional }) => !optional);
1934
- for (const { type } of requiredWalletTypes) {
1935
- const hasWalletForType = this.currentWalletIdsArray.some(([walletId, walletType]) => {
1936
- try {
1937
- const wallet = this.wallets[walletId];
1938
- return wallet && walletType === type && typeof wallet.address === "string";
1939
- } catch (e) {
1940
- return false;
1941
- }
1942
- });
1943
- if (!hasWalletForType) {
1944
- return false;
1945
- }
1946
- }
1947
- const allWalletsLoaded = this.currentWalletIdsArray.every(([walletId]) => {
1948
- const wallet = this.wallets[walletId];
1949
- return wallet && typeof wallet.address === "string";
1950
- });
1951
- if (!allWalletsLoaded) {
1952
- return false;
1953
- }
1954
- return true;
1603
+ return yield __privateGet(this, _sessionManagementService).isFullyLoggedIn();
1955
1604
  });
1956
1605
  }
1957
1606
  get isGuestMode() {
1958
- return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1607
+ var _a;
1608
+ return ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 0 && Object.values(this.wallets).every(
1959
1609
  ({ userId, partnerId }) => {
1960
- var _a;
1961
- return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1610
+ var _a2;
1611
+ return partnerId === ((_a2 = this.partner) == null ? void 0 : _a2.id) && (!userId || userId !== this.userId);
1962
1612
  }
1963
1613
  );
1964
1614
  }
@@ -1988,30 +1638,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1988
1638
  */
1989
1639
  supportedUserAuthMethods() {
1990
1640
  return __async(this, null, function* () {
1991
- this.assertIsAuthSet();
1992
- const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1993
- this.authInfo.auth
1994
- );
1995
- const authMethods = /* @__PURE__ */ new Set();
1996
- for (const type of supportedAuthMethods) {
1997
- switch (type) {
1998
- case "PASSWORD":
1999
- if (hasPasswordWithoutPIN) {
2000
- authMethods.add(import_user_management_client.AuthMethod.PASSWORD);
2001
- }
2002
- break;
2003
- case "PASSKEY":
2004
- authMethods.add(import_user_management_client.AuthMethod.PASSKEY);
2005
- break;
2006
- case "PIN":
2007
- authMethods.add(import_user_management_client.AuthMethod.PIN);
2008
- break;
2009
- case "BASIC_LOGIN":
2010
- authMethods.add(import_user_management_client.AuthMethod.BASIC_LOGIN);
2011
- break;
2012
- }
2013
- }
2014
- return authMethods;
1641
+ return yield __privateGet(this, _authService).supportedUserAuthMethods();
2015
1642
  });
2016
1643
  }
2017
1644
  /**
@@ -2028,94 +1655,14 @@ Need help? Visit: https://docs.getpara.com or contact support
2028
1655
  /**
2029
1656
  * Waits for the session to be active.
2030
1657
  **/
2031
- waitForSignup(_0) {
2032
- return __async(this, arguments, function* ({
2033
- isCanceled = () => false,
2034
- onCancel,
2035
- onPoll
2036
- }) {
2037
- const startedAt = Date.now();
2038
- return new Promise((resolve, reject) => {
2039
- (() => __async(this, null, function* () {
2040
- yield this.touchSession();
2041
- if (!this.isExternalWalletAuth) {
2042
- this.externalWallets = {};
2043
- }
2044
- while (true) {
2045
- try {
2046
- if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
2047
- onCancel == null ? void 0 : onCancel();
2048
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_CREATION_EVENT, false, "failed to sign up user");
2049
- return reject("canceled");
2050
- }
2051
- yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2052
- if (yield this.isSessionActive()) {
2053
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_CREATION_EVENT, true);
2054
- return resolve(true);
2055
- }
2056
- onPoll == null ? void 0 : onPoll();
2057
- } catch (err) {
2058
- console.error(err);
2059
- onPoll == null ? void 0 : onPoll();
2060
- }
2061
- }
2062
- }))();
2063
- });
1658
+ waitForSignup(params) {
1659
+ return __async(this, null, function* () {
1660
+ return yield __privateGet(this, _authService).waitForSignup(params);
2064
1661
  });
2065
1662
  }
2066
- waitForWalletCreation() {
2067
- return __async(this, arguments, function* ({
2068
- isCanceled = () => false,
2069
- onCancel
2070
- } = {}) {
2071
- yield this.waitForSignup({ isCanceled, onCancel });
2072
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2073
- const pregenWallets = yield this.getPregenWallets();
2074
- let recoverySecret, walletIds = {};
2075
- if (pregenWallets.length > 0) {
2076
- let shares = [];
2077
- try {
2078
- shares = yield this.ctx.enclaveClient.getPregenShares({
2079
- userId: this.userId,
2080
- walletIds: pregenWallets.map((w) => w.id),
2081
- partnerId: pregenWallets[0].partnerId
2082
- });
2083
- for (const share of shares) {
2084
- const wallet = pregenWallets.find((w) => w.id === share.walletId);
2085
- if (wallet) {
2086
- this.wallets[wallet.id] = {
2087
- id: wallet.id,
2088
- address: wallet.address,
2089
- scheme: wallet.scheme,
2090
- type: wallet.type,
2091
- partnerId: wallet.partnerId,
2092
- isPregen: wallet.isPregen,
2093
- pregenIdentifier: wallet.pregenIdentifier,
2094
- pregenIdentifierType: wallet.pregenIdentifierType,
2095
- signer: share.signer,
2096
- createdAt: String(wallet.createdAt)
2097
- };
2098
- }
2099
- }
2100
- } catch (err) {
2101
- console.warn("[waitForWalletCreation] Failed to fetch pregen shares:", err);
2102
- }
2103
- if (shares.length > 0) {
2104
- recoverySecret = yield this.claimPregenWallets();
2105
- walletIds = supportedWalletTypes.reduce((acc, { type }) => {
2106
- var _a;
2107
- return __spreadProps(__spreadValues({}, acc), {
2108
- [type]: [(_a = pregenWallets.find((w) => !!import_utils2.WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
2109
- });
2110
- }, {});
2111
- }
2112
- }
2113
- const created = yield this.createWalletPerType();
2114
- recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
2115
- walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
2116
- const resp = { walletIds, recoverySecret };
2117
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2118
- return resp;
1663
+ waitForWalletCreation(params) {
1664
+ return __async(this, null, function* () {
1665
+ return yield __privateGet(this, _authService).waitForWalletCreation(params);
2119
1666
  });
2120
1667
  }
2121
1668
  /**
@@ -2135,35 +1682,34 @@ Need help? Visit: https://docs.getpara.com or contact support
2135
1682
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2136
1683
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2137
1684
  */
2138
- verifyFarcasterProcess(_e) {
1685
+ verifyFarcasterProcess(_c) {
2139
1686
  return __async(this, null, function* () {
2140
- var _f = _e, {
1687
+ var _d = _c, {
2141
1688
  isCanceled = () => false,
2142
1689
  onConnectUri,
2143
1690
  onCancel,
2144
- onPoll,
2145
1691
  isLinkAccount,
2146
1692
  serverAuthState: optsServerAuthState
2147
- } = _f, urlOptions = __objRest(_f, [
1693
+ } = _d, urlOptions = __objRest(_d, [
2148
1694
  "isCanceled",
2149
1695
  "onConnectUri",
2150
1696
  "onCancel",
2151
- "onPoll",
2152
1697
  "isLinkAccount",
2153
1698
  "serverAuthState"
2154
1699
  ]);
2155
- if (optsServerAuthState) {
2156
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
2157
- return authState;
1700
+ if (onConnectUri) {
1701
+ const connectUri = yield this.getFarcasterConnectUri();
1702
+ onConnectUri(connectUri);
1703
+ }
1704
+ if (!isLinkAccount) {
1705
+ return yield __privateGet(this, _authService).verifyFarcaster(__spreadValues({
1706
+ serverAuthState: optsServerAuthState
1707
+ }, urlOptions));
2158
1708
  }
2159
1709
  let accountLinkInProgress;
2160
1710
  if (isLinkAccount) {
2161
1711
  accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
2162
1712
  }
2163
- if (onConnectUri) {
2164
- const connectUri = yield this.getFarcasterConnectUri();
2165
- onConnectUri(connectUri);
2166
- }
2167
1713
  return new Promise((resolve, reject) => {
2168
1714
  (() => __async(this, null, function* () {
2169
1715
  const startedAt = Date.now();
@@ -2174,27 +1720,13 @@ Need help? Visit: https://docs.getpara.com or contact support
2174
1720
  return reject("CANCELED");
2175
1721
  }
2176
1722
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2177
- switch (isLinkAccount) {
2178
- case false:
2179
- {
2180
- const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
2181
- if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
2182
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2183
- return resolve(authState);
2184
- }
2185
- }
2186
- break;
2187
- case true: {
2188
- const result = yield this.verifyLink({
2189
- accountLinkInProgress
2190
- });
2191
- if ("isConflict" in result) {
2192
- throw new Error(import_types.AccountLinkError.Conflict);
2193
- }
2194
- return resolve(result);
2195
- }
1723
+ const result = yield this.verifyLink({
1724
+ accountLinkInProgress
1725
+ });
1726
+ if ("isConflict" in result) {
1727
+ throw new Error(import_types.AccountLinkError.Conflict);
2196
1728
  }
2197
- onPoll == null ? void 0 : onPoll();
1729
+ return resolve(result);
2198
1730
  } catch (e) {
2199
1731
  if (!isLinkAccount || e.message === import_types.AccountLinkError.Conflict) {
2200
1732
  return reject(e.message);
@@ -2205,9 +1737,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2205
1737
  });
2206
1738
  });
2207
1739
  }
2208
- verifyFarcaster(opts) {
1740
+ verifyFarcaster(params) {
2209
1741
  return __async(this, null, function* () {
2210
- return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1742
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2211
1743
  });
2212
1744
  }
2213
1745
  verifyFarcasterLink(opts) {
@@ -2215,11 +1747,17 @@ Need help? Visit: https://docs.getpara.com or contact support
2215
1747
  return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2216
1748
  });
2217
1749
  }
2218
- getOAuthUrl(opts) {
1750
+ /**
1751
+ * Generates a URL for the user to log in with OAuth using a desire method.
1752
+ *
1753
+ * @param {Object} opts the options object
1754
+ * @param {TOAuthMethod} opts.method the third-party service to use for OAuth.
1755
+ * @param {string} [opts.appScheme] the app scheme to redirect to after the OAuth flow. This is for mobile only.
1756
+ * @returns {string} the URL for the user to log in with OAuth.
1757
+ */
1758
+ getOAuthUrl(params) {
2219
1759
  return __async(this, null, function* () {
2220
- var _a;
2221
- const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
2222
- return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
1760
+ return yield __privateGet(this, _portalUrlService).getOAuthUrl(params);
2223
1761
  });
2224
1762
  }
2225
1763
  /**
@@ -2230,27 +1768,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2230
1768
  * @param {Window} [opts.popupWindow] the popup window being used for login.
2231
1769
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2232
1770
  */
2233
- verifyOAuthProcess(_g) {
1771
+ verifyOAuthProcess(params) {
2234
1772
  return __async(this, null, function* () {
2235
- var _h = _g, {
2236
- method,
2237
- appScheme,
2238
- isCanceled = () => false,
2239
- onCancel,
2240
- onPoll,
2241
- onOAuthUrl,
2242
- onOAuthPopup,
2243
- isLinkAccount
2244
- } = _h, urlOptions = __objRest(_h, [
2245
- "method",
2246
- "appScheme",
2247
- "isCanceled",
2248
- "onCancel",
2249
- "onPoll",
2250
- "onOAuthUrl",
2251
- "onOAuthPopup",
2252
- "isLinkAccount"
2253
- ]);
1773
+ if (!params.isLinkAccount) {
1774
+ return yield __privateGet(this, _authService).verifyOAuthProcess(params);
1775
+ }
1776
+ const { method, appScheme, isCanceled = () => false, onCancel, onPoll, onOAuthUrl, onOAuthPopup } = params;
2254
1777
  if (onOAuthPopup) {
2255
1778
  try {
2256
1779
  this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: import_types.PopupType.OAUTH });
@@ -2260,13 +1783,14 @@ Need help? Visit: https://docs.getpara.com or contact support
2260
1783
  }
2261
1784
  let sessionLookupId, accountLinkInProgress;
2262
1785
  if (onOAuthUrl || onOAuthPopup) {
2263
- if (isLinkAccount) {
2264
- accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
2265
- sessionLookupId = (yield this.touchSession()).sessionLookupId;
2266
- } else {
2267
- sessionLookupId = yield this.prepareLogin();
2268
- }
2269
- const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
1786
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
1787
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
1788
+ const oAuthUrl = yield __privateGet(this, _portalUrlService).getOAuthUrl({
1789
+ method,
1790
+ appScheme,
1791
+ sessionLookupId,
1792
+ accountLinkInProgress
1793
+ });
2270
1794
  switch (true) {
2271
1795
  case !!onOAuthUrl: {
2272
1796
  onOAuthUrl(oAuthUrl);
@@ -2291,24 +1815,10 @@ Need help? Visit: https://docs.getpara.com or contact support
2291
1815
  return reject(import_types.AccountLinkError.Canceled);
2292
1816
  }
2293
1817
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2294
- switch (isLinkAccount) {
2295
- case false:
2296
- {
2297
- const serverAuthState = yield this.ctx.client.verifyOAuth();
2298
- if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
2299
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
2300
- return resolve(authState);
2301
- }
2302
- }
2303
- break;
2304
- case true: {
2305
- const accounts = yield this.verifyLink({ accountLinkInProgress });
2306
- return resolve(accounts);
2307
- }
2308
- }
2309
- onPoll == null ? void 0 : onPoll();
1818
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
1819
+ return resolve(accounts);
2310
1820
  } catch (err) {
2311
- if (isLinkAccount && err.message === import_types.AccountLinkError.Conflict) {
1821
+ if (err.message === import_types.AccountLinkError.Conflict) {
2312
1822
  return reject(err.message);
2313
1823
  }
2314
1824
  onPoll == null ? void 0 : onPoll();
@@ -2318,9 +1828,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2318
1828
  });
2319
1829
  });
2320
1830
  }
2321
- verifyOAuth(opts) {
1831
+ verifyOAuth(params) {
2322
1832
  return __async(this, null, function* () {
2323
- return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1833
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2324
1834
  });
2325
1835
  }
2326
1836
  verifyOAuthLink(opts) {
@@ -2336,9 +1846,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2336
1846
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2337
1847
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2338
1848
  **/
2339
- waitForLogin(args) {
1849
+ waitForLogin(params) {
2340
1850
  return __async(this, null, function* () {
2341
- return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
1851
+ return yield __privateGet(this, _authService).waitForLogin(params);
2342
1852
  });
2343
1853
  }
2344
1854
  waitForWalletSwitching(args) {
@@ -2370,32 +1880,20 @@ Need help? Visit: https://docs.getpara.com or contact support
2370
1880
  * @returns a URL for the user to reauthenticate.
2371
1881
  **/
2372
1882
  refreshSession() {
2373
- return __async(this, arguments, function* ({
2374
- shouldOpenPopup = false
2375
- } = {}) {
2376
- const { sessionId } = yield this.touchSession(true);
2377
- if (!this.loginEncryptionKeyPair) {
2378
- yield this.setLoginEncryptionKeyPair();
2379
- }
2380
- const link = yield this.getLoginUrl({
2381
- sessionId
2382
- });
2383
- if (shouldOpenPopup) {
2384
- yield this.platformUtils.openPopup(link);
2385
- }
2386
- return link;
1883
+ return __async(this, arguments, function* (params = {}) {
1884
+ return yield __privateGet(this, _sessionManagementService).refreshSession(params);
2387
1885
  });
2388
1886
  }
2389
1887
  /**
2390
1888
  * Call this method after login to ensure that the user ID is set
2391
1889
  * internally.
2392
1890
  **/
2393
- userSetupAfterLogin() {
1891
+ userSetupAfterLogin(existingSession) {
2394
1892
  return __async(this, null, function* () {
2395
- const session = yield this.touchSession();
2396
- yield this.setUserId(session.userId);
2397
- if (session.currentWalletIds && session.currentWalletIds !== this.currentWalletIds)
2398
- yield this.setCurrentWalletIds(session.currentWalletIds, {
1893
+ const session = existingSession != null ? existingSession : yield this.touchSession();
1894
+ yield __privateGet(this, _authService).setUserId(session.userId);
1895
+ if (session.currentWalletIds && session.currentWalletIds !== __privateGet(this, _walletService).currentWalletIds)
1896
+ yield __privateGet(this, _walletService).setCurrentWalletIds(session.currentWalletIds, {
2399
1897
  sessionLookupId: this.isPortal() ? session.sessionLookupId : void 0
2400
1898
  });
2401
1899
  return session;
@@ -2408,9 +1906,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2408
1906
  * @returns - transmission keyshares.
2409
1907
  **/
2410
1908
  getTransmissionKeyShares() {
2411
- return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2412
- const session = yield this.touchSession();
2413
- const sessionLookupId = isForNewDevice ? `${session.sessionLookupId}-new-device` : session.sessionLookupId;
1909
+ return __async(this, arguments, function* ({
1910
+ isForNewDevice = false,
1911
+ sessionLookupId: existingSessionLookupId
1912
+ } = {}) {
1913
+ const baseSessionLookupId = existingSessionLookupId != null ? existingSessionLookupId : (yield this.touchSession()).sessionLookupId;
1914
+ const sessionLookupId = isForNewDevice ? `${baseSessionLookupId}-new-device` : baseSessionLookupId;
2414
1915
  return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2415
1916
  });
2416
1917
  }
@@ -2429,106 +1930,29 @@ Need help? Visit: https://docs.getpara.com or contact support
2429
1930
  temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2430
1931
  }
2431
1932
  temporaryShares.forEach((share) => {
2432
- const signer = (0, import_utils.decryptWithPrivateKey)(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2433
- this.wallets[share.walletId] = {
2434
- id: share.walletId,
2435
- signer
2436
- };
2437
- });
2438
- yield this.deleteLoginEncryptionKeyPair();
2439
- yield this.populateWalletAddresses();
2440
- yield this.touchSession(!skipSessionRefresh);
2441
- });
2442
- }
2443
- /**
2444
- * Distributes a new wallet recovery share.
2445
- * @param {Object} opts the options object.
2446
- * @param {string} opts.walletId the wallet to distribute the recovery share for.
2447
- * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
2448
- * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
2449
- * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2450
- * @returns {string} the recovery share.
2451
- **/
2452
- distributeNewWalletShare(_0) {
2453
- return __async(this, arguments, function* ({
2454
- walletId,
2455
- userShare,
2456
- skipBiometricShareCreation = false,
2457
- forceRefresh = false
2458
- }) {
2459
- let userSigner = userShare;
2460
- if (!userSigner) {
2461
- userSigner = this.wallets[walletId].signer;
2462
- }
2463
- const recoveryShare = skipBiometricShareCreation ? yield (0, import_recovery.sendRecoveryForShare)({
2464
- ctx: this.ctx,
2465
- userId: this.userId,
2466
- walletId,
2467
- userSigner,
2468
- emailProps: this.getBackupKitEmailProps(),
2469
- forceRefresh
2470
- }) : yield (0, import_shareDistribution.distributeNewShare)({
2471
- ctx: this.ctx,
2472
- userId: this.userId,
2473
- walletId,
2474
- userShare: userSigner,
2475
- emailProps: this.getBackupKitEmailProps(),
2476
- isEnclaveUser: this.isEnclaveUser,
2477
- walletScheme: this.wallets[walletId].scheme
2478
- });
2479
- return recoveryShare;
2480
- });
2481
- }
2482
- waitForWalletAddress(walletId) {
2483
- return __async(this, null, function* () {
2484
- let maxPolls = 0;
2485
- while (true) {
2486
- try {
2487
- if (maxPolls === 10) {
2488
- break;
2489
- }
2490
- ++maxPolls;
2491
- const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
2492
- const wallet = res.data.wallets.find((w) => w.id === walletId);
2493
- if (wallet && wallet.address) {
2494
- return;
2495
- }
2496
- yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2497
- } catch (err) {
2498
- console.error(err);
2499
- }
2500
- }
2501
- throw new Error("timed out waiting for wallet address");
1933
+ const signer = (0, import_utils.decryptWithPrivateKey)(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
1934
+ this.wallets[share.walletId] = {
1935
+ id: share.walletId,
1936
+ signer
1937
+ };
1938
+ });
1939
+ yield this.deleteLoginEncryptionKeyPair();
1940
+ yield __privateGet(this, _walletService).populateWalletAddresses();
1941
+ yield this.touchSession(!skipSessionRefresh);
2502
1942
  });
2503
1943
  }
2504
1944
  /**
2505
- * Waits for a pregen wallet address to be created.
2506
- *
2507
- * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
2508
- * @param walletId - the wallet id
2509
- * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2510
- * @returns - recovery share.
1945
+ * Distributes a new wallet recovery share.
1946
+ * @param {Object} opts the options object.
1947
+ * @param {string} opts.walletId the wallet to distribute the recovery share for.
1948
+ * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
1949
+ * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
1950
+ * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
1951
+ * @returns {string} the recovery share.
2511
1952
  **/
2512
- waitForPregenWalletAddress(walletId) {
1953
+ distributeNewWalletShare(params) {
2513
1954
  return __async(this, null, function* () {
2514
- let maxPolls = 0;
2515
- while (true) {
2516
- try {
2517
- if (maxPolls === 10) {
2518
- break;
2519
- }
2520
- ++maxPolls;
2521
- const res = yield this.getPregenWallets();
2522
- const wallet = res.find((w) => w.id === walletId);
2523
- if (wallet && wallet.address) {
2524
- return;
2525
- }
2526
- yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2527
- } catch (err) {
2528
- console.error(err);
2529
- }
2530
- }
2531
- throw new Error("timed out waiting for wallet address");
1955
+ return yield __privateGet(this, _walletService).distributeNewWalletShare(params);
2532
1956
  });
2533
1957
  }
2534
1958
  /**
@@ -2543,24 +1967,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2543
1967
  * @returns {Object} the wallets created, their ids, and the recovery secret.
2544
1968
  **/
2545
1969
  createWalletPerType() {
2546
- return __async(this, arguments, function* ({
2547
- skipDistribute = false,
2548
- types
2549
- } = {}) {
2550
- const wallets = [];
2551
- const walletIds = {};
2552
- let recoverySecret;
2553
- for (const type of yield this.getTypesToCreate(types)) {
2554
- const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
2555
- wallets.push(wallet);
2556
- (0, import_utils2.getEquivalentTypes)(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
2557
- walletIds[t] = [wallet.id];
2558
- });
2559
- if (recoveryShare) {
2560
- recoverySecret = recoveryShare;
2561
- }
2562
- }
2563
- return { wallets, walletIds, recoverySecret };
1970
+ return __async(this, arguments, function* (params = {}) {
1971
+ return yield __privateGet(this, _walletService).createWalletPerType(params);
2564
1972
  });
2565
1973
  }
2566
1974
  /**
@@ -2575,38 +1983,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2575
1983
  * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2576
1984
  * @returns {Object} the new user share and recovery secret.
2577
1985
  **/
2578
- refreshShare(_0) {
2579
- return __async(this, arguments, function* ({
2580
- walletId,
2581
- share,
2582
- oldPartnerId,
2583
- newPartnerId,
2584
- keyShareProtocolId,
2585
- redistributeBackupEncryptedShares
2586
- }) {
2587
- const { signer, protocolId } = yield this.platformUtils.refresh(
2588
- this.ctx,
2589
- this.retrieveSessionCookie(),
2590
- this.userId,
2591
- walletId,
2592
- share,
2593
- oldPartnerId,
2594
- newPartnerId,
2595
- keyShareProtocolId
2596
- );
2597
- const recoverySecret = yield (0, import_shareDistribution.distributeNewShare)({
2598
- ctx: this.ctx,
2599
- userId: this.userId,
2600
- walletId,
2601
- userShare: signer,
2602
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2603
- emailProps: this.getBackupKitEmailProps(),
2604
- partnerId: newPartnerId,
2605
- protocolId,
2606
- isEnclaveUser: this.isEnclaveUser,
2607
- walletScheme: this.wallets[walletId].scheme
2608
- });
2609
- return { signer, recoverySecret, protocolId };
1986
+ refreshShare(params) {
1987
+ return __async(this, null, function* () {
1988
+ return yield __privateGet(this, _walletService).refreshShare(params);
2610
1989
  });
2611
1990
  }
2612
1991
  /**
@@ -2617,80 +1996,22 @@ Need help? Visit: https://docs.getpara.com or contact support
2617
1996
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2618
1997
  **/
2619
1998
  createWallet() {
2620
- return __async(this, arguments, function* ({
2621
- type: _type,
2622
- skipDistribute = false
2623
- } = {}) {
2624
- var _a, _b;
2625
- this.requireApiKey();
2626
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2627
- const walletType = yield this.assertIsValidWalletType(
2628
- _type != null ? _type : (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
2629
- );
2630
- let signer;
2631
- let wallet;
2632
- let keygenRes;
2633
- switch (walletType) {
2634
- case "SOLANA": {
2635
- keygenRes = yield this.platformUtils.ed25519Keygen(
2636
- this.ctx,
2637
- this.userId,
2638
- this.retrieveSessionCookie(),
2639
- this.getBackupKitEmailProps()
2640
- );
2641
- break;
2642
- }
2643
- default: {
2644
- keygenRes = yield this.platformUtils.keygen(
2645
- this.ctx,
2646
- this.userId,
2647
- walletType,
2648
- null,
2649
- this.retrieveSessionCookie(),
2650
- this.getBackupKitEmailProps()
2651
- );
2652
- break;
2653
- }
2654
- }
2655
- const walletId = keygenRes.walletId;
2656
- const walletScheme = walletType === "SOLANA" ? "ED25519" : "DKLS";
2657
- signer = keygenRes.signer;
2658
- yield this.waitForWalletAddress(walletId);
2659
- let recoveryShare = null;
2660
- if (!skipDistribute) {
2661
- recoveryShare = yield (0, import_shareDistribution.distributeNewShare)({
2662
- ctx: this.ctx,
2663
- userId: this.userId,
2664
- walletId,
2665
- userShare: signer,
2666
- emailProps: this.getBackupKitEmailProps(),
2667
- isEnclaveUser: this.isEnclaveUser,
2668
- walletScheme
2669
- });
2670
- }
2671
- this.wallets[walletId] = {
2672
- id: walletId,
2673
- signer,
2674
- scheme: walletScheme,
2675
- type: walletType
2676
- };
2677
- wallet = this.wallets[walletId];
2678
- yield this.populateWalletAddresses();
2679
- yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
2680
- [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
2681
- }));
2682
- const walletNoSigner = __spreadValues({}, wallet);
2683
- delete walletNoSigner.signer;
2684
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.WALLET_CREATED, {
2685
- wallet: walletNoSigner,
2686
- recoverySecret: recoveryShare
2687
- });
2688
- return [wallet, recoveryShare];
1999
+ return __async(this, arguments, function* (params = {}) {
2000
+ return yield __privateGet(this, _walletService).createWallet(params);
2689
2001
  });
2690
2002
  }
2691
- createPregenWallet(opts) {
2003
+ /**
2004
+ * Creates a new pregenerated wallet.
2005
+ *
2006
+ * @param {Object} opts the options object.
2007
+ * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
2008
+ * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
2009
+ * @param {TWalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
2010
+ * @returns {Wallet} the created wallet.
2011
+ **/
2012
+ createPregenWallet(params) {
2692
2013
  return __async(this, null, function* () {
2693
- return yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, opts);
2014
+ return yield __privateGet(this, _pregenWalletService).createPregenWallet(params);
2694
2015
  });
2695
2016
  }
2696
2017
  /**
@@ -2703,17 +2024,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2703
2024
  * @param {TWalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
2704
2025
  * @returns {Wallet[]} an array containing the created wallets.
2705
2026
  **/
2706
- createPregenWalletPerType(_0) {
2707
- return __async(this, arguments, function* ({
2708
- types,
2709
- pregenId
2710
- }) {
2711
- const wallets = [];
2712
- for (const type of yield this.getTypesToCreate(types)) {
2713
- const wallet = yield this.createPregenWallet({ type, pregenId });
2714
- wallets.push(wallet);
2715
- }
2716
- return wallets;
2027
+ createPregenWalletPerType(params) {
2028
+ return __async(this, null, function* () {
2029
+ return yield __privateGet(this, _pregenWalletService).createPregenWalletPerType(params);
2717
2030
  });
2718
2031
  }
2719
2032
  /**
@@ -2724,70 +2037,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2724
2037
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2725
2038
  **/
2726
2039
  claimPregenWallets() {
2727
- return __async(this, arguments, function* ({
2728
- pregenId
2729
- } = {}) {
2730
- var _a;
2731
- this.requireApiKey();
2732
- const pregenWallets = pregenId ? yield this.getPregenWallets({ pregenId }) : yield this.getPregenWallets();
2733
- if (pregenWallets.length === 0) {
2734
- return void 0;
2735
- }
2736
- const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
2737
- if (missingWallets.length > 0) {
2738
- throw new Error(
2739
- `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(", ")}`
2740
- );
2741
- }
2742
- let newRecoverySecret;
2743
- const { walletIds } = yield this.ctx.client.claimPregenWallets({
2744
- userId: this.userId,
2745
- walletIds: pregenWallets.map((w) => w.id)
2746
- });
2747
- for (const walletId of walletIds) {
2748
- const wallet = this.wallets[walletId];
2749
- let refreshedShare;
2750
- if (wallet.scheme === "ED25519") {
2751
- const distributeRes = yield (0, import_shareDistribution.distributeNewShare)({
2752
- ctx: this.ctx,
2753
- userId: this.userId,
2754
- walletId: wallet.id,
2755
- userShare: this.wallets[wallet.id].signer,
2756
- emailProps: this.getBackupKitEmailProps(),
2757
- partnerId: wallet.partnerId,
2758
- isEnclaveUser: this.isEnclaveUser,
2759
- walletScheme: wallet.scheme
2760
- });
2761
- if (distributeRes.length > 0) {
2762
- newRecoverySecret = distributeRes;
2763
- }
2764
- } else {
2765
- refreshedShare = yield this.refreshShare({
2766
- walletId: wallet.id,
2767
- share: this.wallets[wallet.id].signer,
2768
- oldPartnerId: wallet.partnerId,
2769
- newPartnerId: wallet.partnerId,
2770
- redistributeBackupEncryptedShares: true
2771
- });
2772
- if (refreshedShare.recoverySecret) {
2773
- newRecoverySecret = refreshedShare.recoverySecret;
2774
- }
2775
- }
2776
- this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
2777
- signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
2778
- userId: this.userId,
2779
- pregenIdentifier: void 0,
2780
- pregenIdentifierType: void 0
2781
- });
2782
- const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
2783
- delete walletNoSigner.signer;
2784
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.PREGEN_WALLET_CLAIMED, {
2785
- wallet: walletNoSigner,
2786
- recoverySecret: newRecoverySecret
2787
- });
2788
- }
2789
- yield this.setWallets(this.wallets);
2790
- return newRecoverySecret;
2040
+ return __async(this, arguments, function* (params = {}) {
2041
+ return yield __privateGet(this, _pregenWalletService).claimPregenWallets(params);
2791
2042
  });
2792
2043
  }
2793
2044
  /**
@@ -2797,24 +2048,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2797
2048
  * @param {string} opts.newPregenIdentifier the new identtifier
2798
2049
  * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
2799
2050
  **/
2800
- updatePregenWalletIdentifier(_0) {
2801
- return __async(this, arguments, function* ({
2802
- walletId,
2803
- newPregenId
2804
- }) {
2805
- this.requireApiKey();
2806
- const [newPregenIdentifierType, newPregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(newPregenId);
2807
- yield this.ctx.client.updatePregenWallet(walletId, {
2808
- pregenIdentifier: newPregenIdentifier,
2809
- pregenIdentifierType: newPregenIdentifierType
2810
- });
2811
- if (!!this.wallets[walletId]) {
2812
- this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
2813
- pregenIdentifier: newPregenIdentifier,
2814
- pregenIdentifierType: newPregenIdentifierType
2815
- });
2816
- yield this.setWallets(this.wallets);
2817
- }
2051
+ updatePregenWalletIdentifier(params) {
2052
+ return __async(this, null, function* () {
2053
+ return yield __privateGet(this, _pregenWalletService).updatePregenWalletIdentifier(params);
2818
2054
  });
2819
2055
  }
2820
2056
  /**
@@ -2824,18 +2060,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2824
2060
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
2825
2061
  * @returns {boolean} whether the pregen wallet exists
2826
2062
  **/
2827
- hasPregenWallet(_0) {
2828
- return __async(this, arguments, function* ({ pregenId }) {
2829
- this.requireApiKey();
2830
- const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(pregenId);
2831
- const wallets = yield this.getPregenWallets({ pregenId });
2832
- const wallet = wallets.find(
2833
- (w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType
2834
- );
2835
- if (!wallet) {
2836
- return false;
2837
- }
2838
- return true;
2063
+ hasPregenWallet(params) {
2064
+ return __async(this, null, function* () {
2065
+ return yield __privateGet(this, _pregenWalletService).hasPregenWallet(params);
2839
2066
  });
2840
2067
  }
2841
2068
  /**
@@ -2846,64 +2073,21 @@ Need help? Visit: https://docs.getpara.com or contact support
2846
2073
  * @returns {Promise<WalletEntity[]>} the array of found wallets
2847
2074
  **/
2848
2075
  getPregenWallets() {
2849
- return __async(this, arguments, function* ({ pregenId } = {}) {
2850
- this.requireApiKey();
2851
- const res = yield this.ctx.client.getPregenWallets(
2852
- pregenId ? (0, import_user_management_client.toPregenIds)(pregenId) : this.pregenIds,
2853
- this.isPortal(),
2854
- this.userId
2855
- );
2856
- return res.wallets.filter((w) => this.isWalletSupported((0, import_utils2.entityToWallet)(w)));
2076
+ return __async(this, arguments, function* (params = {}) {
2077
+ return yield __privateGet(this, _pregenWalletService).getPregenWallets(params);
2857
2078
  });
2858
2079
  }
2859
2080
  createGuestWallets() {
2860
2081
  return __async(this, null, function* () {
2861
- let error;
2862
- if (__privateGet(this, _isCreateGuestWalletsPending)) {
2863
- error = new Error("Guest wallets creation already in progress");
2864
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2865
- throw error;
2866
- }
2867
- if (this.isGuestMode) {
2868
- error = new Error("Guest wallets already created");
2869
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2870
- throw error;
2871
- }
2872
- try {
2873
- __privateSet(this, _isCreateGuestWalletsPending, true);
2874
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2875
- const wallets = [];
2876
- const guestId = (0, import_utils2.newUuid)();
2877
- for (const type of yield this.getTypesToCreate(
2878
- supportedWalletTypes.filter(({ optional }) => !optional).map(({ type: type2 }) => type2)
2879
- )) {
2880
- const wallet = yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, { type, pregenId: { guestId } });
2881
- wallets.push(wallet);
2882
- }
2883
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, wallets);
2884
- __privateSet(this, _isCreateGuestWalletsPending, false);
2885
- return wallets;
2886
- } catch (error2) {
2887
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.GUEST_WALLETS_CREATED, null, error2 == null ? void 0 : error2.message);
2888
- __privateSet(this, _isCreateGuestWalletsPending, false);
2889
- throw error2;
2890
- }
2082
+ return yield __privateGet(this, _pregenWalletService).createGuestWallets();
2891
2083
  });
2892
2084
  }
2893
- encodeWalletBase64(wallet) {
2894
- const walletJson = JSON.stringify(wallet);
2895
- const base64Wallet = Buffer.from(walletJson).toString("base64");
2896
- return base64Wallet;
2897
- }
2898
2085
  /**
2899
2086
  * Encodes the current wallets encoded in Base 64.
2900
2087
  * @returns {string} the encoded wallet string
2901
2088
  **/
2902
2089
  getUserShare() {
2903
- if (Object.values(this.wallets).length === 0) {
2904
- return null;
2905
- }
2906
- return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
2090
+ return __privateGet(this, _walletService).getUserShare();
2907
2091
  }
2908
2092
  /**
2909
2093
  * Sets the current wallets from a Base 64 string.
@@ -2911,16 +2095,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2911
2095
  **/
2912
2096
  setUserShare(base64Wallets) {
2913
2097
  return __async(this, null, function* () {
2914
- if (!base64Wallets) {
2915
- return;
2916
- }
2917
- const base64WalletsSplit = base64Wallets.split("-");
2918
- for (const base64Wallet of base64WalletsSplit) {
2919
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
2920
- const wallet = (0, import_utils2.migrateWallet)(JSON.parse(walletJson));
2921
- this.wallets[wallet.id] = wallet;
2922
- yield this.setWallets(this.wallets);
2923
- }
2098
+ return yield __privateGet(this, _walletService).setUserShare(base64Wallets);
2924
2099
  });
2925
2100
  }
2926
2101
  getTransactionReviewUrl(transactionId, timeoutMs) {
@@ -2944,6 +2119,11 @@ Need help? Visit: https://docs.getpara.com or contact support
2944
2119
  });
2945
2120
  });
2946
2121
  }
2122
+ getWalletBalance(params) {
2123
+ return __async(this, null, function* () {
2124
+ return yield __privateGet(this, _walletService).getWalletBalance(params);
2125
+ });
2126
+ }
2947
2127
  /**
2948
2128
  * Signs a message using one of the current wallets.
2949
2129
  *
@@ -2966,7 +2146,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2966
2146
  onPoll
2967
2147
  }) {
2968
2148
  var _a;
2969
- this.assertIsValidWalletId(walletId);
2149
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
2970
2150
  const wallet = this.wallets[walletId];
2971
2151
  let signerId = this.userId;
2972
2152
  if (wallet.partnerId && !wallet.userId) {
@@ -3071,7 +2251,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3071
2251
  onPoll
3072
2252
  }) {
3073
2253
  var _a;
3074
- this.assertIsValidWalletId(walletId);
2254
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
3075
2255
  const wallet = this.wallets[walletId];
3076
2256
  let signerId = this.userId;
3077
2257
  if (wallet.partnerId && !wallet.userId) {
@@ -3155,6 +2335,12 @@ Need help? Visit: https://docs.getpara.com or contact support
3155
2335
  return __async(this, null, function* () {
3156
2336
  var _b;
3157
2337
  const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
2338
+ const allowedProviders = Object.values(import_user_management_client.OnRampProvider);
2339
+ if (!params.provider || !allowedProviders.includes(params.provider)) {
2340
+ throw new Error(
2341
+ `Invalid onramp provider: ${JSON.stringify(params.provider)}. Must be one of: ${allowedProviders.join(", ")}`
2342
+ );
2343
+ }
3158
2344
  const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3159
2345
  userId: this.userId,
3160
2346
  params: __spreadProps(__spreadValues({}, params), {
@@ -3177,12 +2363,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3177
2363
  **/
3178
2364
  keepSessionAlive() {
3179
2365
  return __async(this, null, function* () {
3180
- try {
3181
- yield this.ctx.client.keepSessionAlive(this.userId);
3182
- return true;
3183
- } catch (e) {
3184
- return false;
3185
- }
2366
+ return yield __privateGet(this, _sessionManagementService).keepSessionAlive();
3186
2367
  });
3187
2368
  }
3188
2369
  /**
@@ -3192,10 +2373,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3192
2373
  */
3193
2374
  exportSession({ excludeSigners = false } = {}) {
3194
2375
  const sessionInfo = {
3195
- authInfo: __privateGet(this, _authInfo),
2376
+ authInfo: __privateGet(this, _authService).authInfo,
3196
2377
  userId: this.userId,
3197
2378
  wallets: structuredClone(this.wallets),
3198
- currentWalletIds: this.currentWalletIds,
2379
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
3199
2380
  sessionCookie: this.retrieveSessionCookie(),
3200
2381
  externalWallets: this.externalWallets
3201
2382
  };
@@ -3213,10 +2394,25 @@ Need help? Visit: https://docs.getpara.com or contact support
3213
2394
  importSession(serializedInstanceBase64) {
3214
2395
  return __async(this, null, function* () {
3215
2396
  var _a, _b;
2397
+ yield (0, import_stateListener.waitForAuthStateChange)({
2398
+ stateManager: __privateGet(this, _stateManager),
2399
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2400
+ rejectPhases: [
2401
+ {
2402
+ phase: "authenticated",
2403
+ onPhase: () => new Error("Cannot import a session into a Para instance that already has an active session.")
2404
+ },
2405
+ {
2406
+ phase: "guest_mode",
2407
+ onPhase: () => new Error("Cannot import a session into a Para instance that is in guest mode.")
2408
+ }
2409
+ ],
2410
+ waitForCoreAuthenticated: false
2411
+ });
3216
2412
  const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3217
2413
  const sessionInfo = (0, import_utils2.jsonParse)(serializedInstance);
3218
2414
  const authInfo = (_a = sessionInfo.authInfo) != null ? _a : __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, sessionInfo);
3219
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2415
+ yield __privateGet(this, _authService).setAuthInfo(authInfo);
3220
2416
  yield this.setUserId(sessionInfo.userId);
3221
2417
  yield this.setWallets(sessionInfo.wallets);
3222
2418
  yield this.setExternalWallets(sessionInfo.externalWallets || {});
@@ -3237,7 +2433,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3237
2433
  }
3238
2434
  yield this.setCurrentWalletIds(currentWalletIds);
3239
2435
  }
2436
+ __privateGet(this, _sessionManagementService).isImportedSession = true;
2437
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION, JSON.stringify(true));
3240
2438
  this.persistSessionCookie(sessionInfo.sessionCookie);
2439
+ __privateGet(this, _stateManager).send({ type: "SESSION_IMPORTED" });
3241
2440
  });
3242
2441
  }
3243
2442
  /**
@@ -3246,22 +2445,12 @@ Need help? Visit: https://docs.getpara.com or contact support
3246
2445
  **/
3247
2446
  getVerificationToken() {
3248
2447
  return __async(this, null, function* () {
3249
- const { sessionLookupId } = yield this.touchSession();
3250
- return sessionLookupId;
2448
+ return yield __privateGet(this, _sessionManagementService).getVerificationToken();
3251
2449
  });
3252
2450
  }
3253
2451
  issueJwt() {
3254
- return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
3255
- try {
3256
- return yield this.ctx.client.issueJwt({ keyIndex });
3257
- } catch (error) {
3258
- if (error.status === 403 || error.status === 401) {
3259
- const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3260
- this.displayModalError(errorMessage);
3261
- console.warn(errorMessage);
3262
- }
3263
- throw error;
3264
- }
2452
+ return __async(this, arguments, function* (params = {}) {
2453
+ return yield __privateGet(this, _sessionManagementService).issueJwt(params);
3265
2454
  });
3266
2455
  }
3267
2456
  /**
@@ -3271,30 +2460,39 @@ Need help? Visit: https://docs.getpara.com or contact support
3271
2460
  **/
3272
2461
  logout() {
3273
2462
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3274
- const shouldDispatchLogoutEvent = yield this.isSessionActive();
3275
- yield this.ctx.client.logout();
3276
- yield this.clearStorage();
3277
- if (!clearPregenWallets) {
3278
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3279
- if (!wallet.pregenIdentifier) {
3280
- delete this.wallets[id];
3281
- }
2463
+ yield __privateMethod(this, _ParaCore_instances, logout_fn).call(this, { clearPregenWallets });
2464
+ __privateGet(this, _pollingService).cancelAllPolling();
2465
+ yield __privateGet(this, _externalWalletService).disconnectAllExternalWallets();
2466
+ try {
2467
+ yield (0, import_stateListener.waitForAuthStateChange)({
2468
+ stateManager: __privateGet(this, _stateManager),
2469
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2470
+ rejectInErrorPhaseOnly: true,
2471
+ timeoutMs: 5e3
3282
2472
  });
3283
- yield this.setWallets(this.wallets);
3284
- } else {
3285
- this.wallets = {};
2473
+ } catch (e) {
3286
2474
  }
3287
- this.currentWalletIds = {};
3288
- this.externalWallets = {};
3289
- this.loginEncryptionKeyPair = void 0;
3290
- __privateSet(this, _authInfo, void 0);
3291
- this.accountLinkInProgress = void 0;
3292
- this.userId = void 0;
3293
- this.sessionCookie = void 0;
3294
- this.isEnclaveUser = false;
3295
- if (shouldDispatchLogoutEvent) {
3296
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
2475
+ });
2476
+ }
2477
+ /**
2478
+ * Cancels any in-progress authentication flow, returning the auth state machine
2479
+ * to its initial unauthenticated state. Does not affect existing sessions or stored data.
2480
+ *
2481
+ * Resolves once the auth state machine has settled back to `unauthenticated`.
2482
+ */
2483
+ cancelAuthFlow() {
2484
+ return __async(this, null, function* () {
2485
+ if (this.authPhase === "unauthenticated" || this.authPhase === "error") {
2486
+ return;
3297
2487
  }
2488
+ const settled = (0, import_stateListener.waitForAuthStateChange)({
2489
+ stateManager: __privateGet(this, _stateManager),
2490
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => true }],
2491
+ rejectInErrorPhaseOnly: true,
2492
+ timeoutMs: 5e3
2493
+ });
2494
+ __privateGet(this, _stateManager).send({ type: "CANCEL" });
2495
+ yield settled;
3298
2496
  });
3299
2497
  }
3300
2498
  get toStringAdditions() {
@@ -3327,16 +2525,16 @@ Need help? Visit: https://docs.getpara.com or contact support
3327
2525
  partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3328
2526
  supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3329
2527
  cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
3330
- authInfo: __privateGet(this, _authInfo),
2528
+ authInfo: __privateGet(this, _authService).authInfo,
3331
2529
  isGuestMode: this.isGuestMode,
3332
2530
  userId: this.userId,
3333
2531
  pregenIds: this.pregenIds,
3334
- currentWalletIds: this.currentWalletIds,
3335
- guestWalletIds: __privateGet(this, _ParaCore_instances, guestWalletIds_get),
2532
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
2533
+ guestWalletIds: __privateGet(this, _pregenWalletService).guestWalletIds,
3336
2534
  wallets: redactedWallets,
3337
2535
  externalWallets: redactedExternalWallets,
3338
2536
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3339
- isReady: this.isReady
2537
+ isSetup: this.isSetup
3340
2538
  }, this.toStringAdditions), {
3341
2539
  ctx: {
3342
2540
  apiKey: this.ctx.apiKey,
@@ -3352,90 +2550,13 @@ Need help? Visit: https://docs.getpara.com or contact support
3352
2550
  return `Para ${JSON.stringify(obj, null, 2)}`;
3353
2551
  }
3354
2552
  devLog(...s) {
3355
- if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX) {
2553
+ if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX || !!__privateGet(this, _debugLogsEnabled)) {
3356
2554
  console.log(...s);
3357
2555
  }
3358
2556
  }
3359
2557
  getNewCredentialAndUrl() {
3360
- return __async(this, arguments, function* ({
3361
- authMethod: optsAuthMethod,
3362
- isForNewDevice = false,
3363
- portalTheme,
3364
- shorten = false
3365
- } = {}) {
3366
- const userAuthMethods = yield this.supportedUserAuthMethods();
3367
- const isEnclaveUser = userAuthMethods.has(import_user_management_client.AuthMethod.BASIC_LOGIN);
3368
- const isAddingBasicLogin = optsAuthMethod === "BASIC_LOGIN";
3369
- if (isEnclaveUser && isAddingBasicLogin) {
3370
- throw new Error("That user is already using basic login");
3371
- }
3372
- if (isEnclaveUser || isAddingBasicLogin) {
3373
- isForNewDevice = true;
3374
- }
3375
- const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
3376
- this.assertIsAuthSet();
3377
- let passkeyId, passwordId, urlType, credentialId;
3378
- if (!isAddingBasicLogin) {
3379
- const canAddPasswordOrPIN = !userAuthMethods.has(import_user_management_client.AuthMethod.PASSWORD) && !userAuthMethods.has(import_user_management_client.AuthMethod.PIN);
3380
- if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
3381
- ({
3382
- data: { id: passkeyId }
3383
- } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3384
- status: import_user_management_client.AuthMethodStatus.PENDING,
3385
- type: import_user_management_client.PublicKeyType.WEB
3386
- }));
3387
- urlType = "createAuth";
3388
- }
3389
- if (authMethods.includes("PASSWORD")) {
3390
- if (!canAddPasswordOrPIN) {
3391
- if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3392
- } else {
3393
- ({
3394
- data: { id: passwordId }
3395
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3396
- status: import_user_management_client.AuthMethodStatus.PENDING
3397
- }));
3398
- urlType = "createPassword";
3399
- }
3400
- }
3401
- if (authMethods.includes("PIN")) {
3402
- if (!canAddPasswordOrPIN) {
3403
- if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3404
- } else {
3405
- ({
3406
- data: { id: passwordId }
3407
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3408
- status: import_user_management_client.AuthMethodStatus.PENDING
3409
- }));
3410
- urlType = "createPIN";
3411
- }
3412
- }
3413
- credentialId = passkeyId != null ? passkeyId : passwordId;
3414
- if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3415
- return { credentialId };
3416
- }
3417
- }
3418
- const { sessionId } = yield this.touchSession();
3419
- const url = (isForNewDevice || urlType) && (yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
3420
- isForNewDevice,
3421
- pathId: credentialId,
3422
- portalTheme,
3423
- shorten,
3424
- sessionId: isForNewDevice ? sessionId : void 0,
3425
- addNewCredentialType: optsAuthMethod,
3426
- addNewCredentialPasskeyId: passkeyId,
3427
- addNewCredentialPasswordId: passwordId
3428
- }));
3429
- return __spreadValues({ credentialId }, url ? { url } : {});
3430
- });
3431
- }
3432
- addCredential(_0) {
3433
- return __async(this, arguments, function* ({ authMethod }) {
3434
- if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3435
- throw new Error("Passkeys are not supported.");
3436
- }
3437
- const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3438
- return url;
2558
+ return __async(this, arguments, function* (params = {}) {
2559
+ return yield __privateGet(this, _authService).getNewCredentialAndUrl(params);
3439
2560
  });
3440
2561
  }
3441
2562
  /**
@@ -3446,92 +2567,34 @@ Need help? Visit: https://docs.getpara.com or contact support
3446
2567
  * @param {Theme} opts.portalTheme the Para Portal theme to apply to the password creation URL, if other than the default theme
3447
2568
  * @returns {SignUpOrLogInResponse} an object in the form of either: `{ stage: 'verify' }` or `{ stage: 'login'; passkeyUrl?: string; passwordUrl?: string; biometricHints?: BiometricLocationHint[] }`
3448
2569
  */
3449
- getLoginUrl(_0) {
3450
- return __async(this, arguments, function* ({
3451
- authMethod = "PASSKEY",
3452
- shorten = false,
3453
- portalTheme,
3454
- sessionId
3455
- }) {
3456
- if (!sessionId) {
3457
- sessionId = (yield this.touchSession()).sessionLookupId;
3458
- }
3459
- this.assertIsAuthSet();
3460
- let urlType;
3461
- switch (authMethod) {
3462
- case "PASSKEY":
3463
- urlType = "loginAuth";
3464
- break;
3465
- case "PASSWORD":
3466
- urlType = "loginPassword";
3467
- break;
3468
- case "PIN":
3469
- urlType = "loginPIN";
3470
- break;
3471
- case "BASIC_LOGIN":
3472
- urlType = this.authInfo.authType === "externalWallet" ? "loginExternalWallet" : "loginOTP";
3473
- break;
3474
- default:
3475
- throw new Error(`invalid authentication method: '${authMethod}'`);
3476
- }
3477
- return this.constructPortalUrl(urlType, {
3478
- sessionId,
3479
- shorten,
3480
- portalTheme
3481
- });
2570
+ getLoginUrl(params) {
2571
+ return __async(this, null, function* () {
2572
+ return yield __privateGet(this, _portalUrlService).getLoginUrl(params);
3482
2573
  });
3483
2574
  }
3484
2575
  prepareLogin() {
3485
2576
  return __async(this, null, function* () {
3486
- yield this.logout();
3487
- const { sessionLookupId } = yield this.touchSession(true);
3488
- if (!this.loginEncryptionKeyPair) {
3489
- yield this.setLoginEncryptionKeyPair();
3490
- }
3491
- return sessionLookupId;
2577
+ return __privateGet(this, _authService).prepareLogin();
3492
2578
  });
3493
2579
  }
3494
- signUpOrLogIn(_i) {
2580
+ signUpOrLogIn(params) {
3495
2581
  return __async(this, null, function* () {
3496
- var _j = _i, { auth } = _j, urlOptions = __objRest(_j, ["auth"]);
3497
- let serverAuthState;
3498
- try {
3499
- serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3500
- } catch (error) {
3501
- if (error.message.includes("max beta users reached")) {
3502
- this.displayModalError(
3503
- `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3504
- );
3505
- }
3506
- throw error;
3507
- }
3508
- const authInfo = serverAuthState.auth;
3509
- if (this.fetchPregenWalletsOverride && (0, import_user_management_client.isPregenAuth)(authInfo)) {
3510
- const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
3511
- if (userShare) {
3512
- yield this.setUserShare(userShare);
3513
- }
3514
- }
3515
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
2582
+ return yield __privateGet(this, _authService).signUpOrLogIn(params);
3516
2583
  });
3517
2584
  }
3518
- verifyNewAccount(_k) {
2585
+ authenticateWithEmailOrPhone(params) {
3519
2586
  return __async(this, null, function* () {
3520
- var _l = _k, {
3521
- verificationCode
3522
- } = _l, urlOptions = __objRest(_l, [
3523
- "verificationCode"
3524
- ]);
3525
- this.assertIsAuthSet(["email", "phone"]);
3526
- const userId = this.assertUserId({ allowGuestMode: true });
3527
- const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
3528
- verificationCode
3529
- });
3530
- if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3531
- throw new Error("Account already exists.");
3532
- }
3533
- yield this.touchSession(true);
3534
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2587
+ return yield __privateGet(this, _authService).authenticateWithEmailOrPhone(params);
2588
+ });
2589
+ }
2590
+ authenticateWithOAuth(params) {
2591
+ return __async(this, null, function* () {
2592
+ return yield __privateGet(this, _authService).authenticateWithOAuth(params);
2593
+ });
2594
+ }
2595
+ verifyNewAccount(params) {
2596
+ return __async(this, null, function* () {
2597
+ return yield __privateGet(this, _authService).verifyNewAccount(params);
3535
2598
  });
3536
2599
  }
3537
2600
  getLinkedAccounts() {
@@ -3617,10 +2680,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3617
2680
  });
3618
2681
  }
3619
2682
  verifyLink() {
3620
- return __async(this, arguments, function* (_m = {}) {
3621
- var _n = _m, {
2683
+ return __async(this, arguments, function* (_e = {}) {
2684
+ var _f = _e, {
3622
2685
  accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3623
- } = _n, opts = __objRest(_n, [
2686
+ } = _f, opts = __objRest(_f, [
3624
2687
  "accountLinkInProgress"
3625
2688
  ]);
3626
2689
  try {
@@ -3702,7 +2765,15 @@ Need help? Visit: https://docs.getpara.com or contact support
3702
2765
  });
3703
2766
  }
3704
2767
  };
3705
- _authInfo = new WeakMap();
2768
+ _stateManager = new WeakMap();
2769
+ _authService = new WeakMap();
2770
+ _walletService = new WeakMap();
2771
+ _externalWalletService = new WeakMap();
2772
+ _pregenWalletService = new WeakMap();
2773
+ _pollingService = new WeakMap();
2774
+ _portalUrlService = new WeakMap();
2775
+ _sessionManagementService = new WeakMap();
2776
+ _debugLogsEnabled = new WeakMap();
3706
2777
  _ParaCore_instances = new WeakSet();
3707
2778
  assertPartner_fn = function() {
3708
2779
  return __async(this, null, function* () {
@@ -3716,27 +2787,6 @@ assertPartner_fn = function() {
3716
2787
  return this.partner;
3717
2788
  });
3718
2789
  };
3719
- guestWalletIds_get = function() {
3720
- var _a, _b, _c;
3721
- if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
3722
- return {};
3723
- }
3724
- const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
3725
- return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
3726
- if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
3727
- return __spreadValues(__spreadValues({}, acc), (0, import_utils2.getEquivalentTypes)(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3728
- var _a2;
3729
- return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
3730
- }, {}));
3731
- }
3732
- return acc;
3733
- }, {}) : {};
3734
- };
3735
- guestWalletIdsArray_get = function() {
3736
- return Object.entries(__privateGet(this, _ParaCore_instances, guestWalletIds_get)).reduce((acc, [type, ids]) => {
3737
- return [...acc, ...ids.map((id) => [id, type])];
3738
- }, []);
3739
- };
3740
2790
  toAuthInfo_fn = function({
3741
2791
  email,
3742
2792
  phone,
@@ -3768,27 +2818,7 @@ toAuthInfo_fn = function({
3768
2818
  }
3769
2819
  return (0, import_user_management_client.extractAuthInfo)(auth);
3770
2820
  };
3771
- setAuthInfo_fn = function(authInfo) {
3772
- return __async(this, null, function* () {
3773
- __privateSet(this, _authInfo, authInfo);
3774
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_AUTH_INFO, JSON.stringify(authInfo));
3775
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_EMAIL);
3776
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_PHONE);
3777
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_COUNTRY_CODE);
3778
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_FARCASTER_USERNAME);
3779
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_TELEGRAM_USER_ID);
3780
- });
3781
- };
3782
- getPartner_fn = function(partnerId) {
3783
- return __async(this, null, function* () {
3784
- if (this.isPartnerOptional && !partnerId) {
3785
- return void 0;
3786
- }
3787
- const res = yield this.ctx.client.getPartner(partnerId);
3788
- this.partner = res.data.partner;
3789
- return this.partner;
3790
- });
3791
- };
2821
+ _servicesInitialized = new WeakMap();
3792
2822
  assertIsLinkingAccount_fn = function(types) {
3793
2823
  if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3794
2824
  throw new Error("no account linking in progress");
@@ -3808,49 +2838,6 @@ assertIsLinkingAccountOrStart_fn = function(type) {
3808
2838
  return yield this.linkAccount({ type });
3809
2839
  });
3810
2840
  };
3811
- getOAuthUrl_fn = function(_0) {
3812
- return __async(this, arguments, function* ({
3813
- method,
3814
- appScheme,
3815
- accountLinkInProgress,
3816
- sessionLookupId,
3817
- encryptionKey,
3818
- portalCallbackParams
3819
- }) {
3820
- if (!accountLinkInProgress && !this.isPortal()) {
3821
- return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3822
- }
3823
- const [portalSessionLookupId, callback] = yield Promise.all([
3824
- this.isPortal() ? this.touchSession(true).then((s) => s.sessionLookupId) : Promise.resolve(void 0),
3825
- !accountLinkInProgress ? this.constructPortalUrl("oAuthCallback", __spreadValues({
3826
- sessionId: sessionLookupId,
3827
- oAuthMethod: method,
3828
- appScheme,
3829
- thisDevice: {
3830
- sessionId: sessionLookupId,
3831
- encryptionKey
3832
- }
3833
- }, this.isPortal() && {
3834
- params: portalCallbackParams,
3835
- // Build callback for legacy portal if needed
3836
- useLegacyUrl: typeof window !== "undefined" ? window.location.host.includes("usecapsule") : false
3837
- })) : Promise.resolve(false)
3838
- ]);
3839
- return (0, import_utils2.constructUrl)({
3840
- base: (0, import_userManagementClient.getBaseOAuthUrl)(this.ctx.env),
3841
- path: `/auth/${method.toLowerCase()}`,
3842
- params: __spreadValues(__spreadValues({
3843
- apiKey: this.ctx.apiKey,
3844
- origin: typeof window !== "undefined" ? window.location.origin : void 0,
3845
- sessionLookupId,
3846
- portalSessionLookupId,
3847
- appScheme
3848
- }, accountLinkInProgress ? {
3849
- linkedAccountId: this.accountLinkInProgress.id
3850
- } : {}), callback && { callback })
3851
- });
3852
- });
3853
- };
3854
2841
  waitForLoginProcess_fn = function() {
3855
2842
  return __async(this, arguments, function* ({
3856
2843
  isCanceled = () => false,
@@ -3878,7 +2865,7 @@ waitForLoginProcess_fn = function() {
3878
2865
  var _a;
3879
2866
  if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3880
2867
  this.devLog("[waitForLoginProcess] Clearing external wallets");
3881
- this.externalWallets = {};
2868
+ __privateGet(this, _externalWalletService).externalWallets = {};
3882
2869
  }
3883
2870
  let pollCount = 0;
3884
2871
  while (true) {
@@ -3923,7 +2910,7 @@ waitForLoginProcess_fn = function() {
3923
2910
  continue;
3924
2911
  }
3925
2912
  this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3926
- session = yield this.userSetupAfterLogin();
2913
+ session = yield this.userSetupAfterLogin(session);
3927
2914
  const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3928
2915
  this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3929
2916
  if (isSwitchingWallets) {
@@ -3948,7 +2935,9 @@ waitForLoginProcess_fn = function() {
3948
2935
  }
3949
2936
  }
3950
2937
  this.devLog("[waitForLoginProcess] Getting transmission key shares");
3951
- const tempSharesRes = yield this.getTransmissionKeyShares();
2938
+ const tempSharesRes = yield this.getTransmissionKeyShares({
2939
+ sessionLookupId: session.sessionLookupId
2940
+ });
3952
2941
  this.devLog("[waitForLoginProcess] Transmission shares received", {
3953
2942
  shareCount: tempSharesRes.data.temporaryShares.length,
3954
2943
  shares: tempSharesRes.data.temporaryShares.map((s) => ({
@@ -4015,224 +3004,41 @@ waitForLoginProcess_fn = function() {
4015
3004
  });
4016
3005
  });
4017
3006
  };
4018
- createPregenWallet_fn = function(opts) {
4019
- return __async(this, null, function* () {
4020
- var _a, _b;
4021
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
4022
- const { type: _type = (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type, pregenId } = opts;
4023
- this.requireApiKey();
4024
- const walletType = yield this.assertIsValidWalletType(
4025
- _type != null ? _type : (_b = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
4026
- );
4027
- const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client.toPregenTypeAndId)(pregenId);
4028
- let keygenRes;
4029
- switch (walletType) {
4030
- case "SOLANA":
4031
- keygenRes = yield this.platformUtils.ed25519PreKeygen(
4032
- this.ctx,
4033
- pregenIdentifier,
4034
- pregenIdentifierType,
4035
- this.retrieveSessionCookie()
4036
- );
4037
- break;
4038
- default:
4039
- keygenRes = yield this.platformUtils.preKeygen(
4040
- this.ctx,
4041
- void 0,
4042
- pregenIdentifier,
4043
- pregenIdentifierType,
4044
- walletType,
4045
- null,
4046
- this.retrieveSessionCookie()
4047
- );
4048
- break;
4049
- }
4050
- const { signer, walletId } = keygenRes;
4051
- this.wallets[walletId] = {
4052
- id: walletId,
4053
- signer,
4054
- scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
4055
- type: walletType,
4056
- isPregen: true,
4057
- pregenIdentifier,
4058
- pregenIdentifierType
4059
- };
4060
- yield this.waitForPregenWalletAddress(walletId);
4061
- yield this.populatePregenWalletAddresses();
4062
- return this.wallets[walletId];
4063
- });
4064
- };
4065
- _isCreateGuestWalletsPending = new WeakMap();
4066
- prepareAuthState_fn = function(_0) {
4067
- return __async(this, arguments, function* (serverAuthState, opts = {}) {
4068
- var _a, _b;
4069
- if (!opts.sessionLookupId && serverAuthState.stage === "login" && (!serverAuthState.externalWallet || !(((_a = serverAuthState.externalWallet) == null ? void 0 : _a.withFullParaAuth) && ((_b = serverAuthState.loginAuthMethods) == null ? void 0 : _b.includes(import_user_management_client.AuthMethod.PIN))))) {
4070
- opts.sessionLookupId = yield this.prepareLogin();
4071
- }
4072
- const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
4073
- const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client.extractAuthInfo)(auth, { isRequired: true })), Object.fromEntries(
4074
- Object.entries({
4075
- displayName,
4076
- pfpUrl,
4077
- username,
4078
- externalWallet
4079
- }).filter(([_, v]) => !!v)
4080
- ));
4081
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
4082
- this.assertIsAuthSet();
4083
- if (!!externalWallet) {
4084
- yield this.setExternalWallet([externalWallet]);
4085
- }
4086
- if (!!userId) {
4087
- yield this.setUserId(userId);
3007
+ logout_fn = function() {
3008
+ return __async(this, arguments, function* ({
3009
+ clearPregenWallets = false,
3010
+ skipStateReset = false
3011
+ } = {}) {
3012
+ const isSessionActive = yield this.isSessionActive();
3013
+ if (!isSessionActive && !skipStateReset) {
3014
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
4088
3015
  }
4089
- let authState;
4090
- switch (serverAuthState.stage) {
4091
- case "done": {
4092
- authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
4093
- break;
4094
- }
4095
- case "verify":
4096
- authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
4097
- sessionLookupId: opts.sessionLookupId
4098
- }));
4099
- break;
4100
- case "login":
4101
- if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
4102
- authState = serverAuthState;
4103
- break;
4104
- }
4105
- authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
4106
- break;
4107
- case "signup":
4108
- if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
4109
- authState = serverAuthState;
4110
- break;
3016
+ yield this.ctx.client.logout();
3017
+ yield this.clearStorage();
3018
+ if (!clearPregenWallets) {
3019
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
3020
+ if (!wallet.pregenIdentifier) {
3021
+ delete this.wallets[id];
4111
3022
  }
4112
- authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
4113
- break;
4114
- }
4115
- return authState;
4116
- });
4117
- };
4118
- prepareDoneState_fn = function(doneState) {
4119
- return __async(this, null, function* () {
4120
- let isSLOPossible = doneState.authMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
4121
- this.isEnclaveUser = isSLOPossible;
4122
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_ENCLAVE_USER, JSON.stringify(isSLOPossible));
4123
- return doneState;
4124
- });
4125
- };
4126
- prepareVerificationState_fn = function(_0, _1) {
4127
- return __async(this, arguments, function* (verifyState, {
4128
- useShortUrls: shorten = false,
4129
- portalTheme,
4130
- sessionLookupId
4131
- }) {
4132
- var _a;
4133
- let isSLOPossible = false;
4134
- if (verifyState.nextStage === "login") {
4135
- isSLOPossible = verifyState.loginAuthMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
4136
- } else if (verifyState.nextStage === "signup") {
4137
- isSLOPossible = verifyState.signupAuthMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
4138
- }
4139
- this.isEnclaveUser = isSLOPossible;
4140
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_ENCLAVE_USER, JSON.stringify(isSLOPossible));
4141
- const isExternalWalletFullAuth = (_a = verifyState.externalWallet) == null ? void 0 : _a.withFullParaAuth;
4142
- return __spreadValues(__spreadValues({}, verifyState), isSLOPossible || isExternalWalletFullAuth ? {
4143
- loginUrl: yield this.getLoginUrl({
4144
- authMethod: import_user_management_client.AuthMethod.BASIC_LOGIN,
4145
- sessionId: sessionLookupId,
4146
- shorten,
4147
- portalTheme
4148
- })
4149
- } : {});
4150
- });
4151
- };
4152
- prepareLoginState_fn = function(_0, _1) {
4153
- return __async(this, arguments, function* (loginState, {
4154
- useShortUrls: shorten = false,
4155
- portalTheme,
4156
- sessionLookupId
4157
- }) {
4158
- const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
4159
- const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PIN);
4160
- return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
4161
- isPasskeySupported,
4162
- loginAuthMethods
4163
- }), isPasskeyPossible ? {
4164
- passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
4165
- passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
4166
- sessionId: sessionLookupId,
4167
- newDevice: {
4168
- sessionId: sessionLookupId,
4169
- encryptionKey: (0, import_utils.getPublicKeyHex)(this.loginEncryptionKeyPair)
4170
- },
4171
- shorten,
4172
- portalTheme
4173
- })
4174
- } : {}), isPasswordPossible ? {
4175
- passwordUrl: yield this.constructPortalUrl("loginPassword", {
4176
- sessionId: sessionLookupId,
4177
- shorten,
4178
- portalTheme,
4179
- params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4180
- })
4181
- } : {}), isPINPossible ? {
4182
- pinUrl: yield this.constructPortalUrl("loginPIN", {
4183
- sessionId: sessionLookupId,
4184
- shorten,
4185
- portalTheme,
4186
- params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4187
- })
4188
- } : {});
4189
- });
4190
- };
4191
- prepareSignUpState_fn = function(_0, _1) {
4192
- return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
4193
- const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
4194
- const isPasskeySupported = yield this.isPasskeySupported();
4195
- const [isPasskey, isPassword, isPIN] = [
4196
- signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY),
4197
- signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) || !isPasskeySupported,
4198
- signupAuthMethods.includes(import_user_management_client.AuthMethod.PIN)
4199
- ];
4200
- if (!isPasskey && !isPassword && !isPIN) {
4201
- throw new Error(
4202
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
4203
- );
4204
- }
4205
- const signupState = __spreadProps(__spreadValues({}, authState), {
4206
- isPasskeySupported,
4207
- signupAuthMethods
4208
- });
4209
- if (isPasskey) {
4210
- const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
4211
- authMethod: "PASSKEY",
4212
- shorten
4213
3023
  });
4214
- if (passkeyUrl) signupState.passkeyUrl = passkeyUrl;
4215
- signupState.passkeyId = passkeyId;
4216
- }
4217
- if (isPassword) {
4218
- const { url: passwordUrl, credentialId: passwordId } = yield this.getNewCredentialAndUrl({
4219
- authMethod: "PASSWORD",
4220
- portalTheme,
4221
- shorten
4222
- });
4223
- signupState.passwordUrl = passwordUrl;
4224
- signupState.passwordId = passwordId;
3024
+ yield this.setWallets(this.wallets);
3025
+ } else {
3026
+ __privateGet(this, _walletService).wallets = {};
4225
3027
  }
4226
- if (isPIN) {
4227
- const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
4228
- authMethod: "PIN",
4229
- portalTheme,
4230
- shorten
4231
- });
4232
- signupState.pinUrl = pinUrl;
4233
- signupState.pinId = pinId;
3028
+ __privateGet(this, _walletService).currentWalletIds = {};
3029
+ __privateGet(this, _externalWalletService).externalWallets = {};
3030
+ this.loginEncryptionKeyPair = void 0;
3031
+ __privateGet(this, _authService).authInfo = void 0;
3032
+ this.accountLinkInProgress = void 0;
3033
+ __privateGet(this, _authService).userId = void 0;
3034
+ __privateGet(this, _sessionManagementService).sessionCookie = void 0;
3035
+ this.isEnclaveUser = false;
3036
+ if (isSessionActive) {
3037
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
3038
+ if (!skipStateReset) {
3039
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
3040
+ }
4234
3041
  }
4235
- return signupState;
4236
3042
  });
4237
3043
  };
4238
3044
  _ParaCore.version = constants.PARA_CORE_VERSION;