@getpara/core-sdk 2.12.0 → 2.13.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 +793 -2003
  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 +297 -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 +437 -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 +796 -2031
  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 +261 -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 +382 -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 +190 -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 +22033 -0
  180. package/dist/types/state/machines/walletStateMachine.d.ts +1049 -0
  181. package/dist/types/state/types/auth.d.ts +113 -0
  182. package/dist/types/state/types/core.d.ts +114 -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, 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,9 @@ const _ParaCore = class _ParaCore {
194
197
  yield this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
195
198
  }
196
199
  });
200
+ this.initExternalWalletProvider = (params) => __async(this, null, function* () {
201
+ yield __privateGet(this, _externalWalletService).initExternalWalletProvider(params);
202
+ });
197
203
  this.trackError = (methodName, err) => __async(this, null, function* () {
198
204
  try {
199
205
  yield this.ctx.client.trackError({
@@ -252,7 +258,7 @@ const _ParaCore = class _ParaCore {
252
258
  };
253
259
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
254
260
  }
255
- __privateSet(this, _authInfo, authInfo);
261
+ __privateGet(this, _authService).authInfo = authInfo;
256
262
  };
257
263
  this.updateEnclaveJwtFromStorage = () => {
258
264
  this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
@@ -265,7 +271,7 @@ const _ParaCore = class _ParaCore {
265
271
  }
266
272
  };
267
273
  this.updateUserIdFromStorage = () => {
268
- this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
274
+ __privateGet(this, _authService).userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
269
275
  };
270
276
  this.updateWalletsFromStorage = () => __async(this, null, function* () {
271
277
  var _a;
@@ -306,12 +312,13 @@ const _ParaCore = class _ParaCore {
306
312
  }, {}) : fromJson;
307
313
  })();
308
314
  this.setCurrentWalletIds(currentWalletIds);
309
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
315
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
310
316
  this.findWalletId(void 0, { forbidPregen: true });
311
317
  }
312
318
  };
313
319
  this.updateSessionCookieFromStorage = () => {
314
- this.sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
320
+ __privateGet(this, _sessionManagementService).sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
321
+ __privateGet(this, _sessionManagementService).isImportedSession = this.localStorageGetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION) === "true" || false;
315
322
  };
316
323
  this.updateLoginEncryptionKeyPairFromStorage = () => {
317
324
  const loginEncryptionKey = this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -334,6 +341,25 @@ const _ParaCore = class _ParaCore {
334
341
  }
335
342
  }
336
343
  });
344
+ this.setCurrentWalletIds = (...params) => __async(this, null, function* () {
345
+ const [currentWalletIds, { needsWallet = false, sessionLookupId, newDeviceSessionLookupId } = {}] = params;
346
+ return yield __privateGet(this, _walletService).setCurrentWalletIds(currentWalletIds, {
347
+ needsWallet,
348
+ sessionLookupId,
349
+ newDeviceSessionLookupId
350
+ });
351
+ });
352
+ /**
353
+ * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
354
+ * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
355
+ * @param {string} [walletId] the wallet ID to validate.
356
+ * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
357
+ * @returns {string} the wallet ID originally passed, or the one found.
358
+ */
359
+ this.findWalletId = (...params) => {
360
+ const [walletId, filters = {}] = params;
361
+ return __privateGet(this, _walletService).findWalletId(walletId, filters);
362
+ };
337
363
  /**
338
364
  * Creates several new wallets with the desired types. If no types are provided, this method
339
365
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -343,12 +369,8 @@ const _ParaCore = class _ParaCore {
343
369
  * @deprecated alias for `createWalletPerType`
344
370
  **/
345
371
  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;
372
+ this.addCredential = (params) => __async(this, null, function* () {
373
+ return yield __privateGet(this, _authService).addCredential(params);
352
374
  });
353
375
  let env, apiKey;
354
376
  const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
@@ -379,6 +401,7 @@ const _ParaCore = class _ParaCore {
379
401
  apiKey = apiKeyOrOpts;
380
402
  }
381
403
  if (!opts) opts = {};
404
+ __privateSet(this, _debugLogsEnabled, !!opts.enableDebugLogs);
382
405
  let isE2E = false;
383
406
  if (env === "E2E") {
384
407
  isE2E = true;
@@ -413,7 +436,7 @@ const _ParaCore = class _ParaCore {
413
436
  this.localStorageSetItem = this.sessionStorageSetItem;
414
437
  }
415
438
  this.persistSessionCookie = (cookie) => {
416
- this.sessionCookie = cookie;
439
+ __privateGet(this, _sessionManagementService).sessionCookie = cookie;
417
440
  (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
418
441
  constants.LOCAL_STORAGE_SESSION_COOKIE,
419
442
  cookie
@@ -468,6 +491,59 @@ const _ParaCore = class _ParaCore {
468
491
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
469
492
  return;
470
493
  }
494
+ __privateSet(this, _authService, new import_AuthService.AuthService(this));
495
+ __privateSet(this, _walletService, new import_WalletService.WalletService(this));
496
+ __privateSet(this, _externalWalletService, new import_ExternalWalletService.ExternalWalletService(this));
497
+ __privateSet(this, _pregenWalletService, new import_PregenWalletService.PregenWalletService(this));
498
+ __privateSet(this, _pollingService, new import_PollingService.PollingService(this));
499
+ __privateSet(this, _portalUrlService, new import_PortalUrlService.PortalUrlService(this));
500
+ __privateSet(this, _sessionManagementService, new import_SessionManagementService.SessionManagementService(this));
501
+ __privateSet(this, _stateManager, new import_CoreStateManager.CoreStateManager(this));
502
+ __privateGet(this, _authService).init({
503
+ stateManager: __privateGet(this, _stateManager),
504
+ portalUrlService: __privateGet(this, _portalUrlService),
505
+ externalWalletService: __privateGet(this, _externalWalletService),
506
+ sessionManagementService: __privateGet(this, _sessionManagementService),
507
+ pregenWalletService: __privateGet(this, _pregenWalletService),
508
+ walletService: __privateGet(this, _walletService)
509
+ });
510
+ __privateGet(this, _walletService).init({
511
+ authService: __privateGet(this, _authService),
512
+ pollingService: __privateGet(this, _pollingService),
513
+ pregenWalletService: __privateGet(this, _pregenWalletService),
514
+ externalWalletService: __privateGet(this, _externalWalletService)
515
+ });
516
+ __privateGet(this, _externalWalletService).init({
517
+ stateManager: __privateGet(this, _stateManager),
518
+ authService: __privateGet(this, _authService),
519
+ walletService: __privateGet(this, _walletService)
520
+ });
521
+ __privateGet(this, _pollingService).init({
522
+ authService: __privateGet(this, _authService),
523
+ pregenWalletService: __privateGet(this, _pregenWalletService),
524
+ walletService: __privateGet(this, _walletService),
525
+ portalUrlService: __privateGet(this, _portalUrlService),
526
+ sessionManagementService: __privateGet(this, _sessionManagementService)
527
+ });
528
+ __privateGet(this, _pregenWalletService).init({
529
+ stateManager: __privateGet(this, _stateManager),
530
+ authService: __privateGet(this, _authService),
531
+ walletService: __privateGet(this, _walletService),
532
+ pollingService: __privateGet(this, _pollingService)
533
+ });
534
+ __privateGet(this, _portalUrlService).init({
535
+ authService: __privateGet(this, _authService),
536
+ walletService: __privateGet(this, _walletService),
537
+ pregenWalletService: __privateGet(this, _pregenWalletService),
538
+ sessionManagementService: __privateGet(this, _sessionManagementService)
539
+ });
540
+ __privateGet(this, _sessionManagementService).init({
541
+ authService: __privateGet(this, _authService),
542
+ portalUrlService: __privateGet(this, _portalUrlService),
543
+ walletService: __privateGet(this, _walletService),
544
+ pregenWalletService: __privateGet(this, _pregenWalletService),
545
+ externalWalletService: __privateGet(this, _externalWalletService)
546
+ });
471
547
  this.initializeFromStorage();
472
548
  import_utils2.setupListeners.bind(this)();
473
549
  (0, import_utils2.autoBind)(this);
@@ -487,71 +563,183 @@ const _ParaCore = class _ParaCore {
487
563
  "signTransaction"
488
564
  ]);
489
565
  }
566
+ __privateGet(this, _stateManager).start();
490
567
  }
491
568
  setModalError(_error) {
492
569
  return;
493
570
  }
