Skip to content

fix(perps): recover HIP-3 DEX discovery on transient failure + guard deposit Arbitrum check cp-7.68.0#27127

Merged
michalconsensys merged 4 commits into
mainfrom
fix/perps/sentry-analysis
Mar 6, 2026
Merged

fix(perps): recover HIP-3 DEX discovery on transient failure + guard deposit Arbitrum check cp-7.68.0#27127
michalconsensys merged 4 commits into
mainfrom
fix/perps/sentry-analysis

Conversation

@abretonc7s

@abretonc7s abretonc7s commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

Description

Addresses two perps issues identified via Sentry analysis (branch: fix/perps/sentry-analysis).

Issue 1: HIP-3 DEX discovery not retried after transient failure

Root cause: When perpDexs() fails transiently (WS drop during init), #fetchValidatedDexsInternal was caching [null] (main DEX only). On the next #ensureReady() call, the cache hit returned the stale degraded result — HIP-3 markets stayed unavailable for the entire session.

Fix:

  • On transient fetch failure, return [null] without caching so the next call retries
  • Added #dexDiscoveryComplete flag: when false, #ensureReady() resets its promise after each init so every subsequent trading call (closePosition, placeOrder, etc.) retries DEX discovery
  • Once discovery succeeds, HIP-3 symbols are merged into the existing map and #dexDiscoveryComplete = true — no more retries
  • Trading on main DEX continues uninterrupted during degraded state
  • Flag is cleared on disconnect() for clean reconnection

Note: the upstream fix preventing the permanent provider brick (commit 29d300597d, already in main) should be cherry-picked to 7.67.4. This PR adds the retry logic on top.

Issue 2: "Invalid chain ID 0xa4b1" on deposit from pay-with modal

