Skip to content

Commit 03a88bc

Browse files
authored
fix(predict): Guards against undefined tags being returned from search endpoint (#24266)
<!-- 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 fixes an issue where certain search queries in Predict would return no results despite the API returning valid data. **Reason for change:** When users searched for terms like "nhl", the app would display no results even though the search API returned valid events. Some events had their tags field set to undefined instead of an empty array, causing array method calls to throw. These errors were caught and silently returned an empty array, resulting in "no results" displayed to users. **Solution:** Added defensive checks to safely handle undefined or non-array tags. This ensures malformed events don't crash parsing and valid markets are still displayed. Applied the same pattern to the markets field. <!-- 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? --> ## **Changelog** <!-- If this PR is not End-User-Facing and should not show up in the CHANGELOG, you can choose to either: 1. Write `CHANGELOG entry: null` 2. Label with `no-changelog` If this PR is End-User-Facing, please write a short User-Facing description in the past tense like: `CHANGELOG entry: Added a new tab for users to see their NFTs` `CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker` (This helps the Release Engineer do their job more quickly and accurately) --> CHANGELOG entry: Fixes issue where certain search queries in Predict would return no results ## **Related issues** Fixes: [PRED-414](https://consensyssoftware.atlassian.net/browse/PRED-414) ## **Manual testing steps** ```gherkin Feature: my feature name Scenario: user [verb for user action] Given [describe expected initial app state] When user [verb for user action] Then [describe expected outcome] ``` ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <img width="1320" height="2868" alt="image" src="https://github.com/user-attachments/assets/71fd088c-2c30-45a7-b8bb-a8cc6f728002" /> ### **After** <img width="1320" height="2868" alt="image" src="https://github.com/user-attachments/assets/33fbf6e6-7c3b-4cb4-8dd4-0702160ac331" /> ## **Pre-merge author checklist** - [x] I’ve followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile Coding Standards](https://github.com/MetaMask/metamask-mobile/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 - [x] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-mobile/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] > Improves resilience of Polymarket market parsing and search results handling. > > - Guard `isSportEvent` against non-array `tags`; treat missing tags as empty > - In `sortMarkets`, treat non-array `markets` as empty and respect `event.sortBy` > - In `parsePolymarketEvents`, default missing `tags` to `[]`, ignore inactive markets defensively, and continue parsing > - In `getParsedMarketsFromPolymarketApi`, normalize response (`events`/`data`) to arrays and, for search (`q`), return only events with outcomes; remove extraneous logging > - Tests: add cases for missing `markets` (returns `[]`) and missing `tags` (yields empty tags) > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 0cbcfd6. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> [PRED-414]: https://consensyssoftware.atlassian.net/browse/PRED-414?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
1 parent 2af3c67 commit 03a88bc

2 files changed

Lines changed: 94 additions & 32 deletions

File tree

app/components/UI/Predict/providers/polymarket/utils.test.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2296,6 +2296,61 @@ describe('polymarket utils', () => {
22962296
);
22972297
});
22982298

