Skip to content

Commit 014b56c

Browse files
authored
Patch: Compress transaction history (#26236)
## **Description** Compress transaction history down to 100 entries and truncate any existing transaction historys to just 100 entries. This should fix reports we've seen from production of extremely poor performance and crashes caused by long transaction histories, and will also prevent this problem from happening again. Transaction history has been truncated because in the extreme cases, it would be prohibitively expensive to compress. The downside is that some state of how the transaction has changed may be lost. But this is unlikely to impact users because we only show a limited number of events from the transaction history in our UI, and these events are more likely to be at the beginning of long transaction histories. Even if a displayed event is lost, the impact on the UI is minimal (it's only shown on the transaction details page under "Activity log", and only for informational purposes). For details on how the transaction compression works, and how it prevents history size from growing unbouned, see MetaMask/core#4555 The transaction controller change has been applied using a patch. The patch was generated from the core repository branch `patch/transaction-controller-v32-compress-history`. It will be made on `develop` at a later date because it is blocked by other controller updates at the moment. The truncation is performed by a migration that was added in #26291 and cherry-picked into this branch [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/26236?quickstart=1) ## **Related issues** Relates to #9372 ## **Manual testing steps** To test the migration: * Checkout v11.15.6 and create a dev build (unfortunately the repro steps don't work on MV3 due to snow being enabled even in dev builds, so we're using a pre-MV3 build) * Install the dev build from the `dist/chrome` directory and proceed through onboarding * Make a single transaction * Any chain, any transaction, as long as it's approved. We don't even need to wait for it to settle. * Run this command in the background console to add a huge history to the transaction controller and restart the extension: ``` chrome.storage.local.get( null, (state) => { state.data.TransactionController.transactions[0].history.push( ...[...Array(100000).keys()].map(() => [ { value: '[ethjs-rpc] rpc error with payload {"id":[number],"jsonrpc":"2.0","params":["0x"],"method":"eth_getTransactionReceipt"} { "code": -32603, "message": "Internal JSON-RPC error.", "data": { "code": -32602, "message": "invalid argument 0: hex string has length 0, want 64 for common.Hash", "cause": null }, "stack": ...', path: '/warning/error', op: 'replace' }, { note: 'transactions/pending-tx-tracker#event: tx:warning', value: 'There was a problem loading this transaction.', path: '/warning/message', op: 'replace' }, ]), ); chrome.storage.local.set(state, () => chrome.runtime.reload()); } ); ``` * The extension should become extremely slow * Disable the extension * Switch to this branch and create a dev build * Enable and reload the extension * The extension should no longer be slow To test that the compression is working, we would want to get a transaction in a "stuck pending" state where an error is captured each iteration. I am not yet sure how to do that unfortunately. ## **Screenshots/Recordings** N/A ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.
1 parent ce1ed8d commit 014b56c

File tree

6 files changed

+407
-4
lines changed

6 files changed

+407
-4
lines changed
1.24 MB
Binary file not shown.
Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
import { cloneDeep } from 'lodash';
2+
import { migrate, version } from './120.3';
3+
4+
const sentryCaptureExceptionMock = jest.fn();
5+
6+
global.sentry = {
7+
captureException: sentryCaptureExceptionMock,
8+
};
9+
10+
const oldVersion = 120.2;
11+
12+
describe('migration #120.3', () => {
13+
afterEach(() => {
14+
jest.resetAllMocks();
15+
});
16+
17+
it('updates the version metadata', async () => {
18+
const oldStorage = {
19+
meta: { version: oldVersion },
20+
data: {},
21+
};
22+
23+
const newStorage = await migrate(oldStorage);
24+
25+
expect(newStorage.meta).toStrictEqual({ version });
26+
});
27+
28+
it('returns state unchanged if TransactionController state is missing', async () => {
29+
const oldStorage = {
30+
meta: { version: oldVersion },
31+
data: {
32+
PreferencesController: {},
33+
},
34+
};
35+
const oldStorageDataClone = cloneDeep(oldStorage.data);
36+
37+
const newStorage = await migrate(oldStorage);
38+
39+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
40+
});
41+
42+
it('reports error and returns state unchanged if TransactionController state is invalid', async () => {
43+
const oldStorage = {
44+
meta: { version: oldVersion },
45+
data: {
46+
PreferencesController: {},
47+
TransactionController: 'invalid',
48+
},
49+
};
50+
const oldStorageDataClone = cloneDeep(oldStorage.data);
51+
52+
const newStorage = await migrate(oldStorage);
53+
54+
expect(sentryCaptureExceptionMock).toHaveBeenCalledWith(
55+
`Migration ${version}: Invalid TransactionController state of type 'string'`,
56+
);
57+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
58+
});
59+
60+
it('returns state unchanged if transactions are missing', async () => {
61+
const oldStorage = {
62+
meta: { version: oldVersion },
63+
data: {
64+
PreferencesController: {},
65+
TransactionController: {},
66+
},
67+
};
68+
const oldStorageDataClone = cloneDeep(oldStorage.data);
69+
70+
const newStorage = await migrate(oldStorage);
71+
72+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
73+
});
74+
75+
it('reports error and returns state unchanged if transactions property is invalid', async () => {
76+
const oldStorage = {
77+
meta: { version: oldVersion },
78+
data: {
79+
PreferencesController: {},
80+
TransactionController: {
81+
transactions: 'invalid',
82+
},
83+
},
84+
};
85+
const oldStorageDataClone = cloneDeep(oldStorage.data);
86+
87+
const newStorage = await migrate(oldStorage);
88+
89+
expect(sentryCaptureExceptionMock).toHaveBeenCalledWith(
90+
`Migration ${version}: Invalid TransactionController transactions state of type 'string'`,
91+
);
92+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
93+
});
94+
95+
it('reports error and returns state unchanged if there is an invalid transaction', async () => {
96+
const oldStorage = {
97+
meta: { version: oldVersion },
98+
data: {
99+
PreferencesController: {},
100+
TransactionController: {
101+
transactions: [
102+
{}, // empty object is valid for the purposes of this migration
103+
'invalid',
104+
{},
105+
],
106+
},
107+
},
108+
};
109+
const oldStorageDataClone = cloneDeep(oldStorage.data);
110+
111+
const newStorage = await migrate(oldStorage);
112+
113+
expect(sentryCaptureExceptionMock).toHaveBeenCalledWith(
114+
`Migration ${version}: Invalid transaction of type 'string'`,
115+
);
116+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
117+
});
118+
119+
it('reports error and returns state unchanged if there is a transaction with an invalid history property', async () => {
120+
const oldStorage = {
121+
meta: { version: oldVersion },
122+
data: {
123+
PreferencesController: {},
124+
TransactionController: {
125+
transactions: [
126+
{}, // empty object is valid for the purposes of this migration
127+
{
128+
history: 'invalid',
129+
},
130+
{},
131+
],
132+
},
133+
},
134+
};
135+
const oldStorageDataClone = cloneDeep(oldStorage.data);
136+
137+
const newStorage = await migrate(oldStorage);
138+
139+
expect(sentryCaptureExceptionMock).toHaveBeenCalledWith(
140+
`Migration ${version}: Invalid transaction history of type 'string'`,
141+
);
142+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
143+
});
144+
145+
it('returns state unchanged if there are no transactions', async () => {
146+
const oldStorage = {
147+
meta: { version: oldVersion },
148+
data: {
149+
PreferencesController: {},
150+
TransactionController: {
151+
transactions: [],
152+
},
153+
},
154+
};
155+
const oldStorageDataClone = cloneDeep(oldStorage.data);
156+
157+
const newStorage = await migrate(oldStorage);
158+
159+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
160+
});
161+
162+
it('returns state unchanged if there are no transactions with history', async () => {
163+
const oldStorage = {
164+
meta: { version: oldVersion },
165+
data: {
166+
PreferencesController: {},
167+
TransactionController: {
168+
transactions: [{}, {}, {}],
169+
},
170+
},
171+
};
172+
const oldStorageDataClone = cloneDeep(oldStorage.data);
173+
174+
const newStorage = await migrate(oldStorage);
175+
176+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
177+
});
178+
179+
it('returns state unchanged if there are no transactions with history exceeding max size', async () => {
180+
const oldStorage = {
181+
meta: { version: oldVersion },
182+
data: {
183+
PreferencesController: {},
184+
TransactionController: {
185+
transactions: [
186+
{
187+
history: [...Array(99).keys()],
188+
},
189+
{
190+
history: [...Array(100).keys()],
191+
},
192+
{
193+
history: [],
194+
},
195+
],
196+
},
197+
},
198+
};
199+
const oldStorageDataClone = cloneDeep(oldStorage.data);
200+
201+
const newStorage = await migrate(oldStorage);
202+
203+
expect(newStorage.data).toStrictEqual(oldStorageDataClone);
204+
});
205+
206+
it('trims histories exceeding max size', async () => {
207+
const oldStorage = {
208+
meta: { version: oldVersion },
209+
data: {
210+
PreferencesController: {},
211+
TransactionController: {
212+
transactions: [
213+
{
214+
history: [...Array(99).keys()],
215+
},
216+
{
217+
history: [...Array(100).keys()],
218+
},
219+
{
220+
history: [...Array(101).keys()],
221+
},
222+
{
223+
history: [...Array(1000).keys()],
224+
},
225+
],
226+
},
227+
},
228+
};
229+
const oldStorageDataClone = cloneDeep(oldStorage.data);
230+
231+
const newStorage = await migrate(oldStorage);
232+
233+
expect(newStorage.data).toStrictEqual({
234+
...oldStorageDataClone,
235+
TransactionController: {
236+
transactions: [
237+
{
238+
history: [...Array(99).keys()],
239+
},
240+
{
241+
history: [...Array(100).keys()],
242+
},
243+
{
244+
history: [...Array(100).keys()],
245+
},
246+
{
247+
history: [...Array(100).keys()],
248+
},
249+
],
250+
},
251+
});
252+
});
253+
});

app/scripts/migrations/120.3.ts

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import { RuntimeObject, hasProperty, isObject } from '@metamask/utils';
2+
import { cloneDeep } from 'lodash';
3+
import log from 'loglevel';
4+
5+
type VersionedData = {
6+
meta: { version: number };
7+
data: Record<string, unknown>;
8+
};
9+
10+
export const version = 120.3;
11+
12+
const MAX_TRANSACTION_HISTORY_LENGTH = 100;
13+
14+
/**
15+
* This migration trims the size of any large transaction histories. This will
16+
* result in some loss of information, but the impact is minor. The lost data
17+
* is only used in the "Activity log" on the transaction details page.
18+
*
19+
* @param originalVersionedData - Versioned MetaMask extension state, exactly
20+
* what we persist to dist.
21+
* @param originalVersionedData.meta - State metadata.
22+
* @param originalVersionedData.meta.version - The current state version.
23+
* @param originalVersionedData.data - The persisted MetaMask state, keyed by
24+
* controller.
25+
* @returns Updated versioned MetaMask extension state.
26+
*/
27+
export async function migrate(
28+
originalVersionedData: VersionedData,
29+
): Promise<VersionedData> {
30+
const versionedData = cloneDeep(originalVersionedData);
31+
versionedData.meta.version = version;
32+
transformState(versionedData.data);
33+
return versionedData;
34+
}
35+
36+
function transformState(state: Record<string, unknown>): void {
37+
if (!hasProperty(state, 'TransactionController')) {
38+
log.warn(`Migration ${version}: Missing TransactionController state`);
39+
return;
40+
} else if (!isObject(state.TransactionController)) {
41+
global.sentry?.captureException(
42+
`Migration ${version}: Invalid TransactionController state of type '${typeof state.TransactionController}'`,
43+
);
44+
return;
45+
}
46+
47+
const transactionControllerState = state.TransactionController;
48+
49+
if (!hasProperty(transactionControllerState, 'transactions')) {
50+
log.warn(
51+
`Migration ${version}: Missing TransactionController transactions`,
52+
);
53+
return;
54+
} else if (!Array.isArray(transactionControllerState.transactions)) {
55+
global.sentry?.captureException(
56+
`Migration ${version}: Invalid TransactionController transactions state of type '${typeof transactionControllerState.transactions}'`,
57+
);
58+
return;
59+
}
60+
61+
const { transactions } = transactionControllerState;
62+
const validTransactions = transactions.filter(isObject);
63+
if (transactions.length !== validTransactions.length) {
64+
const invalidTransaction = transactions.find(
65+
(transaction) => !isObject(transaction),
66+
);
67+
global.sentry?.captureException(
68+
`Migration ${version}: Invalid transaction of type '${typeof invalidTransaction}'`,
69+
);
70+
return;
71+
}
72+
73+
const validHistoryTransactions = validTransactions.filter(
74+
hasValidTransactionHistory,
75+
);
76+
if (validHistoryTransactions.length !== validTransactions.length) {
77+
const invalidTransaction = validTransactions.find(
78+
(transaction) => !hasValidTransactionHistory(transaction),
79+
);
80+
global.sentry?.captureException(
81+
`Migration ${version}: Invalid transaction history of type '${typeof invalidTransaction?.history}'`,
82+
);
83+
return;
84+
}
85+
86+
for (const transaction of validHistoryTransactions) {
87+
if (
88+
transaction.history &&
89+
transaction.history.length > MAX_TRANSACTION_HISTORY_LENGTH
90+
) {
91+
transaction.history = transaction.history.slice(
92+
0,
93+
MAX_TRANSACTION_HISTORY_LENGTH,
94+
);
95+
}
96+
}
97+
}
98+
99+
/**
100+
* Check whether the given object has a valid `history` property, or no `history`
101+
* property. We just check that it's an array, we don't validate the contents.
102+
*
103+
* @param transaction - The object to validate.
104+
* @returns True if the given object was valid, false otherwise.
105+
*/
106+
function hasValidTransactionHistory(
107+
transaction: RuntimeObject,
108+
): transaction is RuntimeObject & {
109+
history: undefined | unknown[];
110+
} {
111+
return (
112+
!hasProperty(transaction, 'history') || Array.isArray(transaction.history)
113+
);
114+
}

app/scripts/migrations/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ const migrations = [
133133
require('./120'),
134134
require('./120.1'),
135135
require('./120.2'),
136+
require('./120.3'),
136137
];
137138

138139
export default migrations;

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@
224224
"@trezor/schema-utils@npm:1.0.2": "patch:@trezor/schema-utils@npm%3A1.0.2#~/.yarn/patches/@trezor-schema-utils-npm-1.0.2-7dd48689b2.patch",
225225
"lavamoat-core@npm:^15.1.1": "patch:lavamoat-core@npm%3A15.1.1#~/.yarn/patches/lavamoat-core-npm-15.1.1-51fbe39988.patch",
226226
"@metamask/snaps-sdk": "^5.0.0",
227-
"@metamask/transaction-controller": "^32.0.0",
227+
"@metamask/transaction-controller": "patch:@metamask/transaction-controller@npm%3A32.0.0#~/.yarn/patches/@metamask-transaction-controller-npm-32.0.0-e23c2c3443.patch",
228228
"@babel/runtime@npm:^7.7.6": "patch:@babel/runtime@npm%3A7.24.0#~/.yarn/patches/@babel-runtime-npm-7.24.0-7eb1dd11a2.patch",
229229
"@babel/runtime@npm:^7.9.2": "patch:@babel/runtime@npm%3A7.24.0#~/.yarn/patches/@babel-runtime-npm-7.24.0-7eb1dd11a2.patch",
230230
"@babel/runtime@npm:^7.12.5": "patch:@babel/runtime@npm%3A7.24.0#~/.yarn/patches/@babel-runtime-npm-7.24.0-7eb1dd11a2.patch",
@@ -350,7 +350,7 @@
350350
"@metamask/snaps-rpc-methods": "^9.1.3",
351351
"@metamask/snaps-sdk": "^5.0.0",
352352
"@metamask/snaps-utils": "patch:@metamask/snaps-utils@npm%3A7.6.0#~/.yarn/patches/@metamask-snaps-utils-npm-7.6.0-5569b09766.patch",
353-
"@metamask/transaction-controller": "^32.0.0",
353+
"@metamask/transaction-controller": "patch:@metamask/transaction-controller@npm%3A32.0.0#~/.yarn/patches/@metamask-transaction-controller-npm-32.0.0-e23c2c3443.patch",
354354
"@metamask/user-operation-controller": "^10.0.0",
355355
"@metamask/utils": "^8.2.1",
356356
"@ngraveio/bc-ur": "^1.1.12",

0 commit comments

Comments
 (0)