@metamask-previews/perps-controller 25.0.0-preview-c785ff081 → 26.0.0-preview-203750488

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 (144) hide show
  1. package/CHANGELOG.md +95 -4
  2. package/dist/PerpsController-method-action-types.d.ts +149 -3
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +125 -3
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +746 -28
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +63 -0
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +73 -0
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +15 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +14 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/perpsConfig.d.ts +10 -1
  18. package/dist/constants/perpsConfig.d.ts.map +1 -1
  19. package/dist/constants/perpsConfig.js +11 -1
  20. package/dist/constants/perpsConfig.js.map +1 -1
  21. package/dist/index.d.ts +10 -8
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal/accountReturnOnEquity.d.ts +12 -0
  26. package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
  27. package/dist/internal/accountReturnOnEquity.js +18 -0
  28. package/dist/internal/accountReturnOnEquity.js.map +1 -0
  29. package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
  30. package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
  31. package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
  32. package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
  33. package/dist/internal/marketNumericValues.d.ts +10 -0
  34. package/dist/internal/marketNumericValues.d.ts.map +1 -0
  35. package/dist/internal/marketNumericValues.js +9 -0
  36. package/dist/internal/marketNumericValues.js.map +1 -0
  37. package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
  38. package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
  39. package/dist/internal/perpsDisplaySymbol.js +21 -0
  40. package/dist/internal/perpsDisplaySymbol.js.map +1 -0
  41. package/dist/perpsErrorCodes.d.ts +1 -0
  42. package/dist/perpsErrorCodes.d.ts.map +1 -1
  43. package/dist/perpsErrorCodes.js +1 -0
  44. package/dist/perpsErrorCodes.js.map +1 -1
  45. package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
  46. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  47. package/dist/providers/AggregatedPerpsProvider.js +140 -0
  48. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  49. package/dist/providers/HyperLiquidProvider.d.ts +72 -4
  50. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  51. package/dist/providers/HyperLiquidProvider.js +749 -157
  52. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  53. package/dist/providers/LighterProvider.d.ts +2 -1
  54. package/dist/providers/LighterProvider.d.ts.map +1 -1
  55. package/dist/providers/LighterProvider.js +3 -0
  56. package/dist/providers/LighterProvider.js.map +1 -1
  57. package/dist/services/HyperLiquidClientService.d.ts +8 -0
  58. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  59. package/dist/services/HyperLiquidClientService.js +65 -0
  60. package/dist/services/HyperLiquidClientService.js.map +1 -1
  61. package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
  62. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  63. package/dist/services/HyperLiquidSubscriptionService.js +97 -17
  64. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  65. package/dist/services/MarketDataService.d.ts +15 -1
  66. package/dist/services/MarketDataService.d.ts.map +1 -1
  67. package/dist/services/MarketDataService.js +43 -1
  68. package/dist/services/MarketDataService.js.map +1 -1
  69. package/dist/services/StreamChannelManager.d.ts +139 -0
  70. package/dist/services/StreamChannelManager.d.ts.map +1 -0
  71. package/dist/services/StreamChannelManager.js +475 -0
  72. package/dist/services/StreamChannelManager.js.map +1 -0
  73. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  74. package/dist/services/TerminalMarketService.js +7 -0
  75. package/dist/services/TerminalMarketService.js.map +1 -1
  76. package/dist/services/agentSigner.d.ts +8 -0
  77. package/dist/services/agentSigner.d.ts.map +1 -1
  78. package/dist/services/agentSigner.js +13 -0
  79. package/dist/services/agentSigner.js.map +1 -1
  80. package/dist/types/hyperliquid-types.d.ts +9 -1
  81. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  82. package/dist/types/hyperliquid-types.js +10 -0
  83. package/dist/types/hyperliquid-types.js.map +1 -1
  84. package/dist/types/index.d.ts +430 -14
  85. package/dist/types/index.d.ts.map +1 -1
  86. package/dist/types/index.js.map +1 -1
  87. package/dist/utils/accountAggregation.d.ts +17 -0
  88. package/dist/utils/accountAggregation.d.ts.map +1 -1
  89. package/dist/utils/accountAggregation.js +21 -5
  90. package/dist/utils/accountAggregation.js.map +1 -1
  91. package/dist/utils/accountUtils.d.ts +31 -10
  92. package/dist/utils/accountUtils.d.ts.map +1 -1
  93. package/dist/utils/accountUtils.js +68 -28
  94. package/dist/utils/accountUtils.js.map +1 -1
  95. package/dist/utils/closeCalculations.d.ts +17 -4
  96. package/dist/utils/closeCalculations.d.ts.map +1 -1
  97. package/dist/utils/closeCalculations.js +23 -7
  98. package/dist/utils/closeCalculations.js.map +1 -1
  99. package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
  100. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  101. package/dist/utils/hyperLiquidAdapter.js +17 -1
  102. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  103. package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
  104. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  105. package/dist/utils/hyperLiquidPositionPreview.js +264 -29
  106. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  107. package/dist/utils/index.d.ts +4 -2
  108. package/dist/utils/index.d.ts.map +1 -1
  109. package/dist/utils/index.js +1 -0
  110. package/dist/utils/index.js.map +1 -1
  111. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  112. package/dist/utils/lighterAdapter.js +46 -9
  113. package/dist/utils/lighterAdapter.js.map +1 -1
  114. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  115. package/dist/utils/marketDataTransform.js +8 -0
  116. package/dist/utils/marketDataTransform.js.map +1 -1
  117. package/dist/utils/marketUtils.d.ts +1 -2
  118. package/dist/utils/marketUtils.d.ts.map +1 -1
  119. package/dist/utils/marketUtils.js +7 -17
  120. package/dist/utils/marketUtils.js.map +1 -1
  121. package/dist/utils/orderBookGrouping.d.ts +35 -5
  122. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  123. package/dist/utils/orderBookGrouping.js +62 -6
  124. package/dist/utils/orderBookGrouping.js.map +1 -1
  125. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  126. package/dist/utils/perpsClientCopy.js +4 -0
  127. package/dist/utils/perpsClientCopy.js.map +1 -1
  128. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
  129. package/dist/utils/perpsDiskPersistence.js +10 -0
  130. package/dist/utils/perpsDiskPersistence.js.map +1 -1
  131. package/dist/utils/perpsFormatters.d.ts +31 -0
  132. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  133. package/dist/utils/perpsFormatters.js +26 -0
  134. package/dist/utils/perpsFormatters.js.map +1 -1
  135. package/dist/utils/sortMarkets.d.ts +13 -5
  136. package/dist/utils/sortMarkets.d.ts.map +1 -1
  137. package/dist/utils/sortMarkets.js +60 -38
  138. package/dist/utils/sortMarkets.js.map +1 -1
  139. package/docs/architecture.md +37 -7
  140. package/docs/client-contract.md +42 -17
  141. package/docs/contracts/events.md +34 -30
  142. package/docs/formatting.md +2 -0
  143. package/docs/venues/lighter/capabilities.md +18 -15
  144. package/package.json +1 -1
@@ -5,7 +5,7 @@ import { hasProperty } from '@metamask/utils';
5
5
  import { v4 as uuidv4 } from 'uuid';
6
6
  import { VISIBLE_CANDLE_COUNT_CONFIG, } from './constants/chartConfig.js';
7
7
  import { PERPS_EVENT_PROPERTY, PERPS_EVENT_VALUE, } from './constants/eventNames.js';