2299+
it('returns empty array when search results omit markets', async () => {
2300+
const eventWithoutMarkets = {
2301+
...mockEvent,
2302+
markets: undefined,
2303+
} as unknown as PolymarketApiEvent;
2304+
2305+
const mockResponse = {
2306+
events: [eventWithoutMarkets],
2307+
};
2308+
2309+
mockFetch.mockResolvedValue({
2310+
ok: true,
2311+
json: jest.fn().mockResolvedValue(mockResponse),
2312+
});
2313+
2314+
const params: GetMarketsParams = {
2315+
providerId: 'polymarket',
2316+
q: 'nhl',
2317+
limit: 10,
2318+
offset: 0,
2319+
};
2320+
2321+
const result = await getParsedMarketsFromPolymarketApi(params);
2322+
2323+
expect(result).toEqual([]);
2324+
});
2325+
2326+
it('returns empty tags when search results omit tags', async () => {
2327+
const eventWithoutTags = {
2328+
...mockEvent,
2329+
tags: undefined,
2330+
} as unknown as PolymarketApiEvent;
2331+
2332+
const mockResponse = {
2333+
events: [eventWithoutTags],
2334+
};
2335+
2336+
mockFetch.mockResolvedValue({
2337+
ok: true,
2338+
json: jest.fn().mockResolvedValue(mockResponse),
2339+
});
2340+
2341+
const params: GetMarketsParams = {
2342+
providerId: 'polymarket',
2343+
q: 'nhl',
2344+
limit: 10,
2345+
offset: 0,
2346+
};
2347+
2348+
const result = await getParsedMarketsFromPolymarketApi(params);
2349+
2350+
expect(result).toHaveLength(1);
2351+
expect(result[0].tags).toEqual([]);
2352+
});
2353+
22992354
it('handle different categories', async () => {
23002355
const mockResponse = {
23012356
data: [mockEvent],

app/components/UI/Predict/providers/polymarket/utils.ts

Lines changed: 39 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,9 @@ export const submitClobOrder = async ({
386386
};
387387

388388
export const isSportEvent = (event: PolymarketApiEvent): boolean =>
389-
event.tags.some((tag) => tag.slug === 'sports');
389+
(Array.isArray(event.tags) ? event.tags : []).some(
390+
(tag) => tag.slug === 'sports',
391+
);
390392

391393
export const isSpreadMarket = (market: PolymarketApiMarket): boolean =>
392394
market.sportsMarketType?.toLowerCase().includes('spread') ?? false;
@@ -562,7 +564,8 @@ export const sortMarkets = (
562564
event: PolymarketApiEvent,
563565
sortBy?: 'price' | 'ascending' | 'descending',
564566
): PolymarketApiMarket[] => {
565-
const { markets, sortBy: eventSortBy } = event;
567+
const markets = Array.isArray(event.markets) ? event.markets : [];
568+
const eventSortBy = event.sortBy;
566569

567570
if (sortBy) {
568571
return sortMarketsByField(markets, sortBy);
@@ -605,28 +608,32 @@ export const parsePolymarketEvents = (
605608
sortMarketsBy?: 'price' | 'ascending' | 'descending',
606609
): PredictMarket[] => {
607610
const parsedMarkets: PredictMarket[] = events.map(
608-
(event: PolymarketApiEvent) => ({
609-
id: event.id,
610-
slug: event.slug,
611-
providerId: 'polymarket',
612-
title: event.title,
613-
description: event.description,
614-
image: event.icon,
615-
status: event.closed
616-
? PredictMarketStatus.CLOSED
617-
: PredictMarketStatus.OPEN,
618-
recurrence: getRecurrence(event.series),
619-
endDate: event.endDate,
620-
category,
621-
tags: event.tags.map((t) => t.label),
622-
outcomes: sortMarkets(event, sortMarketsBy)
623-
.filter((market: PolymarketApiMarket) => market.active !== false)
624-
.map((market: PolymarketApiMarket) =>
625-
parsePolymarketMarket(market, event),
626-
),
627-
liquidity: event.liquidity,
628-
volume: event.volume,
629-
}),
611+
(event: PolymarketApiEvent) => {
612+
const tags = Array.isArray(event.tags) ? event.tags : [];
613+
614+
return {
615+
id: event.id,
616+
slug: event.slug,
617+
providerId: 'polymarket',
618+
title: event.title,
619+
description: event.description,
620+
image: event.icon,
621+
status: event.closed
622+
? PredictMarketStatus.CLOSED
623+
: PredictMarketStatus.OPEN,
624+
recurrence: getRecurrence(event.series),
625+
endDate: event.endDate,
626+
category,
627+
tags: tags.map((t) => t.label),
628+
outcomes: sortMarkets(event, sortMarketsBy)
629+
.filter((market: PolymarketApiMarket) => market?.active !== false)
630+
.map((market: PolymarketApiMarket) =>
631+
parsePolymarketMarket(market, event),
632+
),
633+
liquidity: event.liquidity,
634+
volume: event.volume,
635+
};
636+
},
630637
);
631638
return parsedMarkets;
632639
};
@@ -759,21 +766,21 @@ export const getParsedMarketsFromPolymarketApi = async (
759766
}
760767
const data = await response.json();
761768

762-
DevLogger.log('Polymarket response data:', data);
763-
764-
// Handle different response structures
765-
const events = q ? data?.events : data?.data;
766-
767-
if (!events || !Array.isArray(events)) {
768-
return [];
769-
}
769+
const eventsData = q ? data?.events : data?.data;
770+
const events: PolymarketApiEvent[] = Array.isArray(eventsData)
771+
? eventsData
772+
: [];
770773

771774
const parsedMarkets: PredictMarket[] = parsePolymarketEvents(
772775
events,
773776
category,
774777
'price',
775778
);
776779

780+
if (q) {
781+
return parsedMarkets.filter((m) => m.outcomes.length > 0);
782+
}
783+
777784
return parsedMarkets;
778785
};
779786

0 commit comments

Comments
 (0)