@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 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 (156) hide show
  1. package/CHANGELOG.md +105 -9
  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 +787 -31
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +69 -9
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +82 -11
  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 -2
  18. package/dist/constants/perpsConfig.d.ts.map +1 -1
  19. package/dist/constants/perpsConfig.js +11 -3
  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 +751 -159
  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 +11 -6
  56. package/dist/providers/LighterProvider.js.map +1 -1
  57. package/dist/selectors.d.ts +15 -5
  58. package/dist/selectors.d.ts.map +1 -1
  59. package/dist/selectors.js +23 -5
  60. package/dist/selectors.js.map +1 -1
  61. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
  62. package/dist/services/AggregatedOrderBookConnection.js +8 -10
  63. package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
  64. package/dist/services/HyperLiquidClientService.d.ts +8 -0
  65. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  66. package/dist/services/HyperLiquidClientService.js +65 -0
  67. package/dist/services/HyperLiquidClientService.js.map +1 -1
  68. package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
  69. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  70. package/dist/services/HyperLiquidSubscriptionService.js +117 -30
  71. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  72. package/dist/services/MarketDataService.d.ts +20 -3
  73. package/dist/services/MarketDataService.d.ts.map +1 -1
  74. package/dist/services/MarketDataService.js +55 -3
  75. package/dist/services/MarketDataService.js.map +1 -1
  76. package/dist/services/StreamChannelManager.d.ts +139 -0
  77. package/dist/services/StreamChannelManager.d.ts.map +1 -0
  78. package/dist/services/StreamChannelManager.js +475 -0
  79. package/dist/services/StreamChannelManager.js.map +1 -0
  80. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  81. package/dist/services/TerminalMarketService.js +7 -0
  82. package/dist/services/TerminalMarketService.js.map +1 -1
  83. package/dist/services/agentSigner.d.ts +8 -0
  84. package/dist/services/agentSigner.d.ts.map +1 -1
  85. package/dist/services/agentSigner.js +13 -0
  86. package/dist/services/agentSigner.js.map +1 -1
  87. package/dist/types/hyperliquid-types.d.ts +9 -1
  88. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  89. package/dist/types/hyperliquid-types.js +10 -0
  90. package/dist/types/hyperliquid-types.js.map +1 -1
  91. package/dist/types/index.d.ts +434 -17
  92. package/dist/types/index.d.ts.map +1 -1
  93. package/dist/types/index.js.map +1 -1
  94. package/dist/utils/accountAggregation.d.ts +17 -0
  95. package/dist/utils/accountAggregation.d.ts.map +1 -1
  96. package/dist/utils/accountAggregation.js +21 -5
  97. package/dist/utils/accountAggregation.js.map +1 -1
  98. package/dist/utils/accountUtils.d.ts +31 -10
  99. package/dist/utils/accountUtils.d.ts.map +1 -1
  100. package/dist/utils/accountUtils.js +68 -28
  101. package/dist/utils/accountUtils.js.map +1 -1
  102. package/dist/utils/closeCalculations.d.ts +17 -4
  103. package/dist/utils/closeCalculations.d.ts.map +1 -1
  104. package/dist/utils/closeCalculations.js +23 -7
  105. package/dist/utils/closeCalculations.js.map +1 -1
  106. package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
  107. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  108. package/dist/utils/hyperLiquidAdapter.js +17 -1
  109. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  110. package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
  111. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  112. package/dist/utils/hyperLiquidPositionPreview.js +264 -29
  113. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  114. package/dist/utils/index.d.ts +4 -2
  115. package/dist/utils/index.d.ts.map +1 -1
  116. package/dist/utils/index.js +1 -0
  117. package/dist/utils/index.js.map +1 -1
  118. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  119. package/dist/utils/lighterAdapter.js +46 -9
  120. package/dist/utils/lighterAdapter.js.map +1 -1
  121. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  122. package/dist/utils/marketDataTransform.js +13 -8
  123. package/dist/utils/marketDataTransform.js.map +1 -1
  124. package/dist/utils/marketUtils.d.ts +1 -2
  125. package/dist/utils/marketUtils.d.ts.map +1 -1
  126. package/dist/utils/marketUtils.js +7 -17
  127. package/dist/utils/marketUtils.js.map +1 -1
  128. package/dist/utils/orderBookGrouping.d.ts +35 -5
  129. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  130. package/dist/utils/orderBookGrouping.js +62 -6
  131. package/dist/utils/orderBookGrouping.js.map +1 -1
  132. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  133. package/dist/utils/perpsClientCopy.js +4 -0
  134. package/dist/utils/perpsClientCopy.js.map +1 -1
  135. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
  136. package/dist/utils/perpsDiskPersistence.js +10 -0
  137. package/dist/utils/perpsDiskPersistence.js.map +1 -1
  138. package/dist/utils/perpsFormatters.d.ts +31 -0
  139. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  140. package/dist/utils/perpsFormatters.js +26 -0
  141. package/dist/utils/perpsFormatters.js.map +1 -1
  142. package/dist/utils/priceDeviation.d.ts +9 -6
  143. package/dist/utils/priceDeviation.d.ts.map +1 -1
  144. package/dist/utils/priceDeviation.js +17 -26
  145. package/dist/utils/priceDeviation.js.map +1 -1
  146. package/dist/utils/sortMarkets.d.ts +13 -5
  147. package/dist/utils/sortMarkets.d.ts.map +1 -1
  148. package/dist/utils/sortMarkets.js +60 -38
  149. package/dist/utils/sortMarkets.js.map +1 -1
  150. package/docs/architecture.md +54 -24
  151. package/docs/client-contract.md +52 -27
  152. package/docs/contracts/events.md +38 -32
  153. package/docs/contracts/feature-flags.md +4 -4
  154. package/docs/formatting.md +2 -0
  155. package/docs/venues/lighter/capabilities.md +18 -15
  156. package/package.json +1 -1
@@ -3,11 +3,12 @@ import { HyperliquidError } from '@nktkas/hyperliquid';
3
3
  import { BigNumber } from 'bignumber.js';
4
4
  import { v4 as uuidv4 } from 'uuid';
5
5
  import { PERPS_EVENT_PROPERTY, PERPS_EVENT_VALUE, } from '../constants/eventNames.js';
6
- import { BASIS_POINTS_DIVISOR, BUILDER_FEE_CONFIG, canonicalizeHyperLiquidDexes, FEE_RATES, HYPERLIQUID_ORDER_CAPABILITIES, getBridgeInfo, getChainId, HIP3_ASSET_MARKET_TYPES, HIP3_FEE_CONFIG, HIP3_MARGIN_CONFIG, HYPERLIQUID_ACCOUNT_SUPPORT_RECHECK_MS, HYPERLIQUID_ASSET_NAMES, HYPERLIQUID_CONFIG, HYPERLIQUID_WITHDRAWAL_MINUTES, isUnrestrictedMarginMode, REFERRAL_CONFIG, TRADING_DEFAULTS, USDC_DECIMALS, USDC_SYMBOL, } from '../constants/hyperLiquidConfig.js';
6
+ import { BASIS_POINTS_DIVISOR, BUILDER_FEE_CONFIG, canonicalizeHyperLiquidDexes, FEE_RATES, HYPERLIQUID_ORDER_CAPABILITIES, getBridgeInfo, getChainId, HIP3_ASSET_MARKET_TYPES, HIP3_FEE_CONFIG, HIP3_MARGIN_CONFIG, HYPERLIQUID_ACCOUNT_SUPPORT_RECHECK_MS, HYPERLIQUID_ASSET_NAMES, HYPERLIQUID_CONFIG, HYPERLIQUID_WITHDRAWAL_MINUTES, isCrossMarginSupported, REFERRAL_CONFIG, TRADING_DEFAULTS, USDC_DECIMALS, USDC_SYMBOL, } from '../constants/hyperLiquidConfig.js';
7
7
  import { DETAILED_ORDER_TYPES, isTPSLOrder } from '../constants/orderTypes.js';