571
+ /**
572
+ * The current readiness state.
573
+ */
574
+ get isReady() {
575
+ return __privateGet(this, _stateManager).getSnapshot().isReady;
576
+ }
577
+ /**
578
+ * The current phase of the core flow.
579
+ */
580
+ get corePhase() {
581
+ return __privateGet(this, _stateManager).getSnapshot().phase;
582
+ }
583
+ /**
584
+ * The current phase of the authentication flow.
585
+ */
586
+ get authPhase() {
587
+ return __privateGet(this, _stateManager).getSnapshot().authStatePhase;
588
+ }
589
+ /**
590
+ * The current phase of the wallet flow.
591
+ */
592
+ get walletPhase() {
593
+ return __privateGet(this, _stateManager).getSnapshot().walletStatePhase;
594
+ }
595
+ /**
596
+ * Any error that has occurred in the core flow.
597
+ */
598
+ get error() {
599
+ return __privateGet(this, _stateManager).getSnapshot().error;
600
+ }
601
+ /**
602
+ * Get the current state of the core, auth, and wallet phases.
603
+ * @returns An object containing the current core, auth, and wallet state phases, along with any error.
604
+ */
605
+ getCurrentState() {
606
+ const state = __privateGet(this, _stateManager).getSnapshot();
607
+ return {
608
+ corePhase: state.phase,
609
+ authPhase: state.authStatePhase,
610
+ walletPhase: state.walletStatePhase,
611
+ authStateInfo: state.authStateInfo,
612
+ error: state.error,
613
+ isReady: state.isReady
614
+ };
615
+ }
616
+ /**
617
+ * Subscribe to changes in the core, auth, and wallet state phases.
618
+ *
619
+ * This method immediately calls the callback with the current state, then continues
620
+ * to call it whenever any phase changes. This ensures you never miss the initial state
621
+ * and can react to all subsequent changes.
622
+ *
623
+ * @param callback A function that will be called with the current state phases whenever they change.
624
+ * The callback receives an object containing `corePhase`, `authPhase`, `walletPhase`, and `error`.
625
+ *
626
+ * @returns A function that can be called to unsubscribe from the state changes.
627
+ * Always call this function when your component unmounts or when you no longer need updates
628
+ * to prevent memory leaks.
629
+ *
630
+ * @example
631
+ * ```typescript
632
+ * // React example
633
+ * useEffect(() => {
634
+ * const unsubscribe = paraClient.onStatePhaseChange((snapshot) => {
635
+ * console.log('Core phase:', snapshot.corePhase);
636
+ * console.log('Auth phase:', snapshot.authPhase);
637
+ * console.log('Wallet phase:', snapshot.walletPhase);
638
+ *
639
+ * if (snapshot.error) {
640
+ * console.error('Para error:', snapshot.error.message);
641
+ * }
642
+ * });
643
+ *
644
+ * return unsubscribe; // Cleanup on unmount
645
+ * }, [paraClient]);
646
+ *
647
+ * // Vue example
648
+ * onMounted(() => {
649
+ * const unsubscribe = paraClient.onStatePhaseChange((state) => {
650
+ * phases.value = state;
651
+ * });
652
+ *
653
+ * onUnmounted(unsubscribe);
654
+ * });
655
+ * ```
656
+ */
657
+ onStatePhaseChange(callback) {
658
+ let lastSnapshot = null;
659
+ const fullListener = (state) => {
660
+ const currentSnapshot = {
661
+ corePhase: state.phase,
662
+ authPhase: state.authStatePhase,
663
+ walletPhase: state.walletStatePhase,
664
+ authStateInfo: state.authStateInfo,
665
+ error: state.error,
666
+ isReady: state.isReady
667
+ };
668
+ if (!lastSnapshot || lastSnapshot.corePhase !== currentSnapshot.corePhase || lastSnapshot.authPhase !== currentSnapshot.authPhase || lastSnapshot.walletPhase !== currentSnapshot.walletPhase || lastSnapshot.error !== currentSnapshot.error || lastSnapshot.isReady !== currentSnapshot.isReady) {
669
+ lastSnapshot = currentSnapshot;
670
+ callback(currentSnapshot);
671
+ }
672
+ };
673
+ return __privateGet(this, _stateManager).onStateChange(fullListener);
674
+ }
675
+ /**
676
+ * Subscribe to changes in the readiness state of the ParaCore instance.
677
+ * @param callback A function that will be called with the new readiness state.
678
+ * @returns A function that can be called to unsubscribe from the readiness state changes.
679
+ */
680
+ onReadyStateChange(callback) {
681
+ let lastIsReady = null;
682
+ const unsubscribe = __privateGet(this, _stateManager).onStateChange((state) => {
683
+ if (lastIsReady !== state.isReady) {
684
+ lastIsReady = state.isReady;
685
+ callback(state.isReady);
686
+ }
687
+ });
688
+ return () => unsubscribe();
689
+ }
494
690
  get authInfo() {
495
- return __privateGet(this, _authInfo);
691
+ var _a;
692
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
496
693
  }
497
694
  get email() {
498
695
  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;
696
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
500
697
  }
501
698
  get phone() {
502
699
  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;
700
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
504
701
  }
505
702
  get farcasterUsername() {
506
703
  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;
704
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
508
705
  }
509
706
  get telegramUserId() {
510
707
  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;
708
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.telegramUserId;
512
709
  }
513
710
  get externalWalletWithParaAuth() {
514
- const externalWallets = Object.values(this.externalWallets);
515
- return externalWallets.find((w) => w.isExternalWithParaAuth);
711
+ return __privateGet(this, _externalWalletService).externalWalletWithParaAuth;
516
712
  }
517
713
  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";
714
+ return __privateGet(this, _externalWalletService).externalWalletConnectionType;
531
715
  }
532
- get isEmail() {
716
+ get userId() {
533
717
  var _a;
534
- return (0, import_user_management_client.isEmail)((_a = this.authInfo) == null ? void 0 : _a.auth);
718
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
719
+ }
720
+ get isEnclaveUser() {
721
+ return __privateGet(this, _authService).isEnclaveUser;
722
+ }
723
+ set isEnclaveUser(value) {
724
+ __privateGet(this, _authService).isEnclaveUser = value;
725
+ }
726
+ get isEmail() {
727
+ return __privateGet(this, _authService).isEmail;
535
728
  }
536
729
  get isPhone() {
537
- var _a;
538
- return (0, import_user_management_client.isPhone)((_a = this.authInfo) == null ? void 0 : _a.auth);
730
+ return __privateGet(this, _authService).isPhone;
539
731
  }
540
732
  get isFarcaster() {
541
- var _a;
542
- return (0, import_user_management_client.isFarcaster)((_a = this.authInfo) == null ? void 0 : _a.auth);
733
+ return __privateGet(this, _authService).isFarcaster;
543
734
  }
544
735
  get isTelegram() {
545
- var _a;
546
- return (0, import_user_management_client.isTelegram)((_a = this.authInfo) == null ? void 0 : _a.auth);
736
+ return __privateGet(this, _authService).isTelegram;
547
737
  }
548
738
  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);
739
+ return __privateGet(this, _authService).isExternalWalletAuth;
551
740
  }
552
741
  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);
742
+ return __privateGet(this, _authService).isExternalWalletWithVerification;
555
743
  }
556
744
  get partnerId() {
557
745
  var _a;
@@ -565,45 +753,42 @@ const _ParaCore = class _ParaCore {
565
753
  var _a;
566
754
  return (_a = this.partner) == null ? void 0 : _a.logoUrl;
567
755
  }
756
+ get currentWalletIds() {
757
+ return __privateGet(this, _walletService).currentWalletIds;
758
+ }
568
759
  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
- );
760
+ return __privateGet(this, _walletService).currentWalletIdsArray;
582
761
  }
583
762
  get currentWalletIdsUnique() {
584
- return [...new Set(Object.values(this.currentWalletIds).flat())];
763
+ return __privateGet(this, _walletService).currentWalletIdsUnique;
764
+ }
765
+ /**
766
+ * Wallets associated with the `ParaCore` instance. Retrieve a particular wallet using `para.wallets[walletId]`.
767
+ */
768
+ get wallets() {
769
+ var _a;
770
+ return (_a = __privateGet(this, _walletService)) == null ? void 0 : _a.wallets;
771
+ }
772
+ /**
773
+ * Wallets associated with the `ParaCore` instance.
774
+ */
775
+ get externalWallets() {
776
+ var _a;
777
+ return (_a = __privateGet(this, _externalWalletService)) == null ? void 0 : _a.externalWallets;
585
778
  }
586
779
  /**
587
780
  * A map of pre-generated wallet identifiers that can be claimed in the current instance.
588
781
  */
589
782
  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
- }, {}));
783
+ var _a;
784
+ return (_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.pregenIds;
601
785
  }
602
786
  /**
603
787
  * Whether the instance has multiple wallets connected.
604
788
  */
605
789
  get isMultiWallet() {
606
- return this.currentWalletIdsArray.length > 1 || __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 1;
790
+ var _a;
791
+ return this.currentWalletIdsArray.length > 1 || ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 1;
607
792
  }
608
793
  get isNoWalletConfig() {
609
794
  var _a;
@@ -668,60 +853,6 @@ const _ParaCore = class _ParaCore {
668
853
  );
669
854
  }
670
855
  }
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
856
  /**
726
857
  * Returns the formatted address for the desired wallet ID, depending on your app settings.
727
858
  * @param {string} walletId the ID of the wallet address to display.
@@ -730,32 +861,9 @@ const _ParaCore = class _ParaCore {
730
861
  * @param {TWalletType} options.addressType the type of address to display.
731
862
  * @returns the formatted address
732
863
  */
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;
864
+ getDisplayAddress(...params) {
865
+ const [walletId, options = {}] = params;
866
+ return __privateGet(this, _walletService).getDisplayAddress(walletId, options);
759
867
  }