8
- import { canonicalizeHyperLiquidDexes, MAINNET_HIP3_CONFIG, TESTNET_HIP3_CONFIG, USDC_SYMBOL, } from './constants/hyperLiquidConfig.js';
8
+ import { canonicalizeHyperLiquidDexes, isCrossMarginSupported, MAINNET_HIP3_CONFIG, TESTNET_HIP3_CONFIG, USDC_SYMBOL, } from './constants/hyperLiquidConfig.js';
9
9
  import { PerpsMeasurementName } from './constants/performanceMetrics.js';
10
10
  import { PERPS_CONSTANTS, MARKET_SORTING_CONFIG, buildProviderCacheKey, MAX_SLIPPAGE_BOUNDS, DEFAULT_PERPS_MODE, DEFAULT_ORDER_BOOK_PREFERENCES, DEFAULT_PRO_LAYOUT_PREFERENCES, DEFAULT_SELECTED_ORDER_TYPE, } from './constants/perpsConfig.js';
11
11
  import { PERPS_ERROR_CODES } from './perpsErrorCodes.js';
@@ -24,6 +24,7 @@ import { MarketDataService } from './services/MarketDataService.js';
24
24
  import { isMissingActionHandlerError } from './services/missingActionHandler.js';
25
25
  import { isProviderOnTestnet } from './services/providerNetwork.js';
26
26
  import { RewardsIntegrationService } from './services/RewardsIntegrationService.js';
27
+ import { StreamChannelManager } from './services/StreamChannelManager.js';
27
28
  import { TerminalMarketService } from './services/TerminalMarketService.js';
28
29
  import { TradingService } from './services/TradingService.js';
29
30
  // PerpsStreamChannelKey removed: using string for channel keys (PerpsStreamManager.pauseChannel takes string)
@@ -478,6 +479,26 @@ const metadata = {
478
479
  * Number of public trades `getPublicTrades` returns when no limit is given.
479
480
  */
480
481
  const PUBLIC_TRADES_DEFAULT_LIMIT = 50;
482
+ /** `subscribeTo*` streams that read an account rather than a market. */
483
+ const ACCOUNT_STREAMS = new Set([
484
+ 'account',
485
+ 'availableToTrade',
486
+ 'chaseOrderLists',
487
+ 'feeRates',
488
+ 'liveTwapOrders',
489
+ 'marginAdjustmentLimits',
490
+ 'oiCaps',
491
+ 'orderFills',
492
+ 'orders',
493
+ 'positions',
494
+ 'tradingAgentValidity',
495
+ 'twapOrders',
496
+ ]);
497
+ /**
498
+ * Provider part of the key of a channel subscribed while no provider is
499
+ * active. The channel opens on the next successful initialization.
500
+ */
501
+ const PENDING_PROVIDER_CHANNEL_ID = 'pending';
481
502
  const MESSENGER_EXPOSED_METHODS = [
482
503
  'approveSubscriptionBuilderFee',
483
504
  'calculateFees',
@@ -529,6 +550,8 @@ const MESSENGER_EXPOSED_METHODS = [
529
550
  'getOrderBookPreferences',
530
551
  'getOrderCapabilities',
531
552
  'getMarginModeLock',
553
+ 'getMarginAdjustmentLimits',
554
+ 'getMarketMeta',
532
555
  'getScalePriceLadder',
533
556
  'getOrderFills',
534
557
  'getOrders',
@@ -537,6 +560,7 @@ const MESSENGER_EXPOSED_METHODS = [
537
560
  'getPositions',
538
561
  'getProviderHealth',
539
562
  'getPublicTrades',
563
+ 'getStreamSnapshot',
540
564
  'getSelectedOrderType',
541
565
  'getRecoveredDispatches',
542
566
  'getAttachedOrderGroups',
@@ -564,12 +588,14 @@ const MESSENGER_EXPOSED_METHODS = [
564
588
  'placeOrder',
565
589
  'prepareTradingWallet',
566
590
  'previewPositionModify',
591
+ 'estimateCrossLiquidation',
567
592
  'reconnect',
568
593
  'recordMarketViewed',
569
594
  'refreshEligibility',
570
595
  'replacePositionTPSLLeg',
571
596
  'resetFirstTimeUserState',
572
597
  'resetSelectedPaymentToken',
598
+ 'resubscribeStreams',
573
599
  'getMaxSlippage',
574
600
  'setMaxSlippage',
575
601
  'setOrderBookPreferences',
@@ -596,8 +622,12 @@ const MESSENGER_EXPOSED_METHODS = [
596
622
  'subscribeToAvailableToTrade',
597
623
  'subscribeToCandles',
598
624
  'subscribeToChaseOrderLists',
625
+ 'subscribeToConnectionLatency',
599
626
  'subscribeToConnectionState',
627
+ 'subscribeToFeeRates',
600
628
  'subscribeToLiveTwapOrders',
629
+ 'subscribeToMarginAdjustmentLimits',
630
+ 'subscribeToMarketMeta',
601
631
  'subscribeToOICaps',
602
632
  'subscribeToOrderBook',
603
633
  'subscribeToOrderFills',
@@ -606,6 +636,7 @@ const MESSENGER_EXPOSED_METHODS = [
606
636
  'subscribeToPrices',
607
637
  'subscribeToProviderHealth',
608
638
  'subscribeToPublicTrades',
639
+ 'subscribeToTradingAgentValidity',
609
640
  'subscribeToTwapOrders',
610
641
  'suspendChaseOrders',
611
642
  'switchProvider',
@@ -761,6 +792,18 @@ export class PerpsController extends BaseController {
761
792
  #unpersistedWatchlistAdds = new Map();
762
793
  #userDiskWrite = Promise.resolve();
763
794
  #providerSubscriptions = new Set();
795
+ /** The shared stream layer behind every `subscribeTo*` method. */
796
+ #streams = new StreamChannelManager({
797
+ subscribeToConnectionState: (listener) => this.subscribeToConnectionState(listener),
798
+ onError: (error) => this.#logError(ensureError(error, 'PerpsController.streams'), this.#getErrorContext('streams')),
799
+ });
800
+ #providerChannelIds = new WeakMap();
801
+ /**
802
+ * Channel sources being opened. Their provider subscriptions are not
803
+ * tracked for aggregated rebinding: the channel rebinds them itself.
804
+ */
805
+ #openingChannelSources = 0;
806
+ #nextProviderChannelId = 0;
764
807
  // A failed automatic rollback does not end the consumers' subscription context.
765
808
  #hasPendingSubscriptionRecovery = false;
766
809
  // Store options for dependency injection (allows core package to inject platform-specific services)
@@ -879,10 +922,16 @@ export class PerpsController extends BaseController {
879
922
  });
880
923
  }
881
924
  };
882
- this.messenger.subscribe('AccountsController:selectedAccountChange', () => updateSelectedTradingAccount(getSelectedEvmAccountFromMessenger(this.messenger)));
883
- this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId) => updateSelectedTradingAccount(groupId === ''
884
- ? null
885
- : getSelectedEvmAccountFromMessenger(this.messenger)));
925
+ this.messenger.subscribe('AccountsController:selectedAccountChange', () => {
926
+ updateSelectedTradingAccount(getSelectedEvmAccountFromMessenger(this.messenger));
927
+ this.#rebindStreams();
928
+ });
929
+ this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId) => {
930
+ updateSelectedTradingAccount(groupId === ''
931
+ ? null
932
+ : getSelectedEvmAccountFromMessenger(this.messenger));
933
+ this.#rebindStreams();
934
+ });
886
935
  this.providers = new Map();
887
936
  // Migrate old persisted data without accountAddress
888
937
  this.#migrateRequestsIfNeeded();
