Skip to content

perf: throttle perps PnL price ticks and gate Polymarket WS on focus - #34823

Open
javiergarciavera wants to merge 1 commit into
mainfrom
perf/perps-ws-throttle-and-predict-focus-gate
Open

perf: throttle perps PnL price ticks and gate Polymarket WS on focus#34823
javiergarciavera wants to merge 1 commit into
mainfrom
perf/perps-ws-throttle-and-predict-focus-gate

Conversation

@javiergarciavera

@javiergarciavera javiergarciavera commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Description

Updates @metamask/perps-controller from v11 to v12 and adapts Mobile to the controller's new order types and error codes. Close-position flows remain restricted to ordinary market and limit orders, while the new TWAP, scale, and chase validation errors are mapped to user-facing English messages.

The change also updates Perps controller fixtures for the v12 proLayoutPreferences state and adds default Hyperliquid API mocks required by E2E initialization, including a valid userAbstraction response.

Changelog

CHANGELOG entry: Updated Perps with the latest trading engine and clearer errors for advanced order types

Related issues

Fixes: https://consensyssoftware.atlassian.net/browse/TAT-3761

Manual testing steps

N/A — this dependency integration has no intentional visual changes. The affected behavior is covered by Perps error-translation tests, type checking, and E2E fixture validation.

Feature: Perps controller v12 integration

  Scenario: A user closes a Perps position
    Given the user has an open Perps position
    When the user selects a close-position order type
    Then only ordinary market and limit order types are accepted

  Scenario: A strategy order fails validation
    Given the Perps controller returns a v12 strategy-order error code
    When Mobile translates the error
    Then the corresponding user-facing message is displayed

Screenshots/Recordings

N/A — no intentional visual changes.

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.

Two JS-thread cost reductions identified via CPU profile analysis:

1. usePerpsLivePositions: add pnlThrottleMs option (default 1000ms)
   Price updates for live PnL were sharing the position subscription's
   throttleMs=0, so setPriceData({ ...prev, ...newPrices }) ran on every
   raw Hyperliquid WS tick, creating short-lived merged objects and
   triggering frequent GC. Separate throttle limits the merge to ≤1/s,
   matching usePerpsLivePrices' own default.

2. useLiveMarketPrices / useLiveCryptoPrices: gate on useIsFocused()
   Polymarket WebSocket callbacks (parseMarketMessageData → JSON.parse)
   were running on the JS main thread during perps sessions because React
   Navigation keeps tab-mounted components alive. Adding useIsFocused()
   stops subscriptions when the user is off the Predict tab and
   re-establishes them instantly on return (WS connection stays alive).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@javiergarciavera
javiergarciavera requested review from a team as code owners August 14, 2026 16:11
@github-actions

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.

@github-actions github-actions Bot added the pr-not-ready-for-e2e Skip E2E and block merging. Remove this label once the PR is ready to run the E2E tests. label Aug 14, 2026
@metamask-ci metamask-ci Bot added team-qa QA team INVALID-PR-TEMPLATE PR's body doesn't match template labels Aug 14, 2026
@github-actions github-actions Bot added size-S risk:medium AI analysis: medium risk labels Aug 14, 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.

Fix All in Cursor

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

Reviewed by Cursor Bugbot for commit 66fc6eb. Configure here.

isMountedRef.current = true;