760
868
  /**
761
869
  * Returns a unique hash for a wallet suitable for use as an identicon seed.
@@ -763,13 +871,8 @@ const _ParaCore = class _ParaCore {
763
871
  * @param {boolean} options.addressType used to format the hash for another wallet type.
764
872
  * @returns the identicon hash string
765
873
  */
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;
874
+ getIdenticonHash(...params) {
875
+ return __privateGet(this, _walletService).getIdenticonHash(...params);
773
876
  }
774
877
  getWallets() {
775
878
  return this.wallets;
@@ -780,192 +883,7 @@ const _ParaCore = class _ParaCore {
780
883
  }
781
884
  constructPortalUrl(_0) {
782
885
  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;
886
+ return yield __privateGet(this, _portalUrlService).constructPortalUrl(type, opts);
969
887
  });
970
888
  }
971
889
  static resolveEnvironment(env, apiKey) {
@@ -987,58 +905,182 @@ const _ParaCore = class _ParaCore {
987
905
  }
988
906
  return env;
989
907
  }
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();
908
+ // Create a dedicated interface for #authService
909
+ getAuthServiceInterface() {
910
+ const self2 = this;
911
+ return {
912
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
913
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
914
+ localStorageGetItem: this.localStorageGetItem.bind(this),
915
+ localStorageSetItem: this.localStorageSetItem.bind(this),
916
+ localStorageRemoveItem: this.localStorageRemoveItem.bind(this),
917
+ isPasskeySupported: this.isPasskeySupported.bind(this),
918
+ getVerificationEmailProps: this.getVerificationEmailProps.bind(this),
919
+ displayModalError: this.displayModalError.bind(this),
920
+ isPortal: this.isPortal.bind(this),
921
+ assertIsLinkingAccount: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).bind(this),
922
+ requireApiKey: this.requireApiKey.bind(this),
923
+ get loginEncryptionKeyPair() {
924
+ return self2.loginEncryptionKeyPair;
925
+ },
926
+ get isNativePasskey() {
927
+ return self2.isNativePasskey;
928
+ },
929
+ ctx: this.ctx,
930
+ get accountLinkInProgress() {
931
+ return self2.accountLinkInProgress;
932
+ },
933
+ partnerId: this.partnerId,
934
+ platformUtils: this.platformUtils,
935
+ externalWalletConnectionOnly: !!this.externalWalletConnectionOnly
936
+ };
937
+ }
938
+ // Create a dedicated interface for WalletService
939
+ getWalletServiceInterface() {
940
+ const self2 = this;
941
+ return {
942
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
943
+ requireApiKey: this.requireApiKey.bind(this),
944
+ isPortal: this.isPortal.bind(this),
945
+ localStorageSetItem: this.localStorageSetItem.bind(this),
946
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
947
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
948
+ isParaConnect: this.isParaConnect.bind(this),
949
+ ctx: this.ctx,
950
+ get partner() {
951
+ return self2.partner;
952
+ },
953
+ platformUtils: this.platformUtils,
954
+ cosmosPrefix: this.cosmosPrefix
955
+ };
956
+ }
957
+ // Create a dedicated interface for PregenWalletService
958
+ getPregenWalletServiceInterface() {
959
+ var _a;
960
+ const self2 = this;
961
+ return {
962
+ fetchPregenWalletsOverride: (_a = this.fetchPregenWalletsOverride) == null ? void 0 : _a.bind(this),
963
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
964
+ requireApiKey: this.requireApiKey.bind(this),
965
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
966
+ isPortal: this.isPortal.bind(this),
967
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
968
+ ctx: this.ctx,
969
+ platformUtils: this.platformUtils,
970
+ get partner() {
971
+ return self2.partner;
998
972
  }
999
- let session;
1000
- try {
1001
- session = yield this.ctx.client.touchSession(regenerate);
1002
- } catch (error) {
1003
- this.handleTouchSessionError(error);
1004
- throw error;
973
+ };
974
+ }
975
+ // Create a dedicated interface for PortalUrlService
976
+ getPortalUrlServiceInterface() {
977
+ const self2 = this;
978
+ return {
979
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
980
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
981
+ isPortal: this.isPortal.bind(this),
982
+ isPartnerOptional: this.isPartnerOptional,
983
+ ctx: this.ctx,
984
+ get loginEncryptionKeyPair() {
985
+ return self2.loginEncryptionKeyPair;
986
+ },
987
+ get portalTheme() {
988
+ return self2.portalTheme;
989
+ },
990
+ get portalPrimaryButtonColor() {
991
+ return self2.portalPrimaryButtonColor;
992
+ },
993
+ get portalTextColor() {
994
+ return self2.portalTextColor;
995
+ },
996
+ get portalPrimaryButtonTextColor() {
997
+ return self2.portalPrimaryButtonTextColor;
998
+ },
999
+ get portalBackgroundColor() {
1000
+ return self2.portalBackgroundColor;
1001
+ },
1002
+ get accountLinkInProgress() {
1003
+ return self2.accountLinkInProgress;
1005
1004
  }
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
- }
1005
+ };
1006
+ }
1007
+ // Create a dedicated interface for SessionManagementService
1008
+ getSessionManagementServiceInterface() {
1009
+ const self2 = this;
1010
+ return {
1011
+ displayModalError: this.displayModalError.bind(this),
1012
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
1013
+ initializeWorker: this.initializeWorker.bind(this),
1014
+ isPortal: this.isPortal.bind(this),
1015
+ getPartner: this.getPartner.bind(this),
1016
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
1017
+ platformUtils: this.platformUtils,
1018
+ ctx: this.ctx,
1019
+ get loginEncryptionKeyPair() {
1020
+ return self2.loginEncryptionKeyPair;
1021
+ },
1022
+ get partner() {
1023
+ return self2.partner;
1024
+ },
1025
+ get isWorkerInitialized() {
1026
+ return self2.isWorkerInitialized;
1027
+ },
1028
+ get isReady() {
1029
+ return self2.isReady;
1030
+ },
1031
+ isNoWalletConfig: this.isNoWalletConfig,
1032
+ get isSwitchingWallets() {
1033
+ return self2.isSwitchingWallets;
1037
1034
  }
1038
- if (session.currentWalletIds && !(0, import_utils2.currentWalletIdsEq)(session.currentWalletIds, this.currentWalletIds)) {
1039
- yield this.setCurrentWalletIds(session.currentWalletIds);
1035
+ };
1036
+ }
1037
+ getStateMachineInterface() {
1038
+ const self2 = this;
1039
+ return {
1040
+ setup: this.setup.bind(this),
1041
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
1042
+ isPortal: this.isPortal.bind(this),
1043
+ setupAfterLogin: this.setupAfterLogin.bind(this),
1044
+ devLog: this.devLog.bind(this),
1045
+ authService: __privateGet(this, _authService),
1046
+ walletService: __privateGet(this, _walletService),
1047
+ pregenWalletService: __privateGet(this, _pregenWalletService),
1048
+ pollingService: __privateGet(this, _pollingService),
1049
+ externalWalletService: __privateGet(this, _externalWalletService),
1050
+ sessionManagementService: __privateGet(this, _sessionManagementService),
1051
+ portalUrlService: __privateGet(this, _portalUrlService),
1052
+ get isNoWalletConfig() {
1053
+ return self2.isNoWalletConfig;
1040
1054
  }
1041
- return session;
1055
+ };
1056
+ }
1057
+ // Create a dedicated interface for ExternalWalletService
1058
+ getExternalWalletServiceInterface() {
1059
+ return {
1060
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
1061
+ localStorageSetItem: this.localStorageSetItem.bind(this),
1062
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this)
1063
+ };
1064
+ }
1065
+ // Create a dedicated interface for PollingService
1066
+ getPollingServiceInterface() {
1067
+ const self2 = this;
1068
+ return {
1069
+ isPortal: this.isPortal.bind(this),
1070
+ devLog: this.devLog.bind(this),
1071
+ get popupWindow() {
1072
+ return self2.popupWindow;
1073
+ },
1074
+ set popupWindow(w) {
1075
+ self2.popupWindow = w;
1076
+ },
1077
+ platformUtils: this.platformUtils,
1078
+ ctx: this.ctx
1079
+ };
1080
+ }
1081
+ touchSession(regenerate = false) {
1082
+ return __async(this, null, function* () {
1083
+ return __privateGet(this, _sessionManagementService).touchSession(regenerate);
1042
1084
  });
1043
1085
  }
1044
1086
  getVerificationEmailProps() {
@@ -1071,7 +1113,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1071
1113
  init() {
1072
1114
  return __async(this, null, function* () {
1073
1115
  var _a, _b;
1074
- this.userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1116
+ __privateGet(this, _authService).userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1075
1117
  const storageAuthInfo = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_AUTH_INFO)) || void 0;
1076
1118
  const stringExternalWallets = yield this.localStorageGetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS);
1077
1119
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
@@ -1089,7 +1131,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1089
1131
  };
1090
1132
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
1091
1133
  }