@@ -1683,6 +1732,7 @@ export class PerpsController extends BaseController {
1683
1732
  async #withStreamPause(operation, channels) {
1684
1733
  const pausedChannels = [];
1685
1734
  const { streamManager } = this.#options.infrastructure;
1735
+ const releases = channels.map((channel) => this.#streams.pause(channel));
1686
1736
  // Pause emission on specified channels (WebSocket stays connected)
1687
1737
  // Track which channels successfully paused to ensure proper cleanup
1688
1738
  for (const channel of channels) {
@@ -1704,6 +1754,9 @@ export class PerpsController extends BaseController {
1704
1754
  return await operation();
1705
1755
  }
1706
1756
  finally {
1757
+ for (const release of releases) {
1758
+ release();
1759
+ }
1707
1760
  // Resume only channels that were successfully paused
1708
1761
  for (const channel of pausedChannels) {
1709
1762
  try {
@@ -1800,6 +1853,8 @@ export class PerpsController extends BaseController {
1800
1853
  this.#reinitializationOperationPromise = operation;
1801
1854
  return () => {
1802
1855
  this.#isReinitializing = false;
1856
+ // Streams wait for the provider until the whole operation ends.
1857
+ this.#rebindStreams();
1803
1858
  resolveOperation();
1804
1859
  if (this.#reinitializationOperationPromise === operation) {
1805
1860
  this.#reinitializationOperationPromise = null;
@@ -1890,6 +1945,7 @@ export class PerpsController extends BaseController {
1890
1945
  if (preserveSubscriptions) {
1891
1946
  this.#restoreProviderSubscriptions();
1892
1947
  }
1948
+ this.#rebindStreams();
1893
1949
  return; // Exit retry loop on success
1894
1950
  }
1895
1951
  catch (error) {
@@ -1961,6 +2017,7 @@ export class PerpsController extends BaseController {
1961
2017
  ?.subscriptionBuilderAddressMainnet,
1962
2018
  onChaseOrderMaxDistanceReached: this.#publishChaseOrderMaxDistanceReached,
1963
2019
  getAgentSigner: this.#agentBindings.resolve,
2020
+ hasAgentSource: this.#agentBindings.hasSource,
1964
2021
  onAgentRejected: (account, agentAddress) => {
1965
2022
  this.#agentBindings.release(account, agentAddress);
1966
2023
  this.#options.clientConfig?.providerCredentials?.hyperliquid?.onAgentRejected?.(account, agentAddress);
@@ -2503,6 +2560,356 @@ export class PerpsController extends BaseController {
2503
2560
  return this.#getUnavailableMarginModeLock('provider_unavailable', resolvedProviderId);
2504
2561
  }
2505
2562
  }
2563
+ /**
2564
+ * Get how much margin an isolated position can take in (`maxAdd`, what the
2565
+ * venue's isolated margin update accepts) and release (`maxRemove`),
2566
+ * through the active provider route used by order placement. Never throws;
2567
+ * failures report an unavailable status.
2568
+ *
2569
+ * @param params - Market and optional provider route.
2570
+ * @returns The limits, or a typed unavailable result.
2571
+ */
2572
+ async getMarginAdjustmentLimits(params) {
2573
+ try {
2574
+ const activeProvider = await this.#getActiveProviderWhenReady();
2575
+ if (this.#hasConflictingProviderRoute(params.providerId, activeProvider) ||
2576
+ !activeProvider.getMarginAdjustmentLimits) {
2577
+ return { status: 'unavailable', reason: 'provider' };
2578
+ }
2579
+ return await activeProvider.getMarginAdjustmentLimits(params);
2580
+ }
2581
+ catch (error) {
2582
+ this.#debugLog('PerpsController: Margin adjustment limits unavailable', {
2583
+ error: ensureError(error, 'PerpsController.getMarginAdjustmentLimits')
2584
+ .message,
2585
+ });
2586
+ return { status: 'unavailable', reason: 'provider' };
2587
+ }
2588
+ }
2589
+ async getMarketMeta(params) {
2590
+ const provider = await this.#getActiveProviderWhenReady();
2591
+ const providerId = params?.providerId;
2592
+ if (this.#hasConflictingProviderRoute(providerId, provider)) {
2593
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
2594
+ }
2595
+ const symbol = params?.symbol;
2596
+ const metas = await this.#readMarketMetas(provider, providerId, symbol === undefined ? undefined : { symbols: [symbol] });
2597
+ if (symbol === undefined) {
2598
+ return metas;
2599
+ }
2600
+ const meta = metas.find((item) => item.symbol.toLowerCase() === symbol.toLowerCase());
2601
+ if (!meta) {
2602
+ throw new Error(PERPS_ERROR_CODES.MARKET_NOT_FOUND);
2603
+ }
2604
+ return meta;
2605
+ }
2606
+ /**
2607
+ * Read one venue's market list as metadata. The aggregated list drops a
2608
+ * failed venue, so the routed venue is read alone: a failure rejects
2609
+ * instead of reading as missing markets.
2610
+ *
2611
+ * @param provider - Active provider.
2612
+ * @param providerId - Optional explicit route.
2613
+ * @param marketsParams - Optional market filter and cache bypass.
2614
+ * @returns The venue's markets as metadata.
2615
+ */
2616
+ async #readMarketMetas(provider, providerId, marketsParams) {
2617
+ const markets = provider instanceof AggregatedPerpsProvider
2618
+ ? await provider.getProviderMarkets(provider.getWriteProviderId(providerId), marketsParams)
2619
+ : await provider.getMarkets(marketsParams);
2620
+ return markets.map((market) => ({
2621
+ symbol: market.name,
2622
+ marginTiers: market.marginTiers ?? null,
2623
+ isDelisted: market.isDelisted === true,
2624
+ maxLeverage: market.maxLeverage,
2625
+ onlyIsolated: !isCrossMarginSupported(market),
2626
+ }));
2627
+ }
2628
+ /**
2629
+ * Stream every market's metadata (margin tiers, delisting, max leverage,
2630
+ * Cross support) from the routed venue. The callback receives the current
2631
+ * list at once, from the provider's session cache, then a new list each
2632
+ * time the market data preload refreshes (`startMarketDataPreload`), which
2633
+ * re-reads the venue's metadata. It adds no timer of its own. A failed read
2634
+ * goes to `onError` and leaves the last list current; an empty list is
2635
+ * never reported for a failure. In aggregated mode an unrouted stream
2636
+ * rebinds to the new default provider.
2637
+ *
2638
+ * @param params - Optional provider route, callback and error handler.
2639
+ * @returns Cleanup function.
2640
+ */
2641
+ subscribeToMarketMeta(params) {
2642
+ return this.#subscribeToChannel('marketMeta', params, (channelParams) => this.#openMarketMeta(channelParams));
2643
+ }
2644
+ /**
2645
+ * Open the venue subscription behind a `marketMeta` channel.
2646
+ *
2647
+ * @param params - The channel's parameters.
2648
+ * @returns A cleanup function to remove the subscription.
2649
+ */
2650
+ #openMarketMeta(params) {
2651
+ const provider = this.getActiveProviderOrNull();
2652
+ if (!provider ||
2653
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
2654
+ params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
2655
+ return () => undefined;
2656
+ }
2657
+ const subscriber = { params, lastList: null };
2658
+ const open = (nextProvider) => {
2659
+ subscriber.provider = nextProvider;
2660
+ subscriber.lastList = null;
2661
+ this.#marketMetaSubscribers.add(subscriber);
2662
+ this.#emitMarketMeta(subscriber, false).catch(() => undefined);
2663
+ return () => {
2664
+ this.#marketMetaSubscribers.delete(subscriber);
2665
+ };
2666
+ };
2667
+ return this.#trackProviderSubscription(provider, open);
2668
+ }
2669
+ /**
2670
+ * Read the subscriber's venue and report its list when it changed.
2671
+ *
2672
+ * @param subscriber - Market metadata subscriber.
2673
+ * @param skipCache - Re-read the venue's metadata instead of the cache.
2674
+ */
2675
+ async #emitMarketMeta(subscriber, skipCache) {
2676
+ const { provider, params } = subscriber;
2677
+ if (!provider) {
2678
+ return;
2679
+ }
2680
+ try {
2681
+ const metas = await this.#readMarketMetas(provider, params.providerId, skipCache ? { skipCache: true } : undefined);
2682
+ // A subscriber that left, or rebound to another provider, during the
2683
+ // read gets nothing; an empty read is a failure, not a delisting.
2684
+ if (!this.#marketMetaSubscribers.has(subscriber) ||
2685
+ subscriber.provider !== provider) {
2686
+ return;
2687
+ }
2688
+ if (metas.length === 0) {
2689
+ throw new Error(PERPS_ERROR_CODES.MARKETS_FAILED);
2690
+ }
2691
+ const list = JSON.stringify(metas);
2692
+ if (list === subscriber.lastList) {
2693
+ return;
2694
+ }
2695
+ subscriber.lastList = list;
2696
+ params.callback(metas);
2697
+ }
2698
+ catch (error) {
2699
+ if (this.#marketMetaSubscribers.has(subscriber)) {
2700
+ params.onError?.(ensureError(error, 'PerpsController.subscribeToMarketMeta'));
2701
+ }
2702
+ }
2703
+ }
2704
+ /** Re-read every market metadata subscriber's venue after a preload. */
2705
+ #refreshMarketMetaSubscribers() {
2706
+ for (const subscriber of this.#marketMetaSubscribers) {
2707
+ this.#emitMarketMeta(subscriber, true).catch(() => undefined);
2708
+ }
2709
+ }
2710
+ /**
2711
+ * Stream an isolated position's margin adjustment limits from the routed
2712
+ * provider's live account and position streams, with no venue reads. The
2713
+ * callback receives the current limits at once, then each change: the
2714
+ * same result `getMarginAdjustmentLimits` returns. A provider without the
2715
+ * stream, or a route that conflicts with the active provider, reports
2716
+ * `unavailable`/`provider` once.
2717
+ *
2718
+ * @param params - Market, optional route, callback and error handler.
2719
+ * @returns Cleanup function.
2720
+ */
2721
+ subscribeToMarginAdjustmentLimits(params) {
2722
+ return this.#subscribeToChannel('marginAdjustmentLimits', params, (channelParams) => this.#openMarginAdjustmentLimits(channelParams));
2723
+ }
2724
+ /**
2725
+ * Open the venue subscription behind a `marginAdjustmentLimits` channel.
2726
+ *
2727
+ * @param params - The channel's parameters.
2728
+ * @returns A cleanup function to remove the subscription.
2729
+ */
2730
+ #openMarginAdjustmentLimits(params) {
2731
+ const unsupported = () => {
2732
+ params.callback({ status: 'unavailable', reason: 'provider' });
2733
+ return () => undefined;
2734
+ };
2735
+ const provider = this.getActiveProviderOrNull();
2736
+ if (!provider ||
2737
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
2738
+ return unsupported();
2739
+ }
2740
+ try {
2741
+ return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider) ||
2742
+ !nextProvider.subscribeToMarginAdjustmentLimits
2743
+ ? unsupported()
2744
+ : nextProvider.subscribeToMarginAdjustmentLimits(params));
2745
+ }
2746
+ catch (error) {
2747
+ this.#logError(ensureError(error, 'PerpsController.subscribeToMarginAdjustmentLimits'), this.#getErrorContext('subscribeToMarginAdjustmentLimits', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
2748
+ return unsupported();
2749
+ }
2750
+ }
2751
+ /**
2752
+ * Stream the routed provider's WebSocket keepalive round trip, in whole
2753
+ * milliseconds. The callback receives the last measurement at once when
2754
+ * there is one, then each new one, at the keepalive's own cadence. A
2755
+ * provider without a keepalive measurement never calls back.
2756
+ *
2757
+ * @param params - Optional provider route, callback and error handler.
2758
+ * @returns Cleanup function.
2759
+ */
2760
+ subscribeToConnectionLatency(params) {
2761
+ return this.#subscribeToChannel('connectionLatency', params, (channelParams) => this.#openConnectionLatency(channelParams));
2762
+ }
2763
+ /**
2764
+ * Open the venue subscription behind a `connectionLatency` channel.
2765
+ *
2766
+ * @param params - The channel's parameters.
2767
+ * @returns A cleanup function to remove the subscription.
2768
+ */
2769
+ #openConnectionLatency(params) {
2770
+ const provider = this.getActiveProviderOrNull();
2771
+ if (!provider ||
2772
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
2773
+ return () => undefined;
2774
+ }
2775
+ try {
2776
+ return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
2777
+ ? () => undefined
2778
+ : (nextProvider.subscribeToConnectionLatency?.(params) ??
2779
+ (() => undefined)));
2780
+ }
2781
+ catch (error) {
2782
+ params.onError?.(ensureError(error, 'PerpsController.subscribeToConnectionLatency'));
2783
+ return () => undefined;
2784
+ }
2785
+ }
2786
+ /**
2787
+ * Stream a market's post-discount fee rates: the `calculateFees` results
2788
+ * for a taker and a maker fill. The callback receives one read at once,
2789
+ * then a new read only on events: a fill on the account's own fills stream
2790
+ * (its volume tier can change), an account switch, a default provider
2791
+ * change in aggregated mode, and `invalidateSubscriptionBenefits`. There is
2792
+ * no timer. A failed read goes to `onError` and leaves the last rates
2793
+ * current; an unchanged read is not delivered.
2794
+ *
2795
+ * @param params - Market, optional order type, route, account, callback
2796
+ * and error handler.
2797
+ * @returns Cleanup function.
2798
+ */
2799
+ subscribeToFeeRates(params) {
2800
+ return this.#subscribeToChannel('feeRates', params, (channelParams) => this.#openFeeRates(channelParams));
2801
+ }
2802
+ /**
2803
+ * Open the reads behind a `feeRates` channel.
2804
+ *
2805
+ * @param params - The channel's parameters.
2806
+ * @returns A cleanup function to stop the reads.
2807
+ */
2808
+ #openFeeRates(params) {
2809
+ const provider = this.getActiveProviderOrNull();
2810
+ if (!provider) {
2811
+ params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
2812
+ return () => undefined;
2813
+ }
2814
+ const { symbol, orderType, providerId, accountId } = params;
2815
+ let closed = false;
2816
+ let readId = 0;
2817
+ let last;
2818
+ const read = () => {
2819
+ readId += 1;
2820
+ const id = readId;
2821
+ const quote = async (isMaker) => await this.calculateFees({
2822
+ symbol,
2823
+ providerId,
2824
+ isMaker,
2825
+ orderType: orderType ?? (isMaker ? 'limit' : 'market'),
2826
+ });
2827
+ Promise.all([quote(false), quote(true)])
2828
+ .then(([taker, maker]) => {
2829
+ // Only the newest read is reported, so an older one never wins.
2830
+ if (closed || id !== readId) {
2831
+ return;
2832
+ }
2833
+ const rates = { symbol, taker, maker };
2834
+ const key = JSON.stringify(rates);
2835
+ if (key !== last) {
2836
+ last = key;
2837
+ params.callback(rates);
2838
+ }
2839
+ })
2840
+ .catch((error) => {
2841
+ if (!closed && id === readId) {
2842
+ params.onError?.(ensureError(error, 'PerpsController.subscribeToFeeRates'));
2843
+ }
2844
+ });
2845
+ };
2846
+ this.#feeRateRefreshers.add(read);
2847
+ // Re-read when the aggregated default provider changes as well.
2848
+ const stopRoute = this.#trackProviderSubscription(provider, () => {
2849
+ read();
2850
+ return () => undefined;
2851
+ });
2852
+ const stopFills = this.subscribeToOrderFills({
2853
+ accountId,
2854
+ callback: (_fills, isSnapshot) => {
2855
+ if (!isSnapshot) {
2856
+ read();
2857
+ }
2858
+ },
2859
+ });
2860
+ // An account switch rebinds the channel, which reopens this read.
2861
+ return () => {
2862
+ closed = true;
2863
+ this.#feeRateRefreshers.delete(read);
2864
+ stopRoute();
2865
+ stopFills();
2866
+ };
2867
+ }
2868
+ /**
2869
+ * Report whether the selected (or given) account's trading agent is valid
2870
+ * for the routed venue (`PerpsTradingAgentValidity`). The callback receives
2871
+ * one read at once, then a new value on events only: an agent set or
2872
+ * cleared (`setAgentSigner`, `clearAgentSigners`), a venue rejection of the
2873
+ * agent, an account switch, and the agent's `validUntil` expiry, a single
2874
+ * timeout at that deadline. A venue without an agent step reports
2875
+ * `not_required`.
2876
+ *
2877
+ * @param params - Optional account and route, callback and error handler.
2878
+ * @returns Cleanup function.
2879
+ */
2880
+ subscribeToTradingAgentValidity(params) {
2881
+ return this.#subscribeToChannel('tradingAgentValidity', params, (channelParams) => this.#openTradingAgentValidity(channelParams));
2882
+ }
2883
+ /**
2884
+ * Open the venue subscription behind a `tradingAgentValidity` channel.
2885
+ *
2886
+ * @param params - The channel's parameters.
2887
+ * @returns A cleanup function to remove the subscription.
2888
+ */
2889
+ #openTradingAgentValidity(params) {
2890
+ const provider = this.getActiveProviderOrNull();
2891
+ if (!provider ||
2892
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
2893
+ params.onError?.(new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND));
2894
+ return () => undefined;
2895
+ }
2896
+ const open = (nextProvider) => {
2897
+ if (!nextProvider.subscribeToTradingAgentValidity) {
2898
+ params.callback({ status: 'not_required' });
2899
+ return () => undefined;
2900
+ }
2901
+ return nextProvider.subscribeToTradingAgentValidity(params);
2902
+ };
2903
+ try {
2904
+ // An account switch rebinds the channel, which reads the new account's
2905
+ // agent afresh.
2906
+ return this.#trackProviderSubscription(provider, open);
2907
+ }
2908
+ catch (error) {
2909
+ params.onError?.(ensureError(error, 'PerpsController.subscribeToTradingAgentValidity'));
2910
+ return () => undefined;
2911
+ }
2912
+ }
2506
2913
  #getUnavailableMarginModeLock(reason, providerId) {
