@metamask-previews/perps-controller 16.1.0-preview-abca9bcea → 17.0.0-preview-0a30e47

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