Skip to content

Commit e8b9146

Browse files
authored
chore: track token table sort metrics (#47845)
<!-- 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. --> ## **Description** Clicking a token table sort header in widescreen view now sends the existing `Token Sort Preference Updated` event. The sort menu sends the same event with `location: Sort Menu`. `token_sort_preference` stays `title` or `tokenFiatAmount` for the name and balance sorts, and is `price` or `percentChange` for the new header sorts. Those values live on `MetaMetricsTokenSortPreference`. The saved sort keys are unchanged. On the wide table, the sort menu button is now hidden because the column headers are the sort control. ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: https://consensyssoftware.atlassian.net/browse/CEUX-1373 ## **Manual testing steps** 1. Open the wallet wide enough to show the token table. 2. Confirm the sort menu button is not shown next to the network filter. 3. Click Token, Price, 24h change, and Balance, including a second click on the same header. 4. In the MetaMetrics debugger, confirm each click sends `Token Sort Preference Updated` with `location` `Token Column Header` and `token_sort_preference` of `title`, `price`, `percentChange`, or `tokenFiatAmount`. 5. Narrow the wallet until the token list replaces the table. 6. Open the sort menu and choose Alphabetically, then Declining balance. 7. Confirm those events use `location` `Sort Menu` and `token_sort_preference` of `title` or `tokenFiatAmount`, and that the saved sort updates. Example new event ``` { "category": "Settings", "token_sort_preference": "title", "location": "Token Column Header", "environment_type": "fullscreen", "locale": "en", "chain_id": "0x1", "profile_id": "be2ccf24-a244-45d1-b3b5-c5ae833c8702", "canonical_profile_id": "3ad7e304-c059-4d3d-a349-5fb7f9c15e3a" } ``` Updated existing event with location ``` { "category": "Settings", "token_sort_preference": "title", "location": "Sort Menu", "environment_type": "fullscreen", "locale": "en", "chain_id": "0x1", "profile_id": "be2ccf24-a244-45d1-b3b5-c5ae833c8702", "canonical_profile_id": "3ad7e304-c059-4d3d-a349-5fb7f9c15e3a" } ``` ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <!-- [screenshots/recordings] --> ### **After** <!-- [screenshots/recordings] --> ## **Pre-merge author checklist** - [ ] 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. ## **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. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Analytics and UI-only changes; no auth, persistence, or transaction logic affected. > > **Overview** > **Token sort analytics** now distinguish **where** sorting happened and use typed preference values. New enums `MetaMetricsTokenSortLocation` (`Sort Menu`, `Token Column Header`) and `MetaMetricsTokenSortPreference` (`title`, `tokenFiatAmount`, `price`, `percentChange`) standardize the existing `Token Sort Preference Updated` event. > > Clicking a **token table column header** emits that event with `location: Token Column Header` and the column-mapped `token_sort_preference`. The **sort menu** still updates saved preferences but now sends the same event with `location: Sort Menu` and enum-backed values instead of raw sort keys. > > On **wide/table layout**, the separate **Sort** control is hidden because headers handle sorting (header sorts remain session-only; persisted config is unchanged). Tests cover analytics for both surfaces. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 6123ddb. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 19c4052 commit e8b9146

6 files changed

Lines changed: 116 additions & 13 deletions

File tree

‎shared/constants/metametrics.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,8 @@ export type MetaMetricsUserTraits = {
489489
// eslint-disable-next-line @typescript-eslint/naming-convention
490490
security_providers?: string[];
491491
/**
492-
* Does the user change the token sort order on the asset list
492+
* Does the user change the token sort order on the asset list.
493+
* Event values are {@link MetaMetricsTokenSortPreference}.
493494
*/
494495
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
495496
// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -1402,6 +1403,24 @@ export enum MetaMetricsRequestedThrough {
14021403
MultichainApi = 'multichain_api',
14031404
}
14041405

1406+
/**
1407+
* Where a token sort preference was chosen.
1408+
*/
1409+
export enum MetaMetricsTokenSortLocation {
1410+
SortMenu = 'Sort Menu',
1411+
TokenColumnHeader = 'Token Column Header',
1412+
}
1413+
1414+
/**
1415+
* `token_sort_preference` values for Token Sort Preference Updated.
1416+
*/
1417+
export enum MetaMetricsTokenSortPreference {
1418+
Title = 'title',
1419+
TokenFiatAmount = 'tokenFiatAmount',
1420+
Price = 'price',
1421+
PercentChange = 'percentChange',
1422+
}
1423+
14051424
export enum MetaMetricsEventLocation {
14061425
AlertFrictionModal = 'alert_friction_modal',
14071426
Confirmation = 'confirmation',

‎ui/components/app/assets/asset-list/asset-list.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ const AssetList = ({
9898
<AssetControls data-testid="parent-selector-tokens-tab">
9999
<NetworkFilter />
100100
<AssetControlsActions>
101-
<SortByButton />
101+
{variant === 'table' ? null : <SortByButton />}
102102
<TokenOptionsMenu />
103103
</AssetControlsActions>
104104
</AssetControls>

‎ui/components/app/assets/asset-list/sort-control/sort-control.test.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import { getCurrentCurrency } from '../../../../../ducks/metamask/metamask';
88
import {
99
MetaMetricsEventCategory,
1010
MetaMetricsEventName,
11+
MetaMetricsTokenSortLocation,
12+
MetaMetricsTokenSortPreference,
1113
} from '../../../../../../shared/constants/metametrics';
1214
import mockState from '../../../../../../test/data/mock-state.json';
1315
import configureStore from '../../../../../store/store';
@@ -127,7 +129,8 @@ describe('SortControl', () => {
127129
category: MetaMetricsEventCategory.Settings,
128130
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
129131
// eslint-disable-next-line @typescript-eslint/naming-convention
130-
token_sort_preference: 'title',
132+
token_sort_preference: MetaMetricsTokenSortPreference.Title,
133+
location: MetaMetricsTokenSortLocation.SortMenu,
131134
},
132135
sensitiveProperties: {},
133136
}),
@@ -156,7 +159,8 @@ describe('SortControl', () => {
156159
category: MetaMetricsEventCategory.Settings,
157160
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
158161
// eslint-disable-next-line @typescript-eslint/naming-convention
159-
token_sort_preference: 'tokenFiatAmount',
162+
token_sort_preference: MetaMetricsTokenSortPreference.TokenFiatAmount,
163+
location: MetaMetricsTokenSortLocation.SortMenu,
160164
},
161165
sensitiveProperties: {},
162166
}),

‎ui/components/app/assets/asset-list/sort-control/sort-control.tsx‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ import { useAnalytics } from '../../../../../hooks/useAnalytics';
1515
import {
1616
MetaMetricsEventCategory,
1717
MetaMetricsEventName,
18+
MetaMetricsTokenSortLocation,
19+
MetaMetricsTokenSortPreference,
1820
MetaMetricsUserTrait,
1921
} from '../../../../../../shared/constants/metametrics';
2022
import { getTokenSortConfig } from '../../../../../selectors';
@@ -75,6 +77,16 @@ type SortControlProps = {
7577
handleClose: () => void;
7678
};
7779

80+
type SortKey = 'title' | 'tokenFiatAmount';
81+
82+
const TOKEN_SORT_PREFERENCE_BY_KEY: Record<
83+
SortKey,
84+
MetaMetricsTokenSortPreference
85+
> = {
86+
title: MetaMetricsTokenSortPreference.Title,
87+
tokenFiatAmount: MetaMetricsTokenSortPreference.TokenFiatAmount,
88+
};
89+
7890
const SortControl = ({ handleClose }: SortControlProps) => {
7991
const t = useI18nContext();
8092
const { trackEvent, createEventBuilder } = useAnalytics();
@@ -83,13 +95,8 @@ const SortControl = ({ handleClose }: SortControlProps) => {
8395

8496
const dispatch = useDispatch();
8597

86-
type SortKeys = 'title' | 'tokenFiatAmount';
8798
const handleSort = useCallback(
88-
(
89-
key: SortKeys,
90-
sortCallback: keyof SortingCallbacksT,
91-
order: SortOrder,
92-
) => {
99+
(key: SortKey, sortCallback: keyof SortingCallbacksT, order: SortOrder) => {
93100
dispatch(
94101
setTokenSortConfig({
95102
key,
@@ -101,7 +108,9 @@ const SortControl = ({ handleClose }: SortControlProps) => {
101108
createEventBuilder(MetaMetricsEventName.TokenSortPreference)
102109
.addCategory(MetaMetricsEventCategory.Settings)
103110
.addProperties({
104-
[MetaMetricsUserTrait.TokenSortPreference]: key,
111+
[MetaMetricsUserTrait.TokenSortPreference]:
112+
TOKEN_SORT_PREFERENCE_BY_KEY[key],
113+
location: MetaMetricsTokenSortLocation.SortMenu,
105114
})
106115
.build(),
107116
);

‎ui/components/app/assets/token-table/token-table.test.tsx‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,33 @@ import { renderWithProvider } from '../../../../../test/lib/render-helpers-navig
88
import { useTokenListData } from '../hooks/useTokenListData';
99
import type { TokenWithFiatAmount } from '../types';
1010
import { sortTokenAssets } from '../util/sortAssetsWithPriority';
11+
import {
12+
MetaMetricsEventCategory,
13+
MetaMetricsEventName,
14+
MetaMetricsTokenSortLocation,
15+
MetaMetricsTokenSortPreference,
16+
MetaMetricsUserTrait,
17+
} from '../../../../../shared/constants/metametrics';
1118
import { TokenTable } from './token-table';
1219

20+
jest.mock('../../../../hooks/useAnalytics', () => {
21+
const mockTrackEvent = jest.fn();
22+
23+
return {
24+
useAnalytics: () => ({
25+
createEventBuilder: jest.requireActual(
26+
'../../../../../shared/lib/analytics/create-event-builder',
27+
).createEventBuilder,
28+
trackEvent: mockTrackEvent,
29+
}),
30+
mockTrackEvent,
31+
};
32+
});
33+
34+
const getMockTrackEvent = () =>
35+
jest.requireMock('../../../../hooks/useAnalytics')
36+
.mockTrackEvent as jest.Mock;
37+
1338
jest.mock('../hooks/useTokenListData', () => ({
1439
...jest.requireActual('../hooks/useTokenListData'),
1540
useTokenListData: jest.fn(),
@@ -144,32 +169,37 @@ describe('TokenTable', () => {
144169
{
145170
column: 'balance',
146171
label: 'Balance',
172+
preference: MetaMetricsTokenSortPreference.TokenFiatAmount,
147173
first: { direction: 'up', reversed: true, name: 'sorted ascending' },
148174
second: { direction: 'down', reversed: false, name: 'sorted descending' },
149175
},
150176
{
151177
column: 'token',
152178
label: 'Token',
179+
preference: MetaMetricsTokenSortPreference.Title,
153180
first: { direction: 'down', reversed: false, name: 'sorted ascending' },
154181
second: { direction: 'up', reversed: true, name: 'sorted descending' },
155182
},
156183
{
157184
column: 'price',
158185
label: 'Price',
186+
preference: MetaMetricsTokenSortPreference.Price,
159187
first: { direction: 'down', reversed: false, name: 'sorted descending' },
160188
second: { direction: 'up', reversed: true, name: 'sorted ascending' },
161189
},
162190
{
163191
column: 'change',
164192
label: '24h change',
193+
preference: MetaMetricsTokenSortPreference.PercentChange,
165194
first: { direction: 'down', reversed: false, name: 'sorted descending' },
166195
second: { direction: 'up', reversed: true, name: 'sorted ascending' },
167196
},
168197
] as const;
169198

170199
it.each(headerSortCases)(
171200
'toggles the $label header sort',
172-
({ column, label, first, second }) => {
201+
({ column, label, preference, first, second }) => {
202+
getMockTrackEvent().mockClear();
173203
mockTokenListData();
174204

175205
const { getByTestId } = renderTable();
@@ -212,6 +242,18 @@ describe('TokenTable', () => {
212242
sortOverride: sortOverride(second.reversed),
213243
}),
214244
);
245+
246+
const sortEvent = expect.objectContaining({
247+
name: MetaMetricsEventName.TokenSortPreference,
248+
properties: {
249+
category: MetaMetricsEventCategory.Settings,
250+
[MetaMetricsUserTrait.TokenSortPreference]: preference,
251+
location: MetaMetricsTokenSortLocation.TokenColumnHeader,
252+
},
253+
sensitiveProperties: {},
254+
});
255+
expect(getMockTrackEvent()).toHaveBeenNthCalledWith(1, sortEvent);
256+
expect(getMockTrackEvent()).toHaveBeenNthCalledWith(2, sortEvent);
215257
},
216258
);
217259

‎ui/components/app/assets/token-table/token-table.tsx‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,15 @@ import {
1313
TextVariant,
1414
} from '@metamask/design-system-react';
1515
import type { CaipAssetType } from '@metamask/utils';
16+
import { useAnalytics } from '../../../../hooks/useAnalytics';
1617
import { useI18nContext } from '../../../../hooks/useI18nContext';
18+
import {
19+
MetaMetricsEventCategory,
20+
MetaMetricsEventName,
21+
MetaMetricsTokenSortLocation,
22+
MetaMetricsTokenSortPreference,
23+
MetaMetricsUserTrait,
24+
} from '../../../../../shared/constants/metametrics';
1725
import { getTokenSortConfig } from '../../../../selectors';
1826
import { VirtualizedList } from '../../../ui/virtualized-list/virtualized-list';
1927
import type { SafeChain } from '../../../multichain/networks-form/use-safe-chains';
@@ -66,6 +74,16 @@ type TokenTableHeaderProps = {
6674

6775
type SortColumn = TokenTableSort['column'];
6876

77+
const TOKEN_SORT_PREFERENCE_BY_COLUMN: Record<
78+
SortColumn,
79+
MetaMetricsTokenSortPreference
80+
> = {
81+
token: MetaMetricsTokenSortPreference.Title,
82+
balance: MetaMetricsTokenSortPreference.TokenFiatAmount,
83+
price: MetaMetricsTokenSortPreference.Price,
84+
change: MetaMetricsTokenSortPreference.PercentChange,
85+
};
86+
6987
type SortableColumnHeaderProps = {
7088
label: string;
7189
column: SortColumn;
@@ -274,6 +292,7 @@ const TokenTableRow = ({
274292
* @param props.safeChains - Known chains, used by the native token warning.
275293
*/
276294
export const TokenTable = ({ onTokenClick, safeChains }: TokenTableProps) => {
295+
const { trackEvent, createEventBuilder } = useAnalytics();
277296
const tokenSortConfig = useSelector(getTokenSortConfig);
278297
const preferenceKey = `${tokenSortConfig?.key ?? ''}:${tokenSortConfig?.order ?? ''}`;
279298
const [headerSort, setHeaderSort] = useState<TokenTableHeaderSort | null>(
@@ -293,8 +312,18 @@ export const TokenTable = ({ onTokenClick, safeChains }: TokenTableProps) => {
293312
(column: SortColumn) => {
294313
const nextReversed = column === activeColumn ? !reversed : false;
295314
setHeaderSort({ column, reversed: nextReversed });
315+
trackEvent(
316+
createEventBuilder(MetaMetricsEventName.TokenSortPreference)
317+
.addCategory(MetaMetricsEventCategory.Settings)
318+
.addProperties({
319+
[MetaMetricsUserTrait.TokenSortPreference]:
320+
TOKEN_SORT_PREFERENCE_BY_COLUMN[column],
321+
location: MetaMetricsTokenSortLocation.TokenColumnHeader,
322+
})
323+
.build(),
324+
);
296325
},
297-
[activeColumn, reversed],
326+
[activeColumn, createEventBuilder, reversed, trackEvent],
298327
);
299328

300329
const sortOverride = useTokenSortOverride(headerSort);

0 commit comments

Comments
 (0)