@metamask-previews/perps-controller 24.1.0-preview-c4a9d828a → 25.0.0-preview-861fb4f0b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/CHANGELOG.md +106 -1
  2. package/README.md +115 -5
  3. package/dist/PerpsController-method-action-types.d.ts +2 -2
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +19 -6
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +342 -66
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/aggregation/SubscriptionMultiplexer.d.ts +13 -2
  10. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
  11. package/dist/aggregation/SubscriptionMultiplexer.js +27 -13
  12. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +3 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +5 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/lighterConfig.d.ts +17 -0
  18. package/dist/constants/lighterConfig.d.ts.map +1 -1
  19. package/dist/constants/lighterConfig.js +31 -8
  20. package/dist/constants/lighterConfig.js.map +1 -1
  21. package/dist/errors.d.ts +16 -0
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +13 -0
  24. package/dist/errors.js.map +1 -1
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +3 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +3 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +4 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/AggregatedPerpsProvider.d.ts +33 -1
  34. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  35. package/dist/providers/AggregatedPerpsProvider.js +688 -41
  36. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  37. package/dist/providers/HyperLiquidProvider.d.ts +5 -7
  38. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  39. package/dist/providers/HyperLiquidProvider.js +806 -320
  40. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  41. package/dist/providers/LighterProvider.d.ts +9 -2
  42. package/dist/providers/LighterProvider.d.ts.map +1 -1
  43. package/dist/providers/LighterProvider.js +372 -117
  44. package/dist/providers/LighterProvider.js.map +1 -1
  45. package/dist/services/AccountService.d.ts.map +1 -1
  46. package/dist/services/AccountService.js +14 -1
  47. package/dist/services/AccountService.js.map +1 -1
  48. package/dist/services/DepositService.d.ts +8 -1
  49. package/dist/services/DepositService.d.ts.map +1 -1
  50. package/dist/services/DepositService.js +47 -6
  51. package/dist/services/DepositService.js.map +1 -1
  52. package/dist/services/HyperLiquidClientService.d.ts +4 -2
  53. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  54. package/dist/services/HyperLiquidClientService.js +8 -4
  55. package/dist/services/HyperLiquidClientService.js.map +1 -1
  56. package/dist/services/HyperLiquidSubscriptionService.d.ts +19 -14
  57. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  58. package/dist/services/HyperLiquidSubscriptionService.js +612 -191
  59. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  60. package/dist/services/HyperLiquidWalletService.d.ts +7 -0
  61. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
  62. package/dist/services/HyperLiquidWalletService.js +16 -0
  63. package/dist/services/HyperLiquidWalletService.js.map +1 -1
  64. package/dist/services/LighterClientService.d.ts.map +1 -1
  65. package/dist/services/LighterClientService.js +3 -1
  66. package/dist/services/LighterClientService.js.map +1 -1
  67. package/dist/services/RewardsIntegrationService.d.ts +2 -1
  68. package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
  69. package/dist/services/RewardsIntegrationService.js +9 -2
  70. package/dist/services/RewardsIntegrationService.js.map +1 -1
  71. package/dist/services/ServiceContext.d.ts +3 -3
  72. package/dist/services/ServiceContext.d.ts.map +1 -1
  73. package/dist/services/ServiceContext.js.map +1 -1
  74. package/dist/services/TradingService.d.ts +4 -0
  75. package/dist/services/TradingService.d.ts.map +1 -1
  76. package/dist/services/TradingService.js +347 -90
  77. package/dist/services/TradingService.js.map +1 -1
  78. package/dist/types/index.d.ts +326 -14
  79. package/dist/types/index.d.ts.map +1 -1
  80. package/dist/types/index.js.map +1 -1
  81. package/dist/types/lighter-types.d.ts +1 -1
  82. package/dist/types/lighter-types.d.ts.map +1 -1
  83. package/dist/types/lighter-types.js.map +1 -1
  84. package/dist/utils/accountAggregation.d.ts +58 -0
  85. package/dist/utils/accountAggregation.d.ts.map +1 -0
  86. package/dist/utils/accountAggregation.js +117 -0
  87. package/dist/utils/accountAggregation.js.map +1 -0
  88. package/dist/utils/accountUtils.d.ts +18 -0
  89. package/dist/utils/accountUtils.d.ts.map +1 -1
  90. package/dist/utils/accountUtils.js +69 -66
  91. package/dist/utils/accountUtils.js.map +1 -1
  92. package/dist/utils/batchOperationStatus.d.ts +18 -0
  93. package/dist/utils/batchOperationStatus.d.ts.map +1 -0
  94. package/dist/utils/batchOperationStatus.js +26 -0
  95. package/dist/utils/batchOperationStatus.js.map +1 -0
  96. package/dist/utils/cancelOrders.d.ts +32 -0
  97. package/dist/utils/cancelOrders.d.ts.map +1 -0
  98. package/dist/utils/cancelOrders.js +83 -0
  99. package/dist/utils/cancelOrders.js.map +1 -0
  100. package/dist/utils/closePositions.d.ts +24 -0
  101. package/dist/utils/closePositions.d.ts.map +1 -0
  102. package/dist/utils/closePositions.js +20 -0
  103. package/dist/utils/closePositions.js.map +1 -0
  104. package/dist/utils/errorUtils.d.ts +10 -0
  105. package/dist/utils/errorUtils.d.ts.map +1 -1
  106. package/dist/utils/errorUtils.js +33 -3
  107. package/dist/utils/errorUtils.js.map +1 -1
  108. package/dist/utils/feeSupport.d.ts +9 -0
  109. package/dist/utils/feeSupport.d.ts.map +1 -0
  110. package/dist/utils/feeSupport.js +11 -0
  111. package/dist/utils/feeSupport.js.map +1 -0
  112. package/dist/utils/guardedHyperLiquidClient.d.ts +10 -1
  113. package/dist/utils/guardedHyperLiquidClient.d.ts.map +1 -1
  114. package/dist/utils/guardedHyperLiquidClient.js +37 -3
  115. package/dist/utils/guardedHyperLiquidClient.js.map +1 -1
  116. package/dist/utils/hyperLiquidAdapter.d.ts +9 -1
  117. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  118. package/dist/utils/hyperLiquidAdapter.js +37 -1
  119. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  120. package/dist/utils/hyperLiquidPositionPreview.d.ts +46 -0
  121. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  122. package/dist/utils/hyperLiquidPositionPreview.js +98 -6
  123. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  124. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  125. package/dist/utils/hyperLiquidValidation.js +4 -2
  126. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  127. package/dist/utils/index.d.ts +5 -0
  128. package/dist/utils/index.d.ts.map +1 -1
  129. package/dist/utils/index.js +3 -0
  130. package/dist/utils/index.js.map +1 -1
  131. package/dist/utils/lighterAdapter.d.ts +2 -1
  132. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  133. package/dist/utils/lighterAdapter.js +32 -16
  134. package/dist/utils/lighterAdapter.js.map +1 -1
  135. package/dist/utils/orderBookGrouping.d.ts +38 -0
  136. package/dist/utils/orderBookGrouping.d.ts.map +1 -0
  137. package/dist/utils/orderBookGrouping.js +101 -0
  138. package/dist/utils/orderBookGrouping.js.map +1 -0
  139. package/dist/utils/orderTypes.d.ts +2 -0
  140. package/dist/utils/orderTypes.d.ts.map +1 -1
  141. package/dist/utils/orderTypes.js +11 -4
  142. package/dist/utils/orderTypes.js.map +1 -1
  143. package/dist/utils/perpsClientCopy.d.ts +33 -0
  144. package/dist/utils/perpsClientCopy.d.ts.map +1 -0
  145. package/dist/utils/perpsClientCopy.js +509 -0
  146. package/dist/utils/perpsClientCopy.js.map +1 -0
  147. package/dist/utils/standaloneInfoClient.d.ts +20 -3
  148. package/dist/utils/standaloneInfoClient.d.ts.map +1 -1
  149. package/dist/utils/standaloneInfoClient.js +35 -10
  150. package/dist/utils/standaloneInfoClient.js.map +1 -1
  151. package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
  152. package/dist/utils/subscriptionFeeWaiver.js +5 -3
  153. package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
  154. package/docs/README.md +1 -0
  155. package/docs/architecture.md +16 -12
  156. package/docs/contracts/events.md +1 -1
  157. package/docs/tpsl.md +3 -2
  158. package/package.json +7 -6
