Skip to content
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

feat: Add multichain-network-controller package #5209

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
10 changes: 10 additions & 0 deletions packages/multichain-network-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# 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]

[Unreleased]: https://github.com/MetaMask/core/
20 changes: 20 additions & 0 deletions packages/multichain-network-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/multichain-network-controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# `@metamask/multichain-network-controller`

...

## Installation

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

or

`npm install @metamask/multichain-network-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).
26 changes: 26 additions & 0 deletions packages/multichain-network-controller/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
});
73 changes: 73 additions & 0 deletions packages/multichain-network-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"name": "@metamask/multichain-network-controller",
"version": "0.0.0",
"private": true,
"description": "Multichain network controller",
"keywords": [
"MetaMask",
"Ethereum"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/multichain-network-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/multichain-network-controller",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/multichain-network-controller",
"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"
},
"dependencies": {
"@metamask/base-controller": "^7.1.1",
"@metamask/keyring-api": "^16.1.0",
"@metamask/utils": "^11.0.1"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@types/jest": "^27.4.1",
"deepmerge": "^4.2.2",
"immer": "^9.0.6",
"jest": "^27.5.1",
"nock": "^13.3.1",
"ts-jest": "^27.1.4",
"typedoc": "^0.24.8",
"typedoc-plugin-missing-exports": "^2.0.0",
"typescript": "~5.2.2"
},
"peerDependencies": {
"@metamask/accounts-controller": "^21.0.1",
"@metamask/network-controller": "^22.1.1"
},
"engines": {
"node": "^18.18 || >=20"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { ControllerMessenger } from '@metamask/base-controller';
import type {
AllowedActions,
AllowedEvents,
} from './MultichainNetworkController';

import { MultichainNetworkController } from './MultichainNetworkController';

const name = 'MultichainNetworkController';

const buildMessenger = () => {
return new ControllerMessenger<AllowedActions, AllowedEvents>();
};

const buildMultichainNetworkControllerMessenger = (
messenger: ControllerMessenger<AllowedActions, AllowedEvents>,
) => {
return messenger.getRestricted<typeof name, 'NetworkController:setActiveNetwork', never>({
name,
allowedActions: ['NetworkController:setActiveNetwork'],
allowedEvents: [],
});
};

describe('MultichainNetworkController', () => {
let controller: MultichainNetworkController;
let messenger: ControllerMessenger<AllowedActions, AllowedEvents>;

beforeEach(() => {
messenger = buildMessenger();
Copy link
Contributor

Choose a reason for hiding this comment

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

Rather than setting up tests using beforeEach — which can make things complicated over time — what are your thoughts on using a helper method to set up the controller in each test? Unfortunately we don't have a great example of this in core, but NftController has one called setupController that works pretty well:

In your case I'm imagining something like:

/**
 * Constructs a new global messenger for use in tests.
 *
 * @returns A new instance of ControllerMessenger that supports the actions and
 * events MultichainNetworkController needs to access.
 */
function getGlobalMessenger() {
  return new ControllerMessenger<
    MultichainNetworkControllerActions | AllowedActions,
    MultichainNetworkControllerEvents | AllowedEvents
  >();
}

/**
 * Constructs the messenger which is restricted for
 * MultichainNetworkController.
 *
 * @param globalMessenger - The global messenger to base the messenger from.
 * @returns The restricted messenger for MultichainNetworkController.
 */
function getControllerMessenger(
  globalMessenger = getGlobalMessenger(),
): MultichainNetworkControllerMessenger {
  return globalMessenger.getRestricted({
    name: 'MultichainNetworkController',
    allowedActions: ['NetworkController:setActiveNetwork'],
    allowedEvents: [],
  });
}

/**
 * Constructs the MultichainNetworkController and the global messenger for use
 * in tests.
 *
 * @param args - Arguments to this function.
 * @param args.options - Controller options.
 * @param args.mockSetActiveNetwork - The handler to use for the
 * `NetworkController:setActiveNetwork` action.
 * @returns The MultichainNetworkController and the global messenger.
 */
function setupController({
  options,
  mockSetActiveNetwork = jest.fn(async () => {
    // do nothing
  }),
}: {
  options?: Partial<
    ConstructorParameters<typeof MultichainNetworkController>[0]
  >;
  mockSetActiveNetwork?: NetworkControllerSetActiveNetworkAction['handler'];
}) {
  const messenger = getGlobalMessenger();
  messenger.registerActionHandler(
    'NetworkController:setActiveNetwork',
    mockSetActiveNetwork,
  );

  const controllerMessenger = getControllerMessenger(messenger);

  const controller = new MultichainNetworkController({
    ...options,
    messenger: controllerMessenger,
  });

  return { controller, messenger };
}

Then you don't need to spy on the messenger, you can just pass in a function or mock function that lets you override the setActiveNetwork call.

messenger.registerActionHandler(
'NetworkController:setActiveNetwork',
jest.fn(),
);

jest.spyOn(messenger, 'call');

const restrictedMessenger = buildMultichainNetworkControllerMessenger(messenger);

controller = new MultichainNetworkController({
messenger: restrictedMessenger,
state: {
multichainNetworkConfigurationsByChainId: {},
selectedMultichainNetworkChainId: bitcoinCaip2ChainId,
multichainNetworksMetadata: {},
nonEvmSelected: false,
},
});
});

describe('setActiveNetwork', () => {
it('should set non-EVM network when valid chainId is provided', async () => {
const clientId = 'testClient';
const chainId = 'bip122:000000000019d6689c085ae165831e93';
messenger = buildMessenger();
messenger.registerActionHandler(
'NetworkController:setActiveNetwork',
jest.fn(),
);

jest.spyOn(messenger, 'call');

const restrictedMessenger = buildMultichainNetworkControllerMessenger(messenger);

const multiChainController = new MultichainNetworkController({
messenger: restrictedMessenger,
state: {
multichainNetworkConfigurationsByChainId: {
[chainId]: {
chainId,
name: 'Bitcoin',
nativeCurrency: 'BTC',
blockExplorerUrls: ['https://blockstream.info/'],
},
},
selectedMultichainNetworkChainId: bitcoinCaip2ChainId,
multichainNetworksMetadata: {},
nonEvmSelected: false,
},
});

await multiChainController.setActiveNetwork(clientId, chainId);

expect(multiChainController.state.selectedMultichainNetworkChainId).toBe(chainId);
expect(multiChainController.state.nonEvmSelected).toBe(true);
expect(messenger.call).not.toHaveBeenCalled();
});

it('should set EVM network when chainId is not provided', async () => {
const clientId = 'testClient';

await controller.setActiveNetwork(clientId);

expect(controller.state.nonEvmSelected).toBe(false);
expect(messenger.call).toHaveBeenCalledWith(
'NetworkController:setActiveNetwork',
clientId,
);
});

it('should set EVM network when invalid chainId is provided', async () => {
const clientId = 'testClient';
const invalidChainId = 'invalid-chain-id';

await controller.setActiveNetwork(clientId, invalidChainId);

expect(controller.state.nonEvmSelected).toBe(false);
expect(messenger.call).toHaveBeenCalledWith(
'NetworkController:setActiveNetwork',
clientId,
);
});
});

describe('setNonEvmSelected', () => {
it('should set nonEvmSelected to true', () => {
controller.setNonEvmSelected();
expect(controller.state.nonEvmSelected).toBe(true);
});
});

describe('setEvmSelected', () => {
it('should set nonEvmSelected to false', () => {
messenger = buildMessenger();
messenger.registerActionHandler(
'NetworkController:setActiveNetwork',
jest.fn(),
);

jest.spyOn(messenger, 'call');

const restrictedMessenger = buildMultichainNetworkControllerMessenger(messenger);
const multiChainController = new MultichainNetworkController({
messenger: restrictedMessenger,
state: {
multichainNetworkConfigurationsByChainId: {},
selectedMultichainNetworkChainId: bitcoinCaip2ChainId,
multichainNetworksMetadata: {},
nonEvmSelected: true,
},
});

multiChainController.setEvmSelected();
expect(multiChainController.state.nonEvmSelected).toBe(false);
});
});
});
Loading