@metamask/profile-sync-controller 11.0.1 → 13.0.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 (56) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/dist/controllers/user-storage/UserStorageController.cjs +28 -32
  3. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  4. package/dist/controllers/user-storage/UserStorageController.d.cts +11 -10
  5. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  6. package/dist/controllers/user-storage/UserStorageController.d.mts +11 -10
  7. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.mjs +28 -32
  9. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  10. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +5 -14
  11. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +1 -1
  12. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts +4 -6
  13. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts.map +1 -1
  14. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts +4 -6
  15. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts.map +1 -1
  16. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +5 -14
  17. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +1 -1
  18. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs +11 -8
  19. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs.map +1 -1
  20. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts +2 -3
  21. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts.map +1 -1
  22. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts +2 -3
  23. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts.map +1 -1
  24. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs +11 -8
  25. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs.map +1 -1
  26. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs +3 -5
  27. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs.map +1 -1
  28. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts +2 -3
  29. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts.map +1 -1
  30. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts +2 -3
  31. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts.map +1 -1
  32. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs +3 -5
  33. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs.map +1 -1
  34. package/dist/controllers/user-storage/account-syncing/types.cjs.map +1 -1
  35. package/dist/controllers/user-storage/account-syncing/types.d.cts +0 -3
  36. package/dist/controllers/user-storage/account-syncing/types.d.cts.map +1 -1
  37. package/dist/controllers/user-storage/account-syncing/types.d.mts +0 -3
  38. package/dist/controllers/user-storage/account-syncing/types.d.mts.map +1 -1
  39. package/dist/controllers/user-storage/account-syncing/types.mjs.map +1 -1
  40. package/dist/controllers/user-storage/constants.cjs +8 -0
  41. package/dist/controllers/user-storage/constants.cjs.map +1 -0
  42. package/dist/controllers/user-storage/constants.d.cts +5 -0
  43. package/dist/controllers/user-storage/constants.d.cts.map +1 -0
  44. package/dist/controllers/user-storage/constants.d.mts +5 -0
  45. package/dist/controllers/user-storage/constants.d.mts.map +1 -0
  46. package/dist/controllers/user-storage/constants.mjs +5 -0
  47. package/dist/controllers/user-storage/constants.mjs.map +1 -0
  48. package/dist/controllers/user-storage/index.cjs +1 -0
  49. package/dist/controllers/user-storage/index.cjs.map +1 -1
  50. package/dist/controllers/user-storage/index.d.cts +1 -0
  51. package/dist/controllers/user-storage/index.d.cts.map +1 -1
  52. package/dist/controllers/user-storage/index.d.mts +1 -0
  53. package/dist/controllers/user-storage/index.d.mts.map +1 -1
  54. package/dist/controllers/user-storage/index.mjs +1 -0
  55. package/dist/controllers/user-storage/index.mjs.map +1 -1
  56. package/package.json +12 -12
@@ -13,6 +13,7 @@ var _UserStorageController_instances, _UserStorageController_env, _UserStorageCo
13
13
  import { BaseController } from "@metamask/base-controller";
14
14
  import { saveInternalAccountToUserStorage, syncInternalAccountsWithUserStorage } from "./account-syncing/controller-integration.mjs";
15
15
  import { setupAccountSyncingSubscriptions } from "./account-syncing/setup-subscriptions.mjs";
16
+ import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
16
17
  import { performMainNetworkSync, startNetworkSyncing } from "./network-syncing/controller-integration.mjs";
17
18
  import { Env, UserStorage } from "../../sdk/index.mjs";