1092
- __privateSet(this, _authInfo, authInfo);
1134
+ __privateGet(this, _authService).authInfo = authInfo;
1093
1135
  const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_WALLETS);
1094
1136
  const _wallets = JSON.parse(stringWallets || "{}");
1095
1137
  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 +1155,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1113
1155
  }, {}) : fromJson;
1114
1156
  })();
1115
1157
  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) {
1158
+ __privateGet(this, _sessionManagementService).sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1159
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1118
1160
  this.findWalletId(void 0, { forbidPregen: true });
1119
1161
  }
1120
1162
  const loginEncryptionKey = yield this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -1131,12 +1173,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1131
1173
  }
1132
1174
  setAuth(_0) {
1133
1175
  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);
1176
+ return yield __privateGet(this, _authService).setAuth(auth, { extras, userId });
1140
1177
  });
1141
1178
  }
1142
1179
  /**
@@ -1148,40 +1185,11 @@ Need help? Visit: https://docs.getpara.com or contact support
1148
1185
  this.setModalError(error);
1149
1186
  }
1150
1187
  }
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
1188
  assertUserId({ allowGuestMode = false } = {}) {
1172
- if (!this.userId || !allowGuestMode && this.isGuestMode) {
1173
- throw new Error("no userId is set");
1174
- }
1175
- return this.userId;
1189
+ return __privateGet(this, _authService).assertUserId({ allowGuestMode });
1176
1190
  }
1177
1191
  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);
1192
+ return __privateGet(this, _authService).assertIsAuthSet(allowed);
1185
1193
  }
1186
1194
  /**
1187
1195
  * Sets the email associated with the `ParaCore` instance.
@@ -1189,7 +1197,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1189
1197
  */
1190
1198
  setEmail(email) {
1191
1199
  return __async(this, null, function* () {
1192
- yield this.setAuth({ email });
1200
+ yield __privateGet(this, _authService).setAuth({ email });
1193
1201
  });
1194
1202
  }
1195
1203
  /**
@@ -1198,7 +1206,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1198
1206
  */
1199
1207
  setTelegramUserId(telegramUserId) {
1200
1208
  return __async(this, null, function* () {
1201
- yield this.setAuth({ telegramUserId });
1209
+ yield __privateGet(this, _authService).setAuth({ telegramUserId });
1202
1210
  });
1203
1211
  }
1204
1212
  /**
@@ -1208,7 +1216,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1208
1216
  */
1209
1217
  setPhoneNumber(phone, countryCode) {
1210
1218
  return __async(this, null, function* () {
1211
- yield this.setAuth({ phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) });
1219
+ yield __privateGet(this, _authService).setAuth({ phone: (0, import_utils2.formatPhoneNumber)(phone, countryCode) });
1212
1220
  });
1213
1221
  }
1214
1222
  /**
@@ -1217,7 +1225,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1217
1225
  */
1218
1226
  setFarcasterUsername(farcasterUsername) {
1219
1227
  return __async(this, null, function* () {
1220
- yield this.setAuth({ farcasterUsername });
1228
+ yield __privateGet(this, _authService).setAuth({ farcasterUsername });
1221
1229
  });
1222
1230
  }
1223
1231
  /**
@@ -1227,75 +1235,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1227
1235
  */
1228
1236
  setExternalWallet(externalWallet) {
1229
1237
  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);
1238
+ return yield __privateGet(this, _externalWalletService).setExternalWallet({ externalWallet });
1265
1239
  });
1266
1240
  }
1267
1241
  addExternalWallets(externalWallets) {
1268
1242
  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);
1243
+ return yield __privateGet(this, _externalWalletService).addExternalWallets({ externalWallets });
1299
1244
  });
1300
1245
  }
1301
1246
  /**
@@ -1304,8 +1249,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1304
1249
  */
1305
1250
  setUserId(userId) {
1306
1251
  return __async(this, null, function* () {
1307
- this.userId = userId;
1308
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_USER_ID, userId);
1252
+ return yield __privateGet(this, _authService).setUserId(userId);
1309
1253
  });
1310
1254
  }
1311
1255
  /**
@@ -1314,12 +1258,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1314
1258
  */
1315
1259
  setWallets(wallets) {
1316
1260
  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));
1261
+ return yield __privateGet(this, _walletService).setWallets(wallets);
1323
1262
  });
1324
1263
  }
1325
1264
  /**
@@ -1328,12 +1267,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1328
1267
  */
1329
1268
  setExternalWallets(externalWallets) {
1330
1269
  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));
1270
+ return yield __privateGet(this, _externalWalletService).setExternalWallets({ externalWallets });
1337
1271
  });
1338
1272
  }
1339
1273
  /**
@@ -1360,51 +1294,36 @@ Need help? Visit: https://docs.getpara.com or contact support
1360
1294
  * @returns - userId associated with the `ParaCore` instance.
1361
1295
  */
1362
1296
  getUserId() {
1363
- return this.userId;
1297
+ var _a;
1298
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
1364
1299
  }
1365
1300
  getAuthInfo() {
1366
- return this.authInfo;
1301
+ var _a;
1302
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
1367
1303
  }
1368
1304
  /**
1369
1305
  * Gets the email associated with the `ParaCore` instance.
1370
1306
  * @returns - email associated with the `ParaCore` instance.
1371
1307
  */
1372
1308
  getEmail() {
1373
- return this.email;
1309
+ var _a;
1310
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
1374
1311
  }
1375
1312
  /**
1376
1313
  * Gets the formatted phone number associated with the `ParaCore` instance.
1377
1314
  * @returns - formatted phone number associated with the `ParaCore` instance.
1378
1315
  */
1379
1316
  getPhoneNumber() {
1380
- return this.phone;
1317
+ var _a;
1318
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
1381
1319
  }
1382
1320
  /**
1383
1321
  * Gets the farcaster username associated with the `ParaCore` instance.
1384
1322
  * @returns - farcaster username associated with the `ParaCore` instance.
1385
1323
  */
1386
1324
  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
- });
1325
+ var _a;
1326
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
1408
1327
  }
1409
1328
  /**
1410
1329
  * Fetches the most recent OAuth account metadata for the signed-in user.
@@ -1422,29 +1341,6 @@ Need help? Visit: https://docs.getpara.com or contact support
1422
1341
  return accountMetadata;
1423
1342
  });
1424
1343
  }
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
1344
  /**
1449
1345
  * Retrieves a wallet with the given address, if present.
1450
1346
  * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
@@ -1452,78 +1348,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1452
1348
  * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1453
1349
  * @returns {string} the wallet ID originally passed, or the one found.
1454
1350
  */
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
- }
1351
+ findWalletByAddress(...params) {
1352
+ return __privateGet(this, _walletService).findWalletByAddress(...params);
1353
+ }
1354
+ findWallet(...params) {
1355
+ const [walletId, walletType, filters = {}] = params;
1356
+ return __privateGet(this, _walletService).findWallet(walletId, walletType, filters);
1498
1357
  }
1499
1358
  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
- ];
1359
+ return __privateGet(this, _walletService).availableWallets;
1527
1360
  }
1528
1361
  /**
1529
1362
  * Retrieves all usable wallets with the provided type (`'EVM' | 'COSMOS' | 'SOLANA'`)
@@ -1531,52 +1364,16 @@ Need help? Visit: https://docs.getpara.com or contact support
1531
1364
  * @returns {Wallet[]} an array of matching wallets.
1532
1365
  */
1533
1366
  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);
1538
- }
1539
- assertIsValidWalletType(type, walletTypes) {
1540
- 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
- });
1367
+ return __privateGet(this, _walletService).getWalletsByType(type);
1568
1368
  }
1569
- getPartnerURL() {
1369
+ getPartner(partnerId) {
1570
1370
  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;
1371
+ if (this.isPartnerOptional && !partnerId) {
1372
+ return void 0;
1579
1373
  }
1374
+ const res = yield this.ctx.client.getPartner(partnerId);
1375
+ this.partner = res.data.partner;
1376
+ return this.partner;
1580
1377
  });
1581
1378
  }
1582
1379
  /**
@@ -1586,7 +1383,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1586
1383
  */
1587
1384
  getPortalURL(isLegacy) {
1588
1385
  return __async(this, null, function* () {
1589
- return this.ctx.portalUrlOverride || (yield this.getPartnerURL()) || (0, import_utils2.getPortalBaseURL)(this.ctx, false, false, isLegacy);
1386
+ return yield __privateGet(this, _portalUrlService).getPortalURL(isLegacy);
1590
1387
  });
1591
1388
  }
1592
1389
  /**
@@ -1619,33 +1416,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1619
1416
  */
1620
1417
  fetchWallets() {
1621
1418
  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
- );
1419
+ return yield __privateGet(this, _walletService).fetchWallets();
1626
1420
  });
1627
1421
  }
1628
1422
  populateWalletAddresses() {
1629
1423
  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);
1424
+ return yield __privateGet(this, _walletService).populateWalletAddresses();
1649
1425
  });
1650
1426
  }
1651
1427
  /**
@@ -1655,86 +1431,34 @@ Need help? Visit: https://docs.getpara.com or contact support
1655
1431
  * @param {TWalletType} opts.type type of external wallet to use for identification.
1656
1432
  * @param {string} opts.provider the name of the provider for the external wallet.
1657
1433
  */