2507
2914
  return providerId
2508
2915
  ? { status: 'unavailable', providerId, reason }
@@ -4312,6 +4719,10 @@ export class PerpsController extends BaseController {
4312
4719
  'hip3ConfigVersion',
4313
4720
  ]);
4314
4721
  #preloadTimer = null;
4722
+ /** Market metadata streams, refreshed after each market data preload. */
4723
+ #marketMetaSubscribers = new Set();
4724
+ /** Fee rate streams, re-read when subscription benefits are invalidated. */
4725
+ #feeRateRefreshers = new Set();
4315
4726
  #preloadStartRequested = false;
4316
4727
  #isPreloading = false;
4317
4728
  #marketPreloadQueued = false;
@@ -4407,7 +4818,9 @@ export class PerpsController extends BaseController {
4407
4818
  this.#previousIsTestnet = this.state.isTestnet;
4408
4819
  this.#previousHip3ConfigVersion = this.state.hip3ConfigVersion;
4409
4820
  // Immediate preload
4410
- this.#performMarketDataPreload().catch(() => {
4821
+ this.#performMarketDataPreload()
4822
+ .then(() => this.#refreshMarketMetaSubscribers())
4823
+ .catch(() => {
4411
4824
  /* fire-and-forget */
4412
4825
  });
4413
4826
  this.#performUserDataPreload().catch(() => {
@@ -4415,7 +4828,9 @@ export class PerpsController extends BaseController {
4415
4828
  });
4416
4829
  // Periodic refresh
4417
4830
  this.#preloadTimer = setInterval(() => {
4418
- this.#performMarketDataPreload().catch(() => {
4831
+ this.#performMarketDataPreload()
4832
+ .then(() => this.#refreshMarketMetaSubscribers())
4833
+ .catch(() => {
4419
4834
  /* fire-and-forget */
4420
4835
  });
4421
4836
  this.#performUserDataPreload().catch(() => {
@@ -4446,7 +4861,9 @@ export class PerpsController extends BaseController {
4446
4861
  // No need to clear user data cache — per-provider keys include the
4447
4862
  // network, so different networks don't collide. Re-preload will
4448
4863
  // populate the new key.
4449
- this.#performMarketDataPreload().catch(() => {
4864
+ this.#performMarketDataPreload()
4865
+ .then(() => this.#refreshMarketMetaSubscribers())
4866
+ .catch(() => {
4450
4867
  /* fire-and-forget */
4451
4868
  });
4452
4869
  this.#performUserDataPreload().catch(() => {
@@ -4679,7 +5096,9 @@ export class PerpsController extends BaseController {
4679
5096
  this.#isPreloading = false;
4680
5097
  if (this.#marketPreloadQueued && this.#preloadTimer) {
4681
5098
  this.#marketPreloadQueued = false;
4682
- this.#performMarketDataPreload().catch(() => {
5099
+ this.#performMarketDataPreload()
5100
+ .then(() => this.#refreshMarketMetaSubscribers())
5101
+ .catch(() => {
4683
5102
  // Background preload is best-effort.
4684
5103
  });
4685
5104
  }
@@ -4985,9 +5404,10 @@ export class PerpsController extends BaseController {
4985
5404
  });
4986
5405
  }
4987
5406
  /**
4988
- * Project the isolated position that would remain after a proposed order.
5407
+ * Project the position that would remain after a proposed order.
4989
5408
  * Margin and liquidation availability are independent: a missing liquidation
4990
- * does not hide a valid margin projection. Cross-margin returns unsupported.
5409
+ * does not hide a valid margin projection. Hyperliquid projects Cross
5410
+ * positions against the account's Cross collateral.
4991
5411
  *
4992
5412
  * @param params - Live position plus the proposed order.
4993
5413
  * @returns Discriminated preview of the resulting position.
@@ -5001,6 +5421,28 @@ export class PerpsController extends BaseController {
5001
5421
  context,
5002
5422
  });
5003
5423
  }
5424
+ /**
5425
+ * Estimate the liquidation price of the Cross position an order would
5426
+ * leave: an opening, or an add, reduce or flip of the market's position.
5427
+ * Never rejects: `price`, `none` when no price liquidates it at the
5428
+ * account's collateral, or `unavailable` with a typed reason.
5429
+ *
5430
+ * @param params - The proposed Cross order.
5431
+ * @returns The typed estimate.
5432
+ */
5433
+ async estimateCrossLiquidation(params) {
5434
+ // Not initialized or reinitializing: no provider to ask. A direct-mode
5435
+ // route that names another venue would answer for the wrong venue.
5436
+ const provider = this.getActiveProviderOrNull();
5437
+ if (!provider ||
5438
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
5439
+ return { status: 'unavailable', reason: 'provider' };
5440
+ }
5441
+ return this.#marketDataService.estimateCrossLiquidation({
5442
+ provider,
5443
+ params,
5444
+ });
5445
+ }
5004
5446
  /**
5005
5447
  * Calculate maintenance margin for a specific asset
5006
5448
  * Returns a percentage (e.g., 0.0125 for 1.25%)
@@ -5240,7 +5682,9 @@ export class PerpsController extends BaseController {
5240
5682
  // The state-change listener may have already fired during reinit
5241
5683
  // but was skipped due to the #isReinitializing guard.
5242
5684
  if (this.#preloadTimer) {
5243
- this.#performMarketDataPreload().catch(() => {
5685
+ this.#performMarketDataPreload()
5686
+ .then(() => this.#refreshMarketMetaSubscribers())
5687
+ .catch(() => {
5244
5688
  /* fire-and-forget */
5245
5689
  });
