@metamask-previews/perps-controller 13.1.0-preview-8c2a2eeb2 → 13.1.0-preview-4f4c98e

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 (716) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/{PerpsController-method-action-types.d.mts → PerpsController-method-action-types.d.ts} +2 -2
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -0
  4. package/dist/{PerpsController-method-action-types.mjs → PerpsController-method-action-types.js} +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -0
  6. package/dist/{PerpsController.d.mts → PerpsController.d.ts} +17 -17
  7. package/dist/PerpsController.d.ts.map +1 -0
  8. package/dist/{PerpsController.mjs → PerpsController.js} +33 -31
  9. package/dist/PerpsController.js.map +1 -0
  10. package/dist/aggregation/{SubscriptionMultiplexer.d.cts → SubscriptionMultiplexer.d.ts} +2 -2
  11. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -0
  12. package/dist/aggregation/{SubscriptionMultiplexer.mjs → SubscriptionMultiplexer.js} +3 -3
  13. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -0
  14. package/dist/aggregation/index.d.ts +6 -0
  15. package/dist/aggregation/index.d.ts.map +1 -0
  16. package/dist/aggregation/index.js +5 -0
  17. package/dist/aggregation/index.js.map +1 -0
  18. package/dist/constants/{chartConfig.d.mts → chartConfig.d.ts} +34 -34
  19. package/dist/constants/chartConfig.d.ts.map +1 -0
  20. package/dist/constants/{chartConfig.mjs → chartConfig.js} +1 -1
  21. package/dist/constants/chartConfig.js.map +1 -0
  22. package/dist/constants/eventNames.d.ts +555 -0
  23. package/dist/constants/eventNames.d.ts.map +1 -0
  24. package/dist/constants/{eventNames.mjs → eventNames.js} +1 -1
  25. package/dist/constants/eventNames.js.map +1 -0
  26. package/dist/constants/{hyperLiquidConfig.d.cts → hyperLiquidConfig.d.ts} +12 -12
  27. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -0
  28. package/dist/constants/{hyperLiquidConfig.mjs → hyperLiquidConfig.js} +4 -4
  29. package/dist/constants/hyperLiquidConfig.js.map +1 -0
  30. package/dist/constants/index.d.ts +12 -0
  31. package/dist/constants/index.d.ts.map +1 -0
  32. package/dist/constants/index.js +12 -0
  33. package/dist/constants/index.js.map +1 -0
  34. package/dist/constants/{myxConfig.d.mts → myxConfig.d.ts} +9 -8
  35. package/dist/constants/myxConfig.d.ts.map +1 -0
  36. package/dist/constants/{myxConfig.mjs → myxConfig.js} +2 -2
  37. package/dist/constants/myxConfig.js.map +1 -0
  38. package/dist/constants/{orderTypes.d.cts → orderTypes.d.ts} +7 -7
  39. package/dist/constants/orderTypes.d.ts.map +1 -0
  40. package/dist/constants/{orderTypes.mjs → orderTypes.js} +1 -1
  41. package/dist/constants/orderTypes.js.map +1 -0
  42. package/dist/constants/{performanceMetrics.d.cts → performanceMetrics.d.ts} +1 -1
  43. package/dist/constants/performanceMetrics.d.ts.map +1 -0
  44. package/dist/constants/{performanceMetrics.mjs → performanceMetrics.js} +1 -1
  45. package/dist/constants/performanceMetrics.js.map +1 -0
  46. package/dist/constants/{perpsConfig.d.mts → perpsConfig.d.ts} +56 -56
  47. package/dist/constants/perpsConfig.d.ts.map +1 -0
  48. package/dist/constants/{perpsConfig.mjs → perpsConfig.js} +1 -1
  49. package/dist/constants/perpsConfig.js.map +1 -0
  50. package/dist/constants/{transactionsHistoryConfig.d.cts → transactionsHistoryConfig.d.ts} +1 -1
  51. package/dist/constants/transactionsHistoryConfig.d.ts.map +1 -0
  52. package/dist/constants/{transactionsHistoryConfig.mjs → transactionsHistoryConfig.js} +1 -1
  53. package/dist/constants/transactionsHistoryConfig.js.map +1 -0
  54. package/dist/{index.d.mts → index.d.ts} +64 -64
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/{index.mjs → index.js} +41 -41
  57. package/dist/index.js.map +1 -0
  58. package/dist/perpsErrorCodes.d.ts +104 -0
  59. package/dist/perpsErrorCodes.d.ts.map +1 -0
  60. package/dist/{perpsErrorCodes.mjs → perpsErrorCodes.js} +1 -1
  61. package/dist/perpsErrorCodes.js.map +1 -0
  62. package/dist/providers/{AggregatedPerpsProvider.d.cts → AggregatedPerpsProvider.d.ts} +5 -5
  63. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -0
  64. package/dist/providers/{AggregatedPerpsProvider.mjs → AggregatedPerpsProvider.js} +5 -5
  65. package/dist/providers/AggregatedPerpsProvider.js.map +1 -0
  66. package/dist/providers/{HyperLiquidProvider.d.mts → HyperLiquidProvider.d.ts} +7 -7
  67. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -0
  68. package/dist/providers/{HyperLiquidProvider.mjs → HyperLiquidProvider.js} +48 -50
  69. package/dist/providers/HyperLiquidProvider.js.map +1 -0
  70. package/dist/routing/{ProviderRouter.d.mts → ProviderRouter.d.ts} +2 -2
  71. package/dist/routing/ProviderRouter.d.ts.map +1 -0
  72. package/dist/routing/{ProviderRouter.mjs → ProviderRouter.js} +1 -1
  73. package/dist/routing/ProviderRouter.js.map +1 -0
  74. package/dist/routing/index.d.ts +6 -0
  75. package/dist/routing/index.d.ts.map +1 -0
  76. package/dist/routing/index.js +5 -0
  77. package/dist/routing/index.js.map +1 -0
  78. package/dist/{selectors.d.mts → selectors.d.ts} +97 -97
  79. package/dist/selectors.d.ts.map +1 -0
  80. package/dist/{selectors.mjs → selectors.js} +4 -4
  81. package/dist/selectors.js.map +1 -0
  82. package/dist/services/{AccountService.d.cts → AccountService.d.ts} +4 -4
  83. package/dist/services/AccountService.d.ts.map +1 -0
  84. package/dist/services/{AccountService.mjs → AccountService.js} +9 -9
  85. package/dist/services/AccountService.js.map +1 -0
  86. package/dist/services/{AggregatedOrderBookConnection.d.cts → AggregatedOrderBookConnection.d.ts} +2 -2
  87. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -0
  88. package/dist/services/{AggregatedOrderBookConnection.mjs → AggregatedOrderBookConnection.js} +3 -3
  89. package/dist/services/AggregatedOrderBookConnection.js.map +1 -0
  90. package/dist/services/{DataLakeService.d.cts → DataLakeService.d.ts} +4 -4
  91. package/dist/services/DataLakeService.d.ts.map +1 -0
  92. package/dist/services/{DataLakeService.mjs → DataLakeService.js} +7 -7
  93. package/dist/services/DataLakeService.js.map +1 -0
  94. package/dist/services/{DepositService.d.cts → DepositService.d.ts} +4 -4
  95. package/dist/services/DepositService.d.ts.map +1 -0
  96. package/dist/services/{DepositService.mjs → DepositService.js} +7 -7
  97. package/dist/services/DepositService.js.map +1 -0
  98. package/dist/services/{DexDiscoveryCacheManager.d.cts → DexDiscoveryCacheManager.d.ts} +2 -2
  99. package/dist/services/DexDiscoveryCacheManager.d.ts.map +1 -0
  100. package/dist/services/{DexDiscoveryCacheManager.mjs → DexDiscoveryCacheManager.js} +2 -2
  101. package/dist/services/DexDiscoveryCacheManager.js.map +1 -0
  102. package/dist/services/{EligibilityService.d.cts → EligibilityService.d.ts} +2 -2
  103. package/dist/services/EligibilityService.d.ts.map +1 -0
  104. package/dist/services/{EligibilityService.mjs → EligibilityService.js} +3 -3
  105. package/dist/services/EligibilityService.js.map +1 -0
  106. package/dist/services/{FeatureFlagConfigurationService.d.cts → FeatureFlagConfigurationService.d.ts} +3 -3
  107. package/dist/services/FeatureFlagConfigurationService.d.ts.map +1 -0
  108. package/dist/services/{FeatureFlagConfigurationService.mjs → FeatureFlagConfigurationService.js} +7 -7
  109. package/dist/services/FeatureFlagConfigurationService.js.map +1 -0
  110. package/dist/services/{HyperLiquidClientService.d.cts → HyperLiquidClientService.d.ts} +10 -10
  111. package/dist/services/HyperLiquidClientService.d.ts.map +1 -0
  112. package/dist/services/{HyperLiquidClientService.mjs → HyperLiquidClientService.js} +11 -11
  113. package/dist/services/HyperLiquidClientService.js.map +1 -0
  114. package/dist/services/{HyperLiquidSubscriptionService.d.cts → HyperLiquidSubscriptionService.d.ts} +6 -6
  115. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -0
  116. package/dist/services/{HyperLiquidSubscriptionService.mjs → HyperLiquidSubscriptionService.js} +12 -12
  117. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -0
  118. package/dist/services/{HyperLiquidWalletService.d.cts → HyperLiquidWalletService.d.ts} +4 -4
  119. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -0
  120. package/dist/services/{HyperLiquidWalletService.mjs → HyperLiquidWalletService.js} +5 -5
  121. package/dist/services/HyperLiquidWalletService.js.map +1 -0
  122. package/dist/services/{MarketDataService.d.cts → MarketDataService.d.ts} +5 -5
  123. package/dist/services/MarketDataService.d.ts.map +1 -0
  124. package/dist/services/{MarketDataService.mjs → MarketDataService.js} +9 -9
  125. package/dist/services/MarketDataService.js.map +1 -0
  126. package/dist/services/{RewardsIntegrationService.d.cts → RewardsIntegrationService.d.ts} +3 -3
  127. package/dist/services/RewardsIntegrationService.d.ts.map +1 -0
  128. package/dist/services/{RewardsIntegrationService.mjs → RewardsIntegrationService.js} +6 -6
  129. package/dist/services/RewardsIntegrationService.js.map +1 -0
  130. package/dist/services/{ServiceContext.d.cts → ServiceContext.d.ts} +3 -3
  131. package/dist/services/ServiceContext.d.ts.map +1 -0
  132. package/dist/services/ServiceContext.js +2 -0
  133. package/dist/services/ServiceContext.js.map +1 -0
  134. package/dist/services/{TerminalMarketService.d.cts → TerminalMarketService.d.ts} +2 -2
  135. package/dist/services/TerminalMarketService.d.ts.map +1 -0
  136. package/dist/services/{TerminalMarketService.mjs → TerminalMarketService.js} +9 -9
  137. package/dist/services/TerminalMarketService.js.map +1 -0
  138. package/dist/services/{TradingReadinessCache.d.mts → TradingReadinessCache.d.ts} +1 -1
  139. package/dist/services/TradingReadinessCache.d.ts.map +1 -0
  140. package/dist/services/{TradingReadinessCache.mjs → TradingReadinessCache.js} +1 -1
  141. package/dist/services/TradingReadinessCache.js.map +1 -0
  142. package/dist/services/{TradingService.d.cts → TradingService.d.ts} +4 -4
  143. package/dist/services/TradingService.d.ts.map +1 -0
  144. package/dist/services/{TradingService.mjs → TradingService.js} +10 -10
  145. package/dist/services/TradingService.js.map +1 -0
  146. package/dist/types/{config.d.cts → config.d.ts} +2 -2
  147. package/dist/types/config.d.ts.map +1 -0
  148. package/dist/types/config.js +2 -0
  149. package/dist/types/config.js.map +1 -0
  150. package/dist/types/{hyperliquid-types.d.cts → hyperliquid-types.d.ts} +6 -6
  151. package/dist/types/hyperliquid-types.d.ts.map +1 -0
  152. package/dist/types/{hyperliquid-types.mjs → hyperliquid-types.js} +1 -1
  153. package/dist/types/hyperliquid-types.js.map +1 -0
  154. package/dist/types/{index.d.cts → index.d.ts} +41 -41
  155. package/dist/types/index.d.ts.map +1 -0
  156. package/dist/types/{index.mjs → index.js} +3 -3
  157. package/dist/types/index.js.map +1 -0
  158. package/dist/types/{messenger.d.mts → messenger.d.ts} +11 -11
  159. package/dist/types/messenger.d.ts.map +1 -0
  160. package/dist/types/messenger.js +2 -0
  161. package/dist/types/messenger.js.map +1 -0
  162. package/dist/types/{myx-types.d.mts → myx-types.d.ts} +16 -16
  163. package/dist/types/myx-types.d.ts.map +1 -0
  164. package/dist/types/{myx-types.mjs → myx-types.js} +3 -3
  165. package/dist/types/myx-types.js.map +1 -0
  166. package/dist/types/{perps-types.d.cts → perps-types.d.ts} +4 -4
  167. package/dist/types/perps-types.d.ts.map +1 -0
  168. package/dist/types/perps-types.js +2 -0
  169. package/dist/types/perps-types.js.map +1 -0
  170. package/dist/types/{token.d.cts → token.d.ts} +2 -2
  171. package/dist/types/token.d.ts.map +1 -0
  172. package/dist/types/token.js +2 -0
  173. package/dist/types/token.js.map +1 -0
  174. package/dist/types/{transactionTypes.d.cts → transactionTypes.d.ts} +1 -1
  175. package/dist/types/transactionTypes.d.ts.map +1 -0
  176. package/dist/types/{transactionTypes.mjs → transactionTypes.js} +2 -2
  177. package/dist/types/transactionTypes.js.map +1 -0
  178. package/dist/utils/{accountUtils.d.cts → accountUtils.d.ts} +4 -4
  179. package/dist/utils/accountUtils.d.ts.map +1 -0
  180. package/dist/utils/{accountUtils.mjs → accountUtils.js} +2 -2
  181. package/dist/utils/accountUtils.js.map +1 -0
  182. package/dist/utils/{capabilitySymbols.d.mts → capabilitySymbols.d.ts} +1 -1
  183. package/dist/utils/capabilitySymbols.d.ts.map +1 -0
  184. package/dist/utils/{capabilitySymbols.mjs → capabilitySymbols.js} +1 -1
  185. package/dist/utils/capabilitySymbols.js.map +1 -0
  186. package/dist/utils/{coalescePerpsRestRequest.d.cts → coalescePerpsRestRequest.d.ts} +1 -1
  187. package/dist/utils/coalescePerpsRestRequest.d.ts.map +1 -0
  188. package/dist/utils/{coalescePerpsRestRequest.mjs → coalescePerpsRestRequest.js} +2 -2
  189. package/dist/utils/coalescePerpsRestRequest.js.map +1 -0
  190. package/dist/utils/{errorUtils.d.mts → errorUtils.d.ts} +1 -1
  191. package/dist/utils/errorUtils.d.ts.map +1 -0
  192. package/dist/utils/{errorUtils.mjs → errorUtils.js} +3 -3
  193. package/dist/utils/errorUtils.js.map +1 -0
  194. package/dist/utils/{hyperLiquidAbstraction.d.cts → hyperLiquidAbstraction.d.ts} +2 -2
  195. package/dist/utils/hyperLiquidAbstraction.d.ts.map +1 -0
  196. package/dist/utils/{hyperLiquidAbstraction.mjs → hyperLiquidAbstraction.js} +1 -1
  197. package/dist/utils/hyperLiquidAbstraction.js.map +1 -0
  198. package/dist/utils/{hyperLiquidAdapter.d.cts → hyperLiquidAdapter.d.ts} +4 -4
  199. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -0
  200. package/dist/utils/{hyperLiquidAdapter.mjs → hyperLiquidAdapter.js} +9 -9
  201. package/dist/utils/hyperLiquidAdapter.js.map +1 -0
  202. package/dist/utils/{hyperLiquidOrderBookProcessor.d.mts → hyperLiquidOrderBookProcessor.d.ts} +3 -3
  203. package/dist/utils/hyperLiquidOrderBookProcessor.d.ts.map +1 -0
  204. package/dist/utils/{hyperLiquidOrderBookProcessor.mjs → hyperLiquidOrderBookProcessor.js} +1 -1
  205. package/dist/utils/hyperLiquidOrderBookProcessor.js.map +1 -0
  206. package/dist/utils/{hyperLiquidValidation.d.cts → hyperLiquidValidation.d.ts} +4 -4
  207. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -0
  208. package/dist/utils/{hyperLiquidValidation.mjs → hyperLiquidValidation.js} +6 -6
  209. package/dist/utils/hyperLiquidValidation.js.map +1 -0
  210. package/dist/utils/{idUtils.d.cts → idUtils.d.ts} +1 -1
  211. package/dist/utils/idUtils.d.ts.map +1 -0
  212. package/dist/utils/{idUtils.mjs → idUtils.js} +2 -2
  213. package/dist/utils/idUtils.js.map +1 -0
  214. package/dist/utils/index.d.ts +28 -0
  215. package/dist/utils/index.d.ts.map +1 -0
  216. package/dist/utils/{index.mjs → index.js} +21 -21
  217. package/dist/utils/index.js.map +1 -0
  218. package/dist/utils/{marketDataTransform.d.cts → marketDataTransform.d.ts} +3 -3
  219. package/dist/utils/marketDataTransform.d.ts.map +1 -0
  220. package/dist/utils/{marketDataTransform.mjs → marketDataTransform.js} +5 -5
  221. package/dist/utils/marketDataTransform.js.map +1 -0
  222. package/dist/utils/{marketSearch.d.cts → marketSearch.d.ts} +2 -2
  223. package/dist/utils/marketSearch.d.ts.map +1 -0
  224. package/dist/utils/{marketSearch.mjs → marketSearch.js} +1 -1
  225. package/dist/utils/marketSearch.js.map +1 -0
  226. package/dist/utils/{marketUtils.d.cts → marketUtils.d.ts} +3 -3
  227. package/dist/utils/marketUtils.d.ts.map +1 -0
  228. package/dist/utils/{marketUtils.mjs → marketUtils.js} +2 -2
  229. package/dist/utils/marketUtils.js.map +1 -0
  230. package/dist/utils/{myxAdapter.d.cts → myxAdapter.d.ts} +3 -3
  231. package/dist/utils/myxAdapter.d.ts.map +1 -0
  232. package/dist/utils/{myxAdapter.mjs → myxAdapter.js} +3 -3
  233. package/dist/utils/myxAdapter.js.map +1 -0
  234. package/dist/utils/{orderCalculations.d.cts → orderCalculations.d.ts} +4 -4
  235. package/dist/utils/orderCalculations.d.ts.map +1 -0
  236. package/dist/utils/{orderCalculations.mjs → orderCalculations.js} +6 -6
  237. package/dist/utils/orderCalculations.js.map +1 -0
  238. package/dist/utils/{orderTypes.d.mts → orderTypes.d.ts} +3 -3
  239. package/dist/utils/orderTypes.d.ts.map +1 -0
  240. package/dist/utils/{orderTypes.mjs → orderTypes.js} +1 -1
  241. package/dist/utils/orderTypes.js.map +1 -0
  242. package/dist/utils/{perpsConnectionAttemptContext.d.mts → perpsConnectionAttemptContext.d.ts} +1 -1
  243. package/dist/utils/perpsConnectionAttemptContext.d.ts.map +1 -0
  244. package/dist/utils/{perpsConnectionAttemptContext.mjs → perpsConnectionAttemptContext.js} +1 -1
  245. package/dist/utils/perpsConnectionAttemptContext.js.map +1 -0
  246. package/dist/utils/{perpsDiskPersistence.d.cts → perpsDiskPersistence.d.ts} +2 -2
  247. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -0
  248. package/dist/utils/{perpsDiskPersistence.mjs → perpsDiskPersistence.js} +2 -2
  249. package/dist/utils/perpsDiskPersistence.js.map +1 -0
  250. package/dist/utils/{perpsFormatters.d.cts → perpsFormatters.d.ts} +1 -1
  251. package/dist/utils/perpsFormatters.d.ts.map +1 -0
  252. package/dist/utils/{perpsFormatters.mjs → perpsFormatters.js} +2 -2
  253. package/dist/utils/perpsFormatters.js.map +1 -0
  254. package/dist/utils/{rewardsUtils.d.cts → rewardsUtils.d.ts} +4 -4
  255. package/dist/utils/rewardsUtils.d.ts.map +1 -0
  256. package/dist/utils/{rewardsUtils.mjs → rewardsUtils.js} +4 -4
  257. package/dist/utils/rewardsUtils.js.map +1 -0
  258. package/dist/utils/{significantFigures.d.cts → significantFigures.d.ts} +1 -1
  259. package/dist/utils/significantFigures.d.ts.map +1 -0
  260. package/dist/utils/{significantFigures.mjs → significantFigures.js} +2 -2
  261. package/dist/utils/significantFigures.js.map +1 -0
  262. package/dist/utils/{sortMarkets.d.cts → sortMarkets.d.ts} +2 -2
  263. package/dist/utils/sortMarkets.d.ts.map +1 -0
  264. package/dist/utils/{sortMarkets.mjs → sortMarkets.js} +2 -2
  265. package/dist/utils/sortMarkets.js.map +1 -0
  266. package/dist/utils/{standaloneInfoClient.d.cts → standaloneInfoClient.d.ts} +3 -3
  267. package/dist/utils/standaloneInfoClient.d.ts.map +1 -0
  268. package/dist/utils/{standaloneInfoClient.mjs → standaloneInfoClient.js} +3 -3
  269. package/dist/utils/standaloneInfoClient.js.map +1 -0
  270. package/dist/utils/{stringParseUtils.d.cts → stringParseUtils.d.ts} +1 -1
  271. package/dist/utils/stringParseUtils.d.ts.map +1 -0
  272. package/dist/utils/{stringParseUtils.mjs → stringParseUtils.js} +1 -1
  273. package/dist/utils/stringParseUtils.js.map +1 -0
  274. package/dist/utils/{transferData.d.cts → transferData.d.ts} +1 -1
  275. package/dist/utils/transferData.d.ts.map +1 -0
  276. package/dist/utils/{transferData.mjs → transferData.js} +3 -3
  277. package/dist/utils/transferData.js.map +1 -0
  278. package/dist/utils/{wait.d.cts → wait.d.ts} +1 -1
  279. package/dist/utils/wait.d.ts.map +1 -0
  280. package/dist/utils/{wait.mjs → wait.js} +1 -1
  281. package/dist/utils/wait.js.map +1 -0
  282. package/package.json +20 -48
  283. package/dist/PerpsController-method-action-types.cjs +0 -7
  284. package/dist/PerpsController-method-action-types.cjs.map +0 -1
  285. package/dist/PerpsController-method-action-types.d.cts +0 -1163
  286. package/dist/PerpsController-method-action-types.d.cts.map +0 -1
  287. package/dist/PerpsController-method-action-types.d.mts.map +0 -1
  288. package/dist/PerpsController-method-action-types.mjs.map +0 -1
  289. package/dist/PerpsController.cjs +0 -5063
  290. package/dist/PerpsController.cjs.map +0 -1
  291. package/dist/PerpsController.d.cts +0 -1274
  292. package/dist/PerpsController.d.cts.map +0 -1
  293. package/dist/PerpsController.d.mts.map +0 -1
  294. package/dist/PerpsController.mjs.map +0 -1
  295. package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -441
  296. package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
  297. package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
  298. package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -171
  299. package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
  300. package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
  301. package/dist/aggregation/index.cjs +0 -9
  302. package/dist/aggregation/index.cjs.map +0 -1
  303. package/dist/aggregation/index.d.cts +0 -6
  304. package/dist/aggregation/index.d.cts.map +0 -1
  305. package/dist/aggregation/index.d.mts +0 -6
  306. package/dist/aggregation/index.d.mts.map +0 -1
  307. package/dist/aggregation/index.mjs +0 -5
  308. package/dist/aggregation/index.mjs.map +0 -1
  309. package/dist/constants/chartConfig.cjs +0 -239
  310. package/dist/constants/chartConfig.cjs.map +0 -1
  311. package/dist/constants/chartConfig.d.cts +0 -228
  312. package/dist/constants/chartConfig.d.cts.map +0 -1
  313. package/dist/constants/chartConfig.d.mts.map +0 -1
  314. package/dist/constants/chartConfig.mjs.map +0 -1
  315. package/dist/constants/eventNames.cjs +0 -650
  316. package/dist/constants/eventNames.cjs.map +0 -1
  317. package/dist/constants/eventNames.d.cts +0 -555
  318. package/dist/constants/eventNames.d.cts.map +0 -1
  319. package/dist/constants/eventNames.d.mts +0 -555
  320. package/dist/constants/eventNames.d.mts.map +0 -1
  321. package/dist/constants/eventNames.mjs.map +0 -1
  322. package/dist/constants/hyperLiquidConfig.cjs +0 -607
  323. package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
  324. package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
  325. package/dist/constants/hyperLiquidConfig.d.mts +0 -280
  326. package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
  327. package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
  328. package/dist/constants/index.cjs +0 -28
  329. package/dist/constants/index.cjs.map +0 -1
  330. package/dist/constants/index.d.cts +0 -12
  331. package/dist/constants/index.d.cts.map +0 -1
  332. package/dist/constants/index.d.mts +0 -12
  333. package/dist/constants/index.d.mts.map +0 -1
  334. package/dist/constants/index.mjs +0 -12
  335. package/dist/constants/index.mjs.map +0 -1
  336. package/dist/constants/myxConfig.cjs +0 -253
  337. package/dist/constants/myxConfig.cjs.map +0 -1
  338. package/dist/constants/myxConfig.d.cts +0 -145
  339. package/dist/constants/myxConfig.d.cts.map +0 -1
  340. package/dist/constants/myxConfig.d.mts.map +0 -1
  341. package/dist/constants/myxConfig.mjs.map +0 -1
  342. package/dist/constants/orderTypes.cjs +0 -31
  343. package/dist/constants/orderTypes.cjs.map +0 -1
  344. package/dist/constants/orderTypes.d.cts.map +0 -1
  345. package/dist/constants/orderTypes.d.mts +0 -19
  346. package/dist/constants/orderTypes.d.mts.map +0 -1
  347. package/dist/constants/orderTypes.mjs.map +0 -1
  348. package/dist/constants/performanceMetrics.cjs +0 -63
  349. package/dist/constants/performanceMetrics.cjs.map +0 -1
  350. package/dist/constants/performanceMetrics.d.cts.map +0 -1
  351. package/dist/constants/performanceMetrics.d.mts +0 -46
  352. package/dist/constants/performanceMetrics.d.mts.map +0 -1
  353. package/dist/constants/performanceMetrics.mjs.map +0 -1
  354. package/dist/constants/perpsConfig.cjs +0 -553
  355. package/dist/constants/perpsConfig.cjs.map +0 -1
  356. package/dist/constants/perpsConfig.d.cts +0 -474
  357. package/dist/constants/perpsConfig.d.cts.map +0 -1
  358. package/dist/constants/perpsConfig.d.mts.map +0 -1
  359. package/dist/constants/perpsConfig.mjs.map +0 -1
  360. package/dist/constants/transactionsHistoryConfig.cjs +0 -38
  361. package/dist/constants/transactionsHistoryConfig.cjs.map +0 -1
  362. package/dist/constants/transactionsHistoryConfig.d.cts.map +0 -1
  363. package/dist/constants/transactionsHistoryConfig.d.mts +0 -35
  364. package/dist/constants/transactionsHistoryConfig.d.mts.map +0 -1
  365. package/dist/constants/transactionsHistoryConfig.mjs.map +0 -1
  366. package/dist/index.cjs +0 -344
  367. package/dist/index.cjs.map +0 -1
  368. package/dist/index.d.cts +0 -92
  369. package/dist/index.d.cts.map +0 -1
  370. package/dist/index.d.mts.map +0 -1
  371. package/dist/index.mjs.map +0 -1
  372. package/dist/perpsErrorCodes.cjs +0 -127
  373. package/dist/perpsErrorCodes.cjs.map +0 -1
  374. package/dist/perpsErrorCodes.d.cts +0 -104
  375. package/dist/perpsErrorCodes.d.cts.map +0 -1
  376. package/dist/perpsErrorCodes.d.mts +0 -104
  377. package/dist/perpsErrorCodes.d.mts.map +0 -1
  378. package/dist/perpsErrorCodes.mjs.map +0 -1
  379. package/dist/providers/AggregatedPerpsProvider.cjs +0 -689
  380. package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
  381. package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
  382. package/dist/providers/AggregatedPerpsProvider.d.mts +0 -232
  383. package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
  384. package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
  385. package/dist/providers/HyperLiquidProvider.cjs +0 -10416
  386. package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
  387. package/dist/providers/HyperLiquidProvider.d.cts +0 -625
  388. package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
  389. package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
  390. package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
  391. package/dist/routing/ProviderRouter.cjs +0 -154
  392. package/dist/routing/ProviderRouter.cjs.map +0 -1
  393. package/dist/routing/ProviderRouter.d.cts +0 -112
  394. package/dist/routing/ProviderRouter.d.cts.map +0 -1
  395. package/dist/routing/ProviderRouter.d.mts.map +0 -1
  396. package/dist/routing/ProviderRouter.mjs.map +0 -1
  397. package/dist/routing/index.cjs +0 -9
  398. package/dist/routing/index.cjs.map +0 -1
  399. package/dist/routing/index.d.cts +0 -6
  400. package/dist/routing/index.d.cts.map +0 -1
  401. package/dist/routing/index.d.mts +0 -6
  402. package/dist/routing/index.d.mts.map +0 -1
  403. package/dist/routing/index.mjs +0 -5
  404. package/dist/routing/index.mjs.map +0 -1
  405. package/dist/selectors.cjs +0 -264
  406. package/dist/selectors.cjs.map +0 -1
  407. package/dist/selectors.d.cts +0 -336
  408. package/dist/selectors.d.cts.map +0 -1
  409. package/dist/selectors.d.mts.map +0 -1
  410. package/dist/selectors.mjs.map +0 -1
  411. package/dist/services/AccountService.cjs +0 -324
  412. package/dist/services/AccountService.cjs.map +0 -1
  413. package/dist/services/AccountService.d.cts.map +0 -1
  414. package/dist/services/AccountService.d.mts +0 -56
  415. package/dist/services/AccountService.d.mts.map +0 -1
  416. package/dist/services/AccountService.mjs.map +0 -1
  417. package/dist/services/AggregatedOrderBookConnection.cjs +0 -405
  418. package/dist/services/AggregatedOrderBookConnection.cjs.map +0 -1
  419. package/dist/services/AggregatedOrderBookConnection.d.cts.map +0 -1
  420. package/dist/services/AggregatedOrderBookConnection.d.mts +0 -106
  421. package/dist/services/AggregatedOrderBookConnection.d.mts.map +0 -1
  422. package/dist/services/AggregatedOrderBookConnection.mjs.map +0 -1
  423. package/dist/services/DataLakeService.cjs +0 -233
  424. package/dist/services/DataLakeService.cjs.map +0 -1
  425. package/dist/services/DataLakeService.d.cts.map +0 -1
  426. package/dist/services/DataLakeService.d.mts +0 -51
  427. package/dist/services/DataLakeService.d.mts.map +0 -1
  428. package/dist/services/DataLakeService.mjs.map +0 -1
  429. package/dist/services/DepositService.cjs +0 -99
  430. package/dist/services/DepositService.cjs.map +0 -1
  431. package/dist/services/DepositService.d.cts.map +0 -1
  432. package/dist/services/DepositService.d.mts +0 -39
  433. package/dist/services/DepositService.d.mts.map +0 -1
  434. package/dist/services/DepositService.mjs.map +0 -1
  435. package/dist/services/DexDiscoveryCacheManager.cjs +0 -147
  436. package/dist/services/DexDiscoveryCacheManager.cjs.map +0 -1
  437. package/dist/services/DexDiscoveryCacheManager.d.cts.map +0 -1
  438. package/dist/services/DexDiscoveryCacheManager.d.mts +0 -52
  439. package/dist/services/DexDiscoveryCacheManager.d.mts.map +0 -1
  440. package/dist/services/DexDiscoveryCacheManager.mjs.map +0 -1
  441. package/dist/services/EligibilityService.cjs +0 -78
  442. package/dist/services/EligibilityService.cjs.map +0 -1
  443. package/dist/services/EligibilityService.d.cts.map +0 -1
  444. package/dist/services/EligibilityService.d.mts +0 -28
  445. package/dist/services/EligibilityService.d.mts.map +0 -1
  446. package/dist/services/EligibilityService.mjs.map +0 -1
  447. package/dist/services/FeatureFlagConfigurationService.cjs +0 -257
  448. package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
  449. package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
  450. package/dist/services/FeatureFlagConfigurationService.d.mts +0 -73
  451. package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
  452. package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
  453. package/dist/services/HyperLiquidClientService.cjs +0 -1045
  454. package/dist/services/HyperLiquidClientService.cjs.map +0 -1
  455. package/dist/services/HyperLiquidClientService.d.cts.map +0 -1
  456. package/dist/services/HyperLiquidClientService.d.mts +0 -239
  457. package/dist/services/HyperLiquidClientService.d.mts.map +0 -1
  458. package/dist/services/HyperLiquidClientService.mjs.map +0 -1
  459. package/dist/services/HyperLiquidSubscriptionService.cjs +0 -3196
  460. package/dist/services/HyperLiquidSubscriptionService.cjs.map +0 -1
  461. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +0 -1
  462. package/dist/services/HyperLiquidSubscriptionService.d.mts +0 -227
  463. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +0 -1
  464. package/dist/services/HyperLiquidSubscriptionService.mjs.map +0 -1
  465. package/dist/services/HyperLiquidWalletService.cjs +0 -186
  466. package/dist/services/HyperLiquidWalletService.cjs.map +0 -1
  467. package/dist/services/HyperLiquidWalletService.d.cts.map +0 -1
  468. package/dist/services/HyperLiquidWalletService.d.mts +0 -84
  469. package/dist/services/HyperLiquidWalletService.d.mts.map +0 -1
  470. package/dist/services/HyperLiquidWalletService.mjs.map +0 -1
  471. package/dist/services/MarketDataService.cjs +0 -1138
  472. package/dist/services/MarketDataService.cjs.map +0 -1
  473. package/dist/services/MarketDataService.d.cts.map +0 -1
  474. package/dist/services/MarketDataService.d.mts +0 -334
  475. package/dist/services/MarketDataService.d.mts.map +0 -1
  476. package/dist/services/MarketDataService.mjs.map +0 -1
  477. package/dist/services/RewardsIntegrationService.cjs +0 -391
  478. package/dist/services/RewardsIntegrationService.cjs.map +0 -1
  479. package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
  480. package/dist/services/RewardsIntegrationService.d.mts +0 -84
  481. package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
  482. package/dist/services/RewardsIntegrationService.mjs.map +0 -1
  483. package/dist/services/ServiceContext.cjs +0 -3
  484. package/dist/services/ServiceContext.cjs.map +0 -1
  485. package/dist/services/ServiceContext.d.cts.map +0 -1
  486. package/dist/services/ServiceContext.d.mts +0 -102
  487. package/dist/services/ServiceContext.d.mts.map +0 -1
  488. package/dist/services/ServiceContext.mjs +0 -2
  489. package/dist/services/ServiceContext.mjs.map +0 -1
  490. package/dist/services/TerminalMarketService.cjs +0 -623
  491. package/dist/services/TerminalMarketService.cjs.map +0 -1
  492. package/dist/services/TerminalMarketService.d.cts.map +0 -1
  493. package/dist/services/TerminalMarketService.d.mts +0 -45
  494. package/dist/services/TerminalMarketService.d.mts.map +0 -1
  495. package/dist/services/TerminalMarketService.mjs.map +0 -1
  496. package/dist/services/TradingReadinessCache.cjs +0 -329
  497. package/dist/services/TradingReadinessCache.cjs.map +0 -1
  498. package/dist/services/TradingReadinessCache.d.cts +0 -204
  499. package/dist/services/TradingReadinessCache.d.cts.map +0 -1
  500. package/dist/services/TradingReadinessCache.d.mts.map +0 -1
  501. package/dist/services/TradingReadinessCache.mjs.map +0 -1
  502. package/dist/services/TradingService.cjs +0 -1865
  503. package/dist/services/TradingService.cjs.map +0 -1
  504. package/dist/services/TradingService.d.cts.map +0 -1
  505. package/dist/services/TradingService.d.mts +0 -201
  506. package/dist/services/TradingService.d.mts.map +0 -1
  507. package/dist/services/TradingService.mjs.map +0 -1
  508. package/dist/types/config.cjs +0 -3
  509. package/dist/types/config.cjs.map +0 -1
  510. package/dist/types/config.d.cts.map +0 -1
  511. package/dist/types/config.d.mts +0 -49
  512. package/dist/types/config.d.mts.map +0 -1
  513. package/dist/types/config.mjs +0 -2
  514. package/dist/types/config.mjs.map +0 -1
  515. package/dist/types/hyperliquid-types.cjs +0 -45
  516. package/dist/types/hyperliquid-types.cjs.map +0 -1
  517. package/dist/types/hyperliquid-types.d.cts.map +0 -1
  518. package/dist/types/hyperliquid-types.d.mts +0 -67
  519. package/dist/types/hyperliquid-types.d.mts.map +0 -1
  520. package/dist/types/hyperliquid-types.mjs.map +0 -1
  521. package/dist/types/index.cjs +0 -151
  522. package/dist/types/index.cjs.map +0 -1
  523. package/dist/types/index.d.cts.map +0 -1
  524. package/dist/types/index.d.mts +0 -1951
  525. package/dist/types/index.d.mts.map +0 -1
  526. package/dist/types/index.mjs.map +0 -1
  527. package/dist/types/messenger.cjs +0 -3
  528. package/dist/types/messenger.cjs.map +0 -1
  529. package/dist/types/messenger.d.cts +0 -30
  530. package/dist/types/messenger.d.cts.map +0 -1
  531. package/dist/types/messenger.d.mts.map +0 -1
  532. package/dist/types/messenger.mjs +0 -2
  533. package/dist/types/messenger.mjs.map +0 -1
  534. package/dist/types/myx-types.cjs +0 -41
  535. package/dist/types/myx-types.cjs.map +0 -1
  536. package/dist/types/myx-types.d.cts +0 -94
  537. package/dist/types/myx-types.d.cts.map +0 -1
  538. package/dist/types/myx-types.d.mts.map +0 -1
  539. package/dist/types/myx-types.mjs.map +0 -1
  540. package/dist/types/perps-types.cjs +0 -7
  541. package/dist/types/perps-types.cjs.map +0 -1
  542. package/dist/types/perps-types.d.cts.map +0 -1
  543. package/dist/types/perps-types.d.mts +0 -184
  544. package/dist/types/perps-types.d.mts.map +0 -1
  545. package/dist/types/perps-types.mjs +0 -5
  546. package/dist/types/perps-types.mjs.map +0 -1
  547. package/dist/types/token.cjs +0 -3
  548. package/dist/types/token.cjs.map +0 -1
  549. package/dist/types/token.d.cts.map +0 -1
  550. package/dist/types/token.d.mts +0 -25
  551. package/dist/types/token.d.mts.map +0 -1
  552. package/dist/types/token.mjs +0 -2
  553. package/dist/types/token.mjs.map +0 -1
  554. package/dist/types/transactionTypes.cjs +0 -29
  555. package/dist/types/transactionTypes.cjs.map +0 -1
  556. package/dist/types/transactionTypes.d.cts.map +0 -1
  557. package/dist/types/transactionTypes.d.mts +0 -60
  558. package/dist/types/transactionTypes.d.mts.map +0 -1
  559. package/dist/types/transactionTypes.mjs.map +0 -1
  560. package/dist/utils/accountUtils.cjs +0 -236
  561. package/dist/utils/accountUtils.cjs.map +0 -1
  562. package/dist/utils/accountUtils.d.cts.map +0 -1
  563. package/dist/utils/accountUtils.d.mts +0 -72
  564. package/dist/utils/accountUtils.d.mts.map +0 -1
  565. package/dist/utils/accountUtils.mjs.map +0 -1
  566. package/dist/utils/capabilitySymbols.cjs +0 -25
  567. package/dist/utils/capabilitySymbols.cjs.map +0 -1
  568. package/dist/utils/capabilitySymbols.d.cts +0 -15
  569. package/dist/utils/capabilitySymbols.d.cts.map +0 -1
  570. package/dist/utils/capabilitySymbols.d.mts.map +0 -1
  571. package/dist/utils/capabilitySymbols.mjs.map +0 -1
  572. package/dist/utils/coalescePerpsRestRequest.cjs +0 -71
  573. package/dist/utils/coalescePerpsRestRequest.cjs.map +0 -1
  574. package/dist/utils/coalescePerpsRestRequest.d.cts.map +0 -1
  575. package/dist/utils/coalescePerpsRestRequest.d.mts +0 -32
  576. package/dist/utils/coalescePerpsRestRequest.d.mts.map +0 -1
  577. package/dist/utils/coalescePerpsRestRequest.mjs.map +0 -1
  578. package/dist/utils/errorUtils.cjs +0 -104
  579. package/dist/utils/errorUtils.cjs.map +0 -1
  580. package/dist/utils/errorUtils.d.cts +0 -50
  581. package/dist/utils/errorUtils.d.cts.map +0 -1
  582. package/dist/utils/errorUtils.d.mts.map +0 -1
  583. package/dist/utils/errorUtils.mjs.map +0 -1
  584. package/dist/utils/hyperLiquidAbstraction.cjs +0 -23
  585. package/dist/utils/hyperLiquidAbstraction.cjs.map +0 -1
  586. package/dist/utils/hyperLiquidAbstraction.d.cts.map +0 -1
  587. package/dist/utils/hyperLiquidAbstraction.d.mts +0 -11
  588. package/dist/utils/hyperLiquidAbstraction.d.mts.map +0 -1
  589. package/dist/utils/hyperLiquidAbstraction.mjs.map +0 -1
  590. package/dist/utils/hyperLiquidAdapter.cjs +0 -512
  591. package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
  592. package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
  593. package/dist/utils/hyperLiquidAdapter.d.mts +0 -77
  594. package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
  595. package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
  596. package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -83
  597. package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
  598. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -55
  599. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
  600. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
  601. package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +0 -1
  602. package/dist/utils/hyperLiquidValidation.cjs +0 -799
  603. package/dist/utils/hyperLiquidValidation.cjs.map +0 -1
  604. package/dist/utils/hyperLiquidValidation.d.cts.map +0 -1
  605. package/dist/utils/hyperLiquidValidation.d.mts +0 -192
  606. package/dist/utils/hyperLiquidValidation.d.mts.map +0 -1
  607. package/dist/utils/hyperLiquidValidation.mjs.map +0 -1
  608. package/dist/utils/idUtils.cjs +0 -18
  609. package/dist/utils/idUtils.cjs.map +0 -1
  610. package/dist/utils/idUtils.d.cts.map +0 -1
  611. package/dist/utils/idUtils.d.mts +0 -6
  612. package/dist/utils/idUtils.d.mts.map +0 -1
  613. package/dist/utils/idUtils.mjs.map +0 -1
  614. package/dist/utils/index.cjs +0 -65
  615. package/dist/utils/index.cjs.map +0 -1
  616. package/dist/utils/index.d.cts +0 -28
  617. package/dist/utils/index.d.cts.map +0 -1
  618. package/dist/utils/index.d.mts +0 -28
  619. package/dist/utils/index.d.mts.map +0 -1
  620. package/dist/utils/index.mjs.map +0 -1
  621. package/dist/utils/marketDataTransform.cjs +0 -250
  622. package/dist/utils/marketDataTransform.cjs.map +0 -1
  623. package/dist/utils/marketDataTransform.d.cts.map +0 -1
  624. package/dist/utils/marketDataTransform.d.mts +0 -71
  625. package/dist/utils/marketDataTransform.d.mts.map +0 -1
  626. package/dist/utils/marketDataTransform.mjs.map +0 -1
  627. package/dist/utils/marketSearch.cjs +0 -111
  628. package/dist/utils/marketSearch.cjs.map +0 -1
  629. package/dist/utils/marketSearch.d.cts.map +0 -1
  630. package/dist/utils/marketSearch.d.mts +0 -48
  631. package/dist/utils/marketSearch.d.mts.map +0 -1
  632. package/dist/utils/marketSearch.mjs.map +0 -1
  633. package/dist/utils/marketUtils.cjs +0 -266
  634. package/dist/utils/marketUtils.cjs.map +0 -1
  635. package/dist/utils/marketUtils.d.cts.map +0 -1
  636. package/dist/utils/marketUtils.d.mts +0 -73
  637. package/dist/utils/marketUtils.d.mts.map +0 -1
  638. package/dist/utils/marketUtils.mjs.map +0 -1
  639. package/dist/utils/myxAdapter.cjs +0 -569
  640. package/dist/utils/myxAdapter.cjs.map +0 -1
  641. package/dist/utils/myxAdapter.d.cts.map +0 -1
  642. package/dist/utils/myxAdapter.d.mts +0 -168
  643. package/dist/utils/myxAdapter.d.mts.map +0 -1
  644. package/dist/utils/myxAdapter.mjs.map +0 -1
  645. package/dist/utils/orderCalculations.cjs +0 -823
  646. package/dist/utils/orderCalculations.cjs.map +0 -1
  647. package/dist/utils/orderCalculations.d.cts.map +0 -1
  648. package/dist/utils/orderCalculations.d.mts +0 -298
  649. package/dist/utils/orderCalculations.d.mts.map +0 -1
  650. package/dist/utils/orderCalculations.mjs.map +0 -1
  651. package/dist/utils/orderTypes.cjs +0 -301
  652. package/dist/utils/orderTypes.cjs.map +0 -1
  653. package/dist/utils/orderTypes.d.cts +0 -166
  654. package/dist/utils/orderTypes.d.cts.map +0 -1
  655. package/dist/utils/orderTypes.d.mts.map +0 -1
  656. package/dist/utils/orderTypes.mjs.map +0 -1
  657. package/dist/utils/perpsConnectionAttemptContext.cjs +0 -20
  658. package/dist/utils/perpsConnectionAttemptContext.cjs.map +0 -1
  659. package/dist/utils/perpsConnectionAttemptContext.d.cts +0 -7
  660. package/dist/utils/perpsConnectionAttemptContext.d.cts.map +0 -1
  661. package/dist/utils/perpsConnectionAttemptContext.d.mts.map +0 -1
  662. package/dist/utils/perpsConnectionAttemptContext.mjs.map +0 -1
  663. package/dist/utils/perpsDiskPersistence.cjs +0 -259
  664. package/dist/utils/perpsDiskPersistence.cjs.map +0 -1
  665. package/dist/utils/perpsDiskPersistence.d.cts.map +0 -1
  666. package/dist/utils/perpsDiskPersistence.d.mts +0 -112
  667. package/dist/utils/perpsDiskPersistence.d.mts.map +0 -1
  668. package/dist/utils/perpsDiskPersistence.mjs.map +0 -1
  669. package/dist/utils/perpsFormatters.cjs +0 -509
  670. package/dist/utils/perpsFormatters.cjs.map +0 -1
  671. package/dist/utils/perpsFormatters.d.cts.map +0 -1
  672. package/dist/utils/perpsFormatters.d.mts +0 -204
  673. package/dist/utils/perpsFormatters.d.mts.map +0 -1
  674. package/dist/utils/perpsFormatters.mjs.map +0 -1
  675. package/dist/utils/rewardsUtils.cjs +0 -98
  676. package/dist/utils/rewardsUtils.cjs.map +0 -1
  677. package/dist/utils/rewardsUtils.d.cts.map +0 -1
  678. package/dist/utils/rewardsUtils.d.mts +0 -33
  679. package/dist/utils/rewardsUtils.d.mts.map +0 -1
  680. package/dist/utils/rewardsUtils.mjs.map +0 -1
  681. package/dist/utils/significantFigures.cjs +0 -88
  682. package/dist/utils/significantFigures.cjs.map +0 -1
  683. package/dist/utils/significantFigures.d.cts.map +0 -1
  684. package/dist/utils/significantFigures.d.mts +0 -25
  685. package/dist/utils/significantFigures.d.mts.map +0 -1
  686. package/dist/utils/significantFigures.mjs.map +0 -1
  687. package/dist/utils/sortMarkets.cjs +0 -93
  688. package/dist/utils/sortMarkets.cjs.map +0 -1
  689. package/dist/utils/sortMarkets.d.cts.map +0 -1
  690. package/dist/utils/sortMarkets.d.mts +0 -25
  691. package/dist/utils/sortMarkets.d.mts.map +0 -1
  692. package/dist/utils/sortMarkets.mjs.map +0 -1
  693. package/dist/utils/standaloneInfoClient.cjs +0 -70
  694. package/dist/utils/standaloneInfoClient.cjs.map +0 -1
  695. package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
  696. package/dist/utils/standaloneInfoClient.d.mts +0 -37
  697. package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
  698. package/dist/utils/standaloneInfoClient.mjs.map +0 -1
  699. package/dist/utils/stringParseUtils.cjs +0 -34
  700. package/dist/utils/stringParseUtils.cjs.map +0 -1
  701. package/dist/utils/stringParseUtils.d.cts.map +0 -1
  702. package/dist/utils/stringParseUtils.d.mts +0 -11
  703. package/dist/utils/stringParseUtils.d.mts.map +0 -1
  704. package/dist/utils/stringParseUtils.mjs.map +0 -1
  705. package/dist/utils/transferData.cjs +0 -33
  706. package/dist/utils/transferData.cjs.map +0 -1
  707. package/dist/utils/transferData.d.cts.map +0 -1
  708. package/dist/utils/transferData.d.mts +0 -9
  709. package/dist/utils/transferData.d.mts.map +0 -1
  710. package/dist/utils/transferData.mjs.map +0 -1
  711. package/dist/utils/wait.cjs +0 -6
  712. package/dist/utils/wait.cjs.map +0 -1
  713. package/dist/utils/wait.d.cts.map +0 -1
  714. package/dist/utils/wait.d.mts +0 -2
  715. package/dist/utils/wait.d.mts.map +0 -1
  716. package/dist/utils/wait.mjs.map +0 -1
