Skip to content

Commit b4fbb14

Browse files
feat: host-backed OHLCV pagination for older bars (#47753)
## **Description** Pagination PR (3/3, top of the stack) for the Token Details Page advanced charts work. Stacked on **#47751** (chart UI), which is stacked on **#47749** (foundation). Adds host-backed ("RN-backed") pagination of older OHLCV bars so the chart can load more history as the user scrolls back in time, without granting the sandboxed chart iframe any network access: - The initial bulk data (`SET_OHLCV_DATA`) now carries an `rnBackedPagination: { enabled: true }` flag, telling the engine to request older bars from the host rather than fetching them itself. - When the user scrolls to the edge of loaded data, the iframe posts a `FETCH_OLDER_BARS_REQUEST` (with `requestId`, `seriesGeneration`, symbol/resolution/window). The host (`advanced-chart-iframe.tsx`) fetches the next older page from the Price API by cursor and replies with `FETCH_OLDER_BARS_RESPONSE`; the engine echo-guards on `seriesGeneration`, dedupes, and prepends the bars. - `useOHLCVChart` gains cursor-aware paging (`fetchOHLCVPage` + a stable `fetchOlderBars`), surfaced through `useAdvancedChartData` and wired down via `advanced-chart-section`. - Paging terminates cleanly when the API reports no more data (one cheap terminal round-trip, no wasted fetch). All changes are confined to the 8 chart files already introduced in #47751. Still gated behind the `AdvancedCharts` remote feature flag. Base branch: `feat/advanced-charts-ui` (#47751). ## **Changelog** CHANGELOG entry: Added loading of older historical data when scrolling back on the token details page chart. <!-- ## **Related issues** Fixes: --> ## **Manual testing steps** 1. Enable the `AdvancedCharts` remote feature flag, then build and run the extension. 2. Unlock the wallet and open a token details page for an asset with a long price history. 3. With the candlestick chart shown, scroll/drag the chart back in time toward the oldest loaded candle. 4. Verify older candles load and prepend as you keep scrolling back (the chart extends further into the past). 5. Keep scrolling until history is exhausted and confirm it stops gracefully (no errors, no infinite spinner, no duplicated candles). 6. Switch interval/token and repeat to confirm paging restarts correctly for the new series. ## **Screenshots/Recordings** ### **Before** ### **After** ## **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] > **Medium Risk** > Touches OHLCV fetch/pagination and iframe messaging; mistakes could show wrong history or mishandle series switches, but changes stay behind Advanced Charts and include thorough tests. > > **Overview** > Adds **host-backed pagination** so users can scroll the token-details candlestick chart further into the past without letting the sandboxed chart iframe perform network requests (blocked by CSP). > > **Data layer:** `useOHLCVChart` now pages via `fetchOHLCVPage` (cursor + `hasNext` from the Price API) and exposes a stable `fetchOlderBars` that advances the cursor, short-circuits when history is exhausted, and drops stale pages if the asset/interval/currency series changes mid-flight. `useAdvancedChartData` passes this through to `AdvancedChartSection` and `AdvancedChartIframe`. > > **Iframe bridge:** Full `SET_OHLCV_DATA` payloads include `rnBackedPagination: { enabled: true }`. When the engine sends `FETCH_OLDER_BARS_REQUEST`, the host invokes `fetchOlderBars` and replies with `FETCH_OLDER_BARS_RESPONSE` (echoing `requestId` / `seriesGeneration`, or `noData` on error/missing callback). > > Tests cover the new postMessage contract, cursor paging, and wiring mocks across section/data hooks. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f79ea21. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: MetaMask Bot <metamaskbot@users.noreply.github.com>
1 parent 1a84fa0 commit b4fbb14

8 files changed

Lines changed: 525 additions & 49 deletions

‎ui/pages/asset/components/chart/advanced-chart-iframe.test.tsx‎

Lines changed: 164 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,10 @@ describe('AdvancedChartIframe', () => {
212212
expect(postMessageSpy).toHaveBeenCalledWith(
213213
JSON.stringify({
214214
type: 'SET_OHLCV_DATA',
215-
payload: { data: mockOHLCVData },
215+
payload: {
216+
data: mockOHLCVData,
217+
rnBackedPagination: { enabled: true },
218+
},
216219
}),
217220
CHART_ORIGIN,
218221
);
@@ -763,7 +766,10 @@ describe('AdvancedChartIframe', () => {
763766
expect(postMessageSpy).toHaveBeenCalledWith(
764767
JSON.stringify({
765768
type: 'SET_OHLCV_DATA',
766-
payload: { data: sameLengthOtherValues },
769+
payload: {
770+
data: sameLengthOtherValues,
771+
rnBackedPagination: { enabled: true },
772+
},
767773
}),
768774
CHART_ORIGIN,
769775
);
@@ -785,7 +791,10 @@ describe('AdvancedChartIframe', () => {
785791
expect(postMessageSpy).toHaveBeenCalledWith(
786792
JSON.stringify({
787793
type: 'SET_OHLCV_DATA',
788-
payload: { data: sameLengthOtherValues },
794+
payload: {
795+
data: sameLengthOtherValues,
796+
rnBackedPagination: { enabled: true },
797+
},
789798
}),
790799
CHART_ORIGIN,
791800
);
@@ -844,7 +853,10 @@ describe('AdvancedChartIframe', () => {
844853
expect(postMessageSpy).toHaveBeenCalledWith(
845854
JSON.stringify({
846855
type: 'SET_OHLCV_DATA',
847-
payload: { data: sameLengthOtherValues },
856+
payload: {
857+
data: sameLengthOtherValues,
858+
rnBackedPagination: { enabled: true },
859+
},
848860
}),
849861
CHART_ORIGIN,
850862
);
@@ -872,7 +884,10 @@ describe('AdvancedChartIframe', () => {
872884
expect(postMessageSpy).toHaveBeenCalledWith(
873885
JSON.stringify({
874886
type: 'SET_OHLCV_DATA',
875-
payload: { data: sameLengthOtherValues },
887+
payload: {
888+
data: sameLengthOtherValues,
889+
rnBackedPagination: { enabled: true },
890+
},
876891
}),
877892
CHART_ORIGIN,
878893
);
@@ -1010,7 +1025,10 @@ describe('AdvancedChartIframe', () => {
10101025
expect(postMessageSpy).toHaveBeenCalledWith(
10111026
JSON.stringify({
10121027
type: 'SET_OHLCV_DATA',
1013-
payload: { data: mockOHLCVData },
1028+
payload: {
1029+
data: mockOHLCVData,
1030+
rnBackedPagination: { enabled: true },
1031+
},
10141032
}),
10151033
CHART_ORIGIN,
10161034
);
@@ -1060,7 +1078,10 @@ describe('AdvancedChartIframe', () => {
10601078
expect(postMessageSpy).toHaveBeenCalledWith(
10611079
JSON.stringify({
10621080
type: 'SET_OHLCV_DATA',
1063-
payload: { data: newData },
1081+
payload: {
1082+
data: newData,
1083+
rnBackedPagination: { enabled: true },
1084+
},
10641085
}),
10651086
CHART_ORIGIN,
10661087
);
@@ -1215,7 +1236,10 @@ describe('AdvancedChartIframe', () => {
12151236
expect(postMessageSpy).toHaveBeenCalledWith(
12161237
JSON.stringify({
12171238
type: 'SET_OHLCV_DATA',
1218-
payload: { data: mockOHLCVData },
1239+
payload: {
1240+
data: mockOHLCVData,
1241+
rnBackedPagination: { enabled: true },
1242+
},
12191243
}),
12201244
CHART_ORIGIN,
12211245
);
@@ -1258,4 +1282,136 @@ describe('AdvancedChartIframe', () => {
12581282
expect(mockOnError).not.toHaveBeenCalled();
12591283
});
12601284
});
1285+
1286+
describe('Host-backed pagination', () => {
1287+
const loadAndReady = (props = {}) => {
1288+
const result = render(
1289+
<AdvancedChartIframe {...defaultProps} {...props} />,
1290+
);
1291+
act(() => {
1292+
result.container
1293+
.querySelector('iframe')
1294+
?.dispatchEvent(new Event('load'));
1295+
});
1296+
act(() => {
1297+
window.dispatchEvent(
1298+
new MessageEvent('message', {
1299+
origin: CHART_ORIGIN,
1300+
data: JSON.stringify({ type: 'CHART_READY' }),
1301+
}),
1302+
);
1303+
});
1304+
postMessageSpy.mockClear();
1305+
return result;
1306+
};
1307+
1308+
const requestOlderBars = (requestId: string, seriesGeneration: number) => {
1309+
act(() => {
1310+
window.dispatchEvent(
1311+
new MessageEvent('message', {
1312+
origin: CHART_ORIGIN,
1313+
data: JSON.stringify({
1314+
type: 'FETCH_OLDER_BARS_REQUEST',
1315+
payload: { requestId, seriesGeneration },
1316+
}),
1317+
}),
1318+
);
1319+
});
1320+
};
1321+
1322+
it('turns host-backed pagination on in the SET_OHLCV_DATA payload', async () => {
1323+
const { container } = render(<AdvancedChartIframe {...defaultProps} />);
1324+
act(() => {
1325+
container.querySelector('iframe')?.dispatchEvent(new Event('load'));
1326+
});
1327+
1328+
await waitFor(() => {
1329+
expect(postMessageSpy).toHaveBeenCalledWith(
1330+
JSON.stringify({
1331+
type: 'SET_OHLCV_DATA',
1332+
payload: {
1333+
data: mockOHLCVData,
1334+
rnBackedPagination: { enabled: true },
1335+
},
1336+
}),
1337+
CHART_ORIGIN,
1338+
);
1339+
});
1340+
});
1341+
1342+
it('answers a request with the fetched page, echoing requestId and seriesGeneration', async () => {
1343+
const olderBars = [
1344+
{ time: 1699900000, open: 1, high: 1, low: 1, close: 1, volume: 1 },
1345+
];
1346+
const fetchOlderBars = jest
1347+
.fn()
1348+
.mockResolvedValue({ bars: olderBars, noData: false });
1349+
1350+
loadAndReady({ fetchOlderBars });
1351+
requestOlderBars('obr-7', 4);
1352+
1353+
await waitFor(() => {
1354+
expect(fetchOlderBars).toHaveBeenCalledTimes(1);
1355+
});
1356+
await waitFor(() => {
1357+
expect(postMessageSpy).toHaveBeenCalledWith(
1358+
JSON.stringify({
1359+
type: 'FETCH_OLDER_BARS_RESPONSE',
1360+
payload: {
1361+
requestId: 'obr-7',
1362+
seriesGeneration: 4,
1363+
bars: olderBars,
1364+
noData: false,
1365+
},
1366+
}),
1367+
CHART_ORIGIN,
1368+
);
1369+
});
1370+
});
1371+
1372+
it('replies noData when the older-bars fetch rejects', async () => {
1373+
const fetchOlderBars = jest
1374+
.fn()
1375+
.mockRejectedValue(new Error('network down'));
1376+
1377+
loadAndReady({ fetchOlderBars });
1378+
requestOlderBars('obr-8', 5);
1379+
1380+
await waitFor(() => {
1381+
expect(postMessageSpy).toHaveBeenCalledWith(
1382+
JSON.stringify({
1383+
type: 'FETCH_OLDER_BARS_RESPONSE',
1384+
payload: {
1385+
requestId: 'obr-8',
1386+
seriesGeneration: 5,
1387+
bars: [],
1388+
noData: true,
1389+
error: 'network down',
1390+
},
1391+
}),
1392+
CHART_ORIGIN,
1393+
);
1394+
});
1395+
});
1396+
1397+
it('replies noData when no pagination callback is wired', async () => {
1398+
loadAndReady();
1399+
requestOlderBars('obr-9', 6);
1400+
1401+
await waitFor(() => {
1402+
expect(postMessageSpy).toHaveBeenCalledWith(
1403+
JSON.stringify({
1404+
type: 'FETCH_OLDER_BARS_RESPONSE',
1405+
payload: {
1406+
requestId: 'obr-9',
1407+
seriesGeneration: 6,
1408+
bars: [],
1409+
noData: true,
1410+
},
1411+
}),
1412+
CHART_ORIGIN,
1413+
);
1414+
});
1415+
});
1416+
});
12611417
});

‎ui/pages/asset/components/chart/advanced-chart-iframe.tsx‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { ENVIRONMENT } from '../../../../../shared/constants/build';
1212
import { useTheme } from '../../../../hooks/useTheme';
1313
import { isMovingAverage } from './advanced-chart-indicator-bar';
1414
import { CHART_TYPE_CANDLE } from './advanced-chart-interval-bar';
15-
import type { OHLCVBar } from './useOHLCVChart';
15+
import type { FetchOlderBarsResult, OHLCVBar } from './useOHLCVChart';
1616
import type { OHLCVRealtimeBar } from './useOHLCVRealtime';
1717

1818
/**
@@ -120,6 +120,13 @@ type AdvancedChartIframeProps = {
120120
onReady?: () => void;
121121
/** Real-time candle update from useOHLCVRealtime hook */
122122
realtimeBar?: OHLCVRealtimeBar;
123+
/**
124+
* Fetches an older page of candles when the engine scrolls past the oldest
125+
* loaded bar. Host-backed ("RN-backed") pagination: the engine asks us for
126+
* older bars rather than fetching them itself, keeping all network egress in
127+
* the extension where there is no iframe-CSP restriction. Omit to disable.
128+
*/
129+
fetchOlderBars?: () => Promise<FetchOlderBarsResult>;
123130
};
124131

125132
const AdvancedChartIframe = forwardRef<
@@ -137,6 +144,7 @@ const AdvancedChartIframe = forwardRef<
137144
onError,
138145
onReady,
139146
realtimeBar,
147+
fetchOlderBars,
140148
},
141149
ref,
142150
) => {
@@ -149,6 +157,10 @@ const AdvancedChartIframe = forwardRef<
149157
// The bars the engine was last given, so a newer arrival can be sent as a
150158
// cheap REALTIME_UPDATE instead of a full rebuild.
151159
const prevOhlcvDataRef = useRef<OHLCVBar[]>([]);
160+
// The message listener is attached once, but the pagination callback is a
161+
// prop that can change, so read it from a ref kept current each render.
162+
const fetchOlderBarsRef = useRef(fetchOlderBars);
163+
fetchOlderBarsRef.current = fetchOlderBars;
152164
const theme = useTheme();
153165
const isDark = theme === 'dark';
154166
const chartUrl = `${CHART_ORIGIN}/index.html?theme=${isDark ? 'dark' : 'light'}`;
@@ -204,13 +216,51 @@ const AdvancedChartIframe = forwardRef<
204216
url: toTradingViewUrl(msg?.payload?.url),
205217
});
206218
}
219+
// Host-backed pagination: the engine scrolled past its oldest loaded
220+
// bar and is asking us for an older page. Fetch it and reply with the
221+
// same requestId/seriesGeneration so the engine can match the
222+
// response and reject it if the series has since changed.
223+
if (msg?.type === 'FETCH_OLDER_BARS_REQUEST') {
224+
const { requestId, seriesGeneration } = msg.payload ?? {};
225+
const respond = (
226+
bars: OHLCVBar[],
227+
noData: boolean,
228+
error?: string,
229+
) => {
230+
postToChart({
231+
type: 'FETCH_OLDER_BARS_RESPONSE',
232+
payload: {
233+
requestId,
234+
seriesGeneration,
235+
bars,
236+
noData,
237+
...(error ? { error } : {}),
238+
},
239+
});
240+
};
241+
const fetchOlder = fetchOlderBarsRef.current;
242+
if (fetchOlder) {
243+
// eslint-disable-next-line no-void -- fire-and-forget reply
244+
void fetchOlder()
245+
.then(({ bars, noData }) => respond(bars, noData))
246+
.catch((e) =>
247+
respond(
248+
[],
249+
true,
250+
e instanceof Error ? e.message : 'pagination error',
251+
),
252+
);
253+
} else {
254+
respond([], true);
255+
}
256+
}
207257
} catch {
208258
// ignore non-JSON
209259
}
210260
};
211261
window.addEventListener('message', handleMessage);
212262
return () => window.removeEventListener('message', handleMessage);
213-
}, [onError, onReady]);
263+
}, [onError, onReady, postToChart]);
214264

215265
// Fall back to legacy chart if chartReady isn't set within LOAD_TIMEOUT_MS.
216266
useEffect(() => {
@@ -379,7 +429,14 @@ const AdvancedChartIframe = forwardRef<
379429
// First load, a different series, or a bulk change (interval change,
380430
// pagination) → full SET_OHLCV_DATA.
381431
if (!sameSeries || Math.abs(ohlcvData.length - prevData.length) > 1) {
382-
postToChart({ type: 'SET_OHLCV_DATA', payload: { data: ohlcvData } });
432+
postToChart({
433+
type: 'SET_OHLCV_DATA',
434+
// Strategy B (host-backed): the engine asks us for older bars via
435+
// FETCH_OLDER_BARS_REQUEST instead of fetching them itself. Must NOT
436+
// set `pagination` — that would switch on the in-iframe fetch path,
437+
// which the chart origin's strict CSP (connect-src 'none') blocks.
438+
payload: { data: ohlcvData, rnBackedPagination: { enabled: true } },
439+
});
383440
prevOhlcvDataRef.current = ohlcvData;
384441
return;
385442
}

‎ui/pages/asset/components/chart/advanced-chart-section.test.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ function setupData(
132132
isLoading: false,
133133
error: null,
134134
resolvedCurrency: 'eur',
135+
fetchOlderBars: jest.fn().mockResolvedValue({ bars: [], noData: true }),
135136
...overrides,
136137
});
137138
}
@@ -473,6 +474,11 @@ describe('AdvancedChartSection', () => {
473474
});
474475

475476
it('keeps the indicator bar visible after switching token', () => {
477+
// The iframe is not reloaded on a token change (its src is theme-only),
478+
// so the engine never re-emits CHART_READY. Readiness is a one-way latch,
479+
// mirroring mobile's `hasChartBeenRevealed`: once revealed, the bar stays
480+
// up across token/interval changes. Resetting it would hide the bar with
481+
// nothing to turn it back on.
476482
const { rerender } = render();
477483
act(() => {
478484
screen.getByTestId('simulate-ready').click();

‎ui/pages/asset/components/chart/advanced-chart-section.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ export const AdvancedChartSection = ({
156156
isLoading: isOhlcvLoading,
157157
error: ohlcvError,
158158
resolvedCurrency,
159+
fetchOlderBars,
159160
} = useAdvancedChartData({
160161
assetId: caipAssetId,
161162
interval,
@@ -229,6 +230,7 @@ export const AdvancedChartSection = ({
229230
onError={setChartError}
230231
onReady={handleChartReady}
231232
realtimeBar={realtimeBar}
233+
fetchOlderBars={fetchOlderBars}
232234
/>
233235
);
234236
} else {

‎ui/pages/asset/components/chart/useAdvancedChartData.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ function setup(
3131
isLoading: false,
3232
error: null,
3333
resolvedCurrency: 'eur',
34+
fetchOlderBars: jest.fn().mockResolvedValue({ bars: [], noData: true }),
3435
...overrides.chart,
3536
});
3637
mockUseOHLCVRealtime.mockReturnValue({

0 commit comments

Comments
 (0)