5246
5690
  this.#performUserDataPreload().catch(() => {
@@ -5407,7 +5851,9 @@ export class PerpsController extends BaseController {
5407
5851
  completeReinitialization();
5408
5852
  // Re-trigger preload now that reinit is complete.
5409
5853
  if (this.#preloadTimer) {
5410
- this.#performMarketDataPreload().catch(() => {
5854
+ this.#performMarketDataPreload()
5855
+ .then(() => this.#refreshMarketMetaSubscribers())
5856
+ .catch(() => {
5411
5857
  /* fire-and-forget */
5412
5858
  });
5413
5859
  this.#performUserDataPreload().catch(() => {
@@ -5614,17 +6060,16 @@ export class PerpsController extends BaseController {
5614
6060
  *
5615
6061
  * @param provider - Initially active provider.
5616
6062
  * @param open - Opens this subscription on a provider.
5617
- * @param onInvalidate - Invalidates a cached value while the route is detached.
5618
6063
  * @returns Cleanup that always removes the current binding.
5619
6064
  */
5620
- #trackProviderSubscription(provider, open, onInvalidate) {
5621
- if (provider.protocolId !== 'aggregated') {
6065
+ #trackProviderSubscription(provider, open) {
6066
+ if (provider.protocolId !== 'aggregated' ||
6067
+ this.#openingChannelSources > 0) {
5622
6068
  return open(provider);
5623
6069
  }
5624
6070
  const subscription = {
5625
6071
  open,
5626
6072
  unsubscribe: open(provider),
5627
- onInvalidate,
5628
6073
  };
5629
6074
  this.#providerSubscriptions.add(subscription);
5630
6075
  return () => {
@@ -5656,15 +6101,10 @@ export class PerpsController extends BaseController {
5656
6101
  catch (error) {
5657
6102
  this.#logProviderSubscriptionError(error);
5658
6103
  }
5659
- if (!discard && this.#providerSubscriptions.has(subscription)) {
5660
- try {
5661
- subscription.onInvalidate?.();
5662
- }
5663
- catch (error) {
5664
- this.#logProviderSubscriptionError(error);
5665
- }
5666
- }
5667
6104
  }
6105
+ // Stream channels stop before their provider disconnects; readers stay
6106
+ // and the next successful initialization reopens them.
6107
+ this.#streams.rebind((key) => key.providerId === PENDING_PROVIDER_CHANNEL_ID, (key) => ({ ...key, providerId: PENDING_PROVIDER_CHANNEL_ID }));
5668
6108
  }
5669
6109
  /** Reattach surviving registrations after rollback or a later recovery. */
5670
6110
  #restoreProviderSubscriptions() {
@@ -5700,6 +6140,148 @@ export class PerpsController extends BaseController {
5700
6140
  #logProviderSubscriptionError(error) {
5701
6141
  this.#logError(ensureError(error, 'PerpsController.providerSubscriptionRollback'), this.#getErrorContext('providerSubscriptionRollback'));
5702
6142
  }
6143
+ /**
6144
+ * Join the shared channel for one `subscribeTo*` call, opening the venue
6145
+ * subscription when it is the first reader. The key comes from
6146
+ * `#getChannelKey`. A call made while no provider is active joins a pending
6147
+ * channel that opens on the next successful initialization.
6148
+ *
6149
+ * @param stream - Stream name.
6150
+ * @param params - The caller's parameters.
6151
+ * @param open - Opens the venue subscription for the channel.
6152
+ * @param source - Replay and REST seed behaviour of the stream.
6153
+ * @param source.replay - Replay the last value to later readers.
6154
+ * @param source.read - REST read seeding the channel and run once per drop.
6155
+ * @returns Cleanup that leaves the channel.
6156
+ */
6157
+ #subscribeToChannel(stream, params, open, source = {}) {
6158
+ const { callback, onError, throttleMs, onReset, ...options } = params;
6159
+ const { read } = source;
6160
+ return this.#streams.subscribe(this.#getChannelKey(stream, options), {
6161
+ ...source,
6162
+ read: read
6163
+ ? async (key) => key.providerId === PENDING_PROVIDER_CHANNEL_ID
6164
+ ? undefined
6165
+ : await read()
6166
+ : undefined,
6167
+ open: (emit, fail, key) => {
6168
+ // A pending channel opens when `#rebindStreams` finds a provider.
6169
+ if (key.providerId === PENDING_PROVIDER_CHANNEL_ID) {
6170
+ return () => undefined;
6171
+ }
6172
+ this.#openingChannelSources += 1;
6173
+ try {
6174
+ return open({
6175
+ ...params,
6176
+ throttleMs: undefined,
6177
+ onReset: undefined,
6178
+ callback: emit,
6179
+ // Every reader of the channel hears its failures, not only the
6180
+ // reader that opened it.
6181
+ onError: fail,
6182
+ });
6183
+ }
6184
+ finally {
6185
+ this.#openingChannelSources -= 1;
6186
+ }
6187
+ },
6188
+ }, { callback, onError, throttleMs, onReset });
6189
+ }
6190
+ /**
6191
+ * The channel key of a stream: every parameter but the callbacks and
6192
+ * `throttleMs` (each reader throttles on its own), the active provider
6193
+ * instance, and for account streams the account, the selected one when none
6194
+ * is given. `prices` symbols are sorted so their order does not split
6195
+ * channels.
6196
+ *
6197
+ * @param stream - Stream name.
6198
+ * @param options - The stream's parameters without callbacks.
6199
+ * @returns The channel key.
6200
+ */
6201
+ #getChannelKey(stream, options) {
6202
+ const provider = this.getActiveProviderOrNull();
6203
+ const { symbols } = options;
6204
+ return {
6205
+ stream,
6206
+ providerId: provider
6207
+ ? String(this.#getProviderChannelId(provider))
6208
+ : PENDING_PROVIDER_CHANNEL_ID,
6209
+ accountId: ACCOUNT_STREAMS.has(stream)
6210
+ ? this.#getChannelAccountId(options)
6211
+ : undefined,
6212
+ options: stream === 'prices' && Array.isArray(symbols)
6213
+ ? { ...options, symbols: symbols.map(String).sort() }
6214
+ : options,
6215
+ };
6216
+ }
6217
+ /**
6218
+ * Move channels whose provider or selected account changed to the current
6219
+ * one: readers keep their subscription, receive `onReset`, then the new
6220
+ * context's data. Pending channels open here. Does nothing while no
6221
+ * provider is active.
6222
+ */
6223
+ #rebindStreams() {
6224
+ if (!this.getActiveProviderOrNull()) {
6225
+ return;
6226
+ }
6227
+ const nextKey = (key) => this.#getChannelKey(key.stream, key.options ?? {});
6228
+ this.#streams.rebind((key) => {
6229
+ const next = nextKey(key);
6230
+ return (next.providerId === key.providerId && next.accountId === key.accountId);
6231
+ }, nextKey);
6232
+ }
6233
+ /**
6234
+ * The last value a stream's channel delivered, for a synchronous first
6235
+ * render (such as React's `useSyncExternalStore`). Uses the same channel
6236
+ * as a `subscribeTo*` call with these parameters.
6237
+ *
6238
+ * @param stream - Stream name.
6239
+ * @param params - The `subscribeTo*` parameters; callbacks and throttle are
6240
+ * ignored.
6241
+ * @returns The callback arguments last delivered, or `undefined` when the
6242
+ * channel is not open or has no value yet.
6243
+ */
6244
+ getStreamSnapshot(stream, params) {
6245
+ const { callback: _callback, onError: _onError, onReset: _onReset, throttleMs: _throttleMs, ...options } = params;
6246
+ return this.#streams.getLast(this.#getChannelKey(stream, options));
6247
+ }
6248
+ /**
6249
+ * Stop and restart every open stream's venue subscription, keeping readers
6250
+ * and last values. For a socket that reports open but no longer delivers,
6251
+ * such as after an app returns to the foreground.
6252
+ */
6253
+ resubscribeStreams() {
6254
+ this.#streams.reopenAll();
6255
+ }
6256
+ /**
6257
+ * Account part of an account stream's channel key: the explicit account,
6258
+ * else the selected one.
6259
+ *
6260
+ * @param options - The stream's parameters without callbacks.
6261
+ * @returns The account key.
6262
+ */
6263
+ #getChannelAccountId(options) {
6264
+ if ('accountId' in options && typeof options.accountId === 'string') {
6265
+ return options.accountId;
6266
+ }
6267
+ const selected = getSelectedEvmAccountFromMessenger(this.messenger);
6268
+ return `selected:${selected?.address.toLowerCase() ?? 'none'}`;
6269
+ }
6270
+ /**
6271
+ * Stable id of a provider instance for channel keys.
6272
+ *
6273
+ * @param provider - Provider instance.
6274
+ * @returns Its id.
6275
+ */
6276
+ #getProviderChannelId(provider) {
6277
+ let id = this.#providerChannelIds.get(provider);
6278
+ if (id === undefined) {
6279
+ this.#nextProviderChannelId += 1;
6280
+ id = this.#nextProviderChannelId;
6281
+ this.#providerChannelIds.set(provider, id);
6282
+ }
6283
+ return id;
6284
+ }
5703
6285
  // Live data delegation (NO Redux) - delegates to active provider
