Repository navigation
feat(perps-controller): give each exchange its own balance, positions and charts - #11461
Conversation
🛑 Files requiring codeowner reviewTo merge this PR, you'll need to get approvals from the following owners. @MetaMask/perps (52 files)
@MetaMask/core-platform (expand for more) |
8d65ac0 to
d1b138e
Compare
067b22a to
32c9103
Compare
abretonc7s
left a comment
There was a problem hiding this comment.
VERDICT: REQUEST_CHANGES
COMMIT: 2ef9bbc
The fan-out, batch routing and per-venue attribution are solid and well tested. Two confirmed Perps anti-patterns sit in the new aggregation helper, and the pending/unavailable contract is documented three different ways.
| Severity | file:line | Problem | Ask |
|---|---|---|---|
| ❌ Major | packages/perps-controller/src/utils/accountAggregation.ts:71 | Combined sum and RoE duplicate exported aggregateAccountStates, and the decimal fix lands in one copy only. |
Share one helper. |
| ❌ Major | packages/perps-controller/src/utils/accountAggregation.ts:52 | ?? '0' zero-fills a missing venue field; a non-numeric field turns every total into 'NaN'. |
Classify invalid venue data as unavailable. |
| packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:2017 | First-null venue stays pending against the type/README/CHANGELOG wording; an all-pending null wipes perpsBalances. |
Pick one rule; keep pending entries. | |
| packages/perps-controller/src/services/TradingService.ts:2145 | Filtered orderIds cancel hits the same id on both venues. |
Venue-scope ids or pin with a test. | |
| packages/perps-controller/CHANGELOG.md:46 | Breaking change under Added without **BREAKING:**/PR link; intra-PR "Fixed" entries. |
Follow the file's breaking-entry format. | |
| 💬 Nit | packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:2148 | as unknown as PerpsProvider stub. |
Return a no-op unsubscribe directly. |
| 💬 Nit | packages/perps-controller/src/utils/accountAggregation.ts:64 | JSDoc says "PnL-weighted". | Say "margin-weighted". |
Details for agents
| Status | Item | Evidence or gap | Ask |
|---|---|---|---|
| PR description and client plan | The open deposit question (depositRoutes[0]) no longer matches DepositService.#selectDepositRoute. Extension (ref 4c9c2d3c) reads perpsBalances and types accountValue1dAgo as required, but has no row in the client plan. |
Update the description and add an Extension row. | |
| Terminal consumer | No Terminal checkout among the frozen references; the PR's b61ee0d claim is unverified. |
None (reviewer-side gap). |
➖ 10 checklist rules not applicable to this diff; full ledger in the run artifacts: artifacts/review-ledger.md.
Diff scope
| File | Ticket AC or required test | Scope justification or finding |
|---|---|---|
packages/perps-controller/CHANGELOG.md |
TAT-4392 breaking-change process | In scope; release notes for this change. Finding: entry placement/wording (CHANGELOG.md:46). |
packages/perps-controller/README.md |
TAT-4392 documentation | In scope; per-exchange account data section. Finding: pending/unavailable wording disagrees with code (AggregatedPerpsProvider.ts:2017). |
packages/perps-controller/src/PerpsController.ts |
TAT-4392 perpsBalances, stale-response checks, batch routing, deposit attribution | In scope. |
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts |
TAT-4392 per-subscription account cache | In scope. |
packages/perps-controller/src/index.ts |
TAT-4392 new public types | In scope; exports PerpsProviderAccountStateEntry, AccountAggregateMetadata, ClosePositionsTarget. |
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts |
TAT-4392 fan-out reads/streams, batch routing, routes | In scope. Findings at 2017 (minor) and 2148 (nit). |
packages/perps-controller/src/providers/HyperLiquidProvider.ts |
TAT-4392 tagged close targets | In scope; closes only targets naming HyperLiquid. |
packages/perps-controller/src/providers/LighterProvider.ts |
TAT-4392 per-venue account data | In scope; null on rebinding and best-effort crossMarginSummary keep strict aggregate reads from dropping Lighter balances. |
packages/perps-controller/src/services/AccountService.ts |
TAT-4392 withdrawal venue attribution | In scope. |
packages/perps-controller/src/services/DepositService.ts |
TAT-4392 deposit route selection and attribution | In scope. |
packages/perps-controller/src/services/TradingService.ts |
TAT-4392 venue-attributed batch cancel/close and per-venue fees | In scope. Finding at 2145 (minor). |
packages/perps-controller/src/types/index.ts |
TAT-4392 public types | In scope. |
packages/perps-controller/src/utils/accountAggregation.ts |
TAT-4392 combined totals | In scope. Findings at 71 and 52 (major), 64 (nit). |
packages/perps-controller/tests/public-api-types.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.configuration.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.operations.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/services/AccountService.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/services/DepositService.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
packages/perps-controller/tests/src/services/TradingService.test.ts |
Required test for TAT-4392 behavior | In scope; tests the changed controller/provider/service behavior (inspected, not executed). |
tsc-suppressions.json |
Required test: AggregatedPerpsProvider.test.ts type fixes | Sensitive path inspected: removes only the stale TS2304 suppression count for the touched AggregatedPerpsProvider.test.ts (repo lint:tsc:prune workflow). Tightens the baseline; no tooling behavior change; not a scope finding. |
Additional findings
- [minor] packages/perps-controller/src/PerpsController.ts: PR description and client plan are out of date. (1) The "open policy question" says the aggregated deposit flow takes
depositRoutes[0], the first registered venue; the code now picks the explicitproviderId, else the routing default, and fails closed (DepositService.#selectDepositRoute). (2) The client plan lists Mobile and Terminal but not Extension, which consumesperpsBalances(ui/selectors/perps-controller.ts,app/scripts/lib/hyperliquid-deposit/eligibility.ts) and typesaccountValue1dAgoas a required string inui/__mocks__/perps/perps-controller/index.ts:1285(extension ref 4c9c2d3c). Ask: update the description to the shipped deposit behavior and add an Extension row (ticket or "no change needed" with evidence).
| * @param states - Available, valid per-venue account states. | ||
| * @returns The venue-neutral combined totals. | ||
| */ | ||
| export function aggregateAccountTotals( |
There was a problem hiding this comment.
Major. Perps anti-pattern "Copy or port of existing logic". aggregateAccountTotals re-implements the cross-state balance sum and the combined RoE formula (100 × Σ unrealizedPnl ÷ Σ marginUsed, '0' when margin used ≤ 0) that the exported aggregateAccountStates in src/utils/accountUtils.ts:471 already computes for HyperLiquid per-DEX states. The two copies already diverge: the new one is decimal-safe for marginUsed/unrealizedPnl, the old one still uses parseFloat, so the precision fix lands in only one copy. Ask: extract one shared helper for the additive fields + combined RoE (BigNumber throughout) and have both aggregateAccountStates (which then adds its cross-margin merge) and buildAggregatedAccountState call it, so the formula exists once.
There was a problem hiding this comment.
Fixed in b9cbf82. The additive sums and combined RoE now live once in aggregateAccountTotals (src/utils/accountAggregation.ts), BigNumber throughout; aggregateAccountStates in accountUtils.ts calls it and only adds its cross-margin merge, so the parseFloat copy is gone.
| field: (typeof ADDITIVE_FIELDS)[number], | ||
| ): string { | ||
| const total = states.reduce( | ||
| (acc, state) => acc.plus(new BigNumber(state[field] ?? '0')), |
There was a problem hiding this comment.
Major. Perps anti-pattern "Missing data converted to zero". new BigNumber(state[field] ?? '0') turns a missing venue field into a confirmed zero inside the combined balance. The JSDoc above says a value that is not a finite decimal "contributes nothing", but a non-numeric string (for example the '--' fallback aggregateAccountStates returns for an empty HL state set) makes the whole sum NaN, so every top-level total becomes the string 'NaN' while aggregate.status still says the venue is available. Ask: drop the ?? '0', validate that each available venue state has finite decimal values for the additive fields, and classify a venue that fails that check as unavailable (excluded from totals and listed in aggregate.unavailableProviders). Add a test with one venue reporting a non-numeric field.
There was a problem hiding this comment.
Fixed in b9cbf82. ?? '0' is removed. getAccountAggregateMetadata classifies an available venue whose additive fields are missing or non-finite (including '--') as unavailable: it is excluded from the totals and listed in aggregate.unavailableProviders. Covered in tests/src/utils/accountAggregation.test.ts.
| // Reported before and its latest update was null: no current | ||
| // balance is known for this venue. Never seen: it simply has | ||
| // not reported yet. | ||
| return lastReport.has(providerId) |
There was a problem hiding this comment.
Minor. The null/pending contract is documented three different ways and the controller undoes part of it. Code: a venue whose first update is null stays pending, because lastReport only remembers venues that reported data (test "keeps a pending venue pending..." pins this). Docs: PerpsProviderAccountStateEntry JSDoc (src/types/index.ts:1006), CHANGELOG line 75 and the PR description say a venue whose latest update was null is unavailable; README line 107 says a venue that has not reported yet is unavailable and never mentions pending. Separately, if the first emission of the stream is a null (all venues pending), buildAggregatedAccountState returns null and PerpsController sets perpsBalances = {} (src/PerpsController.ts:7642), which wipes the persisted entries the pending status exists to protect. Ask: pick one rule (for example "null before any data is unavailable", or keep pending and say so), make the type JSDoc, README and CHANGELOG match, and keep pending venues' entries in the all-pending null path (only clear entries of venues that were explicitly unavailable). Add a controller test where the first update is a null.
There was a problem hiding this comment.
Fixed in b9cbf82. One rule everywhere: before a venue's first snapshot it is pending (including on null); after a snapshot, null makes it unavailable. The type JSDoc, README and CHANGELOG now say this. The stream callback's second argument carries AccountAggregateMetadata even when the combined state is null, and PerpsController removes only aggregate.unavailableProviders entries in that case, so pending venues keep their persisted balances. Controller test: "preserves pending balances when the first account emission is null".
| } | ||
|
|
||
| // Use batch cancel if provider supports it | ||
| // Use batch cancel if provider supports it. Each target keeps the |
There was a problem hiding this comment.
Minor. Entity ownership: filtered cancelOrders({ orderIds }) selects orders with params.orderIds?.includes(order.orderId) over the aggregated order list, so if HyperLiquid and Lighter both hold an order with the same id, a filtered cancel of one also cancels the other. Each matched order keeps its own venue tag, so both venues receive a cancel. The PR states duplicate order ids across venues are never conflated, and the Perps rule asks for a colliding-id test; none exists (the mixed-venue tests use distinct ids). Ask: accept venue-scoped ids for a filtered cancel (for example orders: { orderId, providerId }[], or reuse BatchCancelOrdersParams) and match on both fields, or add a test that pins and documents the cross-venue behavior.
There was a problem hiding this comment.
Fixed in b9cbf82 and ef86cb0. CancelOrdersParams.orders takes { orderId, providerId } targets matched on both fields, and a bare orderIds (or symbols) filter is refused with PROVIDER_ROUTE_REQUIRED while more than one venue is registered (getUnroutedCancelOrdersRefusal), so a colliding ID can no longer cancel the other venue's order. Colliding-ID tests use the same ID on both venues.
| - Hyperliquid and Lighter implement both on testnet and mainnet with the same `PublicTrade` shape: `{ id, symbol, price, size, side, timestamp, txHash?, providerId }`, where `side` is the aggressor's (`buy` or `sell`). `AggregatedPerpsProvider` routes to `providerId`, else the default provider. Like `subscribeToCandles`, an unrouted stream moves to the new default when `setDefaultProvider` changes it, and an unrouted read resolves to `[]` if the default changes before the venue answers | ||
| - New optional `PerpsProvider.getPublicTrades` and `PerpsProvider.subscribeToPublicTrades` members, and types `PublicTrade`, `GetPublicTradesParams`, `SubscribePublicTradesParams`, `PerpsControllerGetPublicTradesAction` and `PerpsControllerSubscribeToPublicTradesAction` | ||
| - Subpath exports `@metamask/perps-controller/constants/lighterConfig` and `@metamask/perps-controller/utils/*` also expose `LIGHTER_RECENT_TRADES_MAX_LIMIT`, `buildPublicTrade`, `sortPublicTradesNewestFirst`, `PublicTradeFields`, `adaptPublicTradesFromHyperLiquid` and `adaptPublicTradesFromLighter` | ||
| - Add per-exchange account data to aggregated mode: `getAccountState` and `subscribeToAccount` query every enabled venue and expose each venue's state separately plus a correctly identified combined total (**BREAKING**: the aggregated result shape changed) |
There was a problem hiding this comment.
Minor. Release metadata does not follow the repo changelog conventions. (1) The breaking aggregated AccountState change sits under ### Added with a trailing "(BREAKING: ...)" instead of a ### Changed entry starting with **BREAKING:**, which is how every other breaking entry in this file is written (e.g. line 66). (2) Making perpsBalances[*].accountValue1dAgo optional is a type-breaking change for state readers and is not marked breaking. (3) The new Added entries at lines 46-62 have no PR link. (4) Fixed entries at lines 75, 85, 86, 87 and 89 describe fixes to behavior that only exists in this unreleased PR (pending vs unavailable, tagged targets, thrown multi-venue close, first enumerated deposit route, one-venue fallback vs combined snapshot); released consumers never saw those bugs. Ask: move the breaking items to ### Changed with the **BREAKING:** prefix and the PR link, mark the accountValue1dAgo change breaking, and fold the intra-PR "Fixed" entries into the Added/Changed descriptions.
There was a problem hiding this comment.
Fixed in b9cbf82 (refined in later commits). Breaking items are under ### Changed with the **BREAKING:** prefix and PR links, accountValue1dAgo optionality has its own BREAKING entry, every Unreleased entry links its PR, and the intra-PR "Fixed" entries were folded into the Added/Changed descriptions.
| subscribeToCandles: () => () => undefined, | ||
| subscribeToOICaps: () => () => undefined, | ||
| subscribeToOrderBook: () => () => undefined, | ||
| } as unknown as PerpsProvider; |
There was a problem hiding this comment.
Nit. #resolveExplicitStreamRoute builds a stub with as unknown as PerpsProvider for the unregistered-route case. A double assertion hides the stub's real type. Ask: have the three subscribe methods return a no-op unsubscribe directly when the route is missing (e.g. a #reportMissingStreamRoute(params): (() => void) | undefined helper), without the cast.
There was a problem hiding this comment.
| * Additive USD fields are decimal-summed. `returnOnEquity` is a rate, not a | ||
| * balance: both venues report account-level RoE in percentage points | ||
| * (unrealized PnL relative to margin used), so the combined rate is | ||
| * `100 x sum(unrealizedPnl) / sum(marginUsed)` — PnL-weighted, never summed |
There was a problem hiding this comment.
Nit. JSDoc calls the combined RoE "PnL-weighted"; 100 × Σ unrealizedPnl ÷ Σ marginUsed is margin-weighted, as the README and CHANGELOG say. Ask: change the wording to "margin-weighted".
There was a problem hiding this comment.
Fixed in b9cbf82. The JSDoc now says margin-weighted, matching the README and CHANGELOG.
|
Heads up for when this is bumped in metamask-mobile. Our two-exchange test presets (metamask-mobile#39846) have one line that will make It's the line marked
Nothing else should break. If |
65c4337 to
706991b
Compare
abretonc7s
left a comment
There was a problem hiding this comment.
VERDICT: REQUEST_CHANGES
COMMIT: 776b9a4
The missing helper modules are now committed with tests, and the changelog is fixed. One major problem remains: the aggregated account total can report complete while HyperLiquid has returned a partial balance.
Since last review: ✅ resolved TradingService.ts:50 (missing cancelOrders/feeSupport modules, now with unit tests plus the shared resolveCloseSelection); ✅ resolved CHANGELOG.md:89 (intra-PR fixes folded into Added/Changed); ❌ still open AggregatedPerpsProvider.ts:711; README.md:170 and the PR description; 💬 still open PerpsController.ts:4381, :7580.
| Severity | file:line | Problem | Ask |
|---|---|---|---|
| ❌ Major | packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:711 | HyperLiquid ignores throwOnUnavailable for account state. A failed HIP-3 DEX or spot read is labeled available, and the total is reported as complete. |
Make HyperLiquid honor strict account reads, or mark that venue partial or unavailable. Add a test. |
| packages/perps-controller/README.md:170 | The README says balance entries record accountAddress/isTestnet and carry accountValue1dAgo forward; the code does neither. The targets JSDoc also omits that targets take precedence over closeAll. |
Make the docs match the code. | |
| PR description | The description says null makes a venue unavailable and that accountValue1dAgo is carried forward. It still lists the depositRoutes[0] question as open, and its evidence predates the current head. |
Update the description and re-record the evidence on 776b9a4. | |
| 💬 Nit | packages/perps-controller/src/PerpsController.ts:4381 | The deposit venue-attribution comment repeats the comment at :4362. | Keep one. |
| 💬 Nit | packages/perps-controller/src/PerpsController.ts:7580 | The pending comment is broken mid-sentence across lines. |
Reflow it. |
Details for agents
| Status | Item | Evidence or gap | Ask |
|---|---|---|---|
| Runtime and test execution | Static review only: no build, tsc or vitest run on 776b9a4. |
Supply CI for this head. | |
| Terminal consumer | No Terminal reference checkout was supplied. | — | |
| ✅ Delta check | resolveCancelSelection, getUnroutedCancelOrdersRefusal, resolveCloseSelection, hasFeeSetter |
Each matches the inline logic it replaces. Close selection is now one exhaustive selector shared by the controller guard, aggregated execution, HyperLiquid execution, fee pricing and the per-position fallback. | — |
➖ Rules not applicable to this diff (UI, i18n, Pro mode, MetaMetrics, navigation, embedded signer, formatter, multi-sig, unified account) are recorded in artifacts/review-ledger.md.
Diff scope
| File | Ticket AC or required test | Scope justification or finding |
|---|---|---|
packages/perps-controller/CHANGELOG.md |
Ticket: breaking-change process and changelog for consumers | In scope. Prior finding resolved: intra-PR fixes are folded into Added/Changed. The remaining Fixed entries describe 24.0.0 behavior (non-finite skip in batch-close pricing, Lighter wallet scope, HIP-3 cancel discovery, Lighter cancel fallback, decimals, empty filters, Lighter zero emission). |
packages/perps-controller/README.md |
Ticket: "Per-exchange account data" README section named in the PR | In scope. FINDING (minor, still open): provenance and carry-forward claims contradict code. |
packages/perps-controller/src/PerpsController.ts |
Ticket: perpsBalances writes, REST validation, preload buckets, setDefaultProvider, batch routing, deposit attribution | In scope. Delta adds resolveCloseSelection for the legacy symbols refusal. Two comment nits still open. |
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts |
Ticket: per-subscription account venue cache and fan-out | In scope; unchanged in delta. |
packages/perps-controller/src/errors.ts |
Ticket: venue-attributed batch discovery (OrderDiscoveryError) | In scope; unchanged in delta. |
packages/perps-controller/src/index.ts |
Ticket: new package exports | In scope; unchanged in delta. |
packages/perps-controller/src/perpsErrorCodes.ts |
Ticket: batch routing results (BATCH_INCOMPLETE) | In scope; unchanged in delta. |
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts |
Ticket: aggregated account reads/streams, batch routing, venue streams, money-movement routes | In scope. Delta uses resolveCloseSelection with unchanged semantics. MAJOR (still open): the strict account read is not honored by HyperLiquid. |
packages/perps-controller/src/providers/HyperLiquidProvider.ts |
Ticket: venue-attributed batch close targets and strict discovery | In scope. Delta replaces the inline target/symbol selection with resolveCloseSelection; behavior is equivalent. |
packages/perps-controller/src/providers/LighterProvider.ts |
Ticket: per-venue account data and strict discovery | In scope; unchanged in delta. |
packages/perps-controller/src/services/AccountService.ts |
Ticket: withdrawal records capture initiating venue | In scope; unchanged in delta. |
packages/perps-controller/src/services/DepositService.ts |
Ticket: deposit records/routes carry venue identity | In scope; unchanged in delta. |
packages/perps-controller/src/services/RewardsIntegrationService.ts |
Ticket: per-venue batch close fee resolution | In scope; unchanged in delta. |
packages/perps-controller/src/services/ServiceContext.ts |
Ticket: strict discovery for batch cancel | In scope; unchanged in delta. |
packages/perps-controller/src/services/TradingService.ts |
Ticket: venue-attributed cancelOrders/closePositions and per-venue fees | In scope. Blocker resolved: imports now resolve. Delta switches fee routing and per-position fallback to exhaustive resolveCloseSelection branches with equivalent semantics. |
packages/perps-controller/src/types/index.ts |
Ticket: AccountState providerStates/aggregate, batch and stream providerId types | In scope. Minor: targets JSDoc precedence wording (see README finding). |
packages/perps-controller/src/utils/accountAggregation.ts |
Ticket: decimal-safe combined totals and completeness metadata | In scope; unchanged in delta. |
packages/perps-controller/src/utils/accountUtils.ts |
Ticket: decimal-safe totals shared with per-DEX aggregation | In scope; unchanged in delta. |
packages/perps-controller/src/utils/cancelOrders.ts |
Ticket: batch routing (cancel selection and legacy-filter refusal); resolves prior blocker | In scope. One selector shared by the controller guard and TradingService; empty filters select none; legacy orderIds/symbols are refused when more than one venue is registered (fails closed for an aggregated wrapper with unknown membership). |
packages/perps-controller/src/utils/closePositions.ts |
Ticket: batch routing (close selection precedence) | In scope. Deduplicates four inline copies of targets > closeAll > symbols > all (controller, aggregated, HyperLiquid, TradingService). |
packages/perps-controller/src/utils/feeSupport.ts |
Ticket: per-venue batch close fee resolution; resolves prior blocker | In scope. Shared fee-setter check used by the aggregated provider and TradingService. |
packages/perps-controller/src/utils/standaloneInfoClient.ts |
Ticket: strict discovery for standalone reads | In scope; unchanged in delta. |
packages/perps-controller/tests/public-api-types.ts |
Required test: consumer-style export contracts | In scope; unchanged in delta. |
packages/perps-controller/tests/src/PerpsController.configuration.test.ts |
Required test: balances cleared on network toggle | In scope. |
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts |
Required test: default change keeps the aggregate; stale responses; mixed-venue batches | In scope. |
packages/perps-controller/tests/src/PerpsController.lifecycle.test.ts |
Required test: balances cleared on provider selection change | In scope. |
packages/perps-controller/tests/src/PerpsController.operations.test.ts |
Required test: deposit venue forwarding and attribution | In scope. |
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts |
Required test: perpsBalances per venue from stream; pending/unavailable; preload buckets | In scope. |
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.discovery.test.ts |
Required test: strict discovery, account scope, cancel discovery failures | In scope. |
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts |
Required test: aggregated account reads, mixed-venue batch routing, explicit streams | In scope. Gap: no HyperLiquid partial-DEX account-state case (major finding). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.history.test.ts |
Required test: HyperLiquid strict discovery and partial HIP-3 orders | In scope. |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.standalone.test.ts |
Required test: standalone strict reads | In scope. |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts |
Required test: tagged close targets on HyperLiquid | In scope. |
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts |
Required test: Lighter fixture adjustments | In scope. |
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts |
Required test: Lighter account scope and best-effort summary | In scope. |
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts |
Required test: Lighter null emission on deselect | In scope. |
packages/perps-controller/tests/src/services/AccountService.test.ts |
Required test: withdrawal venue attribution | In scope. |
packages/perps-controller/tests/src/services/DepositService.test.ts |
Required test: deposit route selection | In scope. |
packages/perps-controller/tests/src/services/RewardsIntegrationService.test.ts |
Required test: reserved subscription allowance | In scope. |
packages/perps-controller/tests/src/services/TradingService.test.ts |
Required test: cancel selection, per-venue fee pricing, tagged closes | In scope. |
packages/perps-controller/tests/src/utils/accountAggregation.test.ts |
Required test: totals, RoE and metadata | In scope. |
packages/perps-controller/tests/src/utils/accountUtils.test.ts |
Required test: exact decimals in aggregateAccountStates | In scope. |
packages/perps-controller/tests/src/utils/cancelOrders.test.ts |
Required test: direct unit tests for cancel selection and refusal (asked in prior blocker) | In scope. Covers precedence, empty filters, multi-venue refusal, single-venue allowance and fail-closed unknown membership. |
packages/perps-controller/tests/src/utils/closePositions.test.ts |
Required test: close selection precedence | In scope. Covers empty targets/symbols, closeAll over symbols, and targets over closeAll. |
packages/perps-controller/tests/src/utils/feeSupport.test.ts |
Required test: fee-setter detection (asked in prior blocker) | In scope. |
tsc-suppressions.json |
Required test hygiene: PR description evidence names tsc-suppressions.json losing entries after the test-file type fixes | Unchanged in delta. Removes only the TS2304 baseline for the in-scope AggregatedPerpsProvider.test.ts and adds no suppression; pruning is required by lint:tsc:check, not unauthorized tooling churn. |
Additional findings
-
[major] packages/perps-controller/src/providers/AggregatedPerpsProvider.ts:711: Still open from the previous round; the 776b9a4 delta does not touch
HyperLiquidProvider.getAccountState. This is Perps anti-pattern "Unknown treated as confirmed zero" in the new completeness contract. The aggregated read forcesthrowOnUnavailable: trueon the assumption that only a genuine rejection becomesunavailable(comment above line 711), butHyperLiquidProvider.getAccountStatenever readsthrowOnUnavailable. When one HIP-3 DEX'sclearinghouseStatefails, it logs "partial DEX failures" and returns the reachable DEXs' sum. WhenspotClearinghouseStateis rejected, it returns perps-only totals without spot USDC collateral. That partial snapshot becomes{ status: 'available' }.getAccountAggregateMetadatathen reportsstatus: 'complete', and the controller writes it intoperpsBalances.hyperliquidas the live venue balance. The README and PR say apartialtotal must never be shown as the complete portfolio; this path labels a known-incomplete total as complete. Ask: make HyperLiquid honorthrowOnUnavailablefor account state on DEX or spot failure (or return a partial signal the aggregator maps tounavailable/partial). Add an AggregatedPerpsProvider test where HyperLiquid has one failed DEX and assert the aggregate is notcomplete. -
[minor] packages/perps-controller/README.md:170: Still open (README is unchanged in this delta). README lines 170-174 say each
perpsBalancesentry "records theaccountAddressandisTestnetit was observed for; an optionalaccountValue1dAgocarries forward only within that same account and network".PerpsController'swriteBalancewrites onlytotalBalance,unrealizedPnlandlastUpdated, and replaces the whole entry. There is no provenance and no carry-forward; the test 'writes live balances without carrying stale history or adding provenance' asserts exactly that, and the CHANGELOG says "Live updates do not carry historical values forward". Lines 167-168 ("Pending venues retain their persisted entries and history") overstate this as well. TheClosePositionsParams.targetsJSDoc (types/index.ts:1131-1134) also says targets take precedence oversymbols, while the newresolveCloseSelection(utils/closePositions.ts) gives non-empty targets precedence overcloseAlltoo. Ask: remove the provenance and carry-forward sentences from the README and state thataccountValue1dAgois not populated by live updates. Update thetargetsJSDoc to say targets win over bothsymbolsandcloseAll. -
[minor] PR description: Still open: the PR description makes claims the current head contradicts. (1) "A venue whose update is
nullis explicitly unavailable — its previous value is not kept": the stream keeps a venuependingonnullbefore its first snapshot and retains its persisted balance (AggregatedPerpsProvidersubscribeToAccount; PerpsController pending branch; CHANGELOG says the same). (2) "accountValue1dAgo... is only carried forward from a real prior entry": nothing carries it forward. (3) The open question aboutdepositRoutes[0]is stale:DepositService.#selectDepositRoutenow selects the explicitproviderIdor the routing default and fails closed otherwise. (4) The Evidence section (7,067 tests, build andlint:tsc:checkclean) predates the last two commits, which added three utility modules and three test files. The description also omits the stream callback's second argument andpendingProviders. Ask: update the description to the current contract, and re-run and re-record the evidence on 776b9a4. -
[nit] packages/perps-controller/src/PerpsController.ts:4381: Still open: the deposit venue-attribution comment at lines 4381-4383 repeats the comment at lines 4362-4364 nearly word for word, and the
prepareTransactioncall carries a third copy just above. Ask: keep one short comment atdepositVenueId. -
[nit] packages/perps-controller/src/PerpsController.ts:7580: Still open: the
pendingbranch comment is broken mid-sentence ("so its persisted" / "entry stays" / "until the venue reports a snapshot.", lines 7578-7581), which looks like a leftover edit. Ask: reflow it into one or two lines.
776b9a4 to
d89bfef
Compare
abretonc7s
left a comment
There was a problem hiding this comment.
VERDICT: APPROVE
COMMIT: 21f7b82
Each venue now gets its own account data, batch routing, stream routes and money-movement attribution. Venue identity survives every path I traced, and missing data never becomes zero. Two nits; nothing blocking.
| Severity | file:line | Problem | Ask |
|---|---|---|---|
| Nit | packages/perps-controller/src/PerpsController.ts:4365 | The direct-mode deposit venue is read from state after two awaits, but the comment says it is captured first. | Derive it from the provider that prepared the route, as withdrawals do. |
Details for agents
| Status | Item | Evidence or gap | Ask |
|---|---|---|---|
| Nit | PR description export inventory | Omits the root export OrderDiscoveryError, BATCH_INCOMPLETE and the /utils/accountAggregation subpath. The CHANGELOG lists all three. |
Add them to "Breaking package compatibility". |
| Test run | The claim of 7,660 passing tests at 21f7b82 was not reproduced. All 25 changed test files were read, none were run. | None (reviewer-side). | |
| Terminal consumer | No Terminal reference checkout was supplied, so the "no dependency at b61ee0d" note is unverified. | None (reviewer-side). | |
| HyperLiquid stream completeness at runtime | requireCompleteAccount assumes every configured DEX publishes a slice, even one where the user holds nothing. This holds in unit tests but was not checked against a live venue. |
Cover it in TAT-4407 QA. |
Diff scope: all 51 files serve TAT-4392 or its tests. tsc-suppressions.json drops one stale TS2304 entry, which lint:tsc:check requires after the test fix (scripts/lib/tsc-suppressions.ts:352). Mobile 33b5bb61 and Extension 46c84f23 consumers match the CHANGELOG BREAKING list and the ticketed client plan.
➖ 11 rules not applicable to this diff; full ledger in the run artifacts: artifacts/review-ledger.md.
Diff scope
| File | Ticket AC or required test | Scope justification or finding |
|---|---|---|
packages/perps-controller/CHANGELOG.md |
TAT-4392 consumer communication | Unreleased entries for the BREAKING account, route, batch and default-provider changes; released sections untouched. |
packages/perps-controller/README.md |
TAT-4392 documentation | Adds the 'Per-exchange account data' consumer section. |
packages/perps-controller/docs/architecture.md |
TAT-4392 documentation | Provider table, balance contract, error code count (105, verified) and OrderDiscoveryError updated. |
packages/perps-controller/src/PerpsController.ts |
TAT-4392: per-venue balance, positions and charts | Writes perpsBalances per venue, account-scoped stream ownership, isCurrent for aggregate results, preload bucketing, batch refusal narrowing, deposit venue attribution. Nit at line 4365. |
packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts |
TAT-4392: per-venue balance, positions and charts | Per-subscription account cache, onError isolation, accountId/requireCompleteAccount forwarding. |
packages/perps-controller/src/errors.ts |
TAT-4392: per-venue balance, positions and charts | OrderDiscoveryError for strict open-order discovery used by venue-attributed cancel. |
packages/perps-controller/src/index.ts |
TAT-4392: per-venue balance, positions and charts | Exports the new account entry/metadata types, ClosePositionsTarget and OrderDiscoveryError. |
packages/perps-controller/src/perpsErrorCodes.ts |
TAT-4392: per-venue balance, positions and charts | Adds BATCH_INCOMPLETE for merged multi-venue batches. |
packages/perps-controller/src/providers/AggregatedPerpsProvider.ts |
TAT-4392: per-venue balance, positions and charts | Account fan-out and stream, venue-grouped cancel/close, explicit stream routes, per-venue routes and fee scope. |
packages/perps-controller/src/providers/HyperLiquidProvider.ts |
TAT-4392: per-venue balance, positions and charts | throwOnUnavailable for account/positions/orders and tagged close targets so aggregation can mark HL unavailable. |
packages/perps-controller/src/providers/LighterProvider.ts |
TAT-4392: per-venue balance, positions and charts | Account scope guard, null on wallet rebind, strict discovery, best-effort cross-margin summary. |
packages/perps-controller/src/services/AccountService.ts |
TAT-4392: per-venue balance, positions and charts | Withdrawal record venue attribution. |
packages/perps-controller/src/services/DepositService.ts |
TAT-4392: per-venue balance, positions and charts | Deposit route selection by explicit venue or routing default; fails closed. |
packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts |
TAT-4392: per-venue balance, positions and charts | requireCompleteAccount gating and completeness in the account hash. |
packages/perps-controller/src/services/RewardsIntegrationService.ts |
TAT-4392: per-venue balance, positions and charts | Reserved subscription notional so fan-out venues cannot spend the same allowance. |
packages/perps-controller/src/services/ServiceContext.ts |
TAT-4392: per-venue balance, positions and charts | getOpenOrders accepts params for strict discovery. |
packages/perps-controller/src/services/TradingService.ts |
TAT-4392: per-venue balance, positions and charts | Selection helpers, discovery failure accounting, per-venue fee routes for batch close. |
packages/perps-controller/src/types/index.ts |
TAT-4392: per-venue balance, positions and charts | New optional contract fields and types for per-venue data and routing. |
packages/perps-controller/src/utils/accountAggregation.ts |
TAT-4392: per-venue balance, positions and charts | Decimal-safe combined totals and completeness metadata. |
packages/perps-controller/src/utils/accountUtils.ts |
TAT-4392: per-venue balance, positions and charts | getCaipAccountAddress and shared decimal totals in aggregateAccountStates. |
packages/perps-controller/src/utils/cancelOrders.ts |
TAT-4392: per-venue balance, positions and charts | Shared cancel selection and unrouted refusal used by controller and TradingService. |
packages/perps-controller/src/utils/closePositions.ts |
TAT-4392: per-venue balance, positions and charts | Shared close selection used by controller, TradingService and both providers. |
packages/perps-controller/src/utils/feeSupport.ts |
TAT-4392: per-venue balance, positions and charts | hasFeeSetter shared by aggregated provider and TradingService. |
packages/perps-controller/src/utils/standaloneInfoClient.ts |
TAT-4392: per-venue balance, positions and charts | Strict standalone DEX reads for throwOnUnavailable. |
packages/perps-controller/tests/public-api-types.ts |
Required test: consumer-style export assertions | Type assertions through the package entrypoint for the new exports. |
packages/perps-controller/tests/src/PerpsController.configuration.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.default-provider.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.lifecycle.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.operations.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/aggregation/SubscriptionMultiplexer.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.discovery.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.error-handling.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.history.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.standalone.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/HyperLiquidProvider.trading.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.order-validation.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/services/AccountService.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/services/DepositService.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.cache.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/services/RewardsIntegrationService.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/services/TradingService.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/utils/accountAggregation.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/utils/accountUtils.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/utils/cancelOrders.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/utils/closePositions.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
packages/perps-controller/tests/src/utils/feeSupport.test.ts |
Required test | Covers the changed behavior in the matching source file (inspected, not executed). |
tsc-suppressions.json |
Required by test change | Drops one stale TS2304 suppression for AggregatedPerpsProvider.test.ts; scripts/lib/tsc-suppressions.ts:352 fails lint:tsc:check on stale suppressions, so the test edit forces it. Not a tooling-config change. |
Additional findings
- [nit] packages/perps-controller/CHANGELOG.md: The PR description's 'Breaking package compatibility' export inventory lists
PerpsProviderAccountStateEntry,AccountAggregateMetadata,ClosePositionsTargetand three utils subpaths, but omits the new root exportOrderDiscoveryError, theBATCH_INCOMPLETEcode and the/utils/accountAggregationsubpath. The CHANGELOG has all of them. Ask: add them to the PR description so the consumer inventory matches the package.
| // The chosen route names the venue in aggregated mode; in direct mode | ||
| // the active provider is the venue. Captured before any asynchronous | ||
| // work, never relabeled later. | ||
| const directDepositVenue = |
There was a problem hiding this comment.
Nit. The direct-mode deposit venue comes from this.state.activeProvider after await #getActiveProviderWhenReady() and await prepareTransaction(), while the comment says it is captured before any asynchronous work. Withdrawal attribution (AccountService.ts) derives the venue from the provider instance instead. If the active provider changes in that window, the record names a venue that did not prepare the route. Ask: return route.providerId ?? provider.protocolId (narrowed with isPerpsProviderType) from DepositService.prepareTransaction, matching the withdrawal path, or fix the comment.
There was a problem hiding this comment.
Fixed in 8a0b597. DepositService.prepareTransaction now resolves route.providerId ?? provider.protocolId, narrowed with isPerpsProviderType, and the controller uses that result without falling back to mutable state.activeProvider. Updated the comment and added regression coverage for provider changes during preparation and unresolved venues.
21f7b82 to
412c779
Compare
…ask#39846) ## **Description** Adds ready-made component-view presets for a user with Hyperliquid and Lighter both enabled ([TAT-4387](https://consensyssoftware.atlassian.net/browse/TAT-4387)), so the Lighter UI tickets don't each build aggregated mode by hand. `perpsTwoExchangeState(scenario)` returns `{ overrides, streamOverrides }` for any perps renderer. Scenarios: `bothFunded`, `oneFunded`, `sameMarketOnBoth` and `lighterDown`. `withLighterBuildEnabled()` sets and restores the Lighter env var the screens also need. The aggregated test in `PerpsBalanceOrderView.view.test.tsx` now uses `sameMarketOnBoth`, and the presets are documented in `docs/testing/component-view-tests.md`. The scenarios are synthetic fixtures built from fields the installed `perps-controller` supports, not snapshots of what it emits. [core#11461](MetaMask/core#11461) (TAT-4392) adds per-exchange account state, which will replace how "Lighter down" is modeled here. A `@ts-expect-error` in `perpsTwoExchangePresets.ts` makes `yarn lint:tsc` fail when the package is bumped, so the presets get updated then. ## Test layer placement Unit for the presets (`perpsTwoExchangePresets.test.ts`). Component view for the migrated `PerpsBalanceOrderView` test. ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: [TAT-4387](https://consensyssoftware.atlassian.net/browse/TAT-4387) Related: [TAT-4392](https://consensyssoftware.atlassian.net/browse/TAT-4392) ## **Manual testing steps** N/A — test-only change. ## **Screenshots/Recordings** ### **Before** N/A — no UI changes. ### **After** N/A — no UI changes. ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile Coding Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I've included tests if applicable - [x] I've documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I've applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. #### Performance checks (if applicable) N/A, test-only change with no runtime code. - [x] I've tested on Android - Ideally on a mid-range device; emulator is acceptable - [x] I've tested with a power user scenario - Use these [power-user SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93) to import wallets with many accounts and tokens - [x] I've instrumented key operations with Sentry traces for production performance metrics - See [`trace()`](/app/util/trace.ts) for usage and [`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274) for an example For performance guidelines and tooling, see the [Performance Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers). ## **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. [TAT-4387]: https://consensyssoftware.atlassian.net/browse/TAT-4387?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ [TAT-4387]: https://consensyssoftware.atlassian.net/browse/TAT-4387?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Test-only fixtures and documentation; no production runtime or security-sensitive paths change. > > **Overview** > Introduces shared **two-exchange** component-view fixtures so Perps tests can render Hyperliquid + Lighter in aggregated mode without hand-building engine and stream state. > > `perpsTwoExchangeState(scenario)` returns `{ overrides, streamOverrides }` for `bothFunded`, `oneFunded`, `sameMarketOnBoth`, and `lighterDown`, including remote Lighter feature flags and combined balances. `withLighterBuildEnabled()` toggles `MM_PERPS_LIGHTER_PROVIDER_ENABLED` per describe block. Unit tests cover preset math and flag restore behavior; `PerpsBalanceOrderView.view.test` uses `sameMarketOnBoth` for the aggregated Lighter market case. Docs and `babel.config.tests.js` register the new helpers/presets. A `@ts-expect-error` on `AccountState['providerStates']` is meant to force preset updates when core ships per-exchange availability. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 88bbe4a. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
Nice work on the fan-out. One thing in |
<!-- Thanks for your contribution! Take a moment to answer these questions so that reviewers have the information they need to properly understand your changes: * What is the current state of things and why does it need to change? * What is the solution your changes offer and how does it work? * Are there any changes whose purpose might not obvious to those unfamiliar with the domain? * If your primary goal was to update one package but you found you had to update another one along the way, why did you do so? * If you had to upgrade a dependency, why did you do so? --> <!-- Are there any issues that this pull request is tied to? Are there other links that reviewers should consult to understand these changes better? Are there client or consumer pull requests to adopt any breaking changes? For example: * Fixes #12345 * Related to #67890 --> - [ ] I've updated the test suite for new or updated code as appropriate - [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate - [ ] I've communicated my changes to consumers by [updating changelogs for packages I've changed](https://github.com/MetaMask/core/tree/main/docs/processes/updating-changelogs.md) - [ ] I've introduced [breaking changes](https://github.com/MetaMask/core/tree/main/docs/processes/breaking-changes.md) in this PR and have prepared draft pull requests for clients and consumer packages to resolve them <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Breaking account subscription callback and `perpsBalances` semantics affect multi-venue portfolio UI; cancel-order filtering changes prevent accidental mass cancels but alter batch behavior. > > **Overview** > **Multi-venue account streams and aggregation** now distinguish **pending** venues (no first snapshot yet, including an initial `null`) from **unavailable** ones, and reject venues whose additive balance fields are missing or non-finite instead of folding them into combined totals. `subscribeToAccount` callbacks receive an optional second **`AccountAggregateMetadata`** argument even when `account` is `null`, and **`PerpsController`** only clears `perpsBalances` for explicitly unavailable venues on a null aggregate—pending venues keep persisted entries and `accountValue1dAgo` history. Aggregation math in **`accountAggregation`** / **`accountUtils`** is centralized on decimal-safe **`aggregateAccountTotals`** with margin-weighted combined RoE. > > **Order cancellation** adds **`CancelOrdersParams.orders`** (`{ orderId, providerId }`) so colliding IDs across venues cancel only the intended venue; legacy **`orderIds`** still match every venue. Empty **`orders`**, **`orderIds`**, or **`symbols`** no longer fall through to cancel-all. > > **Stream routing**: an explicit but unregistered **`providerId`** on candles/OI/order book subscriptions reports via **`onError`** and returns a no-op cleanup instead of subscribing through a stub provider. Cancel results can include **`providerId`** per item. Changelog/README and type-level tests reflect the breaking account callback and balance semantics. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3a5a66d. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
Co-authored-by: Cursor <cursoragent@cursor.com>
- Commit the cancel-selection and fee-setter helpers that 1e20226 imports but never added, with their tests. - Add resolveCloseSelection so targets > closeAll > symbols precedence lives in one place instead of seven. - Fold Unreleased "Fixed" entries for behaviour that never shipped in 24.0.0 into the Added/Changed entries for the same feature, and list PerpsProvider.getProviderIds under Added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oc, and PR description match the code
…e targets, review fixes - Aggregated account streams request requireCompleteAccount; HyperLiquid emits null until every configured DEX and the spot balance have loaded, so a failed DEX subscription keeps the aggregate partial. - An empty closePositions targets list closes nothing instead of falling through to close-all. - Account streams for a non-selected accountId no longer write or delete perpsBalances entries. - An unregistered explicit stream route reports a bare PROVIDER_NOT_FOUND. - Restore the released 24.1.0 changelog section to main and move this PR's entries back under Unreleased. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… without casts Pass the stream's onError handler to #resolveExplicitStreamRoute instead of a params union checked with an `in` guard, and annotate the validated aggregate entries' return type instead of `as const`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s out of live account state - A HyperLiquid account is complete for `requireCompleteAccount` only when every configured DEX has published on the current connection. Per-DEX slices survive a reconnect, so the cached pre-reconnect account is no longer replayed or emitted as the venue's full live balance. - A controller account stream for an explicit `accountId` other than the selected account now only reaches its own callback: it neither writes nor clears `accountState`, `lastUpdateTimestamp` or `perpsBalances`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ting in architecture Update the AggregatedPerpsProvider row for fan-out account reads and streams, per-venue money-movement routes, venue-grouped batch cancel and close, and explicit stream routes. Add providerStates and aggregate to the AccountState balance contract, and record BATCH_INCOMPLETE and OrderDiscoveryError under Errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and validate account ids - HyperLiquid strict open-order discovery that only partly succeeds now adapts the orders it did read with the same position lookup as a complete read, so a whole-position TP/SL in `OrderDiscoveryError.orders` reports the position size instead of 0. - Account-scope checks parse `accountId` as CAIP-10 instead of taking the last `:` segment. A bare address or an id with extra segments no longer passes as the selected wallet: the controller does not let such a stream write selected-account state, and Lighter rejects it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…opens, block old streams from writing or clearing selected account state after a switch, leave consumer callbacks and subscription lifecycle unchanged
…r, report partial totals when another venue’s cache is unusable, preserve single-venue snapshot shape and venue-local details
8a0b597 to
5fa1352
Compare
Explanation
In aggregated mode, list reads (positions, orders, fills, markets) already fan out to every venue and tag rows with
providerId. Account-level data did not:getAccountStateandsubscribeToAccountread only the default venue,perpsBalanceswas declared but never written, batch cancel/close were refused outright in multi-venue mode, several market streams ignored explicit routes, and money-movement routes and records carried no venue identity. A Lighter chart would show Hyperliquid candles and the second venue's balance was invisible.This PR gives each exchange its own account data and routing. Direct/single-provider modes keep their established behavior, and one-venue aggregated fallback (for example Hyperliquid-only while Lighter fails to load) keeps passing the direct result through unchanged.
Aggregated account reads and streams
AggregatedPerpsProvider.getAccountStatefans out to every enabled venue and returns:totalBalance,spendableBalance,withdrawableBalance,marginUsedandunrealizedPnlas decimal-safe combined totals over the venues that reported data (bignumber.js, never binary float), andreturnOnEquityas the margin-weighted combined rate100 × Σ unrealizedPnl ÷ Σ marginUsed('0'when no margin is used). Both venues' adapters report account-level RoE in percentage points, so the combined rate uses the same units; it is never summed or averaged.providerStatesentries, keyed by provider id, hold each venue's own snapshot — including venue-localcrossMarginSummaryandsubAccountBreakdown, which are never merged into the top level because cross-venue collateral is not mutually usable. Identical sub-account names at different venues do not collide.aggregatemetadata ({ status: 'complete' | 'partial', availableProviders, unavailableProviders, pendingProviders? }) says whether the totals cover every enabled venue. A venue whose read failed is an explicitunavailableentry — never a zero balance; a confirmed zero or nonexistent venue account is anavailableentry with zero balances. A stream venue that has not reported yet, including a firstnull, ispending. Apartialtotal is a subtotal and must not be presented as the complete portfolio value. When no venue has usable data the read throws (REST) or the stream emitsnull— never an all-zero total. Aggregated reads passthrowOnUnavailable: true. HyperLiquid rejects the read when any DEX clearinghouse read or the spot clearinghouse read fails, so that venue isunavailableand the combined total ispartial. Aggregated streams apply the same rule through the newSubscribeAccountParams.requireCompleteAccount: HyperLiquid emitsnulluntil every configured DEX has published on the current connection (after a reconnect, until each DEX republishes) and its spot balance has loaded, so a failed DEX subscription keeps HyperLiquidpending(orunavailableafter a snapshot) and the totalpartial, instead of streaming the reachable DEXs' total as HyperLiquid's complete balance. Direct and single-venue streams keep the lenient total.providerId; per-venue attribution lives inproviderStates. Each entry's venue is captured before the venue request is awaited, so a default change mid-request never mislabels a balance.AggregatedPerpsProvider.subscribeToAccountsubscribes to every enabled venue through the multiplexer and emits the same combined contract. The account stream is venue fan-out, not default-routed: changing the routing default neither drops a venue's subscription nor erases a still-valid all-venue total, and nonullinvalidation is emitted on a default change. Before a venue's first snapshot, anullupdate leaves itpendingand keeps its persisted balance. After a snapshot,nullmakes itunavailableand drops that balance; it is never recorded as zero. The callback's optional second argument carriesAccountAggregateMetadataeven when the combined state isnull, so pending and unavailable venues stay distinguishable. Each simultaneous account subscription owns its venue cache, so one subscription's cleanup never erases another subscription's venue data.Controller state
perpsBalances[providerId]is now written from live account updates: one entry per available venue withtotalBalance,unrealizedPnlandlastUpdated.accountValue1dAgois optional and stays unset on live updates. Entries are cleared when the selected account changes or the network is toggled, and a stream for an explicitaccountIdother than the selected account only reaches its own callback: it neither writes nor clearsaccountStateor these entries. A venue whose data becomes unavailable has its entry removed rather than left looking live. There is no synthetic combined entry; the total lives inaccountState.providerId.setDefaultProviderclears only a single-venue snapshot (for example a one-venue fallback read); an all-venue aggregate snapshot stays valid across the change.Batch routing
cancelOrdersandclosePositionsare venue-attributed rather than refused. Cancel-all reaches every venue that holds an order, and each cancel keeps the venue identity of the order it came from. Scopedorderstargets ({ orderId, providerId }) match on both fields; bareorderIdsorsymbolsfilters are refused while more than one venue is registered (see below).closePositionstakes explicittargetsof{ symbol, providerId }, which take precedence overcloseAllandsymbols, orcloseAll(fans out to every enabled venue). An emptytargetslist closes nothing; it never falls through to close-all. An omitted or empty legacysymbolslist still closes every position, as in 24.x. Selection precedence lives inresolveCloseSelection/resolveCancelSelection, shared by the controller,TradingServiceand both providers.error: BATCH_INCOMPLETEwith structured detail instead of a raw message:failures({ providerId, error }[]) onClosePositionsResultandCancelOrdersResultfor venue batches that threw or returned an error, anddiscoveryFailuresonCancelOrdersResultfor venues or order IDs whose open orders could not be read. Completion checks must look at these fields, notsuccessalone.PROVIDER_ROUTE_REQUIREDwhile multiple venues are registered (single-venue fallback accepts them), and duplicate symbols/order ids across venues are never resolved by choosing the default provider. Results carry aproviderIdper item, and one venue's failure never hides another venue's successes; a thrown venue batch is reported as an explicit per-venue failure.Venue-specific market streams and money movement
subscribeToCandles,subscribeToOICapsandsubscribeToOrderBooktake an optionalproviderId. An explicit route reaches that venue — required when both venues list the same symbol — and stays pinned when the routing default changes. Omitting it keeps the previous default-routed rebinding behavior. An unregistered route is reported as a barePROVIDER_NOT_FOUNDerror throughonError(or thrown when there is noonError) and never silently subscribes to a different venue.getDepositRoutesandgetWithdrawalRoutesreturn every active venue's routes, each tagged with aproviderId; identical asset/chain routes from different venues are distinct entries and are never collapsed.depositWithConfirmationselects the explicitproviderId, otherwise the routing default, and fails closed when that venue has no route. Deposit and withdrawal request records capture that venue before any asynchronous preparation and never relabel it. Legacy persisted records without venue identity keep their shape.Breaking package compatibility
This is a breaking change, following the breaking-change process:
AccountStatesemantics changed: the top-level numeric fields are now combined totals (withproviderStates/aggregatewhen the aggregated producer ran), and the account stream no longer follows the default venue or emits anullsnapshot when the default changes. The new fields are optional, but clients that keyed on the top-levelproviderIdof an aggregated read, presented the top level as a single venue's balance, or relied on default-change invalidation must read per-venue values fromproviderStatesand partial-total obligations fromaggregate.perpsBalancesentries madeaccountValue1dAgooptional and gain entries at runtime (previously declared, never written). Client state readers, typed defaults and fixtures that model the entry as fully required need updating.ClosePositionsParamsgains optionaltargets,BatchCancelOrdersParamsentries gain optionalproviderId,SubscribeAccountParamsgains optionalrequireCompleteAccount, and the batch/stream/route result types gain optionalproviderIdfields. All additive.PerpsProviderAccountStateEntry,AccountAggregateMetadata,ClosePositionsTarget. New subpath exports:@metamask/perps-controller/utils/cancelOrders,/utils/closePositionsand/utils/feeSupport(selection and fee-support helpers).The full consumer inventory, migration notes and unavailability semantics are in the package
CHANGELOG.md(Unreleased) and the package README's "Per-exchange account data" section.Client plan
Client draft PRs are not opened yet; scope is ticketed.
803491c(@metamask/perps-controller^22.3.0): runs HyperLiquid direct mode with no Lighter or multi-provider wiring, and a one-venue aggregated wrapper passes results through unchanged. The only observable change is thatperpsBalances.hyperliquidis now populated;hyperliquid-deposit/eligibility.tsreads it as an extra zero-balance check that agrees withaccountState. No change needed now; multi-venue adoption must readproviderStatesin deposit eligibility and filtergetWithdrawalRoutesbyproviderIdon the withdraw page.b61ee0d: no@metamask/perps-controllerdependency and none of the changed surfaces are consumed; no changes needed.Evidence
@metamask/perps-controllersuite with coverage at 21f7b82: 143 files, 7,660 passed, 40 skipped; coverage thresholds pass (92.45% lines).docs/architecture.mddescribes per-venue account data, batch routing and the new error surface. Per-package suite only; the monorepo suite was not run.yarn lint:tsc:checkreports no new type errors;oxlintandoxfmt --checkon every changed file,yarn changelog:validate, and the package build are clean.## [24.1.0]and older changelog sections are byte-identical tomain; every entry from this PR is under## [Unreleased], including the five BREAKING entries.HyperLiquidProviderwith a failing HIP-3 DEX insideAggregatedPerpsProvideryieldsaggregate.status: 'partial'with HyperLiquidunavailable(REST), and a realHyperLiquidSubscriptionServicewhose HIP-3 DEX subscription fails keeps the aggregated streampartial(verified to fail withoutrequireCompleteAccount).depositWithConfirmationuses the explicitproviderIdor the routing default and fails closed when that venue has no route.References
Checklist
Note
High Risk
Breaking aggregated account and batch-close/cancel contracts touch balances, margin totals, and multi-venue execution paths where mis-handling could show wrong portfolio values or cancel/close on the wrong venue.
Overview
Aggregated perps mode now treats each exchange as a first-class data source instead of hiding everything behind the routing default.
getAccountStateandsubscribeToAccountfan out to every enabled venue and return combined decimal-safe totals plusproviderStatesandaggregatecompleteness metadata; streams userequireCompleteAccountso partial HyperLiquid or Lighter reads are markedpartial/unavailablerather than shown as a full portfolio.perpsBalancesis populated perproviderIdfrom live updates (with optionalaccountValue1dAgo), and controller state clears or isolates balances on account, network, or provider topology changes.Batch cancel/close and money movement are venue-routed. Multi-venue
cancelOrdersandclosePositionsfan out or honor{ providerId, … }targets; legacy bareorderIds/symbolsfilters still require an explicit route when multiple venues are registered. Results exposeBATCH_INCOMPLETE, per-venuefailures, and cancel discovery failures; strict open-order reads can throwOrderDiscoveryError. Deposits/withdrawals list all venues' routes,depositWithConfirmationfails closed on the chosen venue, and request records store an initiatingproviderId. Market streams (subscribeToCandles, OI caps, order book) accept optionalproviderIdpinning.New shared helpers (
accountAggregation,cancelOrders,closePositions,feeSupport) back the aggregated provider, controller cache/preload, and docs/changelog updates. Several breaking consumer contracts: aggregatedAccountStateshape, deposit/withdrawal route lists, default-change behavior for account subscriptions, and multi-venue batch semantics.Reviewed by Cursor Bugbot for commit e80f01d. Bugbot is set up for automated code reviews on this repo. Configure here.