Skip to content

Commit c55c7b4

Browse files
mcmiremikesposito
andauthored
Add example controllers (#4550)
## 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 commit adds controllers which are not meant to be published, but instead serve as models to exemplify best practices for writing controllers, fulfilling a long-standing need. The controllers included here are implemented within a complete package which is linted just like other packages, and they ship with working tests which are run just like other tests. This lessens the chance that they will fall out of date in the future. The two controllers included in this commit are called `GasPricesController` and `PetNamesController`, which are roughly based on, but intentionally not drawn from, `GasFeeController` and `AddressBookController`. They demonstrate the following best practices: - Setting up a common structure for controllers, including creating complete types for the messenger and for state - Using the messenger to access data from another controller - Using service objects to make HTTP requests - Mocking the messenger in tests - Creating mock service objects - Mocking time in tests Certainly, more best practices can be demonstrated, but this should be a good first start. ## 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? For example: * Fixes #12345 * Related to #67890 --> Progresses #4504. ## Changelog <!-- If you're making any consumer-facing changes, list those changes here as if you were updating a changelog, using the template below as a guide. (CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or FIXED. For security-related issues, follow the Security Advisory process.) Please take care to name the exact pieces of the API you've added or changed (e.g. types, interfaces, functions, or methods). If there are any breaking changes, make sure to offer a solution for consumers to follow once they upgrade to the changes. Finally, if you're only making changes to development scripts or tests, you may replace the template below with "None". --> (No consumer-facing changes in this commit.) ## Checklist - [x] I've updated the test suite for new or updated code as appropriate - [x] I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate - [x] I've highlighted breaking changes using the "BREAKING" category above as appropriate --------- Co-authored-by: Michele Esposito <34438276+mikesposito@users.noreply.github.com> Co-authored-by: Michele Esposito <michele@esposito.codes>
1 parent 3c15eaf commit c55c7b4

22 files changed

+1173
-1
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ package-lock.json
1515
# Build preview message
1616
preview-build-message.txt
1717

18+
examples/*/coverage
19+
examples/*/dist
20+
examples/*/docs
1821
packages/*/coverage
1922
packages/*/dist
2023
packages/*/docs
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [Unreleased]
9+
10+
[Unreleased]: https://github.com/MetaMask/core/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
MIT License
2+
3+
Copyright (c) 2024 MetaMask
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# `@metamask/example-controllers`
2+
3+
This package is designed to illustrate best practices for controller packages and controller files, including tests.
4+
5+
## Installation
6+
7+
`yarn add @metamask/example-controllers`
8+
9+
or
10+
11+
`npm install @metamask/example-controllers`
12+
13+
## Contributing
14+
15+
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* For a detailed explanation regarding each configuration property and type check, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
const merge = require('deepmerge');
7+
const path = require('path');
8+
9+
const baseConfig = require('../../jest.config.packages');
10+
11+
const displayName = path.basename(__dirname);
12+
13+
module.exports = merge(baseConfig, {
14+
// The display name when running multiple projects
15+
displayName,
16+
17+
// An object that configures minimum threshold enforcement for coverage results
18+
coverageThreshold: {
19+
global: {
20+
branches: 100,
21+
functions: 100,
22+
lines: 100,
23+
statements: 100,
24+
},
25+
},
26+
});
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"name": "@metamask/example-controllers",
3+
"version": "0.0.0",
4+
"private": true,
5+
"description": "Example package to illustrate best practices for controllers",
6+
"keywords": [
7+
"MetaMask",
8+
"Ethereum"
9+
],
10+
"homepage": "https://github.com/MetaMask/core/tree/main/packages/example-controllers#readme",
11+
"bugs": {
12+
"url": "https://github.com/MetaMask/core/issues"
13+
},
14+
"repository": {
15+
"type": "git",
16+
"url": "https://github.com/MetaMask/core.git"
17+
},
18+
"license": "MIT",
19+
"sideEffects": false,
20+
"exports": {
21+
".": {
22+
"import": {
23+
"types": "./dist/index.d.mts",
24+
"default": "./dist/index.mjs"
25+
},
26+
"require": {
27+
"types": "./dist/index.d.cts",
28+
"default": "./dist/index.cjs"
29+
}
30+
},
31+
"./package.json": "./package.json"
32+
},
33+
"main": "./dist/index.cjs",
34+
"types": "./dist/index.d.cts",
35+
"files": [
36+
"dist/"
37+
],
38+
"scripts": {
39+
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
40+
"build:docs": "typedoc",
41+
"changelog:update": "../../scripts/update-changelog.sh @metamask/example-controllers",
42+
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/example-controllers",
43+
"since-latest-release": "../../scripts/since-latest-release.sh",
44+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
45+
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
46+
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
47+
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
48+
},
49+
"dependencies": {
50+
"@metamask/base-controller": "^7.0.1",
51+
"@metamask/utils": "^9.1.0"
52+
},
53+
"devDependencies": {
54+
"@metamask/auto-changelog": "^3.4.4",
55+
"@metamask/controller-utils": "^11.3.0",
56+
"@types/jest": "^27.4.1",
57+
"deepmerge": "^4.2.2",
58+
"jest": "^27.5.1",
59+
"nock": "^13.3.1",
60+
"ts-jest": "^27.1.4",
61+
"typedoc": "^0.24.8",
62+
"typedoc-plugin-missing-exports": "^2.0.0",
63+
"typescript": "~5.2.2"
64+
},
65+
"engines": {
66+
"node": "^18.18 || >=20"
67+
}
68+
}
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import { ControllerMessenger } from '@metamask/base-controller';
2+
import { GasPricesController } from '@metamask/example-controllers';
3+
import type { GasPricesControllerMessenger } from '@metamask/example-controllers';
4+
5+
import type {
6+
ExtractAvailableAction,
7+
ExtractAvailableEvent,
8+
} from '../../../packages/base-controller/tests/helpers';
9+
import type { AbstractGasPricesService } from './gas-prices-service/abstract-gas-prices-service';
10+
import {
11+
getDefaultNetworkControllerState,
12+
type NetworkControllerGetStateAction,
13+
} from './network-controller-types';
14+
15+
describe('GasPricesController', () => {
16+
describe('constructor', () => {
17+
it('uses all of the given state properties to initialize state', () => {
18+
const gasPricesService = buildGasPricesService();
19+
const givenState = {
20+
gasPricesByChainId: {
21+
'0x1': {
22+
low: 10,
23+
average: 15,
24+
high: 20,
25+
fetchedDate: '2024-01-01',
26+
},
27+
},
28+
};
29+
const controller = new GasPricesController({
30+
messenger: getControllerMessenger(),
31+
state: givenState,
32+
gasPricesService,
33+
});
34+
35+
expect(controller.state).toStrictEqual(givenState);
36+
});
37+
38+
it('fills in missing state properties with default values', () => {
39+
const gasPricesService = buildGasPricesService();
40+
const controller = new GasPricesController({
41+
messenger: getControllerMessenger(),
42+
gasPricesService,
43+
});
44+
45+
expect(controller.state).toMatchInlineSnapshot(`
46+
Object {
47+
"gasPricesByChainId": Object {},
48+
}
49+
`);
50+
});
51+
});
52+
53+
describe('updateGasPrices', () => {
54+
beforeEach(() => {
55+
jest.useFakeTimers().setSystemTime(new Date('2024-01-02'));
56+
});
57+
58+
afterEach(() => {
59+
jest.useRealTimers();
60+
});
61+
62+
it('fetches gas prices for the current chain through the service object and updates state accordingly', async () => {
63+
const gasPricesService = buildGasPricesService();
64+
jest.spyOn(gasPricesService, 'fetchGasPrices').mockResolvedValue({
65+
low: 5,
66+
average: 10,
67+
high: 15,
68+
});
69+
const rootMessenger = getRootControllerMessenger({
70+
networkControllerGetStateActionHandler: () => ({
71+
...getDefaultNetworkControllerState(),
72+
chainId: '0x42',
73+
}),
74+
});
75+
const controller = new GasPricesController({
76+
messenger: getControllerMessenger(rootMessenger),
77+
gasPricesService,
78+
});
79+
80+
await controller.updateGasPrices();
81+
82+
expect(controller.state).toStrictEqual({
83+
gasPricesByChainId: {
84+
'0x42': {
85+
low: 5,
86+
average: 10,
87+
high: 15,
88+
fetchedDate: '2024-01-02T00:00:00.000Z',
89+
},
90+
},
91+
});
92+
});
93+
});
94+
});
95+
96+
/**
97+
* The union of actions that the root messenger allows.
98+
*/
99+
type RootAction = ExtractAvailableAction<GasPricesControllerMessenger>;
100+
101+
/**
102+
* The union of events that the root messenger allows.
103+
*/
104+
type RootEvent = ExtractAvailableEvent<GasPricesControllerMessenger>;
105+
106+
/**
107+
* Constructs the unrestricted messenger. This can be used to call actions and
108+
* publish events within the tests for this controller.
109+
*
110+
* @param args - The arguments to this function.
111+
* @param args.networkControllerGetStateActionHandler - Used to mock the
112+
* `NetworkController:getState` action on the messenger.
113+
* @returns The unrestricted messenger suited for GasPricesController.
114+
*/
115+
function getRootControllerMessenger({
116+
networkControllerGetStateActionHandler = jest
117+
.fn<
118+
ReturnType<NetworkControllerGetStateAction['handler']>,
119+
Parameters<NetworkControllerGetStateAction['handler']>
120+
>()
121+
.mockReturnValue(getDefaultNetworkControllerState()),
122+
}: {
123+
networkControllerGetStateActionHandler?: NetworkControllerGetStateAction['handler'];
124+
} = {}): ControllerMessenger<RootAction, RootEvent> {
125+
const rootMessenger = new ControllerMessenger<RootAction, RootEvent>();
126+
rootMessenger.registerActionHandler(
127+
'NetworkController:getState',
128+
networkControllerGetStateActionHandler,
129+
);
130+
return rootMessenger;
131+
}
132+
133+
/**
134+
* Constructs the messenger which is restricted to relevant GasPricesController
135+
* actions and events.
136+
*
137+
* @param rootMessenger - The root messenger to restrict.
138+
* @returns The restricted messenger.
139+
*/
140+
function getControllerMessenger(
141+
rootMessenger = getRootControllerMessenger(),
142+
): GasPricesControllerMessenger {
143+
return rootMessenger.getRestricted({
144+
name: 'GasPricesController',
145+
allowedActions: ['NetworkController:getState'],
146+
allowedEvents: [],
147+
});
148+
}
149+
150+
/**
151+
* Constructs a mock GasPricesService object for use in testing.
152+
*
153+
* @returns The mock GasPricesService object.
154+
*/
155+
function buildGasPricesService(): AbstractGasPricesService {
156+
return {
157+
fetchGasPrices: jest.fn(),
158+
};
159+
}

0 commit comments

Comments
 (0)