8
- import { CHASE_ORDER_CONFIG, CHASE_ORDER_STATUS, DECIMAL_PRECISION_CONFIG, HYPERLIQUID_ORDER_LIMITS, HYPERLIQUID_TWAP_LIMITS, ORDER_SLIPPAGE_CONFIG, PERFORMANCE_CONFIG, PERPS_CONSTANTS, PROVIDER_CONFIG, SUBSCRIPTION_CLOID_CONFIG, TP_SL_CONFIG, WITHDRAWAL_CONSTANTS, } from '../constants/perpsConfig.js';
8
+ import { CHASE_ORDER_CONFIG, CHASE_ORDER_STATUS, DECIMAL_PRECISION_CONFIG, HYPERLIQUID_TWAP_LIMITS, ORDER_SLIPPAGE_CONFIG, PERFORMANCE_CONFIG, PERPS_CONSTANTS, PROVIDER_CONFIG, SUBSCRIPTION_CLOID_CONFIG, TP_SL_CONFIG, WITHDRAWAL_CONSTANTS, } from '../constants/perpsConfig.js';
9
9
  import { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig.js';
10
10
  import { OrderDiscoveryError, PerpsControllerError } from '../errors.js';
11
+ import { calculateHip3RebalanceAmount } from '../internal/hyperLiquidHip3Rebalance.js';
11
12
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
12
13
  import { AgentSignerUnavailableError, getAgentAccountKey, isAgentSignerUnavailableError, } from '../services/agentSigner.js';
13
14
  import { hasErrorInCauseChain } from '../services/causeChain.js';
@@ -16,7 +17,7 @@ import { HyperLiquidClientService, } from '../services/HyperLiquidClientService.
16
17
  import { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService.js';
17
18
  import { HyperLiquidWalletService } from '../services/HyperLiquidWalletService.js';
18
19
  import { TradingReadinessCache, PerpsSigningCache, } from '../services/TradingReadinessCache.js';
19
- import { HL_ABSTRACTION_WIRE, HL_UNIFIED_ACCOUNT_MODE, hyperLiquidModeFoldsSpot, } from '../types/hyperliquid-types.js';
20
+ import { HL_ABSTRACTION_WIRE, HL_UNIFIED_ACCOUNT_MODE, hyperLiquidModeFoldsSpot, isHyperLiquidStandardMode, } from '../types/hyperliquid-types.js';
20
21
  import { PerpsAnalyticsEvent } from '../types/index.js';
21
22
  import { getCrossCollateral, addSpotBalanceToAccountState, aggregateAccountStates, } from '../utils/accountUtils.js';
22
23
  import { boundTwapExecution, isChaseOrderRunning, reconcileTwapExecution, supersedesTwapOrder, } from '../utils/advancedOrders.js';
@@ -26,10 +27,11 @@ import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, attac
26
27
  import { ensureError, getHyperLiquidWriteGuardCode, isHyperLiquidMultiSigRequiredError, isHyperLiquidUserNotFoundError, isKeyringLockedError, normalizeHyperLiquidError, } from '../utils/errorUtils.js';
27
28
  import { shouldDeferUnifiedAccountSetup } from '../utils/hyperLiquidAbstraction.js';
28
29
  import { adaptAccountStateFromSDK, adaptHyperLiquidLedgerUpdateToUserHistoryItem, adaptMarketFromSDK, adaptOrderFromSDK, adaptPositionFromSDK, adaptPositionTriggerOrderFromSDK, adaptPublicTradesFromHyperLiquid, adaptTpslLinkageToGrouping, buildAssetMapping, buildHyperLiquidFillId, formatHyperLiquidPrice, formatHyperLiquidSize, HYPERLIQUID_SCALE_CLOID_MARKER, parseAssetName, readScaleGroupId, } from '../utils/hyperLiquidAdapter.js';
29
- import { estimateCrossLiquidationPrice, estimateCrossMaintenanceMargin, previewHyperLiquidIsolatedPositionModify, resolveHyperLiquidMarginTiers, } from '../utils/hyperLiquidPositionPreview.js';
30
+ import { isMarginRemovalAllowed, previewHyperLiquidCrossPositionModify, previewHyperLiquidIsolatedPositionModify, projectHyperLiquidCrossPositionModify, resolveHyperLiquidMarginTiers, } from '../utils/hyperLiquidPositionPreview.js';
30
31
  import { normalizeHyperLiquidScalePriceLadder } from '../utils/hyperLiquidScaleOrders.js';
31
32
  import { createErrorResult, getMaxOrderValue, getSupportedPaths, validateAssetSupport, validateBalance, validateCoinExists, validateDepositParams, validateOrderParams, validateWithdrawalParams, } from '../utils/hyperLiquidValidation.js';
32
33
  import { generatePerpsId } from '../utils/idUtils.js';
34
+ import { calculateMaxRemovableMargin } from '../utils/marginAdjustment.js';
33
35
  import { transformMarketData } from '../utils/marketDataTransform.js';
34
36
  import { compileMarketPattern, shouldIncludeMarket, } from '../utils/marketUtils.js';
35
37
  import { buildOrdersArray, calculateFinalPositionSize, calculateOrderPriceAndSize, computeChaseQuotePrice, floorToSizeDecimals, formatPartialTpslSize, getPriceTick, splitScaleSizes, validateOrderPrecision, } from '../utils/orderCalculations.js';
@@ -449,6 +451,9 @@ const validateStrategyNotional = (params) => {
449
451
  }
450
452
  return { isValid: true };
451
453
  };
454
+ const crossLiquidationUnavailable = (reason) => ({ status: 'unavailable', reason });
455
+ /** Longest delay `setTimeout` keeps; a later deadline is re-armed. */
456
+ const MAX_TIMEOUT_MS = 2_147_483_647;
452
457
  /**
453
458
  * Create one recoverable identity for a Scale ladder and one venue CLOID per
454
459
  * rung. HyperLiquid requires every CLOID to be unique, so the last byte holds
@@ -691,6 +696,52 @@ const resolveTwapOrderStatus = (historyEntry, executedSize, totalSize) => {
691
696
  return PerpsTwapLifecycleStatus.Active;
692
697
  }
693
698
  };
699
+ /**
700
+ * Whether a venue TWAP history entry can be read as a schedule: a safe,
701
+ * non-negative `twapId` and finite sizes, notional and times. The stream
702
+ * cache (`#adaptTwapOrder`) and the REST lock read both drop the rest, so
703
+ * they agree on which schedules exist.
704
+ *
705
+ * @param entry - One venue TWAP history entry.
706
+ * @returns True when the entry identifies a readable schedule.
707
+ */
708
+ const isReadableTwapHistoryEntry = (entry) => {
709
+ const { state, twapId } = entry;
710
+ return (twapId !== undefined &&
711
+ Number.isSafeInteger(twapId) &&
712
+ twapId >= 0 &&
713
+ new BigNumber(state.sz).isFinite() &&
714
+ new BigNumber(state.executedSz).isFinite() &&
715
+ new BigNumber(state.executedNtl).isFinite() &&
716
+ Number.isFinite(state.timestamp) &&
717
+ Number.isFinite(entry.time) &&
718
+ Number.isFinite(state.minutes));
719
+ };
720
+ /**
721
+ * Whether a raw `twapHistory` read shows a live schedule on a market. The
722
+ * latest entry per schedule decides; waiting and unknown venue states count
723
+ * as live. Native TWAP schedules are absent from frontendOpenOrders before a
724
+ * slice rests or fills, so the history is the only REST source for them.
725
+ *
726
+ * @param history - The venue's TWAP history for one wallet.
727
+ * @param symbol - Market symbol, including its DEX route when applicable.
728
+ * @returns True when a schedule on that market has not terminated.
729
+ */
730
+ const hasActiveTwapInHistory = (history, symbol) => {
731
+ const latestTwaps = new Map();
732
+ for (const entry of history) {
733
+ if (entry.state.coin !== symbol || !isReadableTwapHistoryEntry(entry)) {
734
+ continue;
735
+ }
736
+ const previous = latestTwaps.get(entry.twapId);
737
+ if (!previous ||
738
+ normalizeTwapHistoryTimestamp(entry.time) >=
739
+ normalizeTwapHistoryTimestamp(previous.time)) {
740
+ latestTwaps.set(entry.twapId, entry);
741
+ }
742
+ }
743
+ return [...latestTwaps.values()].some((entry) => resolveTwapOrderStatus(entry, new BigNumber(entry.state.executedSz), new BigNumber(entry.state.sz)) === PerpsTwapLifecycleStatus.Active);
744
+ };
694
745
  const adaptTwapOrderFill = (entry) => ({
695
746
  fillId: entry.fill.tid.toString(),
696
747
  orderId: entry.fill.oid.toString(),
@@ -867,6 +918,8 @@ export class HyperLiquidProvider {
867
918
  // Track whether clients have been initialized (lazy initialization)
868
919
  #clientsInitialized = false;
869
920
  #getAgentSigner;
921
+ #hasAgentSource;
922
+ #agentValiditySubscribers = new Set();
870
923
  // Incremented by clearAgentSigners so answers pending across a clear are
871
924
  // discarded and asked again.
872
925
  #agentSignersGeneration = 0;
@@ -913,6 +966,7 @@ export class HyperLiquidProvider {
913
966
  this.#subscriptionBuilderAddressMainnet =
914
967
  options.subscriptionBuilderAddressMainnet;
915
968
  this.#getAgentSigner = options.getAgentSigner;
969
+ this.#hasAgentSource = options.hasAgentSource;
916
970
  this.#onAgentRejected = options.onAgentRejected;
917
971
  this.#getCurrentIsTestnet = options.getCurrentIsTestnet;
918
972
  this.#onChaseOrderMaxDistanceReached =
@@ -1011,7 +1065,7 @@ export class HyperLiquidProvider {
1011
1065
  if (result.status === 'unavailable') {
1012
1066
  return result;
1013
1067
  }
1014
- const crossSupported = this.#isCrossMarginSupported(result.market);
1068
+ const crossSupported = isCrossMarginSupported(result.market);
1015
1069
  const supportedMarginModes = Object.freeze(crossSupported ? ['isolated', 'cross'] : ['isolated']);
1016
1070
  const { marginMode } = result.market;
1017
1071
  const crossMarginUnavailableReason = marginMode === 'noCross' || marginMode === 'strictIsolated'
@@ -1020,18 +1074,22 @@ export class HyperLiquidProvider {
1020
1074
  const marginModes = crossSupported
1021
1075
  ? { supportedMarginModes }
1022
1076
  : { supportedMarginModes, crossMarginUnavailableReason };
1077
+ // Copied: the market list is cached, and the estimates take a mutable
1078
+ // tier array.
1079
+ const marginTiers = result.market.marginTiers?.map((tier) => ({ ...tier }));
1080
+ const venueMarket = { ...marginModes, ...(marginTiers && { marginTiers }) };
1023
1081
  const { szDecimals } = result.market;
1024
1082
  if (!Number.isInteger(szDecimals) ||
1025
1083
  szDecimals < 0 ||
1026
1084
  szDecimals > DECIMAL_PRECISION_CONFIG.MaxPriceDecimals) {
1027
1085
  return Object.freeze({
1028
1086
  ...HYPERLIQUID_ORDER_CAPABILITIES,
1029
- ...marginModes,
1087
+ ...venueMarket,
1030
1088
  });
1031
1089
  }
1032
1090
  return Object.freeze({
1033
1091
  ...HYPERLIQUID_ORDER_CAPABILITIES,
1034
- ...marginModes,
1092
+ ...venueMarket,
1035
1093
  pricePrecision: Object.freeze({
1036
1094
  type: 'significant_figures',
1037
1095
  maxSignificantFigures: DECIMAL_PRECISION_CONFIG.MaxSignificantFigures,
@@ -1047,24 +1105,10 @@ export class HyperLiquidProvider {
1047
1105
  maxDurationMinutes: HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes,
1048
1106
  minNotionalUsd: HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd,
1049
1107
  }),
1050
- maxOraclePriceDeviation: HYPERLIQUID_ORDER_LIMITS.MaxOraclePriceDeviation,
1108
+ maxOraclePriceDeviation: this.#priceDeviationLimit,
1051
1109
  }),
1052
1110
  });
1053
1111
  }
1054
- /**
1055
- * Whether the venue accepts Cross margin for a market, main DEX or HIP-3.
1056
- * An absent `marginMode` or `normal` allows Cross; strictIsolated, noCross
1057
- * and any future restriction value prohibit it, as does the deprecated
1058
- * `onlyIsolated` flag.
1059
- *
1060
- * @param asset - Venue margin metadata for the market.
1061
- * @param asset.onlyIsolated - Whether the market only allows isolated margin.
1062
- * @param asset.marginMode - Venue margin-mode restriction, if any.
1063
- * @returns True when Cross margin orders are accepted.
1064
- */
1065
- #isCrossMarginSupported(asset) {
1066
- return !asset.onlyIsolated && isUnrestrictedMarginMode(asset.marginMode);
1067
- }
1068
1112
  /**
1069
1113
  * Report the margin mode HyperLiquid currently binds to a market, so
1070
1114
  * clients can match what order placement will accept.
@@ -1096,6 +1140,375 @@ export class HyperLiquidProvider {
1096
1140
  };
1097
1141
  }
1098
1142
  }
1143
+ /**
1144
+ * Report how much margin an isolated position can take in and release.
1145
+ * `maxAdd` is what `updateIsolatedMargin` accepts: on Unified and Portfolio
1146
+ * Margin accounts the free spot USDC (`spendableBalance`, spot total less
1147
+ * every margin in use, Cross included); on Standard accounts the perps
1148
+ * `withdrawable` of the position's DEX. `maxRemove` is
1149
+ * `calculateMaxRemovableMargin`, or 0 on a market that prohibits removal.
1150
+ * An unknown market, margin mode or position figure, or a failed read, is
1151
+ * `account_unknown`; an account mode without isolated margin limits is
1152
+ * `provider`.
1153
+ *
1154
+ * @param params - Market and optional provider route.
1155
+ * @returns The limits, or a typed unavailable result.
1156
+ */
1157
+ async getMarginAdjustmentLimits(params) {
1158
+ const lifecycleGeneration = this.#lifecycleGeneration;
1159
+ try {
1160
+ await this.#ensureClientsInitialized();
1161
+ this.#clientService.ensureInitialized();
1162
+ const limits = await this.#readMarginAdjustmentLimits(params.symbol);
1163
+ if (lifecycleGeneration !== this.#lifecycleGeneration) {
1164
+ return { status: 'unavailable', reason: 'account_unknown' };
1165
+ }
1166
+ return limits;
1167
+ }
1168
+ catch (error) {
1169
+ this.#deps.debugLogger.log('HyperLiquid: Margin adjustment limits unavailable', {
1170
+ symbol: params.symbol,
1171
+ error: ensureError(error, 'HyperLiquidProvider.getMarginAdjustmentLimits').message,
1172
+ });
1173
+ // A failed read is retryable; `provider` is for unsupported modes.
1174
+ return { status: 'unavailable', reason: 'account_unknown' };
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Stream an isolated position's margin adjustment limits from the live
1179
+ * account and position streams, with the same rules as
1180
+ * `getMarginAdjustmentLimits`: Unified and Portfolio Margin add from the
1181
+ * account's `spendableBalance`, Standard from its DEX's withdrawable. The
1182
+ * market comes from the session's metadata cache. The callback receives the
1183
+ * limits once the market is known, then each change.
1184
+ *
1185
+ * @param params - Market, optional account, callback and error handler.
1186
+ * @returns A cleanup function to unsubscribe.
1187
+ */
1188
+ subscribeToMarginAdjustmentLimits(params) {
1189
+ const { symbol, callback } = params;
1190
+ const { dex } = parseAssetName(symbol);
1191
+ let account;
1192
+ let positions;
1193
+ let market;
1194
+ let marketKnown = false;
1195
+ let closed = false;
1196
+ let last;
1197
+ const emit = () => {
1198
+ if (closed || !marketKnown) {
1199
+ return;
1200
+ }
1201
+ let limits;
1202
+ const mode = account?.accountMode;
1203
+ if (!account || !positions || mode === undefined) {
1204
+ limits = { status: 'unavailable', reason: 'account_unknown' };
1205
+ }
1206
+ else if (!hyperLiquidModeFoldsSpot(mode) &&
1207
+ !isHyperLiquidStandardMode(mode)) {
1208
+ limits = { status: 'unavailable', reason: 'provider' };
1209
+ }
1210
+ else {
1211
+ const maxAdd = isHyperLiquidStandardMode(mode)
1212
+ ? account.subAccountBreakdown?.[dex ?? 'main']?.withdrawableBalance
1213
+ : account.spendableBalance;
1214
+ limits =
1215
+ maxAdd === undefined
1216
+ ? { status: 'unavailable', reason: 'account_unknown' }
1217
+ : this.#computeMarginAdjustmentLimits(maxAdd, positions.find((item) => item.symbol === symbol), market);
1218
+ }
1219
+ const key = JSON.stringify(limits);
1220
+ if (key !== last) {
1221
+ last = key;
1222
+ callback(limits);
1223
+ }
1224
+ };
1225
+ const stopAccount = this.subscribeToAccount({
1226
+ callback: (next) => {
1227
+ account = next ?? undefined;
1228
+ emit();
1229
+ },
1230
+ });
1231
+ const stopPositions = this.subscribeToPositions({
1232
+ callback: (next) => {
1233
+ positions = next;
1234
+ emit();
1235
+ },
1236
+ });
1237
+ this.#fetchMarketsForDex({ dex })
1238
+ .then((markets) => {
1239
+ market = markets.find((item) => item.name === symbol);
1240
+ })
1241
+ // An unknown market is reported as `account_unknown`, never guessed.
1242
+ .catch(() => undefined)
1243
+ .finally(() => {
1244
+ marketKnown = true;
1245
+ emit();
1246
+ });
1247
+ return () => {
1248
+ closed = true;
1249
+ stopAccount();
1250
+ stopPositions();
1251
+ };
1252
+ }
1253
+ /**
1254
+ * Stream the round trip of the WebSocket keepalive ping the transport
1255
+ * already sends, in whole milliseconds. The last measurement, when there
1256
+ * is one, is delivered at once.
1257
+ *
1258
+ * @param params - Callback.
1259
+ * @returns A cleanup function to unsubscribe.
1260
+ */
1261
+ subscribeToConnectionLatency(params) {
1262
+ return this.#clientService.subscribeToLatency(params.callback);
1263
+ }
1264
+ /**
1265
+ * Report whether the account's agent is valid for the venue: resolved
1266
+ * through `getAgentSigner` and listed by `extraAgents` before its
1267
+ * `validUntil`. The callback receives one read at once, then a new value
1268
+ * when agents are set or cleared (`clearAgentSigners`), when the venue
1269
+ * rejects the agent, and at the agent's `validUntil` (a one-shot timeout).
1270
+ *
1271
+ * @param params - Optional account, callback and error handler.
1272
+ * @returns A cleanup function to unsubscribe.
1273
+ */
1274
+ subscribeToTradingAgentValidity(params) {
1275
+ let closed = false;
1276
+ let readId = 0;
1277
+ let deadline;
1278
+ let last;
1279
+ const clearDeadline = () => {
1280
+ clearTimeout(deadline);
1281
+ deadline = undefined;
1282
+ };
1283
+ // One timeout at the agent's expiry; a deadline beyond the longest
1284
+ // `setTimeout` delay is re-armed when it fires.
1285
+ function armDeadline(agentAddress, validUntil) {
1286
+ deadline = setTimeout(() => {
1287
+ deadline = undefined;
1288
+ if (Date.now() >= validUntil) {
1289
+ emit({ status: 'invalid', reason: 'expired', agentAddress });
1290
+ }
1291
+ else {
1292
+ armDeadline(agentAddress, validUntil);
1293
+ }
1294
+ }, Math.min(Math.max(validUntil - Date.now(), 0), MAX_TIMEOUT_MS));
1295
+ }
1296
+ function emit(validity) {
1297
+ clearDeadline();
1298
+ if (validity.status === 'valid' && validity.validUntil !== null) {
1299
+ armDeadline(validity.agentAddress, validity.validUntil);
1300
+ }
1301
+ const key = JSON.stringify(validity);
1302
+ if (key !== last) {
1303
+ last = key;
1304
+ params.callback(validity);
1305
+ }
1306
+ }
1307
+ const subscriber = {
1308
+ refresh: () => {
1309
+ readId += 1;
1310
+ const id = readId;
1311
+ this.#readTradingAgentValidity(params.accountId)
1312
+ .then(({ account, validity }) => {
1313
+ if (closed || id !== readId) {
1314
+ return;
1315
+ }
1316
+ subscriber.account = account;
1317
+ subscriber.agentAddress =
1318
+ 'agentAddress' in validity ? validity.agentAddress : undefined;
1319
+ emit(validity);
1320
+ })
1321
+ .catch((error) => {
1322
+ if (!closed && id === readId) {
1323
+ params.onError?.(ensureError(error, 'HyperLiquidProvider.subscribeToTradingAgentValidity'));
1324
+ }
1325
+ });
1326
+ },
1327
+ reject: (agentAddress) => {
1328
+ // A read in flight predates the rejection.
1329
+ readId += 1;
1330
+ emit({ status: 'invalid', reason: 'rejected', agentAddress });
1331
+ },
1332
+ };
1333
+ this.#agentValiditySubscribers.add(subscriber);
1334
+ subscriber.refresh();
1335
+ return () => {
1336
+ closed = true;
1337
+ clearDeadline();
1338
+ this.#agentValiditySubscribers.delete(subscriber);
1339
+ };
1340
+ }
1341
+ /**
1342
+ * Read the validity of an account's agent once.
1343
+ *
1344
+ * @param accountId - The account, or the selected one.
1345
+ * @returns The account checked and its agent's validity.
1346
+ */
1347
+ async #readTradingAgentValidity(accountId) {
1348
+ let account;
1349
+ try {
1350
+ await this.#ensureClientsInitialized();
1351
+ this.#clientService.ensureInitialized();
1352
+ const mainAddress = this.#walletService.getUserAddress(accountId ?? (await this.getCurrentAccountId()));
1353
+ account = { mainAddress, isTestnet: this.#clientService.isTestnetMode() };
1354
+ }
1355
+ catch {
1356
+ return { validity: { status: 'unknown', reason: 'account_unknown' } };
1357
+ }
1358
+ const hasSource = this.#hasAgentSource?.(account) ?? this.#getAgentSigner !== undefined;
1359
+ if (!hasSource) {
1360
+ return { account, validity: { status: 'not_required' } };
1361
+ }
1362
+ let agent;
1363
+ try {
1364
+ agent = await this.#resolveAgentSigner(account.mainAddress, account.isTestnet);
1365
+ }
1366
+ catch {
1367
+ return {
1368
+ account,
1369
+ validity: { status: 'unknown', reason: 'account_unknown' },
1370
+ };
1371
+ }
1372
+ if (!agent) {
1373
+ return { account, validity: { status: 'invalid', reason: 'no_agent' } };
1374
+ }
1375
+ const agentAddress = agent.address;
1376
+ try {
1377
+ const agents = await this.#clientService
1378
+ .getInfoClient({ useHttp: true })
1379
+ .extraAgents({ user: account.mainAddress });
1380
+ const listed = agents.find(({ address }) => address.toLowerCase() === agentAddress.toLowerCase());
1381
+ if (!listed) {
1382
+ return {
1383
+ account,
1384
+ validity: { status: 'invalid', reason: 'not_approved', agentAddress },
1385
+ };
1386
+ }
1387
+ if (listed.validUntil !== null && listed.validUntil <= Date.now()) {
1388
+ return {
1389
+ account,
1390
+ validity: { status: 'invalid', reason: 'expired', agentAddress },
1391
+ };
1392
+ }
1393
+ return {
1394
+ account,
1395
+ validity: {
1396
+ status: 'valid',
1397
+ agentAddress,
1398
+ validUntil: listed.validUntil,
1399
+ },
1400
+ };
1401
+ }
1402
+ catch (error) {
1403
+ this.#deps.debugLogger.log('HyperLiquidProvider: extraAgents failed', {
1404
+ error: ensureError(error, 'HyperLiquidProvider.readAgentValidity')
1405
+ .message,
1406
+ });
1407
+ return {
1408
+ account,
1409
+ validity: { status: 'unknown', reason: 'read_failed' },
1410
+ };
1411
+ }
1412
+ }
1413
+ async #readMarginAdjustmentLimits(symbol) {
1414
+ const { dex } = parseAssetName(symbol);
1415
+ const accountId = await this.getCurrentAccountId();
1416
+ const userAddress = this.#walletService.getUserAddress(accountId);
1417
+ const infoClient = this.#clientService.getInfoClient();
1418
+ const mode = await infoClient.userAbstraction({ user: userAddress });
1419
+ let maxAdd;
1420
+ let position;
1421
+ if (hyperLiquidModeFoldsSpot(mode)) {
1422
+ // The account read refuses a snapshot taken after a mode change.
1423
+ const reads = await Promise.all([
1424
+ this.#readAccountState({ accountId, throwOnUnavailable: true }, mode),
1425
+ this.getPositions({
1426
+ accountId,
1427
+ throwOnUnavailable: true,
1428
+ skipCache: true,
1429
+ includeProtection: false,
1430
+ }),
1431
+ ]).catch(async (error) => {
1432
+ if ((await infoClient.userAbstraction({ user: userAddress })) !== mode) {
1433
+ return null;
1434
+ }
1435
+ throw error;
1436
+ });
1437
+ if (!reads) {
1438
+ return { status: 'unavailable', reason: 'account_unknown' };
1439
+ }
1440
+ const [account, positions] = reads;
1441
+ maxAdd = account.spendableBalance;
1442
+ position = positions.find((item) => item.symbol === symbol);
1443
+ }
1444
+ else if (isHyperLiquidStandardMode(mode)) {
1445
+ const state = await infoClient.clearinghouseState(dex === null ? { user: userAddress } : { user: userAddress, dex });
1446
+ const assetPosition = state.assetPositions.find((item) => item.position.coin === symbol && Number(item.position.szi) !== 0);
1447
+ maxAdd = state.withdrawable;
1448
+ position =
1449
+ assetPosition &&
1450
+ adaptPositionFromSDK(assetPosition, state.crossMarginSummary);
1451
+ }
1452
+ else {
1453
+ return { status: 'unavailable', reason: 'provider' };
1454
+ }
1455
+ // The account can switch, or migrate collateral mode, while the reads
1456
+ // are in flight; a snapshot from another account or mode is not a limit.
1457
+ const [currentMode, currentAccount] = await Promise.all([
1458
+ infoClient.userAbstraction({ user: userAddress }),
1459
+ this.getCurrentAccountId(),
1460
+ ]);
1461
+ if (currentMode !== mode || currentAccount !== accountId) {
1462
+ return { status: 'unavailable', reason: 'account_unknown' };
1463
+ }
1464
+ const market = (await this.#fetchMarketsForDex({ dex })).find((item) => item.name === symbol);
1465
+ return this.#computeMarginAdjustmentLimits(maxAdd, position, market);
1466
+ }
1467
+ /**
1468
+ * Margin adjustment limits from an account's free margin, its position and
1469
+ * the market, shared by the read and the stream.
1470
+ *
1471
+ * @param maxAdd - Free margin the position can take in.
1472
+ * @param position - The market's position, if any.
1473
+ * @param market - The market, if known.
1474
+ * @returns The limits, or a typed unavailable result.
1475
+ */
1476
+ #computeMarginAdjustmentLimits(maxAdd, position, market) {
1477
+ if (position?.leverage.type !== 'isolated') {
1478
+ return { status: 'unavailable', reason: 'no_isolated_position' };
1479
+ }
1480
+ const addable = Number.parseFloat(maxAdd);
1481
+ if (!Number.isFinite(addable)) {
1482
+ return { status: 'unavailable', reason: 'account_unknown' };
1483
+ }
1484
+ // Only a confirmed strict-isolated market removes nothing; an unknown
1485
+ // market, margin mode or position figure is not a limit.
1486
+ const removalAllowed = isMarginRemovalAllowed(market);
1487
+ const positionLeverage = position.leverage.value;
1488
+ const currentMargin = Number.parseFloat(position.marginUsed);
1489
+ const notionalValue = Number.parseFloat(position.positionValue);
1490
+ if (removalAllowed === undefined ||
1491
+ positionLeverage === undefined ||
1492
+ !Number.isFinite(positionLeverage) ||
1493
+ !Number.isFinite(currentMargin) ||
1494
+ !Number.isFinite(notionalValue)) {
1495
+ return { status: 'unavailable', reason: 'account_unknown' };
1496
+ }
1497
+ const maxRemove = removalAllowed
1498
+ ? calculateMaxRemovableMargin({
1499
+ currentMargin,
1500
+ positionLeverage,
1501
+ notionalValue,
1502
+ })
1503
+ : 0;
1504
+ // Margin moves in micro-USDC; truncate so the amount never exceeds it.
1505
+ const usdcUnits = 10 ** USDC_DECIMALS;
1506
+ return {
1507
+ status: 'available',
1508
+ maxAdd: addable > 0 ? maxAdd : '0',
1509
+ maxRemove: (Math.floor(maxRemove * usdcUnits) / usdcUnits).toString(),
1510
+ };
1511
+ }
1099
1512
  /**
1100
1513
  * Normalize a Scale price ladder with HyperLiquid market precision.
1101
1514
  *
@@ -1621,6 +2034,13 @@ export class HyperLiquidProvider {
1621
2034
  this.#agentSigners.delete(key);
1622
2035
  }
1623
2036
  this.#deps.debugLogger.log('HyperLiquidProvider: agent rejected by the venue, asking again', { agent: agentAddress });
2037
+ for (const subscriber of this.#agentValiditySubscribers) {
2038
+ if (subscriber.account &&
2039
+ getAgentAccountKey(subscriber.account) === key &&
2040
+ subscriber.agentAddress?.toLowerCase() === agentAddress.toLowerCase()) {
2041
+ subscriber.reject(agentAddress);
2042
+ }
2043
+ }
1624
2044
  try {
1625
2045
  this.#onAgentRejected?.(account, agentAddress);
1626
2046
  }
@@ -3268,7 +3688,7 @@ export class HyperLiquidProvider {
3268
3688
  return [];
3269
3689
  }
3270
3690
  // Transform to MarketInfo format
3271
- const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset));
3691
+ const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset, meta.marginTables));
3272
3692
  // Apply HIP-3 filtering on-demand (cheap array operation)
3273
3693
  // Skip filtering for main DEX (null) or if explicitly requested
3274
3694
  const filteredMarkets = skipFilters || dex === null
@@ -4307,9 +4727,8 @@ export class HyperLiquidProvider {
4307
4727
  });
4308
4728
  // Auto-rebalance: Reclaim excess funds back to main DEX
4309
4729
  const desiredBuffer = HIP3_MARGIN_CONFIG.RebalanceDesiredBuffer;
4310
- const excessAmount = postOrderBalance - desiredBuffer;
4311
- const minimumTransferThreshold = HIP3_MARGIN_CONFIG.RebalanceMinThreshold;
4312
- if (excessAmount > minimumTransferThreshold) {
4730
+ const excessAmount = calculateHip3RebalanceAmount({ postOrderBalance });
4731
+ if (excessAmount > 0) {
4313
4732
  try {
4314
4733
  this.#deps.debugLogger.log('🔄 HyperLiquidProvider: Auto-rebalancing excess margin back to main DEX', {
4315
4734
  dex: dexName,
@@ -4353,8 +4772,9 @@ export class HyperLiquidProvider {
4353
4772
  }
4354
4773
  else {
4355
4774
  this.#deps.debugLogger.log('ℹ️ HyperLiquidProvider: No auto-rebalance needed', {
4356
- excessAmount: excessAmount.toFixed(2),
4357
- threshold: minimumTransferThreshold.toFixed(2),
4775
+ spendableBalance: postOrderBalance.toFixed(2),
4776
+ desiredBuffer: desiredBuffer.toFixed(2),
4777
+ threshold: HIP3_MARGIN_CONFIG.RebalanceMinThreshold.toFixed(2),
4358
4778
  note: 'Excess below minimum transfer threshold',
4359
4779
  });
4360
4780
  return true;
@@ -4481,8 +4901,7 @@ export class HyperLiquidProvider {
4481
4901
  if (!Number.isInteger(params.leverage) || (params.leverage ?? 0) < 1) {
4482
4902
  throw new Error(PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID);
4483
4903
  }
4484
- if (params.marginMode === 'cross' &&
4485
- !this.#isCrossMarginSupported(assetInfo)) {
4904
+ if (params.marginMode === 'cross' && !isCrossMarginSupported(assetInfo)) {
4486
4905
  throw new Error(PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED);
4487
4906
  }
4488
4907
  const lock = await this.#readMarginModeLock(params.symbol);
@@ -4497,6 +4916,13 @@ export class HyperLiquidProvider {
4497
4916
  * position fixes it first; otherwise a resting order or active TWAP fixes
4498
4917
  * the mode reported by the asset's leverage data.
4499
4918
  *
4919
+ * Positions, orders and TWAP schedules come from the live streams when the
4920
+ * target DEX has published them for this wallet on the current connection,
4921
+ * and from the venue otherwise. The leverage of a market locked by an order
4922
+ * comes from a live `activeAssetData` stream for the market (an order
4923
+ * form's available-to-trade subscription) when one is open, and from the
4924
+ * venue otherwise.
4925
+ *
4500
4926
  * @param symbol - Market symbol, including its DEX route when applicable.
4501
4927
  * @returns The locked mode and its cause, or null when nothing locks it.
4502
4928
  * @throws When the target DEX positions cannot be read, or when the
@@ -4514,49 +4940,50 @@ export class HyperLiquidProvider {
4514
4940
  throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
4515
4941
  }
4516
4942
  };
4517
- const { answered, positions } = await this.#queryDexPositions(dexName);
4518
- if (!answered) {
4519
- throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
4943
+ // Order and TWAP streams are only trusted alongside a live position
4944
+ // stream for the same DEX and wallet.
4945
+ const streamedPositions = this.#subscriptionService.getCachedPositionsForDex(dexName ?? '', user);
4946
+ let positions;
4947
+ if (streamedPositions) {
4948
+ positions = streamedPositions;
4949
+ }
4950
+ else {
4951
+ const venuePositions = await this.#queryDexPositions(dexName);
4952
+ if (!venuePositions.answered) {
4953
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
4954
+ }
4955
+ await assertSameAccount();
4956
+ positions = venuePositions.positions;
4520
4957
  }
4521
- await assertSameAccount();
4522
4958
  const position = positions.find((item) => item.symbol === symbol);
4523
4959
  if (position) {
4524
4960
  return { marginMode: position.leverage.type, reason: 'position' };
4525
4961
  }
4962
+ const streamedOrders = streamedPositions
4963
+ ? this.#subscriptionService.getCachedOpenOrdersForDex(dexName ?? '', user)
4964
+ : null;
4965
+ const streamedTwaps = streamedPositions
4966
+ ? this.#subscriptionService.getCachedActiveTwapOrders(user)
4967
+ : null;
4526
4968
  const infoClient = this.#clientService.getInfoClient();
4527
- const [orders, twapHistory] = await Promise.all([
4528
- this.#fetchOpenOrders({ dexName }),
4529
- infoClient.twapHistory({ user }),
4969
+ const [orders, hasActiveTwap] = await Promise.all([
4970
+ streamedOrders ?? this.#fetchOpenOrders({ dexName }),
4971
+ streamedTwaps
4972
+ ? streamedTwaps.some((order) => order.symbol === symbol)
4973
+ : infoClient
4974
+ .twapHistory({ user })
4975
+ .then((history) => hasActiveTwapInHistory(history, symbol)),
4530
4976
  ]);
4531
- await assertSameAccount();
4532
- // Native TWAP schedules are absent from frontendOpenOrders before a slice
4533
- // rests or fills. Read history directly: getTwapOrders can rebalance HIP-3
4534
- // collateral, which must not run as part of pre-sign validation.
4535
- const latestTwaps = new Map();
4536
- for (const entry of twapHistory) {
4537
- if (entry.state.coin !== symbol) {
4538
- continue;
4539
- }
4540
- const previous = latestTwaps.get(entry.twapId);
4541
- if (!previous ||
4542
- normalizeTwapHistoryTimestamp(entry.time) >=
4543
- normalizeTwapHistoryTimestamp(previous.time)) {
4544
- latestTwaps.set(entry.twapId, entry);
4545
- }
4977
+ if (!streamedOrders || !streamedTwaps) {
4978
+ await assertSameAccount();
4546
4979
  }
4547
- const hasActiveTwap = [...latestTwaps.values()].some((entry) => {
4548
- switch (entry.status.status) {
4549
- case HyperLiquidTwapLifecycleStatus.Finished:
4550
- case HyperLiquidTwapLifecycleStatus.Stopped:
4551
- case HyperLiquidTwapLifecycleStatus.Terminated:
4552
- case HyperLiquidTwapLifecycleStatus.Failed:
4553
- return false;
4554
- default:
4555
- // Waiting and future venue states are not proof of termination.
4556
- return true;
4557
- }
4558
- });
4559
4980
  if (orders.some((order) => order.coin === symbol) || hasActiveTwap) {
4981
+ // The market's leverage setting, from a live activeAssetData stream
4982
+ // (an order form's available-to-trade) when one is open.
4983
+ const streamedLeverage = this.#subscriptionService.getCachedActiveAssetLeverage(symbol, user);
4984
+ if (streamedLeverage) {
4985
+ return { marginMode: streamedLeverage.type, reason: 'open_order' };
4986
+ }
4560
4987
  const asset = await infoClient.activeAssetData({
4561
4988
  user,
4562
4989
  coin: symbol,
@@ -6803,21 +7230,13 @@ export class HyperLiquidProvider {
6803
7230
  */
6804
7231
  #adaptTwapOrder(params) {
6805
7232
  const { historyEntry, now } = params;
6806
- const { state, twapId } = historyEntry;
6807
- if (twapId === undefined || !Number.isSafeInteger(twapId) || twapId < 0) {
7233
+ if (!isReadableTwapHistoryEntry(historyEntry)) {
6808
7234
  return null;
6809
7235
  }
7236
+ const { state, twapId } = historyEntry;
6810
7237
  const totalSize = new BigNumber(state.sz);
6811
7238
  const executedSize = new BigNumber(state.executedSz);
6812
7239
  const executedNotional = new BigNumber(state.executedNtl);
6813
- if (!totalSize.isFinite() ||
6814
- !executedSize.isFinite() ||
6815
- !executedNotional.isFinite() ||
6816
- !Number.isFinite(state.timestamp) ||
6817
- !Number.isFinite(historyEntry.time) ||
6818
- !Number.isFinite(state.minutes)) {
6819
- return null;
6820
- }
6821
7240
  const { executedSize: boundedExecutedSize, remainingSize, fillProgressBps, } = boundTwapExecution(totalSize, executedSize);
6822
7241
  const status = resolveTwapOrderStatus(historyEntry, boundedExecutedSize, totalSize);
6823
7242
  const fills = params.sliceFills
@@ -11126,7 +11545,12 @@ export class HyperLiquidProvider {
11126
11545
  const aggregatedAccountState = addSpotBalanceToAccountState(aggregateAccountStates(dexAccountStates), standaloneSpotStateResult, {
11127
11546
  foldIntoCollateral: hyperLiquidModeFoldsSpot(standaloneAbstractionResult),
11128
11547
  abstractionMode: standaloneAbstractionResult,
11548
+ rejectMalformedLedger: strictAccountRead,
11129
11549
  });
11550
+ // The read mode, so clients can pass it to calculateAccountSummary.
11551
+ if (standaloneAbstractionResult) {
11552
+ aggregatedAccountState.accountMode = standaloneAbstractionResult;
11553
+ }
11130
11554
  if (standalonePerpsResults.failedDexs.length > 0) {
11131
11555
  aggregatedAccountState.unavailableSubAccounts =
11132
11556
  standalonePerpsResults.failedDexs.map(({ dex }) => dex ?? '');
@@ -11220,6 +11644,7 @@ export class HyperLiquidProvider {
11220
11644
  const aggregatedAccountState = addSpotBalanceToAccountState(aggregateAccountStates(dexAccountStates), spotState, {
11221
11645
  foldIntoCollateral: hyperLiquidModeFoldsSpot(abstractionMode),
11222
11646
  abstractionMode,
11647
+ rejectMalformedLedger: strictAccountRead,
11223
11648
  });
11224
11649
  // Build per-sub-account breakdown (HIP-3 DEXs map to sub-accounts)
11225
11650
  const subAccountBreakdown = {};
@@ -11235,6 +11660,10 @@ export class HyperLiquidProvider {
11235
11660
  });
11236
11661
  // Add sub-account breakdown to result
11237
11662
  aggregatedAccountState.subAccountBreakdown = subAccountBreakdown;
11663
+ // The read mode, so clients can pass it to calculateAccountSummary.
11664
+ if (abstractionMode !== null) {
11665
+ aggregatedAccountState.accountMode = abstractionMode;
11666
+ }
11238
11667
  // The totals exclude DEXs that did not answer; say which.
11239
11668
  if (failedPerpsDexs.length > 0) {
11240
11669
  aggregatedAccountState.unavailableSubAccounts = failedPerpsDexs.map(({ dex }) => dex ?? '');
@@ -11279,7 +11708,7 @@ export class HyperLiquidProvider {
11279
11708
  throw new Error('Invalid universe data received from HyperLiquid API');
11280
11709
  }
11281
11710
  // Transform to MarketInfo format
11282
- const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset));
11711
+ const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset, meta.marginTables));
11283
11712
  // Filter by symbols if provided
11284
11713
  if (params?.symbols?.length) {
11285
11714
  return markets.filter((market) => params.symbols?.some((symbol) => market.name.toUpperCase() === symbol.toUpperCase()));
@@ -11310,6 +11739,7 @@ export class HyperLiquidProvider {
11310
11739
  const marketArrays = await Promise.all(Array.from(symbolsByDex.keys()).map(async (dex) => this.#fetchMarketsForDex({
11311
11740
  dex,
11312
11741
  skipFilters: params?.skipFilters,
11742
+ skipCache: params?.skipCache,
11313
11743
  })));
11314
11744
  // Combine and filter by requested symbols
11315
11745
  const allMarkets = marketArrays.flat();
@@ -11332,6 +11762,7 @@ export class HyperLiquidProvider {
11332
11762
  return await this.#fetchMarketsForDex({
11333
11763
  dex,
11334
11764
  skipFilters: params?.skipFilters,
11765
+ skipCache: params?.skipCache,
11335
11766
  });
