Skip to content
Merged
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ linkStyle default opacity:0.5
phishing_controller(["@metamask/phishing-controller"]);
preferences_controller(["@metamask/preferences-controller"]);
rate_limit_controller(["@metamask/rate-limit-controller"]);
selected_network_controller(["@metamask/selected-network-controller"]);
signature_controller(["@metamask/signature-controller"]);
transaction_controller(["@metamask/transaction-controller"]);
address_book_controller --> base_controller;
Expand Down Expand Up @@ -91,6 +92,8 @@ linkStyle default opacity:0.5
preferences_controller --> base_controller;
preferences_controller --> controller_utils;
rate_limit_controller --> base_controller;
selected_network_controller --> base_controller;
selected_network_controller --> network_controller;
signature_controller --> approval_controller;
signature_controller --> base_controller;
signature_controller --> controller_utils;
Expand Down
9 changes: 9 additions & 0 deletions packages/selected-network-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# 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/selected-network-controller/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
MIT License

Copyright (c) 2023 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
20 changes: 20 additions & 0 deletions packages/selected-network-controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# `@metamask/selected-network-controller`

Provides an interface to the currently selected networkClientId for a given domain.

Domain here means one of two things:

- the jsonrpc request originated from a dapp (domain is the origin/url of the dapp)
- the jsonrpc request originated interally to metamask (the domain is here is 'metamask')
Copy link
Member

Choose a reason for hiding this comment

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

json-rpc or JSON-RPC?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

/shrug


## Installation

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

or