1658
- loginExternalWallet(_a) {
1434
+ loginExternalWallet(params) {
1659
1435
  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);
1436
+ return yield __privateGet(this, _authService).loginExternalWallet(params);
1437
+ });
1438
+ }
1439
+ /**
1440
+ * Connects to an external wallet & logs in to Para (if applicable).
1441
+ * @param {Object} params the params object
1442
+ * @param {Function} params.connect the function called to connect to the external wallet.
1443
+ */
1444
+ connectExternalWallet(params) {
1445
+ return __async(this, null, function* () {
1446
+ return yield __privateGet(this, _authService).connectExternalWallet(params);
1705
1447
  });
1706
1448
  }
1707
1449
  verifyExternalWallet(params) {
1708
1450
  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;
1451
+ return yield __privateGet(this, _authService).verifyExternalWallet(params);
1452
+ });
1453
+ }
1454
+ retryVerifyExternalWallet() {
1455
+ return __async(this, null, function* () {
1456
+ return yield __privateGet(this, _authService).retryVerifyExternalWallet();
1457
+ });
1458
+ }
1459
+ signExternalWalletVerification(params) {
1460
+ return __async(this, null, function* () {
1461
+ return yield __privateGet(this, _authService).signExternalWalletVerification(params);
1738
1462
  });
1739
1463
  }
1740
1464
  verifyExternalWalletLink(opts) {
@@ -1757,13 +1481,13 @@ Need help? Visit: https://docs.getpara.com or contact support
1757
1481
  * @param authResponse - the response JSON object received from the Telegram widget.
1758
1482
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1759
1483
  */
1760
- verifyTelegramProcess(_c) {
1484
+ verifyTelegramProcess(_a) {
1761
1485
  return __async(this, null, function* () {
1762
- var _d = _c, {
1486
+ var _b = _a, {
1763
1487
  serverAuthState: optsServerAuthState,
1764
1488
  telegramAuthResponse,
1765
1489
  isLinkAccount
1766
- } = _d, urlOptions = __objRest(_d, [
1490
+ } = _b, urlOptions = __objRest(_b, [
1767
1491
  "serverAuthState",
1768
1492
  "telegramAuthResponse",
1769
1493
  "isLinkAccount"
@@ -1771,12 +1495,10 @@ Need help? Visit: https://docs.getpara.com or contact support
1771
1495
  try {
1772
1496
  switch (isLinkAccount) {
1773
1497
  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 }));
1498
+ return yield __privateGet(this, _authService).verifyTelegram(__spreadValues({
1499
+ serverAuthState: optsServerAuthState,
1500
+ telegramAuthResponse
1501
+ }, urlOptions));
1780
1502
  }
1781
1503
  case true: {
1782
1504
  if (!telegramAuthResponse) {
@@ -1796,9 +1518,9 @@ Need help? Visit: https://docs.getpara.com or contact support
1796
1518
  }
1797
1519
  });
1798
1520
  }
1799
- verifyTelegram(opts) {
1521
+ verifyTelegram(params) {
1800
1522
  return __async(this, null, function* () {
1801
- return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1523
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
1802
1524
  });
1803
1525
  }
1804
1526
  verifyTelegramLink(opts) {
@@ -1850,35 +1572,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1850
1572
  * Resend a verification email for the current user.
1851
1573
  */
1852
1574
  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()));
1575
+ return __async(this, arguments, function* ({ type: reason = "SIGNUP" }) {
1576
+ return yield __privateGet(this, _authService).resendVerificationCode({ type: reason });
1882
1577
  });
1883
1578
  }
1884
1579
  /**
@@ -1887,18 +1582,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1887
1582
  */
1888
1583
  isSessionActive() {
1889
1584
  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;
1585
+ return yield __privateGet(this, _sessionManagementService).isSessionActive();
1902
1586
  });
1903
1587
  }
1904
1588
  /**
@@ -1907,58 +1591,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1907
1591
  **/
1908
1592
  isFullyLoggedIn() {
1909
1593
  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;
1594
+ return yield __privateGet(this, _sessionManagementService).isFullyLoggedIn();
1955
1595
  });
1956
1596
  }
1957
1597
  get isGuestMode() {
1958
- return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1598
+ var _a;
1599
+ return ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 0 && Object.values(this.wallets).every(
1959
1600
  ({ userId, partnerId }) => {
1960
- var _a;
1961
- return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1601
+ var _a2;
1602
+ return partnerId === ((_a2 = this.partner) == null ? void 0 : _a2.id) && (!userId || userId !== this.userId);
1962
1603
  }
1963
1604
  );
1964
1605
  }
@@ -1988,30 +1629,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1988
1629
  */
1989
1630
  supportedUserAuthMethods() {
1990
1631
  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;
1632
+ return yield __privateGet(this, _authService).supportedUserAuthMethods();
2015
1633
  });
2016
1634
  }
2017
1635
  /**
@@ -2028,94 +1646,14 @@ Need help? Visit: https://docs.getpara.com or contact support
2028
1646
  /**
2029
1647
  * Waits for the session to be active.
2030
1648
  **/
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
- });
1649
+ waitForSignup(params) {
1650
+ return __async(this, null, function* () {
1651
+ return yield __privateGet(this, _authService).waitForSignup(params);
2064
1652
  });
2065
1653
  }
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;
1654
+ waitForWalletCreation(params) {
1655
+ return __async(this, null, function* () {
1656
+ return yield __privateGet(this, _authService).waitForWalletCreation(params);
2119
1657
  });
2120
1658
  }
2121
1659
  /**
@@ -2135,35 +1673,34 @@ Need help? Visit: https://docs.getpara.com or contact support
2135
1673
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2136
1674
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2137
1675
  */
2138
- verifyFarcasterProcess(_e) {
1676
+ verifyFarcasterProcess(_c) {
2139
1677
  return __async(this, null, function* () {
2140
- var _f = _e, {
1678
+ var _d = _c, {
2141
1679
  isCanceled = () => false,
2142
1680
  onConnectUri,
2143
1681
  onCancel,
2144
- onPoll,
2145
1682
  isLinkAccount,
2146
1683
  serverAuthState: optsServerAuthState
2147
- } = _f, urlOptions = __objRest(_f, [
1684
+ } = _d, urlOptions = __objRest(_d, [
2148
1685
  "isCanceled",
2149
1686
  "onConnectUri",
2150
1687
  "onCancel",
2151
- "onPoll",
2152
1688
  "isLinkAccount",
2153
1689
  "serverAuthState"
2154
1690
  ]);
2155
- if (optsServerAuthState) {
2156
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
2157
- return authState;
1691
+ if (onConnectUri) {
1692
+ const connectUri = yield this.getFarcasterConnectUri();
1693
+ onConnectUri(connectUri);
1694
+ }
1695
+ if (!isLinkAccount) {
1696
+ return yield __privateGet(this, _authService).verifyFarcaster(__spreadValues({
1697
+ serverAuthState: optsServerAuthState
1698
+ }, urlOptions));
2158
1699
  }
2159
1700
  let accountLinkInProgress;
2160
1701
  if (isLinkAccount) {
2161
1702
  accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
2162
1703
  }
2163
- if (onConnectUri) {
2164
- const connectUri = yield this.getFarcasterConnectUri();
2165
- onConnectUri(connectUri);
2166
- }
2167
1704
  return new Promise((resolve, reject) => {
2168
1705
  (() => __async(this, null, function* () {
2169
1706
  const startedAt = Date.now();
@@ -2174,27 +1711,13 @@ Need help? Visit: https://docs.getpara.com or contact support
2174
1711
  return reject("CANCELED");
2175
1712
  }
2176
1713
  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
- }
1714
+ const result = yield this.verifyLink({
1715
+ accountLinkInProgress
1716
+ });
1717
+ if ("isConflict" in result) {
1718
+ throw new Error(import_types.AccountLinkError.Conflict);
2196
1719
  }
2197
- onPoll == null ? void 0 : onPoll();
1720
+ return resolve(result);
2198
1721
  } catch (e) {
2199
1722
  if (!isLinkAccount || e.message === import_types.AccountLinkError.Conflict) {
2200
1723
  return reject(e.message);
@@ -2205,9 +1728,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2205
1728
  });
2206
1729
  });
2207
1730
  }
2208
- verifyFarcaster(opts) {
1731
+ verifyFarcaster(params) {
2209
1732
  return __async(this, null, function* () {
2210
- return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1733
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2211
1734
  });
2212
1735
  }
2213
1736
  verifyFarcasterLink(opts) {
@@ -2215,11 +1738,17 @@ Need help? Visit: https://docs.getpara.com or contact support
2215
1738
  return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2216
1739
  });
2217
1740
  }
2218
- getOAuthUrl(opts) {
1741
+ /**
1742
+ * Generates a URL for the user to log in with OAuth using a desire method.
1743
+ *
1744
+ * @param {Object} opts the options object
1745
+ * @param {TOAuthMethod} opts.method the third-party service to use for OAuth.
1746
+ * @param {string} [opts.appScheme] the app scheme to redirect to after the OAuth flow. This is for mobile only.
1747
+ * @returns {string} the URL for the user to log in with OAuth.
1748
+ */
1749
+ getOAuthUrl(params) {
2219
1750
  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 }));
1751
+ return yield __privateGet(this, _portalUrlService).getOAuthUrl(params);
2223
1752
  });
2224
1753
  }
2225
1754
  /**
@@ -2230,27 +1759,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2230
1759
  * @param {Window} [opts.popupWindow] the popup window being used for login.
2231
1760
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2232
1761
  */
2233
- verifyOAuthProcess(_g) {
1762
+ verifyOAuthProcess(params) {
2234
1763
  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
- ]);
1764
+ if (!params.isLinkAccount) {
1765
+ return yield __privateGet(this, _authService).verifyOAuthProcess(params);
1766
+ }
1767
+ const { method, appScheme, isCanceled = () => false, onCancel, onPoll, onOAuthUrl, onOAuthPopup } = params;
2254
1768
  if (onOAuthPopup) {
2255
1769
  try {
2256
1770
  this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: import_types.PopupType.OAUTH });
@@ -2260,13 +1774,14 @@ Need help? Visit: https://docs.getpara.com or contact support
2260
1774
  }
