From 7a3475f1b32835a9b89d496fca0959019d0f3a2f Mon Sep 17 00:00:00 2001 From: Elliot Winkler Date: Tue, 23 Jul 2024 21:26:14 -0600 Subject: [PATCH] Add example controllers 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. --- .gitignore | 3 + examples/example-controllers/CHANGELOG.md | 10 + examples/example-controllers/LICENSE | 20 ++ examples/example-controllers/README.md | 15 ++ examples/example-controllers/jest.config.js | 26 ++ examples/example-controllers/package.json | 40 +++ .../src/gas-prices-controller.test.ts | 159 +++++++++++ .../src/gas-prices-controller.ts | 251 ++++++++++++++++++ .../abstract-gas-prices-service.ts | 8 + .../gas-prices-service.test.ts | 28 ++ .../gas-prices-service/gas-prices-service.ts | 71 +++++ examples/example-controllers/src/index.ts | 25 ++ .../src/network-controller-types.ts | 40 +++ .../src/pet-names-controller.test.ts | 169 ++++++++++++ .../src/pet-names-controller.ts | 197 ++++++++++++++ examples/example-controllers/tests/helpers.ts | 30 +++ .../example-controllers/tsconfig.build.json | 12 + examples/example-controllers/tsconfig.json | 8 + examples/example-controllers/typedoc.json | 7 + package.json | 1 + tsconfig.json | 1 + yarn.lock | 18 ++ 22 files changed, 1139 insertions(+) create mode 100644 examples/example-controllers/CHANGELOG.md create mode 100644 examples/example-controllers/LICENSE create mode 100644 examples/example-controllers/README.md create mode 100644 examples/example-controllers/jest.config.js create mode 100644 examples/example-controllers/package.json create mode 100644 examples/example-controllers/src/gas-prices-controller.test.ts create mode 100644 examples/example-controllers/src/gas-prices-controller.ts create mode 100644 examples/example-controllers/src/gas-prices-service/abstract-gas-prices-service.ts create mode 100644 examples/example-controllers/src/gas-prices-service/gas-prices-service.test.ts create mode 100644 examples/example-controllers/src/gas-prices-service/gas-prices-service.ts create mode 100644 examples/example-controllers/src/index.ts create mode 100644 examples/example-controllers/src/network-controller-types.ts create mode 100644 examples/example-controllers/src/pet-names-controller.test.ts create mode 100644 examples/example-controllers/src/pet-names-controller.ts create mode 100644 examples/example-controllers/tests/helpers.ts create mode 100644 examples/example-controllers/tsconfig.build.json create mode 100644 examples/example-controllers/tsconfig.json create mode 100644 examples/example-controllers/typedoc.json diff --git a/.gitignore b/.gitignore index 76678f8794..5043addaa4 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/examples/example-controllers/CHANGELOG.md b/examples/example-controllers/CHANGELOG.md new file mode 100644 index 0000000000..b518709c7b --- /dev/null +++ b/examples/example-controllers/CHANGELOG.md @@ -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/ diff --git a/examples/example-controllers/LICENSE b/examples/example-controllers/LICENSE new file mode 100644 index 0000000000..6f8bff03fc --- /dev/null +++ b/examples/example-controllers/LICENSE @@ -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 diff --git a/examples/example-controllers/README.md b/examples/example-controllers/README.md new file mode 100644 index 0000000000..7d90e0d0c7 --- /dev/null +++ b/examples/example-controllers/README.md @@ -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). diff --git a/examples/example-controllers/jest.config.js b/examples/example-controllers/jest.config.js new file mode 100644 index 0000000000..ca08413339 --- /dev/null +++ b/examples/example-controllers/jest.config.js @@ -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, + }, + }, +}); diff --git a/examples/example-controllers/package.json b/examples/example-controllers/package.json new file mode 100644 index 0000000000..5df4e3adf0 --- /dev/null +++ b/examples/example-controllers/package.json @@ -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" + } +} diff --git a/examples/example-controllers/src/gas-prices-controller.test.ts b/examples/example-controllers/src/gas-prices-controller.test.ts new file mode 100644 index 0000000000..b96b0f0ed0 --- /dev/null +++ b/examples/example-controllers/src/gas-prices-controller.test.ts @@ -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; + +/** + * The union of events that the root messenger allows. + */ +type RootEvent = ExtractAvailableEvent; + +/** + * 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, + Parameters + >() + .mockReturnValue(getDefaultNetworkControllerState()), +}: { + networkControllerGetStateActionHandler?: NetworkControllerGetStateAction['handler']; +} = {}): ControllerMessenger { + const rootMessenger = new ControllerMessenger(); + 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(), + }; +} diff --git a/examples/example-controllers/src/gas-prices-controller.ts b/examples/example-controllers/src/gas-prices-controller.ts new file mode 100644 index 0000000000..77a92a0345 --- /dev/null +++ b/examples/example-controllers/src/gas-prices-controller.ts @@ -0,0 +1,251 @@ +import type { + ControllerGetStateAction, + ControllerStateChangeEvent, + RestrictedControllerMessenger, + StateMetadata, +} from '@metamask/base-controller'; +import { BaseController } from '@metamask/base-controller'; +import type { Hex } from '@metamask/utils'; + +import type { AbstractGasPricesService } from './gas-prices-service/abstract-gas-prices-service'; +import type { NetworkControllerGetStateAction } from './network-controller-types'; + +// === GENERAL === + +/** + * The name of the {@link GasPricesController}, used to namespace the + * controller's actions and events and to namespace the controller's state data + * when composed with other controllers. + */ +export const controllerName = 'GasPricesController'; + +// === STATE === + +/** + * The collection of gas price data fetched periodically. + */ +type GasPrices = { + /** + * The total estimated gas in the "low" bucket. + */ + low: number; + /** + * The total estimated gas in the "average" bucket. + */ + average: number; + /** + * The total estimated gas in the "high" bucket. + */ + high: number; + /** + * The date/time (in ISO-8601 format) when prices were fetched. + */ + fetchedDate: string; +}; + +/** + * Describes the shape of the state object for {@link GasPricesController}. + */ +export type GasPricesControllerState = { + /** + * The registry of pet names, categorized by chain ID first and address + * second. + */ + gasPricesByChainId: { + [chainId: Hex]: GasPrices; + }; +}; + +/** + * The metadata for each property in {@link GasPricesControllerState}. + */ +const gasPricesControllerMetadata = { + gasPricesByChainId: { + persist: true, + anonymous: false, + }, +} satisfies StateMetadata; + +// === MESSENGER === + +/** + * The action which can be used to retrieve the state of the + * {@link GasPricesController}. + */ +export type GasPricesControllerGetStateAction = ControllerGetStateAction< + typeof controllerName, + GasPricesControllerState +>; + +/** + * The action which can be used to update gas prices. + */ +export type GasPricesControllerUpdateGasPricesAction = { + type: `${typeof controllerName}:updateGasPrices`; + handler: GasPricesController['updateGasPrices']; +}; + +/** + * All actions that {@link GasPricesController} registers, to be called + * externally. + */ +export type GasPricesControllerActions = + | GasPricesControllerGetStateAction + | GasPricesControllerUpdateGasPricesAction; + +/** + * All actions that {@link GasPricesController} calls internally. + */ +export type AllowedActions = NetworkControllerGetStateAction; + +/** + * The event that {@link GasPricesController} publishes when updating state. + */ +export type GasPricesControllerStateChangeEvent = ControllerStateChangeEvent< + typeof controllerName, + GasPricesControllerState +>; + +/** + * All events that {@link GasPricesController} publishes, to be subscribed to + * externally. + */ +export type GasPricesControllerEvents = GasPricesControllerStateChangeEvent; + +/** + * All events that {@link GasPricesController} subscribes to internally. + */ +export type AllowedEvents = never; + +/** + * The messenger which is restricted to actions and events accessed by + * {@link GasPricesController}. + */ +export type GasPricesControllerMessenger = RestrictedControllerMessenger< + typeof controllerName, + GasPricesControllerActions | AllowedActions, + GasPricesControllerEvents | AllowedEvents, + AllowedActions['type'], + AllowedEvents['type'] +>; + +/** + * Constructs the default {@link GasPricesController} state. This allows + * consumers to provide a partial state object when initializing the controller + * and also helps in constructing complete state objects for this controller in + * tests. + * + * @returns The default {@link GasPricesController} state. + */ +export function getDefaultGasPricesControllerState(): GasPricesControllerState { + return { + gasPricesByChainId: {}, + }; +} + +// === CONTROLLER DEFINITION === + +/** + * `GasPricesController` fetches and persists gas prices for various chains. + * + * @example + * + * ``` ts + * import { ControllerMessenger } from '@metamask/base-controller'; + * import { + * GasPricesController, + * GasPricesService + * } from '@metamask/example-controllers'; + * import type { + * GasPricesControllerActions, + * GasPricesControllerEvents + * } from '@metamask/example-controllers'; + * import type { NetworkControllerGetStateAction } from '@metamask/network-controller'; + * + * // Assuming that you're using this in the browser + * const gasPricesService = new GasPricesService({ fetch }); + * const rootMessenger = new ControllerMessenger< + * GasPricesControllerActions | NetworkControllerGetStateAction, + * GasPricesControllerEvents + * >(); + * const gasPricesMessenger = rootMessenger.getRestricted({ + * name: 'GasPricesController', + * allowedActions: ['NetworkController:getState'], + * allowedEvents: [], + * }); + * const gasPricesController = new GasPricesController({ + * messenger: gasPricesMessenger, + * gasPricesService, + * }); + * + * // Assuming that `NetworkController:getState` returns an object with a + * // `chainId` of `0x42`... + * await gasPricesController.updateGasPrices(); + * gasPricesController.state.gasPricesByChainId + * // => { '0x42': { low: 5, average: 10, high: 15, fetchedDate: '2024-01-02T00:00:00.000Z' } } + * ``` + */ +export class GasPricesController extends BaseController< + typeof controllerName, + GasPricesControllerState, + GasPricesControllerMessenger +> { + /** + * The service object that is used to obtain gas prices. + */ + #gasPricesService: AbstractGasPricesService; + + /** + * Constructs a new {@link GasPricesController}. + * + * @param args - The arguments to the controller. + * @param args.messenger - The messenger suited for this controller. + * @param args.state - The desired state with which to initialize this + * controller. Missing properties will be filled in with defaults. + * @param args.gasPricesService - The service object that will be used to + * obtain gas prices. + */ + constructor({ + messenger, + state, + gasPricesService, + }: { + messenger: GasPricesControllerMessenger; + state?: Partial; + gasPricesService: AbstractGasPricesService; + }) { + super({ + messenger, + metadata: gasPricesControllerMetadata, + name: controllerName, + state: { + ...getDefaultGasPricesControllerState(), + ...state, + }, + }); + + this.#gasPricesService = gasPricesService; + + this.messagingSystem.registerActionHandler( + `${controllerName}:updateGasPrices`, + this.updateGasPrices.bind(this), + ); + } + + /** + * Fetches the latest gas prices for the current chain, persisting them to + * state. + */ + async updateGasPrices() { + const { chainId } = this.messagingSystem.call('NetworkController:getState'); + const gasPricesResponse = await this.#gasPricesService.fetchGasPrices( + chainId, + ); + this.update((state) => { + state.gasPricesByChainId[chainId] = { + ...gasPricesResponse, + fetchedDate: new Date().toISOString(), + }; + }); + } +} diff --git a/examples/example-controllers/src/gas-prices-service/abstract-gas-prices-service.ts b/examples/example-controllers/src/gas-prices-service/abstract-gas-prices-service.ts new file mode 100644 index 0000000000..aa7ec94a99 --- /dev/null +++ b/examples/example-controllers/src/gas-prices-service/abstract-gas-prices-service.ts @@ -0,0 +1,8 @@ +import type { PublicInterface } from '@metamask/utils'; + +import type { GasPricesService } from './gas-prices-service'; + +/** + * A service object which is responsible for fetching gas prices. + */ +export type AbstractGasPricesService = PublicInterface; diff --git a/examples/example-controllers/src/gas-prices-service/gas-prices-service.test.ts b/examples/example-controllers/src/gas-prices-service/gas-prices-service.test.ts new file mode 100644 index 0000000000..cff9ec14c7 --- /dev/null +++ b/examples/example-controllers/src/gas-prices-service/gas-prices-service.test.ts @@ -0,0 +1,28 @@ +import nock from 'nock'; + +import { GasPricesService } from './gas-prices-service'; + +describe('GasPricesService', () => { + describe('fetchGasPrices', () => { + it('returns a slightly cleaned up version of what the API returns', async () => { + nock('https://example.com/gas-prices') + .get('/0x1.json') + .reply(200, { + data: { + low: 5, + average: 10, + high: 15, + }, + }); + const gasPricesService = new GasPricesService({ fetch }); + + const gasPricesResponse = await gasPricesService.fetchGasPrices('0x1'); + + expect(gasPricesResponse).toStrictEqual({ + low: 5, + average: 10, + high: 15, + }); + }); + }); +}); diff --git a/examples/example-controllers/src/gas-prices-service/gas-prices-service.ts b/examples/example-controllers/src/gas-prices-service/gas-prices-service.ts new file mode 100644 index 0000000000..c3d063e428 --- /dev/null +++ b/examples/example-controllers/src/gas-prices-service/gas-prices-service.ts @@ -0,0 +1,71 @@ +import type { Hex } from '@metamask/utils'; + +/** + * What the API endpoint returns. + */ +type GasPricesResponse = { + data: { + low: number; + average: number; + high: number; + }; +}; + +/** + * This service object is responsible for fetching gas prices via an API. + * + * @example + * + * On its own: + * + * ``` ts + * const gasPricesService = new GasPricesService({ fetch }); + * // Fetch gas prices for Mainnet + * const gasPricesResponse = await gasPricesService.fetchGasPrices('0x1'); + * // ... Do something with the response ... + * ``` + * + * In conjunction with `GasPricesController`: + * + * ``` ts + * const gasPricesService = new GasPricesService({ fetch }); + * const gasPricesController = new GasPricesController({ + * // ... state, messenger, etc. ... + * gasPricesService, + * }); + * // This will use the service object internally + * gasPricesController.updateGasPrices(); + * ``` + */ +export class GasPricesService { + #fetch: typeof fetch; + + /** + * Constructs a new GasPricesService object. + * + * @param args - The arguments. + * @param args.fetch - A function that can be used to make an HTTP request. + * If your JavaScript environment supports `fetch` natively, you'll probably + * want to pass that; otherwise you can pass an equivalent (such as `fetch` + * via `node-fetch`). + */ + constructor({ fetch: fetchFunction }: { fetch: typeof fetch }) { + this.#fetch = fetchFunction; + } + + /** + * Makes a request to the API in order to retrieve gas prices for a particular + * chain. + * + * @param chainId - The chain ID for which you want to fetch gas prices. + */ + async fetchGasPrices(chainId: Hex) { + const response = await this.#fetch( + `https://example.com/gas-prices/${chainId}.json`, + ); + // Type assertion: We have to assume the shape of the response data. + const gasPricesResponse = + (await response.json()) as unknown as GasPricesResponse; + return gasPricesResponse.data; + } +} diff --git a/examples/example-controllers/src/index.ts b/examples/example-controllers/src/index.ts new file mode 100644 index 0000000000..afeebcd070 --- /dev/null +++ b/examples/example-controllers/src/index.ts @@ -0,0 +1,25 @@ +export type { + GasPricesControllerActions, + GasPricesControllerEvents, + GasPricesControllerGetStateAction, + GasPricesControllerMessenger, + GasPricesControllerState, + GasPricesControllerStateChangeEvent, +} from './gas-prices-controller'; +export { + getDefaultGasPricesControllerState, + GasPricesController, +} from './gas-prices-controller'; +export type { + PetNamesControllerActions, + PetNamesControllerEvents, + PetNamesControllerGetStateAction, + PetNamesControllerMessenger, + PetNamesControllerState, + PetNamesControllerStateChangeEvent, +} from './pet-names-controller'; +export { + getDefaultPetNamesControllerState, + PetNamesController, +} from './pet-names-controller'; +export { GasPricesService } from './gas-prices-service/gas-prices-service'; diff --git a/examples/example-controllers/src/network-controller-types.ts b/examples/example-controllers/src/network-controller-types.ts new file mode 100644 index 0000000000..ef04e41589 --- /dev/null +++ b/examples/example-controllers/src/network-controller-types.ts @@ -0,0 +1,40 @@ +import type { Hex } from '@metamask/utils'; + +/** + * Describes the shape of the state object for a theoretical NetworkController. + * + * Note that this package does not supply a NetworkController; this type is only + * here so it is possible to write a complete example. + */ +type NetworkControllerState = { + networkName: string; + chainId: Hex; +}; + +/** + * Constructs a default representation of a theoretical NetworkController's + * state. + * + * Note that this package does not supply a NetworkController; this type is only + * here so it is possible to write a complete example. + * + * @returns The default network controller state. + */ +export function getDefaultNetworkControllerState(): NetworkControllerState { + return { + networkName: 'Some Network', + chainId: '0x1', + }; +} + +/** + * The action which can be used to obtain the state for a theoretical + * NetworkController. + * + * Note that this package does not supply a NetworkController; this type is only + * here so it is possible to write a complete example. + */ +export type NetworkControllerGetStateAction = { + type: 'NetworkController:getState'; + handler: () => NetworkControllerState; +}; diff --git a/examples/example-controllers/src/pet-names-controller.test.ts b/examples/example-controllers/src/pet-names-controller.test.ts new file mode 100644 index 0000000000..ee409a3d9e --- /dev/null +++ b/examples/example-controllers/src/pet-names-controller.test.ts @@ -0,0 +1,169 @@ +import { ControllerMessenger } from '@metamask/base-controller'; + +import type { + ExtractAvailableAction, + ExtractAvailableEvent, +} from '../../../packages/base-controller/tests/helpers'; +import type { PetNamesControllerMessenger } from './pet-names-controller'; +import { PetNamesController } from './pet-names-controller'; + +describe('PetNamesController', () => { + describe('constructor', () => { + it('uses all of the given state properties to initialize state', () => { + const givenState = { + namesByChainIdAndAddress: { + '0x1': { + '0xabcdef1': 'Primary Account', + '0xabcdef2': 'Secondary Account', + }, + }, + }; + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + state: givenState, + }); + + expect(controller.state).toStrictEqual(givenState); + }); + + it('fills in missing state properties with default values', () => { + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + }); + + expect(controller.state).toMatchInlineSnapshot(` + Object { + "namesByChainIdAndAddress": Object {}, + } + `); + }); + }); + + describe('assignPetName', () => { + it('registers the given pet name in state with the given chain ID and address', () => { + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + state: { + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Account 1', + }, + }, + }, + }); + + controller.assignPetName('0x1', '0xbbbbbb', 'Account 2'); + + expect(controller.state).toStrictEqual({ + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Account 1', + '0xbbbbbb': 'Account 2', + }, + }, + }); + }); + + it("creates a new group for the chain if it doesn't already exist", () => { + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + }); + + controller.assignPetName('0x1', '0xaaaaaa', 'My Account'); + + expect(controller.state).toStrictEqual({ + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'My Account', + }, + }, + }); + }); + + it('overwrites any existing pet name for the address', () => { + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + state: { + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Account 1', + }, + }, + }, + }); + + controller.assignPetName('0x1', '0xaaaaaa', 'Old Account'); + + expect(controller.state).toStrictEqual({ + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Old Account', + }, + }, + }); + }); + + it('lowercases the given address before registering it to avoid duplicate entries', () => { + const controller = new PetNamesController({ + messenger: getControllerMessenger(), + state: { + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Account 1', + }, + }, + }, + }); + + controller.assignPetName('0x1', '0xAAAAAA', 'Old Account'); + + expect(controller.state).toStrictEqual({ + namesByChainIdAndAddress: { + '0x1': { + '0xaaaaaa': 'Old Account', + }, + }, + }); + }); + }); +}); + +/** + * The union of actions that the root messenger allows. + */ +type RootAction = ExtractAvailableAction; + +/** + * The union of events that the root messenger allows. + */ +type RootEvent = ExtractAvailableEvent; + +/** + * Constructs the unrestricted messenger. This can be used to call actions and + * publish events within the tests for this controller. + * + * @returns The unrestricted messenger suited for PetNamesController. + */ +function getRootControllerMessenger(): ControllerMessenger< + RootAction, + RootEvent +> { + return new ControllerMessenger(); +} + +/** + * Constructs the messenger which is restricted to relevant PetNamesController + * actions and events. + * + * @param rootMessenger - The root messenger to restrict. + * @returns The restricted messenger. + */ +function getControllerMessenger( + rootMessenger = getRootControllerMessenger(), +): PetNamesControllerMessenger { + return rootMessenger.getRestricted({ + name: 'PetNamesController', + allowedActions: [], + allowedEvents: [], + }); +} diff --git a/examples/example-controllers/src/pet-names-controller.ts b/examples/example-controllers/src/pet-names-controller.ts new file mode 100644 index 0000000000..95379e8d6e --- /dev/null +++ b/examples/example-controllers/src/pet-names-controller.ts @@ -0,0 +1,197 @@ +import type { + ControllerGetStateAction, + ControllerStateChangeEvent, + RestrictedControllerMessenger, + StateMetadata, +} from '@metamask/base-controller'; +import { BaseController } from '@metamask/base-controller'; +import type { Hex } from '@metamask/utils'; + +// === GENERAL === + +/** + * The name of the {@link PetNamesController}, used to namespace the + * controller's actions and events and to namespace the controller's state data + * when composed with other controllers. + */ +export const controllerName = 'PetNamesController'; + +// === STATE === + +/** + * Describes the shape of the state object for {@link PetNamesController}. + */ +export type PetNamesControllerState = { + /** + * The registry of pet names, categorized by chain ID first and address + * second. + */ + namesByChainIdAndAddress: { + [chainId: Hex]: { + [address: Hex]: string; + }; + }; +}; + +/** + * The metadata for each property in {@link PetNamesControllerState}. + */ +const petNamesControllerMetadata = { + namesByChainIdAndAddress: { + persist: true, + anonymous: false, + }, +} satisfies StateMetadata; + +// === MESSENGER === + +/** + * The action which can be used to retrieve the state of the + * {@link PetNamesController}. + */ +export type PetNamesControllerGetStateAction = ControllerGetStateAction< + typeof controllerName, + PetNamesControllerState +>; + +/** + * All actions that {@link PetNamesController} registers, to be called + * externally. + */ +export type PetNamesControllerActions = PetNamesControllerGetStateAction; + +/** + * All actions that {@link PetNamesController} calls internally. + */ +export type AllowedActions = never; + +/** + * The event that {@link PetNamesController} publishes when updating state. + */ +export type PetNamesControllerStateChangeEvent = ControllerStateChangeEvent< + typeof controllerName, + PetNamesControllerState +>; + +/** + * All events that {@link PetNamesController} publishes, to be subscribed to + * externally. + */ +export type PetNamesControllerEvents = PetNamesControllerStateChangeEvent; + +/** + * All events that {@link PetNamesController} subscribes to internally. + */ +export type AllowedEvents = never; + +/** + * The messenger which is restricted to actions and events accessed by + * {@link PetNamesController}. + */ +export type PetNamesControllerMessenger = RestrictedControllerMessenger< + typeof controllerName, + PetNamesControllerActions | AllowedActions, + PetNamesControllerEvents | AllowedEvents, + AllowedActions['type'], + AllowedEvents['type'] +>; + +/** + * Constructs the default {@link PetNamesController} state. This allows + * consumers to provide a partial state object when initializing the controller + * and also helps in constructing complete state objects for this controller in + * tests. + * + * @returns The default {@link PetNamesController} state. + */ +export function getDefaultPetNamesControllerState(): PetNamesControllerState { + return { + namesByChainIdAndAddress: {}, + }; +} + +// === CONTROLLER DEFINITION === + +/** + * `PetNamesController` records user-provided nicknames for various addresses on + * various chains. + * + * @example + * + * ``` ts + * import { ControllerMessenger } from '@metamask/base-controller'; + * import type { + * PetNamesControllerActions, + * PetNamesControllerEvents + * } from '@metamask/example-controllers'; + * + * const rootMessenger = new ControllerMessenger< + * PetNamesControllerActions, + * PetNamesControllerEvents + * >(); + * const petNamesMessenger = rootMessenger.getRestricted({ + * name: 'PetNamesController', + * allowedActions: [], + * allowedEvents: [], + * }); + * const petNamesController = new GasPricesController({ + * messenger: petNamesMessenger, + * }); + * + * petNamesController.assignPetName( + * '0x1', + * '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99', + * 'Primary Account' + * ); + * petNamesController.state.namesByChainIdAndAddress + * // => { '0x1': { '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99': 'Primary Account' } } + * ``` + */ +export class PetNamesController extends BaseController< + typeof controllerName, + PetNamesControllerState, + PetNamesControllerMessenger +> { + /** + * Constructs a new {@link PetNamesController}. + * + * @param args - The arguments to the controller. + * @param args.messenger - The messenger suited for this controller. + * @param args.state - The desired state with which to initialize this + * controller. Missing properties will be filled in with defaults. + */ + constructor({ + messenger, + state, + }: { + messenger: PetNamesControllerMessenger; + state?: Partial; + }) { + super({ + messenger, + metadata: petNamesControllerMetadata, + name: controllerName, + state: { + ...getDefaultPetNamesControllerState(), + ...state, + }, + }); + } + + /** + * Registers the given name with the given address (relative to the given + * chain). + * + * @param chainId - The chain ID that the address belongs to. + * @param address - The account address to name. + * @param name - The name to assign to the address. + */ + assignPetName(chainId: Hex, address: Hex, name: string) { + const normalizedAddress = address.toLowerCase() as Hex; + + this.update((state) => { + state.namesByChainIdAndAddress[chainId] ??= {}; + state.namesByChainIdAndAddress[chainId][normalizedAddress] = name; + }); + } +} diff --git a/examples/example-controllers/tests/helpers.ts b/examples/example-controllers/tests/helpers.ts new file mode 100644 index 0000000000..179e8a42b4 --- /dev/null +++ b/examples/example-controllers/tests/helpers.ts @@ -0,0 +1,30 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import type { RestrictedControllerMessenger } from '@metamask/base-controller'; + +// We don't care about the types marked with `any` for this type. +export type ExtractAvailableAction = + Messenger extends RestrictedControllerMessenger< + any, + infer Action, + any, + any, + any + > + ? Action + : never; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We don't care about the types marked with `any` for this type. +export type ExtractAvailableEvent = + Messenger extends RestrictedControllerMessenger< + any, + any, + infer Event, + any, + any + > + ? Event + : never; +/* eslint-enable @typescript-eslint/no-explicit-any */ diff --git a/examples/example-controllers/tsconfig.build.json b/examples/example-controllers/tsconfig.build.json new file mode 100644 index 0000000000..7211fee891 --- /dev/null +++ b/examples/example-controllers/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/types", + "rootDir": "./src" + }, + "references": [ + { "path": "../../packages/base-controller/tsconfig.build.json" } + ], + "include": ["../../types", "./src"] +} diff --git a/examples/example-controllers/tsconfig.json b/examples/example-controllers/tsconfig.json new file mode 100644 index 0000000000..25deae1707 --- /dev/null +++ b/examples/example-controllers/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [{ "path": "../../packages/base-controller" }], + "include": ["../../types", "./src", "./tests"] +} diff --git a/examples/example-controllers/typedoc.json b/examples/example-controllers/typedoc.json new file mode 100644 index 0000000000..c9da015dbf --- /dev/null +++ b/examples/example-controllers/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["./src/index.ts"], + "excludePrivate": true, + "hideGenerator": true, + "out": "docs", + "tsconfig": "./tsconfig.build.json" +} diff --git a/package.json b/package.json index 45216564f0..b2f560967c 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ }, "files": [], "workspaces": [ + "examples/*", "packages/*" ], "scripts": { diff --git a/tsconfig.json b/tsconfig.json index e5c3ab12a8..f886671a63 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "esModuleInterop": true, "noEmit": true }, "references": [ + { "path": "./examples/example-controllers" }, { "path": "./packages/accounts-controller" }, { "path": "./packages/address-book-controller" }, { "path": "./packages/announcement-controller" }, diff --git a/yarn.lock b/yarn.lock index e709307800..ad2ae74455 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2993,6 +2993,24 @@ __metadata: languageName: node linkType: hard +"@metamask/example-controllers@workspace:examples/example-controllers": + version: 0.0.0-use.local + resolution: "@metamask/example-controllers@workspace:examples/example-controllers" + dependencies: + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/base-controller": "npm:^6.0.2" + "@metamask/utils": "npm:^9.1.0" + "@types/jest": "npm:^27.4.1" + deepmerge: "npm:^4.2.2" + jest: "npm:^27.5.1" + nock: "npm:^13.3.1" + ts-jest: "npm:^27.1.4" + typedoc: "npm:^0.24.8" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.0.4" + languageName: unknown + linkType: soft + "@metamask/gas-fee-controller@npm:^19.0.0, @metamask/gas-fee-controller@workspace:packages/gas-fee-controller": version: 0.0.0-use.local resolution: "@metamask/gas-fee-controller@workspace:packages/gas-fee-controller"