package/CHANGELOG.md CHANGED
@@ -7,11 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [25.0.0]
11
+
10
12
  ### Added
11
13
 
14
+ - Add optional `maxSlippageBps` to `UpdatePositionTPSLParams`, the slippage cap for a HyperLiquid market-executed TP/SL leg ([#11650](https://github.com/MetaMask/core/pull/11650))
15
+ - Add `crossMarginUnavailableReason` to HyperLiquid order capabilities when Cross is restricted, distinguishing the venue's no-Cross and strict-isolated modes from generic isolated-only markets. ([#11629](https://github.com/MetaMask/core/pull/11629))
12
16
  - **BREAKING:** Add exported `HyperLiquidErrorDetails` and widen `PerpsErrorDetails` to `PriceMovedErrorDetails | HyperLiquidErrorDetails`. Every normalized Hyperliquid failure now carries `{ code, provider: 'hyperliquid' }` details, so clients can translate stable codes without parsing venue messages. `PRICE_MOVED` keeps its existing numeric payload. ([#11206](https://github.com/MetaMask/core/pull/11206))
13
17
  - Code that reads `PriceMovedErrorDetails` fields must first narrow on `errorDetails.code === PERPS_ERROR_CODES.PRICE_MOVED`. `HyperLiquidErrorDetails['code']` never includes `PRICE_MOVED`, so that check still narrows.
14
18
  - Mobile accepts `HyperLiquidErrorDetails` in `isPerpsErrorDetails`, so known codes keep their localized copy ([metamask-mobile#39018](https://github.com/MetaMask/metamask-mobile/pull/39018)). Extension translates the same codes in [metamask-extension#47686](https://github.com/MetaMask/metamask-extension/pull/47686).
19
+ - Add `Position.displayMarginUsed`, the margin Hyperliquid shows for a cross position: `marginUsed × accountValue / totalMarginUsed` when cross equity is below the cross initial margin, otherwise `marginUsed`. `marginUsed` keeps the raw venue figure. `adaptPositionFromSDK` takes the clearinghouse `crossMarginSummary` as an optional second argument to compute it ([#11629](https://github.com/MetaMask/core/pull/11629))
20
+ - Add `AccountState.unavailableSubAccounts`, the Hyperliquid DEXs (`''` for the main DEX) whose account state is unavailable. Account reads set it when some DEXs fail, and the account stream sets it while a configured DEX has not published or its subscription failed, so clients can show the totals as partial ([#11629](https://github.com/MetaMask/core/pull/11629))
21
+ - Add the `PERPS_ERROR_CODES.ORDERS_FAILED` error code ([#11629](https://github.com/MetaMask/core/pull/11629))
22
+ - On the package bump, Mobile's exhaustive error map and Extension's translation map and coverage test need entries for both `ORDERS_FAILED` and `LIQUIDATION_PRICE_UNAVAILABLE`. Terminal should keep failed orders distinct from an empty order list and show an unavailable estimate on the typed liquidation rejection.
23
+ - Add optional `PositionTriggerOrder.coverageUnavailable` to distinguish an active trigger from unconfirmed position coverage while live position data is unavailable ([#11629](https://github.com/MetaMask/core/pull/11629))
24
+ - Add an optional `marginUsed` to `ReturnOnEquityInput`. `calculateWeightedReturnOnEquity` weighs each account by it when given ([#11629](https://github.com/MetaMask/core/pull/11629))
15
25
  - Add `PERPS_ERROR_CODES.ORDER_POST_ONLY_WOULD_CROSS` and `PERPS_ERROR_CODES.ORDER_POST_ONLY_WINDOW`, returned on Hyperliquid provider results when a post-only order would cross the spread or when the venue only accepts post-only orders after a network upgrade. ([#11206](https://github.com/MetaMask/core/pull/11206))
16
26
  - Clients without a catch-all for unknown codes should map both. Mobile maps them in [metamask-mobile#39018](https://github.com/MetaMask/metamask-mobile/pull/39018) and Extension maps them in [metamask-extension#47686](https://github.com/MetaMask/metamask-extension/pull/47686).
17
27
  - `ORDER_POST_ONLY_WOULD_CROSS` on a failed `editOrder` means Hyperliquid has already cancelled the original resting order. Clients read `errorCode` rather than venue wording. Mobile does that in `isPostOnlyWouldCrossError`, `isPostOnlyWindowError`, and `normalizeOrderEditRejection` ([metamask-mobile#39018](https://github.com/MetaMask/metamask-mobile/pull/39018)).
@@ -41,9 +51,76 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
41
51
  - Add `formatPerpsDuration(durationMs, { formatters?, unitDisplay? })` (type `PerpsDurationFormatOptions`) to render TWAP running and elapsed time, slice intervals and chase windows in the client's locale ("1 hr 30 min"). It replaces Mobile `PerpsProTwapFields.tsx` `formatTwapRuntimeSummary` and Terminal `twapSummary.ts` `formatTwapRuntime` ([#11592](https://github.com/MetaMask/core/pull/11592))
42
52
  - Add optional `chaseOrder` to `CancelOrderResult`: the chase's final snapshot when a chase cancel succeeds and the provider knows how it ended. HyperLiquid sets it, and leaves it out when the venue reports the child gone and its status cannot be read ([#11592](https://github.com/MetaMask/core/pull/11592))
43
53
  - Add types `TwapSlicePreview`, `ChaseOrderLists`, `ChasePlacementCheck`, `ScaleLadderSizing`, `ScalePriceWarning`, `SubscribeLiveTwapOrdersParams`, `SubscribeChaseOrderListsParams`, `AdvancedOrderValidationResult`, `LiveTwapOrderSource`, `LiveChaseOrderSource` and `CanceledChaseOrder` ([#11592](https://github.com/MetaMask/core/pull/11592))
54
+ - Add `PERPS_ERROR_CODES.BATCH_INCOMPLETE` and `failures` (`{ providerId, error }[]`) on `ClosePositionsResult` and `CancelOrdersResult`. When any venue's batch throws or returns an error, `error` is `BATCH_INCOMPLETE` and `failures` keeps every venue's error, so a merged batch error stays a translatable code without hiding which venues failed ([#11461](https://github.com/MetaMask/core/pull/11461))
55
+ - Add optional `PerpsProvider.getProviderIds()` to list an aggregating provider's registered venues, including venues whose positions or balances are unavailable ([#11461](https://github.com/MetaMask/core/pull/11461))
56
+ - Add optional `SubscribeAccountParams.requireCompleteAccount`: the venue emits `null` instead of a snapshot that is missing part of its account. HyperLiquid's account is complete once every configured DEX has published on the current connection and the spot balance has loaded; after a reconnect it is incomplete until every DEX republishes ([#11461](https://github.com/MetaMask/core/pull/11461))
57
+ - Add optional `PerpsProvider.supportsFeeResolution(providerId)` to identify venues that consume fee resolutions, and an optional third `RewardsIntegrationService.resolveFee` argument for subscription notional already reserved by earlier venues in a batch ([#11461](https://github.com/MetaMask/core/pull/11461))
58
+ - Add `CancelOrdersParams.orders` with `{ orderId, providerId }` targets, matched on both fields so an ID collision never selects another venue's order. Legacy `orderIds` is supported only with one registered venue; use `orders` for a venue-specific cancel ([#11461](https://github.com/MetaMask/core/pull/11461), [#11552](https://github.com/MetaMask/core/pull/11552))
59
+ - Add venue routing to market streams: `subscribeToCandles`, `subscribeToOICaps` and `subscribeToOrderBook` take an optional `providerId` ([#11461](https://github.com/MetaMask/core/pull/11461))
60
+ - An explicit route reaches that venue even when both venues list the same symbol (a Lighter chart shows Lighter prices), and stays pinned when the routing default changes
61
+ - Omitting `providerId` keeps the previous default-routed behavior, including rebinding when the default changes
62
+ - A route that is not registered is reported as a `PROVIDER_NOT_FOUND` error through the params' `onError` (or thrown when there is no `onError`); the stream never silently subscribes to a different venue
63
+ - Expose `buildAggregatedAccountState`, `getAccountAggregateMetadata`, `aggregateAccountTotals` and the `AggregatedAccountTotals` type through `@metamask/perps-controller/utils/accountAggregation` ([#11461](https://github.com/MetaMask/core/pull/11461))
64
+ - Add venue attribution to money-movement records: deposit and withdrawal request records in controller state take an optional `providerId`, resolved from the chosen route (otherwise the executing provider) during preparation and never relabeled by later provider or default changes. Records persisted before this change omit the field and keep their original shape ([#11461](https://github.com/MetaMask/core/pull/11461))
65
+ - Add `ClosePositionsParams.targets` and `ClosePositionsTarget` for venue-tagged closes, and optional venue attribution on batch close and cancel results ([#11461](https://github.com/MetaMask/core/pull/11461))
66
+ - Expose `resolveCancelSelection`, `getUnroutedCancelOrdersRefusal` and the `CancelSelection` type through `@metamask/perps-controller/utils/cancelOrders`, `resolveCloseSelection` and the `CloseSelection` type through `@metamask/perps-controller/utils/closePositions`, and `hasFeeSetter` through `@metamask/perps-controller/utils/feeSupport` ([#11461](https://github.com/MetaMask/core/pull/11461))
44
67
 
45
68
  ### Changed
46
69
 
70
+ - **BREAKING:** HyperLiquid `PerpsController.calculateLiquidationPrice` now rejects invalid input with `LIQUIDATION_PRICE_UNAVAILABLE` instead of resolving `'0.00'`. Valid prices still resolve as decimal strings. Cross openings use the selected account and market tiers, require a sized order, and reject unavailable estimates. Lighter rejects cross previews with the same code. ([#11629](https://github.com/MetaMask/core/pull/11629))
71
+ - **BREAKING:** `Position.cumulativeFunding` and `Position.leverage.value` are optional. Lighter positions omit `cumulativeFunding` instead of reporting `'0'`, and a flat row without a usable initial margin fraction leaves `leverage.value` undefined instead of reporting 1x. Flip trade events omit `leverage` when it is unknown ([#11629](https://github.com/MetaMask/core/pull/11629))
72
+ - **BREAKING:** `queryStandaloneClearinghouseStates` returns `{ results, failedDexs }` (new `StandaloneClearinghouseStatesResult` type) instead of only the states that answered ([#11629](https://github.com/MetaMask/core/pull/11629))
73
+ - **BREAKING:** `aggregateAccountStates([])` throws `ACCOUNT_STATE_FAILED` instead of returning `'--'` in every numeric field ([#11629](https://github.com/MetaMask/core/pull/11629))
74
+ - **BREAKING:** Lighter `getAccountState` throws `ACCOUNT_STATE_FAILED` on a failed read or a missing account row, as it already did with `throwOnUnavailable`, instead of returning a zero balance. A wallet without a Lighter account still reads as empty. A valid balance still returns when the optional cross-margin summary is unavailable ([#11629](https://github.com/MetaMask/core/pull/11629))
75
+ - **BREAKING:** Lighter `getOpenOrders`, `getOrders` and `getPositions` reject failed reads with `ORDERS_FAILED` or `POSITIONS_FAILED` and a cause. Malformed venue data and stale sessions also reject. A confirmed absent Lighter account still returns empty orders and positions ([#11629](https://github.com/MetaMask/core/pull/11629))
76
+ - **BREAKING:** `AggregatedPerpsProvider` `getOpenOrders`, `getOrders` and `getPositions` reject when any venue's read fails, rethrowing `ORDERS_FAILED`/`POSITIONS_FAILED` or `PROVIDER_LIFECYCLE_STALE` and wrapping other errors (such as a Lighter data-integrity error) in `ORDERS_FAILED`/`POSITIONS_FAILED` with the cause, instead of returning the other venues' results alone ([#11629](https://github.com/MetaMask/core/pull/11629))
77
+ - Ordinary reads reject an incomplete order or position snapshot. Explicit cancellation discovery (`getOpenOrders({ throwOnUnavailable: true })`) uses `OrderDiscoveryError` to retain known orders and identify failed venues or DEXs, so a partial read can drive targeted cancellations without being displayed as complete
78
+ - Hyperliquid can return a discovered whole-position TP/SL trigger with size `'0'` when it cannot load the position used for sizing. The ID remains available for cancellation, and the trigger's quantity is unknown.
79
+ - **BREAKING:** Hyperliquid `getOpenOrders`, `getOrders` and `getPositions` reject with `ORDERS_FAILED` or `POSITIONS_FAILED` when a required read fails, including failed DEX reads in standalone mode ([#11629](https://github.com/MetaMask/core/pull/11629))
80
+ - Direct `getPositions` preserves `PROVIDER_LIFECYCLE_STALE` if a disconnect invalidates DEX discovery.
81
+ - **BREAKING:** Hyperliquid standalone `getAccountState` throws `ACCOUNT_STATE_FAILED` when no DEX answers, and sets `unavailableSubAccounts` when some fail, instead of returning `'--'` placeholders or totals that silently skip DEXs ([#11629](https://github.com/MetaMask/core/pull/11629))
82
+ - **BREAKING:** Lighter `calculateLiquidationPrice` throws `PRICE_UNAVAILABLE` or `ORDER_LEVERAGE_INVALID` for an invalid entry price or leverage instead of returning `'0.00'` ([#11629](https://github.com/MetaMask/core/pull/11629))
83
+ - **BREAKING:** `calculateFees` leaves `feeRate` and `feeAmount` undefined when the protocol fee is unavailable. Clients should show an unavailable total and can still display the known MetaMask fee separately ([#11629](https://github.com/MetaMask/core/pull/11629))
84
+ - **BREAKING:** `previewPositionModify` and `previewHyperLiquidIsolatedPositionModify` treat an omitted, NaN or negative `feeAmountUsd` as unknown: the resulting margin and liquidation price of an increase or flip are unavailable instead of computed with a $0 fee. Pass `0` only for a known zero fee ([#11629](https://github.com/MetaMask/core/pull/11629))
85
+ - **BREAKING:** `getDepositRoutes` and `getWithdrawalRoutes` return routes from every active venue rather than only the default. Filter by `route.providerId` for venue-local money movement; identical asset/chain routes on different venues remain distinct ([#11461](https://github.com/MetaMask/core/pull/11461))
86
+ - `depositWithConfirmation` selects the explicit `providerId`, otherwise the routing default, and fails closed when that venue has no route instead of funding another exchange
87
+ - **BREAKING:** Aggregated `getAccountState` and `subscribeToAccount` now expose per-venue snapshots and combined totals instead of the routing default's account. Consumers must use `providerStates[providerId]` for venue-local balances and margin detail ([#11461](https://github.com/MetaMask/core/pull/11461), [#11552](https://github.com/MetaMask/core/pull/11552))
88
+ - `AggregatedPerpsProvider.getAccountState` fans out to every registered venue and returns top-level `totalBalance`, `spendableBalance`, `withdrawableBalance`, `marginUsed` and `unrealizedPnl` as decimal-safe combined totals over the venues that reported data, plus `returnOnEquity` as a margin-weighted combined rate (`100 × Σ unrealizedPnl ÷ Σ marginUsed`, `0` when no margin is used)
89
+ - New optional `AccountState.providerStates` entries, keyed by provider id, hold each venue's own snapshot — including venue-local `crossMarginSummary` and `subAccountBreakdown`, which are never merged into the top level. Identical sub-account names at different venues do not collide
90
+ - New optional `AccountState.aggregate` metadata (`{ status, availableProviders, unavailableProviders, pendingProviders? }`) says whether the totals cover every enabled venue. A `partial` total is a subtotal: consumers must not present it as the complete portfolio value. A failed venue read or a snapshot with a missing or non-finite additive field is an explicit `unavailable` entry — never a zero balance; a confirmed zero or missing venue account is an `available` entry with zero balances
91
+ - Aggregated account reads pass `throwOnUnavailable: true`. HyperLiquid rejects that read when any DEX clearinghouse read or the spot clearinghouse read fails, so the venue is `unavailable` and the combined total is `partial`. Callers that omit the flag receive the reachable DEXs' total when one DEX or the spot read fails; incomplete DEX balances are identified by `unavailableSubAccounts`
92
+ - Aggregated account streams set `requireCompleteAccount` on every venue. While a HyperLiquid DEX account subscription has failed or the spot balance has not loaded, HyperLiquid is `pending` (or `unavailable` after a snapshot) and the combined total is `partial`, rather than counting the reachable DEXs' total as HyperLiquid's complete balance. Direct and single-venue streams keep the lenient total
93
+ - When no venue has usable data, the read throws (REST) or emits `null` (stream) instead of manufacturing an all-zero total
94
+ - The aggregated result carries no venue `providerId`; per-venue attribution lives in `providerStates`. Aggregated wrappers with a single registered venue keep passing the direct result through unchanged
95
+ - `AggregatedPerpsProvider.subscribeToAccount` subscribes to every enabled venue through the multiplexer and emits the same combined contract on each update. The 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. Before a venue's first snapshot it is `pending`, including on `null`; its persisted balance is retained until the venue reports or the account/network context changes. After a snapshot, `null` makes it `unavailable` and removes its balance entry. The callback's optional second argument carries `AccountAggregateMetadata` even when the combined state is `null`, so consumers can distinguish pending from unavailable venues
96
+ - Each simultaneous account subscription owns its venue cache, so one subscription's cleanup never erases another subscription's venue data
97
+ - `PerpsController` now writes `perpsBalances[providerId]` from live account updates: one entry per available venue with `totalBalance`, `unrealizedPnl` and `lastUpdated`. Live updates do not carry historical values forward; all entries are cleared when the selected account changes or the network is toggled. A direct or single-venue stream removes entries for other venues, and changing the provider selection or migrating out of aggregated mode clears them. A stream for an explicit `accountId` other than the selected account only reaches its own callback: it neither writes nor clears `accountState` or balance entries. A venue whose data becomes unavailable has its entry removed rather than left looking live, and a `null` aggregate clears `accountState` but removes only explicitly unavailable venues' balance entries
98
+ - User-data preload assigns each aggregated venue's account state to its own provider cache bucket; the combined total is never stored in a venue's bucket
99
+ - New exported types `PerpsProviderAccountStateEntry` and `AccountAggregateMetadata`
100
+ - A combined snapshot is not replaced by a one-venue fallback while multiple venues remain registered, including when the fallback names the routing default
101
+ - Lighter's optional venue-local `crossMarginSummary` is best-effort: valid balances still contribute when the summary cannot be derived. Core-read failures and malformed balances remain unavailable
102
+ - **BREAKING:** `perpsBalances[*].accountValue1dAgo` is optional. State readers must handle a missing historical observation; live account updates never fabricate it from the current balance ([#11461](https://github.com/MetaMask/core/pull/11461))
103
+ - **BREAKING:** `setDefaultProvider` no longer moves or invalidates multi-venue account subscriptions: they keep reporting all enabled venues. Combined account snapshots survive default changes; direct or single-venue snapshots are cleared. In-flight account reads are checked against their execution context rather than a subsequently selected default ([#11461](https://github.com/MetaMask/core/pull/11461))
104
+ - **BREAKING:** Multi-venue `cancelOrders` and `closePositions` no longer refuse every batch: cancel-all and close-all fan out to enabled venues, and scoped targets execute only on their named venue. Non-empty legacy `symbols` or bare `orderIds` cancel filters and symbols-only closes still require an unambiguous venue and are refused with `PROVIDER_ROUTE_REQUIRED` ([#11461](https://github.com/MetaMask/core/pull/11461))
105
+ - Batch-close fee resolutions are scoped to each execution venue through the optional `providerId` argument of `PerpsProvider.setUserFeeResolution`, including when position pricing fails or matches no positions
106
+ - A supplied `targets` list takes precedence over `closeAll` and `symbols`, and an empty `targets` list closes nothing instead of falling through to close-all. An omitted or empty legacy `symbols` list still closes every position
107
+ - Venues without a fee setter get no fee lookup, and a bounded subscription allowance is reserved venue by venue, so two venues cannot both spend the same remaining allowance
108
+ - Batch-close fee pricing reads each execution venue independently, allowing a reachable venue to use its fee waiver when another venue's positions are unavailable ([#11629](https://github.com/MetaMask/core/pull/11629))
109
+ - Tagged close targets work in single-venue and multi-venue execution, including per-position fallbacks. Missing or throwing venues retain explicit per-target failures, and a venue whose position lookup fails during close-all is reported in `failures` rather than treated as having nothing to close
110
+ - **BREAKING:** `PerpsController.cancelOrders` and `PerpsController.closePositions` and their messenger actions now require `status: 'all' | 'partial' | 'none'` in their return types ([#11639](https://github.com/MetaMask/core/pull/11639))
111
+ - Existing result readers can keep using `success`, counts and rows. Typed implementations and handler mocks should return `{ ...result, status: getBatchOperationStatus(result) }` when adapting a provider result.
112
+ - `getOrderCapabilities` now reports `pricePrecision` and `orderLimits` for HyperLiquid and Lighter markets, with the new `PerpsPricePrecision` and `PerpsOrderLimits` types ([#11639](https://github.com/MetaMask/core/pull/11639))
113
+ - HyperLiquid: a `significant_figures` grid (5 significant figures, `6 - szDecimals` decimals), size decimals, the $10 minimum order value, Scale rung bounds and TWAP duration and value bounds
114
+ - Lighter: a `fixed_decimals` grid with its `tickSize`, size decimals, minimum order size and value, and Scale rung bounds
115
+ - `orderLimits.minimumAppliesTo` names the orders the minimums apply to: `all_orders` on HyperLiquid, `resting_limit_orders` on Lighter (market and IOC orders are exempt)
116
+ - Both fields are optional. Lighter reports maker bounds as a pair only when both are valid and reachable within the price and size wire limits
117
+ - Add `aggregateOrderBookLevels` and `groupOrderBook` to group an order book at a price step with exact decimal bucketing, plus the `GroupedOrderBook` type ([#11639](https://github.com/MetaMask/core/pull/11639))
118
+ - Add `estimateCrossMaintenanceMargin` and `estimateCrossLiquidationPrice` for HyperLiquid cross-margin positions, plus the `CrossMarginPosition` type ([#11639](https://github.com/MetaMask/core/pull/11639))
119
+ - Add `PERPS_ERROR_COPY` and `getPerpsErrorCopy`, a translation key and English default for every `PERPS_ERROR_CODES` value, and `PERPS_ORDER_TYPE_LABELS` for every `OrderType`, with the `PerpsErrorCopy` and `PerpsOrderTypeLabel` types ([#11639](https://github.com/MetaMask/core/pull/11639))
120
+ - Add `getBatchOperationStatus` and the `BatchOperationStatus` and `WithBatchOperationStatus` types ([#11639](https://github.com/MetaMask/core/pull/11639))
121
+ - Document these in `docs/client-contract.md` ([#11639](https://github.com/MetaMask/core/pull/11639))
122
+ - Publish the `docs/` folder with the package, so clients read the docs for the controller version they install ([#11620](https://github.com/MetaMask/core/pull/11620))
123
+ - Correct Perps code comments and the published traces doc where they no longer matched the code: the `PRICE_RANGES_UNIVERSAL` examples and the `PRICE_THRESHOLD.VERY_SMALL` note now describe the sub-floor `<$0` output instead of promising `$0.000001`, the Lighter `getOrderCapabilities` doc lists the margin modes and strategies it returns, the initialization retry backoff reads `1s, 2s`, `AccountState.totalBalance` names `marginSummary.accountValue`, and the traces doc no longer lists the removed names below ([#11604](https://github.com/MetaMask/core/pull/11604))
47
124
  - **BREAKING:** Normalize known Hyperliquid venue failures to stable `PerpsErrorCode` values on every provider result boundary, including order placement and cancellation, edits, closes, TP/SL updates, margin changes, withdrawals, transfers, and readiness failures. ([#11206](https://github.com/MetaMask/core/pull/11206))
48
125
  - Result `error` fields now hold the stable code instead of venue text, and unknown failures return `UNKNOWN_ERROR`. Clients read `errorCode` instead. Mobile does this in [metamask-mobile#39018](https://github.com/MetaMask/metamask-mobile/pull/39018) and Extension in [metamask-extension#47686](https://github.com/MetaMask/metamask-extension/pull/47686).
49
126
  - Failed Perps analytics events emitted from Hyperliquid result failures (trade, edit, cancel, close, flip, margin, and withdrawal) now carry the stable `PerpsErrorCode` in `error_message` instead of venue text. Unrecognized failures are grouped as `UNKNOWN_ERROR`; dashboards that group by `error_message` must use code-based buckets. Original venue details remain in error-reporting causes, not analytics properties.
@@ -54,8 +131,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
54
131
  - Hyperliquid `prepareTradingWallet` errors include `errorCode` and provider-tagged `errorDetails` even when the signer is locked or the wallet has no exchange account yet. A pending setup step still returns `ready: false` without an error.
55
132
  - A structured failure the provider raises itself without details, such as the `ORDER_SIZE_MIN` returned when the venue rejects an opening order below its minimum, now also carries provider-tagged details. `PRICE_MOVED` is unchanged.
56
133
  - The original failure is never copied into result fields. It stays the `cause` of the reported error, including when `TradingService` reports a failed `closePosition`, `cancelOrder`, or `flipPosition` result, and when it reports a mixed `closePositions` batch.
134
+ - **BREAKING:** `HyperLiquidProvider.subscribeToAccount` throws `PROVIDER_NOT_AVAILABLE` if its shared feed is owned by another wallet. Close the old feed's subscriptions before opening a different wallet. Through `PerpsController`, this reports an unavailable balance to the subscriber and leaves other venues live ([#11629](https://github.com/MetaMask/core/pull/11629))
57
135
  - Publish the `docs/` folder with the package, so clients read the docs for the controller version they install ([#11620](https://github.com/MetaMask/core/pull/11620))
58
136
  - Correct Perps code comments and the published traces doc where they no longer matched the code: the `PRICE_RANGES_UNIVERSAL` examples and the `PRICE_THRESHOLD.VERY_SMALL` note now describe the sub-floor `<$0` output instead of promising `$0.000001`, the Lighter `getOrderCapabilities` doc lists the margin modes and strategies it returns, the initialization retry backoff reads `1s, 2s`, `AccountState.totalBalance` names `marginSummary.accountValue`, and the traces doc no longer lists the removed names below ([#11604](https://github.com/MetaMask/core/pull/11604))
137
+ - Bump `uuid` from `^14.0.2` to `^14.0.3` ([#11645](https://github.com/MetaMask/core/pull/11645))
59
138
 
60
139
  ### Removed
61
140
 
@@ -63,6 +142,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
63
142
 
64
143
  ### Fixed
65
144
 
145
+ - `PerpsController.flipPosition` now signs the flip at the saved max slippage (`setMaxSlippage`); with nothing saved it uses `ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps` on both venues ([#11650](https://github.com/MetaMask/core/pull/11650))
146
+ - HyperLiquid `validateOrder` now rejects leverage `0`, `NaN` or below `1` with `ORDER_LEVERAGE_INVALID`, a non-finite or negative size (or `usdAmount`) with `ORDER_SIZE_POSITIVE`, invalid reduce-only coin caps alongside USD sizes, non-finite limit or current prices with `ORDER_PRICE_POSITIVE`, and a non-finite trigger with `ORDER_TRIGGER_PRICE_POSITIVE` ([#11650](https://github.com/MetaMask/core/pull/11650))
147
+ - HyperLiquid refreshes expired account support before ordinary SDK signing and at dispatch. The SDK accessor records multi-sig venue rejections, including singular TWAP status errors. TWAP and Scale can roll back an acknowledged placement after teardown when the account and network still match ([#11650](https://github.com/MetaMask/core/pull/11650))
148
+ - `PerpsController.updatePositionTPSL` applies the per-call `maxSlippageBps`, saved preference or 10% default to whole-position market stop losses on HyperLiquid. Its take-profit leg stays a limit at the trigger. `replacePositionTPSLLeg` applies the cap to either leg when no explicit limit is supplied. Market limits round inward from the signed trigger. Standalone partial legs and explicit fill prices retain their pricing. An invalid cap used by a whole-position market leg or an invalid limit refuses the update before existing protection is canceled ([#11650](https://github.com/MetaMask/core/pull/11650))
149
+ - Lighter market entries now refresh market metadata and require an active perpetual market. They report the existing `ORDER_UNKNOWN_COIN` code if the market is unavailable for entry. Reduce-only closes stay available ([#11650](https://github.com/MetaMask/core/pull/11650))
150
+ - Batch cancellation rejects malformed selections and stops if the issuing account or provider changes before submission. Strict discovery validates fresh venue responses and preserves available orders alongside venue discovery errors. ([#11650](https://github.com/MetaMask/core/pull/11650))
151
+ - A TP/SL replacement refused inside SDK signing keeps `TPSL_UPDATE_FAILED` or `PROVIDER_NOT_AVAILABLE` after the SDK wraps the refusal, including when the old protection is restored ([#11650](https://github.com/MetaMask/core/pull/11650))
152
+ - Return combined portfolio totals and per-venue completeness metadata from aggregated cached user-data reads, including disk-hydrated startup data, instead of returning only HyperLiquid's account snapshot ([#11461](https://github.com/MetaMask/core/pull/11461))
153
+ - Prevent account streams opened without an `accountId` from overwriting or clearing selected-account state after the selected wallet changes ([#11461](https://github.com/MetaMask/core/pull/11461))
154
+ - Clear live account state and per-venue balances when the selected EVM wallet changes, is cleared, or a group with no EVM wallet is selected. A repeat selection preserves balances known to belong to that wallet. Pending venues do not inherit restored balances with no wallet attribution ([#11629](https://github.com/MetaMask/core/pull/11629))
155
+ - Account streams and REST reads share the selected group's EVM wallet. A REST response for another wallet can still be returned to the caller but cannot overwrite the selected balance.
156
+ - HyperLiquid account streams replay only balances scoped to the stream's wallet.
157
+ - Reject failed position discovery in the per-position `closePositions` fallback instead of treating an unavailable venue account as having no positions to close ([#11461](https://github.com/MetaMask/core/pull/11461))
158
+ - Withhold bounded batch-close fee waivers when any selected position has a non-finite value instead of pricing the venue from an understated subtotal ([#11461](https://github.com/MetaMask/core/pull/11461))
159
+ - Exclude Lighter from aggregated account totals when `getAccountState` or `subscribeToAccount` requests an account other than the selected wallet; unsupported scopes reject instead of returning or streaming the selected wallet's balance, and an aggregate keeps healthy venues live while marking Lighter unavailable ([#11461](https://github.com/MetaMask/core/pull/11461))
160
+ - Report batch-cancel discovery failures in the result instead of throwing or silently skipping orders. When open orders cannot be read from a venue or a HyperLiquid DEX, `cancelOrders` (including cancel-all) still cancels the orders it could discover and returns `error: BATCH_INCOMPLETE` with the unavailable venues and unresolved order IDs in the new `CancelOrdersResult.discoveryFailures` ([#11461](https://github.com/MetaMask/core/pull/11461))
161
+ - `failureCount` includes unresolved requested IDs, or one failure per unavailable venue when its order count is unknown
162
+ - `GetPositionsParams` and `GetOrdersParams` accept optional `throwOnUnavailable` for strict position and open-order discovery; strict open-order reads throw the exported `OrderDiscoveryError` with the orders read from reachable venues and DEXs plus per-venue failures
163
+ - Fall back to individual order cancellations for venues without `cancelOrders`, including Lighter, preserving each order's venue and success or failure in mixed-venue batches ([#11461](https://github.com/MetaMask/core/pull/11461))
164
+ - Preserve exact decimal `marginUsed` and `unrealizedPnl` totals and the margin-weighted `returnOnEquity` in `aggregateAccountStates` by sharing the account-total calculation with cross-venue aggregation instead of using binary floating-point arithmetic ([#11461](https://github.com/MetaMask/core/pull/11461), [#11552](https://github.com/MetaMask/core/pull/11552))
165
+ - Avoid cancelling all orders when `CancelOrdersParams.orderIds` or `symbols` is an empty list; empty filters now select no orders ([#11461](https://github.com/MetaMask/core/pull/11461), [#11552](https://github.com/MetaMask/core/pull/11552))
166
+ - Fix `LighterProvider` account subscribers receiving an all-zero `AccountState` when the wallet switches accounts or is deselected. They now receive `null` (balance not yet known), so the aggregated account stream marks Lighter `unavailable` after a prior snapshot (or keeps it `pending` before its first snapshot) instead of recording a confirmed $0 for the new account. A wallet the venue confirms has no Lighter account still receives the empty state ([#11461](https://github.com/MetaMask/core/pull/11461))
66
167
  - HyperLiquid chase cancels whose child the venue reports gone now read that child's status. A child that filled before the cancel ends the chase as `filled` with its final unfilled size, instead of `canceled` with the size from the last read ([#11592](https://github.com/MetaMask/core/pull/11592))
67
168
  - When that status cannot be read, the chase keeps its last status instead of `canceled`. A session kept for HIP-3 collateral cleanup asks for the child's status again on each `getChaseOrders` read until the venue reports it
68
169
  - HyperLiquid `getChaseOrders` lists only chases placed by the current account on the current network, so a chase started under another account no longer shows, with its cancel action, after the account or network changes ([#11592](https://github.com/MetaMask/core/pull/11592))
@@ -74,6 +175,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
74
175
  - HIP-3 markets with `marginMode` `noCross` or `strictIsolated`, or `onlyIsolated`, still report `['isolated']` and refuse Cross with `ORDER_MARGIN_MODE_UNSUPPORTED`
75
176
  - With manual HIP-3 transfers (`useUnifiedAccount: false`), adding to a Cross position now transfers the new order's margin instead of the whole position's, plus the margin the existing position needs when the order lowers its leverage ([#11623](https://github.com/MetaMask/core/pull/11623))
76
177
  - `adaptMarketFromSDK` and `getMarkets` no longer return `marginMode: 'normal'`, a value outside `MarketInfo.marginMode`; a market without a restriction now has no `marginMode`, and the Terminal global snapshot no longer fails schema validation when a market sends `normal`
178
+ - The Hyperliquid account stream waits for HIP-3 DEX discovery and at least one DEX account state before publishing, excludes disabled DEXs, and sets `unavailableSubAccounts` while a configured DEX, including one enabled at runtime, has not published or its subscription failed ([#11629](https://github.com/MetaMask/core/pull/11629))
179
+ - `calculateWeightedReturnOnEquity` no longer drops accounts whose RoE is 0 when `marginUsed` is given; the Hyperliquid account stream passes it ([#11629](https://github.com/MetaMask/core/pull/11629))
180
+ - Lighter account and position reads reject a payload without the expected account or `positions`. Position reads also reject a malformed position value or unrealized PnL, or an open position without a usable initial margin fraction, instead of reporting zero PnL, `NaN` or an invented 1x margin and RoE. The cross margin summary is omitted for an open cross position without a usable initial margin fraction ([#11629](https://github.com/MetaMask/core/pull/11629))
77
181
 
78
182
  ## [24.1.0]
79
183
 
@@ -1654,7 +1758,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1654
1758
 
1655
1759
  - Bump `@metamask/controller-utils` from `^11.18.0` to `^11.19.0` ([#7995](https://github.com/MetaMask/core/pull/7995))
1656
1760
 
1657
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@24.1.0...HEAD
1761
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@25.0.0...HEAD
1762
+ [25.0.0]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@24.1.0...@metamask/perps-controller@25.0.0
1658
1763
  [24.1.0]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@24.0.0...@metamask/perps-controller@24.1.0
1659
1764
  [24.0.0]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@23.1.0...@metamask/perps-controller@24.0.0
1660
1765
  [23.1.0]: https://github.com/MetaMask/core/compare/@metamask/perps-controller@23.0.0...@metamask/perps-controller@23.1.0
package/README.md CHANGED
@@ -78,11 +78,121 @@ registered venue, including HyperLiquid-only fallback when Lighter is
78
78
  unavailable, accepts these writes without an explicit route because there is
79
79
  only one destination.
80
80
 
81
- `cancelOrders` and `closePositions` cannot name a venue yet, so while multiple
82
- venues are registered they always return `PROVIDER_ROUTE_REQUIRED` instead of
83
- reaching the default venue. Cancel-all and close-all therefore stay unavailable
84
- in multi-venue aggregated mode until a release routes each order or position to
85
- its own venue and Lighter implements `cancelOrders` and `closePositions`.
81
+ `cancelOrders` and `closePositions` are venue-attributed rather than refused.
82
+ `cancelOrders({ orders: [{ orderId, providerId }] })` matches both fields,
83
+ so a colliding ID on another venue is not cancelled. Non-empty legacy `orderIds`
84
+ or `symbols` filters without scoped `orders` return `PROVIDER_ROUTE_REQUIRED`
85
+ when multiple venues are registered; use `orders` to identify the intended venue. Cancel-all batches reach every venue holding an order. An empty
86
+ `orders`, `orderIds` or `symbols` filter selects no orders. `closePositions` takes either `closeAll` (fans out to every enabled
87
+ venue) or explicit `targets` of `{ symbol, providerId }`. A supplied
88
+ `targets` list wins over `closeAll` and `symbols`, so an empty one closes
89
+ nothing. A legacy symbols-only close without venue identity still returns
90
+ `PROVIDER_ROUTE_REQUIRED` while multiple venues are registered, because closing
91
+ a symbol that exists on both venues is ambiguous. Results carry a `providerId`
92
+ per item, so identical symbols or order ids on different venues are never
93
+ conflated: each venue's successes and failures are reported
94
+ separately and one venue's failure never hides another venue's success.
95
+
96
+ Batch cancellation uses strict discovery: an unavailable venue is not an empty
97
+ venue. `CancelOrdersResult.discoveryFailures` names each failed venue and, for
98
+ ID-filtered requests, its unresolved `orderIds`. These targets have no discovered
99
+ symbol, so they are separate from `results`. `failureCount` includes unresolved
100
+ IDs, or one failure per unavailable venue when the order count is unknown;
101
+ `error` is the stable `BATCH_INCOMPLETE` code even when `success` is true.
102
+ Already discovered scoped targets are not counted as discovery failures, even
103
+ when another DEX on the same venue is unavailable. Before presenting a batch as
104
+ complete, clients must inspect `failureCount` and per-item `results` as well as
105
+ `error`, `discoveryFailures` and `failures`.
106
+ A complete direct-venue discovery failure uses the same code and attributes
107
+ its unresolved targets to the provider's validated protocol identity, never a
108
+ tracing tag. If an unknown protocol cannot be attributed safely, the result
109
+ still returns `BATCH_INCOMPLETE` without inventing a venue.
110
+
111
+ Both multi-venue cancel and close execution batches return `BATCH_INCOMPLETE`
112
+ when a venue throws or returns a batch error. `CancelOrdersResult.failures` and
113
+ `ClosePositionsResult.failures` retain every venue detail as
114
+ `{ providerId, error }[]`; discovery failures remain separate from execution
115
+ failures and per-item `results`. Successful work on other venues is preserved.
116
+ For close-all, a venue whose position discovery throws contributes one failure
117
+ when the number
118
+ of unclosed positions is unknown. Direct single-venue batch errors are preserved.
119
+
120
+ Batch closes resolve fees only for venues that consume fee resolutions or
121
+ discounts, exposed by `PerpsProvider.supportsFeeResolution(providerId)`.
122
+ Resolutions are computed sequentially: subscription notional allocated to an
123
+ earlier venue is subtracted from the allowance available to later venues.
124
+ Unused allowance is not persisted locally; the backend remains its source of truth.
125
+
126
+ Existing lenient reads remain unchanged. `getPositions` and
127
+ `getOpenOrders` (both venues, including standalone reads) accept `{ throwOnUnavailable: true }` for callers
128
+ that must distinguish failed discovery from an empty venue. Strict aggregated
129
+ open-order reads throw the exported `OrderDiscoveryError`, whose `orders` retain
130
+ successful reads and whose `failures` identify unavailable venues. These are
131
+ additive contracts: no state migration or existing call-site changes are needed,
132
+ but consumers of batch results should handle partial discovery before rollout.
133
+
134
+ ## Per-exchange account data
135
+
136
+ In aggregated mode, `getAccountState` and `subscribeToAccount` query every
137
+ enabled venue. The result keeps the top-level `AccountState` numeric fields as
138
+ combined totals — `totalBalance`, `spendableBalance`, `withdrawableBalance`,
139
+ `marginUsed` and `unrealizedPnl` are decimal-safe sums over the venues that
140
+ reported data, and `returnOnEquity` is the margin-weighted combined rate
141
+ (`100 × Σ unrealizedPnl ÷ Σ marginUsed`; `0` when no margin is used).
142
+
143
+ Each venue's own snapshot is in `providerStates[providerId]`: either
144
+ `{ status: 'available', state, providerId }` with that venue's balances,
145
+ `crossMarginSummary` and `subAccountBreakdown` (never merged into the top
146
+ level — cross-venue collateral is not mutually usable), or
147
+ `{ status: 'unavailable', error?, providerId }` for a venue whose read failed
148
+ or whose snapshot has a missing or non-finite additive field. Aggregated
149
+ account reads request that failure strictly: a HyperLiquid DEX clearinghouse
150
+ read or spot clearinghouse read that fails rejects the venue, so the combined
151
+ total is `partial` instead of a complete portfolio value. Aggregated account
152
+ streams ask each venue for `requireCompleteAccount`: HyperLiquid emits `null`
153
+ until every configured DEX has published and its spot balance has loaded, so a
154
+ failed DEX subscription keeps the total `partial` too. A stream venue
155
+ is `{ status: 'pending', providerId }` until its first snapshot, even if it
156
+ emits `null`. A rejected subscription setup is immediately `unavailable` instead
157
+ of pending. Lighter can only serve the selected wallet: requesting another
158
+ `accountId` excludes Lighter rather than mixing wallets, and a scoped stream
159
+ never starts emitting another wallet's balances after selection changes.
160
+ After a snapshot, `null` makes it unavailable. `aggregate`
161
+ metadata (`{ status: 'complete' | 'partial', availableProviders,
162
+ unavailableProviders, pendingProviders? }`) says whether the totals cover
163
+ every enabled venue. A `partial` total is a
164
+ subtotal: never present it as the user's complete portfolio value. A failed
165
+ read is never shown as a zero balance; a confirmed zero or nonexistent venue
166
+ account is an `available` entry with zero balances. When no venue has usable
167
+ data the read throws (REST) or the stream emits `null`. The account callback's
168
+ optional second argument carries this completeness metadata even when the
169
+ state is `null`, so pending and unavailable venues remain distinguishable.
170
+
171
+ The controller writes `perpsBalances[providerId]` from live account updates —
172
+ one entry per available venue with `totalBalance`, `unrealizedPnl` and
173
+ `lastUpdated`. Live updates leave `accountValue1dAgo` unset. A venue whose
174
+ data becomes unavailable has its entry removed rather than left looking live.
175
+ A pending venue keeps its stored entry for the same wallet until it reports a
176
+ snapshot, including when the first stream update is `null`. A `null` total
177
+ clears `accountState` and removes explicitly unavailable venues' entries.
178
+ A wallet change, deselection, or network toggle clears all balance entries. A
179
+ stream for an explicit `accountId` other than the selected account only
180
+ reaches its own callback: it neither writes nor clears `accountState` or
181
+ balance entries.
182
+ Combined `spendableBalance` and `withdrawableBalance` span venues: neither is
183
+ a limit any single venue will enforce on a new order or a withdrawal.
184
+
185
+ Market streams (`subscribeToCandles`, `subscribeToOICaps`,
186
+ `subscribeToOrderBook`) take an optional `providerId`. An explicit route
187
+ reaches that venue — required when both venues list the same symbol — and
188
+ stays pinned when the routing default changes. Omitting it keeps the
189
+ default-routed behavior. `getDepositRoutes` and `getWithdrawalRoutes` return
190
+ every active venue's routes, each tagged with a `providerId`; identical
191
+ asset/chain routes from different venues are distinct entries.
192
+ `depositWithConfirmation` funds the route for its `providerId`, or the
193
+ routing default when that is omitted, and fails closed when that venue has
194
+ no route. The chosen route's venue is captured on the deposit or withdrawal
195
+ record it initiates.
86
196
 
87
197
  ## Rewards discounts and fee previews
88
198
 
@@ -220,7 +220,7 @@ export type PerpsControllerSuspendChaseOrdersAction = {
220
220
  * Batch version of cancelOrder() that cancels multiple orders simultaneously
221
221
  *
222
222
  * @param params - The operation parameters.
223
- * @returns The batch cancellation results for each order.
223
+ * @returns Per-order results, plus `status`: `all`, `partial` or `none`.
224
224
  */
225
225
  export type PerpsControllerCancelOrdersAction = {
226
226
  type: `PerpsController:cancelOrders`;
@@ -242,7 +242,7 @@ export type PerpsControllerClosePositionAction = {
242
242
  * Batch version of closePosition() that closes multiple positions simultaneously
243
243
  *
244
244
  * @param params - The operation parameters.
245
- * @returns The batch close results for each position.
245
+ * @returns Per-position results, plus `status`: `all`, `partial` or `none`.
246
246
  */
247
247
  export type PerpsControllerClosePositionsAction = {
248
248
  type: `PerpsController:closePositions`;