Skip to content

Commit ed5d3de

Browse files
committed
fix: Remove previousUserTraits from metametrics controller state (#30621)
<!-- Please submit this PR as a draft initially. Do not mark it as "Ready for review" until the template has been completely filled out, and PR status checks have passed at least once. --> <!-- Write a short description of the changes included in this pull request, also include relevant motivation and context. Have in mind the following questions: 1. What is the reason for the change? 2. What is the improvement/solution? --> Truly solving https://github.com/MetaMask/MetaMask-planning/issues/3932 required us to clear `previousUserTraits` from metametrics controller state. That property just functions as a cache, and we could actually maintain it in memory. The reason we need to clear it is that there are many users who had the `has_marketing_consent` trait populated to `true` when the application had a bug that prevented that trait from being submitted to segment. That bug is fixed, so new users don't hit that problem. However, to correctly track existing users that have `has_marketing_consent` set to true, we need the comparison of previous and current user traits in the `_buildUserTraitsObject` function to fail its equality check. To do that, we are clearing `previousUserTraits` so that, upon update of the extension and when the first metrics event is set to segment, the current user trait values will compare to undefined, and they will all be submitted to segment, including `has_marketing_consent`. [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/30621?quickstart=1) Fixes: 1. Install a build from this branch 2. Open the background console and the network tab 3. Start onboarding. On the metametrics screen, click the checkbox and then "I agree" 4. The network tab should now include a request to segment with user traits, where has_marketing_consent is set to true -- 1. Follow the above steps on the v12.9.3 build (step 4 will fail) 2. Update the version of that install to the build from this branch 3. Log in. 4. The network tab should now include a request to segment with user traits, where has_marketing_consent is set to true <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> <!-- [screenshots/recordings] --> <!-- [screenshots/recordings] --> - [ ] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [ ] I've completed the PR template to the best of my ability - [ ] I’ve included tests if applicable - [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [ ] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. - [ ] 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 ba1bc15 commit ed5d3de

File tree

8 files changed

+104
-40
lines changed

8 files changed

+104
-40
lines changed

app/scripts/constants/sentry-state.ts

-1
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,6 @@ export const SENTRY_BACKGROUND_STATE = {
185185
fragments: false,
186186
metaMetricsId: true,
187187
participateInMetaMetrics: true,
188-
previousUserTraits: false,
189188
segmentApiCalls: false,
190189
traits: false,
191190
dataCollectionForMarketing: false,

app/scripts/controllers/metametrics-controller.ts

+12-18
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,6 @@ const controllerMetadata = {
209209
persist: true,
210210
anonymous: false,
211211
},
212-
previousUserTraits: {
213-
persist: true,
214-
anonymous: false,
215-
},
216212
dataCollectionForMarketing: {
217213
persist: true,
218214
anonymous: false,
@@ -237,7 +233,6 @@ const controllerMetadata = {
237233
* @property fragments - Object keyed by UUID with stored fragments as values.
238234
* @property eventsBeforeMetricsOptIn - Array of queued events added before a user opts into metrics.
239235
* @property traits - Traits that are not derived from other state keys.
240-
* @property previousUserTraits - The user traits the last time they were computed.
241236
* @property dataCollectionForMarketing - Flag to determine if data collection for marketing is enabled.
242237
* @property marketingCampaignCookieId - The marketing campaign cookie id.
243238
* @property segmentApiCalls - Object keyed by messageId with segment event type and payload as values.
@@ -249,7 +244,6 @@ export type MetaMetricsControllerState = {
249244
fragments: Record<string, MetaMetricsEventFragment>;
250245
eventsBeforeMetricsOptIn: MetaMetricsEventPayload[];
251246
traits: MetaMetricsUserTraits;
252-
previousUserTraits?: MetaMetricsUserTraits;
253247
dataCollectionForMarketing: boolean | null;
254248
marketingCampaignCookieId: string | null;
255249
segmentApiCalls: Record<
@@ -336,7 +330,6 @@ export const getDefaultMetaMetricsControllerState =
336330
latestNonAnonymousEventTimestamp: 0,
337331
eventsBeforeMetricsOptIn: [],
338332
traits: {},
339-
previousUserTraits: {},
340333
fragments: {},
341334
segmentApiCalls: {},
342335
});
@@ -352,6 +345,8 @@ export default class MetaMetricsController extends BaseController<
352345

353346
locale: string;
354347

348+
previousUserTraits?: MetaMetricsUserTraits;
349+
355350
version: MetaMetricsControllerOptions['version'];
356351

357352
#extension: MetaMetricsControllerOptions['extension'];
@@ -1178,7 +1173,7 @@ export default class MetaMetricsController extends BaseController<
11781173
? Object.keys(metamaskState.custodyAccountDetails)[0]
11791174
: null;
11801175
///: END:ONLY_INCLUDE_IF
1181-
const { traits, previousUserTraits } = this.state;
1176+
const { traits } = this.state;
11821177

11831178
const currentTraits = {
11841179
[MetaMetricsUserTrait.AddressBookEntries]: sum(
@@ -1239,24 +1234,23 @@ export default class MetaMetricsController extends BaseController<
12391234
),
12401235
};
12411236

1242-
if (!previousUserTraits && metamaskState.participateInMetaMetrics) {
1243-
this.update((state) => {
1244-
state.previousUserTraits = currentTraits;
1245-
});
1237+
if (!this.previousUserTraits && metamaskState.participateInMetaMetrics) {
1238+
this.previousUserTraits = currentTraits;
12461239
return currentTraits;
12471240
}
12481241

1249-
if (previousUserTraits && !isEqual(previousUserTraits, currentTraits)) {
1242+
if (
1243+
this.previousUserTraits &&
1244+
!isEqual(this.previousUserTraits, currentTraits)
1245+
) {
12501246
const updates = pickBy(currentTraits, (v, k) => {
1251-
// @ts-expect-error It's okay that `k` may not be a key of `previousUserTraits`, because we assume `isEqual` can handle it
1252-
const previous = previousUserTraits[k];
1247+
// @ts-expect-error It's okay that `k` may not be a key of `this.previousUserTraits`, because we assume `isEqual` can handle it
1248+
const previous = this.previousUserTraits[k];
12531249
return !isEqual(previous, v);
12541250
});
12551251

12561252
if (metamaskState.participateInMetaMetrics) {
1257-
this.update((state) => {
1258-
state.previousUserTraits = currentTraits;
1259-
});
1253+
this.previousUserTraits = currentTraits;
12601254
}
12611255

12621256
return updates;

app/scripts/migrations/143.1.test.ts

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { migrate, version } from './143.1';
2+
3+
const oldVersion = 143;
4+
5+
describe(`migration #${version}`, () => {
6+
it('updates the version metadata', async () => {
7+
const oldStorage = {
8+
meta: { version: oldVersion },
9+
data: {},
10+
};
11+
const newStorage = await migrate(oldStorage);
12+
expect(newStorage.meta).toStrictEqual({ version });
13+
});
14+
15+
describe(`migration #${version}`, () => {
16+
it('removes the previousUserTraits property from MetaMetricsController state and does not remove other properties', async () => {
17+
const oldStorage = {
18+
meta: { version: oldVersion },
19+
data: {
20+
MetaMetricsController: {
21+
previousUserTraits: { test: 123 },
22+
foo: 'bar',
23+
},
24+
},
25+
};
26+
const expectedData = {
27+
MetaMetricsController: {
28+
foo: 'bar',
29+
},
30+
};
31+
const newStorage = await migrate(oldStorage);
32+
33+
expect(newStorage.data).toStrictEqual(expectedData);
34+
});
35+
36+
it('has no effect if the previousUserTraits property does not exist', async () => {
37+
const oldStorage = {
38+
meta: { version: oldVersion },
39+
data: {
40+
MetaMetricsController: {
41+
foo: 'bar',
42+
},
43+
},
44+
};
45+
const expectedData = {
46+
MetaMetricsController: {
47+
foo: 'bar',
48+
},
49+
};
50+
const newStorage = await migrate(oldStorage);
51+
52+
expect(newStorage.data).toStrictEqual(expectedData);
53+
});
54+
});
55+
});

app/scripts/migrations/143.1.ts

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { cloneDeep } from 'lodash';
2+
3+
type VersionedData = {
4+
meta: { version: number };
5+
data: Record<string, unknown>;
6+
};
7+
8+
export const version = 143.1;
9+
10+
/**
11+
* This migration deletes the `previousUserTraits` property from the MetaMetrics Controller state
12+
*
13+
* @param originalVersionedData - Versioned MetaMask extension state, exactly
14+
* what we persist to dist.
15+
* @param originalVersionedData.meta - State metadata.
16+
* @param originalVersionedData.meta.version - The current state version.
17+
* @param originalVersionedData.data - The persisted MetaMask state, keyed by
18+
* controller.
19+
* @returns Updated versioned MetaMask extension state.
20+
*/
21+
export async function migrate(
22+
originalVersionedData: VersionedData,
23+
): Promise<VersionedData> {
24+
const versionedData = cloneDeep(originalVersionedData);
25+
versionedData.meta.version = version;
26+
transformState(versionedData.data);
27+
return versionedData;
28+
}
29+
30+
function transformState(state: Record<string, unknown>) {
31+
const metaMetricsControllerState = state?.MetaMetricsController as
32+
| Record<string, unknown>
33+
| undefined;
34+
35+
delete metaMetricsControllerState?.previousUserTraits;
36+
}

app/scripts/migrations/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ const migrations = [
168168
require('./141'),
169169
require('./142'),
170170
require('./143'),
171+
require('./143.1'),
171172
];
172173

173174
export default migrations;

test/e2e/tests/metrics/state-snapshots/errors-after-init-opt-in-background-state.json

-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@
135135
"marketingCampaignCookieId": null,
136136
"eventsBeforeMetricsOptIn": "object",
137137
"traits": "object",
138-
"previousUserTraits": "object",
139138
"fragments": "object",
140139
"segmentApiCalls": "object"
141140
},

test/e2e/tests/metrics/state-snapshots/errors-after-init-opt-in-ui-state.json

-1
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,6 @@
203203
"marketingCampaignCookieId": null,
204204
"eventsBeforeMetricsOptIn": "object",
205205
"traits": "object",
206-
"previousUserTraits": "object",
207206
"fragments": "object",
208207
"segmentApiCalls": "object",
209208
"metaMetricsDataDeletionId": null,

test/integration/data/onboarding-completion-route.json

-19
Original file line numberDiff line numberDiff line change
@@ -242,25 +242,6 @@
242242
"preventPollingOnNetworkRestart": false,
243243
"previousAppVersion": "",
244244
"previousMigrationVersion": 0,
245-
"previousUserTraits": {
246-
"address_book_entries": 1,
247-
"install_date_ext": "",
248-
"ledger_connection_type": "u2f",
249-
"networks_added": [],
250-
"networks_without_ticker": [],
251-
"nft_autodetection_enabled": false,
252-
"number_of_accounts": 1,
253-
"number_of_nft_collections": 0,
254-
"number_of_nfts": 0,
255-
"number_of_tokens": 0,
256-
"undefined": false,
257-
"three_box_enabled": false,
258-
"theme": "os",
259-
"token_detection_enabled": true,
260-
"desktop_enabled": false,
261-
"security_providers": ["blockaid"],
262-
"petname_addresses_count": 1
263-
},
264245
"providerConfig": {
265246
"type": "sepolia",
266247
"chainId": "0xaa36a7",

0 commit comments

Comments
 (0)