18
19
  import { createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
@@ -20,6 +21,7 @@ const controllerName = 'UserStorageController';
20
21
  export const defaultState = {
21
22
  isProfileSyncingEnabled: true,
22
23
  isProfileSyncingUpdateLoading: false,
24
+ isAccountSyncingEnabled: true,
23
25
  hasAccountSyncingSyncedAtLeastOnce: false,
24
26
  isAccountSyncingReadyToBeDispatched: false,
25
27
  isAccountSyncingInProgress: false,
@@ -33,6 +35,10 @@ const metadata = {
33
35
  persist: false,
34
36
  anonymous: false,
35
37
  },
38
+ isAccountSyncingEnabled: {
39
+ persist: true,
40
+ anonymous: true,
41
+ },
36
42
  hasAccountSyncingSyncedAtLeastOnce: {
37
43
  persist: true,
38
44
  anonymous: false,
@@ -70,7 +76,6 @@ class UserStorageController extends BaseController {
70
76
  // This is replaced with the actual value in the constructor
71
77
  // We will remove this once the feature will be released
72
78
  _UserStorageController_env.set(this, {
73
- isAccountSyncingEnabled: false,
74
79
  isNetworkSyncingEnabled: false,
75
80
  });
76
81
  _UserStorageController_userStorage.set(this, void 0);
@@ -103,7 +108,6 @@ class UserStorageController extends BaseController {
103
108
  });
104
109
  _UserStorageController_nativeScryptCrypto.set(this, undefined);
105
110
  _UserStorageController__snapSignMessageCache.set(this, {});
106
- __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled = Boolean(env?.isAccountSyncingEnabled);
107
111
  __classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);
108
112
  __classPrivateFieldSet(this, _UserStorageController_config, config, "f");
109
113
  __classPrivateFieldSet(this, _UserStorageController_userStorage, new UserStorage({
@@ -127,12 +131,10 @@ class UserStorageController extends BaseController {
127
131
  __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_registerMessageHandlers).call(this);
128
132
  __classPrivateFieldSet(this, _UserStorageController_nativeScryptCrypto, nativeScryptCrypto, "f");
129
133
  // Account Syncing
130
- if (__classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled) {
131
- setupAccountSyncingSubscriptions({ isAccountSyncingEnabled: true }, {
132
- getUserStorageControllerInstance: () => this,
133
- getMessenger: () => this.messagingSystem,
134
- });
135
- }
134
+ setupAccountSyncingSubscriptions({
135
+ getUserStorageControllerInstance: () => this,
136
+ getMessenger: () => this.messagingSystem,
137
+ });
136
138
  // Network Syncing
137
139
  if (__classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled) {
138
140
  startNetworkSyncing({
@@ -245,35 +247,34 @@ class UserStorageController extends BaseController {
245
247
  flushStorageKeyCache() {
246
248
  __classPrivateFieldSet(this, _UserStorageController_storageKeyCache, {}, "f");
247
249
  }
248
- async enableProfileSyncing() {
250
+ async setIsBackupAndSyncFeatureEnabled(feature, enabled) {
249
251
  try {
250
252
  __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, true);
251
- const isSignedIn = __classPrivateFieldGet(this, _UserStorageController_auth, "f").isSignedIn();
252
- if (!isSignedIn) {
253
- await __classPrivateFieldGet(this, _UserStorageController_auth, "f").signIn();
253
+ if (enabled) {
254
+ // If any of the features are enabled, we need to ensure the user is signed in
255
+ const isSignedIn = __classPrivateFieldGet(this, _UserStorageController_auth, "f").isSignedIn();
256
+ if (!isSignedIn) {
257
+ await __classPrivateFieldGet(this, _UserStorageController_auth, "f").signIn();
258
+ }
254
259
  }
255
260
  this.update((state) => {
256
- state.isProfileSyncingEnabled = true;
261
+ if (feature === BACKUPANDSYNC_FEATURES.main) {
262
+ state.isProfileSyncingEnabled = enabled;
263
+ }
264
+ if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {
265
+ state.isAccountSyncingEnabled = enabled;
266
+ }
257
267
  });
258
- __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, false);
259
268
  }
260
269
  catch (e) {
261
- __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, false);
262
270
  // istanbul ignore next
263
271
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
264
- throw new Error(`${controllerName} - failed to enable profile syncing - ${errorMessage}`);
272
+ // istanbul ignore next
273
+ throw new Error(`${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`);
265
274
  }
266
- }
267
- async disableProfileSyncing() {
268
- const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;
269
- if (isAlreadyDisabled) {
270
- return;
275
+ finally {
276
+ __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, false);
271
277
  }
272
- __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, true);
273
- this.update((state) => {
274
- state.isProfileSyncingEnabled = false;
275
- });
276
- __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_setIsProfileSyncingUpdateLoading).call(this, false);
277
278
  }
278
279
  async setHasAccountSyncingSyncedAtLeastOnce(hasAccountSyncingSyncedAtLeastOnce) {
279
280
  this.update((state) => {
@@ -300,7 +301,6 @@ class UserStorageController extends BaseController {
300
301
  async syncInternalAccountsWithUserStorage() {
301
302
  const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
302
303
  await syncInternalAccountsWithUserStorage({
303
- isAccountSyncingEnabled: __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled,
304
304
  maxNumberOfAccountsToAdd: __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.maxNumberOfAccountsToAdd,
305
305
  onAccountAdded: () => __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountAdded?.(profileId),
306
306
  onAccountNameUpdated: () => __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountNameUpdated?.(profileId),
@@ -316,7 +316,7 @@ class UserStorageController extends BaseController {
316
316
  * @param internalAccount - The internal account to save
317
317
  */
318
318
  async saveInternalAccountToUserStorage(internalAccount) {
319
- await saveInternalAccountToUserStorage(internalAccount, { isAccountSyncingEnabled: __classPrivateFieldGet(this, _UserStorageController_env, "f").isAccountSyncingEnabled }, {
319
+ await saveInternalAccountToUserStorage(internalAccount, {
320
320
  getMessenger: () => this.messagingSystem,
321
321
  getUserStorageControllerInstance: () => this,
322
322
  });
@@ -347,10 +347,6 @@ _UserStorageController_env = new WeakMap(), _UserStorageController_userStorage =
347
347
  this.messagingSystem.registerActionHandler('UserStorageController:performDeleteStorage', this.performDeleteStorage.bind(this));
348
348
  this.messagingSystem.registerActionHandler('UserStorageController:performBatchDeleteStorage', this.performBatchDeleteStorage.bind(this));
349
349
  this.messagingSystem.registerActionHandler('UserStorageController:getStorageKey', this.getStorageKey.bind(this));
350
- this.messagingSystem.registerActionHandler('UserStorageController:enableProfileSyncing', this.enableProfileSyncing.bind(this));
351
- this.messagingSystem.registerActionHandler('UserStorageController:disableProfileSyncing', this.disableProfileSyncing.bind(this));
352
- this.messagingSystem.registerActionHandler('UserStorageController:syncInternalAccountsWithUserStorage', this.syncInternalAccountsWithUserStorage.bind(this));
353
- this.messagingSystem.registerActionHandler('UserStorageController:saveInternalAccountToUserStorage', this.saveInternalAccountToUserStorage.bind(this));
354
350
  }, _UserStorageController_snapSignMessage =
355
351
  /**
356
352
  * Signs a specific message using an underlying auth snap.
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAiB3D,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACpC,qDAAiD;AAClD,OAAO,EAAE,gCAAgC,EAAE,kDAA8C;AACzF,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACpB,qDAAiD;AAClD,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,4BAAkB;AAO7C,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA8B/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;IACpC,kCAAkC,EAAE,KAAK;IACzC,mCAAmC,EAAE,KAAK;IAC1C,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,0BAA0B,EAAE;QAC1B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAyJF;;;;;;;GAOG;AACH,MAAqB,qBAAsB,SAAQ,cAIlD;IAoDC,Y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I,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HA0CC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eArZkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerWithKeyringAction,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type {\n NetworkControllerAddNetworkAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkRemovedEvent,\n NetworkControllerRemoveNetworkAction,\n NetworkControllerUpdateNetworkAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport {\n saveInternalAccountToUserStorage,\n syncInternalAccountsWithUserStorage,\n} from './account-syncing/controller-integration';\nimport { setupAccountSyncingSubscriptions } from './account-syncing/setup-subscriptions';\nimport {\n performMainNetworkSync,\n startNetworkSyncing,\n} from './network-syncing/controller-integration';\nimport { Env, UserStorage } from '../../sdk';\nimport type { UserStorageFeatureKeys } from '../../shared/storage-schema';\nimport {\n type UserStoragePathWithFeatureAndKey,\n type UserStoragePathWithFeatureOnly,\n} from '../../shared/storage-schema';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n /**\n * Condition used by E2E tests to determine if account syncing has been dispatched at least once.\n */\n hasAccountSyncingSyncedAtLeastOnce: boolean;\n /**\n * Condition used by UI to determine if account syncing is ready to be dispatched.\n */\n isAccountSyncingReadyToBeDispatched: boolean;\n /**\n * Condition used by UI to determine if account syncing is in progress.\n */\n isAccountSyncingInProgress: boolean;\n /**\n * Condition used to ensure that we do not perform any network sync mutations until we have synced at least once\n */\n hasNetworkSyncingSyncedAtLeastOnce?: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n hasAccountSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingReadyToBeDispatched: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingInProgress: {\n persist: false,\n anonymous: false,\n },\n hasNetworkSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\n maxNumberOfAccountsToAdd?: number;\n /**\n * Callback that fires when account sync adds an account.\n * This is used for analytics.\n */\n onAccountAdded?: (profileId: string) => void;\n\n /**\n * Callback that fires when account sync updates the name of an account.\n * This is used for analytics.\n */\n onAccountNameUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during account sync.\n * This is used for analytics.\n */\n onAccountSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n\n networkSyncing?: {\n maxNumberOfNetworksToAdd?: number;\n /**\n * Callback that fires when network sync adds a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkAdded?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync updates a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkUpdated?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync deletes a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkRemoved?: (profileId: string, chainId: string) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Account Syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerWithKeyringAction\n // Network Syncing\n | NetworkControllerGetStateAction\n | NetworkControllerAddNetworkAction\n | NetworkControllerRemoveNetworkAction\n | NetworkControllerUpdateNetworkAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkRemovedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n readonly #env = {\n isAccountSyncingEnabled: false,\n isNetworkSyncingEnabled: false,\n };\n\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config?: ControllerConfig;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n constructor({\n messenger,\n state,\n env,\n config,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env.isAccountSyncingEnabled = Boolean(env?.isAccountSyncingEnabled);\n this.#env.isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);\n this.#config = config;\n\n this.#userStorage = new UserStorage(\n {\n env: Env.PRD,\n auth: {\n getAccessToken: () =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n ),\n getUserProfile: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n },\n signMessage: (message) =>\n this.#snapSignMessage(message as `metamask:${string}`),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Account Syncing\n if (this.#env.isAccountSyncingEnabled) {\n setupAccountSyncingSubscriptions(\n { isAccountSyncingEnabled: true },\n {\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n },\n );\n }\n\n // Network Syncing\n if (this.#env.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getUserStorageControllerInstance: () => this,\n isMutationSyncBlocked: () =>\n !this.state.hasNetworkSyncingSyncedAtLeastOnce,\n });\n }\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: [UserStorageFeatureKeys<FeatureName>, string][],\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path);\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: UserStorageFeatureKeys<FeatureName>[],\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values);\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n this.#setIsProfileSyncingUpdateLoading(true);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n async setHasAccountSyncingSyncedAtLeastOnce(\n hasAccountSyncingSyncedAtLeastOnce: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.hasAccountSyncingSyncedAtLeastOnce =\n hasAccountSyncingSyncedAtLeastOnce;\n });\n }\n\n async setIsAccountSyncingReadyToBeDispatched(\n isAccountSyncingReadyToBeDispatched: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingReadyToBeDispatched =\n isAccountSyncingReadyToBeDispatched;\n });\n }\n\n async setIsAccountSyncingInProgress(\n isAccountSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingInProgress = isAccountSyncingInProgress;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n await syncInternalAccountsWithUserStorage(\n {\n isAccountSyncingEnabled: this.#env.isAccountSyncingEnabled,\n maxNumberOfAccountsToAdd:\n this.#config?.accountSyncing?.maxNumberOfAccountsToAdd,\n onAccountAdded: () =>\n this.#config?.accountSyncing?.onAccountAdded?.(profileId),\n onAccountNameUpdated: () =>\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId),\n onAccountSyncErroneousSituation: (situationMessage, sentryContext) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n );\n }\n\n /**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n await saveInternalAccountToUserStorage(\n internalAccount,\n { isAccountSyncingEnabled: this.#env.isAccountSyncingEnabled },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n );\n }\n\n async syncNetworks() {\n if (!this.#env.isNetworkSyncingEnabled) {\n return;\n }\n\n const profileId = await this.#auth.getProfileId();\n\n await performMainNetworkSync({\n messenger: this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n maxNetworksToAdd: this.#config?.networkSyncing?.maxNumberOfNetworksToAdd,\n onNetworkAdded: (cId) =>\n this.#config?.networkSyncing?.onNetworkAdded?.(profileId, cId),\n onNetworkUpdated: (cId) =>\n this.#config?.networkSyncing?.onNetworkUpdated?.(profileId, cId),\n onNetworkRemoved: (cId) =>\n this.#config?.networkSyncing?.onNetworkRemoved?.(profileId, cId),\n });\n\n this.update((s) => {\n s.hasNetworkSyncingSyncedAtLeastOnce = true;\n });\n }\n}\n"]}
1
+ {"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAiB3D,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACpC,qDAAiD;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C,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAC9B,CAAC;AACJ,CAAC;AAyID;;;;;GAKG;AACH,KAAK,iDAAkB,OAA6B;IAClD,IAAI,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HAuCC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eAtXkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerWithKeyringAction,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type {\n NetworkControllerAddNetworkAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkRemovedEvent,\n NetworkControllerRemoveNetworkAction,\n NetworkControllerUpdateNetworkAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport {\n saveInternalAccountToUserStorage,\n syncInternalAccountsWithUserStorage,\n} from './account-syncing/controller-integration';\nimport { setupAccountSyncingSubscriptions } from './account-syncing/setup-subscriptions';\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport {\n performMainNetworkSync,\n startNetworkSyncing,\n} from './network-syncing/controller-integration';\nimport { Env, UserStorage } from '../../sdk';\nimport type { UserStorageFeatureKeys } from '../../shared/storage-schema';\nimport {\n type UserStoragePathWithFeatureAndKey,\n type UserStoragePathWithFeatureOnly,\n} from '../../shared/storage-schema';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used to determine if account syncing has been dispatched at least once.\n * This is used for event listeners to determine if they should be triggered.\n * This is also used in E2E tests for verification purposes.\n */\n hasAccountSyncingSyncedAtLeastOnce: boolean;\n /**\n * Condition used by UI to determine if account syncing is ready to be dispatched.\n */\n isAccountSyncingReadyToBeDispatched: boolean;\n /**\n * Condition used by UI to determine if account syncing is in progress.\n */\n isAccountSyncingInProgress: boolean;\n /**\n * Condition used to ensure that we do not perform any network sync mutations until we have synced at least once\n */\n hasNetworkSyncingSyncedAtLeastOnce?: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n isAccountSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n hasAccountSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingReadyToBeDispatched: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingInProgress: {\n persist: false,\n anonymous: false,\n },\n hasNetworkSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\n maxNumberOfAccountsToAdd?: number;\n /**\n * Callback that fires when account sync adds an account.\n * This is used for analytics.\n */\n onAccountAdded?: (profileId: string) => void;\n\n /**\n * Callback that fires when account sync updates the name of an account.\n * This is used for analytics.\n */\n onAccountNameUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during account sync.\n * This is used for analytics.\n */\n onAccountSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n\n networkSyncing?: {\n maxNumberOfNetworksToAdd?: number;\n /**\n * Callback that fires when network sync adds a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkAdded?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync updates a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkUpdated?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync deletes a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkRemoved?: (profileId: string, chainId: string) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Account Syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerWithKeyringAction\n // Network Syncing\n | NetworkControllerGetStateAction\n | NetworkControllerAddNetworkAction\n | NetworkControllerRemoveNetworkAction\n | NetworkControllerUpdateNetworkAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkRemovedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n readonly #env = {\n isNetworkSyncingEnabled: false,\n };\n\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config?: ControllerConfig;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n constructor({\n messenger,\n state,\n env,\n config,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isNetworkSyncingEnabled?: boolean;\n };\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env.isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);\n this.#config = config;\n\n this.#userStorage = new UserStorage(\n {\n env: Env.PRD,\n auth: {\n getAccessToken: () =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n ),\n getUserProfile: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n },\n signMessage: (message) =>\n this.#snapSignMessage(message as `metamask:${string}`),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Account Syncing\n setupAccountSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n });\n\n // Network Syncing\n if (this.#env.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getUserStorageControllerInstance: () => this,\n isMutationSyncBlocked: () =>\n !this.state.hasNetworkSyncingSyncedAtLeastOnce,\n });\n }\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: [UserStorageFeatureKeys<FeatureName>, string][],\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path);\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: UserStorageFeatureKeys<FeatureName>[],\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values);\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isProfileSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsProfileSyncingUpdateLoading(false);\n }\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n async setHasAccountSyncingSyncedAtLeastOnce(\n hasAccountSyncingSyncedAtLeastOnce: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.hasAccountSyncingSyncedAtLeastOnce =\n hasAccountSyncingSyncedAtLeastOnce;\n });\n }\n\n async setIsAccountSyncingReadyToBeDispatched(\n isAccountSyncingReadyToBeDispatched: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingReadyToBeDispatched =\n isAccountSyncingReadyToBeDispatched;\n });\n }\n\n async setIsAccountSyncingInProgress(\n isAccountSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingInProgress = isAccountSyncingInProgress;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n await syncInternalAccountsWithUserStorage(\n {\n maxNumberOfAccountsToAdd:\n this.#config?.accountSyncing?.maxNumberOfAccountsToAdd,\n onAccountAdded: () =>\n this.#config?.accountSyncing?.onAccountAdded?.(profileId),\n onAccountNameUpdated: () =>\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId),\n onAccountSyncErroneousSituation: (situationMessage, sentryContext) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n );\n }\n\n /**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n await saveInternalAccountToUserStorage(internalAccount, {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n });\n }\n\n async syncNetworks() {\n if (!this.#env.isNetworkSyncingEnabled) {\n return;\n }\n\n const profileId = await this.#auth.getProfileId();\n\n await performMainNetworkSync({\n messenger: this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n maxNetworksToAdd: this.#config?.networkSyncing?.maxNumberOfNetworksToAdd,\n onNetworkAdded: (cId) =>\n this.#config?.networkSyncing?.onNetworkAdded?.(profileId, cId),\n onNetworkUpdated: (cId) =>\n this.#config?.networkSyncing?.onNetworkUpdated?.(profileId, cId),\n onNetworkRemoved: (cId) =>\n this.#config?.networkSyncing?.onNetworkRemoved?.(profileId, cId),\n });\n\n this.update((s) => {\n s.hasNetworkSyncingSyncedAtLeastOnce = true;\n });\n }\n}\n"]}
@@ -10,14 +10,11 @@ const storage_schema_1 = require("../../../shared/storage-schema.cjs");
10
10
  * Saves an individual internal account to the user storage.
11
11
  *
12
12
  * @param internalAccount - The internal account to save
13
- * @param config - parameters used for saving the internal account
14
13
  * @param options - parameters used for saving the internal account
15
14
  */
16
- async function saveInternalAccountToUserStorage(internalAccount, config, options) {
17
- const { isAccountSyncingEnabled } = config;
15
+ async function saveInternalAccountToUserStorage(internalAccount, options) {
18
16
  const { getUserStorageControllerInstance } = options;
19
- if (!isAccountSyncingEnabled ||
20
- !(0, sync_utils_1.canPerformAccountSyncing)(config, options) ||
17
+ if (!(0, sync_utils_1.canPerformAccountSyncing)(options) ||
21
18
  !(0, keyring_api_1.isEvmAccountType)(internalAccount.type) ||
22
19
  !(await (0, utils_1.isInternalAccountFromPrimarySRPHdKeyring)(internalAccount, options))) {
23
20
  return;
@@ -39,15 +36,10 @@ exports.saveInternalAccountToUserStorage = saveInternalAccountToUserStorage;
39
36
  /**
40
37
  * Saves the list of internal accounts to the user storage.
41
38
  *
42
- * @param config - parameters used for saving the list of internal accounts
43
39
  * @param options - parameters used for saving the list of internal accounts
44
40
  */
45
- async function saveInternalAccountsListToUserStorage(config, options) {
46
- const { isAccountSyncingEnabled } = config;
41
+ async function saveInternalAccountsListToUserStorage(options) {
47
42
  const { getUserStorageControllerInstance } = options;
48
- if (!isAccountSyncingEnabled) {
49
- return;
50
- }
51
43
  const internalAccountsList = await (0, sync_utils_1.getInternalAccountsList)(options);
52
44
  if (!internalAccountsList?.length) {
53
45
  return;
@@ -68,8 +60,7 @@ exports.saveInternalAccountsListToUserStorage = saveInternalAccountsListToUserSt
68
60
  * @param options - parameters used for syncing the internal accounts list with the user storage accounts list
69
61
  */
70
62
  async function syncInternalAccountsWithUserStorage(config, options) {
71
- const { isAccountSyncingEnabled } = config;
72
- if (!(0, sync_utils_1.canPerformAccountSyncing)(config, options) || !isAccountSyncingEnabled) {
63
+ if (!(0, sync_utils_1.canPerformAccountSyncing)(options)) {
73
64
  return;
74
65
  }
75
66
  const { maxNumberOfAccountsToAdd = Infinity, onAccountAdded, onAccountNameUpdated, onAccountSyncErroneousSituation, } = config;
@@ -78,7 +69,7 @@ async function syncInternalAccountsWithUserStorage(config, options) {
78
69
  await getUserStorageControllerInstance().setIsAccountSyncingInProgress(true);
79
70
  const userStorageAccountsList = await (0, sync_utils_1.getUserStorageAccountsList)(options);
80
71
  if (!userStorageAccountsList || !userStorageAccountsList.length) {
81
- await saveInternalAccountsListToUserStorage({ isAccountSyncingEnabled }, options);
72
+ await saveInternalAccountsListToUserStorage(options);
82
73
  await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(true);
83
74
  return;
84
75
  }
@@ -1 +1 @@
1
- {"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AACzD,qEAA4D;AAG5D,iDAIsB;AAEtB,uCAIiB;AACjB,uEAA4E;AAE5E;;;;;;GAMG;AACI,KAAK,UAAU,gCAAgC,CACpD,eAAgC,EAChC,MAA4B,EAC5B,OAA8B;IAE9B,MAAM,EAAE,uBAAuB,EAAE,GAAG,MAAM,CAAC;I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E;gBACpE,oEAAoE,CAAC;YAEvE,MAAM,OAAO,GAAG;gBACd,4BAA4B;gBAC5B,yBAAyB;aAC1B,CAAC;YACF,IAAI,iBAAiB,EAAE;gBACrB,+BAA+B,EAAE,CAC/B,6FAA6F,EAC7F,OAAO,CACR,CAAC;aACH;iBAAM;gBACL,+BAA+B,EAAE,CAC/B,oGAAoG,EACpG,OAAO,CACR,CAAC;aACH;SACF;QAED,qFAAqF;QACrF,mFAAmF;QACnF,MAAM,gCAAgC,EAAE,CAAC,qCAAqC,CAC5E,IAAI,CACL,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,uEAAuE,YAAY,EAAE,CACtF,CAAC;KACH;YAAS;QACR,MAAM,gCAAgC,EAAE,CAAC,6BAA6B,CACpE,KAAK,CACN,CAAC;KACH;AACH,CAAC;AAhSD,kFAgSC","sourcesContent":["import { isEvmAccountType } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport {\n canPerformAccountSyncing,\n getInternalAccountsList,\n getUserStorageAccountsList,\n} from './sync-utils';\nimport type { AccountSyncingConfig, AccountSyncingOptions } from './types';\nimport {\n isInternalAccountFromPrimarySRPHdKeyring,\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\n\n/**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n * @param config - parameters used for saving the internal account\n * @param options - parameters used for saving the internal account\n */\nexport async function saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (\n !isAccountSyncingEnabled ||\n !canPerformAccountSyncing(config, options) ||\n !isEvmAccountType(internalAccount.type) ||\n !(await isInternalAccountFromPrimarySRPHdKeyring(internalAccount, options))\n ) {\n return;\n }\n\n try {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await getUserStorageControllerInstance().performSetStorage(\n // ESLint is confused here.\n\n `${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to save account to user storage - ${errorMessage}`,\n );\n }\n}\n\n/**\n * Saves the list of internal accounts to the user storage.\n *\n * @param config - parameters used for saving the list of internal accounts\n * @param options - parameters used for saving the list of internal accounts\n */\nexport async function saveInternalAccountsListToUserStorage(\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (!isAccountSyncingEnabled) {\n return;\n }\n\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList?.length) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n}\n\ntype SyncInternalAccountsWithUserStorageConfig = AccountSyncingConfig & {\n maxNumberOfAccountsToAdd?: number;\n onAccountAdded?: () => void;\n onAccountNameUpdated?: () => void;\n onAccountSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n};\n\n/**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n *\n * @param config - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param options - parameters used for syncing the internal accounts list with the user storage accounts list\n */\nexport async function syncInternalAccountsWithUserStorage(\n config: SyncInternalAccountsWithUserStorageConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n\n if (!canPerformAccountSyncing(config, options) || !isAccountSyncingEnabled) {\n return;\n }\n\n const {\n maxNumberOfAccountsToAdd = Infinity,\n onAccountAdded,\n onAccountNameUpdated,\n onAccountSyncErroneousSituation,\n } = config;\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n try {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n true,\n );\n\n const userStorageAccountsList = await getUserStorageAccountsList(options);\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await saveInternalAccountsListToUserStorage(\n { isAccountSyncingEnabled },\n options,\n );\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n return;\n }\n // Keep a record if erroneous situations are found during the sync\n // This is done so we can send the context to Sentry in case of an erroneous situation\n let erroneousSituationsFound = false;\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreUserStorageAccountsThanInternalAccounts =\n userStorageAccountsList.length > internalAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts in user storage than internal accounts\n if (hasMoreUserStorageAccountsThanInternalAccounts) {\n const numberOfAccountsToAdd =\n Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -\n internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n // NOTE: we only support the primary SRP HD keyring for now\n // This is why we are hardcoding the index to 0\n await getMessenger().call(\n 'KeyringController:withKeyring',\n {\n type: KeyringTypes.hd,\n index: 0,\n },\n async ({ keyring }) => {\n await keyring.addAccounts(numberOfAccountsToAdd);\n },\n );\n\n // TODO: below code is kept for analytics but should probably be re-thought\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n onAccountAdded?.();\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n const refreshedInternalAccountsList =\n await getInternalAccountsList(options);\n\n const newlyAddedAccounts = refreshedInternalAccountsList.filter(\n (account) =>\n !internalAccountsList.find((a) => a.address === account.address),\n );\n\n for (const internalAccount of refreshedInternalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n // If the account is not present in user storage\n // istanbul ignore next\n if (!userStorageAccount) {\n // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account\n if (newlyAddedAccounts.includes(internalAccount)) {\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was added to the internal accounts list but was not present in the user storage accounts list',\n {\n internalAccount,\n userStorageAccount,\n newlyAddedAccounts,\n userStorageAccountsList,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n },\n );\n continue;\n }\n // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // From this point on, we know that the account is present in\n // both the internal accounts list and the user storage accounts list\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n onAccountNameUpdated?.();\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n onAccountNameUpdated?.();\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n if (internalAccountsToBeSavedToUserStorage.length) {\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n }\n\n // In case we have corrupted user storage with accounts that don't exist in the internal accounts list\n // Delete those accounts from the user storage\n const userStorageAccountsToBeDeleted = userStorageAccountsList.filter(\n (account) =>\n !refreshedInternalAccountsList.find((a) => a.address === account.a),\n );\n\n if (userStorageAccountsToBeDeleted.length) {\n await getUserStorageControllerInstance().performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n );\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync',\n {\n userStorageAccountsToBeDeleted,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n userStorageAccountsList,\n },\n );\n }\n\n if (erroneousSituationsFound) {\n const [finalUserStorageAccountsList, finalInternalAccountsList] =\n await Promise.all([\n getUserStorageAccountsList(options),\n getInternalAccountsList(options),\n ]);\n\n const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList =\n finalInternalAccountsList.every((account) =>\n finalUserStorageAccountsList?.some(\n (userStorageAccount) => userStorageAccount.a === account.address,\n ),\n );\n\n // istanbul ignore next\n const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList =\n (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd\n ? true\n : finalUserStorageAccountsList?.every((account) =>\n finalInternalAccountsList.some(\n (internalAccount) => internalAccount.address === account.a,\n ),\n );\n\n const doFinalListsMatch =\n doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&\n doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;\n\n const context = {\n finalUserStorageAccountsList,\n finalInternalAccountsList,\n };\n if (doFinalListsMatch) {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, but final state matches the expected state',\n context,\n );\n } else {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, and final state does not match the expected state',\n context,\n );\n }\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n false,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AACzD,qEAA4D;AAG5D,iDAIsB;AAEtB,uCAIiB;AACjB,uEAA4E;AAE5E;;;;;GAKG;AACI,KAAK,UAAU,gCAAgC,CACpD,eAAgC,EAChC,OAA8B;IAE9B,MAAM,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAErD,IACE,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC;QAClC,CAAC,IAAA,8BAAgB,EAAC,eAAe,CAAC,IAAI,CAAC;QACvC,CAAC,CAAC,MAAM,IAAA,gDAAwC,EAAC,eAAe,EAAE,OAAO,CAAC,CAAC,EAC3E;QACA,OAAO;KACR;IAED,IAAI;QACF,8DAA8D;QAC9D,MAAM,aAAa,GACjB,IAAA,8CAAsC,EAAC,eAAe,CAAC,CAAC;QAE1D,MAAM,gCAAgC,EAAE,CAAC,iBAAiB;QACxD,2BAA2B;QAE3B,GAAG,2CAA0B,CAAC,QAAQ,IAAI,eAAe,CAAC,OAAO,EAAE,EACnE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAC9B,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,oEAAoE,YAAY,EAAE,CACnF,CAAC;KACH;AACH,CAAC;AAhCD,4EAgCC;AAED;;;;GAIG;AACI,KAAK,UAAU,qCAAqC,CACzD,OAA8B;IAE9B,MAAM,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAErD,MAAM,oBAAoB,GAAG,MAAM,IAAA,oCAAuB,EAAC,OAAO,CAAC,CAAC;IAEpE,IAAI,CAAC,oBAAoB,EAAE,MAAM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M,OAAO,GAAG;gBACd,4BAA4B;gBAC5B,yBAAyB;aAC1B,CAAC;YACF,IAAI,iBAAiB,EAAE;gBACrB,+BAA+B,EAAE,CAC/B,6FAA6F,EAC7F,OAAO,CACR,CAAC;aACH;iBAAM;gBACL,+BAA+B,EAAE,CAC/B,oGAAoG,EACpG,OAAO,CACR,CAAC;aACH;SACF;QAED,qFAAqF;QACrF,mFAAmF;QACnF,MAAM,gCAAgC,EAAE,CAAC,qCAAqC,CAC5E,IAAI,CACL,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,uEAAuE,YAAY,EAAE,CACtF,CAAC;KACH;YAAS;QACR,MAAM,gCAAgC,EAAE,CAAC,6BAA6B,CACpE,KAAK,CACN,CAAC;KACH;AACH,CAAC;AA3RD,kFA2RC","sourcesContent":["import { isEvmAccountType } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport {\n canPerformAccountSyncing,\n getInternalAccountsList,\n getUserStorageAccountsList,\n} from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\nimport {\n isInternalAccountFromPrimarySRPHdKeyring,\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\n\n/**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n * @param options - parameters used for saving the internal account\n */\nexport async function saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { getUserStorageControllerInstance } = options;\n\n if (\n !canPerformAccountSyncing(options) ||\n !isEvmAccountType(internalAccount.type) ||\n !(await isInternalAccountFromPrimarySRPHdKeyring(internalAccount, options))\n ) {\n return;\n }\n\n try {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await getUserStorageControllerInstance().performSetStorage(\n // ESLint is confused here.\n\n `${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to save account to user storage - ${errorMessage}`,\n );\n }\n}\n\n/**\n * Saves the list of internal accounts to the user storage.\n *\n * @param options - parameters used for saving the list of internal accounts\n */\nexport async function saveInternalAccountsListToUserStorage(\n options: AccountSyncingOptions,\n): Promise<void> {\n const { getUserStorageControllerInstance } = options;\n\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList?.length) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n}\n\ntype SyncInternalAccountsWithUserStorageConfig = {\n maxNumberOfAccountsToAdd?: number;\n onAccountAdded?: () => void;\n onAccountNameUpdated?: () => void;\n onAccountSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n};\n\n/**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n *\n * @param config - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param options - parameters used for syncing the internal accounts list with the user storage accounts list\n */\nexport async function syncInternalAccountsWithUserStorage(\n config: SyncInternalAccountsWithUserStorageConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n if (!canPerformAccountSyncing(options)) {\n return;\n }\n\n const {\n maxNumberOfAccountsToAdd = Infinity,\n onAccountAdded,\n onAccountNameUpdated,\n onAccountSyncErroneousSituation,\n } = config;\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n try {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n true,\n );\n\n const userStorageAccountsList = await getUserStorageAccountsList(options);\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await saveInternalAccountsListToUserStorage(options);\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n return;\n }\n // Keep a record if erroneous situations are found during the sync\n // This is done so we can send the context to Sentry in case of an erroneous situation\n let erroneousSituationsFound = false;\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreUserStorageAccountsThanInternalAccounts =\n userStorageAccountsList.length > internalAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts in user storage than internal accounts\n if (hasMoreUserStorageAccountsThanInternalAccounts) {\n const numberOfAccountsToAdd =\n Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -\n internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n // NOTE: we only support the primary SRP HD keyring for now\n // This is why we are hardcoding the index to 0\n await getMessenger().call(\n 'KeyringController:withKeyring',\n {\n type: KeyringTypes.hd,\n index: 0,\n },\n async ({ keyring }) => {\n await keyring.addAccounts(numberOfAccountsToAdd);\n },\n );\n\n // TODO: below code is kept for analytics but should probably be re-thought\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n onAccountAdded?.();\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n const refreshedInternalAccountsList =\n await getInternalAccountsList(options);\n\n const newlyAddedAccounts = refreshedInternalAccountsList.filter(\n (account) =>\n !internalAccountsList.find((a) => a.address === account.address),\n );\n\n for (const internalAccount of refreshedInternalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n // If the account is not present in user storage\n // istanbul ignore next\n if (!userStorageAccount) {\n // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account\n if (newlyAddedAccounts.includes(internalAccount)) {\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was added to the internal accounts list but was not present in the user storage accounts list',\n {\n internalAccount,\n userStorageAccount,\n newlyAddedAccounts,\n userStorageAccountsList,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n },\n );\n continue;\n }\n // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // From this point on, we know that the account is present in\n // both the internal accounts list and the user storage accounts list\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n onAccountNameUpdated?.();\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n onAccountNameUpdated?.();\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n if (internalAccountsToBeSavedToUserStorage.length) {\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n }\n\n // In case we have corrupted user storage with accounts that don't exist in the internal accounts list\n // Delete those accounts from the user storage\n const userStorageAccountsToBeDeleted = userStorageAccountsList.filter(\n (account) =>\n !refreshedInternalAccountsList.find((a) => a.address === account.a),\n );\n\n if (userStorageAccountsToBeDeleted.length) {\n await getUserStorageControllerInstance().performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n );\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync',\n {\n userStorageAccountsToBeDeleted,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n userStorageAccountsList,\n },\n );\n }\n\n if (erroneousSituationsFound) {\n const [finalUserStorageAccountsList, finalInternalAccountsList] =\n await Promise.all([\n getUserStorageAccountsList(options),\n getInternalAccountsList(options),\n ]);\n\n const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList =\n finalInternalAccountsList.every((account) =>\n finalUserStorageAccountsList?.some(\n (userStorageAccount) => userStorageAccount.a === account.address,\n ),\n );\n\n // istanbul ignore next\n const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList =\n (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd\n ? true\n : finalUserStorageAccountsList?.every((account) =>\n finalInternalAccountsList.some(\n (internalAccount) => internalAccount.address === account.a,\n ),\n );\n\n const doFinalListsMatch =\n doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&\n doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;\n\n const context = {\n finalUserStorageAccountsList,\n finalInternalAccountsList,\n };\n if (doFinalListsMatch) {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, but final state matches the expected state',\n context,\n );\n } else {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, and final state does not match the expected state',\n context,\n );\n }\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n false,\n );\n }\n}\n"]}
@@ -1,21 +1,19 @@
1
1
  import type { InternalAccount } from "@metamask/keyring-internal-api";
2
- import type { AccountSyncingConfig, AccountSyncingOptions } from "./types.cjs";
2
+ import type { AccountSyncingOptions } from "./types.cjs";
3
3
  /**
4
4
  * Saves an individual internal account to the user storage.
5
5
  *
6
6
  * @param internalAccount - The internal account to save
7
- * @param config - parameters used for saving the internal account
8
7
  * @param options - parameters used for saving the internal account
9
8
  */
10
- export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, config: AccountSyncingConfig, options: AccountSyncingOptions): Promise<void>;
9
+ export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, options: AccountSyncingOptions): Promise<void>;
11
10
  /**
12
11
  * Saves the list of internal accounts to the user storage.
13
12
  *
14
- * @param config - parameters used for saving the list of internal accounts
15
13
  * @param options - parameters used for saving the list of internal accounts
16
14
  */
17
- export declare function saveInternalAccountsListToUserStorage(config: AccountSyncingConfig, options: AccountSyncingOptions): Promise<void>;
18
- type SyncInternalAccountsWithUserStorageConfig = AccountSyncingConfig & {
15
+ export declare function saveInternalAccountsListToUserStorage(options: AccountSyncingOptions): Promise<void>;
16
+ type SyncInternalAccountsWithUserStorageConfig = {
19
17
  maxNumberOfAccountsToAdd?: number;
20
18
  onAccountAdded?: () => void;
21
19
  onAccountNameUpdated?: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,oBAAgB;AAQ3E;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CACzD,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAyBf;AAED,KAAK,yCAAyC,GAAG,oBAAoB,GAAG;IACtE,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA6Rf"}
1
+ {"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAQrD;;;;;GAKG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED;;;;GAIG;AACH,wBAAsB,qCAAqC,CACzD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED,KAAK,yCAAyC,GAAG;IAC/C,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAwRf"}
@@ -1,21 +1,19 @@
1
1
  import type { InternalAccount } from "@metamask/keyring-internal-api";
2
- import type { AccountSyncingConfig, AccountSyncingOptions } from "./types.mjs";
2
+ import type { AccountSyncingOptions } from "./types.mjs";
3
3
  /**
4
4
  * Saves an individual internal account to the user storage.
5
5
  *
6
6
  * @param internalAccount - The internal account to save
7
- * @param config - parameters used for saving the internal account
8
7
  * @param options - parameters used for saving the internal account
9
8
  */
10
- export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, config: AccountSyncingConfig, options: AccountSyncingOptions): Promise<void>;
9
+ export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, options: AccountSyncingOptions): Promise<void>;
11
10
  /**
12
11
  * Saves the list of internal accounts to the user storage.
13
12
  *
14
- * @param config - parameters used for saving the list of internal accounts
15
13
  * @param options - parameters used for saving the list of internal accounts
16
14
  */
17
- export declare function saveInternalAccountsListToUserStorage(config: AccountSyncingConfig, options: AccountSyncingOptions): Promise<void>;
18
- type SyncInternalAccountsWithUserStorageConfig = AccountSyncingConfig & {
15
+ export declare function saveInternalAccountsListToUserStorage(options: AccountSyncingOptions): Promise<void>;
16
+ type SyncInternalAccountsWithUserStorageConfig = {
19
17
  maxNumberOfAccountsToAdd?: number;
20
18
  onAccountAdded?: () => void;
21
19
  onAccountNameUpdated?: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,oBAAgB;AAQ3E;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CACzD,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAyBf;AAED,KAAK,yCAAyC,GAAG,oBAAoB,GAAG;IACtE,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA6Rf"}
1
+ {"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAQrD;;;;;GAKG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED;;;;GAIG;AACH,wBAAsB,qCAAqC,CACzD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED,KAAK,yCAAyC,GAAG;IAC/C,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAwRf"}
@@ -7,14 +7,11 @@ import { USER_STORAGE_FEATURE_NAMES } from "../../../shared/storage-schema.mjs";
7
7
  * Saves an individual internal account to the user storage.
8
8
  *
9
9
  * @param internalAccount - The internal account to save
10
- * @param config - parameters used for saving the internal account
11
10
  * @param options - parameters used for saving the internal account
12
11
  */
13
- export async function saveInternalAccountToUserStorage(internalAccount, config, options) {
14
- const { isAccountSyncingEnabled } = config;
12
+ export async function saveInternalAccountToUserStorage(internalAccount, options) {
15
13
  const { getUserStorageControllerInstance } = options;
16
- if (!isAccountSyncingEnabled ||
17
- !canPerformAccountSyncing(config, options) ||
14
+ if (!canPerformAccountSyncing(options) ||
18
15
  !isEvmAccountType(internalAccount.type) ||
19
16
  !(await isInternalAccountFromPrimarySRPHdKeyring(internalAccount, options))) {
20
17
  return;
@@ -35,15 +32,10 @@ export async function saveInternalAccountToUserStorage(internalAccount, config,
35
32
  /**
36
33
  * Saves the list of internal accounts to the user storage.
37
34
  *
38
- * @param config - parameters used for saving the list of internal accounts
39
35
  * @param options - parameters used for saving the list of internal accounts
40
36
  */
41
- export async function saveInternalAccountsListToUserStorage(config, options) {
42
- const { isAccountSyncingEnabled } = config;
37
+ export async function saveInternalAccountsListToUserStorage(options) {
43
38
  const { getUserStorageControllerInstance } = options;
44
- if (!isAccountSyncingEnabled) {
45
- return;
46
- }
47
39
  const internalAccountsList = await getInternalAccountsList(options);
48
40
  if (!internalAccountsList?.length) {
49
41
  return;
@@ -63,8 +55,7 @@ export async function saveInternalAccountsListToUserStorage(config, options) {
63
55
  * @param options - parameters used for syncing the internal accounts list with the user storage accounts list
64
56
  */
65
57
  export async function syncInternalAccountsWithUserStorage(config, options) {
66
- const { isAccountSyncingEnabled } = config;
67
- if (!canPerformAccountSyncing(config, options) || !isAccountSyncingEnabled) {
58
+ if (!canPerformAccountSyncing(options)) {
68
59
  return;
69
60
  }
70
61
  const { maxNumberOfAccountsToAdd = Infinity, onAccountAdded, onAccountNameUpdated, onAccountSyncErroneousSituation, } = config;
@@ -73,7 +64,7 @@ export async function syncInternalAccountsWithUserStorage(config, options) {
73
64
  await getUserStorageControllerInstance().setIsAccountSyncingInProgress(true);
74
65
  const userStorageAccountsList = await getUserStorageAccountsList(options);
75
66
  if (!userStorageAccountsList || !userStorageAccountsList.length) {
76
- await saveInternalAccountsListToUserStorage({ isAccountSyncingEnabled }, options);
67
+ await saveInternalAccountsListToUserStorage(options);
77
68
  await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(true);
78
69
  return;
79
70
  }