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