@@ -1,3196 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _HyperLiquidSubscriptionService_instances, _a, _HyperLiquidSubscriptionService_clientService, _HyperLiquidSubscriptionService_walletService, _HyperLiquidSubscriptionService_hip3Enabled, _HyperLiquidSubscriptionService_enabledDexs, _HyperLiquidSubscriptionService_allowlistMarkets, _HyperLiquidSubscriptionService_blocklistMarkets, _HyperLiquidSubscriptionService_priceDeviationLimit, _HyperLiquidSubscriptionService_discoverEnabledDexs, _HyperLiquidSubscriptionService_discoveredDexNames, _HyperLiquidSubscriptionService_dexDiscoveryPromise, _HyperLiquidSubscriptionService_dexDiscoveryResolver, _HyperLiquidSubscriptionService_expectedDexs, _HyperLiquidSubscriptionService_initializedDexs, _HyperLiquidSubscriptionService_priceSubscribers, _HyperLiquidSubscriptionService_positionSubscribers, _HyperLiquidSubscriptionService_orderFillSubscribers, _HyperLiquidSubscriptionService_orderSubscribers, _HyperLiquidSubscriptionService_accountSubscribers, _HyperLiquidSubscriptionService_marketDataSubscribers, _HyperLiquidSubscriptionService_orderBookSubscribers, _HyperLiquidSubscriptionService_globalAllMidsSubscription, _HyperLiquidSubscriptionService_globalAllMidsPromise, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, _HyperLiquidSubscriptionService_fastAssetCtxsCoins, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, _HyperLiquidSubscriptionService_globalBboSubscriptions, _HyperLiquidSubscriptionService_pendingBboPromises, _HyperLiquidSubscriptionService_orderFillSubscriptions, _HyperLiquidSubscriptionService_spotStateSubscriptions, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, _HyperLiquidSubscriptionService_symbolSubscriberCounts, _HyperLiquidSubscriptionService_dexSubscriberCounts, _HyperLiquidSubscriptionService_webData3Subscriptions, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, _HyperLiquidSubscriptionService_positionSubscriberCount, _HyperLiquidSubscriptionService_orderSubscriberCount, _HyperLiquidSubscriptionService_accountSubscriberCount, _HyperLiquidSubscriptionService_oiCapSubscriberCount, _HyperLiquidSubscriptionService_dexPositionsCache, _HyperLiquidSubscriptionService_dexOrdersCache, _HyperLiquidSubscriptionService_dexAccountCache, _HyperLiquidSubscriptionService_cachedSpotState, _HyperLiquidSubscriptionService_abstractionModeByUser, _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, _HyperLiquidSubscriptionService_spotStatePromise, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, _HyperLiquidSubscriptionService_spotStateGeneration, _HyperLiquidSubscriptionService_cachedPositions, _HyperLiquidSubscriptionService_cachedOrders, _HyperLiquidSubscriptionService_cachedAccount, _HyperLiquidSubscriptionService_ordersCacheInitialized, _HyperLiquidSubscriptionService_positionsCacheInitialized, _HyperLiquidSubscriptionService_oiCapSubscribers, _HyperLiquidSubscriptionService_cachedOICaps, _HyperLiquidSubscriptionService_cachedOICapsHash, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, _HyperLiquidSubscriptionService_cachedPriceData, _HyperLiquidSubscriptionService_allMidsSnapshots, _HyperLiquidSubscriptionService_cachedFills, _HyperLiquidSubscriptionService_fillsCacheInitialized, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, _HyperLiquidSubscriptionService_dexAssetCtxsCache, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, _HyperLiquidSubscriptionService_openOrdersSubscriptions, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, _HyperLiquidSubscriptionService_dexMetaCache, _HyperLiquidSubscriptionService_orderBookCache, _HyperLiquidSubscriptionService_marketDataCache, _HyperLiquidSubscriptionService_activeAssetCtxPriceTtlMs, _HyperLiquidSubscriptionService_isClearing, _HyperLiquidSubscriptionService_restoreRetryTimeouts, _HyperLiquidSubscriptionService_deps, _HyperLiquidSubscriptionService_logErrorUnlessClearing, _HyperLiquidSubscriptionService_isTransientSdkError, _HyperLiquidSubscriptionService_scheduleRestoreRetry, _HyperLiquidSubscriptionService_getErrorContext, _HyperLiquidSubscriptionService_isDexEnabled, _HyperLiquidSubscriptionService_waitForDexDiscovery, _HyperLiquidSubscriptionService_hashPositions, _HyperLiquidSubscriptionService_hashOrders, _HyperLiquidSubscriptionService_hashAccountState, _HyperLiquidSubscriptionService_cachedPositionsHash, _HyperLiquidSubscriptionService_cachedOrdersHash, _HyperLiquidSubscriptionService_cachedAccountHash, _HyperLiquidSubscriptionService_extractTPSLFromOrders, _HyperLiquidSubscriptionService_mergeTPSLIntoPositions, _HyperLiquidSubscriptionService_aggregateAccountStates, _HyperLiquidSubscriptionService_getAbstractionModeForUser, _HyperLiquidSubscriptionService_getSpotBalanceOptions, _HyperLiquidSubscriptionService_refreshAbstractionModeThrottled, _HyperLiquidSubscriptionService_ensureSpotState, _HyperLiquidSubscriptionService_refreshSpotState, _HyperLiquidSubscriptionService_ensureSpotStateSubscription, _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription, _HyperLiquidSubscriptionService_createUserDataSubscription, _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription, _HyperLiquidSubscriptionService_createClearinghouseSubscription, _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription, _HyperLiquidSubscriptionService_createOpenOrdersSubscription, _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers, _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription, _HyperLiquidSubscriptionService_ensureOrderFillISubscription, _HyperLiquidSubscriptionService_createSubscription, _HyperLiquidSubscriptionService_createPriceUpdate, _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice, _HyperLiquidSubscriptionService_projectPriceUpdate, _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription, _HyperLiquidSubscriptionService_ensureGlobalFastAssetCtxsSubscription, _HyperLiquidSubscriptionService_ensureActiveAssetSubscription, _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription, _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription, _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription, _HyperLiquidSubscriptionService_createDexAllMidsSubscription, _HyperLiquidSubscriptionService_createAssetCtxsSubscription, _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription, _HyperLiquidSubscriptionService_ensureBboSubscription, _HyperLiquidSubscriptionService_cleanupBboSubscription, _HyperLiquidSubscriptionService_processOrderBookData, _HyperLiquidSubscriptionService_notifyAllPriceSubscribers;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.HyperLiquidSubscriptionService = void 0;
16
- const utils_1 = require("@metamask/utils");
17
- const hyperLiquidConfig_js_1 = require("../constants/hyperLiquidConfig.cjs");
18
- const perpsConfig_js_1 = require("../constants/perpsConfig.cjs");
19
- const hyperliquid_types_js_1 = require("../types/hyperliquid-types.cjs");
20
- const index_js_1 = require("../types/index.cjs");
21
- const accountUtils_js_1 = require("../utils/accountUtils.cjs");
22
- const errorUtils_js_1 = require("../utils/errorUtils.cjs");
23
- const hyperLiquidAdapter_js_1 = require("../utils/hyperLiquidAdapter.cjs");
24
- const hyperLiquidOrderBookProcessor_js_1 = require("../utils/hyperLiquidOrderBookProcessor.cjs");
25
- const marketDataTransform_js_1 = require("../utils/marketDataTransform.cjs");
26
- const orderTypes_js_1 = require("../utils/orderTypes.cjs");
27
- /**
28
- * Service for managing HyperLiquid WebSocket subscriptions
29
- * Implements singleton subscription architecture with reference counting
30
- */
31
- class HyperLiquidSubscriptionService {
32
- constructor(clientService, walletService, platformDependencies, hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets, priceDeviationLimit, discoverEnabledDexs) {
33
- _HyperLiquidSubscriptionService_instances.add(this);
34
- // Service dependencies
35
- _HyperLiquidSubscriptionService_clientService.set(this, void 0);
36
- _HyperLiquidSubscriptionService_walletService.set(this, void 0);
37
- // HIP-3 feature flag support
38
- _HyperLiquidSubscriptionService_hip3Enabled.set(this, void 0);
39
- _HyperLiquidSubscriptionService_enabledDexs.set(this, void 0); // DEX identification (maps webData3 indices to DEX names)
40
- _HyperLiquidSubscriptionService_allowlistMarkets.set(this, void 0); // Market filtering (allowlist)
41
- _HyperLiquidSubscriptionService_blocklistMarkets.set(this, void 0); // Market filtering (blocklist)
42
- // Max market-vs-oracle price deviation before a market is reported untradable
43
- _HyperLiquidSubscriptionService_priceDeviationLimit.set(this, void 0);
44
- _HyperLiquidSubscriptionService_discoverEnabledDexs.set(this, void 0);
45
- _HyperLiquidSubscriptionService_discoveredDexNames.set(this, []); // DEX order for mapping webData3 perpDexStates indices
46
- // DEX discovery synchronization - allows subscriptions to wait for HIP-3 DEX discovery
47
- _HyperLiquidSubscriptionService_dexDiscoveryPromise.set(this, null);
48
- _HyperLiquidSubscriptionService_dexDiscoveryResolver.set(this, null);
49
- // Track DEXs for synchronized position notifications
50
- // Ensures all DEXs send initial data before notifying subscribers
51
- _HyperLiquidSubscriptionService_expectedDexs.set(this, new Set());
52
- _HyperLiquidSubscriptionService_initializedDexs.set(this, new Set());
53
- // Subscriber collections
54
- _HyperLiquidSubscriptionService_priceSubscribers.set(this, new Map());
55
- _HyperLiquidSubscriptionService_positionSubscribers.set(this, new Set());
56
- // Order fill subscribers keyed by accountId (normalized: undefined -> 'default')
57
- _HyperLiquidSubscriptionService_orderFillSubscribers.set(this, new Map());
58
- _HyperLiquidSubscriptionService_orderSubscribers.set(this, new Set());
59
- _HyperLiquidSubscriptionService_accountSubscribers.set(this, new Set());
60
- // Track which subscribers want market data
61
- _HyperLiquidSubscriptionService_marketDataSubscribers.set(this, new Map());
62
- // Track which subscribers want top-of-book (best bid/ask) data
63
- _HyperLiquidSubscriptionService_orderBookSubscribers.set(this, new Map());
64
- // Global singleton subscriptions
65
- _HyperLiquidSubscriptionService_globalAllMidsSubscription.set(this, void 0);
66
- _HyperLiquidSubscriptionService_globalAllMidsPromise.set(this, void 0); // Track in-progress subscription
67
- // fastAssetCtxs (TAT-3387): single global feed (no per-DEX param) that owns
68
- // the latency-sensitive mark/mid price path at HyperLiquid's fast (~5s)
69
- // cadence, now that the public assetCtxs feed has been slowed down.
70
- _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription.set(this, void 0);
71
- _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise.set(this, void 0); // Track in-progress subscription
72
- // Coins with a usable price (midPx/markPx) from any fastAssetCtxs event
73
- // (snapshot or diff). Once a coin appears here, the per-DEX assetCtxs
74
- // handler stops writing its price into #cachedPriceData, since
75
- // fastAssetCtxs is the fresher/authoritative source for that coin going
76
- // forward. A coin is only added once fastAssetCtxs has actually supplied a
77
- // usable price for it (not merely appeared in a message with a null/absent
78
- // price), so ownership is never claimed without a fast price backing it —
79
- // otherwise assetCtxs, the coin's only remaining price source, would be
80
- // suppressed with nothing to fall back on. Cleared on clearAll() and when
81
- // the fastAssetCtxs subscription is re-established after a reconnect, so
82
- // assetCtxs can serve prices again until a fresh snapshot arrives.
83
- _HyperLiquidSubscriptionService_fastAssetCtxsCoins.set(this, new Set());
84
- _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions.set(this, new Map());
85
- // Track in-progress activeAssetCtx subscription promises to prevent leaks
86
- // when cleanup fires before the async subscription resolves (#28141)
87
- _HyperLiquidSubscriptionService_pendingActiveAssetPromises.set(this, new Map());
88
- _HyperLiquidSubscriptionService_globalBboSubscriptions.set(this, new Map());
89
- // Track in-progress BBO subscription promises to prevent leaks (#28141)
90
- _HyperLiquidSubscriptionService_pendingBboPromises.set(this, new Map());
91
- // Order fill subscriptions keyed by accountId (normalized: undefined -> 'default')
92
- _HyperLiquidSubscriptionService_orderFillSubscriptions.set(this, new Map());
93
- _HyperLiquidSubscriptionService_spotStateSubscriptions.set(this, new Map());
94
- _HyperLiquidSubscriptionService_spotStateSubscriptionPromises.set(this, new Map());
95
- // Bumped on cleanup so in-flight #ensureSpotStateSubscription
96
- // continuations discard their subscription instead of rehydrating
97
- // #spotStateSubscriptions after clearAll/cleanupSharedWebData3.
98
- _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration.set(this, 0);
99
- _HyperLiquidSubscriptionService_symbolSubscriberCounts.set(this, new Map());
100
- _HyperLiquidSubscriptionService_dexSubscriberCounts.set(this, new Map()); // Track subscribers per DEX for assetCtxs
101
- // Multi-DEX webData3 subscription for all user data (positions, orders, account, OI caps)
102
- _HyperLiquidSubscriptionService_webData3Subscriptions.set(this, new Map()); // Key: dex name ('' for main)
103
- _HyperLiquidSubscriptionService_webData3SubscriptionPromise.set(this, void 0);
104
- _HyperLiquidSubscriptionService_positionSubscriberCount.set(this, 0);
105
- _HyperLiquidSubscriptionService_orderSubscriberCount.set(this, 0);
106
- _HyperLiquidSubscriptionService_accountSubscriberCount.set(this, 0);
107
- _HyperLiquidSubscriptionService_oiCapSubscriberCount.set(this, 0);
108
- // Multi-DEX data caches
109
- _HyperLiquidSubscriptionService_dexPositionsCache.set(this, new Map()); // Per-DEX positions
110
- _HyperLiquidSubscriptionService_dexOrdersCache.set(this, new Map()); // Per-DEX orders
111
- _HyperLiquidSubscriptionService_dexAccountCache.set(this, new Map()); // Per-DEX account state
112
- _HyperLiquidSubscriptionService_cachedSpotState.set(this, null);
113
- // HL abstraction mode (Unified / Standard / Portfolio / DEX-abstraction).
114
- // Gates spot→perps folding in addSpotBalanceToAccountState. Keyed by user
115
- // address so an in-flight refresh or late response for one wallet cannot
116
- // overwrite another wallet's fold semantics after an account switch.
117
- _HyperLiquidSubscriptionService_abstractionModeByUser.set(this, new Map());
118
- // Timestamp of the last successful WS-driven userAbstraction refresh per
119
- // user. This throttle intentionally does not count the initial bootstrap
120
- // fetch so the first spot tick after app launch can still detect an HL-web
121
- // mode flip immediately.
122
- _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser.set(this, new Map());
123
- // In-flight promises for WS-triggered refreshes, keyed by user so concurrent
124
- // ticks for the same wallet share one fetch while account switches can start
125
- // their own refresh immediately.
126
- _HyperLiquidSubscriptionService_abstractionModeInflightByUser.set(this, new Map());
127
- _HyperLiquidSubscriptionService_cachedSpotStateUserAddress.set(this, null);
128
- _HyperLiquidSubscriptionService_spotStatePromise.set(this, void 0);
129
- _HyperLiquidSubscriptionService_spotStatePromiseUserAddress.set(this, void 0);
130
- // Monotonic token bumped on cleanUp/clearAll and on each new fetch.
131
- // Any in-flight #refreshSpotState that resolves with a stale token
132
- // discards its result, preventing cross-account cache contamination
133
- // when accounts are switched mid-fetch.
134
- _HyperLiquidSubscriptionService_spotStateGeneration.set(this, 0);
135
- _HyperLiquidSubscriptionService_cachedPositions.set(this, null); // Aggregated positions
136
- _HyperLiquidSubscriptionService_cachedOrders.set(this, null); // Aggregated orders
137
- _HyperLiquidSubscriptionService_cachedAccount.set(this, null); // Aggregated account
138
- _HyperLiquidSubscriptionService_ordersCacheInitialized.set(this, false); // Track if orders cache has received WebSocket data
139
- _HyperLiquidSubscriptionService_positionsCacheInitialized.set(this, false); // Track if positions cache has received WebSocket data
140
- // OI Cap tracking (from webData3.perpDexStates[].perpsAtOpenInterestCap)
141
- _HyperLiquidSubscriptionService_oiCapSubscribers.set(this, new Set());
142
- _HyperLiquidSubscriptionService_cachedOICaps.set(this, []);
143
- _HyperLiquidSubscriptionService_cachedOICapsHash.set(this, '');
144
- _HyperLiquidSubscriptionService_oiCapsCacheInitialized.set(this, false);
145
- // Global price data cache
146
- _HyperLiquidSubscriptionService_cachedPriceData.set(this, null);
147
- // Raw allMids WS snapshots keyed by DEX ('' for main DEX)
148
- _HyperLiquidSubscriptionService_allMidsSnapshots.set(this, new Map());
149
- // Fills cache for cache-first pattern (similar to price caching)
150
- _HyperLiquidSubscriptionService_cachedFills.set(this, null);
151
- _HyperLiquidSubscriptionService_fillsCacheInitialized.set(this, false);
152
- // HIP-3: assetCtxs subscriptions for multi-DEX market data
153
- _HyperLiquidSubscriptionService_assetCtxsSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
154
- _HyperLiquidSubscriptionService_dexAssetCtxsCache.set(this, new Map()); // Per-DEX asset contexts
155
- _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises.set(this, new Map()); // Track in-progress subscriptions
156
- _HyperLiquidSubscriptionService_dexAllMidsSubscriptions.set(this, new Map());
157
- _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises.set(this, new Map());
158
- _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
159
- _HyperLiquidSubscriptionService_openOrdersSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
160
- // Pending subscription promises to prevent race conditions
161
- // When multiple calls to ensure*Subscription happen concurrently, this ensures
162
- // only one subscription is created per DEX (others wait for the pending promise)
163
- _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions.set(this, new Map());
164
- _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions.set(this, new Map());
165
- // Meta cache per DEX - populated by metaAndAssetCtxs, used by createAssetCtxsSubscription
166
- // This avoids redundant meta() API calls since metaAndAssetCtxs already returns meta data
167
- _HyperLiquidSubscriptionService_dexMetaCache.set(this, new Map());
168
- // Order book data cache
169
- _HyperLiquidSubscriptionService_orderBookCache.set(this, new Map());
170
- // Market data caching for multi-channel consolidation
171
- _HyperLiquidSubscriptionService_marketDataCache.set(this, new Map());
172
- // Flag to suppress error logging during intentional disconnect
173
- // Set in clearAll() and never reset (service instance is discarded after disconnect)
174
- _HyperLiquidSubscriptionService_isClearing.set(this, false);
175
- _HyperLiquidSubscriptionService_restoreRetryTimeouts.set(this, new Map());
176
- // Platform dependencies for logging
177
- _HyperLiquidSubscriptionService_deps.set(this, void 0);
178
- // Cache hashes to avoid recomputation
179
- _HyperLiquidSubscriptionService_cachedPositionsHash.set(this, '');
180
- _HyperLiquidSubscriptionService_cachedOrdersHash.set(this, '');
181
- _HyperLiquidSubscriptionService_cachedAccountHash.set(this, '');
182
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_clientService, clientService, "f");
183
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_walletService, walletService, "f");
184
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_deps, platformDependencies, "f");
185
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_hip3Enabled, hip3Enabled ?? false, "f");
186
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_enabledDexs, enabledDexs ?? [], "f");
187
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoveredDexNames, enabledDexs ?? [], "f");
188
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_allowlistMarkets, allowlistMarkets ?? [], "f");
189
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_blocklistMarkets, blocklistMarkets ?? [], "f");
190
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_priceDeviationLimit, priceDeviationLimit ?? hyperLiquidConfig_js_1.HYPERLIQUID_CONFIG.OraclePriceDeviationLimit, "f");
191
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoverEnabledDexs, discoverEnabledDexs, "f");
192
- }
193
- /**
194
- * Populate DEX meta cache with pre-fetched meta data
195
- * Called by Provider after buildAssetMapping to share cached meta,
196
- * avoiding redundant metaAndAssetCtxs/meta API calls during subscription setup
197
- *
198
- * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
199
- * @param meta - Meta response containing universe data
200
- * @param meta.universe - The array of asset universe entries from the meta response.
201
- */
202
- setDexMetaCache(dex, meta) {
203
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").set(dex, meta);
204
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('[SubscriptionService] DEX meta cache populated', {
205
- dex: dex || 'main',
206
- universeSize: meta.universe.length,
207
- });
208
- }
209
- /**
210
- * Cache asset contexts for a specific DEX from API response
211
- * This allows buildAssetMapping() to populate cache for getMarketDataWithPrices() to use
212
- *
213
- * @param dex - DEX name ('' for main perps)
214
- * @param assetCtxs - Asset contexts from metaAndAssetCtxs response
215
- */
216
- setDexAssetCtxsCache(dex, assetCtxs) {
217
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").set(dex, assetCtxs);
218
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('[SubscriptionService] DEX assetCtxs cache populated', {
219
- dex: dex || 'main',
220
- ctxsCount: assetCtxs.length,
221
- });
222
- }
223
- /**
224
- * Get cached assetCtxs for a DEX
225
- * Returns the cached asset contexts from WebSocket subscription if available
226
- *
227
- * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
228
- * @returns Array of asset contexts or undefined if not cached
229
- */
230
- getDexAssetCtxsCache(dex) {
231
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").get(dex);
232
- }
233
- /**
234
- * Update feature flags for HIP-3 support
235
- * Called when provider configuration changes at runtime
236
- * Note: Market filtering is NOT applied in subscription service - only in Provider
237
- *
238
- * @param hip3Enabled - Whether HIP-3 multi-DEX support is enabled.
239
- * @param enabledDexs - The array of enabled DEX identifiers.
240
- * @param allowlistMarkets - The array of allowed market patterns.
241
- * @param blocklistMarkets - The array of blocked market patterns.
242
- */
243
- async updateFeatureFlags(hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets) {
244
- const previousEnabledDexs = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f")];
245
- const previousAllowlistMarkets = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allowlistMarkets, "f")];
246
- const previousBlocklistMarkets = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_blocklistMarkets, "f")];
247
- const previousHip3Enabled = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f");
248
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_hip3Enabled, hip3Enabled, "f");
249
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_enabledDexs, enabledDexs, "f");
250
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_allowlistMarkets, allowlistMarkets, "f");
251
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_blocklistMarkets, blocklistMarkets, "f");
252
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoveredDexNames, enabledDexs, "f"); // Store DEX order for webData3 index mapping
253
- // Resolve any pending DEX discovery wait now that DEXs are available
254
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, "f") && enabledDexs.length > 0) {
255
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, "f").call(this);
256
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, null, "f");
257
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, null, "f");
258
- }
259
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Feature flags updated:', {
260
- previousHip3Enabled,
261
- hip3Enabled,
262
- previousEnabledDexs,
263
- enabledDexs,
264
- previousAllowlistMarkets,
265
- allowlistMarkets,
266
- previousBlocklistMarkets,
267
- blocklistMarkets,
268
- });
269
- // If equity was just enabled or new DEXs were added
270
- const newDexs = enabledDexs.filter((dex) => !previousEnabledDexs.includes(dex));
271
- if ((!previousHip3Enabled && hip3Enabled && enabledDexs.length > 0) ||
272
- newDexs.length > 0) {
273
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Establishing subscriptions for new DEXs:', newDexs);
274
- // Establish assetCtxs subscriptions for new DEXs (for market data)
275
- const hasMarketDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0;
276
- if (hasMarketDataSubscribers) {
277
- await Promise.all(newDexs.map(async (dex) => {
278
- try {
279
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dex);
280
- }
281
- catch (error) {
282
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.ensureAssetCtxsSubscription', {
283
- dex,
284
- }));
285
- }
286
- }));
287
- }
288
- // Establish clearinghouseState/openOrders subscriptions for new DEXs
289
- // (needed for positions, orders, and account data when using individual subscriptions)
290
- const hasUserDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0 ||
291
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") > 0 ||
292
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") > 0;
293
- if (hasUserDataSubscribers && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")) {
294
- try {
295
- const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault();
296
- await Promise.all(newDexs.map(async (dex) => {
297
- try {
298
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription).call(this, userAddress, dex);
299
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription).call(this, userAddress, dex);
300
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Established user data subscriptions for new DEX: ${dex}`);
301
- }
302
- catch (error) {
303
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.ensureUserDataSubscription', { dex }));
304
- }
305
- }));
306
- }
307
- catch (error) {
308
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.getUserAddress'));
309
- }
310
- }
311
- }
312
- }
313
- /**
314
- * Return the cached HL abstraction mode for the given user address.
315
- *
316
- * @param userAddress - The EVM address to look up.
317
- * @returns Cached abstraction mode, or null when unresolved.
318
- */
319
- getCachedAbstractionMode(userAddress) {
320
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getAbstractionModeForUser).call(this, userAddress);
321
- }
322
- /**
323
- * Record a user's resolved abstraction mode and immediately re-aggregate.
324
- * Call after the provider has confirmed the on-chain mode (already-enabled
325
- * or just-migrated) so the WS-driven aggregator picks up the correct fold
326
- * decision on the next tick.
327
- *
328
- * @param userAddress - The EVM address whose mode is being recorded.
329
- * @param mode - The current abstraction mode for this user.
330
- */
331
- setUserAbstractionMode(userAddress, mode) {
332
- const lower = userAddress.toLowerCase();
333
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").set(lower, mode);
334
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size > 0) {
335
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
336
- }
337
- }
338
- /**
339
- * Subscribe to live price updates with singleton subscription architecture
340
- * Uses allMids for fast price updates and predictedFundings for accurate funding rates
341
- *
342
- * @param params - The subscription parameters including symbols and callbacks.
343
- * @returns A cleanup function to unsubscribe from price updates.
344
- */
345
- async subscribeToPrices(params) {
346
- const { symbols, callback, includeOrderBook = false, includeMarketData = false, } = params;
347
- const unsubscribers = [];
348
- symbols.forEach((symbol) => {
349
- unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f"), callback, symbol));
350
- // Track market data subscribers separately
351
- if (includeMarketData) {
352
- unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f"), callback, symbol));
353
- }
354
- // Track order book subscribers separately
355
- if (includeOrderBook) {
356
- unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f"), callback, symbol));
357
- }
358
- });
359
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
360
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
361
- if (!subscriptionClient) {
362
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('SubscriptionClient not available for price subscription');
363
- return () => unsubscribers.forEach((fn) => fn());
364
- }
365
- // Ensure global subscriptions are established
366
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription).call(this);
367
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalFastAssetCtxsSubscription).call(this);
368
- // Extract unique DEXs from requested symbols
369
- const dexsNeeded = new Set();
370
- symbols.forEach((symbol) => {
371
- const { dex } = (0, hyperLiquidAdapter_js_1.parseAssetName)(symbol);
372
- dexsNeeded.add(dex);
373
- });
374
- // Always ensure assetCtxs subscriptions (1 per DEX, lightweight).
375
- // Provides prevDayPx for percentChange24h even without includeMarketData
376
- // (e.g., prewarm after reconnection). Uses incrementRefCount: false when
377
- // not explicitly requested so lifecycle is managed by component subscriptions.
378
- dexsNeeded.forEach((dex) => {
379
- const dexName = dex ?? '';
380
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dexName, {
381
- incrementRefCount: includeMarketData,
382
- }).catch((error) => {
383
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToPrices'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToPrices.ensureAssetCtxsSubscription', { dex: dexName }));
384
- });
385
- });
386
- // dexAllMids and activeAssetCtx only when market data explicitly requested
387
- if (includeMarketData) {
388
- dexsNeeded.forEach((dex) => {
389
- const dexName = dex ?? '';
390
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription).call(this, dexName).catch((error) => {
391
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToPrices'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToPrices.ensureDexAllMidsSubscription', { dex: dexName }));
392
- });
393
- });
394
- }
395
- // Note: Funding rates are now cached via assetCtxs WebSocket subscription
396
- // (ensureAssetCtxsSubscription above), eliminating the need for a separate
397
- // metaAndAssetCtxs API call here. The WebSocket callback in createAssetCtxsSubscription
398
- // populates marketDataCache with funding rates as they arrive.
399
- symbols.forEach((symbol) => {
400
- // Subscribe to activeAssetCtx only when market data is requested
401
- if (includeMarketData) {
402
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureActiveAssetSubscription).call(this, symbol);
403
- }
404
- if (includeOrderBook) {
405
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureBboSubscription).call(this, symbol);
406
- }
407
- });
408
- // Send cached data immediately if available, projecting the fast-stream
409
- // price for focused subscribers and falling back to the allMids baseline
410
- // for list subscribers.
411
- symbols.forEach((symbol) => {
412
- const cachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol);
413
- if (cachedPrice) {
414
- const projected = includeMarketData
415
- ? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_projectPriceUpdate).call(this, symbol, cachedPrice)
416
- : cachedPrice;
417
- callback([projected]);
418
- }
419
- else if (includeMarketData) {
420
- // No allMids baseline yet; if a fresh fast-stream price is cached,
421
- // send it immediately so focused screens are not blank on first render.
422
- const fastPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice).call(this, symbol);
423
- if (fastPrice !== undefined) {
424
- callback([__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, fastPrice)]);
425
- }
426
- }
427
- });
428
- // Return cleanup function
429
- return () => {
430
- unsubscribers.forEach((fn) => fn());
431
- // Cleanup subscriptions with reference counting
432
- symbols.forEach((symbol) => {
433
- if (includeMarketData) {
434
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription).call(this, symbol);
435
- }
436
- if (includeOrderBook) {
437
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupBboSubscription).call(this, symbol);
438
- }
439
- });
440
- // Cleanup DEX-level assetCtxs subscriptions
441
- if (includeMarketData) {
442
- dexsNeeded.forEach((dex) => {
443
- const dexName = dex ?? '';
444
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription).call(this, dexName);
445
- });
446
- }
447
- };
448
- }
449
- /**
450
- * Subscribe to live position updates with TP/SL data
451
- *
452
- * @param params - The subscription parameters including callback and account ID.
453
- * @returns A cleanup function to unsubscribe from position updates.
454
- */
455
- subscribeToPositions(params) {
456
- const { callback, accountId } = params;
457
- const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f"), callback);
458
- // Increment position subscriber count
459
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") + 1, "f");
460
- // Immediately provide cached data if available
461
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f")) {
462
- callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f"));
463
- }
464
- // Ensure shared subscription is active
465
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
466
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToPositions'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToPositions'));
467
- });
468
- return () => {
469
- unsubscribe();
470
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") - 1, "f");
471
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
472
- };
473
- }
474
- /**
475
- * Subscribe to open interest cap updates
476
- * OI caps are extracted from the shared webData3 subscription (zero additional overhead)
477
- *
478
- * @param params - The subscription parameters including callback and account ID.
479
- * @returns A cleanup function to unsubscribe from OI cap updates.
480
- */
481
- subscribeToOICaps(params) {
482
- const { callback, accountId } = params;
483
- // Create subscription
484
- const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f"), callback);
485
- // Increment OI cap subscriber count
486
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f") + 1, "f");
487
- // Immediately provide cached data if available
488
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICaps, "f")) {
489
- callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICaps, "f"));
490
- }
491
- // Ensure webData3 subscription is active (OI caps come from webData3)
492
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
493
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOICaps'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOICaps'));
494
- });
495
- return () => {
496
- unsubscribe();
497
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f") - 1, "f");
498
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
499
- };
500
- }
501
- /**
502
- * Check if OI caps cache has been initialized
503
- * Useful for preventing UI flashing before first data arrives
504
- *
505
- * @returns True if the condition is met.
506
- */
507
- isOICapsCacheInitialized() {
508
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, "f");
509
- }
510
- /**
511
- * Subscribe to live order fill updates
512
- * Shares subscriptions per accountId to avoid duplicate WebSocket connections
513
- *
514
- * @param params - The subscription parameters including callback and account ID.
515
- * @returns A cleanup function to unsubscribe from order fill updates.
516
- */
517
- subscribeToOrderFills(params) {
518
- const { callback, accountId } = params;
519
- // Normalize accountId: undefined -> 'default' for Map key
520
- const normalizedAccountId = accountId ?? 'default';
521
- const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f"), callback, normalizedAccountId);
522
- // Ensure subscription is established for this accountId
523
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId).catch((error) => {
524
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderFills'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderFills'));
525
- });
526
- return () => {
527
- unsubscribe();
528
- // If no more subscribers for this accountId, clean up subscription
529
- const subscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").get(normalizedAccountId);
530
- if (!subscribers || subscribers.size === 0) {
531
- const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").get(normalizedAccountId);
532
- if (subscription) {
533
- subscription.unsubscribe().catch((error) => {
534
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderFills'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderFills.unsubscribe'));
535
- });
536
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").delete(normalizedAccountId);
537
- }
538
- }
539
- };
540
- }
541
- /**
542
- * Subscribe to live order updates
543
- * Uses the shared per-DEX subscriptions to avoid duplicate connections
544
- *
545
- * @param params - The subscription parameters including callback and account ID.
546
- * @returns A cleanup function to unsubscribe from order updates.
547
- */
548
- subscribeToOrders(params) {
549
- const { callback, accountId } = params;
550
- const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f"), callback);
551
- // Increment order subscriber count
552
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") + 1, "f");
553
- // Immediately provide cached data if available
554
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")) {
555
- callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f"));
556
- }
557
- // Ensure shared subscription is active
558
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
559
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrders'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrders'));
560
- });
561
- return () => {
562
- unsubscribe();
563
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") - 1, "f");
564
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
565
- };
566
- }
567
- /**
568
- * Subscribe to live account updates
569
- * Uses the shared per-DEX subscriptions to avoid duplicate connections
570
- *
571
- * @param params - The subscription parameters including callback and account ID.
572
- * @returns A cleanup function to unsubscribe from account updates.
573
- */
574
- subscribeToAccount(params) {
575
- const { callback, accountId } = params;
576
- const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f"), callback);
577
- // Increment account subscriber count
578
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") + 1, "f");
579
- // Immediately provide cached data if available. May be spot-less if the
580
- // spot fetch has not resolved yet (or permanently failed) — subscribers
581
- // prefer stale-but-present data over silent starvation; the next
582
- // aggregation after #ensureSpotState / next WebSocket update pushes the
583
- // spot-inclusive value.
584
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccount, "f")) {
585
- callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccount, "f"));
586
- }
587
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSpotState).call(this, accountId).catch((error) => {
588
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToAccount'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToAccount.ensureSpotState'));
589
- });
590
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSpotStateSubscription).call(this, accountId).catch((error) => {
591
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToAccount'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToAccount.ensureSpotStateSubscription'));
592
- });
593
- // Ensure shared subscription is active (reuses existing connection)
594
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
595
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToAccount'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToAccount'));
596
- });
597
- return () => {
598
- unsubscribe();
599
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") - 1, "f");
600
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
601
- };
602
- }
603
- /**
604
- * Check if orders cache has been initialized from WebSocket
605
- *
606
- * @returns true if WebSocket has sent at least one update, false otherwise
607
- */
608
- isOrdersCacheInitialized() {
609
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, "f");
610
- }
611
- /**
612
- * Check if positions cache has been initialized from WebSocket
613
- *
614
- * @returns true if WebSocket has sent at least one update, false otherwise
615
- */
616
- isPositionsCacheInitialized() {
617
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, "f");
618
- }
619
- /**
620
- * Get the cached positions for one DEX, or null when that DEX has published
621
- * none this session.
622
- *
623
- * A DEX only enters this map once its `clearinghouseState` subscription has
624
- * published, so `null` means the absence of a symbol proves nothing about
625
- * whether a position exists there.
626
- *
627
- * Prefer this over `getCachedPositions()` when a decision depends on whether a
628
- * specific symbol is absent. The aggregate is only rebuilt once *every*
629
- * expected DEX has published (`#aggregateAndNotifySubscribers`), so after a
630
- * reconnect — which resets `#initializedDexs` without clearing these caches —
631
- * the aggregate can sit frozen at its pre-reconnect contents while this map
632
- * keeps receiving per-DEX updates. Deciding "covered" from this map and then
633
- * reading the symbol from the aggregate would mix a fresh answer with stale
634
- * data.
635
- *
636
- * @param dexName - DEX identifier, or '' for the main DEX.
637
- * @returns That DEX's cached positions, or null if it has not published.
638
- */
639
- getCachedPositionsForDex(dexName) {
640
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").get(dexName) ?? null;
641
- }
642
- /**
643
- * Get cached positions from WebSocket subscription
644
- *
645
- * @returns Cached positions array, or null if not initialized
646
- */
647
- getCachedPositions() {
648
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f");
649
- }
650
- /**
651
- * Get cached orders from WebSocket subscription
652
- *
653
- * @returns Cached orders array, or null if not initialized
654
- */
655
- getCachedOrders() {
656
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f");
657
- }
658
- /**
659
- * Atomically get cached orders if initialized
660
- * Prevents race condition between checking initialization and getting data
661
- *
662
- * @returns Cached orders array if initialized, null otherwise
663
- */
664
- getOrdersCacheIfInitialized() {
665
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, "f")) {
666
- return null;
667
- }
668
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")] : [];
669
- }
670
- /**
671
- * Get cached price for a symbol from WebSocket allMids subscription
672
- * OPTIMIZATION: Use this instead of REST infoClient.allMids() to avoid rate limiting
673
- *
674
- * @param symbol - Asset symbol (e.g., 'BTC', 'ETH', 'xyz:TSLA')
675
- * @returns Price string, or undefined if not cached
676
- */
677
- getCachedPrice(symbol) {
678
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol)?.price;
679
- }
680
- getLastAllMidsSnapshot(dex) {
681
- const dexKey = dex ?? '';
682
- const snapshot = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allMidsSnapshots, "f").get(dexKey);
683
- if (!snapshot) {
684
- return null;
685
- }
686
- return { ...snapshot };
687
- }
688
- /**
689
- * Get cached fills from WebSocket userFills subscription
690
- * OPTIMIZATION: Use this instead of REST userFills() to avoid rate limiting
691
- *
692
- * @returns Copy of cached fills array, or null if not cached
693
- */
694
- getCachedFills() {
695
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f")] : null;
696
- }
697
- /**
698
- * Get cached fills only if the cache has been initialized from WebSocket
699
- * OPTIMIZATION: Distinguishes between "not initialized" (null) and "initialized but empty" ([])
700
- * - Returns null if cache hasn't received WebSocket snapshot yet (caller should use REST)
701
- * - Returns empty array [] if cache is initialized but user has no fills (caller can skip REST)
702
- * - Returns fills array if cache has data
703
- *
704
- * @returns Fills array or empty array if initialized, null if not yet initialized
705
- */
706
- getFillsCacheIfInitialized() {
707
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, "f")) {
708
- return null;
709
- }
710
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f")] : [];
711
- }
712
- /**
713
- * Subscribe to full order book updates with multiple depth levels
714
- * Creates a dedicated L2Book subscription for the requested symbol
715
- * and processes data into OrderBookData format for UI consumption
716
- *
717
- * @param params - Subscription parameters
718
- * @returns Cleanup function to unsubscribe
719
- */
720
- subscribeToOrderBook(params) {
721
- const { symbol, levels = 10, nSigFigs = 5, mantissa, fast, callback, onError, } = params;
722
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f")
723
- .ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter())
724
- .catch(() => {
725
- // Handled by getSubscriptionClient check below
726
- });
727
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
728
- if (!subscriptionClient) {
729
- const error = new Error('Subscription client not available');
730
- onError?.(error);
731
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('subscribeToOrderBook: Subscription client not available');
732
- return () => {
733
- // No-op cleanup
734
- };
735
- }
736
- let subscription;
737
- let cancelled = false;
738
- subscriptionClient
739
- .l2Book({ coin: symbol, nSigFigs, mantissa, fast }, (data) => {
740
- if (cancelled || data?.coin !== symbol || !data?.levels) {
741
- return;
742
- }
743
- const orderBookData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_processOrderBookData).call(this, data, levels);
744
- callback(orderBookData);
745
- })
746
- .then(async (sub) => {
747
- if (cancelled) {
748
- try {
749
- await sub.unsubscribe();
750
- }
751
- catch (unsubError) {
752
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(unsubError, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook.cleanup', { symbol }));
753
- }
754
- return undefined;
755
- }
756
- subscription = sub;
757
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: Order book subscription established for ${symbol}`);
758
- return undefined;
759
- })
760
- .catch((error) => {
761
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook', { symbol }));
762
- onError?.((0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'));
763
- });
764
- return () => {
765
- cancelled = true;
766
- if (subscription) {
767
- subscription.unsubscribe().catch((error) => {
768
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook.unsubscribe', {
769
- symbol,
770
- }));
771
- });
772
- }
773
- };
774
- }
775
- /**
776
- * Restore all active subscriptions after WebSocket reconnection
777
- * Re-establishes WebSocket subscriptions for all active subscribers
778
- *
779
- * IMPORTANT: This method verifies transport readiness before attempting
780
- * any subscriptions to prevent "subscribe error: undefined" errors.
781
- */
782
- async restoreSubscriptions() {
783
- // CRITICAL: Verify transport is ready before attempting any subscriptions
784
- // This prevents race conditions where subscriptions are attempted while
785
- // the WebSocket is still in CONNECTING state
786
- try {
787
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureTransportReady({ timeoutMs: 5000 });
788
- }
789
- catch (error) {
790
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Transport not ready during subscription restore, will retry on next reconnect', { error: error instanceof Error ? error.message : String(error) });
791
- return;
792
- }
793
- // Re-establish global allMids subscription if there are price subscribers
794
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").size > 0) {
795
- // Clear existing subscription reference (it's dead after reconnection)
796
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, undefined, "f");
797
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, undefined, "f");
798
- // Re-establish the subscription
799
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription).call(this);
800
- // Re-establish the fastAssetCtxs subscription alongside allMids (TAT-3387).
801
- // Clear fastAssetCtxsCoins so assetCtxs can serve prices in the gap
802
- // until the fresh post-reconnect snapshot re-establishes coverage.
803
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, undefined, "f");
804
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, undefined, "f");
805
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fastAssetCtxsCoins, "f").clear();
806
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalFastAssetCtxsSubscription).call(this);
807
- }
808
- // Re-establish order fill subscriptions if there are fill subscribers
809
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").size > 0) {
810
- // Clear existing subscription references (they're dead after reconnection)
811
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").clear();
812
- // Re-establish subscriptions for all accountIds with subscribers
813
- // Note: normalizedAccountId is 'default' for undefined, need to convert back
814
- const normalizedAccountIds = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").keys());
815
- await Promise.all(normalizedAccountIds.map((normalizedAccountId) => {
816
- // Convert normalized key back to original accountId (undefined if 'default')
817
- const accountId = normalizedAccountId === 'default'
818
- ? undefined
819
- : normalizedAccountId;
820
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId).catch(() => {
821
- // Ignore errors during order fill subscription restoration
822
- });
823
- }));
824
- }
825
- // Re-establish user data subscriptions if there are user data subscribers
826
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").size > 0 ||
827
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").size > 0 ||
828
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").size > 0 ||
829
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f").size > 0) {
830
- // Clear existing subscription references (they're dead after reconnection)
831
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
832
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
833
- // Clear individual subscriptions (clearinghouseState + openOrders)
834
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
835
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
836
- // Re-establish the subscription (will use current account)
837
- // This sets up per-DEX clearinghouseState + openOrders subscriptions plus webData3 (OI caps only)
838
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this);
839
- }
840
- // Re-establish activeAsset subscriptions if there are market data subscribers
841
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0) {
842
- // Clear existing subscriptions (they're dead after reconnection)
843
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").clear();
844
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").clear();
845
- // Clear reference counts to prevent double-counting after reconnection
846
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").clear();
847
- // Re-establish subscriptions for all symbols with market data subscribers
848
- const symbolsNeedingMarketData = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").keys());
849
- symbolsNeedingMarketData.forEach((symbol) => {
850
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureActiveAssetSubscription).call(this, symbol);
851
- });
852
- }
853
- // Re-establish BBO subscriptions if there are order book subscribers
854
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").size > 0) {
855
- // Clear existing subscriptions (they're dead after reconnection)
856
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").clear();
857
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").clear();
858
- // Re-establish subscriptions for all symbols with order book subscribers
859
- const symbolsNeedingOrderBook = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").keys());
860
- symbolsNeedingOrderBook.forEach((symbol) => {
861
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureBboSubscription).call(this, symbol);
862
- });
863
- }
864
- // Re-establish assetCtxs subscriptions if there are market data subscribers
865
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0) {
866
- // Clear existing subscriptions (they're dead after reconnection)
867
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").clear();
868
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").clear();
869
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").clear();
870
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").clear();
871
- // Re-establish subscriptions for all DEXs with market data subscribers
872
- const dexsNeeded = new Set();
873
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").forEach((_subscribers, symbol) => {
874
- const { dex } = (0, hyperLiquidAdapter_js_1.parseAssetName)(symbol);
875
- if (dex) {
876
- dexsNeeded.add(dex);
877
- }
878
- });
879
- // Add main DEX if any main DEX symbols have subscribers
880
- const hasMainDexSubscribers = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").keys()).some((symbol) => {
881
- const { dex } = (0, hyperLiquidAdapter_js_1.parseAssetName)(symbol);
882
- return !dex;
883
- });
884
- if (hasMainDexSubscribers) {
885
- dexsNeeded.add('');
886
- }
887
- const marketDataRestoreOperations = Array.from(dexsNeeded).flatMap((dex) => {
888
- const operations = [
889
- {
890
- dex,
891
- kind: 'assetCtxs',
892
- promise: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dex, {
893
- incrementRefCount: false,
894
- }),
895
- },
896
- ];
897
- if (dex) {
898
- operations.push({
899
- dex,
900
- kind: 'allMids',
901
- promise: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription).call(this, dex),
902
- });
903
- }
904
- return operations;
905
- });
906
- const marketDataRestoreResults = await Promise.allSettled(marketDataRestoreOperations.map(({ promise }) => promise));
907
- const marketDataRestoreFailures = marketDataRestoreResults.flatMap((result, index) => {
908
- if (result.status === 'fulfilled') {
909
- return [];
910
- }
911
- const operation = marketDataRestoreOperations[index];
912
- return [
913
- {
914
- ...operation,
915
- error: (0, errorUtils_js_1.ensureError)(result.reason, 'HyperLiquidSubscriptionService.restoreSubscriptions'),
916
- },
917
- ];
918
- });
919
- if (marketDataRestoreFailures.length > 0) {
920
- marketDataRestoreFailures.forEach(({ dex, kind }) => {
921
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_scheduleRestoreRetry).call(this, dex, kind);
922
- });
923
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, new Error(`Failed to restore ${marketDataRestoreFailures.length} market data subscriptions`), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'restoreSubscriptions.marketData', {
924
- failures: marketDataRestoreFailures.map(({ dex, kind, error }) => `${kind}:${dex || 'main'}:${error.message}`),
925
- }));
926
- }
927
- }
928
- }
929
- /**
930
- * Clear all subscriptions and cached data (multi-DEX support)
931
- */
932
- clearAll() {
933
- // Suppress error logging for pending unsubscribe requests during intentional disconnect.
934
- // The WebSocket will be closed after this, causing pending unsubscribe promises to reject
935
- // with WebSocketRequestError - these are expected and should not be logged to Sentry.
936
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_isClearing, true, "f");
937
- // Clear all local subscriber collections
938
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").clear();
939
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").clear();
940
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").clear();
941
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").clear();
942
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").clear();
943
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").clear();
944
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").clear();
945
- // Clear order fill subscriptions
946
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").forEach((subscription) => {
947
- subscription.unsubscribe().catch(() => {
948
- // Ignore errors during cleanup
949
- });
950
- });
951
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").clear();
952
- // Clear spotState subscriptions. Bump generation + drop in-flight
953
- // promises so any racing #ensureSpotStateSubscription continuation
954
- // unsubscribes its fresh sub instead of rehydrating the cleared map.
955
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, "f") + 1, "f");
956
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, "f").clear();
957
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").forEach((subscription) => {
958
- subscription.unsubscribe().catch(() => {
959
- // Ignore errors during cleanup
960
- });
961
- });
962
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").clear();
963
- // Clear cached data
964
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, null, "f");
965
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allMidsSnapshots, "f").clear();
966
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, null, "f");
967
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, null, "f");
968
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, null, "f");
969
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, null, "f");
970
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, false, "f"); // Reset cache initialization flag
971
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, false, "f"); // Reset cache initialization flag
972
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, false, "f"); // Reset fills cache initialization flag
973
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").clear();
974
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").clear();
975
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").clear();
976
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").clear();
977
- // Clear hash caches
978
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, '', "f");
979
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, '', "f");
980
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, '', "f");
981
- // Clear multi-DEX caches
982
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquidSubscriptionService: Clearing per-DEX caches', {
983
- dexPositionsCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").size,
984
- dexOrdersCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").size,
985
- dexAccountCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size,
986
- dexAssetCtxsCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").size,
987
- dexPositionsCacheKeys: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").keys()),
988
- dexAssetCtxsCacheKeys: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").keys()),
989
- });
990
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").clear();
991
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").clear();
992
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").clear();
993
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotState, null, "f");
994
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, null, "f");
995
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").clear();
996
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser, "f").clear();
997
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").clear();
998
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f") + 1, "f");
999
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromise, undefined, "f");
1000
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, undefined, "f");
1001
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").clear();
1002
- // Unsubscribe all active subscriptions before clearing references.
1003
- // Without this, orphaned subscriptions try to send unsubscribe frames
1004
- // on the closing WebSocket, causing SOCKET_NOT_CONNECTED errors.
1005
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, "f")) {
1006
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, "f").unsubscribe().catch((error) => {
1007
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.globalAllMids'));
1008
- });
1009
- }
1010
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, undefined, "f");
1011
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, undefined, "f");
1012
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, "f")) {
1013
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, "f")
1014
- .unsubscribe()
1015
- .catch((error) => {
1016
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.globalFastAssetCtxs'));
1017
- });
1018
- }
1019
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, undefined, "f");
1020
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, undefined, "f");
1021
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fastAssetCtxsCoins, "f").clear();
1022
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").forEach((sub, symbol) => {
1023
- sub.unsubscribe().catch((error) => {
1024
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.activeAsset', { symbol }));
1025
- });
1026
- });
1027
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").clear();
1028
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").clear();
1029
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").forEach((sub, symbol) => {
1030
- sub.unsubscribe().catch((error) => {
1031
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.bbo', { symbol }));
1032
- });
1033
- });
1034
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").clear();
1035
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").clear();
1036
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").forEach((sub, dexName) => {
1037
- sub.unsubscribe().catch((error) => {
1038
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.webData3', { dex: dexName }));
1039
- });
1040
- });
1041
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
1042
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
1043
- // HIP-3: Clear assetCtxs subscriptions
1044
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").forEach((sub, dexName) => {
1045
- sub.unsubscribe().catch((error) => {
1046
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.assetCtxs', { dex: dexName }));
1047
- });
1048
- });
1049
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").clear();
1050
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").clear();
1051
- // HIP-3: Clear per-DEX allMids subscriptions
1052
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").forEach((sub, dexName) => {
1053
- sub.unsubscribe().catch((error) => {
1054
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.dexAllMids', { dex: dexName }));
1055
- });
1056
- });
1057
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").clear();
1058
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").clear();
1059
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_restoreRetryTimeouts, "f").forEach((timeoutId) => {
1060
- clearTimeout(timeoutId);
1061
- });
1062
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_restoreRetryTimeouts, "f").clear();
1063
- // Cleanup individual subscriptions (clearinghouseState + openOrders)
1064
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").size > 0) {
1065
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").forEach((subscription, dexName) => {
1066
- subscription.unsubscribe().catch((error) => {
1067
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.clearinghouseState', {
1068
- dex: dexName,
1069
- }));
1070
- });
1071
- });
1072
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
1073
- }
1074
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").size > 0) {
1075
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").forEach((subscription, dexName) => {
1076
- subscription.unsubscribe().catch((error) => {
1077
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.openOrders', {
1078
- dex: dexName,
1079
- }));
1080
- });
1081
- });
1082
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
1083
- }
1084
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquid: Subscription service cleared (multi-DEX with individual subscriptions)', {
1085
- timestamp: new Date().toISOString(),
1086
- });
1087
- }
1088
- }
1089
- exports.HyperLiquidSubscriptionService = HyperLiquidSubscriptionService;
1090
- _a = HyperLiquidSubscriptionService, _HyperLiquidSubscriptionService_clientService = new WeakMap(), _HyperLiquidSubscriptionService_walletService = new WeakMap(), _HyperLiquidSubscriptionService_hip3Enabled = new WeakMap(), _HyperLiquidSubscriptionService_enabledDexs = new WeakMap(), _HyperLiquidSubscriptionService_allowlistMarkets = new WeakMap(), _HyperLiquidSubscriptionService_blocklistMarkets = new WeakMap(), _HyperLiquidSubscriptionService_priceDeviationLimit = new WeakMap(), _HyperLiquidSubscriptionService_discoverEnabledDexs = new WeakMap(), _HyperLiquidSubscriptionService_discoveredDexNames = new WeakMap(), _HyperLiquidSubscriptionService_dexDiscoveryPromise = new WeakMap(), _HyperLiquidSubscriptionService_dexDiscoveryResolver = new WeakMap(), _HyperLiquidSubscriptionService_expectedDexs = new WeakMap(), _HyperLiquidSubscriptionService_initializedDexs = new WeakMap(), _HyperLiquidSubscriptionService_priceSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_positionSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderFillSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_accountSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_marketDataSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderBookSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_globalAllMidsSubscription = new WeakMap(), _HyperLiquidSubscriptionService_globalAllMidsPromise = new WeakMap(), _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription = new WeakMap(), _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise = new WeakMap(), _HyperLiquidSubscriptionService_fastAssetCtxsCoins = new WeakMap(), _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingActiveAssetPromises = new WeakMap(), _HyperLiquidSubscriptionService_globalBboSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingBboPromises = new WeakMap(), _HyperLiquidSubscriptionService_orderFillSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_spotStateSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_spotStateSubscriptionPromises = new WeakMap(), _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration = new WeakMap(), _HyperLiquidSubscriptionService_symbolSubscriberCounts = new WeakMap(), _HyperLiquidSubscriptionService_dexSubscriberCounts = new WeakMap(), _HyperLiquidSubscriptionService_webData3Subscriptions = new WeakMap(), _HyperLiquidSubscriptionService_webData3SubscriptionPromise = new WeakMap(), _HyperLiquidSubscriptionService_positionSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_orderSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_accountSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_oiCapSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_dexPositionsCache = new WeakMap(), _HyperLiquidSubscriptionService_dexOrdersCache = new WeakMap(), _HyperLiquidSubscriptionService_dexAccountCache = new WeakMap(), _HyperLiquidSubscriptionService_cachedSpotState = new WeakMap(), _HyperLiquidSubscriptionService_abstractionModeByUser = new WeakMap(), _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser = new WeakMap(), _HyperLiquidSubscriptionService_abstractionModeInflightByUser = new WeakMap(), _HyperLiquidSubscriptionService_cachedSpotStateUserAddress = new WeakMap(), _HyperLiquidSubscriptionService_spotStatePromise = new WeakMap(), _HyperLiquidSubscriptionService_spotStatePromiseUserAddress = new WeakMap(), _HyperLiquidSubscriptionService_spotStateGeneration = new WeakMap(), _HyperLiquidSubscriptionService_cachedPositions = new WeakMap(), _HyperLiquidSubscriptionService_cachedOrders = new WeakMap(), _HyperLiquidSubscriptionService_cachedAccount = new WeakMap(), _HyperLiquidSubscriptionService_ordersCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_positionsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_oiCapSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_cachedOICaps = new WeakMap(), _HyperLiquidSubscriptionService_cachedOICapsHash = new WeakMap(), _HyperLiquidSubscriptionService_oiCapsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_cachedPriceData = new WeakMap(), _HyperLiquidSubscriptionService_allMidsSnapshots = new WeakMap(), _HyperLiquidSubscriptionService_cachedFills = new WeakMap(), _HyperLiquidSubscriptionService_fillsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_assetCtxsSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_dexAssetCtxsCache = new WeakMap(), _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises = new WeakMap(), _HyperLiquidSubscriptionService_dexAllMidsSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises = new WeakMap(), _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_openOrdersSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_dexMetaCache = new WeakMap(), _HyperLiquidSubscriptionService_orderBookCache = new WeakMap(), _HyperLiquidSubscriptionService_marketDataCache = new WeakMap(), _HyperLiquidSubscriptionService_isClearing = new WeakMap(), _HyperLiquidSubscriptionService_restoreRetryTimeouts = new WeakMap(), _HyperLiquidSubscriptionService_deps = new WeakMap(), _HyperLiquidSubscriptionService_cachedPositionsHash = new WeakMap(), _HyperLiquidSubscriptionService_cachedOrdersHash = new WeakMap(), _HyperLiquidSubscriptionService_cachedAccountHash = new WeakMap(), _HyperLiquidSubscriptionService_instances = new WeakSet(), _HyperLiquidSubscriptionService_logErrorUnlessClearing = function _HyperLiquidSubscriptionService_logErrorUnlessClearing(error, context) {
1091
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_isClearing, "f")) {
1092
- return;
1093
- }
1094
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isTransientSdkError).call(this, error)) {
1095
- // Expected SDK lifecycle: reconnect churn, intentional terminations, or
1096
- // request-side aborts. Forwarding these to Sentry pollutes the error
1097
- // budget with handled events the SDK already recovers from. Keep them
1098
- // visible locally via debugLogger for diagnosis.
1099
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`[Perps transient SDK error] ${context?.context?.data?.method ?? 'unknown'}: ${error.message}`);
1100
- return;
1101
- }
1102
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").logger.error(error, context);
1103
- }, _HyperLiquidSubscriptionService_isTransientSdkError = function _HyperLiquidSubscriptionService_isTransientSdkError(error) {
1104
- const ensuredError = (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.isTransientSdkError');
1105
- const connectionState = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getConnectionState?.();
1106
- const messageParts = [
1107
- ensuredError.message,
1108
- error instanceof Error ? error.name : '',
1109
- typeof error === 'string' ? error : '',
1110
- String(error),
1111
- ]
1112
- .join(' ')
1113
- .toLowerCase();
1114
- const isReconnectChurn = connectionState === index_js_1.WebSocketConnectionState.Connecting ||
1115
- connectionState === index_js_1.WebSocketConnectionState.Disconnected;
1116
- return (messageParts.includes('websocketrequesterror') ||
1117
- messageParts.includes('unknown error while making a websocket request') ||
1118
- messageParts.includes('reconnectingwebsocketerror') ||
1119
- (messageParts.includes('timeouterror') &&
1120
- messageParts.includes('signal timed out')) ||
1121
- (isReconnectChurn &&
1122
- (messageParts.includes('unknown error (no details provided)') ||
1123
- messageParts.includes('undefined'))));
1124
- }, _HyperLiquidSubscriptionService_scheduleRestoreRetry = function _HyperLiquidSubscriptionService_scheduleRestoreRetry(dex, kind) {
1125
- const retryKey = `${kind}:${dex}`;
1126
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_isClearing, "f") || __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_restoreRetryTimeouts, "f").has(retryKey)) {
1127
- return;
1128
- }
1129
- const timeoutId = setTimeout(() => {
1130
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_restoreRetryTimeouts, "f").delete(retryKey);
1131
- const retryPromise = kind === 'assetCtxs'
1132
- ? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dex, {
1133
- incrementRefCount: false,
1134
- })
1135
- : __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription).call(this, dex);
1136
- retryPromise.catch((error) => {
1137
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.restoreSubscriptions.retry'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'restoreSubscriptions.retry', {
1138
- dex,
1139
- kind,
1140
- }));
1141
- });
1142
- }, 1000);
1143
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_restoreRetryTimeouts, "f").set(retryKey, timeoutId);
1144
- }, _HyperLiquidSubscriptionService_getErrorContext = function _HyperLiquidSubscriptionService_getErrorContext(method, extra) {
1145
- return {
1146
- tags: {
1147
- feature: perpsConfig_js_1.PERPS_CONSTANTS.FeatureName,
1148
- provider: 'hyperliquid',
1149
- network: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").isTestnetMode() ? 'testnet' : 'mainnet',
1150
- },
1151
- context: {
1152
- name: 'HyperLiquidSubscriptionService',
1153
- data: {
1154
- method,
1155
- ...extra,
1156
- },
1157
- },
1158
- };
1159
- }, _HyperLiquidSubscriptionService_isDexEnabled = function _HyperLiquidSubscriptionService_isDexEnabled(dex) {
1160
- if (dex === null) {
1161
- return true; // Main DEX always enabled
1162
- }
1163
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")) {
1164
- return false; // HIP-3 disabled entirely
1165
- }
1166
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").includes(dex);
1167
- }, _HyperLiquidSubscriptionService_waitForDexDiscovery =
1168
- /**
1169
- * Wait for DEX discovery to complete (with timeout)
1170
- * Used when HIP-3 is enabled but enabledDexs hasn't been populated yet.
1171
- * This allows subscriptions to wait for DEX discovery before creating per-DEX subscriptions.
1172
- *
1173
- * @param timeoutMs - The maximum time in milliseconds to wait for DEX discovery.
1174
- */
1175
- async function _HyperLiquidSubscriptionService_waitForDexDiscovery(timeoutMs = 5000) {
1176
- // Already have DEXs, no need to wait
1177
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").length > 0) {
1178
- return;
1179
- }
1180
- // Create promise if not exists
1181
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, "f")) {
1182
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, new Promise((resolve) => {
1183
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, resolve, "f");
1184
- }), "f");
1185
- }
1186
- const discovery = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_discoverEnabledDexs, "f")
1187
- ? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_discoverEnabledDexs, "f").call(this)
1188
- .then((enabledDexs) => {
1189
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_enabledDexs, enabledDexs, "f");
1190
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoveredDexNames, enabledDexs, "f");
1191
- return undefined;
1192
- })
1193
- .catch(() => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, "f") ?? Promise.resolve())
1194
- : __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, "f");
1195
- // Wait with timeout
1196
- let timeoutId;
1197
- const timeoutPromise = new Promise((_resolve, reject) => {
1198
- timeoutId = setTimeout(() => reject(new Error('DEX discovery timeout')), timeoutMs);
1199
- });
1200
- try {
1201
- await Promise.race([discovery, timeoutPromise]);
1202
- }
1203
- catch {
1204
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('DEX discovery wait timed out, proceeding with main DEX only');
1205
- }
1206
- finally {
1207
- if (timeoutId) {
1208
- clearTimeout(timeoutId);
1209
- }
1210
- }
1211
- }, _HyperLiquidSubscriptionService_hashPositions = function _HyperLiquidSubscriptionService_hashPositions(positions) {
1212
- if (!positions || positions.length === 0) {
1213
- return '0';
1214
- }
1215
- return positions
1216
- .map((pos) => `${pos.symbol}:${pos.size}:${pos.entryPrice}:${pos.leverage.value}:${pos.takeProfitPrice ?? ''}:${pos.stopLossPrice ?? ''}:${pos.takeProfitCount}:${pos.stopLossCount}:${pos.unrealizedPnl}:${pos.returnOnEquity}:${pos.liquidationPrice ?? ''}:${pos.marginUsed || ''}:${
1217
- // Trigger arrays are part of the emitted shape, so a standalone or
1218
- // partial trigger appearing/disappearing has to change the hash —
1219
- // otherwise subscribers never receive the updated arrays.
1220
- (0, orderTypes_js_1.hashTriggerOrders)(pos.takeProfitOrders)}:${(0, orderTypes_js_1.hashTriggerOrders)(pos.stopLossOrders)}`)
1221
- .join('|');
1222
- }, _HyperLiquidSubscriptionService_hashOrders = function _HyperLiquidSubscriptionService_hashOrders(orders) {
1223
- if (!orders || orders.length === 0) {
1224
- return '0';
1225
- }
1226
- return orders
1227
- .map((ord) => `${ord.symbol}:${ord.side}:${ord.size}:${ord.price}:${ord.orderType}`)
1228
- .join('|');
1229
- }, _HyperLiquidSubscriptionService_hashAccountState = function _HyperLiquidSubscriptionService_hashAccountState(account) {
1230
- return `${account.spendableBalance}:${account.withdrawableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}`;
1231
- }, _HyperLiquidSubscriptionService_extractTPSLFromOrders = function _HyperLiquidSubscriptionService_extractTPSLFromOrders(orders, positions, cachedProcessedOrders) {
1232
- const tpslMap = new Map();
1233
- const tpslCountMap = new Map();
1234
- // Complete per-symbol trigger order view, including quantity-scoped (partial)
1235
- // TP/SL orders that the scalar tpslMap prices cannot represent.
1236
- const triggerOrderMap = new Map();
1237
- const addTriggerOrder = (symbol, triggerOrder) => {
1238
- if (!triggerOrder) {
1239
- return;
1240
- }
1241
- const existing = triggerOrderMap.get(symbol) ?? {
1242
- takeProfitOrders: [],
1243
- stopLossOrders: [],
1244
- };
1245
- if (triggerOrder.direction === 'take_profit') {
1246
- existing.takeProfitOrders.push(triggerOrder);
1247
- }
1248
- else {
1249
- existing.stopLossOrders.push(triggerOrder);
1250
- }
1251
- triggerOrderMap.set(symbol, existing);
1252
- };
1253
- // If cached processed orders provided, extract TP/SL from them directly
1254
- if (cachedProcessedOrders) {
1255
- // Hoisted out of the per-order loop: this runs on every order-update tick.
1256
- const positionsBySymbol = new Map(positions.map((position) => [position.symbol, position]));
1257
- cachedProcessedOrders.forEach((order) => {
1258
- // Use triggerPrice for TP/SL (trigger condition price), falling back to price
1259
- // This ensures consistency with raw SDK order processing which uses triggerPx
1260
- const tpslPrice = order.triggerPrice ?? order.price;
1261
- // Collected before the position-bound filter below: partial TP/SL orders
1262
- // are standalone (not position-bound) and still belong to this view.
1263
- // A trigger that is another order's child does not — same rule as the
1264
- // REST path in HyperLiquidProvider.getPositions.
1265
- if (order.isTrigger && order.reduceOnly && !order.parentOrderId) {
1266
- addTriggerOrder(order.symbol, (0, orderTypes_js_1.buildPositionTriggerOrderFromOrder)({
1267
- order,
1268
- positionSize: positionsBySymbol.get(order.symbol)?.size ?? '0',
1269
- entryPrice: positionsBySymbol.get(order.symbol)?.entryPrice,
1270
- }));
1271
- }
1272
- if (order.isTrigger && tpslPrice) {
1273
- // When UsePositionBoundTpsl is enabled, only position-bound TP/SL orders
1274
- // should be shown on positions — skip normalTpsl children of limit orders
1275
- if (perpsConfig_js_1.TP_SL_CONFIG.UsePositionBoundTpsl &&
1276
- order.isPositionTpsl !== true) {
1277
- return;
1278
- }
1279
- const isTakeProfit = order.detailedOrderType?.includes('Take Profit');
1280
- const isStop = order.detailedOrderType?.includes('Stop');
1281
- const matchingPosition = positions.find((pos) => pos.symbol === order.symbol);
1282
- // Determine TP vs SL classification for count and price updates
1283
- // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
1284
- let classifiedAsTakeProfit = isTakeProfit;
1285
- let classifiedAsStop = isStop;
1286
- if (!isTakeProfit && !isStop && matchingPosition) {
1287
- // Fallback: determine based on trigger price vs entry price
1288
- // This handles orders with ambiguous type 'Trigger'
1289
- const triggerPrice = parseFloat(tpslPrice);
1290
- const entryPrice = parseFloat(matchingPosition.entryPrice || '0');
1291
- const isLong = parseFloat(matchingPosition.size) > 0;
1292
- if (isLong) {
1293
- if (triggerPrice > entryPrice) {
1294
- classifiedAsTakeProfit = true;
1295
- }
1296
- else {
1297
- classifiedAsStop = true;
1298
- }
1299
- }
1300
- else if (triggerPrice < entryPrice) {
1301
- classifiedAsTakeProfit = true;
1302
- }
1303
- else {
1304
- classifiedAsStop = true;
1305
- }
1306
- }
1307
- const currentTakeProfitCount = tpslCountMap.get(order.symbol)?.takeProfitCount ?? 0;
1308
- const currentStopLossCount = tpslCountMap.get(order.symbol)?.stopLossCount ?? 0;
1309
- tpslCountMap.set(order.symbol, {
1310
- takeProfitCount: classifiedAsTakeProfit
1311
- ? currentTakeProfitCount + 1
1312
- : currentTakeProfitCount,
1313
- stopLossCount: classifiedAsStop
1314
- ? currentStopLossCount + 1
1315
- : currentStopLossCount,
1316
- });
1317
- if (matchingPosition) {
1318
- const existing = tpslMap.get(order.symbol) ?? {};
1319
- if (classifiedAsTakeProfit) {
1320
- existing.takeProfitPrice = tpslPrice;
1321
- }
1322
- else if (classifiedAsStop) {
1323
- existing.stopLossPrice = tpslPrice;
1324
- }
1325
- tpslMap.set(order.symbol, existing);
1326
- }
1327
- }
1328
- });
1329
- return {
1330
- tpslMap,
1331
- tpslCountMap,
1332
- triggerOrderMap,
1333
- processedOrders: cachedProcessedOrders,
1334
- };
1335
- }
1336
- // Process raw SDK orders
1337
- const processedOrders = [];
1338
- // TP/SL children of a pending parent order are listed both nested under the
1339
- // parent and as top-level entries. Map each child back to its parent so the
1340
- // converted order carries the link and the position trigger view can exclude
1341
- // them: they protect that order, not a position.
1342
- const parentIdByChildId = new Map();
1343
- orders.forEach((order) => {
1344
- order.children?.forEach((child) => {
1345
- parentIdByChildId.set(child.oid, order.oid);
1346
- });
1347
- });
1348
- orders.forEach((order) => {
1349
- let position;
1350
- let positionForCoin;
1351
- const matchPositionToTpsl = (pos) => {
1352
- if (perpsConfig_js_1.TP_SL_CONFIG.UsePositionBoundTpsl) {
1353
- return (pos.symbol === order.coin &&
1354
- order.reduceOnly &&
1355
- order.isPositionTpsl);
1356
- }
1357
- return (pos.symbol === order.coin &&
1358
- Math.abs(parseFloat(order.sz)) >= Math.abs(parseFloat(pos.size)));
1359
- };
1360
- const matchPositionToCoin = (pos) => pos.symbol === order.coin;
1361
- // Process trigger orders for TP/SL extraction
1362
- if (order.triggerPx) {
1363
- const isTakeProfit = order.orderType?.includes('Take Profit');
1364
- const isStop = order.orderType?.includes('Stop');
1365
- const { coin } = order;
1366
- position = positions.find(matchPositionToTpsl);
1367
- positionForCoin = positions.find(matchPositionToCoin);
1368
- // Determine TP vs SL classification for count and price updates
1369
- // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
1370
- // This matches the cached order processing logic for consistency
1371
- let classifiedAsTakeProfit = isTakeProfit;
1372
- let classifiedAsStop = isStop;
1373
- if (!isTakeProfit && !isStop && position) {
1374
- // Fallback: determine based on trigger price vs entry price
1375
- // This handles orders with ambiguous type 'Trigger'
1376
- const triggerPrice = parseFloat(order.triggerPx);
1377
- const entryPrice = parseFloat(position.entryPrice || '0');
1378
- const isLong = parseFloat(position.size) > 0;
1379
- if (isLong) {
1380
- if (triggerPrice > entryPrice) {
1381
- classifiedAsTakeProfit = true;
1382
- }
1383
- else {
1384
- classifiedAsStop = true;
1385
- }
1386
- }
1387
- else if (triggerPrice < entryPrice) {
1388
- classifiedAsTakeProfit = true;
1389
- }
1390
- else {
1391
- classifiedAsStop = true;
1392
- }
1393
- }
1394
- const currentTakeProfitCount = tpslCountMap.get(coin)?.takeProfitCount ?? 0;
1395
- const currentStopLossCount = tpslCountMap.get(coin)?.stopLossCount ?? 0;
1396
- tpslCountMap.set(coin, {
1397
- takeProfitCount: classifiedAsTakeProfit
1398
- ? currentTakeProfitCount + 1
1399
- : currentTakeProfitCount,
1400
- stopLossCount: classifiedAsStop
1401
- ? currentStopLossCount + 1
1402
- : currentStopLossCount,
1403
- });
1404
- if (position) {
1405
- const existing = tpslMap.get(coin) ?? {};
1406
- // Use classified values for price assignment (consistent with count logic)
1407
- if (classifiedAsTakeProfit) {
1408
- existing.takeProfitPrice = order.triggerPx;
1409
- }
1410
- else if (classifiedAsStop) {
1411
- existing.stopLossPrice = order.triggerPx;
1412
- }
1413
- tpslMap.set(coin, existing);
1414
- }
1415
- }
1416
- // Convert ALL open orders to Order format
1417
- const convertedOrder = (0, hyperLiquidAdapter_js_1.adaptOrderFromSDK)(order, position ?? positionForCoin);
1418
- const parentOrderId = parentIdByChildId.get(order.oid);
1419
- if (parentOrderId !== undefined) {
1420
- convertedOrder.parentOrderId = parentOrderId.toString();
1421
- }
1422
- processedOrders.push(convertedOrder);
1423
- if (convertedOrder.isTrigger &&
1424
- convertedOrder.reduceOnly &&
1425
- !convertedOrder.parentOrderId) {
1426
- addTriggerOrder(convertedOrder.symbol, (0, orderTypes_js_1.buildPositionTriggerOrderFromOrder)({
1427
- order: convertedOrder,
1428
- positionSize: (position ?? positionForCoin)?.size ?? '0',
1429
- entryPrice: (position ?? positionForCoin)?.entryPrice,
1430
- }));
1431
- }
1432
- });
1433
- return { tpslMap, tpslCountMap, triggerOrderMap, processedOrders };
1434
- }, _HyperLiquidSubscriptionService_mergeTPSLIntoPositions = function _HyperLiquidSubscriptionService_mergeTPSLIntoPositions(positions, tpslMap, tpslCountMap, triggerOrderMap) {
1435
- return positions.map((position) => {
1436
- const tpsl = tpslMap.get(position.symbol) ?? {};
1437
- const tpslCount = tpslCountMap.get(position.symbol) ?? {};
1438
- const triggerOrders = triggerOrderMap?.get(position.symbol);
1439
- const takeProfitOrders = triggerOrders?.takeProfitOrders ?? [];
1440
- const stopLossOrders = triggerOrders?.stopLossOrders ?? [];
1441
- return {
1442
- ...position,
1443
- // The scanned prices only ever come from position-bound triggers, so a
1444
- // lone quantity-scoped trigger has to be read off the array instead.
1445
- takeProfitPrice: (0, orderTypes_js_1.resolvePositionTriggerSummaryPrice)({
1446
- triggerOrders: takeProfitOrders,
1447
- scannedPrice: tpsl.takeProfitPrice,
1448
- }),
1449
- stopLossPrice: (0, orderTypes_js_1.resolvePositionTriggerSummaryPrice)({
1450
- triggerOrders: stopLossOrders,
1451
- scannedPrice: tpsl.stopLossPrice,
1452
- }),
1453
- // Counts come from the same arrays as the REST path, so both transports
1454
- // report one definition. Orders whose placement type the exchange did
1455
- // not name (HyperLiquid's ambiguous 'Trigger') are absent from both,
1456
- // where the legacy count included them.
1457
- // Keyed on the map, not on this symbol's entry: a symbol with no
1458
- // entry has no triggers, and falling back to the legacy count there
1459
- // would report a count beside an empty array.
1460
- takeProfitCount: triggerOrderMap
1461
- ? takeProfitOrders.length
1462
- : (tpslCount.takeProfitCount ?? 0),
1463
- stopLossCount: triggerOrderMap
1464
- ? stopLossOrders.length
1465
- : (tpslCount.stopLossCount ?? 0),
1466
- takeProfitOrders,
1467
- stopLossOrders,
1468
- };
1469
- });
1470
- }, _HyperLiquidSubscriptionService_aggregateAccountStates = function _HyperLiquidSubscriptionService_aggregateAccountStates() {
1471
- const subAccountBreakdown = {};
1472
- let totalSpendableBalance = 0;
1473
- let totalWithdrawableBalance = 0;
1474
- let totalBalance = 0;
1475
- let totalMarginUsed = 0;
1476
- let totalUnrealizedPnl = 0;
1477
- // Collect account states for weighted ROE calculation
1478
- const accountStatesForROE = [];
1479
- // Aggregate all cached account states
1480
- Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").entries()).forEach(([currentDex, state]) => {
1481
- const dexKey = currentDex === '' ? 'main' : currentDex;
1482
- subAccountBreakdown[dexKey] = {
1483
- spendableBalance: state.spendableBalance,
1484
- withdrawableBalance: state.withdrawableBalance,
1485
- totalBalance: state.totalBalance,
1486
- };
1487
- totalSpendableBalance += parseFloat(state.spendableBalance);
1488
- totalWithdrawableBalance += parseFloat(state.withdrawableBalance);
1489
- totalBalance += parseFloat(state.totalBalance);
1490
- totalMarginUsed += parseFloat(state.marginUsed);
1491
- totalUnrealizedPnl += parseFloat(state.unrealizedPnl);
1492
- // Collect data for weighted ROE calculation
1493
- accountStatesForROE.push({
1494
- unrealizedPnl: state.unrealizedPnl,
1495
- returnOnEquity: state.returnOnEquity,
1496
- });
1497
- });
1498
- // Use first DEX's account state as base and override aggregated values
1499
- const firstDexAccount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").values().next().value ?? {};
1500
- // Calculate weighted returnOnEquity across all DEXs
1501
- const returnOnEquity = (0, accountUtils_js_1.calculateWeightedReturnOnEquity)(accountStatesForROE);
1502
- return (0, accountUtils_js_1.addSpotBalanceToAccountState)({
1503
- ...firstDexAccount,
1504
- spendableBalance: totalSpendableBalance.toString(),
1505
- withdrawableBalance: totalWithdrawableBalance.toString(),
1506
- totalBalance: totalBalance.toString(),
1507
- marginUsed: totalMarginUsed.toString(),
1508
- unrealizedPnl: totalUnrealizedPnl.toString(),
1509
- subAccountBreakdown,
1510
- returnOnEquity,
1511
- }, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotState, "f"), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getSpotBalanceOptions).call(this));
1512
- }, _HyperLiquidSubscriptionService_getAbstractionModeForUser = function _HyperLiquidSubscriptionService_getAbstractionModeForUser(userAddress) {
1513
- if (!userAddress) {
1514
- return null;
1515
- }
1516
- return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").get(userAddress.toLowerCase()) ?? null;
1517
- }, _HyperLiquidSubscriptionService_getSpotBalanceOptions = function _HyperLiquidSubscriptionService_getSpotBalanceOptions() {
1518
- return {
1519
- foldIntoCollateral: (0, hyperliquid_types_js_1.hyperLiquidModeFoldsSpot)(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getAbstractionModeForUser).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, "f"))),
1520
- };
1521
- }, _HyperLiquidSubscriptionService_refreshAbstractionModeThrottled =
1522
- /**
1523
- * Fetch userAbstraction and update the cache, throttled so the long-lived
1524
- * spotState WebSocket can trigger a background refresh on every tick
1525
- * without burning REST quota. Handles HL-web mode flips propagating back
1526
- * to mobile without requiring a restart or account switch.
1527
- *
1528
- * Concurrent callers share the same in-flight promise so an in-flight
1529
- * fetch (especially a slow-failing one) doesn't ratchet the throttle
1530
- * forward on every WS tick and leave mode stale during a network hang.
1531
- *
1532
- * @param userAddress - Current user address to refresh the cache for.
1533
- * @returns Promise that resolves once the refresh completes (or immediately when throttled).
1534
- */
1535
- async function _HyperLiquidSubscriptionService_refreshAbstractionModeThrottled(userAddress) {
1536
- const normalizedUser = userAddress.toLowerCase();
1537
- const existing = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").get(normalizedUser);
1538
- if (existing) {
1539
- await existing;
1540
- return undefined;
1541
- }
1542
- const now = Date.now();
1543
- const lastWsRefreshAt = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser, "f").get(normalizedUser) ?? 0;
1544
- if (now - lastWsRefreshAt < perpsConfig_js_1.ABSTRACTION_MODE_REFRESH_THROTTLE_MS) {
1545
- return undefined;
1546
- }
1547
- const inflight = (async () => {
1548
- try {
1549
- const infoClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getInfoClient();
1550
- const mode = await infoClient.userAbstraction({ user: userAddress });
1551
- const previousMode = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").get(normalizedUser) ?? null;
1552
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").set(normalizedUser, mode);
1553
- // Set timestamp only on success; a hanging/failed fetch must not
1554
- // ratchet the throttle window forward (which would silence every
1555
- // subsequent spot WS tick for the full throttle duration).
1556
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser, "f").set(normalizedUser, Date.now());
1557
- // If the fold semantics actually changed for this user, trigger a
1558
- // re-aggregation so balance-dependent UI (withdraw cap, order-entry
1559
- // validation) picks up the new mode immediately — otherwise a
1560
- // Unified→Standard flip can stay folded with old semantics until the
1561
- // next spot/account event happens to arrive.
1562
- const foldChanged = (0, hyperliquid_types_js_1.hyperLiquidModeFoldsSpot)(previousMode) !==
1563
- (0, hyperliquid_types_js_1.hyperLiquidModeFoldsSpot)(mode);
1564
- if (foldChanged && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size > 0) {
1565
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1566
- }
1567
- }
1568
- catch (error) {
1569
- // Non-fatal — preserve the last known mode for this user. Leave
1570
- // timestamp at its previous value so a genuine retry on the next
1571
- // WS tick is allowed (no forward ratchet on slow failures). Route
1572
- // through the shared Sentry helper so repeated failures become
1573
- // visible on the perps ops dashboard (consistent with other async
1574
- // boundary errors in this file, e.g. #refreshSpotState).
1575
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.refreshAbstractionModeThrottled'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'refreshAbstractionModeThrottled', {
1576
- user: normalizedUser,
1577
- }));
1578
- }
1579
- })();
1580
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").set(normalizedUser, inflight);
1581
- try {
1582
- await inflight;
1583
- }
1584
- finally {
1585
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").get(normalizedUser) === inflight) {
1586
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").delete(normalizedUser);
1587
- }
1588
- }
1589
- return undefined;
1590
- }, _HyperLiquidSubscriptionService_ensureSpotState = async function _HyperLiquidSubscriptionService_ensureSpotState(accountId) {
1591
- const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
1592
- const lowerUserAddress = userAddress.toLowerCase();
1593
- // Fast-path only when we have spot for this user AND a resolved
1594
- // abstraction mode. Without the mode, `#getSpotBalanceOptions` would
1595
- // fall back to fail-closed (no fold), under-reporting Unified /
1596
- // Portfolio Margin balances — force a refresh instead.
1597
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotState, "f") &&
1598
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, "f") === lowerUserAddress &&
1599
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").has(lowerUserAddress)) {
1600
- return;
1601
- }
1602
- // Share an in-flight fetch only if it targets the same user.
1603
- // A pending fetch for a different user is stale after an account switch —
1604
- // start a fresh fetch; the stale one will self-discard via generation check.
1605
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStatePromise, "f") &&
1606
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, "f") === userAddress) {
1607
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStatePromise, "f");
1608
- return;
1609
- }
1610
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f") + 1, "f");
1611
- const generation = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f");
1612
- const promise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_refreshSpotState).call(this, userAddress, generation);
1613
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromise, promise, "f");
1614
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, userAddress, "f");
1615
- try {
1616
- await promise;
1617
- }
1618
- finally {
1619
- // Only clear tracker if we're still the latest in-flight fetch.
1620
- // A newer fetch may have already replaced us.
1621
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStatePromise, "f") === promise) {
1622
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromise, undefined, "f");
1623
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, undefined, "f");
1624
- }
1625
- }
1626
- }, _HyperLiquidSubscriptionService_refreshSpotState = async function _HyperLiquidSubscriptionService_refreshSpotState(userAddress, generation) {
1627
- try {
1628
- // Cold-start safety: getInfoClient() throws until the SDK has been
1629
- // initialized via ensureSubscriptionClient. On a fresh service
1630
- // instance subscribeToAccount can race ahead of the webData3 path,
1631
- // so initialize here first — subsequent calls are no-ops.
1632
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1633
- // Don't bail here even if generation has bumped (e.g. WS spot snapshot
1634
- // arrived while we awaited the subscription client). We still need to
1635
- // resolve `userAbstraction` for this user — the mode is user-keyed,
1636
- // independent of the spot generation, and the post-fetch path below
1637
- // correctly handles the generation-changed case (seal + re-aggregate
1638
- // instead of overwriting WS spot).
1639
- const infoClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getInfoClient({ useHttp: true });
1640
- const lowerUserAddress = userAddress.toLowerCase();
1641
- // Fetch spot state + abstraction mode in parallel — mode decides
1642
- // whether the spot fold applies in addSpotBalanceToAccountState.
1643
- // Register the userAbstraction call in `#abstractionModeInflightByUser`
1644
- // so a concurrent WS-driven `#refreshAbstractionModeThrottled` awaits
1645
- // this fetch instead of duplicating the REST round-trip.
1646
- const abstractionFetch = infoClient.userAbstraction({
1647
- user: userAddress,
1648
- });
1649
- const trackedAbstraction = abstractionFetch.then(() => undefined, () => undefined);
1650
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").set(lowerUserAddress, trackedAbstraction);
1651
- const [spotResult, abstractionResult] = await Promise.allSettled([
1652
- infoClient.spotClearinghouseState({ user: userAddress }),
1653
- abstractionFetch,
1654
- ]);
1655
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").get(lowerUserAddress) ===
1656
- trackedAbstraction) {
1657
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").delete(lowerUserAddress);
1658
- }
1659
- // Record the abstraction mode regardless of generation. The mode is
1660
- // user-keyed (independent of the spot snapshot generation) so a WS
1661
- // push that bumped generation while we awaited cannot make this
1662
- // result wrong for this user. Discarding it would strand
1663
- // Unified / Portfolio Margin users at fail-closed until another
1664
- // subscribe runs — exactly the race the WS-vs-REST guard creates.
1665
- if (abstractionResult.status === 'fulfilled') {
1666
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").set(lowerUserAddress, abstractionResult.value);
1667
- }
1668
- else {
1669
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('User abstraction fetch failed during spot refresh; spot fold disabled until the mode resolves', {
1670
- error: (0, errorUtils_js_1.ensureError)(abstractionResult.reason, 'HyperLiquidSubscriptionService.refreshSpotState.abstraction').message,
1671
- });
1672
- }
1673
- if (generation !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f")) {
1674
- // A WS push superseded our spot snapshot. The earlier WS-driven
1675
- // aggregation ran with a null mode (fail-closed), so subscribers
1676
- // may currently be under-reported. If we just resolved the mode
1677
- // for the user whose spot is cached (strict match — null cache
1678
- // owner could mean cleanUp ran for a different user), re-aggregate
1679
- // now so the active subscribers immediately see the correct fold.
1680
- if (abstractionResult.status === 'fulfilled' &&
1681
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotState, "f") &&
1682
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, "f") === lowerUserAddress) {
1683
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size > 0) {
1684
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1685
- }
1686
- }
1687
- return;
1688
- }
1689
- if (spotResult.status === 'rejected') {
1690
- throw spotResult.reason;
1691
- }
1692
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotState, spotResult.value, "f");
1693
- // Always record the spot owner so subsequent #ensureSpotState calls
1694
- // and recovery branches can identify whose data is cached. Fast-path
1695
- // eligibility is gated separately by #abstractionModeByUser.has(...);
1696
- // a transient abstraction failure leaves the user out of the map and
1697
- // the next #ensureSpotState retries both fetches.
1698
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, lowerUserAddress, "f");
1699
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size > 0) {
1700
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1701
- }
1702
- }
1703
- catch (error) {
1704
- if (generation !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f")) {
1705
- return;
1706
- }
1707
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.refreshSpotState'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'refreshSpotState'));
1708
- }
1709
- }, _HyperLiquidSubscriptionService_ensureSpotStateSubscription = async function _HyperLiquidSubscriptionService_ensureSpotStateSubscription(accountId) {
1710
- const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
1711
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").has(userAddress)) {
1712
- return;
1713
- }
1714
- const inFlight = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, "f").get(userAddress);
1715
- if (inFlight) {
1716
- await inFlight;
1717
- return;
1718
- }
1719
- const startGeneration = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, "f");
1720
- const promise = (async () => {
1721
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1722
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1723
- if (!subscriptionClient) {
1724
- throw new Error('SubscriptionClient not available');
1725
- }
1726
- const subscription = await subscriptionClient.spotState({ user: userAddress }, (event) => {
1727
- try {
1728
- if (event.user.toLowerCase() !== userAddress.toLowerCase()) {
1729
- return;
1730
- }
1731
- // Invalidate any in-flight REST refreshSpotState so it drops
1732
- // its result instead of overwriting this fresher WS snapshot.
1733
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f") + 1, "f");
1734
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotState, event.spotState, "f");
1735
- // Always record the spot owner so subsequent generation guards
1736
- // and recovery branches can identify whose data is cached.
1737
- // Fast-path eligibility is gated separately in #ensureSpotState
1738
- // by checking #abstractionModeByUser.has(...).
1739
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, userAddress.toLowerCase(), "f");
1740
- // Kick a throttled userAbstraction refresh so HL-web mode
1741
- // flips (Unified → Standard or vice versa) propagate back to
1742
- // mobile while the app stays open. Fire-and-forget: the
1743
- // refresh updates the per-user abstraction-mode cache and the next
1744
- // fold picks up the new value.
1745
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_refreshAbstractionModeThrottled).call(this, event.user.toLowerCase()).catch(() => {
1746
- // Errors are logged inside the throttled refresh helper.
1747
- });
1748
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size > 0) {
1749
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1750
- }
1751
- }
1752
- catch (error) {
1753
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureSpotStateSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'spotState callback error', {
1754
- user: userAddress,
1755
- }));
1756
- }
1757
- });
1758
- // Discard if cleanup ran while we were awaiting the subscription
1759
- // handshake; rehydrating #spotStateSubscriptions here would leave
1760
- // a stale entry that short-circuits future resubscribe attempts.
1761
- if (startGeneration !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, "f")) {
1762
- await subscription.unsubscribe().catch(() => undefined);
1763
- return;
1764
- }
1765
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").set(userAddress, subscription);
1766
- })();
1767
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, "f").set(userAddress, promise);
1768
- try {
1769
- await promise;
1770
- }
1771
- finally {
1772
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, "f").delete(userAddress);
1773
- }
1774
- }, _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription =
1775
- /**
1776
- * Ensure shared webData3 subscription is active (singleton pattern with multi-DEX support)
1777
- * webData3 provides data for all DEXs (main + HIP-3) in a single subscription
1778
- *
1779
- * @param accountId - Optional CAIP account ID to subscribe for.
1780
- */
1781
- async function _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription(accountId) {
1782
- // Establish webData3 subscription (if not exists)
1783
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").has('')) {
1784
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f")) {
1785
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f");
1786
- }
1787
- else {
1788
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createUserDataSubscription).call(this, accountId), "f");
1789
- try {
1790
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f");
1791
- }
1792
- catch (error) {
1793
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
1794
- throw error;
1795
- }
1796
- }
1797
- }
1798
- // Note: webData3 includes all DEX data, so no separate HIP-3 subscriptions needed
1799
- }, _HyperLiquidSubscriptionService_createUserDataSubscription =
1800
- /**
1801
- * Create WebSocket subscription for user data (positions, orders, account).
1802
- *
1803
- * Positions, orders, and account/spot balance are always delivered via
1804
- * per-DEX `clearinghouseState` + `openOrders` subscriptions (sub-second
1805
- * updates). webData3 is used only for OI caps extraction (not
1806
- * latency-sensitive). The deprecated webData2 snapshot channel is no longer
1807
- * used (TAT-3332).
1808
- *
1809
- * - HIP-3 disabled: subscribe to the main DEX only (`dexsToSubscribe = ['']`).
1810
- * - HIP-3 enabled: subscribe to the main DEX plus each enabled HIP-3 DEX.
1811
- *
1812
- * webData3 provides perpDexStates[] array containing OI caps for all DEXs:
1813
- * - Index 0: Main DEX (dexName = '')
1814
- * - Index 1+: HIP-3 DEXs in order of enabledDexs array
1815
- *
1816
- * @param accountId - Optional CAIP account ID to subscribe for.
1817
- * @returns A promise that resolves when the operation completes.
1818
- */
1819
- async function _HyperLiquidSubscriptionService_createUserDataSubscription(accountId) {
1820
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1821
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1822
- if (!subscriptionClient) {
1823
- throw new Error('Subscription client not initialized');
1824
- }
1825
- const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
1826
- const dexName = ''; // Use empty string as key for single subscription
1827
- // Skip if subscription already exists
1828
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").has(dexName)) {
1829
- return undefined;
1830
- }
1831
- // Wait for DEX discovery if HIP-3 is enabled but DEXs haven't been discovered yet
1832
- // This ensures HIP-3 subscriptions are created together with main DEX
1833
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f") && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").length === 0) {
1834
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Waiting for DEX discovery before creating subscriptions...');
1835
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_waitForDexDiscovery).call(this);
1836
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('DEX discovery complete, proceeding with subscriptions', {
1837
- enabledDexs: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f"),
1838
- });
1839
- }
1840
- return new Promise((resolve, reject) => {
1841
- // Use per-DEX clearinghouseState + openOrders subscriptions for
1842
- // positions/orders/account on every path. webData3 is used only for OI
1843
- // caps extraction. The deprecated webData2 channel is no longer used.
1844
- // Determine which DEXs to subscribe to:
1845
- // - HIP-3 enabled: main DEX + each enabled HIP-3 DEX.
1846
- // - HIP-3 disabled: main DEX only.
1847
- const dexsToSubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")
1848
- ? [
1849
- '',
1850
- ...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").filter((dexId) => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isDexEnabled).call(this, dexId)),
1851
- ]
1852
- : [''];
1853
- // Track expected DEXs for synchronized notifications
1854
- // Clear previous tracking and set new expected DEXs
1855
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_expectedDexs, new Set(dexsToSubscribe), "f");
1856
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_initializedDexs, new Set(), "f");
1857
- // Set up individual subscriptions for each DEX
1858
- const subscriptionPromises = [];
1859
- for (const currentDexName of dexsToSubscribe) {
1860
- // Set up clearinghouseState subscription for positions + account
1861
- subscriptionPromises.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription).call(this, userAddress, currentDexName));
1862
- // Set up openOrders subscription for orders
1863
- subscriptionPromises.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription).call(this, userAddress, currentDexName));
1864
- }
1865
- // Also set up webData3 for OI caps only
1866
- const webData3Promise = subscriptionClient
1867
- .webData3({ user: userAddress }, (data) => {
1868
- try {
1869
- // webData3 is ONLY used for OI caps extraction
1870
- // Positions, orders, and account data come from individual subscriptions
1871
- const allOICaps = [];
1872
- data.perpDexStates.forEach((dexState, index) => {
1873
- // Map webData3 index to DEX name
1874
- // Index 0 = main DEX (null), Index 1+ = HIP-3 DEXs from discoveredDexNames
1875
- const dexIdentifier = index === 0 ? null : __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_discoveredDexNames, "f")[index - 1];
1876
- // Skip unknown DEXs (not in discoveredDexNames) to prevent main DEX cache corruption
1877
- if (index > 0 && dexIdentifier === undefined) {
1878
- return; // Unknown DEX - skip to prevent misidentifying as main DEX
1879
- }
1880
- // Only process DEXs we care about (skip others silently)
1881
- if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isDexEnabled).call(this, dexIdentifier ?? null)) {
1882
- return; // Skip this DEX - not enabled in our configuration
1883
- }
1884
- const currentDexName = dexIdentifier ?? '';
1885
- const oiCaps = dexState.perpsAtOpenInterestCap ?? [];
1886
- // Add DEX prefix for HIP-3 symbols (e.g., "xyz:TSLA")
1887
- if (currentDexName) {
1888
- allOICaps.push(...oiCaps.map((symbol) => `${currentDexName}:${symbol}`));
1889
- }
1890
- else {
1891
- // Main DEX - no prefix needed
1892
- allOICaps.push(...oiCaps);
1893
- }
1894
- });
1895
- // Update OI caps cache and notify if changed
1896
- const oiCapsHash = [...allOICaps]
1897
- .sort((a, b) => a.localeCompare(b))
1898
- .join(',');
1899
- if (oiCapsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, "f")) {
1900
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICaps, allOICaps, "f");
1901
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, oiCapsHash, "f");
1902
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, true, "f");
1903
- // Notify all subscribers
1904
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f").forEach((callback) => callback(allOICaps));
1905
- }
1906
- }
1907
- catch (error) {
1908
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'webData3 callback error', {
1909
- user: userAddress,
1910
- hasPerpDexStates: data?.perpDexStates !== undefined,
1911
- perpDexStatesLength: data?.perpDexStates?.length ?? 0,
1912
- }));
1913
- }
1914
- })
1915
- .then((sub) => {
1916
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").set(dexName, sub);
1917
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`webData3 subscription established for OI caps (main + HIP-3)`);
1918
- return undefined;
1919
- })
1920
- .catch((error) => {
1921
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createUserDataSubscription (webData3)', {
1922
- dex: dexName,
1923
- }));
1924
- throw error;
1925
- });
1926
- subscriptionPromises.push(webData3Promise);
1927
- // Wait for all subscriptions to be established
1928
- Promise.all(subscriptionPromises)
1929
- .then(() => {
1930
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`User data subscriptions established for ${dexsToSubscribe.length} DEX(s)`);
1931
- resolve();
1932
- return undefined;
1933
- })
1934
- .catch((error) => {
1935
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createUserDataSubscription', {
1936
- dexs: dexsToSubscribe,
1937
- }));
1938
- reject((0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'));
1939
- });
1940
- });
1941
- }, _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription =
1942
- /**
1943
- * Ensure clearinghouseState subscription exists for a DEX
1944
- * Uses pending promise tracking to prevent race conditions where multiple
1945
- * concurrent calls could create duplicate subscriptions
1946
- *
1947
- * @param userAddress - The user's wallet address.
1948
- * @param dexName - The DEX identifier (empty string for main DEX).
1949
- * @returns A promise that resolves when the subscription is established.
1950
- */
1951
- async function _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription(userAddress, dexName) {
1952
- // Already subscribed
1953
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").has(dexName)) {
1954
- return;
1955
- }
1956
- // Another call is already in progress - wait for it instead of creating duplicate
1957
- const pending = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").get(dexName);
1958
- if (pending) {
1959
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`[ensureClearinghouseStateSubscription] Waiting for pending subscription for DEX: ${dexName || 'main'}`);
1960
- await pending;
1961
- return;
1962
- }
1963
- // Create subscription promise and track it
1964
- const subscriptionPromise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createClearinghouseSubscription).call(this, userAddress, dexName);
1965
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").set(dexName, subscriptionPromise);
1966
- try {
1967
- await subscriptionPromise;
1968
- }
1969
- finally {
1970
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").delete(dexName);
1971
- }
1972
- }, _HyperLiquidSubscriptionService_createClearinghouseSubscription =
1973
- /**
1974
- * Create the actual clearinghouseState subscription
1975
- * Separated from ensureClearinghouseStateSubscription to enable promise deduplication
1976
- *
1977
- * @param userAddress - The user's wallet address.
1978
- * @param dexName - The DEX identifier (empty string for main DEX).
1979
- */
1980
- async function _HyperLiquidSubscriptionService_createClearinghouseSubscription(userAddress, dexName) {
1981
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1982
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1983
- if (!subscriptionClient) {
1984
- throw new Error('Subscription client not available');
1985
- }
1986
- try {
1987
- const subscription = await subscriptionClient.clearinghouseState({
1988
- user: userAddress,
1989
- dex: dexName || undefined, // Empty string -> undefined for main DEX
1990
- }, (data) => {
1991
- const cacheKey = data.dex || '';
1992
- // Update caches and notify subscribers if we have positions/account subscribers
1993
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0 ||
1994
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") > 0) {
1995
- // Process positions from clearinghouse state
1996
- const positions = data.clearinghouseState.assetPositions
1997
- .filter((assetPos) => assetPos.position.szi !== '0')
1998
- .map((assetPos) => (0, hyperLiquidAdapter_js_1.adaptPositionFromSDK)(assetPos));
1999
- // Get cached orders to preserve TP/SL data (prevents flickering)
2000
- // Orders are cached by openOrders subscription
2001
- const cachedOrders = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").get(cacheKey) ?? [];
2002
- // Re-extract TP/SL from cached orders for the new positions
2003
- // This ensures TP/SL data persists across clearinghouseState updates
2004
- // Default the trigger arrays so "no triggers" and "not streamed yet"
2005
- // look the same to consumers as they do on the REST path.
2006
- let positionsWithTPSL = positions.map((position) => ({
2007
- ...position,
2008
- takeProfitOrders: position.takeProfitOrders ?? [],
2009
- stopLossOrders: position.stopLossOrders ?? [],
2010
- }));
2011
- if (cachedOrders.length > 0) {
2012
- const { tpslMap, tpslCountMap, triggerOrderMap } = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_extractTPSLFromOrders).call(this, [], positions, cachedOrders);
2013
- positionsWithTPSL = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_mergeTPSLIntoPositions).call(this, positions, tpslMap, tpslCountMap, triggerOrderMap);
2014
- }
2015
- // Update account state
2016
- const accountState = (0, hyperLiquidAdapter_js_1.adaptAccountStateFromSDK)(data.clearinghouseState);
2017
- // Update caches
2018
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").set(cacheKey, positionsWithTPSL);
2019
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").set(cacheKey, accountState);
2020
- // Mark this DEX as initialized (has sent first data)
2021
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").add(cacheKey);
2022
- // Trigger aggregation and notify subscribers
2023
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
2024
- }
2025
- });
2026
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").set(dexName, subscription);
2027
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`clearinghouseState subscription established for DEX: ${dexName || 'main'}`);
2028
- }
2029
- catch (error) {
2030
- // Remove this DEX from expected set so it doesn't block notifications for other DEXs
2031
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").delete(dexName);
2032
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createClearinghouseSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureClearinghouseStateSubscription', {
2033
- dex: dexName,
2034
- }));
2035
- throw error;
2036
- }
2037
- }, _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription =
2038
- /**
2039
- * Ensure openOrders subscription exists for a DEX
2040
- * Uses pending promise tracking to prevent race conditions where multiple
2041
- * concurrent calls could create duplicate subscriptions
2042
- *
2043
- * @param userAddress - The user's wallet address.
2044
- * @param dexName - The DEX identifier (empty string for main DEX).
2045
- * @returns A promise that resolves when the subscription is established.
2046
- */
2047
- async function _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription(userAddress, dexName) {
2048
- // Already subscribed
2049
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").has(dexName)) {
2050
- return;
2051
- }
2052
- // Another call is already in progress - wait for it instead of creating duplicate
2053
- const pending = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").get(dexName);
2054
- if (pending) {
2055
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`[ensureOpenOrdersSubscription] Waiting for pending subscription for DEX: ${dexName || 'main'}`);
2056
- await pending;
2057
- return;
2058
- }
2059
- // Create subscription promise and track it
2060
- const subscriptionPromise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createOpenOrdersSubscription).call(this, userAddress, dexName);
2061
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").set(dexName, subscriptionPromise);
2062
- try {
2063
- await subscriptionPromise;
2064
- }
2065
- finally {
2066
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").delete(dexName);
2067
- }
2068
- }, _HyperLiquidSubscriptionService_createOpenOrdersSubscription =
2069
- /**
2070
- * Create the actual openOrders subscription
2071
- * Separated from ensureOpenOrdersSubscription to enable promise deduplication
2072
- *
2073
- * @param userAddress - The user's wallet address.
2074
- * @param dexName - The DEX identifier (empty string for main DEX).
2075
- */
2076
- async function _HyperLiquidSubscriptionService_createOpenOrdersSubscription(userAddress, dexName) {
2077
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
2078
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2079
- if (!subscriptionClient) {
2080
- throw new Error('Subscription client not available');
2081
- }
2082
- try {
2083
- const subscription = await subscriptionClient.openOrders({
2084
- user: userAddress,
2085
- dex: dexName || undefined, // Empty string -> undefined for main DEX
2086
- }, (data) => {
2087
- const cacheKey = data.dex || '';
2088
- // Update caches and notify subscribers if we have order subscribers
2089
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") > 0 ||
2090
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0) {
2091
- // Get cached positions for TP/SL processing
2092
- const cachedPositions = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").get(cacheKey) ?? [];
2093
- // Extract TP/SL and process orders
2094
- const { tpslMap, tpslCountMap, triggerOrderMap, processedOrders: orders, } = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_extractTPSLFromOrders).call(this, data.orders, cachedPositions);
2095
- // Update orders cache with processed orders
2096
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").set(cacheKey, orders);
2097
- // Update positions with TP/SL if we have positions
2098
- if (cachedPositions.length > 0) {
2099
- const positionsWithTPSL = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_mergeTPSLIntoPositions).call(this, cachedPositions, tpslMap, tpslCountMap, triggerOrderMap);
2100
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").set(cacheKey, positionsWithTPSL);
2101
- }
2102
- // Mark this DEX as initialized (has sent first data)
2103
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").add(cacheKey);
2104
- // Trigger aggregation and notify subscribers
2105
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
2106
- }
2107
- });
2108
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").set(dexName, subscription);
2109
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`openOrders subscription established for DEX: ${dexName || 'main'}`);
2110
- }
2111
- catch (error) {
2112
- // Remove this DEX from expected set so it doesn't block notifications for other DEXs
2113
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").delete(dexName);
2114
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createOpenOrdersSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureOpenOrdersSubscription', {
2115
- dex: dexName,
2116
- }));
2117
- throw error;
2118
- }
2119
- }, _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers = function _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers() {
2120
- // Wait for all expected DEXs to send initial data before notifying
2121
- // This ensures positions from all DEXs appear simultaneously
2122
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").size > 0) {
2123
- const allDexsInitialized = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f")).every((dex) => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").has(dex));
2124
- if (!allDexsInitialized) {
2125
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Waiting for all DEXs to send initial data', {
2126
- expected: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f")),
2127
- initialized: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f")),
2128
- });
2129
- return; // Don't notify yet - waiting for more DEXs
2130
- }
2131
- }
2132
- // Aggregate data from all DEX caches
2133
- // Order: Main DEX (crypto perps) first, then HIP-3 DEXs
2134
- const mainDexPositions = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").get('') ?? [];
2135
- const hip3DexPositions = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").entries())
2136
- .filter(([key]) => key !== '')
2137
- .flatMap(([, positions]) => positions);
2138
- const aggregatedPositions = [...mainDexPositions, ...hip3DexPositions];
2139
- const mainDexOrders = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").get('') ?? [];
2140
- const hip3DexOrders = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").entries())
2141
- .filter(([key]) => key !== '')
2142
- .flatMap(([, orders]) => orders);
2143
- const aggregatedOrders = [...mainDexOrders, ...hip3DexOrders];
2144
- const aggregatedAccount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAccountStates).call(this);
2145
- // Check if aggregated data changed using fast hash comparison
2146
- const positionsHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashPositions).call(this, aggregatedPositions);
2147
- const ordersHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashOrders).call(this, aggregatedOrders);
2148
- const accountHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashAccountState).call(this, aggregatedAccount);
2149
- const positionsChanged = positionsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, "f");
2150
- const ordersChanged = ordersHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, "f");
2151
- const accountChanged = accountHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccountHash, "f");
2152
- // Only notify subscribers if aggregated data changed
2153
- if (positionsChanged) {
2154
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, aggregatedPositions, "f");
2155
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, positionsHash, "f");
2156
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, true, "f"); // Mark cache as initialized
2157
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").forEach((callback) => {
2158
- callback(aggregatedPositions);
2159
- });
2160
- }
2161
- if (ordersChanged) {
2162
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, aggregatedOrders, "f");
2163
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, ordersHash, "f");
2164
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, true, "f"); // Mark cache as initialized
2165
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").forEach((callback) => {
2166
- callback(aggregatedOrders);
2167
- });
2168
- }
2169
- if (accountChanged) {
2170
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, aggregatedAccount, "f");
2171
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, accountHash, "f");
2172
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").forEach((callback) => {
2173
- callback(aggregatedAccount);
2174
- });
2175
- }
2176
- }, _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription = function _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription() {
2177
- const totalSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") +
2178
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") +
2179
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") +
2180
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f");
2181
- if (totalSubscribers <= 0) {
2182
- // Cleanup webData3 subscription (covers all DEXs)
2183
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").size > 0) {
2184
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").forEach((subscription, dexName) => {
2185
- subscription.unsubscribe().catch((error) => {
2186
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.webData3', {
2187
- dex: dexName,
2188
- }));
2189
- });
2190
- });
2191
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
2192
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
2193
- }
2194
- // Cleanup spotState subscriptions (per-user). Bump generation +
2195
- // drop in-flight promises so a racing #ensureSpotStateSubscription
2196
- // continuation discards its subscription rather than rehydrating
2197
- // #spotStateSubscriptions after this clear.
2198
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionGeneration, "f") + 1, "f");
2199
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptionPromises, "f").clear();
2200
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").size > 0) {
2201
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").forEach((subscription, user) => {
2202
- subscription.unsubscribe().catch((error) => {
2203
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.spotState', { user }));
2204
- });
2205
- });
2206
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateSubscriptions, "f").clear();
2207
- }
2208
- // Cleanup individual subscriptions (clearinghouseState + openOrders)
2209
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").size > 0) {
2210
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").forEach((subscription, dexName) => {
2211
- subscription.unsubscribe().catch((error) => {
2212
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.clearinghouseState', {
2213
- dex: dexName,
2214
- }));
2215
- });
2216
- });
2217
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
2218
- }
2219
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").size > 0) {
2220
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").forEach((subscription, dexName) => {
2221
- subscription.unsubscribe().catch((error) => {
2222
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.openOrders', {
2223
- dex: dexName,
2224
- }));
2225
- });
2226
- });
2227
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
2228
- }
2229
- // Clear pending subscription promises (race condition prevention)
2230
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").clear();
2231
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").clear();
2232
- // Clear subscriber counts
2233
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, 0, "f");
2234
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, 0, "f");
2235
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, 0, "f");
2236
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, 0, "f");
2237
- // Clear per-DEX caches
2238
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").clear();
2239
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").clear();
2240
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").clear();
2241
- // Clear DEX tracking for synchronized notifications
2242
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").clear();
2243
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").clear();
2244
- // Clear aggregated caches
2245
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, null, "f");
2246
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, null, "f");
2247
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, null, "f");
2248
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotState, null, "f");
2249
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedSpotStateUserAddress, null, "f");
2250
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeByUser, "f").clear();
2251
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeLastWsRefreshAtByUser, "f").clear();
2252
- // Drop in-flight refresh handles so stale hanging userAbstraction
2253
- // requests from the prior connection can't be awaited by future calls.
2254
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_abstractionModeInflightByUser, "f").clear();
2255
- // Bump generation so any in-flight spot fetch from a prior user discards
2256
- // its result instead of re-populating the cache post-cleanup.
2257
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStateGeneration, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_spotStateGeneration, "f") + 1, "f");
2258
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromise, undefined, "f");
2259
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_spotStatePromiseUserAddress, undefined, "f");
2260
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, false, "f"); // Reset cache initialization flag
2261
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, false, "f"); // Reset cache initialization flag
2262
- // Clear hash caches
2263
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, '', "f");
2264
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, '', "f");
2265
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, '', "f");
2266
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('All multi-DEX subscriptions cleaned up (webData3 + individual subscriptions)');
2267
- }
2268
- }, _HyperLiquidSubscriptionService_ensureOrderFillISubscription =
2269
- /**
2270
- * Ensure order fill subscription is active for the given accountId
2271
- * Shares subscription across all callbacks for the same accountId
2272
- *
2273
- * @param accountId - Optional CAIP account ID to subscribe for.
2274
- * @returns A promise that resolves when the subscription is established.
2275
- */
2276
- async function _HyperLiquidSubscriptionService_ensureOrderFillISubscription(accountId) {
2277
- // Normalize accountId: undefined -> 'default' for Map key
2278
- const normalizedAccountId = accountId ?? 'default';
2279
- // If subscription already exists, no need to create another
2280
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").has(normalizedAccountId)) {
2281
- return;
2282
- }
2283
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2284
- if (!subscriptionClient) {
2285
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
2286
- const client = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2287
- if (!client) {
2288
- throw new Error('SubscriptionClient not available');
2289
- }
2290
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId);
2291
- return;
2292
- }
2293
- const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
2294
- // userFills returns a Promise<ISubscription>, need to await it
2295
- const subscription = await subscriptionClient.userFills({ user: userAddress }, (data) => {
2296
- // Build a Map for O(1) lookup instead of O(n) find per fill
2297
- const orderMap = new Map();
2298
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")) {
2299
- for (const order of __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")) {
2300
- if (order.detailedOrderType) {
2301
- orderMap.set(order.orderId, order.detailedOrderType);
2302
- }
2303
- }
2304
- }
2305
- const orderFills = data.fills.map((fill) => {
2306
- const oid = fill.oid.toString();
2307
- return {
2308
- orderId: oid,
2309
- symbol: fill.coin,
2310
- side: fill.side,
2311
- size: fill.sz,
2312
- price: fill.px,
2313
- fee: fill.fee,
2314
- timestamp: fill.time,
2315
- pnl: fill.closedPnl,
2316
- direction: fill.dir,
2317
- feeToken: fill.feeToken,
2318
- startPosition: fill.startPosition,
2319
- liquidation: fill.liquidation
2320
- ? {
2321
- liquidatedUser: fill.liquidation.liquidatedUser,
2322
- markPx: fill.liquidation.markPx,
2323
- method: fill.liquidation.method,
2324
- }
2325
- : undefined,
2326
- detailedOrderType: orderMap.get(oid),
2327
- };
2328
- });
2329
- // Cache fills for cache-first pattern (similar to price caching)
2330
- // This allows getOrFetchFills() to return cached data without REST API calls
2331
- if (data.isSnapshot) {
2332
- // Snapshot: replace cache with initial historical data, sorted newest first
2333
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, [...orderFills]
2334
- .sort((a, b) => b.timestamp - a.timestamp)
2335
- .slice(0, 100), "f");
2336
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, true, "f");
2337
- }
2338
- else {
2339
- // Streaming: prepend new fills to existing (newest first)
2340
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, [
2341
- ...orderFills,
2342
- ...(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ?? []),
2343
- ].slice(0, 100), "f");
2344
- }
2345
- // Distribute to all callbacks for this accountId
2346
- const subscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").get(normalizedAccountId);
2347
- if (subscribers) {
2348
- subscribers.forEach((callback) => {
2349
- callback(orderFills, data.isSnapshot);
2350
- });
2351
- }
2352
- });
2353
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").set(normalizedAccountId, subscription);
2354
- }, _HyperLiquidSubscriptionService_createSubscription = function _HyperLiquidSubscriptionService_createSubscription(subscribers, callback, key) {
2355
- if (subscribers instanceof Map && key) {
2356
- if (!subscribers.has(key)) {
2357
- subscribers.set(key, new Set());
2358
- }
2359
- subscribers.get(key)?.add(callback);
2360
- }
2361
- else if (subscribers instanceof Set) {
2362
- subscribers.add(callback);
2363
- }
2364
- return () => {
2365
- if (subscribers instanceof Map && key) {
2366
- const set = subscribers.get(key);
2367
- set?.delete(callback);
2368
- if (set?.size === 0) {
2369
- subscribers.delete(key);
2370
- }
2371
- }
2372
- else if (subscribers instanceof Set) {
2373
- subscribers.delete(callback);
2374
- }
2375
- };
2376
- }, _HyperLiquidSubscriptionService_createPriceUpdate = function _HyperLiquidSubscriptionService_createPriceUpdate(symbol, price) {
2377
- const marketData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").get(symbol);
2378
- const orderBookData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").get(symbol);
2379
- const currentPrice = parseFloat(price);
2380
- let percentChange24h;
2381
- if (marketData?.prevDayPx !== undefined) {
2382
- const change = ((currentPrice - marketData.prevDayPx) / marketData.prevDayPx) * 100;
2383
- percentChange24h = change.toFixed(2);
2384
- }
2385
- // Check if any subscriber for this symbol wants market data
2386
- const hasMarketDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").has(symbol) &&
2387
- (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").get(symbol)?.size ?? 0) > 0;
2388
- const priceUpdate = {
2389
- symbol,
2390
- price,
2391
- timestamp: Date.now(),
2392
- percentChange24h,
2393
- // Add mark price from activeAssetCtx
2394
- markPrice: marketData?.oraclePrice
2395
- ? marketData.oraclePrice.toString()
2396
- : undefined,
2397
- // Add order book data if available
2398
- bestBid: orderBookData?.bestBid,
2399
- bestAsk: orderBookData?.bestAsk,
2400
- spread: orderBookData?.spread,
2401
- // Always include funding when available (don't default to 0, preserve undefined)
2402
- funding: marketData?.funding,
2403
- // Add market data only if requested by at least one subscriber
2404
- openInterest: hasMarketDataSubscribers
2405
- ? marketData?.openInterest
2406
- : undefined,
2407
- volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,
2408
- // Flag markets that are currently untradable because the mid price has drifted
2409
- // too far from the oracle price (HyperLiquid rejects such orders). Lets clients
2410
- // warn the user before they attempt an order that would fail. Defaults to tradable
2411
- // when the oracle price isn't yet cached.
2412
- isTradable: (0, marketDataTransform_js_1.isMarketTradable)({
2413
- midPrice: currentPrice,
2414
- oraclePrice: marketData?.oraclePrice,
2415
- deviationLimit: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceDeviationLimit, "f"),
2416
- }),
2417
- };
2418
- return priceUpdate;
2419
- }, _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice = function _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice(symbol) {
2420
- const marketData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").get(symbol);
2421
- if (marketData?.activeAssetCtxPrice === undefined ||
2422
- marketData.priceLastUpdated === undefined) {
2423
- return undefined;
2424
- }
2425
- if (Date.now() - marketData.priceLastUpdated >
2426
- __classPrivateFieldGet(_a, _a, "f", _HyperLiquidSubscriptionService_activeAssetCtxPriceTtlMs)) {
2427
- return undefined;
2428
- }
2429
- return marketData.activeAssetCtxPrice.toString();
2430
- }, _HyperLiquidSubscriptionService_projectPriceUpdate = function _HyperLiquidSubscriptionService_projectPriceUpdate(symbol, base) {
2431
- const fastPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice).call(this, symbol);
2432
- if (fastPrice === undefined) {
2433
- return base;
2434
- }
2435
- return {
2436
- ...base,
2437
- price: fastPrice,
2438
- timestamp: Date.now(),
2439
- };
2440
- }, _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription = function _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription() {
2441
- // Check both the subscription AND the promise to prevent race conditions
2442
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, "f") ?? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, "f")) {
2443
- return;
2444
- }
2445
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2446
- if (!subscriptionClient) {
2447
- return;
2448
- }
2449
- // Track WebSocket metrics
2450
- const wsMetrics = {
2451
- messagesReceived: 0,
2452
- lastMessageTime: Date.now(),
2453
- reconnectCount: 0,
2454
- startTime: Date.now(),
2455
- };
2456
- // Store the promise immediately to prevent duplicate calls
2457
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, subscriptionClient
2458
- .allMids((data) => {
2459
- wsMetrics.messagesReceived += 1;
2460
- wsMetrics.lastMessageTime = Date.now();
2461
- // Initialize cache if needed
2462
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
2463
- // Store raw snapshot for the main DEX so market fetches can reuse it without REST.
2464
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allMidsSnapshots, "f").set('', data.mids);
2465
- const subscribedSymbols = new Set();
2466
- // Collect all symbols that have subscribers
2467
- for (const [symbol, subscriberSet,] of __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").entries()) {
2468
- if (subscriberSet.size > 0) {
2469
- subscribedSymbols.add(symbol);
2470
- }
2471
- }
2472
- // Track which subscribed symbols actually changed price, so
2473
- // notification can be scoped to just those symbols
2474
- const changedSymbols = new Set();
2475
- // Only process symbols that are actually subscribed to
2476
- for (const symbol in data.mids) {
2477
- // Skip if nobody is subscribed to this symbol
2478
- if (!subscribedSymbols.has(symbol)) {
2479
- continue;
2480
- }
2481
- const price = data.mids[symbol].toString();
2482
- const cachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").get(symbol);
2483
- // Skip if price hasn't changed
2484
- if (cachedPrice?.price === price) {
2485
- continue;
2486
- }
2487
- // Price changed or new symbol - update cache
2488
- const priceUpdate = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, price);
2489
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, priceUpdate);
2490
- changedSymbols.add(symbol);
2491
- }
2492
- // Only notify subscribers of symbols whose price actually changed
2493
- // This prevents unnecessary React re-renders when prices haven't changed
2494
- if (changedSymbols.size > 0) {
2495
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this, changedSymbols);
2496
- }
2497
- })
2498
- .then((sub) => {
2499
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, sub, "f");
2500
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquid: Global allMids subscription established');
2501
- // Notify existing subscribers with any cached data now that subscription is established
2502
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").size > 0) {
2503
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
2504
- }
2505
- return undefined;
2506
- })
2507
- .catch((error) => {
2508
- // Clear the promise on error so it can be retried
2509
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, undefined, "f");
2510
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureGlobalAllMidsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureGlobalAllMidsSubscription'));
2511
- }), "f");
2512
- }, _HyperLiquidSubscriptionService_ensureGlobalFastAssetCtxsSubscription = function _HyperLiquidSubscriptionService_ensureGlobalFastAssetCtxsSubscription() {
2513
- // Check both the subscription AND the promise to prevent race conditions
2514
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, "f") ??
2515
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, "f")) {
2516
- return;
2517
- }
2518
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2519
- if (!subscriptionClient) {
2520
- return;
2521
- }
2522
- const handleFastAssetCtxsUpdate = (data) => {
2523
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
2524
- // Track which subscribed symbols actually changed price, so
2525
- // notification can be scoped to just those symbols
2526
- const changedSymbols = new Set();
2527
- for (const coin in data) {
2528
- if (!(0, utils_1.hasProperty)(data, coin)) {
2529
- continue;
2530
- }
2531
- const ctx = data[coin];
2532
- const priceRaw = ctx.midPx ?? ctx.markPx;
2533
- if (priceRaw === undefined || priceRaw === null) {
2534
- // No usable price for this coin in this message — don't claim
2535
- // ownership. Otherwise a coin with no usable price here would be
2536
- // marked as fastAssetCtxs-owned while never having a fast price
2537
- // cached, suppressing assetCtxs (its only remaining price source)
2538
- // for that coin indefinitely.
2539
- continue;
2540
- }
2541
- // Mark this coin as covered by fastAssetCtxs now that a usable
2542
- // price backs that ownership (regardless of whether there's
2543
- // currently a subscriber), so the slower per-DEX assetCtxs handler
2544
- // knows to defer to this feed for the coin's price.
2545
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fastAssetCtxsCoins, "f").add(coin);
2546
- const price = priceRaw.toString();
2547
- const cachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").get(coin);
2548
- // Skip if price hasn't changed
2549
- if (cachedPrice?.price === price) {
2550
- continue;
2551
- }
2552
- const priceUpdate = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, coin, price);
2553
- // Cache every valid price, even for coins nobody is subscribed to
2554
- // yet (snapshot messages include every asset on the exchange), so
2555
- // a later subscriber gets an immediate baseline via the
2556
- // subscribe-time cached-price replay instead of an assetCtxs feed
2557
- // that's been suppressed with no fastAssetCtxs price to fall back
2558
- // on.
2559
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(coin, priceUpdate);
2560
- // Scope notification to coins with an active subscriber; snapshot
2561
- // messages cover the full exchange and most coins have none.
2562
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").get(coin)?.size) {
2563
- changedSymbols.add(coin);
2564
- }
2565
- }
2566
- // Only notify subscribers of symbols whose price actually changed
2567
- if (changedSymbols.size > 0) {
2568
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this, changedSymbols);
2569
- }
2570
- };
2571
- const subscribeWithRetry = async () => {
2572
- const maxAttempts = 3;
2573
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2574
- try {
2575
- return await subscriptionClient.fastAssetCtxs(handleFastAssetCtxsUpdate);
2576
- }
2577
- catch (error) {
2578
- const ensuredError = (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureGlobalFastAssetCtxsSubscription');
2579
- const isLastAttempt = attempt === maxAttempts;
2580
- if (isLastAttempt || !__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isTransientSdkError).call(this, ensuredError)) {
2581
- throw ensuredError;
2582
- }
2583
- const retryDelayMs = attempt * 500;
2584
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Transient fastAssetCtxs subscription failure during reconnect, retrying', {
2585
- attempt,
2586
- retryDelayMs,
2587
- error: ensuredError.message,
2588
- });
2589
- await new Promise((_resolve) => setTimeout(_resolve, retryDelayMs));
2590
- }
2591
- }
2592
- throw new Error('Failed to establish fastAssetCtxs subscription');
2593
- };
2594
- // Store the promise immediately to prevent duplicate calls
2595
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, subscribeWithRetry()
2596
- .then((sub) => {
2597
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsSubscription, sub, "f");
2598
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquid: Global fastAssetCtxs subscription established');
2599
- return undefined;
2600
- })
2601
- .catch((error) => {
2602
- // Clear the promise on error so it can be retried
2603
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalFastAssetCtxsPromise, undefined, "f");
2604
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureGlobalFastAssetCtxsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureGlobalFastAssetCtxsSubscription'));
2605
- }), "f");
2606
- }, _HyperLiquidSubscriptionService_ensureActiveAssetSubscription = function _HyperLiquidSubscriptionService_ensureActiveAssetSubscription(symbol) {
2607
- // Increment subscriber count
2608
- const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").get(symbol) ?? 0;
2609
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").set(symbol, currentCount + 1);
2610
- // If subscription already exists or is being created, just return
2611
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").has(symbol) ||
2612
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").has(symbol)) {
2613
- return;
2614
- }
2615
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2616
- if (!subscriptionClient) {
2617
- return;
2618
- }
2619
- // Track metrics for this subscription
2620
- const subscriptionMetrics = {
2621
- messagesReceived: 0,
2622
- startTime: Date.now(),
2623
- };
2624
- const promise = subscriptionClient
2625
- .activeAssetCtx({ coin: symbol }, (data) => {
2626
- subscriptionMetrics.messagesReceived += 1;
2627
- if (data.coin === symbol && data.ctx) {
2628
- // Type guard using SDK types: check if this is perps (has funding) or spot (no funding)
2629
- const isPerpsContext = (event) => (0, utils_1.hasProperty)(event.ctx, 'funding') &&
2630
- (0, utils_1.hasProperty)(event.ctx, 'openInterest') &&
2631
- (0, utils_1.hasProperty)(event.ctx, 'oraclePx');
2632
- const { ctx } = data;
2633
- // Cache market data for consolidation with price updates
2634
- const ctxPrice = ctx.midPx ?? ctx.markPx;
2635
- const now = Date.now();
2636
- const openInterestUSD = isPerpsContext(data) && ctxPrice
2637
- ? (0, marketDataTransform_js_1.calculateOpenInterestUSD)(data.ctx.openInterest, ctxPrice)
2638
- : NaN;
2639
- const marketData = {
2640
- prevDayPx: ctx.prevDayPx
2641
- ? parseFloat(ctx.prevDayPx.toString())
2642
- : undefined,
2643
- // Cache funding rate from activeAssetCtx for real-time updates
2644
- // SDK defines funding as string (not nullable) in ActiveAssetCtxEvent
2645
- funding: isPerpsContext(data)
2646
- ? parseFloat(data.ctx.funding.toString())
2647
- : undefined,
2648
- openInterest: isNaN(openInterestUSD)
2649
- ? undefined
2650
- : openInterestUSD,
2651
- volume24h: ctx.dayNtlVlm
2652
- ? parseFloat(ctx.dayNtlVlm.toString())
2653
- : undefined,
2654
- oraclePrice: isPerpsContext(data)
2655
- ? parseFloat(data.ctx.oraclePx.toString())
2656
- : undefined,
2657
- lastUpdated: now,
2658
- // Store fast-stream price for per-subscriber projection in
2659
- // #notifyAllPriceSubscribers. Used only for focused subscribers.
2660
- activeAssetCtxPrice: ctxPrice
2661
- ? parseFloat(ctxPrice.toString())
2662
- : undefined,
2663
- priceLastUpdated: ctxPrice ? now : undefined,
2664
- };
2665
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").set(symbol, marketData);
2666
- // Rebuild the allMids baseline so derived fields (isTradable,
2667
- // funding, openInterest, volume24h, markPrice, percentChange24h)
2668
- // pick up the new activeAssetCtx data. Only rebuild when a baseline
2669
- // already exists to preserve the startup zero-price guard: we never
2670
- // want to synthesize a baseline from a '0' / absent allMids price.
2671
- const priceCache = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f");
2672
- const existingBaseline = priceCache?.get(symbol);
2673
- if (priceCache && existingBaseline) {
2674
- priceCache.set(symbol, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, existingBaseline.price));
2675
- }
2676
- // Notify subscribers of this symbol only. #notifyAllPriceSubscribers
2677
- // projects the fast-stream price (now stored in #marketDataCache) for
2678
- // focused (includeMarketData: true) subscribers, while list subscribers
2679
- // continue to receive only the allMids baseline from #cachedPriceData.
2680
- // Scoping to this symbol avoids redundant reference-equal allMids
2681
- // updates to list subscribers watching other symbols, since their
2682
- // allMids baseline hasn't changed on this tick.
2683
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this, new Set([symbol]));
2684
- }
2685
- })
2686
- .then((sub) => {
2687
- // Only clear pending ref if this is still the current promise.
2688
- // A rapid away-and-back can replace the pending promise; blindly
2689
- // deleting would remove the *newer* reference (#28141).
2690
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").get(symbol) === promise) {
2691
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").delete(symbol);
2692
- }
2693
- // Stale subscription: cleanup was called while pending, a newer
2694
- // subscription already won the race, OR a different pending promise
2695
- // exists (rapid away-and-back before this one resolved). (#28141)
2696
- if ((__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").get(symbol) ?? 0) <= 0 ||
2697
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").has(symbol) ||
2698
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").has(symbol)) {
2699
- return sub.unsubscribe();
2700
- }
2701
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").set(symbol, sub);
2702
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: Market data subscription established for ${symbol}`);
2703
- return undefined;
2704
- })
2705
- .catch((error) => {
2706
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").get(symbol) === promise) {
2707
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").delete(symbol);
2708
- }
2709
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureActiveAssetSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureActiveAssetSubscription', { symbol }));
2710
- });
2711
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").set(symbol, promise);
2712
- }, _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription = function _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription(symbol) {
2713
- const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").get(symbol) ?? 0;
2714
- if (currentCount <= 1) {
2715
- // Last subscriber, cleanup subscription
2716
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").delete(symbol);
2717
- const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").get(symbol);
2718
- if (subscription && typeof subscription.unsubscribe === 'function') {
2719
- const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
2720
- unsubscribeResult.catch(() => {
2721
- // Ignore errors during cleanup
2722
- });
2723
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").delete(symbol);
2724
- }
2725
- else if (subscription) {
2726
- // Subscription exists but unsubscribe is not a function or doesn't return a Promise
2727
- // Just clean up the reference
2728
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").delete(symbol);
2729
- }
2730
- // If subscription is still pending (async), the .then() handler in
2731
- // #ensureActiveAssetSubscription will check symbolSubscriberCounts
2732
- // and unsubscribe immediately when it resolves (#28141)
2733
- // Clean up the pending promise reference
2734
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingActiveAssetPromises, "f").delete(symbol);
2735
- }
2736
- else {
2737
- // Still has subscribers, just decrement count
2738
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").set(symbol, currentCount - 1);
2739
- }
2740
- }, _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription =
2741
- /**
2742
- * Ensure assetCtxs subscription for specific DEX (HIP-3 support)
2743
- * Uses WebSocket instead of REST polling for market data
2744
- * Implements reference counting to track active subscribers per DEX
2745
- *
2746
- * @param dex - The DEX identifier (empty string for main DEX).
2747
- * @param options - Subscription behavior overrides.
2748
- * @param options.incrementRefCount - Skip incrementing when restoring existing subscribers after reconnect.
2749
- */
2750
- async function _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription(dex, options = {}) {
2751
- const dexKey = dex || '';
2752
- const { incrementRefCount = true } = options;
2753
- if (incrementRefCount) {
2754
- const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").get(dexKey) ?? 0;
2755
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").set(dexKey, currentCount + 1);
2756
- }
2757
- // Return if subscription already exists
2758
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").has(dexKey)) {
2759
- return;
2760
- }
2761
- let promise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").get(dexKey);
2762
- if (!promise) {
2763
- promise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createAssetCtxsSubscription).call(this, dex);
2764
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").set(dexKey, promise);
2765
- }
2766
- try {
2767
- await promise;
2768
- }
2769
- catch (error) {
2770
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").get(dexKey) === promise) {
2771
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").delete(dexKey);
2772
- }
2773
- if (incrementRefCount) {
2774
- const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").get(dexKey) ?? 0;
2775
- if (currentCount <= 1) {
2776
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").delete(dexKey);
2777
- }
2778
- else {
2779
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").set(dexKey, currentCount - 1);
2780
- }
2781
- }
2782
- throw error;
2783
- }
2784
- }, _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription =
2785
- /**
2786
- * Ensure a per-DEX allMids WS subscription exists (singleton per DEX).
2787
- * Mirrors the assetCtxs subscription dedup pattern and is used only for HIP-3 DEXs.
2788
- *
2789
- * @param dex - The HIP-3 DEX name.
2790
- */
2791
- async function _HyperLiquidSubscriptionService_ensureDexAllMidsSubscription(dex) {
2792
- if (!dex) {
2793
- return;
2794
- }
2795
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").has(dex)) {
2796
- return;
2797
- }
2798
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").has(dex)) {
2799
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").get(dex);
2800
- return;
2801
- }
2802
- const promise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createDexAllMidsSubscription).call(this, dex);
2803
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").set(dex, promise);
2804
- try {
2805
- await promise;
2806
- }
2807
- catch (error) {
2808
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").delete(dex);
2809
- throw error;
2810
- }
2811
- }, _HyperLiquidSubscriptionService_createDexAllMidsSubscription =
2812
- /**
2813
- * Create allMids WS subscription for a specific HIP-3 DEX.
2814
- *
2815
- * @param dex - The HIP-3 DEX name.
2816
- */
2817
- async function _HyperLiquidSubscriptionService_createDexAllMidsSubscription(dex) {
2818
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
2819
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2820
- if (!subscriptionClient) {
2821
- throw new Error('Subscription client not initialized');
2822
- }
2823
- return new Promise((resolve, reject) => {
2824
- subscriptionClient
2825
- .allMids({ dex }, (data) => {
2826
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allMidsSnapshots, "f").set(dex, data.mids);
2827
- })
2828
- .then((sub) => {
2829
- // If a newer subscription already won the race, discard this one (#28141)
2830
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").has(dex)) {
2831
- resolve();
2832
- return sub.unsubscribe();
2833
- }
2834
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").set(dex, sub);
2835
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`allMids subscription established for DEX: ${dex}`);
2836
- resolve();
2837
- return undefined;
2838
- })
2839
- .catch((error) => {
2840
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createDexAllMidsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createDexAllMidsSubscription', { dex }));
2841
- reject((0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createDexAllMidsSubscription'));
2842
- });
2843
- });
2844
- }, _HyperLiquidSubscriptionService_createAssetCtxsSubscription =
2845
- /**
2846
- * Create assetCtxs subscription for specific DEX
2847
- * Provides real-time market data for all assets on the DEX
2848
- *
2849
- * Performance: Uses cached meta from dexMetaCache (populated by metaAndAssetCtxs)
2850
- * to avoid redundant meta() API calls during subscription setup
2851
- *
2852
- * @param dex - The DEX identifier (empty string for main DEX).
2853
- */
2854
- async function _HyperLiquidSubscriptionService_createAssetCtxsSubscription(dex) {
2855
- await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
2856
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2857
- if (!subscriptionClient) {
2858
- throw new Error('Subscription client not initialized');
2859
- }
2860
- const dexKey = dex || '';
2861
- const dexIdentifier = dex ?? 'main DEX';
2862
- // Check cache first - populated by metaAndAssetCtxs in ensureAssetCtxsSubscription
2863
- let perpsMeta = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").get(dexKey);
2864
- if (!perpsMeta) {
2865
- // Fallback: fetch meta if not in cache (shouldn't happen in normal flow)
2866
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Meta cache miss for ${dexIdentifier}, fetching from API`);
2867
- const infoClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getInfoClient();
2868
- const fetchedMeta = await infoClient.meta({ dex: dex || undefined });
2869
- if (fetchedMeta?.universe) {
2870
- perpsMeta = fetchedMeta;
2871
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").set(dexKey, fetchedMeta);
2872
- }
2873
- }
2874
- if (!perpsMeta?.universe) {
2875
- const errorMessage = `No universe data available for ${dexIdentifier}`;
2876
- throw new Error(errorMessage);
2877
- }
2878
- // Capture narrowed perpsMeta in a const for use inside closures
2879
- const validatedMeta = perpsMeta;
2880
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Using ${__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").has(dexKey) ? 'cached' : 'fetched'} meta for ${dexIdentifier}`, {
2881
- dex,
2882
- universeCount: validatedMeta.universe.length,
2883
- firstAssetSample: validatedMeta.universe[0]?.name,
2884
- });
2885
- return new Promise((resolve, reject) => {
2886
- const subscriptionParams = dex ? { dex } : {};
2887
- const handleAssetCtxsUpdate = (data) => {
2888
- // Cache asset contexts for this DEX
2889
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").set(dexKey, data.ctxs);
2890
- // Use cached meta to map ctxs array indices to symbols (no REST API call!)
2891
- validatedMeta.universe.forEach((asset, index) => {
2892
- const ctx = data.ctxs[index];
2893
- if (ctx && (0, utils_1.hasProperty)(ctx, 'funding')) {
2894
- // This is a perps context
2895
- const ctxPrice = ctx.midPx ?? ctx.markPx;
2896
- const openInterestUSD = (0, marketDataTransform_js_1.calculateOpenInterestUSD)(ctx.openInterest, ctxPrice);
2897
- // Preserve the fast-stream price fields set by the per-symbol
2898
- // activeAssetCtx handler. assetCtxs is a per-DEX batch that does not
2899
- // carry the fast-stream price concept, so rebuilding the entry from
2900
- // scratch would clobber activeAssetCtxPrice/priceLastUpdated and make
2901
- // #getFreshActiveAssetCtxPrice return stale, dropping focused
2902
- // subscribers back to the slower allMids baseline. priceLastUpdated
2903
- // is carried forward (not reset) so the staleness gate keeps
2904
- // reflecting the last activeAssetCtx tick.
2905
- const existingMarketData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").get(asset.name);
2906
- const marketData = {
2907
- prevDayPx: ctx.prevDayPx
2908
- ? parseFloat(ctx.prevDayPx.toString())
2909
- : undefined,
2910
- funding: parseFloat(ctx.funding.toString()),
2911
- openInterest: isNaN(openInterestUSD)
2912
- ? undefined
2913
- : openInterestUSD,
2914
- volume24h: ctx.dayNtlVlm
2915
- ? parseFloat(ctx.dayNtlVlm.toString())
2916
- : undefined,
2917
- oraclePrice: parseFloat(ctx.oraclePx.toString()),
2918
- lastUpdated: Date.now(),
2919
- activeAssetCtxPrice: existingMarketData?.activeAssetCtxPrice,
2920
- priceLastUpdated: existingMarketData?.priceLastUpdated,
2921
- };
2922
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").set(asset.name, marketData);
2923
- // HIP-3: Extract price from assetCtx and update cached prices.
2924
- // For HIP-3 DEXs, meta() returns asset.name already containing the
2925
- // DEX prefix (e.g., "xyz:XYZ100"), so use it directly.
2926
- const symbol = asset.name;
2927
- const price = ctx.midPx?.toString() ?? ctx.markPx?.toString();
2928
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fastAssetCtxsCoins, "f").has(symbol)) {
2929
- // fastAssetCtxs (TAT-3387) owns the price string for this coin
2930
- // with fresher, ~5s-cadence data, so don't overwrite it with
2931
- // this batch's price. Still rebuild the baseline (keeping the
2932
- // existing price) so derived fields just refreshed above in
2933
- // #marketDataCache (funding, openInterest, volume24h,
2934
- // oraclePrice, percentChange24h/isTradable via markPrice) reach
2935
- // list subscribers instead of going stale until the next
2936
- // fastAssetCtxs/allMids price change. Only rebuild an existing
2937
- // baseline to preserve the startup zero-price guard: we never
2938
- // want to synthesize a baseline from a '0' / absent allMids
2939
- // price.
2940
- const existingBaseline = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol);
2941
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") && existingBaseline) {
2942
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, existingBaseline.price));
2943
- }
2944
- }
2945
- else if (price) {
2946
- const priceUpdate = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, price);
2947
- __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
2948
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, priceUpdate);
2949
- }
2950
- }
2951
- });
2952
- // Notify price subscribers with updated market data
2953
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
2954
- };
2955
- const subscribeWithRetry = async () => {
2956
- const maxAttempts = 3;
2957
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2958
- try {
2959
- return await subscriptionClient.assetCtxs(subscriptionParams, handleAssetCtxsUpdate);
2960
- }
2961
- catch (error) {
2962
- const ensuredError = (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createAssetCtxsSubscription');
2963
- const isLastAttempt = attempt === maxAttempts;
2964
- if (isLastAttempt || !__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isTransientSdkError).call(this, ensuredError)) {
2965
- throw ensuredError;
2966
- }
2967
- const retryDelayMs = attempt * 500;
2968
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Transient assetCtxs subscription failure during reconnect, retrying', {
2969
- dex: dexKey || 'main',
2970
- attempt,
2971
- retryDelayMs,
2972
- error: ensuredError.message,
2973
- });
2974
- await new Promise((_resolve) => setTimeout(_resolve, retryDelayMs));
2975
- }
2976
- }
2977
- throw new Error(`Failed to establish assetCtxs subscription for ${dexIdentifier}`);
2978
- };
2979
- subscribeWithRetry()
2980
- .then((sub) => {
2981
- // If a newer subscription already won the race, discard this one (#28141)
2982
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").has(dexKey)) {
2983
- resolve();
2984
- return sub.unsubscribe();
2985
- }
2986
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").set(dexKey, sub);
2987
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`assetCtxs subscription established for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
2988
- resolve();
2989
- return undefined;
2990
- })
2991
- .catch((error) => {
2992
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createAssetCtxsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createAssetCtxsSubscription', { dex }));
2993
- reject((0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.createAssetCtxsSubscription'));
2994
- });
2995
- });
2996
- }, _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription = function _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription(dex) {
2997
- const dexKey = dex || '';
2998
- // Decrement subscriber count for this DEX
2999
- const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").get(dexKey) ?? 0;
3000
- if (currentCount <= 1) {
3001
- // Last subscriber - cleanup the subscription
3002
- const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").get(dexKey);
3003
- const allMidsSubscription = dex
3004
- ? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").get(dex)
3005
- : undefined;
3006
- if (subscription) {
3007
- subscription.unsubscribe().catch((error) => {
3008
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupAssetCtxsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupAssetCtxsSubscription', { dex }));
3009
- });
3010
- }
3011
- if (allMidsSubscription) {
3012
- allMidsSubscription.unsubscribe().catch((error) => {
3013
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupDexAllMidsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupDexAllMidsSubscription', { dex }));
3014
- });
3015
- }
3016
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").delete(dexKey);
3017
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").delete(dexKey);
3018
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").delete(dexKey);
3019
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").delete(dexKey);
3020
- if (dex) {
3021
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptions, "f").delete(dex);
3022
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAllMidsSubscriptionPromises, "f").delete(dex);
3023
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allMidsSnapshots, "f").delete(dex);
3024
- }
3025
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Cleaned up assetCtxs subscription for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
3026
- }
3027
- else {
3028
- // Still has subscribers - just decrement count
3029
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").set(dexKey, currentCount - 1);
3030
- }
3031
- }, _HyperLiquidSubscriptionService_ensureBboSubscription = function _HyperLiquidSubscriptionService_ensureBboSubscription(symbol) {
3032
- // Skip if subscription already exists or is being created
3033
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").has(symbol) ||
3034
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").has(symbol)) {
3035
- return;
3036
- }
3037
- const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
3038
- if (!subscriptionClient) {
3039
- return;
3040
- }
3041
- const promise = subscriptionClient
3042
- .bbo({ coin: symbol }, (data) => {
3043
- (0, hyperLiquidOrderBookProcessor_js_1.processBboData)({
3044
- symbol,
3045
- data,
3046
- orderBookCache: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f"),
3047
- cachedPriceData: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f"),
3048
- createPriceUpdate: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).bind(this),
3049
- notifySubscribers: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).bind(this),
3050
- });
3051
- })
3052
- .then((sub) => {
3053
- // Only clear pending ref if this is still the current promise (#28141).
3054
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").get(symbol) === promise) {
3055
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").delete(symbol);
3056
- }
3057
- // Stale subscription: cleanup was called while pending, a newer
3058
- // subscription already won the race, OR a different pending promise
3059
- // exists (rapid away-and-back before this one resolved). (#28141)
3060
- if ((__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").get(symbol)?.size ?? 0) <= 0 ||
3061
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").has(symbol) ||
3062
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").has(symbol)) {
3063
- return sub.unsubscribe();
3064
- }
3065
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").set(symbol, sub);
3066
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: BBO subscription established for ${symbol}`);
3067
- return undefined;
3068
- })
3069
- .catch((error) => {
3070
- if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").get(symbol) === promise) {
3071
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").delete(symbol);
3072
- }
3073
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_js_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureBboSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureBboSubscription', { symbol }));
3074
- });
3075
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").set(symbol, promise);
3076
- }, _HyperLiquidSubscriptionService_cleanupBboSubscription = function _HyperLiquidSubscriptionService_cleanupBboSubscription(symbol) {
3077
- // If anyone still wants order book (top-of-book) data for this symbol, keep the subscription alive.
3078
- if ((__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").get(symbol)?.size ?? 0) > 0) {
3079
- return;
3080
- }
3081
- const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").get(symbol);
3082
- if (subscription && typeof subscription.unsubscribe === 'function') {
3083
- const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
3084
- unsubscribeResult.catch(() => {
3085
- // Ignore errors during cleanup
3086
- });
3087
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").delete(symbol);
3088
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").delete(symbol);
3089
- }
3090
- else if (subscription) {
3091
- // Subscription exists but unsubscribe is not a function or doesn't return a Promise
3092
- // Just clean up the reference
3093
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").delete(symbol);
3094
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").delete(symbol);
3095
- }
3096
- // If subscription is still pending (async), the .then() handler in
3097
- // #ensureBboSubscription will check orderBookSubscribers and
3098
- // unsubscribe immediately when it resolves (#28141)
3099
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingBboPromises, "f").delete(symbol);
3100
- }, _HyperLiquidSubscriptionService_processOrderBookData = function _HyperLiquidSubscriptionService_processOrderBookData(data, levels) {
3101
- const bidsRaw = data?.levels?.[0] ?? [];
3102
- const asksRaw = data?.levels?.[1] ?? [];
3103
- // Process bids (buy orders) - highest price first
3104
- let bidCumulativeSize = 0;
3105
- let bidCumulativeNotional = 0;
3106
- const bids = bidsRaw.slice(0, levels).map((level) => {
3107
- const price = parseFloat(level.px);
3108
- const size = parseFloat(level.sz);
3109
- const notional = price * size;
3110
- bidCumulativeSize += size;
3111
- bidCumulativeNotional += notional;
3112
- return {
3113
- price: level.px,
3114
- size: level.sz,
3115
- total: bidCumulativeSize.toString(),
3116
- notional: notional.toFixed(2),
3117
- totalNotional: bidCumulativeNotional.toFixed(2),
3118
- };
3119
- });
3120
- // Process asks (sell orders) - lowest price first
3121
- let askCumulativeSize = 0;
3122
- let askCumulativeNotional = 0;
3123
- const asks = asksRaw.slice(0, levels).map((level) => {
3124
- const price = parseFloat(level.px);
3125
- const size = parseFloat(level.sz);
3126
- const notional = price * size;
3127
- askCumulativeSize += size;
3128
- askCumulativeNotional += notional;
3129
- return {
3130
- price: level.px,
3131
- size: level.sz,
3132
- total: askCumulativeSize.toString(),
3133
- notional: notional.toFixed(2),
3134
- totalNotional: askCumulativeNotional.toFixed(2),
3135
- };
3136
- });
3137
- // Calculate spread and mid price
3138
- const bestBid = bids[0];
3139
- const bestAsk = asks[0];
3140
- const bidPrice = bestBid ? parseFloat(bestBid.price) : 0;
3141
- const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;
3142
- const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
3143
- const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
3144
- const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
3145
- // Calculate max total for depth chart scaling
3146
- const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
3147
- return {
3148
- bids,
3149
- asks,
3150
- spread: spread.toFixed(5),
3151
- spreadPercentage,
3152
- midPrice: midPrice.toFixed(5),
3153
- lastUpdated: Date.now(),
3154
- maxTotal,
3155
- };
3156
- }, _HyperLiquidSubscriptionService_notifyAllPriceSubscribers = function _HyperLiquidSubscriptionService_notifyAllPriceSubscribers(changedSymbols) {
3157
- const subscriberUpdates = new Map();
3158
- __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").forEach((subscriberSet, symbol) => {
3159
- if (changedSymbols && !changedSymbols.has(symbol)) {
3160
- return;
3161
- }
3162
- const allMidsBase = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol);
3163
- const fastPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getFreshActiveAssetCtxPrice).call(this, symbol);
3164
- const now = Date.now();
3165
- subscriberSet.forEach((callback) => {
3166
- const isFocused = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").get(symbol)?.has(callback) ?? false;
3167
- let priceUpdate;
3168
- if (isFocused && fastPrice !== undefined) {
3169
- // Use allMids baseline as the structural base when available;
3170
- // fall back to a freshly computed PriceUpdate if allMids hasn't
3171
- // arrived yet so focused screens stay responsive on first render.
3172
- const base = allMidsBase ?? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, fastPrice);
3173
- priceUpdate = { ...base, price: fastPrice, timestamp: now };
3174
- }
3175
- else if (allMidsBase !== undefined) {
3176
- priceUpdate = allMidsBase;
3177
- }
3178
- if (priceUpdate !== undefined) {
3179
- const updates = subscriberUpdates.get(callback) ?? [];
3180
- updates.push(priceUpdate);
3181
- subscriberUpdates.set(callback, updates);
3182
- }
3183
- });
3184
- });
3185
- // Send batched updates to each subscriber
3186
- subscriberUpdates.forEach((updates, callback) => {
3187
- if (updates.length > 0) {
3188
- callback(updates);
3189
- }
3190
- });
3191
- };
3192
- // Stale threshold for the fast-stream price preference. If the last
3193
- // activeAssetCtx price update is older than this, the allMids baseline is
3194
- // used for focused subscribers.
3195
- _HyperLiquidSubscriptionService_activeAssetCtxPriceTtlMs = { value: 10000 };
3196
- //# sourceMappingURL=HyperLiquidSubscriptionService.cjs.map