Skip to content

chore: create network order controller #6022

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

## Assets Team
/packages/assets-controllers @MetaMask/metamask-assets
/packages/network-order-controller @MetaMask/metamask-assets

## Confirmations Team
/packages/address-book-controller @MetaMask/confirmations
Expand Down Expand Up @@ -153,3 +154,5 @@
/packages/foundryup/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/wallet-framework-engineers
/packages/seedless-onboarding-controller/package.json @MetaMask/web3auth @MetaMask/wallet-framework-engineers
/packages/seedless-onboarding-controller/CHANGELOG.md @MetaMask/web3auth @MetaMask/wallet-framework-engineers
/packages/network-order-controller/package.json @MetaMask/metamask-assets @MetaMask/wallet-framework-engineers
/packages/network-order-controller/CHANGELOG.md @MetaMask/metamask-assets @MetaMask/wallet-framework-engineers
2 changes: 2 additions & 0 deletions README.md
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you re-run yarn update-readme-content? It looks like some dependencies are not reflected here.

Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Each package in this repository has its own README where you can find installati
- [`@metamask/multichain-transactions-controller`](packages/multichain-transactions-controller)
- [`@metamask/name-controller`](packages/name-controller)
- [`@metamask/network-controller`](packages/network-controller)
- [`@metamask/network-order-controller`](packages/network-order-controller)
- [`@metamask/notification-services-controller`](packages/notification-services-controller)
- [`@metamask/permission-controller`](packages/permission-controller)
- [`@metamask/permission-log-controller`](packages/permission-log-controller)
Expand Down Expand Up @@ -109,6 +110,7 @@ linkStyle default opacity:0.5
multichain_transactions_controller(["@metamask/multichain-transactions-controller"]);
name_controller(["@metamask/name-controller"]);
network_controller(["@metamask/network-controller"]);
network_order_controller(["@metamask/network-order-controller"]);
notification_services_controller(["@metamask/notification-services-controller"]);
permission_controller(["@metamask/permission-controller"]);
permission_log_controller(["@metamask/permission-log-controller"]);
Expand Down
14 changes: 14 additions & 0 deletions packages/network-order-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Initial release ([#6022](https://github.com/MetaMask/core/pull/6022))

[Unreleased]: https://github.com/MetaMask/core/
20 changes: 20 additions & 0 deletions packages/network-order-controller/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
MIT License

Copyright (c) 2025 MetaMask

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
15 changes: 15 additions & 0 deletions packages/network-order-controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# `@metamask/network-order-controller`

Provides an interface to the currently network order via a MetaMask-compatible provider object
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: what do you think about rephrasing this to ?

Suggested change
Provides an interface to the currently network order via a MetaMask-compatible provider object
Provides an interface to the current network display order via a MetaMask-compatible provider object


## Installation

`yarn add @metamask/network-order-controller`

or

`npm install @metamask/network-order-controller`

## Contributing

This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
30 changes: 30 additions & 0 deletions packages/network-order-controller/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

const merge = require('deepmerge');
const path = require('path');

const baseConfig = require('../../jest.config.packages');

const displayName = path.basename(__dirname);

module.exports = merge(baseConfig, {
// The display name when running multiple projects
displayName,

// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 88.47,
functions: 97.43,
lines: 94.47,
statements: 94.29,
},
},

// Currently the tests for NetworkController have a race condition which
// causes intermittent failures. This seems to fix it.
testEnvironment: 'jsdom',
Comment on lines +26 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: do you think we can drop this as may not be related to this controller ?

});
73 changes: 73 additions & 0 deletions packages/network-order-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"name": "@metamask/network-order-controller",
"version": "0.0.0",
"description": "Provides an interface to the currently network order via a MetaMask-compatible provider object",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: to align with README, if you opt in for the suggestion

Suggested change
"description": "Provides an interface to the currently network order via a MetaMask-compatible provider object",
"description": "Provides an interface to the current network display order via a MetaMask-compatible provider object",