2261
1775
  let sessionLookupId, accountLinkInProgress;
2262
1776
  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 });
1777
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
1778
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
1779
+ const oAuthUrl = yield __privateGet(this, _portalUrlService).getOAuthUrl({
1780
+ method,
1781
+ appScheme,
1782
+ sessionLookupId,
1783
+ accountLinkInProgress
1784
+ });
2270
1785
  switch (true) {
2271
1786
  case !!onOAuthUrl: {
2272
1787
  onOAuthUrl(oAuthUrl);
@@ -2291,24 +1806,10 @@ Need help? Visit: https://docs.getpara.com or contact support
2291
1806
  return reject(import_types.AccountLinkError.Canceled);
2292
1807
  }
2293
1808
  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();
1809
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
1810
+ return resolve(accounts);
2310
1811
  } catch (err) {
2311
- if (isLinkAccount && err.message === import_types.AccountLinkError.Conflict) {
1812
+ if (err.message === import_types.AccountLinkError.Conflict) {
2312
1813
  return reject(err.message);
2313
1814
  }
2314
1815
  onPoll == null ? void 0 : onPoll();
@@ -2318,9 +1819,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2318
1819
  });
2319
1820
  });
2320
1821
  }
2321
- verifyOAuth(opts) {
1822
+ verifyOAuth(params) {
2322
1823
  return __async(this, null, function* () {
2323
- return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1824
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2324
1825
  });
2325
1826
  }
2326
1827
  verifyOAuthLink(opts) {
@@ -2336,9 +1837,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2336
1837
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2337
1838
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2338
1839
  **/
2339
- waitForLogin(args) {
1840
+ waitForLogin(params) {
2340
1841
  return __async(this, null, function* () {
2341
- return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
1842
+ return yield __privateGet(this, _authService).waitForLogin(params);
2342
1843
  });
2343
1844
  }
2344
1845
  waitForWalletSwitching(args) {
@@ -2370,32 +1871,20 @@ Need help? Visit: https://docs.getpara.com or contact support
2370
1871
  * @returns a URL for the user to reauthenticate.
2371
1872
  **/
2372
1873
  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;
1874
+ return __async(this, arguments, function* (params = {}) {
1875
+ return yield __privateGet(this, _sessionManagementService).refreshSession(params);
2387
1876
  });
2388
1877
  }
2389
1878
  /**
2390
1879
  * Call this method after login to ensure that the user ID is set
2391
1880
  * internally.
2392
1881
  **/
2393
- userSetupAfterLogin() {
1882
+ userSetupAfterLogin(existingSession) {
2394
1883
  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, {
1884
+ const session = existingSession != null ? existingSession : yield this.touchSession();
1885
+ yield __privateGet(this, _authService).setUserId(session.userId);
1886
+ if (session.currentWalletIds && session.currentWalletIds !== __privateGet(this, _walletService).currentWalletIds)
1887
+ yield __privateGet(this, _walletService).setCurrentWalletIds(session.currentWalletIds, {
2399
1888
  sessionLookupId: this.isPortal() ? session.sessionLookupId : void 0
2400
1889
  });
2401
1890
  return session;
@@ -2408,9 +1897,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2408
1897
  * @returns - transmission keyshares.
2409
1898
  **/
2410
1899
  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;
1900
+ return __async(this, arguments, function* ({
1901
+ isForNewDevice = false,
1902
+ sessionLookupId: existingSessionLookupId
1903
+ } = {}) {
1904
+ const baseSessionLookupId = existingSessionLookupId != null ? existingSessionLookupId : (yield this.touchSession()).sessionLookupId;
1905
+ const sessionLookupId = isForNewDevice ? `${baseSessionLookupId}-new-device` : baseSessionLookupId;
2414
1906
  return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2415
1907
  });
2416
1908
  }
@@ -2424,111 +1916,34 @@ Need help? Visit: https://docs.getpara.com or contact support
2424
1916
  return __async(this, arguments, function* ({
2425
1917
  temporaryShares,
2426
1918
  skipSessionRefresh = false
2427
- } = {}) {
2428
- if (!temporaryShares) {
2429
- temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2430
- }
2431
- 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
- }
1919
+ } = {}) {
1920
+ if (!temporaryShares) {
1921
+ temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2500
1922
  }
2501
- throw new Error("timed out waiting for wallet address");
1923
+ temporaryShares.forEach((share) => {
1924
+ const signer = (0, import_utils.decryptWithPrivateKey)(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
1925
+ this.wallets[share.walletId] = {
1926
+ id: share.walletId,
1927
+ signer
1928
+ };
1929
+ });
1930
+ yield this.deleteLoginEncryptionKeyPair();
1931
+ yield __privateGet(this, _walletService).populateWalletAddresses();
1932
+ yield this.touchSession(!skipSessionRefresh);
2502
1933
  });
2503
1934
  }
2504
1935
  /**
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.
1936
+ * Distributes a new wallet recovery share.
1937
+ * @param {Object} opts the options object.
1938
+ * @param {string} opts.walletId the wallet to distribute the recovery share for.
1939
+ * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
1940
+ * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
1941
+ * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
1942
+ * @returns {string} the recovery share.
2511
1943
  **/
2512
- waitForPregenWalletAddress(walletId) {
1944
+ distributeNewWalletShare(params) {
2513
1945
  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");
1946
+ return yield __privateGet(this, _walletService).distributeNewWalletShare(params);
2532
1947
  });
2533
1948
  }
2534
1949
  /**
@@ -2543,24 +1958,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2543
1958
  * @returns {Object} the wallets created, their ids, and the recovery secret.
2544
1959
  **/
2545
1960
  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 };
1961
+ return __async(this, arguments, function* (params = {}) {
1962
+ return yield __privateGet(this, _walletService).createWalletPerType(params);
2564
1963
  });
2565
1964
  }
2566
1965
  /**
@@ -2575,38 +1974,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2575
1974
  * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2576
1975
  * @returns {Object} the new user share and recovery secret.
2577
1976
  **/
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 };
1977
+ refreshShare(params) {
1978
+ return __async(this, null, function* () {
1979
+ return yield __privateGet(this, _walletService).refreshShare(params);
2610
1980
  });
2611
1981
  }
2612
1982
  /**
@@ -2617,80 +1987,22 @@ Need help? Visit: https://docs.getpara.com or contact support
2617
1987
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2618
1988
  **/
2619
1989
  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];
1990
+ return __async(this, arguments, function* (params = {}) {
1991
+ return yield __privateGet(this, _walletService).createWallet(params);
2689
1992
  });
2690
1993
  }
2691
- createPregenWallet(opts) {
1994
+ /**
1995
+ * Creates a new pregenerated wallet.
1996
+ *
1997
+ * @param {Object} opts the options object.
1998
+ * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
1999
+ * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
2000
+ * @param {TWalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
2001
+ * @returns {Wallet} the created wallet.
2002
+ **/
2003
+ createPregenWallet(params) {
2692
2004
  return __async(this, null, function* () {
2693
- return yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, opts);
2005
+ return yield __privateGet(this, _pregenWalletService).createPregenWallet(params);
2694
2006
  });
2695
2007
  }
2696
2008
  /**
@@ -2703,17 +2015,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2703
2015
  * @param {TWalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
2704
2016
  * @returns {Wallet[]} an array containing the created wallets.
2705
2017
  **/
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;
2018
+ createPregenWalletPerType(params) {
2019
+ return __async(this, null, function* () {
2020
+ return yield __privateGet(this, _pregenWalletService).createPregenWalletPerType(params);
2717
2021
  });
2718
2022
  }
2719
2023
  /**
@@ -2724,70 +2028,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2724
2028
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2725
2029
  **/
2726
2030
  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;
2031
+ return __async(this, arguments, function* (params = {}) {
2032
+ return yield __privateGet(this, _pregenWalletService).claimPregenWallets(params);
2791
2033
  });
2792
2034
  }
