Skip to content

Commit f0ab05f

Browse files
fix(discover-search): remove client sorting (#47699)
## **Description** Discover Search's crypto results should display in the order their data source provides. A Slack-reported issue (parent ticket ASSETS-4296) surfaced risky-flagged tokens at the top of Explore/Search because the extension re-sorted results client-side. Per the ASSETS-4296 decision ("We do not need this client side filtering. It's causing us more headaches than good."), the crypto search client-side ordering is removed so the search API owns the order. Scope (per the ASSETS-4298/ASSETS-4296 update recorded on the tickets): - **Crypto search — changed:** removed the first-page merge/re-sort in `ui/hooks/discover-search/useDiscoverCryptoSearch.ts`. Search results now pass through in the API's relevance order — no merging of locally cached trending matches into page 1 and no `byMarketCap` re-sort. Cursor pages over live market data can repeat an asset, so exact `assetId` repeats across pages are dropped (first occurrence wins) to keep the consumer's assetId-keyed list rows unique; ordering is otherwise untouched. The RWA membership filter is unchanged (stocks are served by their own section). - **Perps — intentionally unchanged:** the perps market stream comes from the perps team with no server ordering, so the client-side 24h % change sort in the Discover Search perps feed is load-bearing and stays as-is. `byMarketCap` remains in `shared/lib/token-search/token-search-api.ts` (still used by cashtag resolution); only the Discover Search usage is removed. Other surfaces intentionally untouched: - The volume-descending base ordering in `ui/hooks/perps/stream/usePerpsLiveMarketData.ts` (shared by other perps surfaces — Perps Market List default sort, Top Movers input). - Perps Top Movers and the Perps Market List page (user-driven sorting is the feature there). - The stocks feed (already server-ordered via `sortBy=price_change_desc`). - Perps active-query Fuse.js relevance ordering. ## **Changelog** CHANGELOG entry: Updated Discover Search crypto results to show the order provided by the search API ## **Related issues** Fixes: [ASSETS-4298](https://consensyssoftware.atlassian.net/browse/ASSETS-4298) Sibling (mobile, parallel): [ASSETS-4297](https://consensyssoftware.atlassian.net/browse/ASSETS-4297) Parent: [ASSETS-4296](https://consensyssoftware.atlassian.net/browse/ASSETS-4296) ## **Manual testing steps** 1. Run the extension (`yarn start`), unlock a wallet. 2. Open Discover Search from the home search bar (Explore). 3. Type a query (e.g. "eth") and check the Crypto results: the list should follow the API's relevance order (no market-cap reshuffle, no locally cached trending matches merged in ahead of the API's own results). 4. Use "View X more" / "View all" on the crypto results: later pages should append in server order, with no repeated rows. 5. Check the Perps section (empty query and with a query): ordering behavior is unchanged — the empty-query feed still sorts by 24h price change (intentionally kept; the perps stream has no server ordering). ## **Screenshots/Recordings** ### **Before** N/A — previous behavior was the client-side trending merge into the first search page, followed by a market-cap re-sort (described above). ### **After (head `90a00458ec9`, captured 2026-11-09)** | What it shows | Screenshot | | --- | --- | | Empty Discover Search query — Crypto/Perps/Stocks sections render normally | ![Empty Discover Search query — Crypto/Perps/Stocks sections render normally](https://github.com/user-attachments/assets/17a4500b-92d1-4b86-9dc4-c89d428aa1dc) | | Crypto "pepe" query — 20 rows in API relevance order (PEPE mainnet first, then variants across chains) | ![Crypto "pepe" query — 20 rows in API relevance order (PEPE mainnet first, then variants across chains)](https://github.com/user-attachments/assets/539fc7aa-e9ed-4275-945b-ae4ead5f34e7) | | Perps tab — intentionally unchanged client-side 24h % change sort | ![Perps tab — intentionally unchanged client-side 24h % change sort](https://github.com/user-attachments/assets/04e6e58e-54b6-49aa-8092-d690ec02c169) | <!-- ## **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. --> ## **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/main/.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 - [ ] 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. ## **Adversarial review (adverse) — superseded head** Final verdict (round 2/3): SHIP (unanimous, 3/3 ship) Findings: 0 critical · 1 warning · 7 info. Fixed (from round 1): cross-page duplicate `assetId`s reaching an assetId-keyed list (order-preserving repeat drop added, server relevance order otherwise untouched); misleading "the server dedupes" comment (now describes what the client does); perps empty-query order dependency on the upstream volume sort unpinned by tests (combined `markets` volume-descending assertion added to `usePerpsLiveMarketData` test). Declined: "byMarketCap may now be an export with no production callers": false positive — cashtag resolution (`app/scripts/cashtag/lib/data.ts` `resolveTicker`, wired via the `scripts/n` background entry) still calls it in production. Reviewer: `pi -p --model litellm/claude-opus-5-5` via adverse 0.2.1 (3 personas, 2 rounds) — designated backup reviewer during the `claude -p` spend-limit outage. Note: this round reviewed the earlier head (`0fe7f3d765b`), which also removed the perps 24h % change sort; that removal was reverted by the ASSETS-4298 scope update (perps stream has no server ordering — the client sort is load-bearing). The crypto search change reviewed here is unchanged. See the section below for the re-review of the final head. ## **Adversarial review (adverse) — final head (`7c9dc5e08f6`)** Final verdict (round 3/3): SHIP (unanimous, 3/3 ship) Findings: 0 critical · 0 warnings · 7 info. Fixed: none required. Info items, no action: result order depending on the search API's relevance ranking is the ticket's intent; `totalCount` vs visible rows difference is pre-existing server semantics (server total includes RWA items served by the stocks section); the trending query running during active search is an intentional cache warm for the empty-query state (pre-existing fetch behavior); "byMarketCap may have no callers" is a false positive (cashtag resolution still calls it in production); trending mocks in the search tests intentionally prove that no trending merge happens (regression guard for this change). Reviewer: `pi -p --model litellm/claude-opus-5-5` via adverse 0.2.1 (3 personas, 2 rounds) — designated backup reviewer during the `claude -p` spend-limit outage. [ASSETS-4298]: https://consensyssoftware.atlassian.net/browse/ASSETS-4298?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
1 parent 69cd4a7 commit f0ab05f

2 files changed

Lines changed: 8 additions & 56 deletions

File tree

‎ui/hooks/discover-search/useDiscoverCryptoSearch.test.tsx‎

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ describe('useDiscoverCryptoSearch', () => {
136136
expect(result.current.totalCount).toBe(2);
137137
});
138138

139-
it('merges, deduplicates, and sorts local trending matches into the first search page', async () => {
139+
it('returns search pages in API relevance order without merging local trending matches', async () => {
140140
mockGetTrendingTokens.mockResolvedValue([
141141
{
142142
assetId: 'eip155:1/slip44:60',
@@ -152,14 +152,6 @@ describe('useDiscoverCryptoSearch', () => {
152152
decimals: 18,
153153
marketCap: 500,
154154
},
155-
{
156-
assetId: 'eip155:1/erc20:0xstock',
157-
name: 'Ether Stock',
158-
symbol: 'ESTK',
159-
decimals: 18,
160-
marketCap: 1_000,
161-
rwaData: { type: 'stock' },
162-
},
163155
] as never);
164156
mockSearchTokens
165157
.mockResolvedValueOnce({
@@ -236,19 +228,18 @@ describe('useDiscoverCryptoSearch', () => {
236228
}),
237229
);
238230
expect(result.current.data.map(({ symbol }) => symbol)).toStrictEqual([
239-
'GEM',
240231
'ETH',
241232
'WETH',
242233
'DOGE',
243234
'BTC',
244235
]);
245236
expect(result.current.data).not.toEqual(
246-
expect.arrayContaining([expect.objectContaining({ symbol: 'ESTK' })]),
237+
expect.arrayContaining([expect.objectContaining({ symbol: 'GEM' })]),
247238
);
248239
expect(result.current.totalCount).toBe(5);
249240
});
250241

251-
it('does not show local trending matches when the API search has no results', async () => {
242+
it('returns an empty result list when the API search has no results', async () => {
252243
mockGetTrendingTokens.mockResolvedValue([
253244
{
254245
assetId: 'eip155:1/slip44:60',
@@ -277,7 +268,7 @@ describe('useDiscoverCryptoSearch', () => {
277268
expect(result.current.data).toStrictEqual([]);
278269
});
279270

280-
it('merges local trending matches when the API only returns RWA assets', async () => {
271+
it('excludes RWA results from the crypto feed without merging local trending matches', async () => {
281272
mockGetTrendingTokens.mockResolvedValue([
282273
{
283274
assetId: 'eip155:1/slip44:60',
@@ -311,8 +302,6 @@ describe('useDiscoverCryptoSearch', () => {
311302
expect(result.current.isLoading).toBe(false);
312303
});
313304

314-
expect(result.current.data.map(({ symbol }) => symbol)).toStrictEqual([
315-
'ETH',
316-
]);
305+
expect(result.current.data).toStrictEqual([]);
317306
});
318307
});

‎ui/hooks/discover-search/useDiscoverCryptoSearch.ts‎

Lines changed: 3 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@ import {
55
type TrendingAsset,
66
} from '@metamask/assets-controllers';
77
import type { CaipChainId } from '@metamask/utils';
8-
import {
9-
byMarketCap,
10-
TOKEN_SEARCH_SERVICE_PROFILE,
11-
} from '#shared/lib/token-search/token-search-api';
8+
import { TOKEN_SEARCH_SERVICE_PROFILE } from '#shared/lib/token-search/token-search-api';
129
import { MultichainNetworks } from '../../../shared/constants/multichain/networks';
1310
import { getIsStellarSupportEnabled } from '../../selectors/multichain/feature-flags';
1411
import {
@@ -38,7 +35,6 @@ export type UseDiscoverCryptoSearchResult = {
3835
type CryptoSearchPage = {
3936
data: TrendingAsset[];
4037
totalCount?: number;
41-
hasSearchResults: boolean;
4238
pageInfo?: {
4339
endCursor: string | null;
4440
hasNextPage: boolean;
@@ -63,27 +59,6 @@ const mapSearchResultToTrendingAsset = (
6359
securityData: item.securityData,
6460
});
6561

66-
const matchesSearchQuery = (asset: TrendingAsset, query: string): boolean => {
67-
const normalizedQuery = query.toLowerCase();
68-
69-
return (
70-
asset.symbol?.toLowerCase().includes(normalizedQuery) ||
71-
asset.name?.toLowerCase().includes(normalizedQuery)
72-
);
73-
};
74-
75-
const dedupeByAssetId = (assets: TrendingAsset[]): TrendingAsset[] => {
76-
const assetsById = new Map<string, TrendingAsset>();
77-
78-
assets.forEach((asset) => {
79-
if (!assetsById.has(asset.assetId)) {
80-
assetsById.set(asset.assetId, asset);
81-
}
82-
});
83-
84-
return Array.from(assetsById.values());
85-
};
86-
8762
/**
8863
* Crypto Discover feed: trending when query is empty, market-data search otherwise.
8964
* @param options0
@@ -147,7 +122,6 @@ export const useDiscoverCryptoSearch = ({
147122
return {
148123
data,
149124
totalCount: response.totalCount ?? data.length,
150-
hasSearchResults: searchResults.length > 0,
151125
pageInfo: response.pageInfo,
152126
};
153127
},
@@ -165,18 +139,8 @@ export const useDiscoverCryptoSearch = ({
165139

166140
if (isSearch) {
167141
const pages = searchQuery.data?.pages ?? [];
168-
const [firstPage, ...remainingPages] = pages;
169-
const firstPageData = firstPage?.data ?? [];
170-
const trendingMatches = (trendingQuery.data ?? []).filter(
171-
(asset) => !asset.rwaData && matchesSearchQuery(asset, trimmedQuery),
172-
);
173-
const sortedFirstPage = firstPage?.hasSearchResults
174-
? dedupeByAssetId([...trendingMatches, ...firstPageData]).toSorted(
175-
byMarketCap,
176-
)
177-
: [];
178-
const seenAssetIds = new Set(sortedFirstPage.map((asset) => asset.assetId));
179-
const appendedData = remainingPages
142+
const seenAssetIds = new Set<string>();
143+
const data = pages
180144
.flatMap((page) => page.data)
181145
.filter((asset) => {
182146
if (seenAssetIds.has(asset.assetId)) {
@@ -186,7 +150,6 @@ export const useDiscoverCryptoSearch = ({
186150
seenAssetIds.add(asset.assetId);
187151
return true;
188152
});
189-
const data = [...sortedFirstPage, ...appendedData];
190153
const lastPage = pages.at(-1);
191154

192155
return {

0 commit comments

Comments
 (0)