Skip to content

Commit 08302be

Browse files
mikespositoGudahtt
andauthored
refactor: migrate assets controllers messenger (#6745)
## Explanation <!-- Thanks for your contribution! Take a moment to answer these questions so that reviewers have the information they need to properly understand your changes: * What is the current state of things and why does it need to change? * What is the solution your changes offer and how does it work? * Are there any changes whose purpose might not obvious to those unfamiliar with the domain? * If your primary goal was to update one package but you found you had to update another one along the way, why did you do so? * If you had to upgrade a dependency, why did you do so? --> This PR migrates all remaining assets controllers to `@metamask/messenger` instead of `@metamask/base-controller`. This is part of a larger effort to migrate all controllers to use `@metamask/messenger`. ## References <!-- Are there any issues that this pull request is tied to? Are there other links that reviewers should consult to understand these changes better? Are there client or consumer pull requests to adopt any breaking changes? For example: * Fixes #12345 * Related to #67890 --> * Related to #5626 ## Checklist - [ ] I've updated the test suite for new or updated code as appropriate - [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate - [ ] I've communicated my changes to consumers by [updating changelogs for packages I've changed](https://github.com/MetaMask/core/tree/main/docs/contributing.md#updating-changelogs), highlighting breaking changes as necessary - [ ] I've prepared draft pull requests for clients and consumer packages to resolve any breaking changes <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Migrates remaining assets controllers and tests from base-controller RestrictedMessenger to @metamask/messenger, updating metadata flags and event wiring. > > - **Controllers (migration to `@metamask/messenger`)**: > - `MultichainAssetsController`, `MultichainBalancesController`, `NftDetectionController`, `RatesController`, `TokenSearchDiscoveryDataController` now use `Messenger` types and `this.messenger` for `call/subscribe/publish` (replacing `RestrictedMessenger`/`messagingSystem`). > - Update controller-specific messenger types and allowed actions/events; add namespaced messengers in tests via `delegate`. > - **Metadata updates**: > - Switch to `@metamask/base-controller/next` and `StateMetadata`; replace `anonymous` with `includeInDebugSnapshot` where applicable. > - **Tests**: > - Refactor to root messenger + delegated namespaced messengers; update imports to `/next`; adjust assertions to new metadata flags; minor test helpers tweaks. > - **RatesController**: > - Maintain polling events via `this.messenger.publish` and expose metadata via `StateMetadata`. > - **Changelog**: > - Consolidate BREAKING note: controllers migrated to new `Messenger` API. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 241e6a0. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Mark Stacey <[email protected]>
1 parent b4c76ed commit 08302be

File tree

13 files changed

+336
-265
lines changed

13 files changed

+336
-265
lines changed

eslint-warning-thresholds.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@
3434
"jsdoc/tag-lines": 1
3535
},
3636
"packages/assets-controllers/src/RatesController/RatesController.test.ts": {
37-
"import-x/order": 2,
38-
"jsdoc/tag-lines": 4
37+
"import-x/order": 1,
38+
"jsdoc/tag-lines": 2
3939
},
4040
"packages/assets-controllers/src/RatesController/RatesController.ts": {
4141
"@typescript-eslint/prefer-readonly": 1,

packages/assets-controllers/CHANGELOG.md

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313

1414
### Changed
1515

16-
- **BREAKING:** Migrate the following controllers to the new `Messenger` from `@metamask/messenger` ([#6444](https://github.com/MetaMask/core/pull/6444))
17-
- `AccountTrackerController`
18-
- `CurrencyRateController`
19-
- `DeFiPositionController`
20-
- `MultichainAssetsRatesController`
21-
- `TokenBalancesController`
22-
- `TokenDetectionController`
23-
- `TokenListController`
24-
- `TokenRatesController`
25-
- **BREAKING:** Migrate `AssetsContractController`, `NftController`, and `TokensController` to new `Messenger` from `@metamask/messenger` ([#6386](https://github.com/MetaMask/core/pull/6386))
16+
- **BREAKING:** Migrate controllers to new `Messenger` from `@metamask/messenger` ([#6444](https://github.com/MetaMask/core/pull/6444), [#6386](https://github.com/MetaMask/core/pull/6386), [#6745](https://github.com/MetaMask/core/pull/6745))
2617
- Previously, the controllers accepted a `RestrictedMessenger` instance from `@metamask/base-controller`.
2718
- Bump `@metamask/polling-controller` from `^14.0.1` to `^14.0.2` ([#6940](https://github.com/MetaMask/core/pull/6940))
2819

packages/assets-controllers/src/MultichainAssetsController/MultichainAssetsController.test.ts

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { deriveStateFromMetadata, Messenger } from '@metamask/base-controller';
1+
import { deriveStateFromMetadata } from '@metamask/base-controller/next';
22
import type {
33
AccountAssetListUpdatedEventPayload,
44
CaipAssetTypeOrId,
@@ -11,6 +11,13 @@ import {
1111
} from '@metamask/keyring-api';
1212
import { KeyringTypes } from '@metamask/keyring-controller';
1313
import type { InternalAccount } from '@metamask/keyring-internal-api';
14+
import {
15+
Messenger,
16+
MOCK_ANY_NAMESPACE,
17+
type MessengerActions,
18+
type MessengerEvents,
19+
type MockAnyNamespace,
20+
} from '@metamask/messenger';
1421
import type { PermissionConstraint } from '@metamask/permission-controller';
1522
import type { SubjectPermissions } from '@metamask/permission-controller';
1623
import type { Snap } from '@metamask/snaps-utils';
@@ -27,10 +34,6 @@ import type {
2734
MultichainAssetsControllerState,
2835
} from './MultichainAssetsController';
2936
import { advanceTime } from '../../../../tests/helpers';
30-
import type {
31-
ExtractAvailableAction,
32-
ExtractAvailableEvent,
33-
} from '../../../base-controller/tests/helpers';
3437

3538
const mockSolanaAccount: InternalAccount = {
3639
type: 'solana:data-account',
@@ -216,21 +219,26 @@ const mockGetMetadataReturnValue: AssetMetadataResponse | undefined = {
216219
/**
217220
* The union of actions that the root messenger allows.
218221
*/
219-
type RootAction = ExtractAvailableAction<MultichainAssetsControllerMessenger>;
222+
type RootAction = MessengerActions<MultichainAssetsControllerMessenger>;
220223

221224
/**
222225
* The union of events that the root messenger allows.
223226
*/
224-
type RootEvent = ExtractAvailableEvent<MultichainAssetsControllerMessenger>;
227+
type RootEvent = MessengerEvents<MultichainAssetsControllerMessenger>;
228+
229+
/**
230+
* The root messenger type.
231+
*/
232+
type RootMessenger = Messenger<MockAnyNamespace, RootAction, RootEvent>;
225233

226234
/**
227-
* Constructs the unrestricted messenger. This can be used to call actions and
235+
* Constructs the root messenger. This can be used to call actions and
228236
* publish events within the tests for this controller.
229237
*
230-
* @returns The unrestricted messenger suited for MultichainAssetsController.
238+
* @returns The root messenger suited for MultichainAssetsController.
231239
*/
232-
function getRootMessenger(): Messenger<RootAction, RootEvent> {
233-
return new Messenger<RootAction, RootEvent>();
240+
function getRootMessenger(): RootMessenger {
241+
return new Messenger({ namespace: MOCK_ANY_NAMESPACE });
234242
}
235243

236244
const setupController = ({
@@ -248,20 +256,24 @@ const setupController = ({
248256
const messenger = getRootMessenger();
249257

250258
const multichainAssetsControllerMessenger: MultichainAssetsControllerMessenger =
251-
messenger.getRestricted({
252-
name: 'MultichainAssetsController',
253-
allowedActions: [
254-
'AccountsController:listMultichainAccounts',
255-
'SnapController:handleRequest',
256-
'SnapController:getAll',
257-
'PermissionController:getPermissions',
258-
],
259-
allowedEvents: [
260-
'AccountsController:accountAdded',
261-
'AccountsController:accountRemoved',
262-
'AccountsController:accountAssetListUpdated',
263-
],
259+
new Messenger({
260+
namespace: 'MultichainAssetsController',
261+
parent: messenger,
264262
});
263+
messenger.delegate({
264+
messenger: multichainAssetsControllerMessenger,
265+
actions: [
266+
'AccountsController:listMultichainAccounts',
267+
'SnapController:handleRequest',
268+
'SnapController:getAll',
269+
'PermissionController:getPermissions',
270+
],
271+
events: [
272+
'AccountsController:accountAdded',
273+
'AccountsController:accountRemoved',
274+
'AccountsController:accountAssetListUpdated',
275+
],
276+
});
265277

266278
const mockSnapHandleRequest = jest.fn();
267279
messenger.registerActionHandler(
@@ -827,7 +839,7 @@ describe('MultichainAssetsController', () => {
827839
deriveStateFromMetadata(
828840
controller.state,
829841
controller.metadata,
830-
'anonymous',
842+
'includeInDebugSnapshot',
831843
),
832844
).toMatchInlineSnapshot(`Object {}`);
833845
});

packages/assets-controllers/src/MultichainAssetsController/MultichainAssetsController.ts

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import {
88
BaseController,
99
type ControllerGetStateAction,
1010
type ControllerStateChangeEvent,
11-
type RestrictedMessenger,
12-
} from '@metamask/base-controller';
11+
type StateMetadata,
12+
} from '@metamask/base-controller/next';
1313
import { isEvmAccountType } from '@metamask/keyring-api';
1414
import type {
1515
AccountAssetListUpdatedEventPayload,
@@ -18,6 +18,7 @@ import type {
1818
} from '@metamask/keyring-api';
1919
import type { InternalAccount } from '@metamask/keyring-internal-api';
2020
import { KeyringClient } from '@metamask/keyring-snap-client';
21+
import type { Messenger } from '@metamask/messenger';
2122
import type {
2223
GetPermissions,
2324
PermissionConstraint,
@@ -141,12 +142,10 @@ type AllowedEvents =
141142
/**
142143
* Messenger type for the MultichainAssetsController.
143144
*/
144-
export type MultichainAssetsControllerMessenger = RestrictedMessenger<
145+
export type MultichainAssetsControllerMessenger = Messenger<
145146
typeof controllerName,
146147
MultichainAssetsControllerActions | AllowedActions,
147-
MultichainAssetsControllerEvents | AllowedEvents,
148-
AllowedActions['type'],
149-
AllowedEvents['type']
148+
MultichainAssetsControllerEvents | AllowedEvents
150149
>;
151150

152151
/**
@@ -156,20 +155,21 @@ export type MultichainAssetsControllerMessenger = RestrictedMessenger<
156155
* using the `persist` flag; and if they can be sent to Sentry or not, using
157156
* the `anonymous` flag.
158157
*/
159-
const assetsControllerMetadata = {
160-
assetsMetadata: {
161-
includeInStateLogs: false,
162-
persist: true,
163-
anonymous: false,
164-
usedInUi: true,
165-
},
166-
accountsAssets: {
167-
includeInStateLogs: false,
168-
persist: true,
169-
anonymous: false,
170-
usedInUi: true,
171-
},
172-
};
158+
const assetsControllerMetadata: StateMetadata<MultichainAssetsControllerState> =
159+
{
160+
assetsMetadata: {
161+
includeInStateLogs: false,
162+
persist: true,
163+
includeInDebugSnapshot: false,
164+
usedInUi: true,
165+
},
166+
accountsAssets: {
167+
includeInStateLogs: false,
168+
persist: true,
169+
includeInDebugSnapshot: false,
170+
usedInUi: true,
171+
},
172+
};
173173

174174
// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.
175175

@@ -202,15 +202,15 @@ export class MultichainAssetsController extends BaseController<
202202

203203
this.#snaps = {};
204204

205-
this.messagingSystem.subscribe(
205+
this.messenger.subscribe(
206206
'AccountsController:accountAdded',
207207
async (account) => await this.#handleOnAccountAddedEvent(account),
208208
);
209-
this.messagingSystem.subscribe(
209+
this.messenger.subscribe(
210210
'AccountsController:accountRemoved',
211211
async (account) => await this.#handleOnAccountRemovedEvent(account),
212212
);
213-
this.messagingSystem.subscribe(
213+
this.messenger.subscribe(
214214
'AccountsController:accountAssetListUpdated',
215215
async (event) => await this.#handleAccountAssetListUpdatedEvent(event),
216216
);
@@ -237,7 +237,7 @@ export class MultichainAssetsController extends BaseController<
237237
* actions.
238238
*/
239239
#registerMessageHandlers() {
240-
this.messagingSystem.registerActionHandler(
240+
this.messenger.registerActionHandler(
241241
'MultichainAssetsController:getAssetMetadata',
242242
this.getAssetMetadata.bind(this),
243243
);
@@ -323,7 +323,7 @@ export class MultichainAssetsController extends BaseController<
323323
// Trigger fetching metadata for new assets
324324
await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));
325325

326-
this.messagingSystem.publish(`${controllerName}:accountAssetListUpdated`, {
326+
this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {
327327
assets: accountsAndAssetsToUpdate,
328328
});
329329
}
@@ -364,17 +364,14 @@ export class MultichainAssetsController extends BaseController<
364364
this.update((state) => {
365365
state.accountsAssets[account.id] = assets;
366366
});
367-
this.messagingSystem.publish(
368-
`${controllerName}:accountAssetListUpdated`,
369-
{
370-
assets: {
371-
[account.id]: {
372-
added: assets,
373-
removed: [],
374-
},
367+
this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {
368+
assets: {
369+
[account.id]: {
370+
added: assets,
371+
removed: [],
375372
},
376373
},
377-
);
374+
});
378375
}
379376
}
380377

@@ -510,7 +507,7 @@ export class MultichainAssetsController extends BaseController<
510507
*/
511508
#getAllSnaps(): Snap[] {
512509
// TODO: Use dedicated SnapController's action once available for this:
513-
return this.messagingSystem
510+
return this.messenger
514511
.call('SnapController:getAll')
515512
.filter((snap) => snap.enabled && !snap.blocked);
516513
}
@@ -524,7 +521,7 @@ export class MultichainAssetsController extends BaseController<
524521
#getSnapsPermissions(
525522
origin: string,
526523
): SubjectPermissions<PermissionConstraint> {
527-
return this.messagingSystem.call(
524+
return this.messenger.call(
528525
'PermissionController:getPermissions',
529526
origin,
530527
) as SubjectPermissions<PermissionConstraint>;
@@ -542,7 +539,7 @@ export class MultichainAssetsController extends BaseController<
542539
snapId: string,
543540
): Promise<AssetMetadataResponse | undefined> {
544541
try {
545-
return (await this.messagingSystem.call('SnapController:handleRequest', {
542+
return (await this.messenger.call('SnapController:handleRequest', {
546543
snapId: snapId as SnapId,
547544
origin: 'metamask',
548545
handler: HandlerType.OnAssetsLookup,
@@ -584,7 +581,7 @@ export class MultichainAssetsController extends BaseController<
584581
#getClient(snapId: string): KeyringClient {
585582
return new KeyringClient({
586583
send: async (request: JsonRpcRequest) =>
587-
(await this.messagingSystem.call('SnapController:handleRequest', {
584+
(await this.messenger.call('SnapController:handleRequest', {
588585
snapId: snapId as SnapId,
589586
origin: 'metamask',
590587
handler: HandlerType.OnKeyringRequest,

0 commit comments

Comments
 (0)