2793
2035
  /**
@@ -2797,24 +2039,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2797
2039
  * @param {string} opts.newPregenIdentifier the new identtifier
2798
2040
  * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
2799
2041
  **/
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
- }
2042
+ updatePregenWalletIdentifier(params) {
2043
+ return __async(this, null, function* () {
2044
+ return yield __privateGet(this, _pregenWalletService).updatePregenWalletIdentifier(params);
2818
2045
  });
2819
2046
  }
2820
2047
  /**
@@ -2824,18 +2051,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2824
2051
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
2825
2052
  * @returns {boolean} whether the pregen wallet exists
2826
2053
  **/
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;
2054
+ hasPregenWallet(params) {
2055
+ return __async(this, null, function* () {
2056
+ return yield __privateGet(this, _pregenWalletService).hasPregenWallet(params);
2839
2057
  });
2840
2058
  }
2841
2059
  /**
@@ -2846,64 +2064,21 @@ Need help? Visit: https://docs.getpara.com or contact support
2846
2064
  * @returns {Promise<WalletEntity[]>} the array of found wallets
2847
2065
  **/
2848
2066
  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)));
2067
+ return __async(this, arguments, function* (params = {}) {
2068
+ return yield __privateGet(this, _pregenWalletService).getPregenWallets(params);
2857
2069
  });
2858
2070
  }
2859
2071
  createGuestWallets() {
2860
2072
  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
- }
2073
+ return yield __privateGet(this, _pregenWalletService).createGuestWallets();
2891
2074
  });
2892
2075
  }
2893
- encodeWalletBase64(wallet) {
2894
- const walletJson = JSON.stringify(wallet);
2895
- const base64Wallet = Buffer.from(walletJson).toString("base64");
2896
- return base64Wallet;
2897
- }
2898
2076
  /**
2899
2077
  * Encodes the current wallets encoded in Base 64.
2900
2078
  * @returns {string} the encoded wallet string
2901
2079
  **/
2902
2080
  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("-");
2081
+ return __privateGet(this, _walletService).getUserShare();
2907
2082
  }
2908
2083
  /**
2909
2084
  * Sets the current wallets from a Base 64 string.
@@ -2911,16 +2086,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2911
2086
  **/
2912
2087
  setUserShare(base64Wallets) {
2913
2088
  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
- }
2089
+ return yield __privateGet(this, _walletService).setUserShare(base64Wallets);
2924
2090
  });
2925
2091
  }
2926
2092
  getTransactionReviewUrl(transactionId, timeoutMs) {
@@ -2944,6 +2110,11 @@ Need help? Visit: https://docs.getpara.com or contact support
2944
2110
  });
2945
2111
  });
2946
2112
  }
2113
+ getWalletBalance(params) {
2114
+ return __async(this, null, function* () {
2115
+ return yield __privateGet(this, _walletService).getWalletBalance(params);
2116
+ });
2117
+ }
2947
2118
  /**
2948
2119
  * Signs a message using one of the current wallets.
2949
2120
  *
@@ -2966,7 +2137,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2966
2137
  onPoll
2967
2138
  }) {
2968
2139
  var _a;
2969
- this.assertIsValidWalletId(walletId);
2140
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
2970
2141
  const wallet = this.wallets[walletId];
2971
2142
  let signerId = this.userId;
2972
2143
  if (wallet.partnerId && !wallet.userId) {
@@ -3071,7 +2242,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3071
2242
  onPoll
3072
2243
  }) {
3073
2244
  var _a;
3074
- this.assertIsValidWalletId(walletId);
2245
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
3075
2246
  const wallet = this.wallets[walletId];
3076
2247
  let signerId = this.userId;
3077
2248
  if (wallet.partnerId && !wallet.userId) {
@@ -3177,12 +2348,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3177
2348
  **/
3178
2349
  keepSessionAlive() {
3179
2350
  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
- }
2351
+ return yield __privateGet(this, _sessionManagementService).keepSessionAlive();
3186
2352
  });
3187
2353
  }
3188
2354
  /**
@@ -3192,10 +2358,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3192
2358
  */
3193
2359
  exportSession({ excludeSigners = false } = {}) {
3194
2360
  const sessionInfo = {
3195
- authInfo: __privateGet(this, _authInfo),
2361
+ authInfo: __privateGet(this, _authService).authInfo,
3196
2362
  userId: this.userId,
3197
2363
  wallets: structuredClone(this.wallets),
3198
- currentWalletIds: this.currentWalletIds,
2364
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
3199
2365
  sessionCookie: this.retrieveSessionCookie(),
3200
2366
  externalWallets: this.externalWallets
3201
2367
  };
@@ -3213,10 +2379,25 @@ Need help? Visit: https://docs.getpara.com or contact support
3213
2379
  importSession(serializedInstanceBase64) {
3214
2380
  return __async(this, null, function* () {
3215
2381
  var _a, _b;
2382
+ yield (0, import_stateListener.waitForAuthStateChange)({
2383
+ stateManager: __privateGet(this, _stateManager),
2384
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2385
+ rejectPhases: [
2386
+ {
2387
+ phase: "authenticated",
2388
+ onPhase: () => new Error("Cannot import a session into a Para instance that already has an active session.")
2389
+ },
2390
+ {
2391
+ phase: "guest_mode",
2392
+ onPhase: () => new Error("Cannot import a session into a Para instance that is in guest mode.")
2393
+ }
2394
+ ],
2395
+ waitForCoreAuthenticated: false
2396
+ });
3216
2397
  const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3217
2398
  const sessionInfo = (0, import_utils2.jsonParse)(serializedInstance);
3218
2399
  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);
2400
+ yield __privateGet(this, _authService).setAuthInfo(authInfo);
3220
2401
  yield this.setUserId(sessionInfo.userId);
3221
2402
  yield this.setWallets(sessionInfo.wallets);
3222
2403
  yield this.setExternalWallets(sessionInfo.externalWallets || {});
@@ -3237,7 +2418,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3237
2418
  }
3238
2419
  yield this.setCurrentWalletIds(currentWalletIds);
3239
2420
  }
2421
+ __privateGet(this, _sessionManagementService).isImportedSession = true;
2422
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION, JSON.stringify(true));
3240
2423
  this.persistSessionCookie(sessionInfo.sessionCookie);
2424
+ __privateGet(this, _stateManager).send({ type: "SESSION_IMPORTED" });
3241
2425
  });
3242
2426
  }
3243
2427
  /**
@@ -3246,22 +2430,12 @@ Need help? Visit: https://docs.getpara.com or contact support
3246
2430
  **/
3247
2431
  getVerificationToken() {
3248
2432
  return __async(this, null, function* () {
3249
- const { sessionLookupId } = yield this.touchSession();
3250
- return sessionLookupId;
2433
+ return yield __privateGet(this, _sessionManagementService).getVerificationToken();
3251
2434
  });
3252
2435
  }
3253
2436
  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
- }
2437
+ return __async(this, arguments, function* (params = {}) {
2438
+ return yield __privateGet(this, _sessionManagementService).issueJwt(params);
3265
2439
  });
3266
2440
  }
3267
2441
  /**
@@ -3271,30 +2445,39 @@ Need help? Visit: https://docs.getpara.com or contact support
3271
2445
  **/
3272
2446
  logout() {
3273
2447
  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
- }
2448
+ yield __privateMethod(this, _ParaCore_instances, logout_fn).call(this, { clearPregenWallets });
2449
+ __privateGet(this, _pollingService).cancelAllPolling();
2450
+ yield __privateGet(this, _externalWalletService).disconnectAllExternalWallets();
2451
+ try {
2452
+ yield (0, import_stateListener.waitForAuthStateChange)({
2453
+ stateManager: __privateGet(this, _stateManager),
2454
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2455
+ rejectInErrorPhaseOnly: true,
2456
+ timeoutMs: 5e3
3282
2457
  });
3283
- yield this.setWallets(this.wallets);
3284
- } else {
3285
- this.wallets = {};
2458
+ } catch (e) {
3286
2459
  }
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);
2460
+ });
2461
+ }
2462
+ /**
2463
+ * Cancels any in-progress authentication flow, returning the auth state machine
2464
+ * to its initial unauthenticated state. Does not affect existing sessions or stored data.
2465
+ *
2466
+ * Resolves once the auth state machine has settled back to `unauthenticated`.
2467
+ */
2468
+ cancelAuthFlow() {
2469
+ return __async(this, null, function* () {
2470
+ if (this.authPhase === "unauthenticated" || this.authPhase === "error") {
2471
+ return;
3297
2472
  }
2473
+ const settled = (0, import_stateListener.waitForAuthStateChange)({
2474
+ stateManager: __privateGet(this, _stateManager),
2475
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => true }],
2476
+ rejectInErrorPhaseOnly: true,
2477
+ timeoutMs: 5e3
2478
+ });
2479
+ __privateGet(this, _stateManager).send({ type: "CANCEL" });
2480
+ yield settled;
3298
2481
  });
3299
2482
  }
