Skip to content

Conversation

@abretonc7s
Copy link
Contributor

@abretonc7s abretonc7s commented Nov 6, 2025

Description

This PR fixes 429 rate limit errors and improves Perps trading performance through two complementary changes:

  1. Dual Transport Architecture: Separates HTTP and WebSocket transports to match their intended use cases
  2. Session-Based Caching: Eliminates redundant API calls during user sessions

What is the reason for the change?

Problem 1: 429 Rate Limit Errors After SDK Upgrade (TAT-1974)

HyperLiquid SDK v0.25.9 defaulted all operations to WebSocket transport, causing 429 errors during normal trading. Write operations (orders, cancellations) were exhausting WebSocket rate limits that should be reserved for real-time subscriptions.

Problem 2: Redundant API Calls (TAT-2022)

Builder fee approval, referral setup, and market metadata were called repeatedly during each session, adding unnecessary latency and rate limit pressure.

What is the improvement/solution?

Solution 1: Dual Transport Architecture (TAT-1974)

Separated HTTP and WebSocket transports to match their intended use:

  • HTTP transport: Request/response operations (orders, queries, account data)
  • WebSocket transport: Real-time subscriptions only (price feeds, position updates)

Benefits:

  • Eliminates 429 errors (separate rate limit pools)
  • Improved reliability (write operations don't compete with subscriptions)

Solution 2: Session-Based Caching (TAT-2022)

Moved repeated API calls to once-per-session initialization:

  • Builder fee approval: Called once during initialization instead of per-order
  • Referral setup: Non-blocking fire-and-forget pattern
  • Market metadata: Single shared cache for all operations

Benefits:

  • Reduced API calls (1 vs many per session)
  • Lower latency (no per-order network overhead)
  • Improved reliability (referral failures don't block orders)

Changelog

CHANGELOG entry: Fixed 429 rate limit errors by separating HTTP/WebSocket transports and improved Perps trading performance through session-based caching

Related issues

Fixes: https://consensyssoftware.atlassian.net/browse/TAT-1974
Fixes: https://consensyssoftware.atlassian.net/browse/TAT-2022

Manual testing steps

Feature: Dual transport architecture and session-based caching for Perps trading

  Scenario: Write operations use HTTP transport
    Given user opens Perps and initializes connection

    When user places multiple orders rapidly
    Then orders should complete successfully without 429 errors
    And WebSocket subscriptions should remain active for price updates

  Scenario: Session caching reduces redundant API calls
    Given user opens Perps and initializes connection

    When user places multiple orders
    Then builder fee approval should only be called once
    And referral setup should happen in background (non-blocking)
    And meta responses should be cached and reused

    When user disconnects or switches account
    Then caches should be cleared and reinitialized

Screenshots/Recordings

Backend performance optimization (no UI changes).

Simulator.Screen.Recording.-.iPhone.16.Pro.-.2025-11-05.at.11.57.28.mp4

Demo on iOS/Android showing functionality still works correctly.

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.

Technical Implementation Details

For reviewers: Implementation overview

Files Modified:

Transport Architecture (TAT-1974):

  1. HyperLiquidClientService.ts - Dual transport creation and injection
  2. HyperLiquidClientService.test.ts - Transport configuration tests

Session-Based Caching (TAT-2022):
3. HyperLiquidProvider.ts - Session cache implementation and initialization flow
4. HyperLiquidProvider.test.ts - Updated test expectations

Test Coverage:

  • Transport Architecture: 32 tests passing
  • Session Caching: 244 tests passing
  • Total: 276 tests passing

Note

Splits SDK transport into HTTP (Info/Exchange) and WebSocket (Subscription), adds session-scoped caching for meta, referral, and builder-fee approval, refactors provider to use cached meta across methods, updates tests, and bumps SDK.

  • Perps Backend (HyperLiquidProvider.ts)
    • Introduces shared getCachedMeta() and replaces prior market cache; used in placeOrder, editOrder, closePositions, getMarkets, getMaxLeverage, getAvailableHip3Dexs, etc.
    • Adds session caches for referral and builder-fee approval; initializes once in ensureReady() and clears on disconnect().
    • Refactors market fetching API to { dex, skipFilters, skipCache } and updates internal callers.
    • Improves meta validation and error messaging; switches TP/SL/referral to non-blocking behavior where applicable.
    • Adds HIP‑3 balance handling helpers and post-order rebalance/rollback flow (uses cached meta and session state).
  • SDK Client Service (HyperLiquidClientService.ts)
    • Implements dual transports: HttpTransport for ExchangeClient/InfoClient, WebSocketTransport for SubscriptionClient.
    • Updates logging and disconnect to close only WebSocket transport; exposes connection state helpers.
  • Tests
    • Updates provider tests for new error messages (e.g., "Invalid meta response"), non-blocking referral, and session-cached builder-fee approval (verifies single approval across orders).
    • Updates client service tests to validate dual transports, config, and disconnect behavior.
  • Dependencies
    • Bumps @nktkas/hyperliquid to ^0.25.9 (lockfile updated).

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

… market metadata

- Updated caching mechanism for market metadata to improve efficiency and reduce redundant API calls.
- Changed error messages for better clarity when fetching market metadata fails.
- Refactored referral and builder fee approval processes to utilize session caching, ensuring they are only set once per session.
- Improved tests to reflect changes in error handling and caching logic.

This refactor aims to streamline the provider's performance and enhance user experience by minimizing unnecessary API requests.
@abretonc7s abretonc7s requested a review from a team as a code owner November 6, 2025 11:42
@abretonc7s abretonc7s added the team-perps Perps team label Nov 6, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Nov 6, 2025

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.

Copy link

@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.

Bug: Remove redundant checks after ensureReady in updatePositionTPSL

The updatePositionTPSL() method still explicitly calls ensureBuilderFeeApproval() and ensureReferralSet() after calling ensureReady(). This is inconsistent with the session-based caching optimization implemented in this PR. According to the PR description and the changes in placeOrder() (where these calls were removed), builder fee approval and referral setup should only happen once during ensureReady() initialization, not per-operation. These redundant calls in updatePositionTPSL() defeat the purpose of session-based caching and will still make unnecessary API calls on every TP/SL update. These lines should be removed to match the pattern used in placeOrder().

app/components/UI/Perps/controllers/providers/HyperLiquidProvider.ts#L2428-L2433

const userAddress = await this.walletService.getUserAddressWithDefault();
// Extract DEX name for API calls (main DEX = null)
const { dex: dexName } = parseAssetName(coin);
// Fetch current price for this asset's DEX

Fix in Cursor Fix in Web


- Changed referral code setup to be blocking, ensuring proper attribution while logging errors to Sentry for retries in the next session.
- Introduced a new method to generate user-specific session cache keys for better organization.
- Enhanced error messages for clarity and added context to error logging throughout the referral process.
- Updated comments for better understanding of caching behavior and error handling.

These changes aim to streamline the referral process and improve overall reliability in user sessions.
…val processes

- Updated referral code setup to block initialization for better attribution, ensuring users can trade immediately even if setup fails.
- Improved caching logic for builder fee approvals, now only caching successful approvals to avoid redundant checks.
- Enhanced comments for clarity on caching behavior and error handling.

These changes aim to streamline user sessions and improve overall reliability in the HyperLiquidProvider.
abretonc7s and others added 2 commits November 6, 2025 22:37
- Updated caching behavior to only store successful referral states, preventing redundant checks and allowing detection of external referral changes.
- Enhanced comments for clarity on caching semantics and error handling.
- Adjusted session cache updates to streamline the referral process and improve reliability.

These changes aim to optimize user sessions and ensure accurate referral tracking in the HyperLiquidProvider.
@abretonc7s abretonc7s enabled auto-merge November 6, 2025 15:06
Copy link

@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.

Bug: Cache Clearing Gap: Network Toggle Misuses Data

Session caches are not cleared when toggling between testnet and mainnet, which can cause cached data from one network to be incorrectly used on another network. The toggleTestnet() method should clear referralCheckCache, builderFeeCheckCache, and cachedMetaByDex since:

  1. Builder fee approval is network-specific (different builder addresses for testnet vs mainnet)
  2. Referral state is network-specific (different referral codes)
  3. Meta responses contain network-specific market data

This can lead to:

  • Using mainnet builder fee approval cache on testnet
  • Using testnet referral state on mainnet
  • Using wrong market metadata for the current network

The fix should add cache clearing calls similar to the disconnect() method:

this.referralCheckCache.clear();
this.builderFeeCheckCache.clear();
this.cachedMetaByDex.clear();

app/components/UI/Perps/controllers/providers/HyperLiquidProvider.ts#L5309-L5325

https://github.com/MetaMask/metamask-mobile/blob/48fdd3b0010eaa10ce3dcc6a4f1231d5e4c37b61/app/components/UI/Perps/controllers/providers/HyperLiquidProvider.ts#L5309-L5325

Fix in Cursor Fix in Web


michalconsensys
michalconsensys previously approved these changes Nov 7, 2025
@abretonc7s abretonc7s changed the title perf(perps): optimize initialization with session-based caching for builder fee and referral fix(perps): optimize initialization with session-based caching for builder fee and referral Nov 10, 2025
@abretonc7s abretonc7s changed the title fix(perps): optimize initialization with session-based caching for builder fee and referral fix(perps): Resolve 429 errors and improve session performance cp-7.59.0 Nov 10, 2025
@github-actions github-actions bot added size-L and removed size-M labels Nov 10, 2025
@socket-security
Copy link

socket-security bot commented Nov 10, 2025

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Updatednpm/​@​nktkas/​hyperliquid@​0.25.7 ⏵ 0.25.9100 +1100100 +196 +1100

View full report

- Added `maxRetries` and `connectionTimeout` parameters to the reconnect configuration in `HyperLiquidClientService`.
- Updated corresponding test to reflect these new options.
@michalconsensys
Copy link
Contributor

@sonarqubecloud
Copy link

@abretonc7s abretonc7s added this pull request to the merge queue Nov 10, 2025
Merged via the queue into main with commit cf57bcc Nov 10, 2025
84 checks passed
@abretonc7s abretonc7s deleted the fix/perps/session-caching branch November 10, 2025 16:27
@github-actions github-actions bot locked and limited conversation to collaborators Nov 10, 2025
@metamaskbot metamaskbot added the release-7.60.0 Issue or pull request that will be included in release 7.60.0 label Nov 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.60.0 Issue or pull request that will be included in release 7.60.0 size-L team-perps Perps team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants