@metamask/profile-sync-controller 0.8.1 → 0.9.1

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 (72) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/controllers/user-storage/UserStorageController.cjs +55 -14
  3. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  4. package/dist/controllers/user-storage/UserStorageController.d.cts +12 -3
  5. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  6. package/dist/controllers/user-storage/UserStorageController.d.mts +12 -3
  7. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.mjs +57 -15
  9. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  10. package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs +38 -0
  11. package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs.map +1 -1
  12. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts +26 -0
  13. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts.map +1 -1
  14. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts +26 -0
  15. package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts.map +1 -1
  16. package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs +39 -0
  17. package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs.map +1 -1
  18. package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs +9 -1
  19. package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs.map +1 -1
  20. package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts +5 -0
  21. package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts.map +1 -1
  22. package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts +5 -0
  23. package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts.map +1 -1
  24. package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs +7 -0
  25. package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs.map +1 -1
  26. package/dist/controllers/user-storage/__fixtures__/mockServices.cjs +15 -3
  27. package/dist/controllers/user-storage/__fixtures__/mockServices.cjs.map +1 -1
  28. package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts +2 -1
  29. package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts.map +1 -1
  30. package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts +2 -1
  31. package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts.map +1 -1
  32. package/dist/controllers/user-storage/__fixtures__/mockServices.mjs +14 -3
  33. package/dist/controllers/user-storage/__fixtures__/mockServices.mjs.map +1 -1
  34. package/dist/controllers/user-storage/services.cjs +58 -2
  35. package/dist/controllers/user-storage/services.cjs.map +1 -1
  36. package/dist/controllers/user-storage/services.d.cts +10 -1
  37. package/dist/controllers/user-storage/services.d.cts.map +1 -1
  38. package/dist/controllers/user-storage/services.d.mts +10 -1
  39. package/dist/controllers/user-storage/services.d.mts.map +1 -1
  40. package/dist/controllers/user-storage/services.mjs +33 -1
  41. package/dist/controllers/user-storage/services.mjs.map +1 -1
  42. package/dist/controllers/user-storage/utils.cjs +27 -1
  43. package/dist/controllers/user-storage/utils.cjs.map +1 -1
  44. package/dist/controllers/user-storage/utils.d.cts +11 -0
  45. package/dist/controllers/user-storage/utils.d.cts.map +1 -1
  46. package/dist/controllers/user-storage/utils.d.mts +11 -0
  47. package/dist/controllers/user-storage/utils.d.mts.map +1 -1
  48. package/dist/controllers/user-storage/utils.mjs +25 -0
  49. package/dist/controllers/user-storage/utils.mjs.map +1 -1
  50. package/dist/sdk/__fixtures__/mock-userstorage.cjs +4 -2
  51. package/dist/sdk/__fixtures__/mock-userstorage.cjs.map +1 -1
  52. package/dist/sdk/__fixtures__/mock-userstorage.d.cts +1 -1
  53. package/dist/sdk/__fixtures__/mock-userstorage.d.cts.map +1 -1
  54. package/dist/sdk/__fixtures__/mock-userstorage.d.mts +1 -1
  55. package/dist/sdk/__fixtures__/mock-userstorage.d.mts.map +1 -1
  56. package/dist/sdk/__fixtures__/mock-userstorage.mjs +4 -2
  57. package/dist/sdk/__fixtures__/mock-userstorage.mjs.map +1 -1
  58. package/dist/sdk/user-storage.cjs +39 -1
  59. package/dist/sdk/user-storage.cjs.map +1 -1
  60. package/dist/sdk/user-storage.d.cts +2 -1
  61. package/dist/sdk/user-storage.d.cts.map +1 -1
  62. package/dist/sdk/user-storage.d.mts +2 -1
  63. package/dist/sdk/user-storage.d.mts.map +1 -1
  64. package/dist/sdk/user-storage.mjs +39 -1
  65. package/dist/sdk/user-storage.mjs.map +1 -1
  66. package/dist/shared/storage-schema.cjs.map +1 -1
  67. package/dist/shared/storage-schema.d.cts +5 -2
  68. package/dist/shared/storage-schema.d.cts.map +1 -1
  69. package/dist/shared/storage-schema.d.mts +5 -2
  70. package/dist/shared/storage-schema.d.mts.map +1 -1
  71. package/dist/shared/storage-schema.mjs.map +1 -1
  72. package/package.json +3 -3
