From 65964ede6bb8203619e080af25d8867a76c051d3 Mon Sep 17 00:00:00 2001 From: Javier Garcia Vera Date: Thu, 5 Nov 2026 12:40:42 +0100 Subject: [PATCH 1/2] fix(perps): force controller REST refresh when Activity refetches Activity's forced refresh only cleared the UI coalesce cache. The controller still served its 60s REST cache for perpsGetOrderFills, perpsGetOrders and perpsGetFunding, so a just-closed trade could be missing unless the live userFills stream delivered it. Pass forceRefresh on explicit refetches only, and drop the second userFills push from the close-fill E2E flow. Co-authored-by: Cursor --- .../flows/perps-activity-close-fill.flow.ts | 7 +- .../perps/usePerpsTransactionHistory.test.ts | 39 +++- ui/hooks/perps/usePerpsTransactionHistory.ts | 171 ++++++++++-------- 3 files changed, 132 insertions(+), 85 deletions(-) diff --git a/test/e2e/page-objects/flows/perps-activity-close-fill.flow.ts b/test/e2e/page-objects/flows/perps-activity-close-fill.flow.ts index 23c5a73dac58..eb52b1d8f5ed 100644 --- a/test/e2e/page-objects/flows/perps-activity-close-fill.flow.ts +++ b/test/e2e/page-objects/flows/perps-activity-close-fill.flow.ts @@ -8,6 +8,9 @@ import { PerpsMarketListPage } from '../pages/perps/perps-market-list-page'; * After a simulated position change in E2E, pushes a `userFills` snapshot via * `pushUserFills`, then opens Perps Activity and asserts a trade row appears * with the expected title fragment (same navigation pattern as other lifecycle tests). + * `pushUserFills` must also make the mocked `userFills` REST read return the fill: + * opening Activity force-refreshes history, so that read is what the page renders + * regardless of whether the live stream delivered the push. * * @param options * @param options.driver @@ -39,10 +42,6 @@ export async function assertPerpsActivityShowsCloseFill({ const perpsTab = new PerpsTab(driver); await perpsTab.navigateToPerpsHome(); await perpsTab.waitForPerpsViewStable(); - // Activity only shows a just-closed trade via the live fill (REST history is - // cached for 60s), and the wallet can drop a fill that arrives while leaving - // market detail. Push it again so the trade reliably reaches Activity. - pushUserFills(); await perpsTab.waitForRecentActivitySection(); await perpsTab.clickRecentActivitySeeAll(); diff --git a/ui/hooks/perps/usePerpsTransactionHistory.test.ts b/ui/hooks/perps/usePerpsTransactionHistory.test.ts index 5459089eb10f..b7af81876e34 100644 --- a/ui/hooks/perps/usePerpsTransactionHistory.test.ts +++ b/ui/hooks/perps/usePerpsTransactionHistory.test.ts @@ -1,4 +1,4 @@ -import { renderHook, act } from '@testing-library/react'; +import { renderHook, act, waitFor } from '@testing-library/react'; import type { Order, OrderFill, Funding } from '@metamask/perps-controller'; import { usePerpsTransactionHistory } from './usePerpsTransactionHistory'; import { resetCoalesceCacheForTests } from './coalesceBackgroundRequest'; @@ -202,20 +202,51 @@ describe('usePerpsTransactionHistory', () => { expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( 'perpsGetOrderFills', - [{ accountId: 'eip155:1:0xabc', aggregateByTime: false }], + [ + { accountId: 'eip155:1:0xabc', aggregateByTime: false }, + { forceRefresh: true }, + ], ); expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( 'perpsGetOrders', - [{ accountId: 'eip155:1:0xabc' }], + [{ accountId: 'eip155:1:0xabc' }, { forceRefresh: true }], ); expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( 'perpsGetFunding', - [{ accountId: 'eip155:1:0xabc', startTime: 1000, endTime: 2000 }], + [ + { accountId: 'eip155:1:0xabc', startTime: 1000, endTime: 2000 }, + { forceRefresh: true }, + ], ); }); + it('asks the controller to bypass its REST cache when forceFreshOnMount is set', async () => { + renderHook(() => usePerpsTransactionHistory({ forceFreshOnMount: true })); + + await waitFor(() => { + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrderFills', + [ + { accountId: undefined, aggregateByTime: false }, + { forceRefresh: true }, + ], + ); + }); + }); + + it('keeps the controller REST cache for passive fetches', async () => { + renderHook(() => usePerpsTransactionHistory()); + + await waitFor(() => { + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrderFills', + [{ accountId: undefined, aggregateByTime: false }], + ); + }); + }); + it('enriches fills with detailedOrderType from orders', async () => { const fillWithOrderId: OrderFill[] = [ { diff --git a/ui/hooks/perps/usePerpsTransactionHistory.ts b/ui/hooks/perps/usePerpsTransactionHistory.ts index d1b7b3d7582b..f559454d9f46 100644 --- a/ui/hooks/perps/usePerpsTransactionHistory.ts +++ b/ui/hooks/perps/usePerpsTransactionHistory.ts @@ -177,85 +177,102 @@ export function usePerpsTransactionHistory({ userHistoryRef.current = userHistory; }, [userHistory]); - const fetchAllTransactions = useCallback(async () => { - fetchGenerationRef.current += 1; - const generation = fetchGenerationRef.current; - try { - const [fillsResult, ordersResult, funding] = await Promise.all([ - coalesceBackgroundRequest(coalesceKeys.fills, () => - submitRequestToBackground('perpsGetOrderFills', [ - { accountId, aggregateByTime: false }, - ]), - ), - coalesceBackgroundRequest(coalesceKeys.orders, () => - submitRequestToBackground('perpsGetOrders', [{ accountId }]), - ), - coalesceBackgroundRequest(coalesceKeys.funding, () => - submitRequestToBackground('perpsGetFunding', [ - { accountId, startTime, endTime }, - ]), - ), - ]); - - if (fetchGenerationRef.current !== generation) { - return; - } - - const fills: OrderFill[] = Array.isArray(fillsResult) ? fillsResult : []; - const orders: Order[] = Array.isArray(ordersResult) ? ordersResult : []; - const orderMap = new Map(orders.map((order) => [order.orderId, order])); - - // Attaching detailedOrderType allows us to display the TP/SL pill in the trades history list. - const enrichedFills = fills.map((fill) => ({ - ...fill, - detailedOrderType: orderMap.get(fill.orderId)?.detailedOrderType, - })); - - // Transform each data type to PerpsTransaction format - const fillTransactions = transformFillsToTransactions(enrichedFills); - const orderTransactions = transformOrdersToTransactions(orders); - const fundingTransactions = transformFundingToTransactions(funding); - const userHistoryTransactions = transformUserHistoryToTransactions( - userHistoryRef.current, - ); - - // Combine all transactions (no Arbitrum withdrawals - using user history as single source of truth) - const allTransactions = [ - ...fillTransactions, - ...orderTransactions, - ...fundingTransactions, - ...userHistoryTransactions, - ]; - - // Sort by timestamp descending (newest first) - allTransactions.sort((a, b) => b.timestamp - a.timestamp); - - // Remove duplicates based on ID - const uniqueTransactions = allTransactions.reduce((acc, transaction) => { - const existingIndex = acc.findIndex((t) => t.id === transaction.id); - if (existingIndex === -1) { - acc.push(transaction); + const fetchAllTransactions = useCallback( + async (forceRefresh = false) => { + fetchGenerationRef.current += 1; + const generation = fetchGenerationRef.current; + // The controller coalesces these REST reads for 60s on its own, so an + // explicit refresh must opt out of that cache too. Otherwise a read made + // before a fill (e.g. by the perps home preview) hides it from Activity. + const controllerOptions = forceRefresh ? [{ forceRefresh: true }] : []; + try { + const [fillsResult, ordersResult, funding] = await Promise.all([ + coalesceBackgroundRequest(coalesceKeys.fills, () => + submitRequestToBackground('perpsGetOrderFills', [ + { accountId, aggregateByTime: false }, + ...controllerOptions, + ]), + ), + coalesceBackgroundRequest(coalesceKeys.orders, () => + submitRequestToBackground('perpsGetOrders', [ + { accountId }, + ...controllerOptions, + ]), + ), + coalesceBackgroundRequest(coalesceKeys.funding, () => + submitRequestToBackground('perpsGetFunding', [ + { accountId, startTime, endTime }, + ...controllerOptions, + ]), + ), + ]); + + if (fetchGenerationRef.current !== generation) { + return; } - return acc; - }, [] as PerpsTransaction[]); - setTransactions(uniqueTransactions); - } catch (err) { - if (fetchGenerationRef.current !== generation) { - return; - } - const errorMessage = - err instanceof Error - ? err.message - : 'Failed to fetch transaction history'; - setError(errorMessage); - setTransactions([]); - } finally { - if (fetchGenerationRef.current === generation) { - setIsLoading(false); + const fills: OrderFill[] = Array.isArray(fillsResult) + ? fillsResult + : []; + const orders: Order[] = Array.isArray(ordersResult) ? ordersResult : []; + const orderMap = new Map(orders.map((order) => [order.orderId, order])); + + // Attaching detailedOrderType allows us to display the TP/SL pill in the trades history list. + const enrichedFills = fills.map((fill) => ({ + ...fill, + detailedOrderType: orderMap.get(fill.orderId)?.detailedOrderType, + })); + + // Transform each data type to PerpsTransaction format + const fillTransactions = transformFillsToTransactions(enrichedFills); + const orderTransactions = transformOrdersToTransactions(orders); + const fundingTransactions = transformFundingToTransactions(funding); + const userHistoryTransactions = transformUserHistoryToTransactions( + userHistoryRef.current, + ); + + // Combine all transactions (no Arbitrum withdrawals - using user history as single source of truth) + const allTransactions = [ + ...fillTransactions, + ...orderTransactions, + ...fundingTransactions, + ...userHistoryTransactions, + ]; + + // Sort by timestamp descending (newest first) + allTransactions.sort((a, b) => b.timestamp - a.timestamp); + + // Remove duplicates based on ID + const uniqueTransactions = allTransactions.reduce( + (acc, transaction) => { + const existingIndex = acc.findIndex((t) => t.id === transaction.id); + if (existingIndex === -1) { + acc.push(transaction); + } + return acc; + }, + [] as PerpsTransaction[], + ); + + setTransactions(uniqueTransactions); + } catch (err) { + if (fetchGenerationRef.current !== generation) { + return; + } + const errorMessage = + err instanceof Error + ? err.message + : 'Failed to fetch transaction history'; + setError(errorMessage); + setTransactions([]); + } finally { + if (fetchGenerationRef.current === generation) { + setIsLoading(false); + } } - } - }, [startTime, endTime, accountId, coalesceKeys]); + }, + [startTime, endTime, accountId, coalesceKeys], + ); const initialFetch = useCallback(async () => { // Cache-respecting path — lets rapid re-mounts within the 10s TTL hit the @@ -276,7 +293,7 @@ export function usePerpsTransactionHistory({ invalidateCoalescedRequest(coalesceKeys.funding); const freshUserHistory = await refetchUserHistory(); userHistoryRef.current = freshUserHistory; - await fetchAllTransactions(); + await fetchAllTransactions(true); }, [fetchAllTransactions, refetchUserHistory, coalesceKeys]); const scopeFingerprint = `${perpsScopeKey}:${accountId ?? ''}:${startTime ?? ''}:${endTime ?? ''}:${forceFreshOnMount ? '1' : '0'}`; From b2641ab89aea991332dd5941f6101c0951a6b599 Mon Sep 17 00:00:00 2001 From: Javier Garcia Vera Date: Thu, 5 Nov 2026 13:40:15 +0100 Subject: [PATCH 2/2] fix(perps): do not join a passive read on a forced history refresh A forced Activity refetch invalidated the UI cache but still adopted an in-flight passive request, so forceRefresh never reached the controller. Forced reads now replace that in-flight slot, and tests cover the race for fills, orders, and funding. Co-authored-by: Cursor --- .../perps/coalesceBackgroundRequest.test.ts | 50 ++++++++++- ui/hooks/perps/coalesceBackgroundRequest.ts | 43 +++++++--- .../perps/usePerpsTransactionHistory.test.ts | 84 +++++++++++++++++++ ui/hooks/perps/usePerpsTransactionHistory.ts | 47 +++++++---- 4 files changed, 193 insertions(+), 31 deletions(-) diff --git a/ui/hooks/perps/coalesceBackgroundRequest.test.ts b/ui/hooks/perps/coalesceBackgroundRequest.test.ts index baa7b603ae84..4db07a4dcd53 100644 --- a/ui/hooks/perps/coalesceBackgroundRequest.test.ts +++ b/ui/hooks/perps/coalesceBackgroundRequest.test.ts @@ -83,10 +83,9 @@ describe('coalesceBackgroundRequest', () => { }); it('invalidate() mid-flight preserves the in-flight promise so concurrent callers coalesce into one request', async () => { - // Rapid-navigation scenario: hook A fires a request, then hook B's - // forceFreshOnMount refetch invalidates the cache while A is still - // in flight. B must share A's request rather than fire a duplicate HL - // call — the in-flight snapshot is the freshest data available. + // Rapid navigation: hook A fires a request, then hook B invalidates the + // cache while A is still in flight. A caller that does not opt out shares + // A's request. A caller that cannot share it passes replaceInFlight. let resolveFirst: ((v: string) => void) | undefined; const firstPromise = new Promise((resolve) => { resolveFirst = resolve; @@ -151,6 +150,49 @@ describe('coalesceBackgroundRequest', () => { expect(fn).toHaveBeenCalledTimes(2); }); + it('replaceInFlight issues a new request and keeps that result in the cache', async () => { + let resolveFirst: ((value: string) => void) | undefined; + const firstPromise = new Promise((resolve) => { + resolveFirst = resolve; + }); + const fn = jest + .fn, []>() + .mockReturnValueOnce(firstPromise) + .mockResolvedValueOnce('fresh'); + + const firstCall = coalesceBackgroundRequest('k', fn, 10_000); + await Promise.resolve(); + + const secondCall = coalesceBackgroundRequest('k', fn, 10_000, { + replaceInFlight: true, + }); + resolveFirst?.('stale'); + + const [first, second] = await Promise.all([firstCall, secondCall]); + expect(first).toBe('stale'); + expect(second).toBe('fresh'); + expect(fn).toHaveBeenCalledTimes(2); + + const cached = await coalesceBackgroundRequest('k', fn, 10_000); + expect(cached).toBe('fresh'); + expect(fn).toHaveBeenCalledTimes(2); + }); + + it('replaceInFlight does not return a value cached inside the TTL', async () => { + const fn = jest + .fn, []>() + .mockResolvedValueOnce('cached') + .mockResolvedValueOnce('fresh'); + + await coalesceBackgroundRequest('k', fn, 10_000); + const second = await coalesceBackgroundRequest('k', fn, 10_000, { + replaceInFlight: true, + }); + + expect(second).toBe('fresh'); + expect(fn).toHaveBeenCalledTimes(2); + }); + it('drops in-flight entry when fn throws synchronously so the next caller retries', async () => { const fn = jest .fn, []>() diff --git a/ui/hooks/perps/coalesceBackgroundRequest.ts b/ui/hooks/perps/coalesceBackgroundRequest.ts index 9d6deed36d8e..4ac6e7999144 100644 --- a/ui/hooks/perps/coalesceBackgroundRequest.ts +++ b/ui/hooks/perps/coalesceBackgroundRequest.ts @@ -15,7 +15,9 @@ * home; callers that need a tighter window pass their own TTL, as the Perps * withdraw confirmation alert does at 5 s. Top-level consumers * (`PerpsActivityPage`) pass `forceFreshOnMount` and bypass the cache - * entirely. + * entirely. A forced read also replaces an in-flight request for the same + * key: that request was started without `forceRefresh`, so joining it would + * return the controller's cached snapshot. * * Explicit refetch paths (pull-to-refresh) bypass the cache via invalidate(). * Scope-level teardown (account switch, testnet toggle, wallet lock, @@ -28,6 +30,18 @@ const DEFAULT_TTL_MS = 10_000; type CacheEntry = { at: number; value: TValue }; +/** + * Options for {@link coalesceBackgroundRequest}. + */ +export type CoalesceBackgroundRequestOptions = { + /** + * Issue `fn` even when this key has a cached or in-flight result, and take + * the in-flight slot. The replaced request still resolves for its own + * caller, but it no longer writes the cache. + */ + replaceInFlight?: boolean; +}; + const cache = new Map>(); const inFlight = new Map>(); @@ -37,23 +51,29 @@ const inFlight = new Map>(); * value. * * @param key - Stable key derived from the request method and its params. - * @param fn - Thunk that issues the underlying request. Only called on miss. + * @param fn - Thunk that issues the underlying request. Only called on miss, + * or when `options.replaceInFlight` is set. * @param ttlMs - Optional override for the short-cache TTL. + * @param options - Optional call modifiers. + * @param options.replaceInFlight - Issue a new request and take the in-flight + * slot instead of joining one that is already running. * @returns Resolved value from the request (fresh or cached). */ export async function coalesceBackgroundRequest( key: string, fn: () => Promise, ttlMs: number = DEFAULT_TTL_MS, + options?: CoalesceBackgroundRequestOptions, ): Promise { + const replaceInFlight = options?.replaceInFlight === true; const now = Date.now(); const cached = cache.get(key) as CacheEntry | undefined; - if (cached && now - cached.at < ttlMs) { + if (!replaceInFlight && cached && now - cached.at < ttlMs) { return cached.value; } const existing = inFlight.get(key) as Promise | undefined; - if (existing !== undefined) { + if (!replaceInFlight && existing !== undefined) { return existing; } @@ -67,8 +87,8 @@ export async function coalesceBackgroundRequest( const promise: Promise = Promise.resolve().then(async () => { try { const value = await fn(); - // Only persist if this promise still owns the slot; invalidate() may - // have evicted us mid-flight in favor of a newer request. + // Only persist if this promise still owns the slot. A newer request may + // have taken it via replaceInFlight. if (inFlight.get(key) === promise) { cache.set(key, { at: Date.now(), value }); } @@ -89,12 +109,11 @@ export async function coalesceBackgroundRequest( * the next coalesceBackgroundRequest() to hit the backend instead of serving * the previous cached value. * - * Intentionally leaves any in-flight promise alone: an in-flight request is - * by definition the freshest server snapshot being computed right now, so - * concurrent callers (e.g. a `refetch()` racing with a sibling hook's mount - * fetch) should coalesce into the same request rather than fire a duplicate - * HL call. Dropping the in-flight entry here was the root cause of duplicate - * request bursts during rapid navigation. + * Intentionally leaves any in-flight promise alone. Callers that can share + * that request join it, which avoids the duplicate HyperLiquid calls that + * dropping the slot caused during rapid navigation. A caller that must not + * share it, because the in-flight request was sent with different controller + * options, passes `replaceInFlight` on its own call. * * @param key - Key previously used with coalesceBackgroundRequest. */ diff --git a/ui/hooks/perps/usePerpsTransactionHistory.test.ts b/ui/hooks/perps/usePerpsTransactionHistory.test.ts index b7af81876e34..0f22d6fa2bda 100644 --- a/ui/hooks/perps/usePerpsTransactionHistory.test.ts +++ b/ui/hooks/perps/usePerpsTransactionHistory.test.ts @@ -233,6 +233,90 @@ describe('usePerpsTransactionHistory', () => { { forceRefresh: true }, ], ); + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrders', + [{ accountId: undefined }, { forceRefresh: true }], + ); + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetFunding', + [ + { + accountId: undefined, + startTime: undefined, + endTime: undefined, + }, + { forceRefresh: true }, + ], + ); + }); + }); + + it('sends forceRefresh while a passive read for the same key is still in flight', async () => { + let releasePassive: (() => void) | undefined; + const passiveGate = new Promise((resolve) => { + releasePassive = resolve; + }); + + mockSubmitRequestToBackground.mockImplementation( + (method: string, args: unknown[]) => { + const resultByMethod: Record = { + perpsGetOrderFills: mockFills, + perpsGetOrders: mockOrders, + perpsGetFunding: mockFunding, + }; + const result = resultByMethod[method] ?? []; + const forced = Array.isArray(args) && args.length > 1; + return forced + ? Promise.resolve(result) + : passiveGate.then(() => result); + }, + ); + + const passive = renderHook(() => usePerpsTransactionHistory()); + + await waitFor(() => { + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrderFills', + [{ accountId: undefined, aggregateByTime: false }], + ); + }); + + const forced = renderHook(() => + usePerpsTransactionHistory({ forceFreshOnMount: true }), + ); + + await waitFor(() => { + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrderFills', + [ + { accountId: undefined, aggregateByTime: false }, + { forceRefresh: true }, + ], + ); + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetOrders', + [{ accountId: undefined }, { forceRefresh: true }], + ); + expect(mockSubmitRequestToBackground).toHaveBeenCalledWith( + 'perpsGetFunding', + [ + { + accountId: undefined, + startTime: undefined, + endTime: undefined, + }, + { forceRefresh: true }, + ], + ); + }); + + await act(async () => { + releasePassive?.(); + }); + + await waitFor(() => { + expect(passive.result.current.isLoading).toBe(false); + expect(forced.result.current.isLoading).toBe(false); }); }); diff --git a/ui/hooks/perps/usePerpsTransactionHistory.ts b/ui/hooks/perps/usePerpsTransactionHistory.ts index f559454d9f46..9cc58a79dee8 100644 --- a/ui/hooks/perps/usePerpsTransactionHistory.ts +++ b/ui/hooks/perps/usePerpsTransactionHistory.ts @@ -184,26 +184,43 @@ export function usePerpsTransactionHistory({ // The controller coalesces these REST reads for 60s on its own, so an // explicit refresh must opt out of that cache too. Otherwise a read made // before a fill (e.g. by the perps home preview) hides it from Activity. + // replaceInFlight covers the same window while that preview's read is + // still in flight: joining it would drop forceRefresh. const controllerOptions = forceRefresh ? [{ forceRefresh: true }] : []; + const coalesceOptions = forceRefresh + ? { replaceInFlight: true } + : undefined; try { const [fillsResult, ordersResult, funding] = await Promise.all([ - coalesceBackgroundRequest(coalesceKeys.fills, () => - submitRequestToBackground('perpsGetOrderFills', [ - { accountId, aggregateByTime: false }, - ...controllerOptions, - ]), + coalesceBackgroundRequest( + coalesceKeys.fills, + () => + submitRequestToBackground('perpsGetOrderFills', [ + { accountId, aggregateByTime: false }, + ...controllerOptions, + ]), + undefined, + coalesceOptions, ), - coalesceBackgroundRequest(coalesceKeys.orders, () => - submitRequestToBackground('perpsGetOrders', [ - { accountId }, - ...controllerOptions, - ]), + coalesceBackgroundRequest( + coalesceKeys.orders, + () => + submitRequestToBackground('perpsGetOrders', [ + { accountId }, + ...controllerOptions, + ]), + undefined, + coalesceOptions, ), - coalesceBackgroundRequest(coalesceKeys.funding, () => - submitRequestToBackground('perpsGetFunding', [ - { accountId, startTime, endTime }, - ...controllerOptions, - ]), + coalesceBackgroundRequest( + coalesceKeys.funding, + () => + submitRequestToBackground('perpsGetFunding', [ + { accountId, startTime, endTime }, + ...controllerOptions, + ]), + undefined, + coalesceOptions, ), ]);