Root cause: usePerpsBalanceTokenFilter.handlePerpsDepositPress called depositWithConfirmation() directly without first calling ensureArbitrumNetworkExists(). Users without Arbitrum in their network list hit NetworkController.findNetworkClientIdByChainId throwing on chain 0xa4b1 (Arbitrum One — HyperLiquid's bridge chain). The guard existed in usePerpsHomeActions but was missing from this second entry point.

Fix: Call ensureArbitrumNetworkExists() before depositWithConfirmation() in handlePerpsDepositPress, matching the existing pattern in usePerpsHomeActions.

This error predates 7.67 — it became visible due to improved Sentry tagging in Feb 2026 (commits 30f8e72cc4/61a2be3e9d). Not a regression, low volume (~170 users).

Changelog

CHANGELOG entry: null

Related issues

Fixes: (Sentry: METAMASK-MOBILE-5JCV, METAMASK-MOBILE-5G4T, METAMASK-MOBILE-5JGC, METAMASK-MOBILE-5H0A)

Manual testing steps

Feature: Perps DEX discovery recovery

  Scenario: user opens perps while connection is unstable
    Given the app is open on the Perps screen
    And the WebSocket connection drops during provider initialization

    When the user waits for reconnection
    Then HIP-3 DEX markets should become available once connection recovers
    And main DEX trading (closePosition, placeOrder) should work immediately

  Scenario: user without Arbitrum taps Add Funds from confirmation screen
    Given the user has no Arbitrum network configured
    And the user is on a perpsDepositAndOrder confirmation screen

    When user taps the "Add funds" button in the token selector
    Then Arbitrum should be added to their network list
    And the deposit flow should proceed normally

Screenshots/Recordings

Before

N/A — logic fix, no UI change

After

N/A — logic fix, no UI change

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 provider initialization/caching and the deposit entrypoint, which can affect market availability and deposit/trading flows if the retry/caching logic misbehaves. Changes are contained and covered by updated unit tests, but they run in core perps paths.

Overview
Improves perps reliability by making HIP-3 DEX discovery recoverable after transient perpDexs() failures: degraded fallback results are no longer cached, a new #dexDiscoveryComplete flag tracks whether discovery succeeded with real data, and #ensureReady() now rebuilds/retries the asset/DEX mapping on subsequent calls until discovery completes (reset on disconnect()).

Fixes a deposit crash from the token selector by ensuring Arbitrum is present/enabled via usePerpsNetworkManagement.ensureArbitrumNetworkExists() before navigating to the perps deposit flow and calling depositWithConfirmation(). Tests were updated to mock the new network guard and to stub metaAndAssetCtxs in HyperLiquidProvider test clients to match the new initialization behavior.

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

…d deposit flow

- HyperLiquidProvider: on transient perpDexs() fetch failure, return [null] without
  caching so the next #ensureReady() call retries DEX discovery instead of reusing a
  stale degraded result. Added #dexDiscoveryComplete flag so #ensureReady resets its
  promise and re-runs #buildAssetMapping until discovery succeeds — trading on main
  DEX continues uninterrupted in the meantime. Flag is cleared on disconnect for
  clean reconnection.

- usePerpsBalanceTokenFilter: call ensureArbitrumNetworkExists() before
  depositWithConfirmation() in handlePerpsDepositPress, matching the existing guard
  in usePerpsHomeActions. Fixes "Invalid chain ID 0xa4b1" for users without Arbitrum
  configured who tap "Add funds" from the pay-with modal.
@github-actions

github-actions Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

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 Mar 6, 2026
@abretonc7s abretonc7s changed the title fix(perps): recover HIP-3 DEX discovery on transient failure + guard deposit Arbitrum check fix(perps): recover HIP-3 DEX discovery on transient failure + guard deposit Arbitrum check cp-7.68.0 Mar 6, 2026
@github-actions github-actions Bot added the size-S label Mar 6, 2026
@abretonc7s abretonc7s marked this pull request as ready for review March 6, 2026 13:08
@abretonc7s abretonc7s requested a review from a team as a code owner March 6, 2026 13:08
Comment thread app/controllers/perps/providers/HyperLiquidProvider.ts
aganglada
aganglada previously approved these changes Mar 6, 2026
@aganglada aganglada enabled auto-merge March 6, 2026 13:21
@aganglada aganglada disabled auto-merge March 6, 2026 13:25
Align test mocks with provider behavior: buildAssetMapping uses
metaAndAssetCtxs (not meta) to populate cache. Add metaAndAssetCtxs
to placeOrder retry, closePosition TP/SL, and builder fee tests.
Expect metaAndAssetCtxs in getMarkets test. Update invalid-meta
tests to expect asset-not-found when metaAndAssetCtxs returns no
valid universe.
michalconsensys
michalconsensys previously approved these changes Mar 6, 2026
@github-actions github-actions Bot added size-M and removed size-S labels Mar 6, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

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.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

this.#cachedMetaByDex.clear();
this.#cachedSpotMeta = null;
this.#perpDexsCache = { data: null, timestamp: 0 };
this.#dexDiscoveryComplete = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Race condition: disconnect flag overwritten by completing IIFE

Low Severity

#dexDiscoveryComplete = false is set on line 7339 before awaiting pendingReady on lines 7363–7366. If the in-flight #ensureReadyPromise IIFE completes during that await, its #buildAssetMapping() sets #dexDiscoveryComplete = true, overwriting the reset. After disconnect, the flag stays true, so the next reconnect skips #buildAssetMapping() entirely — the cleared #cachedMetaByDex is never repopulated and stale #symbolToAssetId entries persist. This is inconsistent with #clientsInitialized, which is correctly reset after the awaits at line 7381.

Additional Locations (1)

Fix in Cursor Fix in Web

…uidProvider tests

- Mock usePerpsNetworkManagement to prevent test hang
- Fix allowlist test by matching useSelector call order
- Await async handlePerpsDepositPress in Add funds test
- Format HyperLiquidProvider.test.ts
@github-actions

github-actions Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

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

E2E Test Selection:
The changes are focused on two areas:

  1. usePerpsBalanceTokenFilter hook: Modified to call ensureArbitrumNetworkExists() before navigating to perps deposit confirmation. This ensures the Arbitrum network is available before attempting deposits. This affects the Add Funds flow in perps.

  2. HyperLiquidProvider: Added transient error recovery for DEX discovery. The provider now tracks whether DEX discovery completed successfully via #dexDiscoveryComplete flag, and retries on subsequent calls if it failed transiently. This improves resilience of the perps trading functionality.

Tag selection rationale:

  • SmokePerps: Primary tag - changes directly affect perps Add Funds flow and HyperLiquid provider initialization
  • SmokeConfirmations: Required per tag description - "When selecting SmokePerps, also select SmokeConfirmations (Add Funds deposits are on-chain transactions)"
  • SmokeWalletPlatform: Required per tag description - "When selecting SmokePerps, also select SmokeWalletPlatform (Trending section)" since Perps is a section inside Trending

The changes are medium risk because:

  • They modify the deposit flow logic (adding network check before deposit)
  • They change error handling behavior in the HyperLiquid provider
  • However, the changes are well-scoped to perps functionality and include comprehensive unit tests

Performance Test Selection:
The HyperLiquidProvider changes affect initialization and error recovery logic, including the #ensureReady() method and DEX discovery caching. These changes could impact perps loading performance, particularly in error recovery scenarios. The @PerformancePreps tag covers perps market loading and add funds flow which are directly affected by these changes.

View GitHub Actions results

@github-actions

github-actions Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

⚠️ E2E Fixture Validation — Structural changes detected

Category Count
New keys 68
Missing keys 11
Type mismatches 0
Value mismatches 7 (informational)

The committed fixture schema is out of date. To update, comment:

@metamaskbot update-mobile-fixture

View full details | Download diff report

@sonarqubecloud

sonarqubecloud Bot commented Mar 6, 2026

Copy link
Copy Markdown

@michalconsensys michalconsensys added this pull request to the merge queue Mar 6, 2026
Merged via the queue into main with commit f10a65b Mar 6, 2026
97 checks passed
@michalconsensys michalconsensys deleted the fix/perps/sentry-analysis branch March 6, 2026 15:46
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 6, 2026
@metamaskbot metamaskbot added the release-7.70.0 Issue or pull request that will be included in release 7.70.0 label Mar 6, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.70.0 Issue or pull request that will be included in release 7.70.0 size-M team-perps Perps team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants