Skip to content

perf(perps): stop re-fetching HyperLiquid data the homepage already has - #34511

Open
juanmigdr wants to merge 3 commits into
mainfrom
chore/remove-all-hyperliquid-api-calls
Open

perf(perps): stop re-fetching HyperLiquid data the homepage already has#34511
juanmigdr wants to merge 3 commits into
mainfrom
chore/remove-all-hyperliquid-api-calls

Conversation

@juanmigdr

@juanmigdr juanmigdr commented Aug 7, 2026

Copy link
Copy Markdown
Member

Description

On wallet unlock, the homepage's Perpetuals section (trending tiles + sparklines) was hitting HyperLiquid directly for data that the Terminal API response already contains: one base price call (allMids/metaAndAssetCtxs), plus one candleSnapshot call per trending tile just to build a sparkline.

The companion @metamask/perps-controller change (MetaMask/core#9808) surfaces the price/trend fields already present in the Terminal API response. This PR updates the mobile side to consume that instead of re-fetching from HyperLiquid:

  • useHomepageSparklines now derives sparklines from the trend field already present on each market object, instead of opening a per-symbol candle stream subscription.
  • PerpsSectionMain and usePerpsFeed now pass market objects into useHomepageSparklines instead of bare symbol strings.
  • Pull-to-refresh on the homepage trending carousel now refreshes the market list directly instead of just bumping a re-subscribe key.

Depends on: MetaMask/core#9808 (needs to merge and release first for the HyperLiquid call reduction to take effect; this PR is safe to merge independently since it keeps working against the existing provider fallback path).

Changelog

CHANGELOG entry: Improved homepage load performance by reducing redundant network requests for the Perpetuals section's trending tiles and sparklines.

Related issues

Refs: ASSETS-3858

Manual testing steps

Feature: Homepage Perpetuals section

  Scenario: user unlocks their wallet
    Given the user has the homepage Perpetuals section enabled

    When the user unlocks their wallet
    Then the trending carousel tiles and sparklines render with the same data as before
    And no extra HyperLiquid candleSnapshot/allMids requests are made beyond the existing fallback path

  Scenario: user pulls to refresh on the homepage
    Given the homepage trending carousel is showing

    When the user pulls to refresh
    Then the market list and sparklines both update with fresh data

Screenshots/Recordings

N/A — this is a data-fetching refactor with no UI/visual changes. The trending carousel and sparklines render identically to before.

Before

N/A

After

N/A

Pre-merge author checklist

Performance checks (if applicable)

  • I've tested on Android
    • Ideally on a mid-range device; emulator is acceptable
  • I've tested with a power user scenario
    • Use these power-user SRPs to import wallets with many accounts and tokens
  • I've instrumented key operations with Sentry traces for production performance metrics

For performance guidelines and tooling, see the Performance Guide.

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.

Note

Medium Risk
Changes homepage perps data sourcing and refresh behavior on a high-traffic unlock path; sparkline freshness shifts to hourly trend data until the paired perps-controller release exposes trend reliably.

Overview
Homepage Perpetuals sparklines no longer open a WebSocket candle subscription per trending tile. useHomepageSparklines now takes market objects (not symbol strings), reads each market’s trend from the existing markets fetch, downsamples to ~50 points, and drops the hook’s refresh API.

Call sites (PerpsSectionMain, usePerpsFeed) pass sliced carousel markets into that hook. When the trending carousel is visible, pull-to-refresh on the section calls refreshMarkets from usePerpsTrendingCarouselData (wired through usePerpsMarkets) instead of re-triggering sparkline stream subscriptions.

Sparklines trade live 15m candles for hourly trend data from the Terminal response—intentional to cut redundant HyperLiquid candleSnapshot traffic on unlock/reconnect. Tests cover trend parsing, refresh wiring, and feed sparkline inputs.

Reviewed by Cursor Bugbot for commit 878395a. Bugbot is set up for automated code reviews on this repo. Configure here.

On wallet unlock, the homepage's Perpetuals section was making a burst of
calls straight to HyperLiquid: one for the base price feed, plus one
candleSnapshot call per trending tile for sparklines. All of that data is
already sitting in the Terminal API response the app fetches for the same
markets, once @metamask/perps-controller is updated to expose it.

useHomepageSparklines now reads the trend field already present on each
market object instead of opening a per-symbol candle stream subscription.
PerpsSectionMain and usePerpsFeed pass market objects through instead of
bare symbol strings, and pull-to-refresh now refreshes the market list
directly rather than just re-subscribing to candles.

Requires the paired @metamask/perps-controller change:
https://github.com/MetaMask/core/pull/TBD
@metamask-ci

metamask-ci Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

PR template — items to address before "Ready for review"

Warnings — informational, address before merging:

See docs/readme/ready-for-review.md for the full Definition of Ready for Review.

@github-actions github-actions Bot added size-M risk:medium AI analysis: medium risk labels Aug 7, 2026
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🧪 Flaky unit test detection

Run history flaky detection

View recent run history

Historical failure rate is a hint, not proof — review each suggestion in context. See the flaky-test-detection skill for the full pattern reference and manual audit workflow.

Failures / runs sampled per window:

File 7d 15d 30d
app/components/Views/Homepage/Sections/Perpetuals/PerpsSection.test.tsx 0/86 0/220 0/359

AI-detected flaky patterns

app/components/Views/Homepage/Sections/Perpetuals/PerpsSection.test.tsx

  • J1 — Missing act() around async state updates (critical)
    • This newly-added test directly awaits an async refresh() method exposed via ref (which internally performs state updates or Redux dispatches in the component). Per J1, any async handler that can trigger React state updates must be wrapped in act() to avoid races, unhandled updates, and intermittent 'TypeError: terminated' or similar CI failures. The test passes the mock but does not synchronize the update. Historical data showed no prior flakiness for this file, but this pattern introduces risk.
    • Suggested fix in app/components/Views/Homepage/Sections/Perpetuals/PerpsSection.test.tsx:
      -    it('refreshes the market list on pull-to-refresh when the trending carousel is showing', async () => {
      -      const refresh = jest.fn().mockResolvedValue(undefined);
      -      usePerpsMarkets.mockReturnValue({
      -        markets: [
      -          makeTrendingMarket({ symbol: 'BTC', volumeNumber: 5000000000 }),
      -        ],
      -        isLoading: false,
      -        error: null,
      -        refresh,
      -        isRefreshing: false,
      -      });
      -      const ref = React.createRef<{ refresh: () => Promise<void> }>();
      -
      -      renderWithProvider(
      -        <PerpsSection sectionIndex={0} totalSectionsLoaded={1} ref={ref} />,
      -      );
      -
      -      await ref.current?.refresh();
      -
      -      expect(refresh).toHaveBeenCalledTimes(1);
      -    });
      -
      +    it('refreshes the market list on pull-to-refresh when the trending carousel is showing', async () => {
      +      const refresh = jest.fn().mockResolvedValue(undefined);
      +      usePerpsMarkets.mockReturnValue({
      +        markets: [
      +          makeTrendingMarket({ symbol: 'BTC', volumeNumber: 5000000000 }),
      +        ],
      +        isLoading: false,
      +        error: null,
      +        refresh,
      +        isRefreshing: false,
      +      });
      +      const ref = React.createRef<{ refresh: () => Promise<void> }>();
      +
      +      renderWithProvider(
      +        <PerpsSection sectionIndex={0} totalSectionsLoaded={1} ref={ref} />,
      +      );
      +
      +      await act(async () => {
      +        await ref.current?.refresh();
      +      });
      +
      +      expect(refresh).toHaveBeenCalledTimes(1);
      +    });
      +

This check is informational only and does not block merging.

@juanmigdr juanmigdr added the area-performance Issues relating to slowness of app, cpu usage, and/or blank screens. label Aug 7, 2026
@metamask-ci metamask-ci Bot removed the INVALID-PR-TEMPLATE PR's body doesn't match template label Aug 7, 2026
… release

PerpsMarketData.trend isn't in the currently published perps-controller
package types yet - that lands with the paired core PR. Read it through a
local type until the dependency is bumped, and fix the mock typing in
usePerpsFeed's test that was tripping up on an untyped spread.
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

  • Selected E2E tags: SmokePerps, SmokeWalletPlatform, SmokeConfirmations
  • Selected Performance tags: @PerformancePreps
  • Risk Level: medium
  • AI Confidence: 88%
click to see 🤖 AI reasoning details

E2E Test Selection:
The PR changes the sparkline data source for the Perps section from WebSocket candle stream subscriptions (HyperLiquid per-symbol candleSnapshot calls) to reading the trend field already present in PerpsMarketData from the Terminal API. This is a functional change affecting:

  1. PerpsSectionMain.tsx: Pull-to-refresh now calls refreshMarkets instead of refreshSparklines, changing what data is refreshed on user interaction.
  2. useHomepageSparklines.ts: Complete refactor — removes WebSocket subscriptions, removes refresh return value, now derives sparklines from market trend data synchronously via useMemo.
  3. usePerpsTrendingCarouselData.ts: Exposes refreshMarkets from usePerpsMarkets.
  4. usePerpsFeed.ts: Passes full market objects (not just symbols) to useHomepageSparklines.

SmokePerps: Directly tests Perps functionality including the Add Funds flow, balance verification, and market display. The sparkline rendering and pull-to-refresh behavior changes need validation.

SmokeWalletPlatform: Per the tag description, Perps is a section inside the Trending tab. Changes to Perps views (headers, lists, full views) affect Trending. The usePerpsFeed.ts change directly affects how Perps data is displayed in the TrendingView.

SmokeConfirmations: Per SmokePerps description, Add Funds deposits are on-chain transactions requiring confirmation flows. Required when selecting SmokePerps.

The test files are unit tests only (no E2E smoke specs), so they don't directly map to additional E2E tags beyond what the functional changes warrant.

Performance Test Selection:
The PR removes per-symbol WebSocket candle stream subscriptions for sparklines and replaces them with synchronous derivation from pre-fetched market trend data. This directly impacts the Perps market loading flow — previously each symbol triggered a separate HyperLiquid candleSnapshot WebSocket subscription on every reconnect, which could add latency and overhead. The new approach reads trend data already present in the market response, potentially improving load times. @PerformancePreps covers perps market loading, position management, add funds flow, and order execution — all of which are affected by this data-fetching architecture change.

View GitHub Actions results

@sonarqubecloud

sonarqubecloud Bot commented Aug 7, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

⚡ Performance Test Results

ℹ️ Performance test results are currently non-blocking and will not block this PR.

All tests passed · 2 tests · 1 device

📱 Devices tested (1)

Android: Google Pixel 8 Pro (v14.0)

✅ Passed Tests (2)
Test Platform Device Duration Team Recording
Perps add funds Android Google Pixel 8 Pro (v14.0) 7.55s @mm-perps-engineering-team 📹 Watch
Perps open position and close it Android Google Pixel 8 Pro (v14.0) 20.58s @mm-perps-engineering-team 📹 Watch

Branch: chore/remove-all-hyperliquid-api-calls · Build: E2E · Commit: 3cca68c · View full run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-performance Issues relating to slowness of app, cpu usage, and/or blank screens. risk:medium AI analysis: medium risk size-M team-assets

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant