Skip to content

Commit 5ddc6ba

Browse files
Create shield controller (#6137)
## Explanation New controller for MetaMask Shield. Functionality: - Watch for incoming transactions added to transaction controller. - On new transaction, trigger coverage check. - Store the coverage check result. - Update coverage check data whenever a transaction is re-simulated. <!-- 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? --> ## 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? Are there client or consumer pull requests to adopt any breaking changes? For example: * Fixes #12345 * Related to #67890 --> ## Changelog <!-- THIS SECTION IS NO LONGER NEEDED. The process for updating changelogs has changed. Please consult the "Updating changelogs" section of the Contributing doc for more. --> ## 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 - [ ] ~~I've communicated my changes to consumers by [updating changelogs for packages I've changed](https://github.com/MetaMask/core/tree/main/docs/contributing.md#updating-changelogs), highlighting breaking changes as necessary~~ - [ ] ~~I've prepared draft pull requests for clients and consumer packages to resolve any breaking changes~~ (The last two are not applicable as this is a new package.)
1 parent 7be2c73 commit 5ddc6ba

25 files changed

+1055
-0
lines changed

.github/CODEOWNERS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575

7676
## Web3Auth Team
7777
/packages/seedless-onboarding-controller @MetaMask/web3auth
78+
/packages/shield-controller @MetaMask/web3auth
7879

7980
## Joint team ownership
8081
/packages/eth-json-rpc-provider @MetaMask/wallet-api-platform-engineers @MetaMask/core-platform
@@ -158,5 +159,7 @@
158159
/packages/foundryup/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/core-platform
159160
/packages/seedless-onboarding-controller/package.json @MetaMask/web3auth @MetaMask/core-platform
160161
/packages/seedless-onboarding-controller/CHANGELOG.md @MetaMask/web3auth @MetaMask/core-platform
162+
/packages/shield-controller/package.json @MetaMask/web3auth @MetaMask/core-platform
163+
/packages/shield-controller/CHANGELOG.md @MetaMask/web3auth @MetaMask/core-platform
161164
/packages/network-enablement-controller/package.json @MetaMask/metamask-assets @MetaMask/core-platform
162165
/packages/network-enablement-controller/CHANGELOG.md @MetaMask/metamask-assets @MetaMask/core-platform

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Each package in this repository has its own README where you can find installati
6767
- [`@metamask/sample-controllers`](packages/sample-controllers)
6868
- [`@metamask/seedless-onboarding-controller`](packages/seedless-onboarding-controller)
6969
- [`@metamask/selected-network-controller`](packages/selected-network-controller)
70+
- [`@metamask/shield-controller`](packages/shield-controller)
7071
- [`@metamask/signature-controller`](packages/signature-controller)
7172
- [`@metamask/token-search-discovery-controller`](packages/token-search-discovery-controller)
7273
- [`@metamask/transaction-controller`](packages/transaction-controller)
@@ -127,6 +128,7 @@ linkStyle default opacity:0.5
127128
sample_controllers(["@metamask/sample-controllers"]);
128129
seedless_onboarding_controller(["@metamask/seedless-onboarding-controller"]);
129130
selected_network_controller(["@metamask/selected-network-controller"]);
131+
shield_controller(["@metamask/shield-controller"]);
130132
signature_controller(["@metamask/signature-controller"]);
131133
token_search_discovery_controller(["@metamask/token-search-discovery-controller"]);
132134
transaction_controller(["@metamask/transaction-controller"]);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
### Added
11+
12+
- Initial release of the shield-controller package ([#6137](https://github.com/MetaMask/core/pull/6137))
13+
14+
[Unreleased]: https://github.com/MetaMask/core/

packages/shield-controller/LICENSE

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) 2025 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/shield-controller`
2+
3+
Controller handling shield transaction coverage logic.
4+
5+
## Installation
6+
7+
`yarn add @metamask/shield-controller`
8+
9+
or
10+
11+
`npm install @metamask/shield-controller`
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: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
{
2+
"name": "@metamask/shield-controller",
3+
"version": "0.0.0",
4+
"description": "Controller handling shield transaction coverage logic",
5+
"keywords": [
6+
"MetaMask",
7+
"Ethereum"
8+
],
9+
"homepage": "https://github.com/MetaMask/core/tree/main/packages/shield-controller#readme",
10+
"bugs": {
11+
"url": "https://github.com/MetaMask/core/issues"
12+
},
13+
"repository": {
14+
"type": "git",
15+
"url": "https://github.com/MetaMask/core.git"
16+
},
17+
"license": "MIT",
18+
"sideEffects": false,
19+
"exports": {
20+
".": {
21+
"import": {
22+
"types": "./dist/index.d.mts",
23+
"default": "./dist/index.mjs"
24+
},
25+
"require": {
26+
"types": "./dist/index.d.cts",
27+
"default": "./dist/index.cjs"
28+
}
29+
},
30+
"./package.json": "./package.json"
31+
},
32+
"main": "./dist/index.cjs",
33+
"types": "./dist/index.d.cts",
34+
"files": [
35+
"dist/"
36+
],
37+
"scripts": {
38+
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
39+
"build:docs": "typedoc",
40+
"changelog:update": "../../scripts/update-changelog.sh @metamask/shield-controller",
41+
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/shield-controller",
42+
"publish:preview": "yarn npm publish --tag preview",
43+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
44+
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
45+
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
46+
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
47+
"since-latest-release": "../../scripts/since-latest-release.sh"
48+
},
49+
"dependencies": {
50+
"@metamask/base-controller": "^8.1.0",
51+
"@metamask/utils": "^11.4.2"
52+
},
53+
"devDependencies": {
54+
"@babel/runtime": "^7.23.9",
55+
"@lavamoat/allow-scripts": "^3.0.4",
56+
"@lavamoat/preinstall-always-fail": "^2.1.0",
57+
"@metamask/auto-changelog": "^3.4.4",
58+
"@metamask/transaction-controller": "^59.2.0",
59+
"@ts-bridge/cli": "^0.6.1",
60+
"@types/jest": "^27.4.1",
61+
"deepmerge": "^4.2.2",
62+
"jest": "^27.5.1",
63+
"ts-jest": "^27.1.4",
64+
"typedoc": "^0.24.8",
65+
"typedoc-plugin-missing-exports": "^2.0.0",
66+
"typescript": "~5.2.2",
67+
"uuid": "^8.3.2"
68+
},
69+
"peerDependencies": {
70+
"@metamask/transaction-controller": "^59.2.0"
71+
},
72+
"engines": {
73+
"node": "^18.18 || >=20"
74+
},
75+
"publishConfig": {
76+
"access": "public",
77+
"registry": "https://registry.npmjs.org/"
78+
},
79+
"lavamoat": {
80+
"allowScripts": {
81+
"@lavamoat/allow-scripts>@lavamoat/preinstall-always-fail": false
82+
}
83+
}
84+
}
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import type { TransactionControllerState } from '@metamask/transaction-controller';
2+
3+
import { ShieldController } from './ShieldController';
4+
import { createMockBackend } from '../tests/mocks/backend';
5+
import { createMockMessenger } from '../tests/mocks/messenger';
6+
import { generateMockTxMeta } from '../tests/utils';
7+
8+
/**
9+
* Sets up a ShieldController for testing.
10+
*
11+
* @param options - The options for setup.
12+
* @param options.coverageHistoryLimit - The coverage history limit.
13+
* @param options.transactionHistoryLimit - The transaction history limit.
14+
* @returns Objects that have been created for testing.
15+
*/
16+
function setup({
17+
coverageHistoryLimit,
18+
transactionHistoryLimit,
19+
}: {
20+
coverageHistoryLimit?: number;
21+
transactionHistoryLimit?: number;
22+
} = {}) {
23+
const backend = createMockBackend();
24+
const { messenger, baseMessenger } = createMockMessenger();
25+
26+
const controller = new ShieldController({
27+
backend,
28+
coverageHistoryLimit,
29+
transactionHistoryLimit,
30+
messenger,
31+
});
32+
controller.start();
33+
return {
34+
controller,
35+
messenger,
36+
baseMessenger,
37+
backend,
38+
};
39+
}
40+
41+
describe('ShieldController', () => {
42+
describe('checkCoverage', () => {
43+
it('should trigger checkCoverage when a new transaction is added', async () => {
44+
const { baseMessenger, backend } = setup();
45+
const txMeta = generateMockTxMeta();
46+
const coverageResultReceived = new Promise<void>((resolve) => {
47+
baseMessenger.subscribe(
48+
'ShieldController:coverageResultReceived',
49+
(_coverageResult) => resolve(),
50+
);
51+
});
52+
baseMessenger.publish(
53+
'TransactionController:stateChange',
54+
{ transactions: [txMeta] } as TransactionControllerState,
55+
undefined as never,
56+
);
57+
expect(await coverageResultReceived).toBeUndefined();
58+
expect(backend.checkCoverage).toHaveBeenCalledWith(txMeta);
59+
});
60+
61+
it('should no longer trigger checkCoverage when controller is stopped', async () => {
62+
const { controller, baseMessenger, backend } = setup();
63+
controller.stop();
64+
const txMeta = generateMockTxMeta();
65+
const coverageResultReceived = new Promise<void>((resolve, reject) => {
66+
baseMessenger.subscribe(
67+
'ShieldController:coverageResultReceived',
68+
(_coverageResult) => resolve(),
69+
);
70+
setTimeout(
71+
() => reject(new Error('Coverage result not received')),
72+
100,
73+
);
74+
});
75+
baseMessenger.publish(
76+
'TransactionController:stateChange',
77+
{ transactions: [txMeta] } as TransactionControllerState,
78+
undefined as never,
79+
);
80+
await expect(coverageResultReceived).rejects.toThrow(
81+
'Coverage result not received',
82+
);
83+
expect(backend.checkCoverage).not.toHaveBeenCalled();
84+
});
85+
86+
it('should purge coverage history when the limit is exceeded', async () => {
87+
const { controller } = setup({
88+
coverageHistoryLimit: 1,
89+
});
90+
const txMeta = generateMockTxMeta();
91+
await controller.checkCoverage(txMeta);
92+
await controller.checkCoverage(txMeta);
93+
expect(controller.state.coverageResults).toHaveProperty(txMeta.id);
94+
expect(controller.state.coverageResults[txMeta.id].results).toHaveLength(
95+
1,
96+
);
97+
});
98+
99+
it('should purge transaction history when the limit is exceeded', async () => {
100+
const { controller } = setup({
101+
transactionHistoryLimit: 1,
102+
});
103+
const txMeta1 = generateMockTxMeta();
104+
const txMeta2 = generateMockTxMeta();
105+
await controller.checkCoverage(txMeta1);
106+
await controller.checkCoverage(txMeta2);
107+
expect(controller.state.coverageResults).toHaveProperty(txMeta2.id);
108+
expect(controller.state.coverageResults[txMeta2.id].results).toHaveLength(
109+
1,
110+
);
111+
});
112+
113+
it('should check coverage when a transaction is simulated', async () => {
114+
const { baseMessenger, backend } = setup();
115+
const txMeta = generateMockTxMeta();
116+
const coverageResultReceived = new Promise<void>((resolve) => {
117+
baseMessenger.subscribe(
118+
'ShieldController:coverageResultReceived',
119+
(_coverageResult) => resolve(),
120+
);
121+
});
122+
123+
// Add transaction.
124+
baseMessenger.publish(
125+
'TransactionController:stateChange',
126+
{ transactions: [txMeta] } as TransactionControllerState,
127+
undefined as never,
128+
);
129+
expect(await coverageResultReceived).toBeUndefined();
130+
expect(backend.checkCoverage).toHaveBeenCalledWith(txMeta);
131+
132+
// Simulate transaction.
133+
txMeta.simulationData = {
134+
tokenBalanceChanges: [],
135+
};
136+
baseMessenger.publish(
137+
'TransactionController:stateChange',
138+
{ transactions: [txMeta] } as TransactionControllerState,
139+
undefined as never,
140+
);
141+
expect(await coverageResultReceived).toBeUndefined();
142+
expect(backend.checkCoverage).toHaveBeenCalledWith(txMeta);
143+
});
144+
});
145+
});

0 commit comments

Comments
 (0)