5704
6286
  /**
5705
6287
  * Subscribe to live price updates
@@ -5708,6 +6290,15 @@ export class PerpsController extends BaseController {
5708
6290
  * @returns A cleanup function to remove the subscription.
5709
6291
  */
5710
6292
  subscribeToPrices(params) {
6293
+ return this.#subscribeToChannel('prices', params, (channelParams) => this.#openPrices(channelParams));
6294
+ }
6295
+ /**
6296
+ * Open the venue subscription behind a `prices` channel.
6297
+ *
6298
+ * @param params - The channel's parameters.
6299
+ * @returns A cleanup function to remove the subscription.
6300
+ */
6301
+ #openPrices(params) {
5711
6302
  const provider = this.getActiveProviderOrNull();
5712
6303
  if (!provider) {
5713
6304
  return () => {
@@ -5733,6 +6324,19 @@ export class PerpsController extends BaseController {
5733
6324
  * @returns A cleanup function to remove the subscription.
5734
6325
  */
5735
6326
  subscribeToPositions(params) {
6327
+ return this.#subscribeToChannel('positions', params, (channelParams) => this.#openPositions(channelParams), {
6328
+ read: async () => params.accountId === undefined
6329
+ ? [await this.getPositions(), params.includeSnapshotStatus]
6330
+ : undefined,
6331
+ });
6332
+ }
6333
+ /**
6334
+ * Open the venue subscription behind a `positions` channel.
6335
+ *
6336
+ * @param params - The channel's parameters.
6337
+ * @returns A cleanup function to remove the subscription.
6338
+ */
6339
+ #openPositions(params) {
5736
6340
  const provider = this.getActiveProviderOrNull();
5737
6341
  if (!provider) {
5738
6342
  return () => {
@@ -5758,6 +6362,15 @@ export class PerpsController extends BaseController {
5758
6362
  * @returns A cleanup function to remove the subscription.
5759
6363
  */
5760
6364
  subscribeToOrderFills(params) {
6365
+ return this.#subscribeToChannel('orderFills', params, (channelParams) => this.#openOrderFills(channelParams), { replay: false });
6366
+ }
6367
+ /**
6368
+ * Open the venue subscription behind a `orderFills` channel.
6369
+ *
6370
+ * @param params - The channel's parameters.
6371
+ * @returns A cleanup function to remove the subscription.
6372
+ */
6373
+ #openOrderFills(params) {
5761
6374
  const provider = this.getActiveProviderOrNull();
5762
6375
  if (!provider) {
5763
6376
  return () => {
@@ -5787,6 +6400,15 @@ export class PerpsController extends BaseController {
5787
6400
  * @returns A cleanup function to remove the subscription.
5788
6401
  */
5789
6402
  subscribeToTwapOrders(params) {
6403
+ return this.#subscribeToChannel('twapOrders', params, (channelParams) => this.#openTwapOrders(channelParams));
6404
+ }
6405
+ /**
6406
+ * Open the venue subscription behind a `twapOrders` channel.
6407
+ *
6408
+ * @param params - The channel's parameters.
6409
+ * @returns A cleanup function to remove the subscription.
6410
+ */
6411
+ #openTwapOrders(params) {
5790
6412
  const provider = this.getActiveProviderOrNull();
5791
6413
  if (!provider?.subscribeToTwapOrders) {
5792
6414
  return () => {
@@ -5794,7 +6416,7 @@ export class PerpsController extends BaseController {
5794
6416
  };
5795
6417
  }
5796
6418
  try {
5797
- return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined), () => params.callback([], true));
6419
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined));
5798
6420
  }
5799
6421
  catch (error) {
5800
6422
  this.#logError(ensureError(error, 'PerpsController.subscribeToTwapOrders'), this.#getErrorContext('subscribeToTwapOrders', {
@@ -5815,6 +6437,15 @@ export class PerpsController extends BaseController {
5815
6437
  * @returns A cleanup function that stops reads and the stream.
5816
6438
  */
5817
6439
  subscribeToLiveTwapOrders(params) {
6440
+ return this.#subscribeToChannel('liveTwapOrders', params, (channelParams) => this.#openLiveTwapOrders(channelParams));
6441
+ }
6442
+ /**
6443
+ * Open the venue subscription behind a `liveTwapOrders` channel.
6444
+ *
6445
+ * @param params - The channel's parameters.
6446
+ * @returns A cleanup function to remove the subscription.
6447
+ */
6448
+ #openLiveTwapOrders(params) {
5818
6449
  return createLiveTwapOrderList({
5819
6450
  source: {
5820
6451
  getTwapOrders: async () => await this.getTwapOrders(),
@@ -5887,6 +6518,15 @@ export class PerpsController extends BaseController {
5887
6518
  * @returns A cleanup function that stops reads.
5888
6519
  */
5889
6520
  subscribeToChaseOrderLists(params) {
6521
+ return this.#subscribeToChannel('chaseOrderLists', params, (channelParams) => this.#openChaseOrderLists(channelParams));
6522
+ }
6523
+ /**
6524
+ * Open the venue subscription behind a `chaseOrderLists` channel.
6525
+ *
6526
+ * @param params - The channel's parameters.
6527
+ * @returns A cleanup function to remove the subscription.
6528
+ */
6529
+ #openChaseOrderLists(params) {
5890
6530
  return createLiveChaseOrderList({
5891
6531
  source: {
5892
6532
  getChaseOrders: async () => await this.getChaseOrders(),
@@ -5942,6 +6582,23 @@ export class PerpsController extends BaseController {
5942
6582
  * @returns A cleanup function to remove the subscription.
5943
6583
  */
5944
6584
  subscribeToOrders(params) {
6585
+ return this.#subscribeToChannel('orders', params, (channelParams) => this.#openOrders(channelParams), {
6586
+ read: async () => params.accountId === undefined
6587
+ ? [
6588
+ await this.getOpenOrders({ throwOnUnavailable: true }),
6589
+ undefined,
6590
+ params.includeSnapshotStatus,
6591
+ ]
6592
+ : undefined,
6593
+ });
6594
+ }
6595
+ /**
6596
+ * Open the venue subscription behind a `orders` channel.
6597
+ *
6598
+ * @param params - The channel's parameters.
6599
+ * @returns A cleanup function to remove the subscription.
6600
+ */
6601
+ #openOrders(params) {
5945
6602
  const provider = this.getActiveProviderOrNull();
5946
6603
  if (!provider) {
5947
6604
  return () => {
@@ -6008,6 +6665,15 @@ export class PerpsController extends BaseController {
6008
6665
  * @returns A cleanup function to remove the subscription.
6009
6666
  */
6010
6667
  subscribeToAccount(params) {
6668
+ return this.#subscribeToChannel('account', params, (channelParams) => this.#openAccount(channelParams));
6669
+ }
6670
+ /**
6671
+ * Open the venue subscription behind a `account` channel.
6672
+ *
6673
+ * @param params - The channel's parameters.
6674
+ * @returns A cleanup function to remove the subscription.
6675
+ */
6676
+ #openAccount(params) {
6011
6677
  const provider = this.getActiveProviderOrNull();
6012
6678
  if (!provider) {
6013
6679
  return () => {
@@ -6125,7 +6791,7 @@ export class PerpsController extends BaseController {
6125
6791
  }
6126
6792
  throw error;
6127
6793
  }
6128
- }, () => originalCallback(null));
6794
+ });
6129
6795
  }
6130
6796
  catch (error) {
6131
6797
  this.#logError(ensureError(error, 'PerpsController.subscribeToAccount'), this.#getErrorContext('subscribeToAccount', {
@@ -6144,6 +6810,16 @@ export class PerpsController extends BaseController {
6144
6810
  * @returns A cleanup function to remove the subscription.
6145
6811
  */
6146
6812
  subscribeToOrderBook(params) {
6813
+ // A replaced transport does not restore the book; the channel reopens it.
6814
+ return this.#subscribeToChannel('orderBook', params, (channelParams) => this.#openOrderBook(channelParams), { reopenOnReconnect: true });
6815
+ }
6816
+ /**
6817
+ * Open the venue subscription behind a `orderBook` channel.
6818
+ *
6819
+ * @param params - The channel's parameters.
6820
+ * @returns A cleanup function to remove the subscription.
6821
+ */
6822
+ #openOrderBook(params) {
6147
6823
  const provider = this.getActiveProviderOrNull();
6148
6824
  if (!provider) {
6149
6825
  return () => {
@@ -6178,6 +6854,15 @@ export class PerpsController extends BaseController {
6178
6854
  * @returns A cleanup function to remove the subscription.
6179
6855
  */
6180
6856
  subscribeToAvailableToTrade(params) {
6857
+ return this.#subscribeToChannel('availableToTrade', params, (channelParams) => this.#openAvailableToTrade(channelParams));
6858
+ }
6859
+ /**
6860
+ * Open the venue subscription behind a `availableToTrade` channel.
6861
+ *
6862
+ * @param params - The channel's parameters.
6863
+ * @returns A cleanup function to remove the subscription.
6864
+ */
6865
+ #openAvailableToTrade(params) {
6181
6866
  const noop = () => {
6182
6867
  // No-op: value unavailable for this route
6183
6868
  };
@@ -6190,7 +6875,7 @@ export class PerpsController extends BaseController {
6190
6875
  return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
6191
6876
  ? () => undefined
6192
6877
  : (nextProvider.subscribeToAvailableToTrade?.(params) ??
6193
- (() => undefined)), () => params.onError?.(new Error('Available-to-trade provider replaced')));
6878
+ (() => undefined)));
6194
6879
  }
6195
6880
  catch (error) {
6196
6881
  this.#logError(ensureError(error, 'PerpsController.subscribeToAvailableToTrade'), this.#getErrorContext('subscribeToAvailableToTrade', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
@@ -6264,6 +6949,17 @@ export class PerpsController extends BaseController {
6264
6949
  * @returns A cleanup function to remove the subscription.
6265
6950
  */
6266
6951
  subscribeToPublicTrades(params) {
6952
+ return this.#subscribeToChannel('publicTrades', params, (channelParams) => this.#openPublicTrades(channelParams),
6953
+ // A replaced transport does not restore trades; the channel reopens it.
6954
+ { replay: false, reopenOnReconnect: true });
6955
+ }
6956
+ /**
6957
+ * Open the venue subscription behind a `publicTrades` channel.
6958
+ *
6959
+ * @param params - The channel's parameters.
6960
+ * @returns A cleanup function to remove the subscription.
6961
+ */
6962
+ #openPublicTrades(params) {
6267
6963
  const noop = () => {
6268
6964
  // No-op: no public trade feed for this route
6269
6965
  };
@@ -6314,6 +7010,15 @@ export class PerpsController extends BaseController {
6314
7010
  * @returns A cleanup function to remove the subscription.
6315
7011
  */
6316
7012
  subscribeToCandles(params) {
7013
+ return this.#subscribeToChannel('candles', params, (channelParams) => this.#openCandles(channelParams));
7014
+ }
7015
+ /**
7016
+ * Open the venue subscription behind a `candles` channel.
7017
+ *
7018
+ * @param params - The channel's parameters.
7019
+ * @returns A cleanup function to remove the subscription.
7020
+ */
7021
+ #openCandles(params) {
6317
7022
  const provider = this.getActiveProviderOrNull();
6318
7023
  if (!provider) {
6319
7024
  return () => {
@@ -6342,6 +7047,15 @@ export class PerpsController extends BaseController {
6342
7047
  * @returns A cleanup function to remove the subscription.
6343
7048
  */
6344
7049
  subscribeToOICaps(params) {
7050
+ return this.#subscribeToChannel('oiCaps', params, (channelParams) => this.#openOICaps(channelParams));
7051
+ }
7052
+ /**
7053
+ * Open the venue subscription behind a `oiCaps` channel.
7054
+ *
7055
+ * @param params - The channel's parameters.
7056
+ * @returns A cleanup function to remove the subscription.
7057
+ */
7058
+ #openOICaps(params) {
6345
7059
  const provider = this.getActiveProviderOrNull();
6346
7060
  if (!provider) {
6347
7061
  return () => {
@@ -6565,6 +7279,10 @@ export class PerpsController extends BaseController {
6565
7279
  */
6566
7280
  invalidateSubscriptionBenefits() {
6567
7281
  this.#rewardsIntegrationService.invalidateSubscriptionBenefits();
7282
+ // The discount the fee rates were priced with may have changed.
7283
+ for (const refresh of this.#feeRateRefreshers) {
7284
+ refresh();
7285
+ }
6568
7286
  }
6569
7287
  /**
6570
7288
  * Disconnect provider and cleanup subscriptions