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