@@ -11,11 +11,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _UserStorageController_instances, _UserStorageController_auth, _UserStorageController_accounts, _UserStorageController_config, _UserStorageController_notificationServices, _UserStorageController_isUnlocked, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_registerMessageHandlers, _UserStorageController_assertProfileSyncingEnabled, _UserStorageController_getStorageKeyAndBearerToken, _UserStorageController_createStorageKey, _UserStorageController__snapSignMessageCache, _UserStorageController_snapSignMessage, _UserStorageController_setIsProfileSyncingUpdateLoading;
13
13
  import { BaseController } from "@metamask/base-controller";
14
+ import $metamaskkeyringapi from "@metamask/keyring-api";
15
+ const { isEvmAccountType } = $metamaskkeyringapi;
16
+ import { KeyringTypes } from "@metamask/keyring-controller";
14
17
  import { createSHA256Hash } from "../../shared/encryption/index.mjs";
15
18
  import { createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
16
19
  import { isNameDefaultAccountName, mapInternalAccountToUserStorageAccount } from "./accounts/user-storage.mjs";
17
20
  import { startNetworkSyncing } from "./network-syncing/controller-integration.mjs";
18
- import { getUserStorage, getUserStorageAllFeatureEntries, upsertUserStorage } from "./services.mjs";
21
+ import { batchUpsertUserStorage, getUserStorage, getUserStorageAllFeatureEntries, upsertUserStorage } from "./services.mjs";
22
+ import { waitForExpectedValue } from "./utils.mjs";
19
23
  const controllerName = 'UserStorageController';
20
24
  export const defaultState = {
21
25
  isProfileSyncingEnabled: true,
@@ -71,6 +75,7 @@ class UserStorageController extends BaseController {
71
75
  // We will remove this once the feature will be released
72
76
  isAccountSyncingEnabled: false,
73
77
  isAccountSyncingInProgress: false,
78
+ addedAccountsCount: 0,
74
79
  canSync: () => {
75
80
  try {
76
81
  __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
@@ -85,6 +90,7 @@ class UserStorageController extends BaseController {
85
90
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
86
91
  async (account) => {
87
92
  if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress) {
93
+ __classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount += 1;
88
94
  return;
89
95
  }
90
96
  await this.saveInternalAccountToUserStorage(account);
@@ -98,8 +104,13 @@ class UserStorageController extends BaseController {
98
104
  await this.saveInternalAccountToUserStorage(account);
99
105
  });
100
106
  },
107
+ doesInternalAccountHaveCorrectKeyringType: (account) => {
108
+ return (account.metadata.keyring.type === KeyringTypes.hd ||
109
+ account.metadata.keyring.type === KeyringTypes.simple);
110
+ },
101
111
  getInternalAccountsList: async () => {
102
- return this.messagingSystem.call('AccountsController:listAccounts');
112
+ const internalAccountsList = await this.messagingSystem.call('AccountsController:listAccounts');
113
+ return internalAccountsList?.filter(__classPrivateFieldGet(this, _UserStorageController_accounts, "f").doesInternalAccountHaveCorrectKeyringType);
103
114
  },
104
115
  getUserStorageAccountsList: async () => {
105
116
  const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries('accounts');
@@ -116,10 +127,11 @@ class UserStorageController extends BaseController {
116
127
  if (!internalAccountsList) {
117
128
  return;
118
129
  }
119
- const userStorageAccountsList = internalAccountsList.map(mapInternalAccountToUserStorageAccount);
120
- await Promise.all(userStorageAccountsList.map(async (userStorageAccount) => {
121
- await this.performSetStorage(`accounts.${userStorageAccount.a}`, JSON.stringify(userStorageAccount));
122
- }));
130
+ const internalAccountsListFormattedForUserStorage = internalAccountsList.map(mapInternalAccountToUserStorageAccount);
131
+ await this.performBatchSetStorage('accounts', internalAccountsListFormattedForUserStorage.map((account) => [
132
+ account.a,
133
+ JSON.stringify(account),
134
+ ]));
123
135
  },
124
136
  });
125
137
  _UserStorageController_config.set(this, void 0);
@@ -271,6 +283,24 @@ class UserStorageController extends BaseController {
271
283
  nativeScryptCrypto: __classPrivateFieldGet(this, _UserStorageController_nativeScryptCrypto, "f"),
272
284
  });
273
285
  }
286
+ /**
287
+ * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.
288
+ * Developers can extend the entry path through the `schema.ts` file.
289
+ *
290
+ * @param path - string in the form of `${feature}` that matches schema
291
+ * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs
292
+ * @returns nothing. NOTE that an error is thrown if fails to store data.
293
+ */
294
+ async performBatchSetStorage(path, values) {
295
+ __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
296
+ const { bearerToken, storageKey } = await __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getStorageKeyAndBearerToken).call(this);
297
+ await batchUpsertUserStorage(values, {
298
+ path,
299
+ bearerToken,
300
+ storageKey,
301
+ nativeScryptCrypto: __classPrivateFieldGet(this, _UserStorageController_nativeScryptCrypto, "f"),
302
+ });
303
+ }
274
304
  /**
275
305
  * Retrieves the storage key, for internal use only!
276
306
  *
@@ -292,12 +322,15 @@ class UserStorageController extends BaseController {
292
322
  }
293
323
  try {
294
324
  __classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress = true;
325
+ __classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount = 0;
295
326
  const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
296
327
  const userStorageAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getUserStorageAccountsList();
297
328
  if (!userStorageAccountsList || !userStorageAccountsList.length) {
298
329
  await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountsListToUserStorage();
299
330
  return;
300
331
  }
332
+ // Prepare an array of internal accounts to be saved to the user storage
333
+ const internalAccountsToBeSavedToUserStorage = [];
301
334
  // Compare internal accounts list with user storage accounts list
302
335
  // First step: compare lengths
303
336
  let internalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
@@ -310,13 +343,15 @@ class UserStorageController extends BaseController {
310
343
  if (!hasMoreInternalAccountsThanUserStorageAccounts) {
311
344
  const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
312
345
  // Create new accounts to match the user storage accounts list
313
- const addNewAccountsPromises = Array.from({
346
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
347
+ for await (const _ of Array.from({
314
348
  length: numberOfAccountsToAdd,
315
- }).map(async () => {
349
+ })) {
350
+ const expectedAccountsCountAfterAddition = __classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount + 1;
316
351
  await this.messagingSystem.call('KeyringController:addNewAccount');
352
+ await waitForExpectedValue(() => __classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount, expectedAccountsCountAfterAddition, 5000);
317
353
  __classPrivateFieldGet(this, _UserStorageController_config, "f")?.accountSyncing?.onAccountAdded?.(profileId);
318
- });
319
- await Promise.all(addNewAccountsPromises);
354
+ }
320
355
  }
321
356
  // Second step: compare account names
322
357
  // Get the internal accounts list again since new accounts might have been added in the previous step
@@ -324,7 +359,7 @@ class UserStorageController extends BaseController {
324
359
  for await (const internalAccount of internalAccountsList) {
325
360
  const userStorageAccount = userStorageAccountsList.find((account) => account.a === internalAccount.address);
326
361
  if (!userStorageAccount) {
327
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountToUserStorage(internalAccount);
362
+ internalAccountsToBeSavedToUserStorage.push(internalAccount);
328
363
  continue;
329
364
  }
330
365
  // One or both accounts have default names
@@ -342,7 +377,7 @@ class UserStorageController extends BaseController {
342
377
  }
343
378
  // Internal account has custom name but user storage account has default name
344
379
  if (isUserStorageAccountNameDefault) {
345
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountToUserStorage(internalAccount);
380
+ internalAccountsToBeSavedToUserStorage.push(internalAccount);
346
381
  continue;
347
382
  }
348
383
  // Both accounts have custom names
@@ -353,7 +388,7 @@ class UserStorageController extends BaseController {
353
388
  const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt >
354
389
  userStorageAccount.nlu;
355
390
  if (isInternalAccountNameNewer) {
356
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountToUserStorage(internalAccount);
391
+ internalAccountsToBeSavedToUserStorage.push(internalAccount);
357
392
  continue;
358
393
  }
359
394
  }
@@ -365,10 +400,15 @@ class UserStorageController extends BaseController {
365
400
  continue;
366
401
  }
367
402
  else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {
368
- await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").saveInternalAccountToUserStorage(internalAccount);
403
+ internalAccountsToBeSavedToUserStorage.push(internalAccount);
369
404
  continue;
370
405
  }
371
406
  }
407
+ // Save the internal accounts list to the user storage
408
+ await this.performBatchSetStorage('accounts', internalAccountsToBeSavedToUserStorage.map((account) => [
409
+ account.address,
410
+ JSON.stringify(mapInternalAccountToUserStorageAccount(account)),
411
+ ]));
372
412
  }
373
413
  catch (e) {
374
414
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
@@ -383,7 +423,9 @@ class UserStorageController extends BaseController {
383
423
  * @param internalAccount - The internal account to save
384
424
  */
