@metamask-previews/profile-sync-controller 7.0.1-preview-cd1fb95d → 7.0.1-preview-74b4a89
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/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +2 -2
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +2 -2
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.cjs +5 -5
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.cjs.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.cts +3 -3
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.cts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.mts +3 -3
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.d.mts.map +1 -1
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.mjs +5 -5
- package/dist/controllers/user-storage/__fixtures__/mockMessenger.mjs.map +1 -1
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.cjs +1 -1
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.cjs.map +1 -1
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.cts +2 -2
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.d.mts +2 -2
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.mjs +1 -1
- package/dist/controllers/user-storage/account-syncing/__fixtures__/test-utils.mjs.map +1 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +7 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +1 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts.map +1 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts.map +1 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +7 -1
- package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +1 -1
- package/dist/sdk/user-storage.cjs +9 -3
- package/dist/sdk/user-storage.cjs.map +1 -1
- package/dist/sdk/user-storage.d.cts +8 -8
- package/dist/sdk/user-storage.d.cts.map +1 -1
- package/dist/sdk/user-storage.d.mts +8 -8
- package/dist/sdk/user-storage.d.mts.map +1 -1
- package/dist/sdk/user-storage.mjs +9 -3
- package/dist/sdk/user-storage.mjs.map +1 -1
- package/dist/shared/storage-schema.cjs +18 -11
- package/dist/shared/storage-schema.cjs.map +1 -1
- package/dist/shared/storage-schema.d.cts +24 -2
- package/dist/shared/storage-schema.d.cts.map +1 -1
- package/dist/shared/storage-schema.d.mts +24 -2
- package/dist/shared/storage-schema.d.mts.map +1 -1
- package/dist/shared/storage-schema.mjs +18 -11
- package/dist/shared/storage-schema.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -32,7 +32,7 @@ export declare function createCustomUserStorageMessenger(props?: {
|
|
|
32
32
|
identifierId: string;
|
|
33
33
|
profileId: string;
|
|
34
34
|
}>;
|
|
35
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
35
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../index.cjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
36
36
|
};
|
|
37
37
|
type OverrideMessengers = {
|
|
38
38
|
baseMessenger: Messenger<AllowedActions, AllowedEvents>;
|
|
@@ -64,7 +64,7 @@ export declare function mockUserStorageMessenger(overrideMessengers?: OverrideMe
|
|
|
64
64
|
identifierId: string;
|
|
65
65
|
profileId: string;
|
|
66
66
|
}>;
|
|
67
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
67
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../index.cjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
68
68
|
mockSnapGetPublicKey: jest.Mock<any, any>;
|
|
69
69
|
mockSnapSignMessage: jest.Mock<any, any>;
|
|
70
70
|
mockAuthGetBearerToken: jest.Mock<Promise<string>, []>;
|
|
@@ -75,7 +75,7 @@ export declare function mockUserStorageMessenger(overrideMessengers?: OverrideMe
|
|
|
75
75
|
mockAuthPerformSignIn: jest.Mock<Promise<string>, []>;
|
|
76
76
|
mockAuthIsSignedIn: jest.Mock<boolean, []>;
|
|
77
77
|
mockAuthPerformSignOut: jest.Mock<void, []>;
|
|
78
|
-
|
|
78
|
+
mockKeyringWithKeyring: jest.Mock<Promise<unknown>, [selector: import("@metamask/keyring-controller").KeyringSelector, operation: (keyring: import("@metamask/keyring-internal-api").EthKeyring<import("@metamask/utils").Json>) => Promise<unknown>]>;
|
|
79
79
|
mockAccountsUpdateAccountMetadata: jest.Mock<void, [accountId: string, metadata: Partial<{
|
|
80
80
|
name: string;
|
|
81
81
|
importTime: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockMessenger.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kCAAkC;AACjE,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAGtD,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,8BAA8B,EAC/B,qBAAW;AAyBZ,KAAK,cAAc,GAAG,eAAe,CACnC,uBAAuB,EACvB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,CAAC,EAAE;IACvD,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;CACnC;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"mockMessenger.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kCAAkC;AACjE,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAGtD,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,8BAA8B,EAC/B,qBAAW;AAyBZ,KAAK,cAAc,GAAG,eAAe,CACnC,uBAAuB,EACvB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,CAAC,EAAE;IACvD,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;CACnC;;;;;;;;;;;;;;;;;;;;;EAgCA;AAED,KAAK,kBAAkB,GAAG;IACxB,aAAa,EAAE,SAAS,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;IACxD,SAAS,EAAE,8BAA8B,CAAC;CAC3C,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,kBAAkB,CAAC,EAAE,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoKxC"}
|
|
@@ -32,7 +32,7 @@ export declare function createCustomUserStorageMessenger(props?: {
|
|
|
32
32
|
identifierId: string;
|
|
33
33
|
profileId: string;
|
|
34
34
|
}>;
|
|
35
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
35
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../index.mjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
36
36
|
};
|
|
37
37
|
type OverrideMessengers = {
|
|
38
38
|
baseMessenger: Messenger<AllowedActions, AllowedEvents>;
|
|
@@ -64,7 +64,7 @@ export declare function mockUserStorageMessenger(overrideMessengers?: OverrideMe
|
|
|
64
64
|
identifierId: string;
|
|
65
65
|
profileId: string;
|
|
66
66
|
}>;
|
|
67
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
67
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../index.mjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
68
68
|
mockSnapGetPublicKey: jest.Mock<any, any>;
|
|
69
69
|
mockSnapSignMessage: jest.Mock<any, any>;
|
|
70
70
|
mockAuthGetBearerToken: jest.Mock<Promise<string>, []>;
|
|
@@ -75,7 +75,7 @@ export declare function mockUserStorageMessenger(overrideMessengers?: OverrideMe
|
|
|
75
75
|
mockAuthPerformSignIn: jest.Mock<Promise<string>, []>;
|
|
76
76
|
mockAuthIsSignedIn: jest.Mock<boolean, []>;
|
|
77
77
|
mockAuthPerformSignOut: jest.Mock<void, []>;
|
|
78
|
-
|
|
78
|
+
mockKeyringWithKeyring: jest.Mock<Promise<unknown>, [selector: import("@metamask/keyring-controller").KeyringSelector, operation: (keyring: import("@metamask/keyring-internal-api").EthKeyring<import("@metamask/utils").Json>) => Promise<unknown>]>;
|
|
79
79
|
mockAccountsUpdateAccountMetadata: jest.Mock<void, [accountId: string, metadata: Partial<{
|
|
80
80
|
name: string;
|
|
81
81
|
importTime: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockMessenger.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kCAAkC;AACjE,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAGtD,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,8BAA8B,EAC/B,qBAAW;AAyBZ,KAAK,cAAc,GAAG,eAAe,CACnC,uBAAuB,EACvB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,CAAC,EAAE;IACvD,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;CACnC;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"mockMessenger.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kCAAkC;AACjE,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAGtD,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,8BAA8B,EAC/B,qBAAW;AAyBZ,KAAK,cAAc,GAAG,eAAe,CACnC,uBAAuB,EACvB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,CAAC,EAAE;IACvD,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;CACnC;;;;;;;;;;;;;;;;;;;;;EAgCA;AAED,KAAK,kBAAkB,GAAG;IACxB,aAAa,EAAE,SAAS,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;IACxD,SAAS,EAAE,8BAA8B,CAAC;CAC3C,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,kBAAkB,CAAC,EAAE,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoKxC"}
|
|
@@ -14,7 +14,6 @@ export function createCustomUserStorageMessenger(props) {
|
|
|
14
14
|
name: 'UserStorageController',
|
|
15
15
|
allowedActions: [
|
|
16
16
|
'KeyringController:getState',
|
|
17
|
-
'KeyringController:addNewAccount',
|
|
18
17
|
'SnapController:handleRequest',
|
|
19
18
|
'AuthenticationController:getBearerToken',
|
|
20
19
|
'AuthenticationController:getSessionProfile',
|
|
@@ -61,7 +60,7 @@ export function mockUserStorageMessenger(overrideMessengers) {
|
|
|
61
60
|
const mockAuthPerformSignIn = typedMockFn('AuthenticationController:performSignIn').mockResolvedValue('New Access Token');
|
|
62
61
|
const mockAuthIsSignedIn = typedMockFn('AuthenticationController:isSignedIn').mockReturnValue(true);
|
|
63
62
|
const mockAuthPerformSignOut = typedMockFn('AuthenticationController:performSignOut');
|
|
64
|
-
const
|
|
63
|
+
const mockKeyringWithKeyring = typedMockFn('KeyringController:withKeyring');
|
|
65
64
|
// Untyped mock as there is a TS(2742) issue.
|
|
66
65
|
// This will return `InternalAccount[]`
|
|
67
66
|
const mockAccountsListAccounts = jest.fn();
|
|
@@ -105,8 +104,9 @@ export function mockUserStorageMessenger(overrideMessengers) {
|
|
|
105
104
|
if (actionType === 'KeyringController:getState') {
|
|
106
105
|
return { isUnlocked: true };
|
|
107
106
|
}
|
|
108
|
-
if (actionType === 'KeyringController:
|
|
109
|
-
|
|
107
|
+
if (actionType === 'KeyringController:withKeyring') {
|
|
108
|
+
const [, ...params] = typedArgs;
|
|
109
|
+
return mockKeyringWithKeyring(...params);
|
|
110
110
|
}
|
|
111
111
|
if (actionType === 'AccountsController:listAccounts') {
|
|
112
112
|
return mockAccountsListAccounts();
|
|
@@ -142,7 +142,7 @@ export function mockUserStorageMessenger(overrideMessengers) {
|
|
|
142
142
|
mockAuthPerformSignIn,
|
|
143
143
|
mockAuthIsSignedIn,
|
|
144
144
|
mockAuthPerformSignOut,
|
|
145
|
-
|
|
145
|
+
mockKeyringWithKeyring,
|
|
146
146
|
mockAccountsUpdateAccountMetadata,
|
|
147
147
|
mockAccountsListAccounts,
|
|
148
148
|
mockNetworkControllerGetState,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockMessenger.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAEtD,OAAO,EAAE,0BAA0B,EAAE,oBAAU;AAmB/C,MAAM,WAAW,GAAG,CAQlB,KAAiB,EACjB,EAAE,CAAC,IAAI,CAAC,EAAE,EAAsC,CAAC;AAOnD;;;;;;GAMG;AACH,MAAM,UAAU,gCAAgC,CAAC,KAEhD;IACC,MAAM,aAAa,GAAG,IAAI,SAAS,EAAiC,CAAC;IACrE,MAAM,SAAS,GAAG,aAAa,CAAC,aAAa,CAAC;QAC5C,IAAI,EAAE,uBAAuB;QAC7B,cAAc,EAAE;YACd,4BAA4B;YAC5B,iCAAiC;YACjC,8BAA8B;YAC9B,yCAAyC;YACzC,4CAA4C;YAC5C,qCAAqC;YACrC,yCAAyC;YACzC,wCAAwC;YACxC,iCAAiC;YACjC,0CAA0C;YAC1C,4BAA4B;YAC5B,8BAA8B;YAC9B,iCAAiC;YACjC,iCAAiC;SAClC;QACD,aAAa,EAAE,KAAK,EAAE,cAAc,IAAI;YACtC,wBAAwB;YACxB,0BAA0B;YAC1B,iCAAiC;YACjC,mCAAmC;YACnC,kCAAkC;SACnC;KACF,CAAC,CAAC;IAEH,OAAO;QACL,aAAa;QACb,SAAS;KACV,CAAC;AACJ,CAAC;AAOD;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,kBAAuC;IAEvC,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,GAChC,kBAAkB,IAAI,gCAAgC,EAAE,CAAC;IAE3D,MAAM,oBAAoB,GAAG,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,CAAC,CAAC,KAAK,0CAA0C,EAAE;YAC/D,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,iCAAiC,CAAC,GAAG,MAAM,CAAC,CAAC;SACrD;QAED,IAAI,UAAU,KAAK,4BAA4B,EAAE;YAC/C,OAAO,6BAA6B,EAAE,CAAC;SACxC;QAED,IAAI,UAAU,KAAK,8BAA8B,EAAE;YACjD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,+BAA+B,CAAC,GAAG,MAAM,CAAC,CAAC;SACnD;QAED,IAAI,UAAU,KAAK,iCAAiC,EAAE;YACpD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,kCAAkC,CAAC,GAAG,MAAM,CAAC,CAAC;SACtD;QAED,IAAI,UAAU,KAAK,iCAAiC,EAAE;YACpD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,kCAAkC,CAAC,GAAG,MAAM,CAAC,CAAC;SACtD;QAED,MAAM,IAAI,KAAK,CACb,2CAA2C,UAAoB,EAAE,CAClE,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,aAAa;QACb,SAAS;QACT,oBAAoB;QACpB,mBAAmB;QACnB,sBAAsB;QACtB,yBAAyB;QACzB,qBAAqB;QACrB,kBAAkB;QAClB,sBAAsB;QACtB,wBAAwB;QACxB,iCAAiC;QACjC,wBAAwB;QACxB,6BAA6B;QAC7B,+BAA+B;QAC/B,kCAAkC;QAClC,kCAAkC;KACnC,CAAC;AACJ,CAAC","sourcesContent":["import type { NotNamespacedBy } from '@metamask/base-controller';\nimport { Messenger } from '@metamask/base-controller';\n\nimport { MOCK_STORAGE_KEY_SIGNATURE } from '.';\nimport type {\n AllowedActions,\n AllowedEvents,\n UserStorageControllerMessenger,\n} from '..';\n\ntype GetHandler<ActionType extends AllowedActions['type']> = Extract<\n AllowedActions,\n { type: ActionType }\n>['handler'];\n\ntype CallParams = {\n [K in AllowedActions['type']]: [\n K,\n ...Parameters<Extract<AllowedActions, { type: K }>['handler']>,\n ];\n}[AllowedActions['type']];\n\nconst typedMockFn = <\n ActionType extends AllowedActions['type'],\n Handler = GetHandler<ActionType>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Func extends (...args: any) => any = Handler extends (...args: any[]) => any\n ? Handler\n : never,\n>(\n _type: ActionType,\n) => jest.fn<ReturnType<Func>, Parameters<Func>>();\n\ntype ExternalEvents = NotNamespacedBy<\n 'UserStorageController',\n AllowedEvents['type']\n>;\n\n/**\n * creates a custom user storage messenger, in case tests need different permissions\n *\n * @param props - overrides\n * @param props.overrideEvents - override events\n * @returns base messenger, and messenger. You can pass this into the mocks below to mock messenger calls\n */\nexport function createCustomUserStorageMessenger(props?: {\n overrideEvents?: ExternalEvents[];\n}) {\n const baseMessenger = new Messenger<AllowedActions, AllowedEvents>();\n const messenger = baseMessenger.getRestricted({\n name: 'UserStorageController',\n allowedActions: [\n 'KeyringController:getState',\n 'KeyringController:addNewAccount',\n 'SnapController:handleRequest',\n 'AuthenticationController:getBearerToken',\n 'AuthenticationController:getSessionProfile',\n 'AuthenticationController:isSignedIn',\n 'AuthenticationController:performSignOut',\n 'AuthenticationController:performSignIn',\n 'AccountsController:listAccounts',\n 'AccountsController:updateAccountMetadata',\n 'NetworkController:getState',\n 'NetworkController:addNetwork',\n 'NetworkController:updateNetwork',\n 'NetworkController:removeNetwork',\n ],\n allowedEvents: props?.overrideEvents ?? [\n 'KeyringController:lock',\n 'KeyringController:unlock',\n 'AccountsController:accountAdded',\n 'AccountsController:accountRenamed',\n 'NetworkController:networkRemoved',\n ],\n });\n\n return {\n baseMessenger,\n messenger,\n };\n}\n\ntype OverrideMessengers = {\n baseMessenger: Messenger<AllowedActions, AllowedEvents>;\n messenger: UserStorageControllerMessenger;\n};\n\n/**\n * Jest Mock Utility to generate a mock User Storage Messenger\n *\n * @param overrideMessengers - override messengers if need to modify the underlying permissions\n * @returns series of mocks to actions that can be called\n */\nexport function mockUserStorageMessenger(\n overrideMessengers?: OverrideMessengers,\n) {\n const { baseMessenger, messenger } =\n overrideMessengers ?? createCustomUserStorageMessenger();\n\n const mockSnapGetPublicKey = jest.fn().mockResolvedValue('MOCK_PUBLIC_KEY');\n const mockSnapSignMessage = jest\n .fn()\n .mockResolvedValue(MOCK_STORAGE_KEY_SIGNATURE);\n\n const mockAuthGetBearerToken = typedMockFn(\n 'AuthenticationController:getBearerToken',\n ).mockResolvedValue('MOCK_BEARER_TOKEN');\n\n const mockAuthGetSessionProfile = typedMockFn(\n 'AuthenticationController:getSessionProfile',\n ).mockResolvedValue({\n identifierId: '',\n profileId: 'MOCK_PROFILE_ID',\n });\n\n const mockAuthPerformSignIn = typedMockFn(\n 'AuthenticationController:performSignIn',\n ).mockResolvedValue('New Access Token');\n\n const mockAuthIsSignedIn = typedMockFn(\n 'AuthenticationController:isSignedIn',\n ).mockReturnValue(true);\n\n const mockAuthPerformSignOut = typedMockFn(\n 'AuthenticationController:performSignOut',\n );\n\n const mockKeyringAddNewAccount = typedMockFn(\n 'KeyringController:addNewAccount',\n );\n\n // Untyped mock as there is a TS(2742) issue.\n // This will return `InternalAccount[]`\n const mockAccountsListAccounts = jest.fn();\n\n const mockAccountsUpdateAccountMetadata = typedMockFn(\n 'AccountsController:updateAccountMetadata',\n ).mockResolvedValue(true as never);\n\n const mockNetworkControllerGetState = typedMockFn(\n 'NetworkController:getState',\n ).mockReturnValue({\n selectedNetworkClientId: '',\n networksMetadata: {},\n networkConfigurationsByChainId: {},\n });\n\n const mockNetworkControllerAddNetwork = typedMockFn(\n 'NetworkController:addNetwork',\n );\n\n const mockNetworkControllerRemoveNetwork = typedMockFn(\n 'NetworkController:removeNetwork',\n );\n\n const mockNetworkControllerUpdateNetwork = typedMockFn(\n 'NetworkController:updateNetwork',\n );\n\n jest.spyOn(messenger, 'call').mockImplementation((...args) => {\n const typedArgs = args as unknown as CallParams;\n const [actionType] = typedArgs;\n\n if (actionType === 'SnapController:handleRequest') {\n const [, params] = typedArgs;\n if (params.request.method === 'getPublicKey') {\n return mockSnapGetPublicKey();\n }\n\n if (params.request.method === 'signMessage') {\n return mockSnapSignMessage();\n }\n\n throw new Error(\n `MOCK_FAIL - unsupported SnapController:handleRequest call: ${\n params.request.method as string\n }`,\n );\n }\n\n if (actionType === 'AuthenticationController:getBearerToken') {\n return mockAuthGetBearerToken();\n }\n\n if (actionType === 'AuthenticationController:getSessionProfile') {\n return mockAuthGetSessionProfile();\n }\n\n if (actionType === 'AuthenticationController:performSignIn') {\n return mockAuthPerformSignIn();\n }\n\n if (actionType === 'AuthenticationController:isSignedIn') {\n return mockAuthIsSignedIn();\n }\n\n if (actionType === 'AuthenticationController:performSignOut') {\n return mockAuthPerformSignOut();\n }\n\n if (actionType === 'KeyringController:getState') {\n return { isUnlocked: true };\n }\n\n if (actionType === 'KeyringController:addNewAccount') {\n return mockKeyringAddNewAccount();\n }\n\n if (actionType === 'AccountsController:listAccounts') {\n return mockAccountsListAccounts();\n }\n\n if (typedArgs[0] === 'AccountsController:updateAccountMetadata') {\n const [, ...params] = typedArgs;\n return mockAccountsUpdateAccountMetadata(...params);\n }\n\n if (actionType === 'NetworkController:getState') {\n return mockNetworkControllerGetState();\n }\n\n if (actionType === 'NetworkController:addNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerAddNetwork(...params);\n }\n\n if (actionType === 'NetworkController:removeNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerRemoveNetwork(...params);\n }\n\n if (actionType === 'NetworkController:updateNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerUpdateNetwork(...params);\n }\n\n throw new Error(\n `MOCK_FAIL - unsupported messenger call: ${actionType as string}`,\n );\n });\n\n return {\n baseMessenger,\n messenger,\n mockSnapGetPublicKey,\n mockSnapSignMessage,\n mockAuthGetBearerToken,\n mockAuthGetSessionProfile,\n mockAuthPerformSignIn,\n mockAuthIsSignedIn,\n mockAuthPerformSignOut,\n mockKeyringAddNewAccount,\n mockAccountsUpdateAccountMetadata,\n mockAccountsListAccounts,\n mockNetworkControllerGetState,\n mockNetworkControllerAddNetwork,\n mockNetworkControllerRemoveNetwork,\n mockNetworkControllerUpdateNetwork,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mockMessenger.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/__fixtures__/mockMessenger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAEtD,OAAO,EAAE,0BAA0B,EAAE,oBAAU;AAmB/C,MAAM,WAAW,GAAG,CAQlB,KAAiB,EACjB,EAAE,CAAC,IAAI,CAAC,EAAE,EAAsC,CAAC;AAOnD;;;;;;GAMG;AACH,MAAM,UAAU,gCAAgC,CAAC,KAEhD;IACC,MAAM,aAAa,GAAG,IAAI,SAAS,EAAiC,CAAC;IACrE,MAAM,SAAS,GAAG,aAAa,CAAC,aAAa,CAAC;QAC5C,IAAI,EAAE,uBAAuB;QAC7B,cAAc,EAAE;YACd,4BAA4B;YAC5B,8BAA8B;YAC9B,yCAAyC;YACzC,4CAA4C;YAC5C,qCAAqC;YACrC,yCAAyC;YACzC,wCAAwC;YACxC,iCAAiC;YACjC,0CAA0C;YAC1C,4BAA4B;YAC5B,8BAA8B;YAC9B,iCAAiC;YACjC,iCAAiC;SAClC;QACD,aAAa,EAAE,KAAK,EAAE,cAAc,IAAI;YACtC,wBAAwB;YACxB,0BAA0B;YAC1B,iCAAiC;YACjC,mCAAmC;YACnC,kCAAkC;SACnC;KACF,CAAC,CAAC;IAEH,OAAO;QACL,aAAa;QACb,SAAS;KACV,CAAC;AACJ,CAAC;AAOD;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,kBAAuC;IAEvC,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,GAChC,kBAAkB,IAAI,gCAAgC,EAAE,CAAC;IAE3D,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C;QAED,IAAI,UAAU,KAAK,iCAAiC,EAAE;YACpD,OAAO,wBAAwB,EAAE,CAAC;SACnC;QAED,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,0CAA0C,EAAE;YAC/D,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,iCAAiC,CAAC,GAAG,MAAM,CAAC,CAAC;SACrD;QAED,IAAI,UAAU,KAAK,4BAA4B,EAAE;YAC/C,OAAO,6BAA6B,EAAE,CAAC;SACxC;QAED,IAAI,UAAU,KAAK,8BAA8B,EAAE;YACjD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,+BAA+B,CAAC,GAAG,MAAM,CAAC,CAAC;SACnD;QAED,IAAI,UAAU,KAAK,iCAAiC,EAAE;YACpD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,kCAAkC,CAAC,GAAG,MAAM,CAAC,CAAC;SACtD;QAED,IAAI,UAAU,KAAK,iCAAiC,EAAE;YACpD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;YAChC,OAAO,kCAAkC,CAAC,GAAG,MAAM,CAAC,CAAC;SACtD;QAED,MAAM,IAAI,KAAK,CACb,2CAA2C,UAAoB,EAAE,CAClE,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,aAAa;QACb,SAAS;QACT,oBAAoB;QACpB,mBAAmB;QACnB,sBAAsB;QACtB,yBAAyB;QACzB,qBAAqB;QACrB,kBAAkB;QAClB,sBAAsB;QACtB,sBAAsB;QACtB,iCAAiC;QACjC,wBAAwB;QACxB,6BAA6B;QAC7B,+BAA+B;QAC/B,kCAAkC;QAClC,kCAAkC;KACnC,CAAC;AACJ,CAAC","sourcesContent":["import type { NotNamespacedBy } from '@metamask/base-controller';\nimport { Messenger } from '@metamask/base-controller';\n\nimport { MOCK_STORAGE_KEY_SIGNATURE } from '.';\nimport type {\n AllowedActions,\n AllowedEvents,\n UserStorageControllerMessenger,\n} from '..';\n\ntype GetHandler<ActionType extends AllowedActions['type']> = Extract<\n AllowedActions,\n { type: ActionType }\n>['handler'];\n\ntype CallParams = {\n [K in AllowedActions['type']]: [\n K,\n ...Parameters<Extract<AllowedActions, { type: K }>['handler']>,\n ];\n}[AllowedActions['type']];\n\nconst typedMockFn = <\n ActionType extends AllowedActions['type'],\n Handler = GetHandler<ActionType>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Func extends (...args: any) => any = Handler extends (...args: any[]) => any\n ? Handler\n : never,\n>(\n _type: ActionType,\n) => jest.fn<ReturnType<Func>, Parameters<Func>>();\n\ntype ExternalEvents = NotNamespacedBy<\n 'UserStorageController',\n AllowedEvents['type']\n>;\n\n/**\n * creates a custom user storage messenger, in case tests need different permissions\n *\n * @param props - overrides\n * @param props.overrideEvents - override events\n * @returns base messenger, and messenger. You can pass this into the mocks below to mock messenger calls\n */\nexport function createCustomUserStorageMessenger(props?: {\n overrideEvents?: ExternalEvents[];\n}) {\n const baseMessenger = new Messenger<AllowedActions, AllowedEvents>();\n const messenger = baseMessenger.getRestricted({\n name: 'UserStorageController',\n allowedActions: [\n 'KeyringController:getState',\n 'SnapController:handleRequest',\n 'AuthenticationController:getBearerToken',\n 'AuthenticationController:getSessionProfile',\n 'AuthenticationController:isSignedIn',\n 'AuthenticationController:performSignOut',\n 'AuthenticationController:performSignIn',\n 'AccountsController:listAccounts',\n 'AccountsController:updateAccountMetadata',\n 'NetworkController:getState',\n 'NetworkController:addNetwork',\n 'NetworkController:updateNetwork',\n 'NetworkController:removeNetwork',\n ],\n allowedEvents: props?.overrideEvents ?? [\n 'KeyringController:lock',\n 'KeyringController:unlock',\n 'AccountsController:accountAdded',\n 'AccountsController:accountRenamed',\n 'NetworkController:networkRemoved',\n ],\n });\n\n return {\n baseMessenger,\n messenger,\n };\n}\n\ntype OverrideMessengers = {\n baseMessenger: Messenger<AllowedActions, AllowedEvents>;\n messenger: UserStorageControllerMessenger;\n};\n\n/**\n * Jest Mock Utility to generate a mock User Storage Messenger\n *\n * @param overrideMessengers - override messengers if need to modify the underlying permissions\n * @returns series of mocks to actions that can be called\n */\nexport function mockUserStorageMessenger(\n overrideMessengers?: OverrideMessengers,\n) {\n const { baseMessenger, messenger } =\n overrideMessengers ?? createCustomUserStorageMessenger();\n\n const mockSnapGetPublicKey = jest.fn().mockResolvedValue('MOCK_PUBLIC_KEY');\n const mockSnapSignMessage = jest\n .fn()\n .mockResolvedValue(MOCK_STORAGE_KEY_SIGNATURE);\n\n const mockAuthGetBearerToken = typedMockFn(\n 'AuthenticationController:getBearerToken',\n ).mockResolvedValue('MOCK_BEARER_TOKEN');\n\n const mockAuthGetSessionProfile = typedMockFn(\n 'AuthenticationController:getSessionProfile',\n ).mockResolvedValue({\n identifierId: '',\n profileId: 'MOCK_PROFILE_ID',\n });\n\n const mockAuthPerformSignIn = typedMockFn(\n 'AuthenticationController:performSignIn',\n ).mockResolvedValue('New Access Token');\n\n const mockAuthIsSignedIn = typedMockFn(\n 'AuthenticationController:isSignedIn',\n ).mockReturnValue(true);\n\n const mockAuthPerformSignOut = typedMockFn(\n 'AuthenticationController:performSignOut',\n );\n\n const mockKeyringWithKeyring = typedMockFn('KeyringController:withKeyring');\n\n // Untyped mock as there is a TS(2742) issue.\n // This will return `InternalAccount[]`\n const mockAccountsListAccounts = jest.fn();\n\n const mockAccountsUpdateAccountMetadata = typedMockFn(\n 'AccountsController:updateAccountMetadata',\n ).mockResolvedValue(true as never);\n\n const mockNetworkControllerGetState = typedMockFn(\n 'NetworkController:getState',\n ).mockReturnValue({\n selectedNetworkClientId: '',\n networksMetadata: {},\n networkConfigurationsByChainId: {},\n });\n\n const mockNetworkControllerAddNetwork = typedMockFn(\n 'NetworkController:addNetwork',\n );\n\n const mockNetworkControllerRemoveNetwork = typedMockFn(\n 'NetworkController:removeNetwork',\n );\n\n const mockNetworkControllerUpdateNetwork = typedMockFn(\n 'NetworkController:updateNetwork',\n );\n\n jest.spyOn(messenger, 'call').mockImplementation((...args) => {\n const typedArgs = args as unknown as CallParams;\n const [actionType] = typedArgs;\n\n if (actionType === 'SnapController:handleRequest') {\n const [, params] = typedArgs;\n if (params.request.method === 'getPublicKey') {\n return mockSnapGetPublicKey();\n }\n\n if (params.request.method === 'signMessage') {\n return mockSnapSignMessage();\n }\n\n throw new Error(\n `MOCK_FAIL - unsupported SnapController:handleRequest call: ${\n params.request.method as string\n }`,\n );\n }\n\n if (actionType === 'AuthenticationController:getBearerToken') {\n return mockAuthGetBearerToken();\n }\n\n if (actionType === 'AuthenticationController:getSessionProfile') {\n return mockAuthGetSessionProfile();\n }\n\n if (actionType === 'AuthenticationController:performSignIn') {\n return mockAuthPerformSignIn();\n }\n\n if (actionType === 'AuthenticationController:isSignedIn') {\n return mockAuthIsSignedIn();\n }\n\n if (actionType === 'AuthenticationController:performSignOut') {\n return mockAuthPerformSignOut();\n }\n\n if (actionType === 'KeyringController:getState') {\n return { isUnlocked: true };\n }\n\n if (actionType === 'KeyringController:withKeyring') {\n const [, ...params] = typedArgs;\n return mockKeyringWithKeyring(...params);\n }\n\n if (actionType === 'AccountsController:listAccounts') {\n return mockAccountsListAccounts();\n }\n\n if (typedArgs[0] === 'AccountsController:updateAccountMetadata') {\n const [, ...params] = typedArgs;\n return mockAccountsUpdateAccountMetadata(...params);\n }\n\n if (actionType === 'NetworkController:getState') {\n return mockNetworkControllerGetState();\n }\n\n if (actionType === 'NetworkController:addNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerAddNetwork(...params);\n }\n\n if (actionType === 'NetworkController:removeNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerRemoveNetwork(...params);\n }\n\n if (actionType === 'NetworkController:updateNetwork') {\n const [, ...params] = typedArgs;\n return mockNetworkControllerUpdateNetwork(...params);\n }\n\n throw new Error(\n `MOCK_FAIL - unsupported messenger call: ${actionType as string}`,\n );\n });\n\n return {\n baseMessenger,\n messenger,\n mockSnapGetPublicKey,\n mockSnapSignMessage,\n mockAuthGetBearerToken,\n mockAuthGetSessionProfile,\n mockAuthPerformSignIn,\n mockAuthIsSignedIn,\n mockAuthPerformSignOut,\n mockKeyringWithKeyring,\n mockAccountsUpdateAccountMetadata,\n mockAccountsListAccounts,\n mockNetworkControllerGetState,\n mockNetworkControllerAddNetwork,\n mockNetworkControllerRemoveNetwork,\n mockNetworkControllerUpdateNetwork,\n };\n}\n"]}
|
|
@@ -15,7 +15,7 @@ const utils_1 = require("../utils.cjs");
|
|
|
15
15
|
*/
|
|
16
16
|
function mockUserStorageMessengerForAccountSyncing(options) {
|
|
17
17
|
const messengerMocks = (0, mockMessenger_1.mockUserStorageMessenger)();
|
|
18
|
-
messengerMocks.
|
|
18
|
+
messengerMocks.mockKeyringWithKeyring.mockImplementation(async () => {
|
|
19
19
|
messengerMocks.baseMessenger.publish('AccountsController:accountAdded', mockAccounts_1.MOCK_INTERNAL_ACCOUNTS.ONE[0]);
|
|
20
20
|
return mockAccounts_1.MOCK_INTERNAL_ACCOUNTS.ONE[0].address;
|
|
21
21
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-utils.cjs","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/account-syncing/__fixtures__/test-utils.ts"],"names":[],"mappings":";;;AAEA,qDAAwD;AACxD,wEAAiE;AACjE,wEAA4E;AAC5E,wCAAkE;AAElE;;;;;;;GAOG;AACH,SAAgB,yCAAyC,CAAC,OAIzD;IACC,MAAM,cAAc,GAAG,IAAA,wCAAwB,GAAE,CAAC;IAElD,cAAc,CAAC,
|
|
1
|
+
{"version":3,"file":"test-utils.cjs","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/account-syncing/__fixtures__/test-utils.ts"],"names":[],"mappings":";;;AAEA,qDAAwD;AACxD,wEAAiE;AACjE,wEAA4E;AAC5E,wCAAkE;AAElE;;;;;;;GAOG;AACH,SAAgB,yCAAyC,CAAC,OAIzD;IACC,MAAM,cAAc,GAAG,IAAA,wCAAwB,GAAE,CAAC;IAElD,cAAc,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,KAAK,IAAI,EAAE;QAClE,cAAc,CAAC,aAAa,CAAC,OAAO,CAClC,iCAAiC,EACjC,qCAAsB,CAAC,GAAG,CAAC,CAAC,CAAoB,CACjD,CAAC;QACF,OAAO,qCAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC/C,CAAC,CAAC,CAAC;IAEH,cAAc,CAAC,wBAAwB,CAAC,eAAe,CACrD,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY;QAC9B,qCAAsB,CAAC,GAAG,CAAsB,CACnD,CAAC;IAEF,OAAO,cAAc,CAAC;AACxB,CAAC;AArBD,8FAqBC;AAED;;;;;;GAMG;AACH,SAAgB,wCAAwC,CACtD,IAAiC,EACjC,UAAkB;IAElB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;QAC1C,IAAA,6BAAgB,EAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAC;QAC/C,IAAI,CAAC,SAAS,CAAC,IAAA,8CAAsC,EAAC,UAAU,CAAC,CAAC;KACnE,CAAC,CAAC;AACL,CAAC;AARD,4FAQC;AAED;;;;;;GAMG;AACH,SAAgB,wCAAwC,CACtD,IAAc,EACd,UAAkB;IAElB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAC3B,IAAA,6BAAgB,EAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAC,CAChD,CAAC;AACJ,CAAC;AAPD,4FAOC","sourcesContent":["import type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport { MOCK_INTERNAL_ACCOUNTS } from './mockAccounts';\nimport { createSHA256Hash } from '../../../../shared/encryption';\nimport { mockUserStorageMessenger } from '../../__fixtures__/mockMessenger';\nimport { mapInternalAccountToUserStorageAccount } from '../utils';\n\n/**\n * Test Utility - create a mock user storage messenger for account syncing tests\n *\n * @param options - options for the mock messenger\n * @param options.accounts - options for the accounts part of the controller\n * @param options.accounts.accountsList - list of accounts to return for the 'AccountsController:listAccounts' action\n * @returns Mock User Storage Messenger\n */\nexport function mockUserStorageMessengerForAccountSyncing(options?: {\n accounts?: {\n accountsList?: InternalAccount[];\n };\n}) {\n const messengerMocks = mockUserStorageMessenger();\n\n messengerMocks.mockKeyringWithKeyring.mockImplementation(async () => {\n messengerMocks.baseMessenger.publish(\n 'AccountsController:accountAdded',\n MOCK_INTERNAL_ACCOUNTS.ONE[0] as InternalAccount,\n );\n return MOCK_INTERNAL_ACCOUNTS.ONE[0].address;\n });\n\n messengerMocks.mockAccountsListAccounts.mockReturnValue(\n (options?.accounts?.accountsList ??\n MOCK_INTERNAL_ACCOUNTS.ALL) as InternalAccount[],\n );\n\n return messengerMocks;\n}\n\n/**\n * Test Utility - creates a realistic expected batch upsert payload\n *\n * @param data - data supposed to be upserted\n * @param storageKey - storage key\n * @returns expected body\n */\nexport function createExpectedAccountSyncBatchUpsertBody(\n data: [string, InternalAccount][],\n storageKey: string,\n) {\n return data.map(([entryKey, entryValue]) => [\n createSHA256Hash(String(entryKey) + storageKey),\n JSON.stringify(mapInternalAccountToUserStorageAccount(entryValue)),\n ]);\n}\n\n/**\n * Test Utility - creates a realistic expected batch delete payload\n *\n * @param data - data supposed to be deleted\n * @param storageKey - storage key\n * @returns expected body\n */\nexport function createExpectedAccountSyncBatchDeleteBody(\n data: string[],\n storageKey: string,\n) {\n return data.map((entryKey) =>\n createSHA256Hash(String(entryKey) + storageKey),\n );\n}\n"]}
|
|
@@ -32,7 +32,7 @@ export declare function mockUserStorageMessengerForAccountSyncing(options?: {
|
|
|
32
32
|
identifierId: string;
|
|
33
33
|
profileId: string;
|
|
34
34
|
}>;
|
|
35
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
35
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../../index.cjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
36
36
|
mockSnapGetPublicKey: jest.Mock<any, any>;
|
|
37
37
|
mockSnapSignMessage: jest.Mock<any, any>;
|
|
38
38
|
mockAuthGetBearerToken: jest.Mock<Promise<string>, []>;
|
|
@@ -43,7 +43,7 @@ export declare function mockUserStorageMessengerForAccountSyncing(options?: {
|
|
|
43
43
|
mockAuthPerformSignIn: jest.Mock<Promise<string>, []>;
|
|
44
44
|
mockAuthIsSignedIn: jest.Mock<boolean, []>;
|
|
45
45
|
mockAuthPerformSignOut: jest.Mock<void, []>;
|
|
46
|
-
|
|
46
|
+
mockKeyringWithKeyring: jest.Mock<Promise<unknown>, [selector: import("@metamask/keyring-controller").KeyringSelector, operation: (keyring: import("@metamask/keyring-internal-api").EthKeyring<import("@metamask/utils").Json>) => Promise<unknown>]>;
|
|
47
47
|
mockAccountsUpdateAccountMetadata: jest.Mock<void, [accountId: string, metadata: Partial<{
|
|
48
48
|
name: string;
|
|
49
49
|
importTime: number;
|
|
@@ -32,7 +32,7 @@ export declare function mockUserStorageMessengerForAccountSyncing(options?: {
|
|
|
32
32
|
identifierId: string;
|
|
33
33
|
profileId: string;
|
|
34
34
|
}>;
|
|
35
|
-
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/
|
|
35
|
+
} | import("@metamask/keyring-controller").KeyringControllerGetStateAction | import("@metamask/accounts-controller").AccountsControllerListAccountsAction | import("@metamask/accounts-controller").AccountsControllerUpdateAccountMetadataAction | import("@metamask/network-controller").NetworkControllerGetStateAction | import("@metamask/network-controller").NetworkControllerAddNetworkAction | import("@metamask/network-controller").NetworkControllerRemoveNetworkAction | import("@metamask/network-controller").NetworkControllerUpdateNetworkAction, import("@metamask/keyring-controller").KeyringControllerLockEvent | import("@metamask/keyring-controller").KeyringControllerUnlockEvent | import("../../index.mjs").UserStorageControllerStateChangeEvent | import("@metamask/accounts-controller").AccountsControllerAccountAddedEvent | import("@metamask/accounts-controller").AccountsControllerAccountRenamedEvent | import("@metamask/network-controller").NetworkControllerNetworkRemovedEvent, "SnapController:handleRequest" | "KeyringController:getState" | "AuthenticationController:isSignedIn" | "AuthenticationController:performSignIn" | "AuthenticationController:performSignOut" | "AuthenticationController:getBearerToken" | "AuthenticationController:getSessionProfile" | "AccountsController:listAccounts" | "AccountsController:updateAccountMetadata" | "NetworkController:getState" | "NetworkController:addNetwork" | "NetworkController:removeNetwork" | "NetworkController:updateNetwork", "KeyringController:lock" | "KeyringController:unlock" | "AccountsController:accountAdded" | "AccountsController:accountRenamed" | "NetworkController:networkRemoved">;
|
|
36
36
|
mockSnapGetPublicKey: jest.Mock<any, any>;
|
|
37
37
|
mockSnapSignMessage: jest.Mock<any, any>;
|
|
38
38
|
mockAuthGetBearerToken: jest.Mock<Promise<string>, []>;
|
|
@@ -43,7 +43,7 @@ export declare function mockUserStorageMessengerForAccountSyncing(options?: {
|
|
|
43
43
|
mockAuthPerformSignIn: jest.Mock<Promise<string>, []>;
|
|
44
44
|
mockAuthIsSignedIn: jest.Mock<boolean, []>;
|
|
45
45
|
mockAuthPerformSignOut: jest.Mock<void, []>;
|
|
46
|
-
|
|
46
|
+
mockKeyringWithKeyring: jest.Mock<Promise<unknown>, [selector: import("@metamask/keyring-controller").KeyringSelector, operation: (keyring: import("@metamask/keyring-internal-api").EthKeyring<import("@metamask/utils").Json>) => Promise<unknown>]>;
|
|
47
47
|
mockAccountsUpdateAccountMetadata: jest.Mock<void, [accountId: string, metadata: Partial<{
|
|
48
48
|
name: string;
|
|
49
49
|
importTime: number;
|
|
@@ -12,7 +12,7 @@ import { mapInternalAccountToUserStorageAccount } from "../utils.mjs";
|
|
|
12
12
|
*/
|
|
13
13
|
export function mockUserStorageMessengerForAccountSyncing(options) {
|
|
14
14
|
const messengerMocks = mockUserStorageMessenger();
|
|
15
|
-
messengerMocks.
|
|
15
|
+
messengerMocks.mockKeyringWithKeyring.mockImplementation(async () => {
|
|
16
16
|
messengerMocks.baseMessenger.publish('AccountsController:accountAdded', MOCK_INTERNAL_ACCOUNTS.ONE[0]);
|
|
17
17
|
return MOCK_INTERNAL_ACCOUNTS.ONE[0].address;
|
|
18
18
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-utils.mjs","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/account-syncing/__fixtures__/test-utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,2BAAuB;AACxD,OAAO,EAAE,gBAAgB,EAAE,gDAAsC;AACjE,OAAO,EAAE,wBAAwB,EAAE,6CAAyC;AAC5E,OAAO,EAAE,sCAAsC,EAAE,qBAAiB;AAElE;;;;;;;GAOG;AACH,MAAM,UAAU,yCAAyC,CAAC,OAIzD;IACC,MAAM,cAAc,GAAG,wBAAwB,EAAE,CAAC;IAElD,cAAc,CAAC,
|
|
1
|
+
{"version":3,"file":"test-utils.mjs","sourceRoot":"","sources":["../../../../../src/controllers/user-storage/account-syncing/__fixtures__/test-utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,2BAAuB;AACxD,OAAO,EAAE,gBAAgB,EAAE,gDAAsC;AACjE,OAAO,EAAE,wBAAwB,EAAE,6CAAyC;AAC5E,OAAO,EAAE,sCAAsC,EAAE,qBAAiB;AAElE;;;;;;;GAOG;AACH,MAAM,UAAU,yCAAyC,CAAC,OAIzD;IACC,MAAM,cAAc,GAAG,wBAAwB,EAAE,CAAC;IAElD,cAAc,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,KAAK,IAAI,EAAE;QAClE,cAAc,CAAC,aAAa,CAAC,OAAO,CAClC,iCAAiC,EACjC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAoB,CACjD,CAAC;QACF,OAAO,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAC/C,CAAC,CAAC,CAAC;IAEH,cAAc,CAAC,wBAAwB,CAAC,eAAe,CACrD,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY;QAC9B,sBAAsB,CAAC,GAAG,CAAsB,CACnD,CAAC;IAEF,OAAO,cAAc,CAAC;AACxB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wCAAwC,CACtD,IAAiC,EACjC,UAAkB;IAElB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;QAC1C,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAC;QAC/C,IAAI,CAAC,SAAS,CAAC,sCAAsC,CAAC,UAAU,CAAC,CAAC;KACnE,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wCAAwC,CACtD,IAAc,EACd,UAAkB;IAElB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAC3B,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAC,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport { MOCK_INTERNAL_ACCOUNTS } from './mockAccounts';\nimport { createSHA256Hash } from '../../../../shared/encryption';\nimport { mockUserStorageMessenger } from '../../__fixtures__/mockMessenger';\nimport { mapInternalAccountToUserStorageAccount } from '../utils';\n\n/**\n * Test Utility - create a mock user storage messenger for account syncing tests\n *\n * @param options - options for the mock messenger\n * @param options.accounts - options for the accounts part of the controller\n * @param options.accounts.accountsList - list of accounts to return for the 'AccountsController:listAccounts' action\n * @returns Mock User Storage Messenger\n */\nexport function mockUserStorageMessengerForAccountSyncing(options?: {\n accounts?: {\n accountsList?: InternalAccount[];\n };\n}) {\n const messengerMocks = mockUserStorageMessenger();\n\n messengerMocks.mockKeyringWithKeyring.mockImplementation(async () => {\n messengerMocks.baseMessenger.publish(\n 'AccountsController:accountAdded',\n MOCK_INTERNAL_ACCOUNTS.ONE[0] as InternalAccount,\n );\n return MOCK_INTERNAL_ACCOUNTS.ONE[0].address;\n });\n\n messengerMocks.mockAccountsListAccounts.mockReturnValue(\n (options?.accounts?.accountsList ??\n MOCK_INTERNAL_ACCOUNTS.ALL) as InternalAccount[],\n );\n\n return messengerMocks;\n}\n\n/**\n * Test Utility - creates a realistic expected batch upsert payload\n *\n * @param data - data supposed to be upserted\n * @param storageKey - storage key\n * @returns expected body\n */\nexport function createExpectedAccountSyncBatchUpsertBody(\n data: [string, InternalAccount][],\n storageKey: string,\n) {\n return data.map(([entryKey, entryValue]) => [\n createSHA256Hash(String(entryKey) + storageKey),\n JSON.stringify(mapInternalAccountToUserStorageAccount(entryValue)),\n ]);\n}\n\n/**\n * Test Utility - creates a realistic expected batch delete payload\n *\n * @param data - data supposed to be deleted\n * @param storageKey - storage key\n * @returns expected body\n */\nexport function createExpectedAccountSyncBatchDeleteBody(\n data: string[],\n storageKey: string,\n) {\n return data.map((entryKey) =>\n createSHA256Hash(String(entryKey) + storageKey),\n );\n}\n"]}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.syncInternalAccountsWithUserStorage = exports.saveInternalAccountsListToUserStorage = exports.saveInternalAccountToUserStorage = void 0;
|
|
4
4
|
const keyring_api_1 = require("@metamask/keyring-api");
|
|
5
|
+
const keyring_controller_1 = require("@metamask/keyring-controller");
|
|
5
6
|
const sync_utils_1 = require("./sync-utils.cjs");
|
|
6
7
|
const utils_1 = require("./utils.cjs");
|
|
7
8
|
const storage_schema_1 = require("../../../shared/storage-schema.cjs");
|
|
@@ -99,8 +100,13 @@ async function syncInternalAccountsWithUserStorage(config, options) {
|
|
|
99
100
|
const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -
|
|
100
101
|
internalAccountsList.length;
|
|
101
102
|
// Create new accounts to match the user storage accounts list
|
|
103
|
+
await getMessenger().call('KeyringController:withKeyring', {
|
|
104
|
+
type: keyring_controller_1.KeyringTypes.hd,
|
|
105
|
+
}, async (keyring) => {
|
|
106
|
+
keyring.addAccounts(numberOfAccountsToAdd);
|
|
107
|
+
});
|
|
108
|
+
// Keeping this for analytics purposes, but should probably be re-thought
|
|
102
109
|
for (let i = 0; i < numberOfAccountsToAdd; i++) {
|
|
103
|
-
await getMessenger().call('KeyringController:addNewAccount');
|
|
104
110
|
onAccountAdded?.();
|
|
105
111
|
}
|
|
106
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AAGzD,iDAIsB;AAEtB,uCAIiB;AACjB,uEAA4E;AAE5E;;;;;;GAMG;AACI,KAAK,UAAU,gCAAgC,CACpD,eAAgC,EAChC,MAA4B,EAC5B,OAA8B;IAE9B,MAAM,EAAE,uBAAuB,EAAE,GAAG,MAAM,CAAC;IAC3C,MAAM,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAErD,IACE,CAAC,uBAAuB;QACxB,CAAC,IAAA,qCAAwB,EAAC,MAAM,EAAE,OAAO,CAAC;QAC1C,CAAC,IAAA,8BAAgB,EAAC,eAAe,CAAC,IAAI,CAAC;QACvC,CAAC,IAAA,iDAAyC,EAAC,eAAe,CAAC,EAC3D;QACA,OAAO;KACR;IAED,IAAI;QACF,8DAA8D;QAC9D,MAAM,aAAa,GACjB,IAAA,8CAAsC,EAAC,eAAe,CAAC,CAAC;QAE1D,MAAM,gCAAgC,EAAE,CAAC,iBAAiB;QACxD,2BAA2B;QAE3B,GAAG,2CAA0B,CAAC,QAAQ,IAAI,eAAe,CAAC,OAAO,EAAE,EACnE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAC9B,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,oEAAoE,YAAY,EAAE,CACnF,CAAC;KACH;AACH,CAAC;AAnCD,4EAmCC;AAED;;;;;GAKG;AACI,KAAK,UAAU,qCAAqC,CACzD,MAA4B,EAC5B,OAA8B;IAE9B,MAAM,EAAE,uBAAuB,EAAE,GAAG,MAAM,CAAC;IAC3C,MAAM,EAAE,gCAAgC,EAAE,GAAG,OAAO,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oEAAoE;gBACpE,oEAAoE,CAAC;YAEvE,MAAM,OAAO,GAAG;gBACd,4BAA4B;gBAC5B,yBAAyB;aAC1B,CAAC;YACF,IAAI,iBAAiB,EAAE;gBACrB,+BAA+B,EAAE,CAC/B,6FAA6F,EAC7F,OAAO,CACR,CAAC;aACH;iBAAM;gBACL,+BAA+B,EAAE,CAC/B,oGAAoG,EACpG,OAAO,CACR,CAAC;aACH;SACF;QAED,qFAAqF;QACrF,mFAAmF;QACnF,MAAM,gCAAgC,EAAE,CAAC,qCAAqC,CAC5E,IAAI,CACL,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,uEAAuE,YAAY,EAAE,CACtF,CAAC;KACH;YAAS;QACR,MAAM,gCAAgC,EAAE,CAAC,6BAA6B,CACpE,KAAK,CACN,CAAC;KACH;AACH,CAAC;AAnRD,kFAmRC","sourcesContent":["import { isEvmAccountType } from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport {\n canPerformAccountSyncing,\n getInternalAccountsList,\n getUserStorageAccountsList,\n} from './sync-utils';\nimport type { AccountSyncingConfig, AccountSyncingOptions } from './types';\nimport {\n doesInternalAccountHaveCorrectKeyringType,\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\n\n/**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n * @param config - parameters used for saving the internal account\n * @param options - parameters used for saving the internal account\n */\nexport async function saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (\n !isAccountSyncingEnabled ||\n !canPerformAccountSyncing(config, options) ||\n !isEvmAccountType(internalAccount.type) ||\n !doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await getUserStorageControllerInstance().performSetStorage(\n // ESLint is confused here.\n\n `${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to save account to user storage - ${errorMessage}`,\n );\n }\n}\n\n/**\n * Saves the list of internal accounts to the user storage.\n *\n * @param config - parameters used for saving the list of internal accounts\n * @param options - parameters used for saving the list of internal accounts\n */\nexport async function saveInternalAccountsListToUserStorage(\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (!isAccountSyncingEnabled) {\n return;\n }\n\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList?.length) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n}\n\ntype SyncInternalAccountsWithUserStorageConfig = AccountSyncingConfig & {\n maxNumberOfAccountsToAdd?: number;\n onAccountAdded?: () => void;\n onAccountNameUpdated?: () => void;\n onAccountSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n};\n\n/**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n *\n * @param config - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param options - parameters used for syncing the internal accounts list with the user storage accounts list\n */\nexport async function syncInternalAccountsWithUserStorage(\n config: SyncInternalAccountsWithUserStorageConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n\n if (!canPerformAccountSyncing(config, options) || !isAccountSyncingEnabled) {\n return;\n }\n\n const {\n maxNumberOfAccountsToAdd = Infinity,\n onAccountAdded,\n onAccountNameUpdated,\n onAccountSyncErroneousSituation,\n } = config;\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n try {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n true,\n );\n\n const userStorageAccountsList = await getUserStorageAccountsList(options);\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await saveInternalAccountsListToUserStorage(\n { isAccountSyncingEnabled },\n options,\n );\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n return;\n }\n // Keep a record if erroneous situations are found during the sync\n // This is done so we can send the context to Sentry in case of an erroneous situation\n let erroneousSituationsFound = false;\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreUserStorageAccountsThanInternalAccounts =\n userStorageAccountsList.length > internalAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts in user storage than internal accounts\n if (hasMoreUserStorageAccountsThanInternalAccounts) {\n const numberOfAccountsToAdd =\n Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -\n internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await getMessenger().call('KeyringController:addNewAccount');\n onAccountAdded?.();\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n const refreshedInternalAccountsList =\n await getInternalAccountsList(options);\n\n const newlyAddedAccounts = refreshedInternalAccountsList.filter(\n (account) =>\n !internalAccountsList.find((a) => a.address === account.address),\n );\n\n for (const internalAccount of refreshedInternalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n // If the account is not present in user storage\n // istanbul ignore next\n if (!userStorageAccount) {\n // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account\n if (newlyAddedAccounts.includes(internalAccount)) {\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was added to the internal accounts list but was not present in the user storage accounts list',\n {\n internalAccount,\n userStorageAccount,\n newlyAddedAccounts,\n userStorageAccountsList,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n },\n );\n continue;\n }\n // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // From this point on, we know that the account is present in\n // both the internal accounts list and the user storage accounts list\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n onAccountNameUpdated?.();\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n onAccountNameUpdated?.();\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n if (internalAccountsToBeSavedToUserStorage.length) {\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n }\n\n // In case we have corrupted user storage with accounts that don't exist in the internal accounts list\n // Delete those accounts from the user storage\n const userStorageAccountsToBeDeleted = userStorageAccountsList.filter(\n (account) =>\n !refreshedInternalAccountsList.find((a) => a.address === account.a),\n );\n\n if (userStorageAccountsToBeDeleted.length) {\n await getUserStorageControllerInstance().performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n );\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync',\n {\n userStorageAccountsToBeDeleted,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n userStorageAccountsList,\n },\n );\n }\n\n if (erroneousSituationsFound) {\n const [finalUserStorageAccountsList, finalInternalAccountsList] =\n await Promise.all([\n getUserStorageAccountsList(options),\n getInternalAccountsList(options),\n ]);\n\n const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList =\n finalInternalAccountsList.every((account) =>\n finalUserStorageAccountsList?.some(\n (userStorageAccount) => userStorageAccount.a === account.address,\n ),\n );\n\n // istanbul ignore next\n const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList =\n (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd\n ? true\n : finalUserStorageAccountsList?.every((account) =>\n finalInternalAccountsList.some(\n (internalAccount) => internalAccount.address === account.a,\n ),\n );\n\n const doFinalListsMatch =\n doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&\n doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;\n\n const context = {\n finalUserStorageAccountsList,\n finalInternalAccountsList,\n };\n if (doFinalListsMatch) {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, but final state matches the expected state',\n context,\n );\n } else {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, and final state does not match the expected state',\n context,\n );\n }\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n false,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AACzD,qEAA4D;AAG5D,iDAIsB;AAEtB,uCAIiB;AACjB,uEAA4E;AAE5E;;;;;;GAMG;AACI,KAAK,UAAU,gCAAgC,CACp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AoE,CAAC;YAEvE,MAAM,OAAO,GAAG;gBACd,4BAA4B;gBAC5B,yBAAyB;aAC1B,CAAC;YACF,IAAI,iBAAiB,EAAE;gBACrB,+BAA+B,EAAE,CAC/B,6FAA6F,EAC7F,OAAO,CACR,CAAC;aACH;iBAAM;gBACL,+BAA+B,EAAE,CAC/B,oGAAoG,EACpG,OAAO,CACR,CAAC;aACH;SACF;QAED,qFAAqF;QACrF,mFAAmF;QACnF,MAAM,gCAAgC,EAAE,CAAC,qCAAqC,CAC5E,IAAI,CACL,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,uBAAuB;QACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACxE,MAAM,IAAI,KAAK,CACb,uEAAuE,YAAY,EAAE,CACtF,CAAC;KACH;YAAS;QACR,MAAM,gCAAgC,EAAE,CAAC,6BAA6B,CACpE,KAAK,CACN,CAAC;KACH;AACH,CAAC;AA7RD,kFA6RC","sourcesContent":["import { isEvmAccountType } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport {\n canPerformAccountSyncing,\n getInternalAccountsList,\n getUserStorageAccountsList,\n} from './sync-utils';\nimport type { AccountSyncingConfig, AccountSyncingOptions } from './types';\nimport {\n doesInternalAccountHaveCorrectKeyringType,\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\n\n/**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n * @param config - parameters used for saving the internal account\n * @param options - parameters used for saving the internal account\n */\nexport async function saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (\n !isAccountSyncingEnabled ||\n !canPerformAccountSyncing(config, options) ||\n !isEvmAccountType(internalAccount.type) ||\n !doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await getUserStorageControllerInstance().performSetStorage(\n // ESLint is confused here.\n\n `${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to save account to user storage - ${errorMessage}`,\n );\n }\n}\n\n/**\n * Saves the list of internal accounts to the user storage.\n *\n * @param config - parameters used for saving the list of internal accounts\n * @param options - parameters used for saving the list of internal accounts\n */\nexport async function saveInternalAccountsListToUserStorage(\n config: AccountSyncingConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n const { getUserStorageControllerInstance } = options;\n\n if (!isAccountSyncingEnabled) {\n return;\n }\n\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList?.length) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n}\n\ntype SyncInternalAccountsWithUserStorageConfig = AccountSyncingConfig & {\n maxNumberOfAccountsToAdd?: number;\n onAccountAdded?: () => void;\n onAccountNameUpdated?: () => void;\n onAccountSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n};\n\n/**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n *\n * @param config - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param options - parameters used for syncing the internal accounts list with the user storage accounts list\n */\nexport async function syncInternalAccountsWithUserStorage(\n config: SyncInternalAccountsWithUserStorageConfig,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { isAccountSyncingEnabled } = config;\n\n if (!canPerformAccountSyncing(config, options) || !isAccountSyncingEnabled) {\n return;\n }\n\n const {\n maxNumberOfAccountsToAdd = Infinity,\n onAccountAdded,\n onAccountNameUpdated,\n onAccountSyncErroneousSituation,\n } = config;\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n try {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n true,\n );\n\n const userStorageAccountsList = await getUserStorageAccountsList(options);\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await saveInternalAccountsListToUserStorage(\n { isAccountSyncingEnabled },\n options,\n );\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n return;\n }\n // Keep a record if erroneous situations are found during the sync\n // This is done so we can send the context to Sentry in case of an erroneous situation\n let erroneousSituationsFound = false;\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n const internalAccountsList = await getInternalAccountsList(options);\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreUserStorageAccountsThanInternalAccounts =\n userStorageAccountsList.length > internalAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts in user storage than internal accounts\n if (hasMoreUserStorageAccountsThanInternalAccounts) {\n const numberOfAccountsToAdd =\n Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -\n internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n await getMessenger().call(\n 'KeyringController:withKeyring',\n {\n type: KeyringTypes.hd,\n },\n async (keyring) => {\n keyring.addAccounts(numberOfAccountsToAdd);\n },\n );\n\n // Keeping this for analytics purposes, but should probably be re-thought\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n onAccountAdded?.();\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n const refreshedInternalAccountsList =\n await getInternalAccountsList(options);\n\n const newlyAddedAccounts = refreshedInternalAccountsList.filter(\n (account) =>\n !internalAccountsList.find((a) => a.address === account.address),\n );\n\n for (const internalAccount of refreshedInternalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n // If the account is not present in user storage\n // istanbul ignore next\n if (!userStorageAccount) {\n // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account\n if (newlyAddedAccounts.includes(internalAccount)) {\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was added to the internal accounts list but was not present in the user storage accounts list',\n {\n internalAccount,\n userStorageAccount,\n newlyAddedAccounts,\n userStorageAccountsList,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n },\n );\n continue;\n }\n // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // From this point on, we know that the account is present in\n // both the internal accounts list and the user storage accounts list\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n onAccountNameUpdated?.();\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n onAccountNameUpdated?.();\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n if (internalAccountsToBeSavedToUserStorage.length) {\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n }\n\n // In case we have corrupted user storage with accounts that don't exist in the internal accounts list\n // Delete those accounts from the user storage\n const userStorageAccountsToBeDeleted = userStorageAccountsList.filter(\n (account) =>\n !refreshedInternalAccountsList.find((a) => a.address === account.a),\n );\n\n if (userStorageAccountsToBeDeleted.length) {\n await getUserStorageControllerInstance().performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n );\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync',\n {\n userStorageAccountsToBeDeleted,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n userStorageAccountsList,\n },\n );\n }\n\n if (erroneousSituationsFound) {\n const [finalUserStorageAccountsList, finalInternalAccountsList] =\n await Promise.all([\n getUserStorageAccountsList(options),\n getInternalAccountsList(options),\n ]);\n\n const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList =\n finalInternalAccountsList.every((account) =>\n finalUserStorageAccountsList?.some(\n (userStorageAccount) => userStorageAccount.a === account.address,\n ),\n );\n\n // istanbul ignore next\n const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList =\n (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd\n ? true\n : finalUserStorageAccountsList?.every((account) =>\n finalInternalAccountsList.some(\n (internalAccount) => internalAccount.address === account.a,\n ),\n );\n\n const doFinalListsMatch =\n doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&\n doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;\n\n const context = {\n finalUserStorageAccountsList,\n finalInternalAccountsList,\n };\n if (doFinalListsMatch) {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, but final state matches the expected state',\n context,\n );\n } else {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, and final state does not match the expected state',\n context,\n );\n }\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await getUserStorageControllerInstance().setHasAccountSyncingSyncedAtLeastOnce(\n true,\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n false,\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,oBAAgB;AAQ3E;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CACzD,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAyBf;AAED,KAAK,yCAAyC,GAAG,oBAAoB,GAAG;IACtE,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA0Rf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,oBAAgB;AAQ3E;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CACzD,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAyBf;AAED,KAAK,yCAAyC,GAAG,oBAAoB,GAAG;IACtE,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA0Rf"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isEvmAccountType } from "@metamask/keyring-api";
|
|
2
|
+
import { KeyringTypes } from "@metamask/keyring-controller";
|
|
2
3
|
import { canPerformAccountSyncing, getInternalAccountsList, getUserStorageAccountsList } from "./sync-utils.mjs";
|
|
3
4
|
import { doesInternalAccountHaveCorrectKeyringType, isNameDefaultAccountName, mapInternalAccountToUserStorageAccount } from "./utils.mjs";
|
|
4
5
|
import { USER_STORAGE_FEATURE_NAMES } from "../../../shared/storage-schema.mjs";
|
|
@@ -94,8 +95,13 @@ export async function syncInternalAccountsWithUserStorage(config, options) {
|
|
|
94
95
|
const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -
|
|
95
96
|
internalAccountsList.length;
|
|
96
97
|
// Create new accounts to match the user storage accounts list
|
|
98
|
+
await getMessenger().call('KeyringController:withKeyring', {
|
|
99
|
+
type: KeyringTypes.hd,
|
|
100
|
+
}, async (keyring) => {
|
|
101
|
+
keyring.addAccounts(numberOfAccountsToAdd);
|
|
102
|
+
});
|
|
103
|
+
// Keeping this for analytics purposes, but should probably be re-thought
|
|
97
104
|
for (let i = 0; i < numberOfAccountsToAdd; i++) {
|
|
98
|
-
await getMessenger().call('KeyringController:addNewAccount');
|
|
99
105
|
onAccountAdded?.();
|
|
100
106
|
}
|
|
101
107
|
}
|