Skip to content

fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets cp-7.63.0 cp-7.64.0#25493

Merged
abretonc7s merged 3 commits intomainfrom
fix/perps/spotmeta-cache
Feb 2, 2026
Merged

fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets cp-7.63.0 cp-7.64.0#25493
abretonc7s merged 3 commits intomainfrom
fix/perps/spotmeta-cache

Conversation

@abretonc7s
Copy link
Copy Markdown
Contributor

@abretonc7s abretonc7s commented Feb 1, 2026

Description

fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets

This PR adds session-based caching for HyperLiquid's global spotMeta endpoint to avoid redundant API calls during HIP-3 operations.

Context

Following a rate limiting incident where excessive API calls triggered HyperLiquid's rate limits (2000 msg/min), this is a defensive improvement to reduce unnecessary network requests.

Problem

The spotMeta API (which returns token metadata like USDC/USDH indices) was being called multiple times per trading session:

  • getUsdcTokenId() - called during transfers
  • isUsdhCollateralDex() - called to check collateral type
  • swapUsdcToUsdh() - called during HIP-3 USDH swaps

Each call was making a fresh API request, even though the data (token indices) doesn't change during a session.

Solution

  • Added cachedSpotMeta property for session-based caching (no TTL - token indices are stable)
  • Added getCachedSpotMeta() method that returns cached data or fetches once
  • Pre-fetch spotMeta in ensureReadyForTrading() when HIP-3 is enabled (non-blocking)
  • Cache invalidated on disconnect() to ensure fresh state on reconnect/account switch

Design Decisions

  • Global cache (not per-DEX): spotMeta is a global endpoint returning all tokens
  • Session-based (no TTL): Token indices don't change during a session
  • Graceful fallback: If pre-fetch fails, methods fetch on-demand
  • Follows existing patterns: getCachedMeta(), getCachedPerpDexs()

Changelog

CHANGELOG entry: Fixed excessive API calls on HIP-3 markets by caching spot metadata

Related issues

Fixes: N/A (Defensive improvement following rate limiting incident)

Manual testing steps

Feature: SpotMeta caching for HIP-3 operations

  Scenario: User places order on HIP-3 DEX (SILVER)
    Given user has connected wallet with USDC balance
    And user is on a HIP-3 enabled DEX (e.g., SILVER)

    When user places an order
    Then order should succeed
    And spotMeta API should only be called once per session (check debug logs)

  Scenario: User disconnects and reconnects
    Given user has placed orders (spotMeta is cached)

    When user disconnects wallet
    And user reconnects wallet
    Then spotMeta cache should be cleared
    And next HIP-3 operation should fetch fresh spotMeta

Screenshots/Recordings

N/A - Internal optimization, no UI changes

Before

Multiple spotMeta API calls per session (one per HIP-3 operation)

After

Single spotMeta API call per session, cached for subsequent operations

Pre-merge author checklist

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
Touches perps trading setup and HIP-3 collateral/token resolution by introducing session-cached spotMeta; incorrect caching or cache invalidation could affect order/transfer flows, though it falls back to on-demand fetch and clears on disconnect.

Overview
Reduces HyperLiquid rate-limit pressure on HIP-3 flows by adding a session-level spotMeta cache in HyperLiquidProvider, prefetching it during ensureReadyForTrading(), reusing it in USDC/USDH collateral checks and swaps, and clearing it on disconnect.

Standardizes error handling across perps controllers/providers by extending ensureError with optional context (including better messages for null/undefined) and replacing ad-hoc instanceof Error checks in connection, streaming, deposit/testnet toggle, and provider operations; updates related tests and types (SpotMetaResponse).

Written by Cursor Bugbot for commit 3ee4cb2. This will update automatically on new commits. Configure here.

@abretonc7s abretonc7s requested a review from a team as a code owner February 1, 2026 14:05
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Feb 1, 2026

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

@metamaskbot metamaskbot added the team-perps Perps team label Feb 1, 2026
@github-actions github-actions bot added the size-S label Feb 1, 2026
@aganglada
Copy link
Copy Markdown
Contributor

QA Testing Performed ✅

Environment

  • Device: iOS Simulator (iPhone 17)
  • Build: main-dev
  • Network: Mainnet (HIP-3 DEXs: SILVER, GOLD)

Test 1: SpotMeta Caching - Single API Call Per Session ✅

Steps:

  1. Connected wallet with USDC balance
  2. Navigated to Perps → Selected HIP-3 DEX (SILVER)
  3. Placed first order
  4. Placed second order
  5. Checked debug logs for spotMeta API calls

Test 2: Cache Invalidation on Disconnect ✅

Steps:

  1. With cached spotMeta from Test 1
  2. Disconnected wallet (navigated away from Perps for >20s grace period)
  3. Reconnected wallet
  4. Navigated to HIP-3 DEX
  5. Placed order

Test 3: Account Switch - Cache Cleared ✅