11336
11767
  }
11337
11768
  catch (error) {
@@ -11351,6 +11782,7 @@ export class HyperLiquidProvider {
11351
11782
  return await this.#fetchMarketsForDex({
11352
11783
  dex: params?.dex ?? null,
11353
11784
  skipFilters: params?.skipFilters,
11785
+ skipCache: params?.skipCache,
11354
11786
  });
11355
11787
  }
11356
11788
  catch (error) {
@@ -12769,6 +13201,10 @@ export class HyperLiquidProvider {
12769
13201
  clearAgentSigners() {
12770
13202
  this.#agentSignersGeneration += 1;
12771
13203
  this.#agentSigners.clear();
13204
+ // A set or cleared agent changes what validity readers report.
13205
+ for (const subscriber of this.#agentValiditySubscribers) {
13206
+ subscriber.refresh();
13207
+ }
12772
13208
  }
12773
13209
  /**
12774
13210
  * Run the deferred account migration, builder fee and referral setup ahead
@@ -12893,19 +13329,19 @@ export class HyperLiquidProvider {
12893
13329
  }
12894
13330
  }
12895
13331
  /**
12896
- * Project the isolated position that would remain after a proposed order.
13332
+ * Project the position that would remain after a proposed order.
12897
13333
  *
12898
13334
  * Fetches the asset's margin table from cached meta so liquidation uses the
12899
- * maintenance tier at the resulting liquidation notional. Cross-margin
12900
- * positions return unsupported without a table lookup.
13335
+ * maintenance tier at the resulting liquidation notional. A Cross position
13336
+ * is projected from the position the selected account holds and priced
13337
+ * against its Cross collateral and maintenance, as `#readCrossOrderAccount`
13338
+ * reads them; without them, or when the account holds no Cross position in
13339
+ * the market, only the margin is projected.
12901
13340
  *
12902
13341
  * @param params - Live position plus the proposed order.
12903
13342
  * @returns Discriminated preview; margin and liquidation are independently available.
12904
13343
  */
12905
13344
  async previewPositionModify(params) {
12906
- if (params.position.leverage.type === 'cross') {
12907
- return { status: 'unsupported', reason: 'cross_margin' };
12908
- }
12909
13345
  const { dex: dexName } = parseAssetName(params.position.symbol);
12910
13346
  let marginTiers = null;
12911
13347
  try {
@@ -12923,6 +13359,34 @@ export class HyperLiquidProvider {
12923
13359
  error,
12924
13360
  });
12925
13361
  }
13362
+ if (params.position.leverage.type === 'cross') {
13363
+ let crossAccount = null;
13364
+ let { position } = params;
13365
+ try {
13366
+ const context = await this.#readCrossOrderAccount({
13367
+ asset: params.position.symbol,
13368
+ positionSize: Number.parseFloat(params.size),
13369
+ orderPrice: Number.parseFloat(params.price),
13370
+ leverage: params.leverage,
13371
+ isBuy: params.direction === 'long',
13372
+ });
13373
+ // The account's maintenance must already hold the modified position,
13374
+ // projected as the account reads it.
13375
+ if (context.status === 'ok' && context.hasPosition) {
13376
+ crossAccount = context.crossAccount;
13377
+ position = context.position;
13378
+ }
13379
+ }
13380
+ catch (error) {
13381
+ this.#deps.debugLogger.log('HyperLiquidProvider: cross account unavailable for position preview', { symbol: params.position.symbol, error });
13382
+ }
13383
+ return previewHyperLiquidCrossPositionModify({
13384
+ ...params,
13385
+ position,
13386
+ marginTiers,
13387
+ crossAccount,
13388
+ });
13389
+ }
12926
13390
  return previewHyperLiquidIsolatedPositionModify({
12927
13391
  ...params,
12928
13392
  marginTiers,
@@ -12933,6 +13397,11 @@ export class HyperLiquidProvider {
12933
13397
  * Formula: liq_price = price - side * margin_available / position_size / (1 - maintenanceMarginRatio * side)
12934
13398
  * where maintenanceMarginRatio = 1 / MAINTENANCE_LEVERAGE = 1 / (2 * max_leverage)
12935
13399
  *
13400
+ * Cross (`marginType: 'cross'`) delegates to `estimateCrossLiquidation`.
13401
+ * Like the isolated estimate it resolves `'0'` when no positive price
13402
+ * liquidates the resulting position (`none`), and rejects
13403
+ * `LIQUIDATION_PRICE_UNAVAILABLE` when the estimate is `unavailable`.
13404
+ *
12936
13405
  * @param params - The operation parameters.
12937
13406
  * @returns A promise that resolves to the string result.
12938
13407
  */
@@ -12954,24 +13423,17 @@ export class HyperLiquidProvider {
12954
13423
  positionSize <= 0) {
12955
13424
  throw new PerpsControllerError(unavailable, unavailable);
12956
13425
  }
12957
- let estimate;
12958
- try {
12959
- estimate = await this.#estimateOpeningCrossLiquidationPrice({
12960
- asset,
12961
- entryPrice,
12962
- positionSize,
12963
- isLong: direction === 'long',
12964
- });
12965
- }
12966
- catch (error) {
12967
- throw new PerpsControllerError(unavailable, unavailable, undefined, {
12968
- cause: error,
12969
- });
12970
- }
12971
- if (estimate === null) {
13426
+ const estimate = await this.estimateCrossLiquidation({
13427
+ symbol: asset,
13428
+ direction,
13429
+ size: String(positionSize),
13430
+ entryPrice: String(entryPrice),
13431
+ leverage,
13432
+ });
13433
+ if (estimate.status === 'unavailable') {
12972
13434
  throw new PerpsControllerError(unavailable, unavailable);
12973
13435
  }
12974
- return String(estimate);
13436
+ return estimate.status === 'price' ? estimate.price : '0';
12975
13437
  }
12976
13438
  // Get asset's max leverage to calculate maintenance margin
12977
13439
  let maxLeverage = PERPS_CONSTANTS.DefaultMaxLeverage; // Default fallback
@@ -13013,16 +13475,89 @@ export class HyperLiquidProvider {
13013
13475
  return String(Math.max(0, liquidationPrice));
13014
13476
  }
13015
13477
  /**
13016
- * Estimate a new cross position using the selected wallet and venue tiers.
13478
+ * Liquidation price of the Cross position an order would leave: an opening,
13479
+ * or an add, reduce or flip of the market's position, priced against the
13480
+ * selected account's Cross collateral (`projectHyperLiquidCrossPositionModify`).
13481
+ * A `feeAmountUsd` is taken from the collateral as the fill takes it;
13482
+ * without one the estimate excludes the fee. Never rejects.
13483
+ *
13484
+ * @param params - The proposed Cross order.
13485
+ * @returns `price`, `none` when no positive price liquidates the resulting
13486
+ * position, or `unavailable` with the reason.
13487
+ */
13488
+ async estimateCrossLiquidation(params) {
13489
+ const { symbol, direction, leverage } = params;
13490
+ const positionSize = Number.parseFloat(params.size);
13491
+ const entryPrice = Number.parseFloat(params.entryPrice);
13492
+ if (!symbol ||
13493
+ (direction !== 'long' && direction !== 'short') ||
13494
+ !(positionSize > 0 && Number.isFinite(positionSize)) ||
13495
+ !(entryPrice > 0 && Number.isFinite(entryPrice)) ||
13496
+ !(leverage > 0 && Number.isFinite(leverage)) ||
13497
+ // A fee that is given must be a usable amount; it is never guessed.
13498
+ (params.feeAmountUsd !== undefined &&
13499
+ !(params.feeAmountUsd >= 0 && Number.isFinite(params.feeAmountUsd)))) {
13500
+ return crossLiquidationUnavailable('missing_inputs');
13501
+ }
13502
+ try {
13503
+ const context = await this.#readCrossOrderAccount({
13504
+ asset: symbol,
13505
+ positionSize,
13506
+ orderPrice: entryPrice,
13507
+ leverage,
13508
+ isBuy: direction === 'long',
13509
+ });
13510
+ if (context.status === 'unavailable') {
13511
+ return context;
13512
+ }
13513
+ const projection = projectHyperLiquidCrossPositionModify({
13514
+ position: context.position,
13515
+ direction,
13516
+ size: params.size,
13517
+ price: params.entryPrice,
13518
+ leverage,
13519
+ // Without a fee the estimate excludes it.
13520
+ feeAmountUsd: params.feeAmountUsd ?? 0,
13521
+ marginTiers: context.marginTiers,
13522
+ crossAccount: context.crossAccount,
13523
+ });
13524
+ if (projection.status !== 'open') {
13525
+ return crossLiquidationUnavailable('missing_inputs');
13526
+ }
13527
+ const { liquidation } = projection;
13528
+ if (liquidation.status === 'price') {
13529
+ return { status: 'price', price: String(liquidation.price) };
13530
+ }
13531
+ return liquidation.status === 'covered_by_account'
13532
+ ? { status: 'none', reason: 'covered_by_account' }
13533
+ : crossLiquidationUnavailable('missing_inputs');
13534
+ }
13535
+ catch (error) {
13536
+ this.#deps.debugLogger.log('HyperLiquidProvider: Cross account unavailable for liquidation estimate', { symbol, error });
13537
+ return crossLiquidationUnavailable('account_unknown');
13538
+ }
13539
+ }
13540
+ /**
13541
+ * Read the selected account's Cross figures for an order on `asset`: its
13542
+ * Cross collateral and maintenance, the market's tiers and the live
13543
+ * position, flat when the account holds none.
13544
+ *
13545
+ * Standard accounts keep a separate clearinghouse per DEX. On a HIP-3 DEX
13546
+ * with `useUnifiedAccount` off, placement moves margin in from another DEX
13547
+ * when the DEX's withdrawable balance is below the order's required margin,
13548
+ * and returns the excess afterwards (`#handleHip3PreOrder`, `#handleHip3PostOrderRebalance`).
13549
+ * `hip3Funding` carries that balance and the required margin placement
13550
+ * computes, so the estimate prices the DEX as placement leaves it.
13017
13551
  *
13018
- * @param params - Sized order and its preview price.
13552
+ * @param params - The proposed order.
13019
13553
  * @param params.asset - Venue market symbol.
13020
- * @param params.entryPrice - Expected price at entry.
13021
- * @param params.positionSize - Absolute size in base units.
13022
- * @param params.isLong - Whether the new position is long.
13023
- * @returns The estimated price, or null if the preview is unavailable.
13554
+ * @param params.positionSize - Order size in base units.
13555
+ * @param params.orderPrice - Expected fill or limit price.
13556
+ * @param params.leverage - Leverage placement sets on the asset.
13557
+ * @param params.isBuy - Whether the order buys.
13558
+ * @returns The Cross inputs, or why they are unavailable.
13024
13559
  */