"keywords": [
"MetaMask",
"Ethereum"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/network-order-controller#readme",
"bugs": {
"url": "https://github.com/MetaMask/core/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/core.git"
},
"license": "MIT",
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"files": [
"dist/"
],
"scripts": {
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
"build:docs": "typedoc",
"changelog:update": "../../scripts/update-changelog.sh @metamask/network-order-controller",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/network-order-controller",
"publish:preview": "yarn npm publish --tag preview",
"since-latest-release": "../../scripts/since-latest-release.sh",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@types/jest": "^27.4.1",
"deepmerge": "^4.2.2",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"typedoc": "^0.24.8",
"typedoc-plugin-missing-exports": "^2.0.0",
"typescript": "~5.2.2"
},
"dependencies": {
"@metamask/base-controller": "^8.0.1",
"@metamask/keyring-api": "^18.0.0",
"@metamask/multichain-network-controller": "^0.9.0",
"@metamask/utils": "^11.2.0",
"@metamask/network-controller": "^24.0.0"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this controller talks to NetworkController, should this be a peer dependency instead?

},
"engines": {
"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
168 changes: 168 additions & 0 deletions packages/network-order-controller/src/NetworkOrderController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { BaseController } from '@metamask/base-controller';
import type { RestrictedMessenger } from '@metamask/base-controller';
import { BtcScope, SolScope } from '@metamask/keyring-api';
import { toEvmCaipChainId } from '@metamask/multichain-network-controller';
import type {
NetworkControllerStateChangeEvent,
NetworkState,
} from '@metamask/network-controller';
import type { CaipChainId, Hex } from '@metamask/utils';
import type { Patch } from 'immer';

import { TEST_CHAINS } from './constant';

// Unique name for the controller
const controllerName = 'NetworkOrderController';

/**
* Information about an ordered network.
*/
export type NetworksInfo = {
networkId: CaipChainId; // The network's chain id
};

// State shape for NetworkOrderController
export type NetworkOrderControllerState = {
orderedNetworkList: NetworksInfo[];
};

// Describes the structure of a state change event
export type NetworkOrderStateChange = {
type: `${typeof controllerName}:stateChange`;
payload: [NetworkOrderControllerState, Patch[]];
};
Comment on lines +30 to +33
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export type NetworkOrderStateChange = {
type: `${typeof controllerName}:stateChange`;
payload: [NetworkOrderControllerState, Patch[]];
};
export type NetworkOrderStateControllerChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
NetworkOrderControllerState
>;
export type NetworkOrderControllerEvents = NetworkOrderStateControllerChangeEvent;
/**
* All events that {@link NetworkOrderController} calls internally.
*/
type AllowedEvents = NetworkControllerStateChangeEvent;


// Describes the action for updating the networks list
export type NetworkOrderControllerupdateNetworksListAction = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export type NetworkOrderControllerupdateNetworksListAction = {
export type NetworkOrderControllerUpdateNetworksListAction = {

type: `${typeof controllerName}:updateNetworksList`;
handler: NetworkOrderController['updateNetworksList'];
};

// Union of all possible actions for the messenger
export type NetworkOrderControllerMessengerActions =
NetworkOrderControllerupdateNetworksListAction;
Comment on lines +41 to +43
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Union of all possible actions for the messenger
export type NetworkOrderControllerMessengerActions =
NetworkOrderControllerupdateNetworksListAction;
// Union of all possible actions for the messenger
export type NetworkOrderControllerActions =
NetworkOrderControllerUpdateNetworksListAction;
/**
* All actions that {@link NetworkOrderControlle} calls internally.
*/
type AllowedActions = never;


// Type for the messenger of NetworkOrderController
export type NetworkOrderControllerMessenger = RestrictedMessenger<
typeof controllerName,
NetworkOrderControllerMessengerActions,
NetworkOrderStateChange | NetworkControllerStateChangeEvent,
never,
NetworkOrderStateChange['type'] | NetworkControllerStateChangeEvent['type']
>;
Comment on lines +45 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Type for the messenger of NetworkOrderController
export type NetworkOrderControllerMessenger = RestrictedMessenger<
typeof controllerName,
NetworkOrderControllerMessengerActions,
NetworkOrderStateChange | NetworkControllerStateChangeEvent,
never,
NetworkOrderStateChange['type'] | NetworkControllerStateChangeEvent['type']
>;
// Type for the messenger of NetworkOrderController
export type NetworkOrderControllerMessenger = RestrictedMessenger<
typeof controllerName,
NetworkOrderControllerActions | AllowedActions,
NetworkOrderControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;


// Default state for the controller
const defaultState: NetworkOrderControllerState = {
orderedNetworkList: [],
};
Comment on lines +55 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we convert this to a method getDefaultNetworkOrderControllerState


// Metadata for the controller state
const metadata = {
orderedNetworkList: {
persist: true,
anonymous: true,
},
};

/**
* Controller that updates the order of the network list.
* This controller subscribes to network state changes and ensures
* that the network list is updated based on the latest network configurations.
*/

export class NetworkOrderController extends BaseController<
typeof controllerName,
NetworkOrderControllerState,
NetworkOrderControllerMessenger
> {
/**
* Creates a NetworkOrderController instance.
*
* @param args - The arguments to this function.
* @param args.messenger - Messenger used to communicate with BaseV2 controller.
* @param args.state - Initial state to set on this controller.
*/
constructor({
messenger,
state,
}: {
messenger: NetworkOrderControllerMessenger;
state?: NetworkOrderControllerState;
}) {
// Call the constructor of BaseControllerV2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this comment can be dropped

Suggested change
// Call the constructor of BaseControllerV2

super({
messenger,
metadata,
name: controllerName,
state: { ...defaultState, ...state },
});

// Subscribe to network state changes
this.messagingSystem.subscribe(
'NetworkController:stateChange',
(networkControllerState: NetworkState) => {
this.onNetworkControllerStateChange(networkControllerState);
},
);
}

/**
* Handles the state change of the network controller and updates the networks list.
*
* @param networkControllerState - The state of the network controller.
* @param networkControllerState.networkConfigurationsByChainId - The network configurations by chain id.
*/
onNetworkControllerStateChange({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this method can be private ?

Suggested change
onNetworkControllerStateChange({
#onNetworkControllerStateChange({

networkConfigurationsByChainId,
}: NetworkState) {
this.update((state: NetworkOrderControllerState) => {
// Filter out testnets, which are in the state but not orderable
const hexChainIds = Object.keys(networkConfigurationsByChainId).filter(
(chainId) =>
!TEST_CHAINS.includes(chainId as (typeof TEST_CHAINS)[number]),
) as Hex[];
const chainIds: CaipChainId[] = hexChainIds.map(toEvmCaipChainId);
const nonEvmChainIds: CaipChainId[] = [
BtcScope.Mainnet,
SolScope.Mainnet,
];

const newNetworks = chainIds
.filter(
(chainId) =>
!state.orderedNetworkList.some(
({ networkId }: { networkId: CaipChainId }) =>
networkId === chainId,
),
)
.map((chainId) => ({ networkId: chainId }));

state.orderedNetworkList = state.orderedNetworkList
// Filter out deleted networks
.filter(
({ networkId }: { networkId: CaipChainId }) =>
chainIds.includes(networkId) ||
// Since Bitcoin and Solana are not part of the @metamask/network-controller, we have
// to add a second check to make sure it is not filtered out.
// TODO: Update this logic to @metamask/multichain-network-controller once all networks are migrated.
nonEvmChainIds.includes(networkId),
)
// Append new networks to the end
.concat(newNetworks);
});
}

/**
* Updates the networks list in the state with the provided list of networks.
*
* @param networkList - The list of networks to update in the state.
*/

updateNetworksList(chainIds: CaipChainId[]) {
this.update((state: NetworkOrderControllerState) => {
state.orderedNetworkList = chainIds.map((chainId) => ({
networkId: chainId,
}));
});
}
}
9 changes: 9 additions & 0 deletions packages/network-order-controller/src/constant.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this file be called constants.ts?

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { Hex } from '@metamask/utils';

export const TEST_CHAINS: Hex[] = [
'0xaa36a7',
'0xe705',
'0x539',
'0x18c6',
'0x279f',
Comment on lines +4 to +8
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add comments to document what these are?

];
10 changes: 10 additions & 0 deletions packages/network-order-controller/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export {
NetworkOrderController,
type NetworkOrderControllerState,
type NetworkOrderControllerMessenger,
type NetworkOrderControllerMessengerActions,
type NetworkOrderStateChange,
type NetworksInfo,
} from './NetworkOrderController';

export { TEST_CHAINS } from './constant';
Loading
Loading