Skip to content

Commit 3f06885

Browse files
authored
feat: add wide screen token table sort controls (#47835)
<!-- 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** This PR affects the new wide screen experience only, where the Token List renders as a new Token Table. This PR adds in sort controls to the 4 headers: Token, Price, 24h Change, Balance. When sorted, they stay local to the table and are not written to the saved sort preference (the existing `tokenSortConfig`). So the sort preference in state is unchanged, and DeFi still uses that preference, as well as non-widescreen Token List. The down arrow is the default: A–Z, or the highest value first. The first click on a column selects that default. Another click reverses it. Missing and non-finite prices and 24h changes sort last in both directions. Equal prices and changes fall back to the token name. Low-balance tokens collapse only for a high-to-low balance sort. Changing the saved sort clears the header selection. If a user hasn't sorted on the table, it will show the active sort currently being used in the `tokenSortConfig` i.e. Token (alphabetical) or Balance (descending). Piece | File | Change -- | -- | -- TokenTable, TokenTableHeader | ui/components/app/assets/token-table/token-table.tsx | Header buttons and the local sort state. useTokenSortOverride | ui/components/app/assets/hooks/useTokenSortOverride.ts | New. Turns the header click into the sort override, and reads price or 24h only when that column is selected. useTokenListData | ui/components/app/assets/hooks/useTokenListData.ts | Takes the override, filters before sorting, and collapses low-balance tokens only for a high-to-low balance sort. sortTokenAssets | ui/components/app/assets/util/sortAssetsWithPriority.ts | New. Applies the header override. The saved-preference sort stays in sortAssetsWithPriority. getCachedSpotPrice, getCachedPercentChange | shared/lib/token-price.ts | New. Shared price and 24h reads. TokenCellPercentChange | ui/components/app/assets/token-cell/cells/token-cell-percent-change.tsx | 24h change now comes from getCachedPercentChange. useCachedPrice | ui/pages/asset/hooks/useCurrentPrice.ts | Spot price now comes from getCachedSpotPrice. ## **Changelog** CHANGELOG entry: Adds sort controls to the wide screen Token Table ## **Related issues** Part fixes: https://consensyssoftware.atlassian.net/browse/CEUX-1482 ## **Manual testing steps** 1. Open the home screen at least 768px wide, so the token table is shown. 2. Click Price. The arrow points down and the highest price is first. Tokens with no price stay at the bottom. 2. Click Price again. The arrow points up, the lowest price is first, and tokens with no price stay at the bottom. 3. Widen the table until 24h change is its own column, and repeat those two clicks. The largest gain is first, then the largest loss. Missing changes stay at the bottom. 4. Click Token, then Balance. The first click on Token is A–Z. Balance starts as the saved high-to-low sort, so the first click reverses it. 5. With the balance arrow pointing down, confirm low-balance tokens are behind the collapsed section. Reverse the balance sort, or sort by price, and confirm those tokens appear in the list. 7. Sort by price, then narrow the window below 768px. The token list replaces the table, and widening it again does not restore the price sort. 8. Verify that one smaller screens there is no difference to the existing Token List sort behaviour ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <!-- [screenshots/recordings] --> ### **After** https://github.com/user-attachments/assets/2243f5b4-503f-4b42-8133-987ddc147d6f ## **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** > UI-only sorting and shared price read helpers with test coverage; saved global sort preference behavior is explicitly preserved. > > **Overview** > Adds **click-to-sort headers** on the wide-screen **Token Table** for Token, Price, 24h Change, and Balance. Sorting is **session-local** (not written to `tokenSortConfig`); the UI reflects the saved preference until a header is clicked, then clears header sort when that preference changes. Headers show direction arrows and accessible **sorted ascending/descending** labels. > > Sorting is driven by a new **`sortTokenAssets`** path (optional header override) wired through **`useTokenSortOverride`** and an optional **`sortOverride`** on **`useTokenListData`**. Price and 24h sorts use shared **`getCachedSpotPrice`** / **`getCachedPercentChange`** helpers (also used by **`useCachedPrice`** and token cell 24h display). Missing/non-finite values sort last; low-value token collapse still applies only for high-to-low balance sort. > > Locale strings and broad unit/integration tests cover header toggling, preference reset, and sort ordering. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3d99580. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 388b476 commit 3f06885

13 files changed

Lines changed: 1072 additions & 161 deletions

File tree

‎app/_locales/en/messages.json‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎app/_locales/en_GB/messages.json‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎shared/lib/token-price.test.ts‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import {
2+
getNativeTokenAddress,
3+
type CurrencyRateState,
4+
type MultichainAssetsRatesControllerState,
5+
type TokenRatesControllerState,
6+
} from '@metamask/assets-controllers';
7+
import type { Hex } from '@metamask/utils';
8+
import { getCachedPercentChange, getCachedSpotPrice } from './token-price';
9+
10+
const marketData = (data: object) =>
11+
data as TokenRatesControllerState['marketData'];
12+
const currencyRates = (data: object) =>
13+
data as CurrencyRateState['currencyRates'];
14+
const conversionRates = (data: object) =>
15+
data as MultichainAssetsRatesControllerState['conversionRates'];
16+
17+
const USDC_ADDRESS = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
18+
19+
describe('getCachedSpotPrice', () => {
20+
it('uses the currency rate for a native token', () => {
21+
const price = getCachedSpotPrice({
22+
isNative: true,
23+
symbol: 'ETH',
24+
chainId: '0x1',
25+
currencyRates: currencyRates({ ETH: { conversionRate: 1800 } }),
26+
});
27+
28+
expect(price).toBe(1800);
29+
});
30+
31+
it('multiplies an EVM token market price by the currency rate', () => {
32+
const price = getCachedSpotPrice({
33+
isNative: false,
34+
symbol: 'USDC',
35+
chainId: '0x1',
36+
address: USDC_ADDRESS.toLowerCase(),
37+
marketData: marketData({
38+
'0x1': {
39+
[USDC_ADDRESS]: { price: 0.0005, currency: 'ETH' },
40+
},
41+
}),
42+
currencyRates: currencyRates({ ETH: { conversionRate: 2000 } }),
43+
});
44+
45+
expect(price).toBe(1);
46+
});
47+
48+
it('returns undefined when an EVM token has no market data', () => {
49+
const price = getCachedSpotPrice({
50+
isNative: false,
51+
symbol: 'USDC',
52+
chainId: '0x1',
53+
address: USDC_ADDRESS,
54+
});
55+
56+
expect(price).toBeUndefined();
57+
});
58+
59+
it('parses a non-EVM conversion rate', () => {
60+
const assetId = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/slip44:501';
61+
const price = getCachedSpotPrice({
62+
isNative: true,
63+
symbol: 'SOL',
64+
chainId: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
65+
conversionRates: conversionRates({ [assetId]: { rate: '150.25' } }),
66+
});
67+
68+
expect(price).toBe(150.25);
69+
});
70+
});
71+
72+
describe('getCachedPercentChange', () => {
73+
it('reads an EVM token change from market data', () => {
74+
const change = getCachedPercentChange({
75+
isNative: false,
76+
chainId: '0x1',
77+
address: USDC_ADDRESS.toLowerCase(),
78+
marketData: marketData({
79+
'0x1': {
80+
[USDC_ADDRESS]: { pricePercentChange1d: 1.5 },
81+
},
82+
}),
83+
});
84+
85+
expect(change).toBe(1.5);
86+
});
87+
88+
it('reads a native EVM change from the chain native token address', () => {
89+
const nativeAddress = getNativeTokenAddress('0x1' as Hex);
90+
const change = getCachedPercentChange({
91+
isNative: true,
92+
chainId: '0x1',
93+
address: 'slip44:60',
94+
marketData: marketData({
95+
'0x1': {
96+
[nativeAddress]: { pricePercentChange1d: -3 },
97+
},
98+
}),
99+
});
100+
101+
expect(change).toBe(-3);
102+
});
103+
104+
it('reads a non-EVM change from the conversion rate', () => {
105+
const assetId = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/slip44:501';
106+
const change = getCachedPercentChange({
107+
isNative: true,
108+
chainId: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
109+
address: assetId,
110+
conversionRates: conversionRates({
111+
[assetId]: { marketData: { pricePercentChange: { P1D: 2.25 } } },
112+
}),
113+
});
114+
115+
expect(change).toBe(2.25);
116+
});
117+
118+
it('returns undefined when the change is missing', () => {
119+
const change = getCachedPercentChange({
120+
isNative: false,
121+
chainId: '0x1',
122+
address: USDC_ADDRESS,
123+
});
124+
125+
expect(change).toBeUndefined();
126+
});
127+
});

‎shared/lib/token-price.ts‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import {
2+
getNativeTokenAddress,
3+
type CurrencyRateState,
4+
type MultichainAssetsRatesControllerState,
5+
type TokenRatesControllerState,
6+
} from '@metamask/assets-controllers';
7+
import type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';
8+
import { getNativeAssetId, isEvmChainId } from './asset-utils';
9+
import { toChecksumHexAddress } from './hexstring-utils';
10+
11+
type MarketData = TokenRatesControllerState['marketData'];
12+
type CurrencyRates = CurrencyRateState['currencyRates'];
13+
type ConversionRates = MultichainAssetsRatesControllerState['conversionRates'];
14+
15+
type CachedSpotPriceInput = {
16+
isNative: boolean;
17+
symbol: string;
18+
chainId: Hex | CaipChainId;
19+
/** EVM token address, or the non-EVM token asset id. */
20+
address?: string;
21+
marketData?: MarketData;
22+
currencyRates?: CurrencyRates;
23+
conversionRates?: ConversionRates;
24+
};
25+
26+
/**
27+
* Cached spot price in the user's currency. Native tokens use the currency
28+
* rate, EVM tokens use the market price times that rate, and non-EVM assets
29+
* use their conversion rate. Missing data returns `undefined`.
30+
*
31+
* @param input - The asset identity and the cached rate maps.
32+
* @param input.isNative - Whether the asset is the chain's native token.
33+
* @param input.symbol - The asset symbol, used for the native currency rate.
34+
* @param input.chainId - The asset's chain id. This decides the EVM lookup and the non-EVM native asset id.
35+
* @param input.address - The EVM token address, or the non-EVM token asset id.
36+
* @param input.marketData - EVM market data keyed by chain id and address.
37+
* @param input.currencyRates - Fiat rates keyed by currency symbol.
38+
* @param input.conversionRates - Non-EVM rates keyed by asset id.
39+
* @returns The price, or `undefined` when it is not cached.
40+
*/
41+
export function getCachedSpotPrice({
42+
isNative,
43+
symbol,
44+
chainId,
45+
address,
46+
marketData,
47+
currencyRates,
48+
conversionRates,
49+
}: CachedSpotPriceInput): number | undefined {
50+
if (isEvmChainId(chainId)) {
51+
if (isNative) {
52+
return currencyRates?.[symbol]?.conversionRate ?? undefined;
53+
}
54+
55+
if (!address) {
56+
return undefined;
57+
}
58+
59+
const tokenMarket =
60+
marketData?.[chainId as Hex]?.[toChecksumHexAddress(address) as Hex];
61+
const exchangeRate = tokenMarket?.currency
62+
? (currencyRates?.[tokenMarket.currency]?.conversionRate ?? undefined)
63+
: undefined;
64+
const price = tokenMarket?.price;
65+
66+
return exchangeRate !== undefined && price !== undefined
67+
? exchangeRate * price
68+
: undefined;
69+
}
70+
71+
const rateKey = isNative ? getNativeAssetId(chainId) : address;
72+
if (!rateKey) {
73+
return undefined;
74+
}
75+
76+
const rate = conversionRates?.[rateKey as CaipAssetType]?.rate;
77+
if (!rate) {
78+
return undefined;
79+
}
80+
81+
return parseFloat(rate);
82+
}
83+
84+
type CachedPercentChangeInput = {
85+
isNative: boolean;
86+
chainId: Hex | CaipChainId;
87+
/** EVM token address, or the non-EVM asset id. */
88+
address?: string;
89+
marketData?: MarketData;
90+
conversionRates?: ConversionRates;
91+
};
92+
93+
/**
94+
* Cached 24h percent change. EVM assets read `pricePercentChange1d`. Native
95+
* EVM assets use the chain's native token address, which is where that change
96+
* is stored. Non-EVM assets read the P1D conversion-rate change.
97+
*
98+
* @param input - The asset identity and the cached rate maps.
99+
* @param input.isNative - Whether the asset is the chain's native token.
100+
* @param input.chainId - The asset's chain id. This decides the EVM lookup.
101+
* @param input.address - The EVM token address, or the non-EVM asset id.
102+
* @param input.marketData - EVM market data keyed by chain id and address.
103+
* @param input.conversionRates - Non-EVM rates keyed by asset id.
104+
* @returns The percent change, or `undefined` when it is not cached.
105+
*/
106+
export function getCachedPercentChange({
107+
isNative,
108+
chainId,
109+
address,
110+
marketData,
111+
conversionRates,
112+
}: CachedPercentChangeInput): number | undefined {
113+
const evm = isEvmChainId(chainId);
114+
const tokenAddress =
115+
evm && isNative ? getNativeTokenAddress(chainId as Hex) : address;
116+
117+
if (!tokenAddress) {
118+
return undefined;
119+
}
120+
121+
if (evm) {
122+
return (
123+
marketData?.[chainId as Hex]?.[toChecksumHexAddress(tokenAddress) as Hex]
124+
?.pricePercentChange1d ?? undefined
125+
);
126+
}
127+
128+
return (
129+
conversionRates?.[tokenAddress as CaipAssetType]?.marketData
130+
?.pricePercentChange?.P1D ?? undefined
131+
);
132+
}

0 commit comments

Comments
 (0)