13025
- async #estimateOpeningCrossLiquidationPrice({ asset, entryPrice, positionSize, isLong, }) {
13560
+ async #readCrossOrderAccount({ asset, positionSize, orderPrice, leverage, isBuy, }) {
13026
13561
  const generation = this.#lifecycleGeneration;
13027
13562
  const accountId = await this.getCurrentAccountId();
13028
13563
  const userAddress = this.#walletService.getUserAddress(accountId);
@@ -13031,74 +13566,122 @@ export class HyperLiquidProvider {
13031
13566
  if (dex !== null &&
13032
13567
  (!(await this.#getValidatedDexsStrict()).includes(dex) ||
13033
13568
  !(await this.#fetchMarketsForDex({ dex })).some((market) => market.name === asset))) {
13034
- return null;
13569
+ return crossLiquidationUnavailable('missing_inputs');
13035
13570
  }
13036
13571
  const meta = await this.#getCachedMeta({ dexName: dex });
13037
13572
  const currentAccount = await this.getCurrentAccountId();
13038
13573
  const market = meta.universe.find((item) => item.name === asset);
13039
13574
  if (currentAccount !== accountId ||
13040
- generation !== this.#lifecycleGeneration ||
13041
- !market ||
13042
- !this.#isCrossMarginSupported(market)) {
13043
- return null;
13575
+ generation !== this.#lifecycleGeneration) {
13576
+ return crossLiquidationUnavailable('account_unknown');
13577
+ }
13578
+ if (!market || !isCrossMarginSupported(market)) {
13579
+ return crossLiquidationUnavailable('missing_inputs');
13044
13580
  }
13045
- // An add, close or flip needs the existing position's change in
13046
- // maintenance. This preview only models an opening in a flat market.
13047
13581
  const streamed = this.#subscriptionService.getFreshCrossMarginContext(userAddress, asset);
13048
- if (streamed?.hasPosition) {
13049
- return null;
13582
+ let context;
13583
+ if (streamed) {
13584
+ const position = streamed.hasPosition
13585
+ ? this.#subscriptionService
13586
+ .getCachedPositionsForDex(dex ?? '', userAddress)
13587
+ ?.find((item) => item.symbol === asset)
13588
+ : undefined;
13589
+ context =
13590
+ streamed.hasPosition && !position
13591
+ ? crossLiquidationUnavailable('account_unknown')
13592
+ : {
13593
+ status: 'ok',
13594
+ summary: streamed.summary,
13595
+ spotCollateral: streamed.spotCollateral,
13596
+ position,
13597
+ };
13050
13598
  }
13051
- const context = streamed ??
13052
- (await this.#readCrossMarginContext(asset, accountId, userAddress, generation));
13053
- if (!context) {
13054
- return null;
13599
+ else {
13600
+ context = await this.#readCrossMarginContext(asset, accountId, userAddress, generation);
13601
+ }
13602
+ if (context.status === 'unavailable') {
13603
+ return context;
13604
+ }
13605
+ const { summary, spotCollateral, position, withdrawable } = context;
13606
+ // An isolated position in the market holds no Cross maintenance.
13607
+ if (position !== undefined && position.leverage.type !== 'cross') {
13608
+ return crossLiquidationUnavailable('missing_inputs');
13055
13609
  }
13056
- const { summary, spotCollateral } = context;
13057
13610
  const accountValue = getCrossCollateral(summary, spotCollateral);
13058
13611
  if (accountValue === undefined ||
13059
13612
  summary === undefined ||
13060
13613
  summary.maintenanceMargin.trim() === '') {
13061
- return null;
13614
+ return crossLiquidationUnavailable('missing_inputs');
13062
13615
  }
13063
- const priorMaintenance = Number(summary.maintenanceMargin);
13064
- if (!Number.isFinite(priorMaintenance) || priorMaintenance < 0) {
13065
- return null;
13066
- }
13067
- const marginTiers = resolveHyperLiquidMarginTiers({
13068
- marginTableId: market.marginTableId,
13069
- maxLeverage: market.maxLeverage,
13070
- marginTables: meta.marginTables,
13071
- });
13072
- const addedMaintenance = estimateCrossMaintenanceMargin([
13073
- { notional: entryPrice * positionSize, marginTiers },
13074
- ]);
13075
- if (addedMaintenance === null) {
13076
- return null;
13616
+ const maintenanceMargin = Number(summary.maintenanceMargin);
13617
+ if (!Number.isFinite(maintenanceMargin) || maintenanceMargin < 0) {
13618
+ return crossLiquidationUnavailable('missing_inputs');
13077
13619
  }
13078
- return estimateCrossLiquidationPrice({
13079
- isLong,
13080
- markPrice: entryPrice,
13081
- positionSize,
13620
+ const crossAccount = {
13082
13621
  accountValue,
13083
- maintenanceMargin: priorMaintenance + addedMaintenance,
13084
- marginTiers,
13085
- });
13622
+ maintenanceMargin,
13623
+ };
13624
+ // Placement moves funds to the DEX only without Unified Account.
13625
+ if (dex !== null &&
13626
+ withdrawable !== undefined &&
13627
+ !this.#useUnifiedAccount) {
13628
+ crossAccount.hip3Funding = {
13629
+ withdrawable,
13630
+ requiredMargin: await this.#calculateHip3RequiredMargin({
13631
+ symbol: asset,
13632
+ dexName: dex,
13633
+ positionSize,
13634
+ orderPrice,
13635
+ leverage,
13636
+ isBuy,
13637
+ }),
13638
+ };
13639
+ if ((await this.getCurrentAccountId()) !== accountId ||
13640
+ generation !== this.#lifecycleGeneration) {
13641
+ return crossLiquidationUnavailable('account_unknown');
13642
+ }
13643
+ }
13644
+ return {
13645
+ status: 'ok',
13646
+ crossAccount,
13647
+ marginTiers: resolveHyperLiquidMarginTiers({
13648
+ marginTableId: market.marginTableId,
13649
+ maxLeverage: market.maxLeverage,
13650
+ marginTables: meta.marginTables,
13651
+ }),
13652
+ position: position ?? {
13653
+ symbol: asset,
13654
+ size: '0',
13655
+ entryPrice: '0',
13656
+ positionValue: '0',
13657
+ marginUsed: '0',
13658
+ leverage: { type: 'cross', value: leverage },
13659
+ liquidationPrice: null,
13660
+ maxLeverage: market.maxLeverage,
13661
+ },
13662
+ hasPosition: position !== undefined,
13663
+ };
13086
13664
  }
13087
13665
  /**
13088
13666
  * Read Cross inputs when live account coverage is incomplete.
13089
13667
  *
13668
+ * Unified accounts share Cross collateral across DEXs. Standard accounts
13669
+ * keep one clearinghouse per DEX, so a HIP-3 market reads its own DEX and
13670
+ * also returns its withdrawable balance for `#readCrossOrderAccount`.
13671
+ *
13090
13672
  * @param asset - The proposed position's market.
13091
13673
  * @param accountId - Selected account when the quote began.
13092
13674
  * @param userAddress - Venue address for the selected account.
13093
13675
  * @param generation - Provider lifecycle when the quote began.
13094
- * @returns Confirmed margin inputs for a flat market, or null.
13676
+ * @returns Confirmed margin inputs and any open position: `provider` for
13677
+ * an account mode without a Cross estimate, `account_unknown` when the
13678
+ * reads do not describe the selected account.
13095
13679
  */
13096
13680
  async #readCrossMarginContext(asset, accountId, userAddress, generation) {
13097
13681
  const { dex } = parseAssetName(asset);
13098
13682
  const infoClient = this.#clientService.getInfoClient();
13099
13683
  const mode = await infoClient.userAbstraction({ user: userAddress });
13100
- let summary;
13101
- let spotCollateral;
13684
+ let context;
13102
13685
  if (mode === HL_UNIFIED_ACCOUNT_MODE) {
13103
13686
  const [account, positions] = await Promise.all([
13104
13687
  this.#readAccountState({ accountId, throwOnUnavailable: true }, mode),
@@ -13109,24 +13692,33 @@ export class HyperLiquidProvider {
13109
13692
  includeProtection: false,
13110
13693
  }),
13111
13694
  ]);
13112
- if (positions.some((position) => position.symbol === asset)) {
13113
- return null;
13114
- }
13115
- summary = account.crossMarginSummary;
13116
- spotCollateral = account.spotCollateral;
13695
+ context = {
13696
+ status: 'ok',
13697
+ summary: account.crossMarginSummary,
13698
+ spotCollateral: account.spotCollateral,
13699
+ position: positions.find((position) => position.symbol === asset),
13700
+ };
13117
13701
  }
13118
- else if ((mode === 'disabled' || mode === 'default') && dex === null) {
13119
- // Standard mode keeps separate DEX margin pools. A HIP-3 addition may
13120
- // first move collateral into its DEX, which this preview cannot model.
13121
- const state = await infoClient.clearinghouseState({ user: userAddress });
13122
- if (state.assetPositions.some(({ position }) => position.coin === asset && Number(position.szi) !== 0)) {
13123
- return null;
13702
+ else if (isHyperLiquidStandardMode(mode)) {
13703
+ const state = await infoClient.clearinghouseState(dex === null ? { user: userAddress } : { user: userAddress, dex });
13704
+ const assetPosition = state.assetPositions.find(({ position }) => position.coin === asset && Number(position.szi) !== 0);
13705
+ context = {
13706
+ status: 'ok',
13707
+ summary: adaptAccountStateFromSDK(state).crossMarginSummary,
13708
+ spotCollateral: '0',
13709
+ position: assetPosition &&
13710
+ adaptPositionFromSDK(assetPosition, state.crossMarginSummary),
13711
+ };
13712
+ if (dex !== null) {
13713
+ const withdrawable = Number.parseFloat(state.withdrawable);
13714
+ if (!Number.isFinite(withdrawable)) {
13715
+ return crossLiquidationUnavailable('account_unknown');
13716
+ }
13717
+ context.withdrawable = withdrawable;
13124
13718
  }
13125
- summary = adaptAccountStateFromSDK(state).crossMarginSummary;
13126
- spotCollateral = '0';
13127
13719
  }
13128
13720
  else {
13129
- return null;
13721
+ return crossLiquidationUnavailable('provider');
13130
13722
  }
13131
13723
  // Account setup can migrate the same wallet while the exchange reads are
13132
13724
  // in flight. A snapshot from a different collateral mode cannot price it.
@@ -13137,9 +13729,9 @@ export class HyperLiquidProvider {
13137
13729
  if (currentMode !== mode ||
13138
13730
  currentAccount !== accountId ||
13139
13731
  generation !== this.#lifecycleGeneration) {
13140
- return null;
13732
+ return crossLiquidationUnavailable('account_unknown');
13141
13733
  }
13142
- return { summary, spotCollateral };
13734
+ return context;
13143
13735
  }
13144
13736
  /**
13145
13737
  * Calculate maintenance margin for a specific asset