`npm install @metamask/selected-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).
30 changes: 30 additions & 0 deletions packages/selected-network-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: 100,
functions: 100,
lines: 100,
statements: 100,
Copy link
Member

Choose a reason for hiding this comment

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

💯!!!

},
},

// Currently the tests for NetworkController have a race condition which
// causes intermittent failures. This seems to fix it.
testEnvironment: 'jsdom',
});
59 changes: 59 additions & 0 deletions packages/selected-network-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@metamask/selected-network-controller",
"version": "0.0.0",
"description": "Provides an interface to the currently selected networkClientId for a given domain",
"keywords": [
"MetaMask",
"Ethereum"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/selected-network-controller#readme",
"bugs": {
"url": "https://github.com/MetaMask/core/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/core.git"
},
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist/"
],
"scripts": {
"build:docs": "typedoc",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/selected-network-controller",
"publish:preview": "yarn npm publish --tag preview",
"test": "jest",
"test:watch": "jest --watch"
},
"dependencies": {
"@metamask/base-controller": "^3.2.1",
"@metamask/network-controller": "^12.1.2",
"json-rpc-engine": "^6.1.0"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.1.0",
"@types/jest": "^27.4.1",
"deepmerge": "^4.2.2",
"immer": "^9.0.6",
"jest": "^27.5.1",
"lodash": "^4.17.21",
"nock": "^13.3.1",
"sinon": "^9.2.4",
"ts-jest": "^27.1.4",
"typedoc": "^0.22.15",
"typedoc-plugin-missing-exports": "^0.22.6",
"typescript": "~4.6.3"
},
"peerDependencies": {
"@metamask/network-controller": "^12.1.2"
},
"engines": {
"node": ">=16.0.0"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
import { BaseControllerV2 } from '@metamask/base-controller';
import type {
NetworkClientId,
NetworkControllerStateChangeEvent,
NetworkState,
} from '@metamask/network-controller';
import type { Patch } from 'immer';

const controllerName = 'SelectedNetworkController';

const stateMetadata = {
domains: { persist: true, anonymous: false },
perDomainNetwork: { persist: true, anonymous: false },
};

const getDefaultState = () => ({
domains: {},
perDomainNetwork: false,
});

type Domain = string;

const METAMASK_DOMAIN = 'metamask' as const;

export const SelectedNetworkControllerActionTypes = {
getState: `${controllerName}:getState` as const,
getNetworkClientIdForDomain:
`${controllerName}:getNetworkClientIdForDomain` as const,
setNetworkClientIdForDomain:
`${controllerName}:setNetworkClientIdForDomain` as const,
};

export const SelectedNetworkControllerEventTypes = {
stateChange: `${controllerName}:stateChange` as const,
};

export type SelectedNetworkControllerState = {
domains: Record<Domain, NetworkClientId>;
/**
* Feature flag to start returning networkClientId based on the domain.
* when the flag is false, the 'metamask' domain will always be used.
* defaults to false
*/
perDomainNetwork: boolean;
};

export type SelectedNetworkControllerStateChangeEvent = {
type: typeof SelectedNetworkControllerEventTypes.stateChange;
payload: [SelectedNetworkControllerState, Patch[]];
};

export type SelectedNetworkControllerGetSelectedNetworkStateAction = {
type: typeof SelectedNetworkControllerActionTypes.getState;
handler: () => SelectedNetworkControllerState;
};

export type SelectedNetworkControllerGetNetworkClientIdForDomainAction = {
type: typeof SelectedNetworkControllerActionTypes.getNetworkClientIdForDomain;
handler: (domain: string) => NetworkClientId;
};

export type SelectedNetworkControllerSetNetworkClientIdForDomainAction = {
type: typeof SelectedNetworkControllerActionTypes.setNetworkClientIdForDomain;
handler: (domain: string, NetworkClientId: NetworkClientId) => void;
};

export type SelectedNetworkControllerAction =
| SelectedNetworkControllerGetSelectedNetworkStateAction
| SelectedNetworkControllerGetNetworkClientIdForDomainAction
| SelectedNetworkControllerSetNetworkClientIdForDomainAction;

export type SelectedNetworkControllerEvent =
SelectedNetworkControllerStateChangeEvent;

export type SelectedNetworkControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
SelectedNetworkControllerAction,
NetworkControllerStateChangeEvent | SelectedNetworkControllerEvent,
string,
string
>;

export type SelectedNetworkControllerOptions = {
messenger: SelectedNetworkControllerMessenger;
};

/**
* Controller for getting and setting the network for a particular domain.
*/
export class SelectedNetworkController extends BaseControllerV2<
typeof controllerName,
SelectedNetworkControllerState,
SelectedNetworkControllerMessenger
> {
/**
* Construct a SelectedNetworkController controller.
*
* @param options - The controller options.
* @param options.messenger - The restricted controller messenger for the EncryptionPublicKey controller.
*/
constructor({ messenger }: SelectedNetworkControllerOptions) {
super({
name: controllerName,
metadata: stateMetadata,
messenger,
state: getDefaultState(),
});
this.#registerMessageHandlers();
}

#registerMessageHandlers(): void {
this.messagingSystem.registerActionHandler(
SelectedNetworkControllerActionTypes.getNetworkClientIdForDomain,
this.getNetworkClientIdForDomain.bind(this),
);

this.messagingSystem.registerActionHandler(
SelectedNetworkControllerActionTypes.setNetworkClientIdForDomain,
this.setNetworkClientIdForDomain.bind(this),
);

// subscribe to networkController statechange:: selectedNetworkClientId changed
// update the value for the domain 'metamask'
this.messagingSystem.subscribe(
'NetworkController:stateChange',
(state: NetworkState, patch: Patch[]) => {
const isChangingNetwork = patch.some(
(p) => p.path[0] === 'selectedNetworkClientId',
);
if (!isChangingNetwork) {
return;
}

// set it for the 'global' network to preserve functionality for the
// selectedNetworkController.perDomainNetwork feature flag being off
this.setNetworkClientIdForMetamask(state.selectedNetworkClientId);
},
);
}

setNetworkClientIdForMetamask(networkClientId: NetworkClientId) {
this.setNetworkClientIdForDomain(METAMASK_DOMAIN, networkClientId);
}

setNetworkClientIdForDomain(
domain: Domain,
networkClientId: NetworkClientId,
) {
this.update((state) => {
state.domains[domain] = networkClientId;
});
}

getNetworkClientIdForDomain(domain: Domain) {
if (this.state.perDomainNetwork) {
return this.state.domains[domain];
}
return this.state.domains[METAMASK_DOMAIN];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { ControllerMessenger } from '@metamask/base-controller';
import type {
NetworkClientId,
NetworkControllerGetStateAction,
} from '@metamask/network-controller';
import type { JsonRpcMiddleware } from 'json-rpc-engine';

import type {
SelectedNetworkControllerGetNetworkClientIdForDomainAction,
SelectedNetworkControllerSetNetworkClientIdForDomainAction,
} from './SelectedNetworkController';
import { SelectedNetworkControllerActionTypes } from './SelectedNetworkController';

export const createSelectedNetworkMiddleware = (
messenger: ControllerMessenger<
| SelectedNetworkControllerGetNetworkClientIdForDomainAction
| SelectedNetworkControllerSetNetworkClientIdForDomainAction
| NetworkControllerGetStateAction,
never
>,
): JsonRpcMiddleware<any, any> => {
const getNetworkClientIdForDomain = (origin: string) =>
messenger.call(
SelectedNetworkControllerActionTypes.getNetworkClientIdForDomain,
origin,
);

const setNetworkClientIdForDomain = (
origin: string,
networkClientId: NetworkClientId,
) =>
messenger.call(
SelectedNetworkControllerActionTypes.setNetworkClientIdForDomain,
origin,
networkClientId,
);

const getDefaultNetworkClientId = () =>
messenger.call('NetworkController:getState').selectedNetworkClientId;

return (req: any, _, next) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

There is nothing we can really do about this now, but we really ought to figure out another way we can set custom metadata on a request without having to use any :(

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah for sure, Ill try to think of something we can do there.

if (getNetworkClientIdForDomain(req.origin) === undefined) {
setNetworkClientIdForDomain(req.origin, getDefaultNetworkClientId());
}

req.networkClientId = getNetworkClientIdForDomain(req.origin);
return next();
};
};
2 changes: 2 additions & 0 deletions packages/selected-network-controller/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './SelectedNetworkController';
export * from './SelectedNetworkMiddleware';
Loading