Steps:

  1. Connected Account 1, placed order on HIP-3 DEX
  2. Switched to Account 2
  3. Placed order on HIP-3 DEX

Test 4: Graceful Fallback - Pre-fetch Failure ✅

Steps:

  1. Simulated slow network during connection
  2. ensureReadyForTrading() pre-fetch timed out (non-blocking)
  3. Attempted to place order on HIP-3 DEX

Test 5: Rate Limit Protection ✅

Steps:

  1. Rapid successive order placements on HIP-3 DEX
  2. Monitored API call frequency

Expected: No rate limit errors, spotMeta cached
Actual: ✅ Single spotMeta call regardless of order frequency


Network Request Comparison

Scenario Before (API calls) After (API calls)
First HIP-3 order 1 1
Second HIP-3 order 1 0 (cached)
Third HIP-3 order 1 0 (cached)
After reconnect 1 1 (fresh)
Total (3 orders) 3 1

Edge Cases Tested

  • Empty cache on first connection
  • Cache cleared on disconnect()
  • Cache survives app backgrounding (within grace period)
  • Pre-fetch failure doesn't block trading
  • Main DEX (non-HIP-3) operations unaffected

Code Review Notes

  • ✅ Follows existing caching patterns (getCachedMeta(), getCachedPerpDexs())
  • ✅ Session-based cache appropriate for stable token indices
  • ✅ Non-blocking pre-fetch prevents connection delays
  • ✅ Tests updated for new SpotMetaResponse type

Conclusion

All test scenarios passed. The caching implementation correctly reduces API calls while maintaining data freshness on reconnection/account switch.

@abretonc7s abretonc7s added the skip-sonar-cloud Only used for bypassing sonar cloud when failures are not relevant to the changes. label Feb 2, 2026
@abretonc7s abretonc7s changed the title fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets cp-7.63.0 Feb 2, 2026
@github-actions github-actions bot added size-M and removed size-S labels Feb 2, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Feb 2, 2026

🔍 Smart E2E Test Selection

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

E2E Test Selection:
The changes are focused entirely on the Perps (perpetuals trading) feature:

  1. Error handling improvements: The ensureError utility function in app/util/errorUtils.ts was enhanced to handle undefined/null errors better and accept an optional context parameter. This is a backward-compatible change that only affects error message formatting.

  2. Perps-specific changes:

    • PerpsController.ts: Updated error handling in initiateDeposit and toggleTestnet methods
    • HyperLiquidProvider.ts: Added caching for spotMeta API calls (HIP-3 collateral checks), pre-fetches in ensureReadyForTrading() for performance, updated error handling throughout
    • PerpsConnectionProvider.tsx, PerpsStreamManager.tsx, PerpsConnectionManager.ts: Updated error handling to use ensureError with context
    • hyperliquid-types.ts: Added SpotMetaResponse type export
  3. Impact assessment:

    • The ensureError utility is used exclusively within the Perps module (20 files, all in app/components/UI/Perps/)
    • No changes to core Engine, network controllers, or other critical infrastructure
    • The changes are isolated to the perpetuals trading feature
    • The caching optimization for spotMeta could improve performance but is non-breaking
  4. Risk level: Medium because:

    • Changes affect a controller (PerpsController) which is marked as critical
    • Error handling changes could affect user-facing error messages
    • Caching changes could affect API behavior if not properly implemented
    • However, changes are well-isolated to the Perps feature domain

Only SmokePerps tag is needed as all changes are contained within the Perps feature domain.

Performance Test Selection:
The changes include a performance optimization in HyperLiquidProvider.ts - adding caching for spotMeta API calls and pre-fetching in ensureReadyForTrading(). This caching mechanism is specifically designed to improve performance during order placement by avoiding repeated API calls. The @PerformancePreps tag should be run to verify that these caching changes actually improve performance and don't introduce any regressions in the perps trading flow (add funds, position management, order execution).

View GitHub Actions results

Copy link
Copy Markdown

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Feb 2, 2026

Quality Gate Failed Quality Gate failed

Failed conditions
69.2% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

@abretonc7s abretonc7s enabled auto-merge February 2, 2026 07:44
@abretonc7s abretonc7s added this pull request to the merge queue Feb 2, 2026
@abretonc7s abretonc7s changed the title fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets cp-7.63.0 fix(perps): add spotMeta caching to reduce API calls on HIP-3 markets cp-7.63.0 cp-7.64.0 Feb 2, 2026
Merged via the queue into main with commit b5c386c Feb 2, 2026
90 of 91 checks passed
@abretonc7s abretonc7s deleted the fix/perps/spotmeta-cache branch February 2, 2026 08:43
@github-actions github-actions bot locked and limited conversation to collaborators Feb 2, 2026
@metamaskbot metamaskbot added the release-7.65.0 Issue or pull request that will be included in release 7.65.0 label Feb 2, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.65.0 Issue or pull request that will be included in release 7.65.0 size-M skip-sonar-cloud Only used for bypassing sonar cloud when failures are not relevant to the changes. team-perps Perps team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants