Skip to content

Commit

Permalink
Add example controllers
Browse files Browse the repository at this point in the history
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
mcmire committed Jul 24, 2024
1 parent 8ad3072 commit 7a3475f
Show file tree
Hide file tree
Showing 22 changed files with 1,139 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ package-lock.json
# Build preview message
preview-build-message.txt

examples/*/coverage
examples/*/dist
examples/*/docs
packages/*/coverage
packages/*/dist
packages/*/docs
Expand Down
10 changes: 10 additions & 0 deletions examples/example-controllers/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 examples/example-controllers/LICENSE
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
15 changes: 15 additions & 0 deletions examples/example-controllers/README.md
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).
26 changes: 26 additions & 0 deletions examples/example-controllers/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,
},
},
});
40 changes: 40 additions & 0 deletions examples/example-controllers/package.json
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 examples/example-controllers/src/gas-prices-controller.test.ts
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(),
};
}
Loading

0 comments on commit 7a3475f

Please sign in to comment.