-
-
Notifications
You must be signed in to change notification settings - Fork 187
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Showing
22 changed files
with
1,139 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# `@metamask/example-controllers` | ||
|
||
This package is designed to illustrate best practices for controller packages and controller files, including tests. | ||
|
||
## Installation | ||
|
||
`yarn add @metamask/example-controllers` | ||
|
||
or | ||
|
||
`npm install @metamask/example-controllers` | ||
|
||
## Contributing | ||
|
||
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}, | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
{ | ||
"name": "@metamask/example-controllers", | ||
"version": "0.0.0", | ||
"private": true, | ||
"description": "Fetches gas prices periodically", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/MetaMask/core.git" | ||
}, | ||
"files": [ | ||
"dist/" | ||
], | ||
"scripts": { | ||
"build": "tsup --config ../../tsup.config.ts --tsconfig ./tsconfig.build.json --clean", | ||
"build:docs": "typedoc", | ||
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/example-controllers", | ||
"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": "^6.0.2", | ||
"@metamask/utils": "^9.1.0" | ||
}, | ||
"devDependencies": { | ||
"@metamask/auto-changelog": "^3.4.4", | ||
"@types/jest": "^27.4.1", | ||
"deepmerge": "^4.2.2", | ||
"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.0.4" | ||
}, | ||
"engines": { | ||
"node": "^18.18 || >=20" | ||
} | ||
} |
159 changes: 159 additions & 0 deletions
159
examples/example-controllers/src/gas-prices-controller.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
import { ControllerMessenger } from '@metamask/base-controller'; | ||
|
||
import type { | ||
ExtractAvailableAction, | ||
ExtractAvailableEvent, | ||
} from '../tests/helpers'; | ||
import type { GasPricesControllerMessenger } from './gas-prices-controller'; | ||
import { GasPricesController } from './gas-prices-controller'; | ||
import type { AbstractGasPricesService } from './gas-prices-service/abstract-gas-prices-service'; | ||
import { | ||
getDefaultNetworkControllerState, | ||
type NetworkControllerGetStateAction, | ||
} from './network-controller-types'; | ||
|
||
describe('GasPricesController', () => { | ||
describe('constructor', () => { | ||
it('uses all of the given state properties to initialize state', () => { | ||
const gasPricesService = buildGasPricesService(); | ||
const givenState = { | ||
gasPricesByChainId: { | ||
'0x1': { | ||
low: 10, | ||
average: 15, | ||
high: 20, | ||
fetchedDate: '2024-01-01', | ||
}, | ||
}, | ||
}; | ||
const controller = new GasPricesController({ | ||
messenger: getControllerMessenger(), | ||
state: givenState, | ||
gasPricesService, | ||
}); | ||
|
||
expect(controller.state).toStrictEqual(givenState); | ||
}); | ||
|
||
it('fills in missing state properties with default values', () => { | ||
const gasPricesService = buildGasPricesService(); | ||
const controller = new GasPricesController({ | ||
messenger: getControllerMessenger(), | ||
gasPricesService, | ||
}); | ||
|
||
expect(controller.state).toMatchInlineSnapshot(` | ||
Object { | ||
"gasPricesByChainId": Object {}, | ||
} | ||
`); | ||
}); | ||
}); | ||
|
||
describe('updateGasPrices', () => { | ||
beforeEach(() => { | ||
jest.useFakeTimers().setSystemTime(new Date('2024-01-02')); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.useRealTimers(); | ||
}); | ||
|
||
it('fetches gas prices for the current chain through the service object and updates state accordingly', async () => { | ||
const gasPricesService = buildGasPricesService(); | ||
jest.spyOn(gasPricesService, 'fetchGasPrices').mockResolvedValue({ | ||
low: 5, | ||
average: 10, | ||
high: 15, | ||
}); | ||
const rootMessenger = getRootControllerMessenger({ | ||
networkControllerGetStateActionHandler: () => ({ | ||
...getDefaultNetworkControllerState(), | ||
chainId: '0x42', | ||
}), | ||
}); | ||
const controller = new GasPricesController({ | ||
messenger: getControllerMessenger(rootMessenger), | ||
gasPricesService, | ||
}); | ||
|
||
await controller.updateGasPrices(); | ||
|
||
expect(controller.state).toStrictEqual({ | ||
gasPricesByChainId: { | ||
'0x42': { | ||
low: 5, | ||
average: 10, | ||
high: 15, | ||
fetchedDate: '2024-01-02T00:00:00.000Z', | ||
}, | ||
}, | ||
}); | ||
}); | ||
}); | ||
}); | ||
|
||
/** | ||
* The union of actions that the root messenger allows. | ||
*/ | ||
type RootAction = ExtractAvailableAction<GasPricesControllerMessenger>; | ||
|
||
/** | ||
* The union of events that the root messenger allows. | ||
*/ | ||
type RootEvent = ExtractAvailableEvent<GasPricesControllerMessenger>; | ||
|
||
/** | ||
* Constructs the unrestricted messenger. This can be used to call actions and | ||
* publish events within the tests for this controller. | ||
* | ||
* @param args - The arguments to this function. | ||
* @param args.networkControllerGetStateActionHandler - Used to mock the | ||
* `NetworkController:getState` action on the messenger. | ||
* @returns The unrestricted messenger suited for GasPricesController. | ||
*/ | ||
function getRootControllerMessenger({ | ||
networkControllerGetStateActionHandler = jest | ||
.fn< | ||
ReturnType<NetworkControllerGetStateAction['handler']>, | ||
Parameters<NetworkControllerGetStateAction['handler']> | ||
>() | ||
.mockReturnValue(getDefaultNetworkControllerState()), | ||
}: { | ||
networkControllerGetStateActionHandler?: NetworkControllerGetStateAction['handler']; | ||
} = {}): ControllerMessenger<RootAction, RootEvent> { | ||
const rootMessenger = new ControllerMessenger<RootAction, RootEvent>(); | ||
rootMessenger.registerActionHandler( | ||
'NetworkController:getState', | ||
networkControllerGetStateActionHandler, | ||
); | ||
return rootMessenger; | ||
} | ||
|
||
/** | ||
* Constructs the messenger which is restricted to relevant GasPricesController | ||
* actions and events. | ||
* | ||
* @param rootMessenger - The root messenger to restrict. | ||
* @returns The restricted messenger. | ||
*/ | ||
function getControllerMessenger( | ||
rootMessenger = getRootControllerMessenger(), | ||
): GasPricesControllerMessenger { | ||
return rootMessenger.getRestricted({ | ||
name: 'GasPricesController', | ||
allowedActions: ['NetworkController:getState'], | ||
allowedEvents: [], | ||
}); | ||
} | ||
|
||
/** | ||
* Constructs a mock GasPricesService object for use in testing. | ||
* | ||
* @returns The mock GasPricesService object. | ||
*/ | ||
function buildGasPricesService(): AbstractGasPricesService { | ||
return { | ||
fetchGasPrices: jest.fn(), | ||
}; | ||
} |
Oops, something went wrong.