3300
2483
  get toStringAdditions() {
@@ -3327,16 +2510,16 @@ Need help? Visit: https://docs.getpara.com or contact support
3327
2510
  partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3328
2511
  supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3329
2512
  cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
3330
- authInfo: __privateGet(this, _authInfo),
2513
+ authInfo: __privateGet(this, _authService).authInfo,
3331
2514
  isGuestMode: this.isGuestMode,
3332
2515
  userId: this.userId,
3333
2516
  pregenIds: this.pregenIds,
3334
- currentWalletIds: this.currentWalletIds,
3335
- guestWalletIds: __privateGet(this, _ParaCore_instances, guestWalletIds_get),
2517
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
2518
+ guestWalletIds: __privateGet(this, _pregenWalletService).guestWalletIds,
3336
2519
  wallets: redactedWallets,
3337
2520
  externalWallets: redactedExternalWallets,
3338
2521
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3339
- isReady: this.isReady
2522
+ isSetup: this.isSetup
3340
2523
  }, this.toStringAdditions), {
3341
2524
  ctx: {
3342
2525
  apiKey: this.ctx.apiKey,
@@ -3352,90 +2535,13 @@ Need help? Visit: https://docs.getpara.com or contact support
3352
2535
  return `Para ${JSON.stringify(obj, null, 2)}`;
3353
2536
  }
3354
2537
  devLog(...s) {
3355
- if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX) {
2538
+ if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX || !!__privateGet(this, _debugLogsEnabled)) {
3356
2539
  console.log(...s);
3357
2540
  }
3358
2541
  }
3359
2542
  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;
2543
+ return __async(this, arguments, function* (params = {}) {
2544
+ return yield __privateGet(this, _authService).getNewCredentialAndUrl(params);
3439
2545
  });
3440
2546
  }
3441
2547
  /**
@@ -3446,92 +2552,34 @@ Need help? Visit: https://docs.getpara.com or contact support
3446
2552
  * @param {Theme} opts.portalTheme the Para Portal theme to apply to the password creation URL, if other than the default theme
3447
2553
  * @returns {SignUpOrLogInResponse} an object in the form of either: `{ stage: 'verify' }` or `{ stage: 'login'; passkeyUrl?: string; passwordUrl?: string; biometricHints?: BiometricLocationHint[] }`
3448
2554
  */
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
- });
2555
+ getLoginUrl(params) {
2556
+ return __async(this, null, function* () {
2557
+ return yield __privateGet(this, _portalUrlService).getLoginUrl(params);
3482
2558
  });
3483
2559
  }
3484
2560
  prepareLogin() {
3485
2561
  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;
2562
+ return __privateGet(this, _authService).prepareLogin();
3492
2563
  });
3493
2564
  }
3494
- signUpOrLogIn(_i) {
2565
+ signUpOrLogIn(params) {
3495
2566
  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));
2567
+ return yield __privateGet(this, _authService).signUpOrLogIn(params);
3516
2568
  });
3517
2569
  }
3518
- verifyNewAccount(_k) {
2570
+ authenticateWithEmailOrPhone(params) {
3519
2571
  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);
2572
+ return yield __privateGet(this, _authService).authenticateWithEmailOrPhone(params);
2573
+ });
2574
+ }
2575
+ authenticateWithOAuth(params) {
2576
+ return __async(this, null, function* () {
2577
+ return yield __privateGet(this, _authService).authenticateWithOAuth(params);
2578
+ });
2579
+ }
2580
+ verifyNewAccount(params) {
2581
+ return __async(this, null, function* () {
2582
+ return yield __privateGet(this, _authService).verifyNewAccount(params);
3535
2583
  });
3536
2584
  }
3537
2585
  getLinkedAccounts() {
@@ -3617,10 +2665,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3617
2665
  });
3618
2666
  }
3619
2667
  verifyLink() {
3620
- return __async(this, arguments, function* (_m = {}) {
3621
- var _n = _m, {
2668
+ return __async(this, arguments, function* (_e = {}) {
2669
+ var _f = _e, {
3622
2670
  accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3623
- } = _n, opts = __objRest(_n, [
2671
+ } = _f, opts = __objRest(_f, [
3624
2672
  "accountLinkInProgress"
3625
2673
  ]);
3626
2674
  try {
@@ -3702,7 +2750,15 @@ Need help? Visit: https://docs.getpara.com or contact support
3702
2750
  });
3703
2751
  }
3704
2752
  };
3705
- _authInfo = new WeakMap();
2753
+ _stateManager = new WeakMap();
2754
+ _authService = new WeakMap();
2755
+ _walletService = new WeakMap();
2756
+ _externalWalletService = new WeakMap();
2757
+ _pregenWalletService = new WeakMap();
2758
+ _pollingService = new WeakMap();
2759
+ _portalUrlService = new WeakMap();
2760
+ _sessionManagementService = new WeakMap();
2761
+ _debugLogsEnabled = new WeakMap();
3706
2762
  _ParaCore_instances = new WeakSet();
3707
2763
  assertPartner_fn = function() {
3708
2764
  return __async(this, null, function* () {
@@ -3716,27 +2772,6 @@ assertPartner_fn = function() {
3716
2772
  return this.partner;
3717
2773
  });
3718
2774
  };
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
2775
  toAuthInfo_fn = function({
3741
2776
  email,
3742
2777
  phone,
@@ -3768,27 +2803,6 @@ toAuthInfo_fn = function({
3768
2803
  }
3769
2804
  return (0, import_user_management_client.extractAuthInfo)(auth);
3770
2805
  };
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
- };
3792
2806
  assertIsLinkingAccount_fn = function(types) {
3793
2807
  if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3794
2808
  throw new Error("no account linking in progress");
@@ -3808,49 +2822,6 @@ assertIsLinkingAccountOrStart_fn = function(type) {
3808
2822
  return yield this.linkAccount({ type });
3809
2823
  });
3810
2824
  };
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
2825
  waitForLoginProcess_fn = function() {
3855
2826
  return __async(this, arguments, function* ({
3856
2827
  isCanceled = () => false,
@@ -3878,7 +2849,7 @@ waitForLoginProcess_fn = function() {
3878
2849
  var _a;
3879
2850
  if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3880
2851
  this.devLog("[waitForLoginProcess] Clearing external wallets");
3881
- this.externalWallets = {};
2852
+ __privateGet(this, _externalWalletService).externalWallets = {};
3882
2853
  }
3883
2854
  let pollCount = 0;
3884
2855
  while (true) {
@@ -3923,7 +2894,7 @@ waitForLoginProcess_fn = function() {
3923
2894
  continue;
3924
2895
  }
3925
2896
  this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3926
- session = yield this.userSetupAfterLogin();
2897
+ session = yield this.userSetupAfterLogin(session);
3927
2898
  const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3928
2899
  this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3929
2900
  if (isSwitchingWallets) {
@@ -3948,7 +2919,9 @@ waitForLoginProcess_fn = function() {
3948
2919
  }
3949
2920
  }
3950
2921
  this.devLog("[waitForLoginProcess] Getting transmission key shares");
3951
- const tempSharesRes = yield this.getTransmissionKeyShares();
2922
+ const tempSharesRes = yield this.getTransmissionKeyShares({
2923
+ sessionLookupId: session.sessionLookupId
2924
+ });
3952
2925
  this.devLog("[waitForLoginProcess] Transmission shares received", {
3953
2926
  shareCount: tempSharesRes.data.temporaryShares.length,
3954
2927
  shares: tempSharesRes.data.temporaryShares.map((s) => ({
@@ -4015,224 +2988,41 @@ waitForLoginProcess_fn = function() {
4015
2988
  });
4016
2989
  });
4017
2990
  };
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);
2991
+ logout_fn = function() {
2992
+ return __async(this, arguments, function* ({
2993
+ clearPregenWallets = false,
2994
+ skipStateReset = false
2995
+ } = {}) {
2996
+ const isSessionActive = yield this.isSessionActive();
2997
+ if (!isSessionActive && !skipStateReset) {
2998
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
4088
2999
  }
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;
3000
+ yield this.ctx.client.logout();
3001
+ yield this.clearStorage();
3002
+ if (!clearPregenWallets) {
3003
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
3004
+ if (!wallet.pregenIdentifier) {
3005
+ delete this.wallets[id];
4111
3006
  }
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
3007
  });
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;
3008
+ yield this.setWallets(this.wallets);
3009
+ } else {
3010
+ __privateGet(this, _walletService).wallets = {};
4225
3011
  }
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;
3012
+ __privateGet(this, _walletService).currentWalletIds = {};
3013
+ __privateGet(this, _externalWalletService).externalWallets = {};
3014
+ this.loginEncryptionKeyPair = void 0;
3015
+ __privateGet(this, _authService).authInfo = void 0;
3016
+ this.accountLinkInProgress = void 0;
3017
+ __privateGet(this, _authService).userId = void 0;
3018
+ __privateGet(this, _sessionManagementService).sessionCookie = void 0;
3019
+ this.isEnclaveUser = false;
3020
+ if (isSessionActive) {
3021
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
3022
+ if (!skipStateReset) {
3023
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
3024
+ }
4234
3025
  }
4235
- return signupState;
4236
3026
  });
4237
3027
  };
4238
3028
  _ParaCore.version = constants.PARA_CORE_VERSION;