@metamask/profile-sync-controller 1.0.0 → 1.0.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.
- package/CHANGELOG.md +16 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +56 -15
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +12 -2
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +12 -2
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +57 -16
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs +11 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts +1 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts +1 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs +11 -0
- package/dist/controllers/user-storage/__fixtures__/mockAccounts.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs +15 -7
- package/dist/controllers/user-storage/__fixtures__/mockResponses.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts +5 -0
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts +5 -0
- package/dist/controllers/user-storage/__fixtures__/mockResponses.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs +14 -7
- package/dist/controllers/user-storage/__fixtures__/mockResponses.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.cjs +18 -7
- package/dist/controllers/user-storage/__fixtures__/mockServices.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts +2 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts +2 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockServices.mjs +17 -7
- package/dist/controllers/user-storage/__fixtures__/mockServices.mjs.map +1 -1
- package/dist/controllers/user-storage/index.cjs +1 -0
- package/dist/controllers/user-storage/index.cjs.map +1 -1
- package/dist/controllers/user-storage/index.d.cts +1 -0
- package/dist/controllers/user-storage/index.d.cts.map +1 -1
- package/dist/controllers/user-storage/index.d.mts +1 -0
- package/dist/controllers/user-storage/index.d.mts.map +1 -1
- package/dist/controllers/user-storage/index.mjs +1 -0
- package/dist/controllers/user-storage/index.mjs.map +1 -1
- package/dist/controllers/user-storage/network-syncing/services.cjs +2 -1
- package/dist/controllers/user-storage/network-syncing/services.cjs.map +1 -1
- package/dist/controllers/user-storage/network-syncing/services.d.cts.map +1 -1
- package/dist/controllers/user-storage/network-syncing/services.d.mts.map +1 -1
- package/dist/controllers/user-storage/network-syncing/services.mjs +2 -1
- package/dist/controllers/user-storage/network-syncing/services.mjs.map +1 -1
- package/dist/controllers/user-storage/services.cjs +32 -1
- package/dist/controllers/user-storage/services.cjs.map +1 -1
- package/dist/controllers/user-storage/services.d.cts +10 -2
- package/dist/controllers/user-storage/services.d.cts.map +1 -1
- package/dist/controllers/user-storage/services.d.mts +10 -2
- package/dist/controllers/user-storage/services.d.mts.map +1 -1
- package/dist/controllers/user-storage/services.mjs +30 -0
- package/dist/controllers/user-storage/services.mjs.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.cjs +15 -3
- package/dist/sdk/__fixtures__/mock-userstorage.cjs.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.cts +1 -0
- package/dist/sdk/__fixtures__/mock-userstorage.d.cts.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.d.mts +1 -0
- package/dist/sdk/__fixtures__/mock-userstorage.d.mts.map +1 -1
- package/dist/sdk/__fixtures__/mock-userstorage.mjs +13 -2
- package/dist/sdk/__fixtures__/mock-userstorage.mjs.map +1 -1
- package/dist/sdk/index.cjs +1 -0
- package/dist/sdk/index.cjs.map +1 -1
- package/dist/sdk/index.d.cts +1 -0
- package/dist/sdk/index.d.cts.map +1 -1
- package/dist/sdk/index.d.mts +1 -0
- package/dist/sdk/index.d.mts.map +1 -1
- package/dist/sdk/index.mjs +1 -0
- package/dist/sdk/index.mjs.map +1 -1
- package/dist/sdk/user-storage.cjs +35 -1
- package/dist/sdk/user-storage.cjs.map +1 -1
- package/dist/sdk/user-storage.d.cts +3 -2
- package/dist/sdk/user-storage.d.cts.map +1 -1
- package/dist/sdk/user-storage.d.mts +3 -2
- package/dist/sdk/user-storage.d.mts.map +1 -1
- package/dist/sdk/user-storage.mjs +35 -1
- package/dist/sdk/user-storage.mjs.map +1 -1
- package/dist/shared/storage-schema.cjs +9 -4
- package/dist/shared/storage-schema.cjs.map +1 -1
- package/dist/shared/storage-schema.d.cts +12 -10
- package/dist/shared/storage-schema.d.cts.map +1 -1
- package/dist/shared/storage-schema.d.mts +12 -10
- package/dist/shared/storage-schema.d.mts.map +1 -1
- package/dist/shared/storage-schema.mjs +8 -3
- package/dist/shared/storage-schema.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -15,10 +15,11 @@ import $metamaskkeyringapi from "@metamask/keyring-api";
|
|
|
15
15
|
const { isEvmAccountType } = $metamaskkeyringapi;
|
|
16
16
|
import { KeyringTypes } from "@metamask/keyring-controller";
|
|
17
17
|
import { createSHA256Hash } from "../../shared/encryption/index.mjs";
|
|
18
|
+
import { USER_STORAGE_FEATURE_NAMES } from "../../shared/storage-schema.mjs";
|
|
18
19
|
import { createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
|
|
19
20
|
import { isNameDefaultAccountName, mapInternalAccountToUserStorageAccount } from "./accounts/user-storage.mjs";
|
|
20
21
|
import { startNetworkSyncing } from "./network-syncing/controller-integration.mjs";
|
|
21
|
-
import { batchUpsertUserStorage, deleteUserStorage, deleteUserStorageAllFeatureEntries, getUserStorage, getUserStorageAllFeatureEntries, upsertUserStorage } from "./services.mjs";
|
|
22
|
+
import { batchDeleteUserStorage, batchUpsertUserStorage, deleteUserStorage, deleteUserStorageAllFeatureEntries, getUserStorage, getUserStorageAllFeatureEntries, upsertUserStorage } from "./services.mjs";
|
|
22
23
|
const controllerName = 'UserStorageController';
|
|
23
24
|
export const defaultState = {
|
|
24
25
|
isProfileSyncingEnabled: true,
|
|
@@ -74,6 +75,7 @@ class UserStorageController extends BaseController {
|
|
|
74
75
|
isAccountSyncingEnabled: false,
|
|
75
76
|
isAccountSyncingInProgress: false,
|
|
76
77
|
maxNumberOfAccountsToAdd: 0,
|
|
78
|
+
hasSyncedAtLeastOnce: false,
|
|
77
79
|
canSync: () => {
|
|
78
80
|
try {
|
|
79
81
|
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
|
|
@@ -96,7 +98,8 @@ class UserStorageController extends BaseController {
|
|
|
96
98
|
this.messagingSystem.subscribe('AccountsController:accountAdded',
|
|
97
99
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
98
100
|
async (account) => {
|
|
99
|
-
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()
|
|
101
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
|
|
102
|
+
!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").hasSyncedAtLeastOnce) {
|
|
100
103
|
return;
|
|
101
104
|
}
|
|
102
105
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -104,7 +107,8 @@ class UserStorageController extends BaseController {
|
|
|
104
107
|
this.messagingSystem.subscribe('AccountsController:accountRenamed',
|
|
105
108
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
106
109
|
async (account) => {
|
|
107
|
-
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()
|
|
110
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync() ||
|
|
111
|
+
!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").hasSyncedAtLeastOnce) {
|
|
108
112
|
return;
|
|
109
113
|
}
|
|
110
114
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -119,14 +123,14 @@ class UserStorageController extends BaseController {
|
|
|
119
123
|
return internalAccountsList?.filter(__classPrivateFieldGet(this, _UserStorageController_accounts, "f").doesInternalAccountHaveCorrectKeyringType);
|
|
120
124
|
},
|
|
121
125
|
getUserStorageAccountsList: async () => {
|
|
122
|
-
const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries(
|
|
126
|
+
const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries(USER_STORAGE_FEATURE_NAMES.accounts);
|
|
123
127
|
return (rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??
|
|
124
128
|
null);
|
|
125
129
|
},
|
|
126
130
|
saveInternalAccountToUserStorage: async (internalAccount) => {
|
|
127
131
|
// Map the internal account to the user storage account schema
|
|
128
132
|
const mappedAccount = mapInternalAccountToUserStorageAccount(internalAccount);
|
|
129
|
-
await this.performSetStorage(
|
|
133
|
+
await this.performSetStorage(`${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`, JSON.stringify(mappedAccount));
|
|
130
134
|
},
|
|
131
135
|
saveInternalAccountsListToUserStorage: async () => {
|
|
132
136
|
const internalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
|
|
@@ -134,7 +138,7 @@ class UserStorageController extends BaseController {
|
|
|
134
138
|
return;
|
|
135
139
|
}
|
|
136
140
|
const internalAccountsListFormattedForUserStorage = internalAccountsList.map(mapInternalAccountToUserStorageAccount);
|
|
137
|
-
await this.performBatchSetStorage(
|
|
141
|
+
await this.performBatchSetStorage(USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsListFormattedForUserStorage.map((account) => [
|
|
138
142
|
account.a,
|
|
139
143
|
JSON.stringify(account),
|
|
140
144
|
]));
|
|
@@ -340,6 +344,24 @@ class UserStorageController extends BaseController {
|
|
|
340
344
|
storageKey,
|
|
341
345
|
});
|
|
342
346
|
}
|
|
347
|
+
/**
|
|
348
|
+
* Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.
|
|
349
|
+
* Developers can extend the entry path through the `schema.ts` file.
|
|
350
|
+
*
|
|
351
|
+
* @param path - string in the form of `${feature}` that matches schema
|
|
352
|
+
* @param values - data to store, in the form of an array of entryKey[]
|
|
353
|
+
* @returns nothing. NOTE that an error is thrown if fails to store data.
|
|
354
|
+
*/
|
|
355
|
+
async performBatchDeleteStorage(path, values) {
|
|
356
|
+
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
|
|
357
|
+
const { bearerToken, storageKey } = await __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_getStorageKeyAndBearerToken).call(this);
|
|
358
|
+
await batchDeleteUserStorage(values, {
|
|
359
|
+
path,
|
|
360
|
+
bearerToken,
|
|
361
|
+
storageKey,
|
|
362
|
+
nativeScryptCrypto: __classPrivateFieldGet(this, _UserStorageController_nativeScryptCrypto, "f"),
|
|
363
|
+
});
|
|
364
|
+
}
|
|
343
365
|
/**
|
|
344
366
|
* Retrieves the storage key, for internal use only!
|
|
345
367
|
*
|
|
@@ -371,14 +393,14 @@ class UserStorageController extends BaseController {
|
|
|
371
393
|
const internalAccountsToBeSavedToUserStorage = [];
|
|
372
394
|
// Compare internal accounts list with user storage accounts list
|
|
373
395
|
// First step: compare lengths
|
|
374
|
-
|
|
396
|
+
const internalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
|
|
375
397
|
if (!internalAccountsList || !internalAccountsList.length) {
|
|
376
398
|
throw new Error(`Failed to get internal accounts list`);
|
|
377
399
|
}
|
|
378
|
-
const
|
|
400
|
+
const hasMoreUserStorageAccountsThanInternalAccounts = userStorageAccountsList.length > internalAccountsList.length;
|
|
379
401
|
// We don't want to remove existing accounts for a user
|
|
380
|
-
// so we only add new accounts if the user has more accounts than
|
|
381
|
-
if (
|
|
402
|
+
// so we only add new accounts if the user has more accounts in user storage than internal accounts
|
|
403
|
+
if (hasMoreUserStorageAccountsThanInternalAccounts) {
|
|
382
404
|
const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, __classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd) - internalAccountsList.length;
|
|
383
405
|
// Create new accounts to match the user storage accounts list
|
|
384
406
|
for (let i = 0; i < numberOfAccountsToAdd; i++) {
|
|
@@ -388,13 +410,22 @@ class UserStorageController extends BaseController {
|
|
|
388
410
|
}
|
|
389
411
|
// Second step: compare account names
|
|
390
412
|
// Get the internal accounts list again since new accounts might have been added in the previous step
|
|
391
|
-
|
|
392
|
-
|
|
413
|
+
const refreshedInternalAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getInternalAccountsList();
|
|
414
|
+
const newlyAddedAccounts = refreshedInternalAccountsList.filter((account) => !internalAccountsList.find((a) => a.address === account.address));
|
|
415
|
+
for (const internalAccount of refreshedInternalAccountsList) {
|
|
393
416
|
const userStorageAccount = userStorageAccountsList.find((account) => account.a === internalAccount.address);
|
|
417
|
+
// If the account is not present in user storage
|
|
394
418
|
if (!userStorageAccount) {
|
|
419
|
+
// If the account was just added in the previous step, skip saving it, it's likely to be a bogus account
|
|
420
|
+
if (newlyAddedAccounts.includes(internalAccount)) {
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
// Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage
|
|
395
424
|
internalAccountsToBeSavedToUserStorage.push(internalAccount);
|
|
396
425
|
continue;
|
|
397
426
|
}
|
|
427
|
+
// From this point on, we know that the account is present in
|
|
428
|
+
// both the internal accounts list and the user storage accounts list
|
|
398
429
|
// One or both accounts have default names
|
|
399
430
|
const isInternalAccountNameDefault = isNameDefaultAccountName(internalAccount.metadata.name);
|
|
400
431
|
const isUserStorageAccountNameDefault = isNameDefaultAccountName(userStorageAccount.n);
|
|
@@ -441,10 +472,20 @@ class UserStorageController extends BaseController {
|
|
|
441
472
|
}
|
|
442
473
|
}
|
|
443
474
|
// Save the internal accounts list to the user storage
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
475
|
+
if (internalAccountsToBeSavedToUserStorage.length) {
|
|
476
|
+
await this.performBatchSetStorage(USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsToBeSavedToUserStorage.map((account) => [
|
|
477
|
+
account.address,
|
|
478
|
+
JSON.stringify(mapInternalAccountToUserStorageAccount(account)),
|
|
479
|
+
]));
|
|
480
|
+
}
|
|
481
|
+
// In case we have corrupted user storage with accounts that don't exist in the internal accounts list
|
|
482
|
+
// Delete those accounts from the user storage
|
|
483
|
+
const userStorageAccountsToBeDeleted = userStorageAccountsList.filter((account) => !refreshedInternalAccountsList.find((a) => a.address === account.a));
|
|
484
|
+
if (userStorageAccountsToBeDeleted.length) {
|
|
485
|
+
await this.performBatchDeleteStorage(USER_STORAGE_FEATURE_NAMES.accounts, userStorageAccountsToBeDeleted.map((account) => account.a));
|
|
486
|
+
}
|
|
487
|
+
// We add this here and not in the finally statement because we want to make sure that the accounts are saved before we set this flag
|
|
488
|
+
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").hasSyncedAtLeastOnce = true;
|
|
448
489
|
}
|
|
449
490
|
catch (e) {
|
|
450
491
|
const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":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,CAAC,CAAC;AACL,CAAC;eAhkBkB,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 deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\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 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\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 isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n maxNumberOfAccountsToAdd: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n if (this.#accounts.isAccountSyncingInProgress) {\n return false;\n }\n\n if (!this.#accounts.isAccountSyncingEnabled) {\n return false;\n }\n\n if (!this.#auth.isAuthEnabled()) {\n return false;\n }\n\n return true;\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.canSync()) {\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.canSync()) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\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.#accounts.maxNumberOfAccountsToAdd =\n config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;\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 * 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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\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 // 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 Math.min(\n userStorageAccountsList.length,\n this.#accounts.maxNumberOfAccountsToAdd,\n ) - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\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 (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 const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\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 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
|
+
{"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,EAAE,gBAAgB,EAAE,0CAAgC;AAE3D,OAAO,EACL,0BAA0B,EAG3B,wCAAoC;AAErC,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AASpF,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACvC,oCAAgC;AACjC,OAAO,EAAE,mBAAmB,EAAE,qDAAiD;AAC/E,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,iBAAiB,EACj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\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 { UserStorageFeatureKeys } from '../../shared/storage-schema';\nimport {\n USER_STORAGE_FEATURE_NAMES,\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 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 batchDeleteUserStorage,\n batchUpsertUserStorage,\n deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\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 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\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 isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n maxNumberOfAccountsToAdd: 0,\n hasSyncedAtLeastOnce: false,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n if (this.#accounts.isAccountSyncingInProgress) {\n return false;\n }\n\n if (!this.#accounts.isAccountSyncingEnabled) {\n return false;\n }\n\n if (!this.#auth.isAuthEnabled()) {\n return false;\n }\n\n return true;\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 (\n !this.#accounts.canSync() ||\n !this.#accounts.hasSyncedAtLeastOnce\n ) {\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 (\n !this.#accounts.canSync() ||\n !this.#accounts.hasSyncedAtLeastOnce\n ) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\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(\n USER_STORAGE_FEATURE_NAMES.accounts,\n );\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 `${USER_STORAGE_FEATURE_NAMES.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 USER_STORAGE_FEATURE_NAMES.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.#accounts.maxNumberOfAccountsToAdd =\n config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;\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 FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: [UserStorageFeatureKeys<FeatureName>, 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 * 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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n });\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 this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchDeleteUserStorage(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\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 const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\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(\n userStorageAccountsList.length,\n this.#accounts.maxNumberOfAccountsToAdd,\n ) - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\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 const refreshedInternalAccountsList =\n await this.#accounts.getInternalAccountsList();\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 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 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 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 const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\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 this.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 this.performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n );\n }\n\n // We add this here and not in the finally statement because we want to make sure that the accounts are saved before we set this flag\n this.#accounts.hasSyncedAtLeastOnce = true;\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"]}
|
|
@@ -143,6 +143,17 @@ exports.MOCK_INTERNAL_ACCOUNTS = {
|
|
|
143
143
|
exports.MOCK_USER_STORAGE_ACCOUNTS = {
|
|
144
144
|
SAME_AS_INTERNAL_ALL: mapInternalAccountsListToUserStorageAccountsList(exports.MOCK_INTERNAL_ACCOUNTS.ALL),
|
|
145
145
|
ONE: mapInternalAccountsListToUserStorageAccountsList(exports.MOCK_INTERNAL_ACCOUNTS.ONE),
|
|
146
|
+
TWO_DEFAULT_NAMES_WITH_ONE_BOGUS: mapInternalAccountsListToUserStorageAccountsList([
|
|
147
|
+
...exports.MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME,
|
|
148
|
+
{
|
|
149
|
+
...exports.MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME[0],
|
|
150
|
+
address: '0x000000',
|
|
151
|
+
metadata: {
|
|
152
|
+
name: `${(0, exports.getMockRandomDefaultAccountName)()} 1`,
|
|
153
|
+
nameLastUpdatedAt: 2,
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
]),
|
|
146
157
|
ONE_DEFAULT_NAME: mapInternalAccountsListToUserStorageAccountsList(exports.MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME),
|
|
147
158
|
ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: mapInternalAccountsListToUserStorageAccountsList([
|
|
148
159
|
{
|
|
@@ -1 +1 @@
|
|
|
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,E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AAgD,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
|
+
{"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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,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 TWO_DEFAULT_NAMES_WITH_ONE_BOGUS:\n mapInternalAccountsListToUserStorageAccountsList([\n ...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME,\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME[0],\n address: '0x000000',\n metadata: {\n name: `${getMockRandomDefaultAccountName()} 1`,\n nameLastUpdatedAt: 2,\n },\n },\n ] as InternalAccount[]),\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"]}
|
|
@@ -82,6 +82,7 @@ export declare const MOCK_INTERNAL_ACCOUNTS: {
|
|
|
82
82
|
export declare const MOCK_USER_STORAGE_ACCOUNTS: {
|
|
83
83
|
SAME_AS_INTERNAL_ALL: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
84
84
|
ONE: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
85
|
+
TWO_DEFAULT_NAMES_WITH_ONE_BOGUS: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
85
86
|
ONE_DEFAULT_NAME: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
86
87
|
ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
87
88
|
ONE_CUSTOM_NAME_WITH_LAST_UPDATED: import("../accounts/user-storage.cjs").UserStorageAccount[];
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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;;;;;;;CAyCtC,CAAC"}
|
|
@@ -82,6 +82,7 @@ export declare const MOCK_INTERNAL_ACCOUNTS: {
|
|
|
82
82
|
export declare const MOCK_USER_STORAGE_ACCOUNTS: {
|
|
83
83
|
SAME_AS_INTERNAL_ALL: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
84
84
|
ONE: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
85
|
+
TWO_DEFAULT_NAMES_WITH_ONE_BOGUS: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
85
86
|
ONE_DEFAULT_NAME: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
86
87
|
ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
87
88
|
ONE_CUSTOM_NAME_WITH_LAST_UPDATED: import("../accounts/user-storage.mjs").UserStorageAccount[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockAccounts.d.mts","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
|
|
1
|
+
{"version":3,"file":"mockAccounts.d.mts","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;;;;;;;CAyCtC,CAAC"}
|
|
@@ -140,6 +140,17 @@ export const MOCK_INTERNAL_ACCOUNTS = {
|
|
|
140
140
|
export const MOCK_USER_STORAGE_ACCOUNTS = {
|
|
141
141
|
SAME_AS_INTERNAL_ALL: mapInternalAccountsListToUserStorageAccountsList(MOCK_INTERNAL_ACCOUNTS.ALL),
|
|
142
142
|
ONE: mapInternalAccountsListToUserStorageAccountsList(MOCK_INTERNAL_ACCOUNTS.ONE),
|
|
143
|
+
TWO_DEFAULT_NAMES_WITH_ONE_BOGUS: mapInternalAccountsListToUserStorageAccountsList([
|
|
144
|
+
...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME,
|
|
145
|
+
{
|
|
146
|
+
...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME[0],
|
|
147
|
+
address: '0x000000',
|
|
148
|
+
metadata: {
|
|
149
|
+
name: `${getMockRandomDefaultAccountName()} 1`,
|
|
150
|
+
nameLastUpdatedAt: 2,
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
]),
|
|
143
154
|
ONE_DEFAULT_NAME: mapInternalAccountsListToUserStorageAccountsList(MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME),
|
|
144
155
|
ONE_CUSTOM_NAME_WITHOUT_LAST_UPDATED: mapInternalAccountsListToUserStorageAccountsList([
|
|
145
156
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockAccounts.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAE5D,OAAO,EAAE,+BAA+B,EAAE,kCAA8B;AACxE,OAAO,EAAE,sCAAsC,EAAE,qCAAiC;AAElF;;;;;GAKG;AACH,MAAM,gDAAgD,GAAG,CACvD,gBAAmC,EACnC,EAAE,CAAC,gBAAgB,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAAG,EAAE,CAClD,+BAA+B,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,+BAA+B,CAAC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,GAAwB,CAChD;IACD,gBAAgB,EAAE,gDAAgD,CAChE,sBAAsB,CAAC,gBAAqC,CAC7D;IACD,oCAAoC,EAClC,gDAAgD,CAAC;QAC/C;YACE,GAAG,sBAAsB,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,sBAAsB,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
|
+
{"version":3,"file":"mockAccounts.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockAccounts.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAE5D,OAAO,EAAE,+BAA+B,EAAE,kCAA8B;AACxE,OAAO,EAAE,sCAAsC,EAAE,qCAAiC;AAElF;;;;;GAKG;AACH,MAAM,gDAAgD,GAAG,CACvD,gBAAmC,EACnC,EAAE,CAAC,gBAAgB,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAAG,EAAE,CAClD,+BAA+B,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,+BAA+B,CAAC,MAAM,CAAC,CACnE,CAAC;AAEJ,MAAM,CAAC,MAAM,sBAAsB,GAAG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BAAsB,CAAC,gBAAgB;QAC1C;YACE,GAAG,sBAAsB,CAAC,gBAAgB,CAAC,CAAC,CAAC;YAC7C,OAAO,EAAE,UAAU;YACnB,QAAQ,EAAE;gBACR,IAAI,EAAE,GAAG,+BAA+B,EAAE,IAAI;gBAC9C,iBAAiB,EAAE,CAAC;aACrB;SACF;KACmB,CAAC;IACzB,gBAAgB,EAAE,gDAAgD,CAChE,sBAAsB,CAAC,gBAAqC,CAC7D;IACD,oCAAoC,EAClC,gDAAgD,CAAC;QAC/C;YACE,GAAG,sBAAsB,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,sBAAsB,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 TWO_DEFAULT_NAMES_WITH_ONE_BOGUS:\n mapInternalAccountsListToUserStorageAccountsList([\n ...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME,\n {\n ...MOCK_INTERNAL_ACCOUNTS.ONE_DEFAULT_NAME[0],\n address: '0x000000',\n metadata: {\n name: `${getMockRandomDefaultAccountName()} 1`,\n nameLastUpdatedAt: 2,\n },\n },\n ] as InternalAccount[]),\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"]}
|