385
425
  async saveInternalAccountToUserStorage(internalAccount) {
386
- if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
426
+ if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
427
+ !isEvmAccountType(internalAccount.type) ||
428
+ !__classPrivateFieldGet(this, _UserStorageController_accounts, "f").doesInternalAccountHaveCorrectKeyringType(internalAccount)) {
387
429
  return;
388
430
  }
389
431
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAW3D,OAAO,EAAE,gBAAgB,EAAE,0CAAgC;AAM3D,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AASpF,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACvC,oCAAgC;AACjC,OAAO,EAAE,mBAAmB,EAAE,qDAAiD;AAC/E,OAAO,EACL,cAAc,EACd,+BAA+B,EAC/B,iBAAiB,EAClB,uBAAmB;AAoCpB,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAc/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;CACrC,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;CACF,CAAC;AAsHF;;;;;;;GAOG;AACH,MAAqB,qBAAsB,SAAQ,cAIlD;IA0JC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,EACN,mBAAmB,EACnB,kBAAkB,GAWnB;QACC,KAAK,CAAC;YACJ,SAA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EAAE;QACP,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;KACzE;IAED,MAAM,mBAAmB,GAAG,MAAM,uBAAA,IAAI,gFAAiB,MAArB,IAAI,EAAkB,YAAY,EAAE,EAAE,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,gBAAgB,CAAC,mBAAmB,CAAC,CAAC;IACzD,OAAO,UAAU,CAAC;AACpB,CAAC;AAID;;;;;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,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eAtekB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n 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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\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\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: 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};\n\ntype ControllerConfig = {\n accountSyncing?: {\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\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 | '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 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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n return (\n this.#accounts.isAccountSyncingEnabled && this.#auth.isAuthEnabled()\n );\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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: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 public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\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 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 setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\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 #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.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 than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\n });\n\n await Promise.all(addNewAccountsPromises);\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 internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount,\n );\n continue;\n }\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 this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount,\n );\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 >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\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;;;AAE3D,OAAO,EAKL,YAAY,EACb,qCAAqC;AAItC,OAAO,EA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7C;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,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eA5gBkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { type InternalAccount, isEvmAccountType } from '@metamask/keyring-api';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerAddNewAccountAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n batchUpsertUserStorage,\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\nimport { waitForExpectedValue } from './utils';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\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\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: 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};\n\ntype ControllerConfig = {\n accountSyncing?: {\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\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 | '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 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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n addedAccountsCount: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n return (\n this.#accounts.isAccountSyncingEnabled && this.#auth.isAuthEnabled()\n );\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n this.#accounts.addedAccountsCount += 1;\n return;\n }\n\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return (\n account.metadata.keyring.type === KeyringTypes.hd ||\n account.metadata.keyring.type === KeyringTypes.simple\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n const internalAccountsList = await this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n return internalAccountsList?.filter(\n this.#accounts.doesInternalAccountHaveCorrectKeyringType,\n );\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage =\n internalAccountsList.map(mapInternalAccountToUserStorageAccount);\n\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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: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 public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\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 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 setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\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 path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchUpsertUserStorage(values, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\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 #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n this.#accounts.addedAccountsCount = 0;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\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 let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.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 than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of Array.from({\n length: numberOfAccountsToAdd,\n })) {\n const expectedAccountsCountAfterAddition =\n this.#accounts.addedAccountsCount + 1;\n await this.messagingSystem.call('KeyringController:addNewAccount');\n await waitForExpectedValue(\n () => this.#accounts.addedAccountsCount,\n expectedAccountsCountAfterAddition,\n 5000,\n );\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\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 internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\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 this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\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 >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\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 await this.performBatchSetStorage(\n 'accounts',\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (\n !this.#accounts.canSync() ||\n !isEvmAccountType(internalAccount.type) ||\n !this.#accounts.doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MOCK_USER_STORAGE_ACCOUNTS = exports.MOCK_INTERNAL_ACCOUNTS = exports.getMockRandomDefaultAccountName = void 0;
4
+ const keyring_api_1 = require("@metamask/keyring-api");
5
+ const keyring_controller_1 = require("@metamask/keyring-controller");
4
6
  const constants_1 = require("../accounts/constants.cjs");
5
7
  const user_storage_1 = require("../accounts/user-storage.cjs");
6
8
  /**
@@ -22,9 +24,13 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
22
24
  {
23
25
  address: '0x123',
24
26
  id: '1',
27
+ type: keyring_api_1.EthAccountType.Eoa,
25
28
  metadata: {
26
29
  name: 'test',
27
30
  nameLastUpdatedAt: 1,
31
+ keyring: {
32
+ type: keyring_controller_1.KeyringTypes.hd,
33
+ },
28
34
  },
29
35
  },
30
36
  ],
@@ -32,9 +38,13 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
32
38
  {
33
39
  address: '0x123',
34
40
  id: '1',
41
+ type: keyring_api_1.EthAccountType.Eoa,
35
42
  metadata: {
36
43
  name: `${(0, exports.getMockRandomDefaultAccountName)()} 1`,
37
44
  nameLastUpdatedAt: 1,
45
+ keyring: {
46
+ type: keyring_controller_1.KeyringTypes.hd,
47
+ },
38
48
  },
39
49
  },
40
50
  ],
@@ -42,8 +52,12 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
42
52
  {
43
53
  address: '0x123',
44
54
  id: '1',
55
+ type: keyring_api_1.EthAccountType.Eoa,
45
56
  metadata: {
46
57
  name: 'Internal account custom name without nameLastUpdatedAt',
58
+ keyring: {
59
+ type: keyring_controller_1.KeyringTypes.hd,
60
+ },
47
61
  },
48
62
  },
49
63
  ],
@@ -51,9 +65,13 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
51
65
  {
52
66
  address: '0x123',
53
67
  id: '1',
68
+ type: keyring_api_1.EthAccountType.Eoa,
54
69
  metadata: {
55
70
  name: 'Internal account custom name with nameLastUpdatedAt',
56
71
  nameLastUpdatedAt: 1,
72
+ keyring: {
73
+ type: keyring_controller_1.KeyringTypes.hd,
74
+ },
57
75
  },
58
76
  },
59
77
  ],
@@ -61,9 +79,13 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
61
79
  {
62
80
  address: '0x123',
63
81
  id: '1',
82
+ type: keyring_api_1.EthAccountType.Eoa,
64
83
  metadata: {
65
84
  name: 'Internal account custom name with nameLastUpdatedAt',
66
85
  nameLastUpdatedAt: 9999,
86
+ keyring: {
87
+ type: keyring_controller_1.KeyringTypes.hd,
88
+ },
67
89
  },
68
90
  },
69
91
  ],
@@ -71,33 +93,49 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
71
93
  {
72
94
  address: '0x123',
73
95
  id: '1',
96
+ type: keyring_api_1.EthAccountType.Eoa,
74
97
  metadata: {
75
98
  name: 'test',
76
99
  nameLastUpdatedAt: 1,
100
+ keyring: {
101
+ type: keyring_controller_1.KeyringTypes.hd,
102
+ },
77
103
  },
78
104
  },
79
105
  {
80
106
  address: '0x456',
81
107
  id: '2',
108
+ type: keyring_api_1.EthAccountType.Eoa,
82
109
  metadata: {
83
110
  name: 'Account 2',
84
111
  nameLastUpdatedAt: 2,
112
+ keyring: {
113
+ type: keyring_controller_1.KeyringTypes.hd,
114
+ },
85
115
  },
86
116
  },
87
117
  {
88
118
  address: '0x789',
89
119
  id: '3',
120
+ type: keyring_api_1.EthAccountType.Eoa,
90
121
  metadata: {
91
122
  name: 'Účet 2',
92
123
  nameLastUpdatedAt: 3,
124
+ keyring: {
125
+ type: keyring_controller_1.KeyringTypes.hd,
126
+ },
93
127
  },
94
128
  },
95
129
  {
96
130
  address: '0xabc',
97
131
  id: '4',
132
+ type: keyring_api_1.EthAccountType.Eoa,
98
133
  metadata: {
99
134
  name: 'My Account 4',
100
135
  nameLastUpdatedAt: 4,
136
+ keyring: {
137
+ type: keyring_controller_1.KeyringTypes.hd,
138
+ },
101
139
  },
102
140
  },
103
141
  ],
@@ -1 +1 @@
1
- {"version":3,"file":"mockAccounts.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":";;;AAEA,yDAAwE;AACxE,+DAAkF;AAElF;;;;;GAKG;AACH,MAAM,gDAAgD,GAAG,CACvD,gBAAmC,EACnC,EAAE,CAAC,gBAAgB,CAAC,GAAG,CAAC,qDAAsC,CAAC,CAAC;AAElE;;;GAGG;AACI,MAAM,+BAA+B,GAAG,GAAG,EAAE,CAClD,2CAA+B,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,2CAA+B,CAAC,MAAM,CAAC,CACnE,CAAC;AAHS,QAAA,+BAA+B,mCAGxC;AAES,QAAA,sBAAsB,GAAG;IACpC,KAAK,EAAE,EAAE;IACT,GAAG,EAAE;QACH;YACE,OAAO,EAAE,OAAO;YAChB,EAAE,EAAE,GAAG;YACP,QAAQ,EAAE;gBACR,IAAI,EAAE,MAAM;gBACZ,iBAAiB,EAAE,CAAC;aACrB;SACF;KACF;IACD,gBAAgB,EAAE;QAChB;YACE,OAAO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BAAsB,CAAC,GAAwB,CAChD;IACD,GAAG,EAAE,gDAAgD,CACnD,8BAAsB,CAAC,GAAwB,CAChD;IACD,gBAAgB,EAAE,gDAAgD,CAChE,8BAAsB,CAAC,gBAAqC,CAC7D;IACD,oCAAoC,EAClC,gDAAgD,CAAC;QAC/C;YACE,GAAG,8BAAsB,CAAC,oCAAoC,CAAC,CAAC,CAAC;YACjE,QAAQ,EAAE;gBACR,IAAI,EAAE,4DAA4D;aACnE;SACF;KACmB,CAAC;IACzB,iCAAiC,EAC/B,gDAAgD,CAAC;QAC/C;YACE,GAAG,8BAAsB,CAAC,oCAAoC,CAAC,CAAC,CAAC;YACjE,QAAQ,EAAE;gBACR,IAAI,EAAE,yDAAyD;gBAC/D,iBAAiB,EAAE,CAAC;aACrB;SACF;KACmB,CAAC;CAC1B,CAAC","sourcesContent":["import type { InternalAccount } from '@metamask/keyring-api';\n\nimport { LOCALIZED_DEFAULT_ACCOUNT_NAMES } from '../accounts/constants';\nimport { mapInternalAccountToUserStorageAccount } from '../accounts/user-storage';\n\n/**\n * Map an array of internal accounts to an array of user storage accounts\n * Only used for testing purposes\n * @param internalAccounts - An array of internal accounts\n * @returns An array of user storage accounts\n */\nconst mapInternalAccountsListToUserStorageAccountsList = (\n internalAccounts: InternalAccount[],\n) => internalAccounts.map(mapInternalAccountToUserStorageAccount);\n\n/**\n * Get a random default account name from the list of localized default account names\n * @returns A random default account name\n */\nexport const getMockRandomDefaultAccountName = () =>\n LOCALIZED_DEFAULT_ACCOUNT_NAMES[\n Math.floor(Math.random() * LOCALIZED_DEFAULT_ACCOUNT_NAMES.length)\n ];\n\nexport const MOCK_INTERNAL_ACCOUNTS = {\n EMPTY: [],\n ONE: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: 'test',\n nameLastUpdatedAt: 1,\n },\n },\n ],\n ONE_DEFAULT_NAME: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: `${getMockRandomDefaultAccountName()} 1`,\n nameLastUpdatedAt: 1,\n },\n },\n ],\n ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: 'Internal account custom name without nameLastUpdatedAt',\n },\n },\n ],\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: 'Internal account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 1,\n },\n },\n ],\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED_MOST_RECENT: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: 'Internal account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 9999,\n },\n },\n ],\n ALL: [\n {\n address: '0x123',\n id: '1',\n metadata: {\n name: 'test',\n nameLastUpdatedAt: 1,\n },\n },\n {\n address: '0x456',\n id: '2',\n metadata: {\n name: 'Account 2',\n nameLastUpdatedAt: 2,\n },\n },\n {\n address: '0x789',\n id: '3',\n metadata: {\n name: 'Účet 2',\n nameLastUpdatedAt: 3,\n },\n },\n {\n address: '0xabc',\n id: '4',\n metadata: {\n name: 'My Account 4',\n nameLastUpdatedAt: 4,\n },\n },\n ],\n};\n\nexport const MOCK_USER_STORAGE_ACCOUNTS = {\n SAME_AS_INTERNAL_ALL: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ALL as InternalAccount[],\n ),\n ONE: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ONE as InternalAccount[],\n ),\n ONE_DEFAULT_NAME: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME as InternalAccount[],\n ),\n ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED:\n mapInternalAccountsListToUserStorageAccountsList([\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED[0],\n metadata: {\n name: 'User storage account custom name without nameLastUpdatedAt',\n },\n },\n ] as InternalAccount[]),\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED:\n mapInternalAccountsListToUserStorageAccountsList([\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED[0],\n metadata: {\n name: 'User storage account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 3,\n },\n },\n ] as InternalAccount[]),\n};\n"]}
1
+ {"version":3,"file":"mockAccounts.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":";;;AAAA,uDAA6E;AAC7E,qEAA4D;AAE5D,yDAAwE;AACxE,+DAAkF;AAElF;;;;;GAKG;AACH,MAAM,gDAAgD,GAAG,CACvD,gBAAmC,EACnC,EAAE,CAAC,gBAAgB,CAAC,GAAG,CAAC,qDAAsC,CAAC,CAAC;AAElE;;;GAGG;AACI,MAAM,+BAA+B,GAAG,GAAG,EAAE,CAClD,2CAA+B,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,2CAA+B,CAAC,MAAM,CAAC,CACnE,CAAC;AAHS,QAAA,+BAA+B,mCAGxC;AAES,QAAA,sBAAsB,GAAG;IACpC,KAAK,EAAE,EAAE;IACT,GAAG,EAAE;QACH;YACE,OAAO,EAAE,OAAO;YAChB,EAAE,EAAE,GAAG;YACP,IAAI,EAAE,4BAAc,CAAC,GAAG;YACxB,QAAQ,EAAE;gBACR,IAAI,EAAE,MAAM;gBACZ,iBAAiB,EAAE,CAAC;gBACpB,OAAO,EAAE;oBACP,IAAI,EAAE,iCAAY,CAAC,EAAE;iBACtB;aACF;SACF;KACF;IACD,gBAAgB,EAAE;QAChB;YACE,OAAO,EAAE,OAAO;YAChB,EAAE,EAAE,GAAG;YACP,IAAI,EAAE,4BAAc,CAAC,GAAG;YACxB,QAAQ,EAAE;gBACR,IAAI,EAAE,GAAG,IAAA,uCAA+B,GAAE,IAAI;gBAC9C,iBAAiB,EAA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BAAiB,EAAE,CAAC;gBACpB,OAAO,EAAE;oBACP,IAAI,EAAE,iCAAY,CAAC,EAAE;iBACtB;aACF;SACF;QACD;YACE,OAAO,EAAE,OAAO;YAChB,EAAE,EAAE,GAAG;YACP,IAAI,EAAE,4BAAc,CAAC,GAAG;YACxB,QAAQ,EAAE;gBACR,IAAI,EAAE,QAAQ;gBACd,iBAAiB,EAAE,CAAC;gBACpB,OAAO,EAAE;oBACP,IAAI,EAAE,iCAAY,CAAC,EAAE;iBACtB;aACF;SACF;QACD;YACE,OAAO,EAAE,OAAO;YAChB,EAAE,EAAE,GAAG;YACP,IAAI,EAAE,4BAAc,CAAC,GAAG;YACxB,QAAQ,EAAE;gBACR,IAAI,EAAE,cAAc;gBACpB,iBAAiB,EAAE,CAAC;gBACpB,OAAO,EAAE;oBACP,IAAI,EAAE,iCAAY,CAAC,EAAE;iBACtB;aACF;SACF;KACF;CACF,CAAC;AAEW,QAAA,0BAA0B,GAAG;IACxC,oBAAoB,EAAE,gDAAgD,CACpE,8BAAsB,CAAC,GAAwB,CAChD;IACD,GAAG,EAAE,gDAAgD,CACnD,8BAAsB,CAAC,GAAwB,CAChD;IACD,gBAAgB,EAAE,gDAAgD,CAChE,8BAAsB,CAAC,gBAAqC,CAC7D;IACD,oCAAoC,EAClC,gDAAgD,CAAC;QAC/C;YACE,GAAG,8BAAsB,CAAC,oCAAoC,CAAC,CAAC,CAAC;YACjE,QAAQ,EAAE;gBACR,IAAI,EAAE,4DAA4D;aACnE;SACF;KACmB,CAAC;IACzB,iCAAiC,EAC/B,gDAAgD,CAAC;QAC/C;YACE,GAAG,8BAAsB,CAAC,oCAAoC,CAAC,CAAC,CAAC;YACjE,QAAQ,EAAE;gBACR,IAAI,EAAE,yDAAyD;gBAC/D,iBAAiB,EAAE,CAAC;aACrB;SACF;KACmB,CAAC;CAC1B,CAAC","sourcesContent":["import { EthAccountType, type InternalAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\n\nimport { LOCALIZED_DEFAULT_ACCOUNT_NAMES } from '../accounts/constants';\nimport { mapInternalAccountToUserStorageAccount } from '../accounts/user-storage';\n\n/**\n * Map an array of internal accounts to an array of user storage accounts\n * Only used for testing purposes\n * @param internalAccounts - An array of internal accounts\n * @returns An array of user storage accounts\n */\nconst mapInternalAccountsListToUserStorageAccountsList = (\n internalAccounts: InternalAccount[],\n) => internalAccounts.map(mapInternalAccountToUserStorageAccount);\n\n/**\n * Get a random default account name from the list of localized default account names\n * @returns A random default account name\n */\nexport const getMockRandomDefaultAccountName = () =>\n LOCALIZED_DEFAULT_ACCOUNT_NAMES[\n Math.floor(Math.random() * LOCALIZED_DEFAULT_ACCOUNT_NAMES.length)\n ];\n\nexport const MOCK_INTERNAL_ACCOUNTS = {\n EMPTY: [],\n ONE: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'test',\n nameLastUpdatedAt: 1,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n ONE_DEFAULT_NAME: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: `${getMockRandomDefaultAccountName()} 1`,\n nameLastUpdatedAt: 1,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'Internal account custom name without nameLastUpdatedAt',\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'Internal account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 1,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED_MOST_RECENT: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'Internal account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 9999,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n ALL: [\n {\n address: '0x123',\n id: '1',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'test',\n nameLastUpdatedAt: 1,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n {\n address: '0x456',\n id: '2',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'Account 2',\n nameLastUpdatedAt: 2,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n {\n address: '0x789',\n id: '3',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'Účet 2',\n nameLastUpdatedAt: 3,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n {\n address: '0xabc',\n id: '4',\n type: EthAccountType.Eoa,\n metadata: {\n name: 'My Account 4',\n nameLastUpdatedAt: 4,\n keyring: {\n type: KeyringTypes.hd,\n },\n },\n },\n ],\n};\n\nexport const MOCK_USER_STORAGE_ACCOUNTS = {\n SAME_AS_INTERNAL_ALL: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ALL as InternalAccount[],\n ),\n ONE: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ONE as InternalAccount[],\n ),\n ONE_DEFAULT_NAME: mapInternalAccountsListToUserStorageAccountsList(\n MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME as InternalAccount[],\n ),\n ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED:\n mapInternalAccountsListToUserStorageAccountsList([\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED[0],\n metadata: {\n name: 'User storage account custom name without nameLastUpdatedAt',\n },\n },\n ] as InternalAccount[]),\n ONE_CUSTOM_NAME_WITH_LAST_UPDATED:\n mapInternalAccountsListToUserStorageAccountsList([\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED[0],\n metadata: {\n name: 'User storage account custom name with nameLastUpdatedAt',\n nameLastUpdatedAt: 3,\n },\n },\n ] as InternalAccount[]),\n};\n"]}
@@ -1,3 +1,5 @@
1
+ import { EthAccountType } from "@metamask/keyring-api";
2
+ import { KeyringTypes } from "@metamask/keyring-controller";
1
3
  /**
2
4
  * Get a random default account name from the list of localized default account names
3
5
  * @returns A random default account name
@@ -8,48 +10,72 @@ export declare const MOCK_INTERNAL_ACCOUNTS: {
8
10
  ONE: {
9
11
  address: string;
10
12
  id: string;
13
+ type: EthAccountType;
11
14
  metadata: {
12
15
  name: string;
13
16
  nameLastUpdatedAt: number;
17
+ keyring: {
18
+ type: KeyringTypes;
19
+ };
14
20
  };
15
21
  }[];
16
22
  ONE_DEFAULT_NAME: {
17
23
  address: string;
18
24
  id: string;
25
+ type: EthAccountType;
19
26
  metadata: {
20
27
  name: string;
21
28
  nameLastUpdatedAt: number;
29
+ keyring: {
30
+ type: KeyringTypes;
31
+ };
22
32
  };
23
33
  }[];
24
34
  ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: {
25
35
  address: string;
26
36
  id: string;
37
+ type: EthAccountType;
27
38
  metadata: {
28
39
  name: string;
40
+ keyring: {
41
+ type: KeyringTypes;
42
+ };
29
43
  };
30
44
  }[];
31
45
  ONE_CUSTOM_NAME_WITH_LAST_UPDATED: {
32
46
  address: string;
33
47
  id: string;
48
+ type: EthAccountType;
34
49
  metadata: {
35
50
  name: string;
36
51
  nameLastUpdatedAt: number;
52
+ keyring: {
53
+ type: KeyringTypes;
54
+ };
37
55
  };
38
56
  }[];
39
57
  ONE_CUSTOM_NAME_WITH_LAST_UPDATED_MOST_RECENT: {
40
58
  address: string;
41
59
  id: string;
60
+ type: EthAccountType;
42
61
  metadata: {
43
62
  name: string;
44
63
  nameLastUpdatedAt: number;
64
+ keyring: {
65
+ type: KeyringTypes;
66
+ };
45
67
  };
46
68
  }[];
47
69
  ALL: {
48
70
  address: string;
49
71
  id: string;
72
+ type: EthAccountType;
50
73
  metadata: {
51
74
  name: string;
52
75
  nameLastUpdatedAt: number;
76
+ keyring: {
77
+ type: KeyringTypes;
78
+ };
53
79
  };
54
80
  }[];
55
81
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mockAccounts.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":"AAeA;;;GAGG;AACH,eAAO,MAAM,+BAA+B,mbAGzC,CAAC;AAEJ,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqFlC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;CA6BtC,CAAC"}
1
+ {"version":3,"file":"mockAccounts.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,8BAA8B;AAC7E,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAe5D;;;GAGG;AACH,eAAO,MAAM,+BAA+B,mbAGzC,CAAC;AAEJ,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyHlC,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;CA6BtC,CAAC"}