if (!symbol) {
if (!symbol || !isFocused) {

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.

Focus pause triggers false stream failure

Medium Severity

Gating useLiveCryptoPrices on useIsFocused() stops ticks while Predict tabs stay mounted, but useCryptoUpDownChartData still treats a quiet stream as failure. After the stale timeout it resumes HTTP polling in the background, then marks connectionError, so returning to Predict can show a false disconnect UI until ticks resume.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 66fc6eb. Configure here.

@metamask-ci metamask-ci Bot removed the INVALID-PR-TEMPLATE PR's body doesn't match template label Aug 14, 2026
@javiergarciavera javiergarciavera removed the pr-not-ready-for-e2e Skip E2E and block merging. Remove this label once the PR is ready to run the E2E tests. label Aug 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

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

E2E Test Selection:

The PR contains performance optimization changes to live data streaming hooks in Perps and Predict features:

  1. usePerpsLivePositions.ts: Added pnlThrottleMs option (default: 1000ms) that changes the throttle for price subscription used in PnL calculations from 0ms to 1000ms. This is a behavioral change — live PnL updates in Perps positions will now be throttled at 1s intervals instead of being unthrottled. This needs E2E validation to ensure positions still display correctly with live PnL.

  2. useLiveCryptoPrices.ts and useLiveMarketPrices.ts: Both hooks now use useIsFocused() to gate live price subscriptions — subscriptions are paused when the screen is not focused. This is a behavioral change that could affect price display when navigating back to Predict screens (prices should resume updating on focus). Needs E2E validation.

  3. Test files: Unit tests updated to reflect new defaults and mock useIsFocused.

Tag selection:

  • SmokePerps: Directly tests Perps positions and Add Funds flows — the throttle change affects live PnL display in positions.
  • SmokePredictions: Directly tests Predictions flows — the focus-gating change affects live price updates in market views.
  • SmokeWalletPlatform: Per tag description, Perps and Predictions are sections inside the Trending tab; changes to these views affect Trending/SmokeWalletPlatform.
  • SmokeConfirmations: Per tag descriptions for SmokePerps and SmokePredictions, SmokeConfirmations must also be selected as deposits/transactions are part of those flows.

Performance Test Selection:
The PR directly optimizes performance-sensitive streaming hooks: (1) usePerpsLivePositions now throttles PnL price updates at 1000ms (was 0ms), explicitly reducing GC pressure from frequent price merges — this directly impacts Perps performance scenarios. (2) useLiveCryptoPrices and useLiveMarketPrices now pause subscriptions when screens are unfocused, reducing unnecessary background processing — this directly impacts Predict performance scenarios. Both changes are performance optimizations that should be validated by the corresponding performance test suites.

View GitHub Actions results

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Performance Test Results

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

1 test failed · 5 tests · 1 device

📱 Devices tested (1)

Android: Google Pixel 8 Pro (v14.0)

❌ Failed Tests (1)

🔬 App profiling vs main is included under each failed scenario that has a prior baseline.

@mm-perps-engineering-team

Perps open position and close it

Platform Device Reason Recording
Android Google Pixel 8 Pro (v14.0) no_performance_metrics 📹 Watch

🔬 App profiling check · Current run 31818134286 · Baseline (last run on main (scenario also failing)) run 30897750395 @ 67486d2

⚠️ No green baseline on main — comparing against the latest usable profiling.

Summary: ⚠️ 4 metrics over +10%: CPU max (+3.3 (+17.5%)), Memory avg (+280.64 (+50.5%)), Memory max (+390.95 (+64.2%)), Slow frames (+3.84 (+74.4%))

ℹ️ API calls unavailable: Network logs API error: Bad Request

Full metric table (+10% variance rules)

Disclaimer — allowed variance: a +10% margin over the baseline is permitted.

  • If Current <= Baseline + 10%, treated as acceptable noise.
  • If Current > Baseline + 10%, Current and variance % are highlighted with ⚠️.
Metric Baseline Current Δ
CPU avg 10.44% 7.61% -2.83 (-27.1%)
CPU max 18.83% 22.13% +3.3 (+17.5%) ⚠️
Memory avg 555.64 MB 836.28 MB +280.64 (+50.5%) ⚠️
Memory max 609.03 MB 999.98 MB +390.95 (+64.2%) ⚠️
Slow frames 5.16% 9% +3.84 (+74.4%) ⚠️
Frozen frames 0% 0% 0 (0%)
ANRs 0 0 0 (0%)
Issues 2 2 0 (0%)
Critical issues 1 1 0 (0%)
App size 328.67 MB 329.45 MB +0.78 (+0.2%)
✅ Passed Tests (4)
Test Platform Device Duration Team Recording
Predict Available Balance - Complete Flow Performance Android Google Pixel 8 Pro (v14.0) 0.73s @team-predict 📹 Watch
Predict Deposit - Complete Flow Performance Android Google Pixel 8 Pro (v14.0) 11.67s @team-predict 📹 Watch
Perps add funds Android Google Pixel 8 Pro (v14.0) 9.07s @mm-perps-engineering-team 📹 Watch
Predict Market Details - Complete Flow Performance Android Google Pixel 8 Pro (v14.0) 5.89s @team-predict 📹 Watch

Branch: perf/perps-ws-throttle-and-predict-focus-gate · Build: E2E · Commit: 1327016 · View full run

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

Labels

risk:medium AI analysis: medium risk size-S team-qa QA team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant