@metamask-previews/perps-controller 0.0.0-preview-685dbf46b → 1.0.0-preview-bc00f2c

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 (482) hide show
  1. package/CHANGELOG.md +30 -2
  2. package/dist/PerpsController.cjs +3077 -65
  3. package/dist/PerpsController.cjs.map +1 -1
  4. package/dist/PerpsController.d.cts +969 -82
  5. package/dist/PerpsController.d.cts.map +1 -1
  6. package/dist/PerpsController.d.mts +969 -82
  7. package/dist/PerpsController.d.mts.map +1 -1
  8. package/dist/PerpsController.mjs +3073 -62
  9. package/dist/PerpsController.mjs.map +1 -1
  10. package/dist/aggregation/SubscriptionMultiplexer.cjs +441 -0
  11. package/dist/aggregation/SubscriptionMultiplexer.cjs.map +1 -0
  12. package/dist/aggregation/SubscriptionMultiplexer.d.cts +171 -0
  13. package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +1 -0
  14. package/dist/aggregation/SubscriptionMultiplexer.d.mts +171 -0
  15. package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +1 -0
  16. package/dist/aggregation/SubscriptionMultiplexer.mjs +437 -0
  17. package/dist/aggregation/SubscriptionMultiplexer.mjs.map +1 -0
  18. package/dist/aggregation/index.cjs +9 -0
  19. package/dist/aggregation/index.cjs.map +1 -0
  20. package/dist/aggregation/index.d.cts +6 -0
  21. package/dist/aggregation/index.d.cts.map +1 -0
  22. package/dist/aggregation/index.d.mts +6 -0
  23. package/dist/aggregation/index.d.mts.map +1 -0
  24. package/dist/aggregation/index.mjs +5 -0
  25. package/dist/aggregation/index.mjs.map +1 -0
  26. package/dist/constants/chartConfig.cjs +227 -0
  27. package/dist/constants/chartConfig.cjs.map +1 -0
  28. package/dist/constants/chartConfig.d.cts +216 -0
  29. package/dist/constants/chartConfig.d.cts.map +1 -0
  30. package/dist/constants/chartConfig.d.mts +216 -0
  31. package/dist/constants/chartConfig.d.mts.map +1 -0
  32. package/dist/constants/chartConfig.mjs +221 -0
  33. package/dist/constants/chartConfig.mjs.map +1 -0
  34. package/dist/constants/eventNames.cjs +436 -0
  35. package/dist/constants/eventNames.cjs.map +1 -0
  36. package/dist/constants/eventNames.d.cts +387 -0
  37. package/dist/constants/eventNames.d.cts.map +1 -0
  38. package/dist/constants/eventNames.d.mts +387 -0
  39. package/dist/constants/eventNames.d.mts.map +1 -0
  40. package/dist/constants/eventNames.mjs +433 -0
  41. package/dist/constants/eventNames.mjs.map +1 -0
  42. package/dist/constants/hyperLiquidConfig.cjs +380 -0
  43. package/dist/constants/hyperLiquidConfig.cjs.map +1 -0
  44. package/dist/constants/hyperLiquidConfig.d.cts +236 -0
  45. package/dist/constants/hyperLiquidConfig.d.cts.map +1 -0
  46. package/dist/constants/hyperLiquidConfig.d.mts +236 -0
  47. package/dist/constants/hyperLiquidConfig.d.mts.map +1 -0
  48. package/dist/constants/hyperLiquidConfig.mjs +371 -0
  49. package/dist/constants/hyperLiquidConfig.mjs.map +1 -0
  50. package/dist/constants/index.cjs +28 -0
  51. package/dist/constants/index.cjs.map +1 -0
  52. package/dist/constants/index.d.cts +12 -0
  53. package/dist/constants/index.d.cts.map +1 -0
  54. package/dist/constants/index.d.mts +12 -0
  55. package/dist/constants/index.d.mts.map +1 -0
  56. package/dist/constants/index.mjs +12 -0
  57. package/dist/constants/index.mjs.map +1 -0
  58. package/dist/constants/myxConfig.cjs +229 -0
  59. package/dist/constants/myxConfig.cjs.map +1 -0
  60. package/dist/constants/myxConfig.d.cts +106 -0
  61. package/dist/constants/myxConfig.d.cts.map +1 -0
  62. package/dist/constants/myxConfig.d.mts +106 -0
  63. package/dist/constants/myxConfig.d.mts.map +1 -0
  64. package/dist/constants/myxConfig.mjs +219 -0
  65. package/dist/constants/myxConfig.mjs.map +1 -0
  66. package/dist/constants/orderTypes.cjs +31 -0
  67. package/dist/constants/orderTypes.cjs.map +1 -0
  68. package/dist/constants/orderTypes.d.cts +19 -0
  69. package/dist/constants/orderTypes.d.cts.map +1 -0
  70. package/dist/constants/orderTypes.d.mts +19 -0
  71. package/dist/constants/orderTypes.d.mts.map +1 -0
  72. package/dist/constants/orderTypes.mjs +27 -0
  73. package/dist/constants/orderTypes.mjs.map +1 -0
  74. package/dist/constants/performanceMetrics.cjs +63 -0
  75. package/dist/constants/performanceMetrics.cjs.map +1 -0
  76. package/dist/constants/performanceMetrics.d.cts +46 -0
  77. package/dist/constants/performanceMetrics.d.cts.map +1 -0
  78. package/dist/constants/performanceMetrics.d.mts +46 -0
  79. package/dist/constants/performanceMetrics.d.mts.map +1 -0
  80. package/dist/constants/performanceMetrics.mjs +60 -0
  81. package/dist/constants/performanceMetrics.mjs.map +1 -0
  82. package/dist/constants/perpsConfig.cjs +295 -0
  83. package/dist/constants/perpsConfig.cjs.map +1 -0
  84. package/dist/constants/perpsConfig.d.cts +221 -0
  85. package/dist/constants/perpsConfig.d.cts.map +1 -0
  86. package/dist/constants/perpsConfig.d.mts +221 -0
  87. package/dist/constants/perpsConfig.d.mts.map +1 -0
  88. package/dist/constants/perpsConfig.mjs +292 -0
  89. package/dist/constants/perpsConfig.mjs.map +1 -0
  90. package/dist/constants/transactionsHistoryConfig.cjs +19 -0
  91. package/dist/constants/transactionsHistoryConfig.cjs.map +1 -0
  92. package/dist/constants/transactionsHistoryConfig.d.cts +16 -0
  93. package/dist/constants/transactionsHistoryConfig.d.cts.map +1 -0
  94. package/dist/constants/transactionsHistoryConfig.d.mts +16 -0
  95. package/dist/constants/transactionsHistoryConfig.d.mts.map +1 -0
  96. package/dist/constants/transactionsHistoryConfig.mjs +16 -0
  97. package/dist/constants/transactionsHistoryConfig.mjs.map +1 -0
  98. package/dist/index.cjs +63 -1
  99. package/dist/index.cjs.map +1 -1
  100. package/dist/index.d.cts +38 -2
  101. package/dist/index.d.cts.map +1 -1
  102. package/dist/index.d.mts +38 -2
  103. package/dist/index.d.mts.map +1 -1
  104. package/dist/index.mjs +46 -1
  105. package/dist/index.mjs.map +1 -1
  106. package/dist/perpsErrorCodes.cjs +80 -0
  107. package/dist/perpsErrorCodes.cjs.map +1 -0
  108. package/dist/perpsErrorCodes.d.cts +65 -0
  109. package/dist/perpsErrorCodes.d.cts.map +1 -0
  110. package/dist/perpsErrorCodes.d.mts +65 -0
  111. package/dist/perpsErrorCodes.d.mts.map +1 -0
  112. package/dist/perpsErrorCodes.mjs +77 -0
  113. package/dist/perpsErrorCodes.mjs.map +1 -0
  114. package/dist/providers/AggregatedPerpsProvider.cjs +508 -0
  115. package/dist/providers/AggregatedPerpsProvider.cjs.map +1 -0
  116. package/dist/providers/AggregatedPerpsProvider.d.cts +171 -0
  117. package/dist/providers/AggregatedPerpsProvider.d.cts.map +1 -0
  118. package/dist/providers/AggregatedPerpsProvider.d.mts +171 -0
  119. package/dist/providers/AggregatedPerpsProvider.d.mts.map +1 -0
  120. package/dist/providers/AggregatedPerpsProvider.mjs +504 -0
  121. package/dist/providers/AggregatedPerpsProvider.mjs.map +1 -0
  122. package/dist/providers/HyperLiquidProvider.cjs +5679 -0
  123. package/dist/providers/HyperLiquidProvider.cjs.map +1 -0
  124. package/dist/providers/HyperLiquidProvider.d.cts +516 -0
  125. package/dist/providers/HyperLiquidProvider.d.cts.map +1 -0
  126. package/dist/providers/HyperLiquidProvider.d.mts +516 -0
  127. package/dist/providers/HyperLiquidProvider.d.mts.map +1 -0
  128. package/dist/providers/HyperLiquidProvider.mjs +5675 -0
  129. package/dist/providers/HyperLiquidProvider.mjs.map +1 -0
  130. package/dist/providers/MYXProvider.cjs +514 -0
  131. package/dist/providers/MYXProvider.cjs.map +1 -0
  132. package/dist/providers/MYXProvider.d.cts +105 -0
  133. package/dist/providers/MYXProvider.d.cts.map +1 -0
  134. package/dist/providers/MYXProvider.d.mts +105 -0
  135. package/dist/providers/MYXProvider.d.mts.map +1 -0
  136. package/dist/providers/MYXProvider.mjs +510 -0
  137. package/dist/providers/MYXProvider.mjs.map +1 -0
  138. package/dist/routing/ProviderRouter.cjs +154 -0
  139. package/dist/routing/ProviderRouter.cjs.map +1 -0
  140. package/dist/routing/ProviderRouter.d.cts +112 -0
  141. package/dist/routing/ProviderRouter.d.cts.map +1 -0
  142. package/dist/routing/ProviderRouter.d.mts +112 -0
  143. package/dist/routing/ProviderRouter.d.mts.map +1 -0
  144. package/dist/routing/ProviderRouter.mjs +150 -0
  145. package/dist/routing/ProviderRouter.mjs.map +1 -0
  146. package/dist/routing/index.cjs +9 -0
  147. package/dist/routing/index.cjs.map +1 -0
  148. package/dist/routing/index.d.cts +6 -0
  149. package/dist/routing/index.d.cts.map +1 -0
  150. package/dist/routing/index.d.mts +6 -0
  151. package/dist/routing/index.d.mts.map +1 -0
  152. package/dist/routing/index.mjs +5 -0
  153. package/dist/routing/index.mjs.map +1 -0
  154. package/dist/selectors.cjs +166 -0
  155. package/dist/selectors.cjs.map +1 -0
  156. package/dist/selectors.d.cts +362 -0
  157. package/dist/selectors.d.cts.map +1 -0
  158. package/dist/selectors.d.mts +362 -0
  159. package/dist/selectors.d.mts.map +1 -0
  160. package/dist/selectors.mjs +158 -0
  161. package/dist/selectors.mjs.map +1 -0
  162. package/dist/services/AccountService.cjs +324 -0
  163. package/dist/services/AccountService.cjs.map +1 -0
  164. package/dist/services/AccountService.d.cts +56 -0
  165. package/dist/services/AccountService.d.cts.map +1 -0
  166. package/dist/services/AccountService.d.mts +56 -0
  167. package/dist/services/AccountService.d.mts.map +1 -0
  168. package/dist/services/AccountService.mjs +320 -0
  169. package/dist/services/AccountService.mjs.map +1 -0
  170. package/dist/services/DataLakeService.cjs +233 -0
  171. package/dist/services/DataLakeService.cjs.map +1 -0
  172. package/dist/services/DataLakeService.d.cts +51 -0
  173. package/dist/services/DataLakeService.d.cts.map +1 -0
  174. package/dist/services/DataLakeService.d.mts +51 -0
  175. package/dist/services/DataLakeService.d.mts.map +1 -0
  176. package/dist/services/DataLakeService.mjs +229 -0
  177. package/dist/services/DataLakeService.mjs.map +1 -0
  178. package/dist/services/DepositService.cjs +98 -0
  179. package/dist/services/DepositService.cjs.map +1 -0
  180. package/dist/services/DepositService.d.cts +39 -0
  181. package/dist/services/DepositService.d.cts.map +1 -0
  182. package/dist/services/DepositService.d.mts +39 -0
  183. package/dist/services/DepositService.d.mts.map +1 -0
  184. package/dist/services/DepositService.mjs +94 -0
  185. package/dist/services/DepositService.mjs.map +1 -0
  186. package/dist/services/EligibilityService.cjs +173 -0
  187. package/dist/services/EligibilityService.cjs.map +1 -0
  188. package/dist/services/EligibilityService.d.cts +39 -0
  189. package/dist/services/EligibilityService.d.cts.map +1 -0
  190. package/dist/services/EligibilityService.d.mts +39 -0
  191. package/dist/services/EligibilityService.d.mts.map +1 -0
  192. package/dist/services/EligibilityService.mjs +169 -0
  193. package/dist/services/EligibilityService.mjs.map +1 -0
  194. package/dist/services/FeatureFlagConfigurationService.cjs +257 -0
  195. package/dist/services/FeatureFlagConfigurationService.cjs.map +1 -0
  196. package/dist/services/FeatureFlagConfigurationService.d.cts +73 -0
  197. package/dist/services/FeatureFlagConfigurationService.d.cts.map +1 -0
  198. package/dist/services/FeatureFlagConfigurationService.d.mts +73 -0
  199. package/dist/services/FeatureFlagConfigurationService.d.mts.map +1 -0
  200. package/dist/services/FeatureFlagConfigurationService.mjs +253 -0
  201. package/dist/services/FeatureFlagConfigurationService.mjs.map +1 -0
  202. package/dist/services/HyperLiquidClientService.cjs +867 -0
  203. package/dist/services/HyperLiquidClientService.cjs.map +1 -0
  204. package/dist/services/HyperLiquidClientService.d.cts +214 -0
  205. package/dist/services/HyperLiquidClientService.d.cts.map +1 -0
  206. package/dist/services/HyperLiquidClientService.d.mts +214 -0
  207. package/dist/services/HyperLiquidClientService.d.mts.map +1 -0
  208. package/dist/services/HyperLiquidClientService.mjs +862 -0
  209. package/dist/services/HyperLiquidClientService.mjs.map +1 -0
  210. package/dist/services/HyperLiquidSubscriptionService.cjs +2199 -0
  211. package/dist/services/HyperLiquidSubscriptionService.cjs.map +1 -0
  212. package/dist/services/HyperLiquidSubscriptionService.d.cts +187 -0
  213. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +1 -0
  214. package/dist/services/HyperLiquidSubscriptionService.d.mts +187 -0
  215. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +1 -0
  216. package/dist/services/HyperLiquidSubscriptionService.mjs +2195 -0
  217. package/dist/services/HyperLiquidSubscriptionService.mjs.map +1 -0
  218. package/dist/services/HyperLiquidWalletService.cjs +163 -0
  219. package/dist/services/HyperLiquidWalletService.cjs.map +1 -0
  220. package/dist/services/HyperLiquidWalletService.d.cts +78 -0
  221. package/dist/services/HyperLiquidWalletService.d.cts.map +1 -0
  222. package/dist/services/HyperLiquidWalletService.d.mts +78 -0
  223. package/dist/services/HyperLiquidWalletService.d.mts.map +1 -0
  224. package/dist/services/HyperLiquidWalletService.mjs +159 -0
  225. package/dist/services/HyperLiquidWalletService.mjs.map +1 -0
  226. package/dist/services/MYXClientService.cjs +304 -0
  227. package/dist/services/MYXClientService.cjs.map +1 -0
  228. package/dist/services/MYXClientService.d.cts +81 -0
  229. package/dist/services/MYXClientService.d.cts.map +1 -0
  230. package/dist/services/MYXClientService.d.mts +81 -0
  231. package/dist/services/MYXClientService.d.mts.map +1 -0
  232. package/dist/services/MYXClientService.mjs +300 -0
  233. package/dist/services/MYXClientService.mjs.map +1 -0
  234. package/dist/services/MarketDataService.cjs +848 -0
  235. package/dist/services/MarketDataService.cjs.map +1 -0
  236. package/dist/services/MarketDataService.d.cts +291 -0
  237. package/dist/services/MarketDataService.d.cts.map +1 -0
  238. package/dist/services/MarketDataService.d.mts +291 -0
  239. package/dist/services/MarketDataService.d.mts.map +1 -0
  240. package/dist/services/MarketDataService.mjs +844 -0
  241. package/dist/services/MarketDataService.mjs.map +1 -0
  242. package/dist/services/RewardsIntegrationService.cjs +120 -0
  243. package/dist/services/RewardsIntegrationService.cjs.map +1 -0
  244. package/dist/services/RewardsIntegrationService.d.cts +28 -0
  245. package/dist/services/RewardsIntegrationService.d.cts.map +1 -0
  246. package/dist/services/RewardsIntegrationService.d.mts +28 -0
  247. package/dist/services/RewardsIntegrationService.d.mts.map +1 -0
  248. package/dist/services/RewardsIntegrationService.mjs +116 -0
  249. package/dist/services/RewardsIntegrationService.mjs.map +1 -0
  250. package/dist/services/ServiceContext.cjs +3 -0
  251. package/dist/services/ServiceContext.cjs.map +1 -0
  252. package/dist/services/ServiceContext.d.cts +86 -0
  253. package/dist/services/ServiceContext.d.cts.map +1 -0
  254. package/dist/services/ServiceContext.d.mts +86 -0
  255. package/dist/services/ServiceContext.d.mts.map +1 -0
  256. package/dist/services/ServiceContext.mjs +2 -0
  257. package/dist/services/ServiceContext.mjs.map +1 -0
  258. package/dist/services/TradingReadinessCache.cjs +288 -0
  259. package/dist/services/TradingReadinessCache.cjs.map +1 -0
  260. package/dist/services/TradingReadinessCache.d.cts +174 -0
  261. package/dist/services/TradingReadinessCache.d.cts.map +1 -0
  262. package/dist/services/TradingReadinessCache.d.mts +174 -0
  263. package/dist/services/TradingReadinessCache.d.mts.map +1 -0
  264. package/dist/services/TradingReadinessCache.mjs +285 -0
  265. package/dist/services/TradingReadinessCache.mjs.map +1 -0
  266. package/dist/services/TradingService.cjs +1457 -0
  267. package/dist/services/TradingService.cjs.map +1 -0
  268. package/dist/services/TradingService.d.cts +195 -0
  269. package/dist/services/TradingService.d.cts.map +1 -0
  270. package/dist/services/TradingService.d.mts +195 -0
  271. package/dist/services/TradingService.d.mts.map +1 -0
  272. package/dist/services/TradingService.mjs +1453 -0
  273. package/dist/services/TradingService.mjs.map +1 -0
  274. package/dist/types/config.cjs +3 -0
  275. package/dist/types/config.cjs.map +1 -0
  276. package/dist/types/config.d.cts +49 -0
  277. package/dist/types/config.d.cts.map +1 -0
  278. package/dist/types/config.d.mts +49 -0
  279. package/dist/types/config.d.mts.map +1 -0
  280. package/dist/types/config.mjs +2 -0
  281. package/dist/types/config.mjs.map +1 -0
  282. package/dist/types/hyperliquid-types.cjs +3 -0
  283. package/dist/types/hyperliquid-types.cjs.map +1 -0
  284. package/dist/types/hyperliquid-types.d.cts +20 -0
  285. package/dist/types/hyperliquid-types.d.cts.map +1 -0
  286. package/dist/types/hyperliquid-types.d.mts +20 -0
  287. package/dist/types/hyperliquid-types.d.mts.map +1 -0
  288. package/dist/types/hyperliquid-types.mjs +2 -0
  289. package/dist/types/hyperliquid-types.mjs.map +1 -0
  290. package/dist/types/index.cjs +115 -0
  291. package/dist/types/index.cjs.map +1 -0
  292. package/dist/types/index.d.cts +1262 -0
  293. package/dist/types/index.d.cts.map +1 -0
  294. package/dist/types/index.d.mts +1262 -0
  295. package/dist/types/index.d.mts.map +1 -0
  296. package/dist/types/index.mjs +97 -0
  297. package/dist/types/index.mjs.map +1 -0
  298. package/dist/types/messenger.cjs +3 -0
  299. package/dist/types/messenger.cjs.map +1 -0
  300. package/dist/types/messenger.d.cts +27 -0
  301. package/dist/types/messenger.d.cts.map +1 -0
  302. package/dist/types/messenger.d.mts +27 -0
  303. package/dist/types/messenger.d.mts.map +1 -0
  304. package/dist/types/messenger.mjs +2 -0
  305. package/dist/types/messenger.mjs.map +1 -0
  306. package/dist/types/myx-types.cjs +25 -0
  307. package/dist/types/myx-types.cjs.map +1 -0
  308. package/dist/types/myx-types.d.cts +63 -0
  309. package/dist/types/myx-types.d.cts.map +1 -0
  310. package/dist/types/myx-types.d.mts +63 -0
  311. package/dist/types/myx-types.d.mts.map +1 -0
  312. package/dist/types/myx-types.mjs +22 -0
  313. package/dist/types/myx-types.mjs.map +1 -0
  314. package/dist/types/perps-types.cjs +4 -0
  315. package/dist/types/perps-types.cjs.map +1 -0
  316. package/dist/types/perps-types.d.cts +105 -0
  317. package/dist/types/perps-types.d.cts.map +1 -0
  318. package/dist/types/perps-types.d.mts +105 -0
  319. package/dist/types/perps-types.d.mts.map +1 -0
  320. package/dist/types/perps-types.mjs +2 -0
  321. package/dist/types/perps-types.mjs.map +1 -0
  322. package/dist/types/token.cjs +3 -0
  323. package/dist/types/token.cjs.map +1 -0
  324. package/dist/types/token.d.cts +25 -0
  325. package/dist/types/token.d.cts.map +1 -0
  326. package/dist/types/token.d.mts +25 -0
  327. package/dist/types/token.d.mts.map +1 -0
  328. package/dist/types/token.mjs +2 -0
  329. package/dist/types/token.mjs.map +1 -0
  330. package/dist/types/transactionTypes.cjs +28 -0
  331. package/dist/types/transactionTypes.cjs.map +1 -0
  332. package/dist/types/transactionTypes.d.cts +64 -0
  333. package/dist/types/transactionTypes.d.cts.map +1 -0
  334. package/dist/types/transactionTypes.d.mts +64 -0
  335. package/dist/types/transactionTypes.d.mts.map +1 -0
  336. package/dist/types/transactionTypes.mjs +23 -0
  337. package/dist/types/transactionTypes.mjs.map +1 -0
  338. package/dist/utils/accountUtils.cjs +100 -0
  339. package/dist/utils/accountUtils.cjs.map +1 -0
  340. package/dist/utils/accountUtils.d.cts +30 -0
  341. package/dist/utils/accountUtils.d.cts.map +1 -0
  342. package/dist/utils/accountUtils.d.mts +30 -0
  343. package/dist/utils/accountUtils.d.mts.map +1 -0
  344. package/dist/utils/accountUtils.mjs +92 -0
  345. package/dist/utils/accountUtils.mjs.map +1 -0
  346. package/dist/utils/errorUtils.cjs +35 -0
  347. package/dist/utils/errorUtils.cjs.map +1 -0
  348. package/dist/utils/errorUtils.d.cts +15 -0
  349. package/dist/utils/errorUtils.d.cts.map +1 -0
  350. package/dist/utils/errorUtils.d.mts +15 -0
  351. package/dist/utils/errorUtils.d.mts.map +1 -0
  352. package/dist/utils/errorUtils.mjs +31 -0
  353. package/dist/utils/errorUtils.mjs.map +1 -0
  354. package/dist/utils/hyperLiquidAdapter.cjs +331 -0
  355. package/dist/utils/hyperLiquidAdapter.cjs.map +1 -0
  356. package/dist/utils/hyperLiquidAdapter.d.cts +42 -0
  357. package/dist/utils/hyperLiquidAdapter.d.cts.map +1 -0
  358. package/dist/utils/hyperLiquidAdapter.d.mts +42 -0
  359. package/dist/utils/hyperLiquidAdapter.d.mts.map +1 -0
  360. package/dist/utils/hyperLiquidAdapter.mjs +316 -0
  361. package/dist/utils/hyperLiquidAdapter.mjs.map +1 -0
  362. package/dist/utils/hyperLiquidOrderBookProcessor.cjs +83 -0
  363. package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +1 -0
  364. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +55 -0
  365. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +1 -0
  366. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +55 -0
  367. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +1 -0
  368. package/dist/utils/hyperLiquidOrderBookProcessor.mjs +78 -0
  369. package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +1 -0
  370. package/dist/utils/hyperLiquidValidation.cjs +426 -0
  371. package/dist/utils/hyperLiquidValidation.cjs.map +1 -0
  372. package/dist/utils/hyperLiquidValidation.d.cts +143 -0
  373. package/dist/utils/hyperLiquidValidation.d.cts.map +1 -0
  374. package/dist/utils/hyperLiquidValidation.d.mts +143 -0
  375. package/dist/utils/hyperLiquidValidation.d.mts.map +1 -0
  376. package/dist/utils/hyperLiquidValidation.mjs +413 -0
  377. package/dist/utils/hyperLiquidValidation.mjs.map +1 -0
  378. package/dist/utils/idUtils.cjs +18 -0
  379. package/dist/utils/idUtils.cjs.map +1 -0
  380. package/dist/utils/idUtils.d.cts +6 -0
  381. package/dist/utils/idUtils.d.cts.map +1 -0
  382. package/dist/utils/idUtils.d.mts +6 -0
  383. package/dist/utils/idUtils.d.mts.map +1 -0
  384. package/dist/utils/idUtils.mjs +10 -0
  385. package/dist/utils/idUtils.mjs.map +1 -0
  386. package/dist/utils/index.cjs +59 -0
  387. package/dist/utils/index.cjs.map +1 -0
  388. package/dist/utils/index.d.cts +25 -0
  389. package/dist/utils/index.d.cts.map +1 -0
  390. package/dist/utils/index.d.mts +25 -0
  391. package/dist/utils/index.d.mts.map +1 -0
  392. package/dist/utils/index.mjs +30 -0
  393. package/dist/utils/index.mjs.map +1 -0
  394. package/dist/utils/marketDataTransform.cjs +211 -0
  395. package/dist/utils/marketDataTransform.cjs.map +1 -0
  396. package/dist/utils/marketDataTransform.d.cts +40 -0
  397. package/dist/utils/marketDataTransform.d.cts.map +1 -0
  398. package/dist/utils/marketDataTransform.d.mts +40 -0
  399. package/dist/utils/marketDataTransform.d.mts.map +1 -0
  400. package/dist/utils/marketDataTransform.mjs +205 -0
  401. package/dist/utils/marketDataTransform.mjs.map +1 -0
  402. package/dist/utils/marketUtils.cjs +151 -0
  403. package/dist/utils/marketUtils.cjs.map +1 -0
  404. package/dist/utils/marketUtils.d.cts +30 -0
  405. package/dist/utils/marketUtils.d.cts.map +1 -0
  406. package/dist/utils/marketUtils.d.mts +30 -0
  407. package/dist/utils/marketUtils.d.mts.map +1 -0
  408. package/dist/utils/marketUtils.mjs +138 -0
  409. package/dist/utils/marketUtils.mjs.map +1 -0
  410. package/dist/utils/myxAdapter.cjs +224 -0
  411. package/dist/utils/myxAdapter.cjs.map +1 -0
  412. package/dist/utils/myxAdapter.d.cts +81 -0
  413. package/dist/utils/myxAdapter.d.cts.map +1 -0
  414. package/dist/utils/myxAdapter.d.mts +81 -0
  415. package/dist/utils/myxAdapter.d.mts.map +1 -0
  416. package/dist/utils/myxAdapter.mjs +213 -0
  417. package/dist/utils/myxAdapter.mjs.map +1 -0
  418. package/dist/utils/orderCalculations.cjs +283 -0
  419. package/dist/utils/orderCalculations.cjs.map +1 -0
  420. package/dist/utils/orderCalculations.d.cts +107 -0
  421. package/dist/utils/orderCalculations.d.cts.map +1 -0
  422. package/dist/utils/orderCalculations.d.mts +107 -0
  423. package/dist/utils/orderCalculations.d.mts.map +1 -0
  424. package/dist/utils/orderCalculations.mjs +274 -0
  425. package/dist/utils/orderCalculations.mjs.map +1 -0
  426. package/dist/utils/rewardsUtils.cjs +98 -0
  427. package/dist/utils/rewardsUtils.cjs.map +1 -0
  428. package/dist/utils/rewardsUtils.d.cts +33 -0
  429. package/dist/utils/rewardsUtils.d.cts.map +1 -0
  430. package/dist/utils/rewardsUtils.d.mts +33 -0
  431. package/dist/utils/rewardsUtils.d.mts.map +1 -0
  432. package/dist/utils/rewardsUtils.mjs +92 -0
  433. package/dist/utils/rewardsUtils.mjs.map +1 -0
  434. package/dist/utils/significantFigures.cjs +88 -0
  435. package/dist/utils/significantFigures.cjs.map +1 -0
  436. package/dist/utils/significantFigures.d.cts +25 -0
  437. package/dist/utils/significantFigures.d.cts.map +1 -0
  438. package/dist/utils/significantFigures.d.mts +25 -0
  439. package/dist/utils/significantFigures.d.mts.map +1 -0
  440. package/dist/utils/significantFigures.mjs +82 -0
  441. package/dist/utils/significantFigures.mjs.map +1 -0
  442. package/dist/utils/sortMarkets.cjs +93 -0
  443. package/dist/utils/sortMarkets.cjs.map +1 -0
  444. package/dist/utils/sortMarkets.d.cts +27 -0
  445. package/dist/utils/sortMarkets.d.cts.map +1 -0
  446. package/dist/utils/sortMarkets.d.mts +27 -0
  447. package/dist/utils/sortMarkets.d.mts.map +1 -0
  448. package/dist/utils/sortMarkets.mjs +88 -0
  449. package/dist/utils/sortMarkets.mjs.map +1 -0
  450. package/dist/utils/standaloneInfoClient.cjs +70 -0
  451. package/dist/utils/standaloneInfoClient.cjs.map +1 -0
  452. package/dist/utils/standaloneInfoClient.d.cts +37 -0
  453. package/dist/utils/standaloneInfoClient.d.cts.map +1 -0
  454. package/dist/utils/standaloneInfoClient.d.mts +37 -0
  455. package/dist/utils/standaloneInfoClient.d.mts.map +1 -0
  456. package/dist/utils/standaloneInfoClient.mjs +64 -0
  457. package/dist/utils/standaloneInfoClient.mjs.map +1 -0
  458. package/dist/utils/stringParseUtils.cjs +18 -0
  459. package/dist/utils/stringParseUtils.cjs.map +1 -0
  460. package/dist/utils/stringParseUtils.d.cts +3 -0
  461. package/dist/utils/stringParseUtils.d.cts.map +1 -0
  462. package/dist/utils/stringParseUtils.d.mts +3 -0
  463. package/dist/utils/stringParseUtils.d.mts.map +1 -0
  464. package/dist/utils/stringParseUtils.mjs +13 -0
  465. package/dist/utils/stringParseUtils.mjs.map +1 -0
  466. package/dist/utils/transferData.cjs +33 -0
  467. package/dist/utils/transferData.cjs.map +1 -0
  468. package/dist/utils/transferData.d.cts +9 -0
  469. package/dist/utils/transferData.d.cts.map +1 -0
  470. package/dist/utils/transferData.d.mts +9 -0
  471. package/dist/utils/transferData.d.mts.map +1 -0
  472. package/dist/utils/transferData.mjs +29 -0
  473. package/dist/utils/transferData.mjs.map +1 -0
  474. package/dist/utils/wait.cjs +6 -0
  475. package/dist/utils/wait.cjs.map +1 -0
  476. package/dist/utils/wait.d.cts +2 -0
  477. package/dist/utils/wait.d.cts.map +1 -0
  478. package/dist/utils/wait.d.mts +2 -0
  479. package/dist/utils/wait.d.mts.map +1 -0
  480. package/dist/utils/wait.mjs +2 -0
  481. package/dist/utils/wait.mjs.map +1 -0
  482. package/package.json +16 -2
@@ -0,0 +1,2199 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _HyperLiquidSubscriptionService_instances, _HyperLiquidSubscriptionService_clientService, _HyperLiquidSubscriptionService_walletService, _HyperLiquidSubscriptionService_hip3Enabled, _HyperLiquidSubscriptionService_enabledDexs, _HyperLiquidSubscriptionService_allowlistMarkets, _HyperLiquidSubscriptionService_blocklistMarkets, _HyperLiquidSubscriptionService_discoveredDexNames, _HyperLiquidSubscriptionService_dexDiscoveryPromise, _HyperLiquidSubscriptionService_dexDiscoveryResolver, _HyperLiquidSubscriptionService_expectedDexs, _HyperLiquidSubscriptionService_initializedDexs, _HyperLiquidSubscriptionService_priceSubscribers, _HyperLiquidSubscriptionService_positionSubscribers, _HyperLiquidSubscriptionService_orderFillSubscribers, _HyperLiquidSubscriptionService_orderSubscribers, _HyperLiquidSubscriptionService_accountSubscribers, _HyperLiquidSubscriptionService_marketDataSubscribers, _HyperLiquidSubscriptionService_orderBookSubscribers, _HyperLiquidSubscriptionService_globalAllMidsSubscription, _HyperLiquidSubscriptionService_globalAllMidsPromise, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, _HyperLiquidSubscriptionService_globalBboSubscriptions, _HyperLiquidSubscriptionService_orderFillSubscriptions, _HyperLiquidSubscriptionService_symbolSubscriberCounts, _HyperLiquidSubscriptionService_dexSubscriberCounts, _HyperLiquidSubscriptionService_webData3Subscriptions, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, _HyperLiquidSubscriptionService_positionSubscriberCount, _HyperLiquidSubscriptionService_orderSubscriberCount, _HyperLiquidSubscriptionService_accountSubscriberCount, _HyperLiquidSubscriptionService_oiCapSubscriberCount, _HyperLiquidSubscriptionService_dexPositionsCache, _HyperLiquidSubscriptionService_dexOrdersCache, _HyperLiquidSubscriptionService_dexAccountCache, _HyperLiquidSubscriptionService_cachedPositions, _HyperLiquidSubscriptionService_cachedOrders, _HyperLiquidSubscriptionService_cachedAccount, _HyperLiquidSubscriptionService_ordersCacheInitialized, _HyperLiquidSubscriptionService_positionsCacheInitialized, _HyperLiquidSubscriptionService_oiCapSubscribers, _HyperLiquidSubscriptionService_cachedOICaps, _HyperLiquidSubscriptionService_cachedOICapsHash, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, _HyperLiquidSubscriptionService_cachedPriceData, _HyperLiquidSubscriptionService_cachedFills, _HyperLiquidSubscriptionService_fillsCacheInitialized, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, _HyperLiquidSubscriptionService_dexAssetCtxsCache, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, _HyperLiquidSubscriptionService_openOrdersSubscriptions, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, _HyperLiquidSubscriptionService_dexMetaCache, _HyperLiquidSubscriptionService_orderBookCache, _HyperLiquidSubscriptionService_marketDataCache, _HyperLiquidSubscriptionService_isClearing, _HyperLiquidSubscriptionService_deps, _HyperLiquidSubscriptionService_logErrorUnlessClearing, _HyperLiquidSubscriptionService_getErrorContext, _HyperLiquidSubscriptionService_isDexEnabled, _HyperLiquidSubscriptionService_waitForDexDiscovery, _HyperLiquidSubscriptionService_hashPositions, _HyperLiquidSubscriptionService_hashOrders, _HyperLiquidSubscriptionService_hashAccountState, _HyperLiquidSubscriptionService_cachedPositionsHash, _HyperLiquidSubscriptionService_cachedOrdersHash, _HyperLiquidSubscriptionService_cachedAccountHash, _HyperLiquidSubscriptionService_extractTPSLFromOrders, _HyperLiquidSubscriptionService_mergeTPSLIntoPositions, _HyperLiquidSubscriptionService_aggregateAccountStates, _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription, _HyperLiquidSubscriptionService_createUserDataSubscription, _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription, _HyperLiquidSubscriptionService_createClearinghouseSubscription, _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription, _HyperLiquidSubscriptionService_createOpenOrdersSubscription, _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers, _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription, _HyperLiquidSubscriptionService_ensureOrderFillISubscription, _HyperLiquidSubscriptionService_createSubscription, _HyperLiquidSubscriptionService_createPriceUpdate, _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription, _HyperLiquidSubscriptionService_ensureActiveAssetSubscription, _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription, _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription, _HyperLiquidSubscriptionService_createAssetCtxsSubscription, _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription, _HyperLiquidSubscriptionService_ensureBboSubscription, _HyperLiquidSubscriptionService_cleanupBboSubscription, _HyperLiquidSubscriptionService_processOrderBookData, _HyperLiquidSubscriptionService_notifyAllPriceSubscribers;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.HyperLiquidSubscriptionService = void 0;
16
+ const perpsConfig_1 = require("../constants/perpsConfig.cjs");
17
+ const accountUtils_1 = require("../utils/accountUtils.cjs");
18
+ const errorUtils_1 = require("../utils/errorUtils.cjs");
19
+ const hyperLiquidAdapter_1 = require("../utils/hyperLiquidAdapter.cjs");
20
+ const hyperLiquidOrderBookProcessor_1 = require("../utils/hyperLiquidOrderBookProcessor.cjs");
21
+ const marketDataTransform_1 = require("../utils/marketDataTransform.cjs");
22
+ /**
23
+ * Service for managing HyperLiquid WebSocket subscriptions
24
+ * Implements singleton subscription architecture with reference counting
25
+ */
26
+ class HyperLiquidSubscriptionService {
27
+ constructor(clientService, walletService, platformDependencies, hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets) {
28
+ _HyperLiquidSubscriptionService_instances.add(this);
29
+ // Service dependencies
30
+ _HyperLiquidSubscriptionService_clientService.set(this, void 0);
31
+ _HyperLiquidSubscriptionService_walletService.set(this, void 0);
32
+ // HIP-3 feature flag support
33
+ _HyperLiquidSubscriptionService_hip3Enabled.set(this, void 0);
34
+ _HyperLiquidSubscriptionService_enabledDexs.set(this, void 0); // DEX identification (maps webData3 indices to DEX names)
35
+ _HyperLiquidSubscriptionService_allowlistMarkets.set(this, void 0); // Market filtering (allowlist)
36
+ _HyperLiquidSubscriptionService_blocklistMarkets.set(this, void 0); // Market filtering (blocklist)
37
+ _HyperLiquidSubscriptionService_discoveredDexNames.set(this, []); // DEX order for mapping webData3 perpDexStates indices
38
+ // DEX discovery synchronization - allows subscriptions to wait for HIP-3 DEX discovery
39
+ _HyperLiquidSubscriptionService_dexDiscoveryPromise.set(this, null);
40
+ _HyperLiquidSubscriptionService_dexDiscoveryResolver.set(this, null);
41
+ // Track DEXs for synchronized position notifications
42
+ // Ensures all DEXs send initial data before notifying subscribers
43
+ _HyperLiquidSubscriptionService_expectedDexs.set(this, new Set());
44
+ _HyperLiquidSubscriptionService_initializedDexs.set(this, new Set());
45
+ // Subscriber collections
46
+ _HyperLiquidSubscriptionService_priceSubscribers.set(this, new Map());
47
+ _HyperLiquidSubscriptionService_positionSubscribers.set(this, new Set());
48
+ // Order fill subscribers keyed by accountId (normalized: undefined -> 'default')
49
+ _HyperLiquidSubscriptionService_orderFillSubscribers.set(this, new Map());
50
+ _HyperLiquidSubscriptionService_orderSubscribers.set(this, new Set());
51
+ _HyperLiquidSubscriptionService_accountSubscribers.set(this, new Set());
52
+ // Track which subscribers want market data
53
+ _HyperLiquidSubscriptionService_marketDataSubscribers.set(this, new Map());
54
+ // Track which subscribers want top-of-book (best bid/ask) data
55
+ _HyperLiquidSubscriptionService_orderBookSubscribers.set(this, new Map());
56
+ // Global singleton subscriptions
57
+ _HyperLiquidSubscriptionService_globalAllMidsSubscription.set(this, void 0);
58
+ _HyperLiquidSubscriptionService_globalAllMidsPromise.set(this, void 0); // Track in-progress subscription
59
+ _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions.set(this, new Map());
60
+ _HyperLiquidSubscriptionService_globalBboSubscriptions.set(this, new Map());
61
+ // Order fill subscriptions keyed by accountId (normalized: undefined -> 'default')
62
+ _HyperLiquidSubscriptionService_orderFillSubscriptions.set(this, new Map());
63
+ _HyperLiquidSubscriptionService_symbolSubscriberCounts.set(this, new Map());
64
+ _HyperLiquidSubscriptionService_dexSubscriberCounts.set(this, new Map()); // Track subscribers per DEX for assetCtxs
65
+ // Multi-DEX webData3 subscription for all user data (positions, orders, account, OI caps)
66
+ _HyperLiquidSubscriptionService_webData3Subscriptions.set(this, new Map()); // Key: dex name ('' for main)
67
+ _HyperLiquidSubscriptionService_webData3SubscriptionPromise.set(this, void 0);
68
+ _HyperLiquidSubscriptionService_positionSubscriberCount.set(this, 0);
69
+ _HyperLiquidSubscriptionService_orderSubscriberCount.set(this, 0);
70
+ _HyperLiquidSubscriptionService_accountSubscriberCount.set(this, 0);
71
+ _HyperLiquidSubscriptionService_oiCapSubscriberCount.set(this, 0);
72
+ // Multi-DEX data caches
73
+ _HyperLiquidSubscriptionService_dexPositionsCache.set(this, new Map()); // Per-DEX positions
74
+ _HyperLiquidSubscriptionService_dexOrdersCache.set(this, new Map()); // Per-DEX orders
75
+ _HyperLiquidSubscriptionService_dexAccountCache.set(this, new Map()); // Per-DEX account state
76
+ _HyperLiquidSubscriptionService_cachedPositions.set(this, null); // Aggregated positions
77
+ _HyperLiquidSubscriptionService_cachedOrders.set(this, null); // Aggregated orders
78
+ _HyperLiquidSubscriptionService_cachedAccount.set(this, null); // Aggregated account
79
+ _HyperLiquidSubscriptionService_ordersCacheInitialized.set(this, false); // Track if orders cache has received WebSocket data
80
+ _HyperLiquidSubscriptionService_positionsCacheInitialized.set(this, false); // Track if positions cache has received WebSocket data
81
+ // OI Cap tracking (from webData3.perpDexStates[].perpsAtOpenInterestCap)
82
+ _HyperLiquidSubscriptionService_oiCapSubscribers.set(this, new Set());
83
+ _HyperLiquidSubscriptionService_cachedOICaps.set(this, []);
84
+ _HyperLiquidSubscriptionService_cachedOICapsHash.set(this, '');
85
+ _HyperLiquidSubscriptionService_oiCapsCacheInitialized.set(this, false);
86
+ // Global price data cache
87
+ _HyperLiquidSubscriptionService_cachedPriceData.set(this, null);
88
+ // Fills cache for cache-first pattern (similar to price caching)
89
+ _HyperLiquidSubscriptionService_cachedFills.set(this, null);
90
+ _HyperLiquidSubscriptionService_fillsCacheInitialized.set(this, false);
91
+ // HIP-3: assetCtxs subscriptions for multi-DEX market data
92
+ _HyperLiquidSubscriptionService_assetCtxsSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
93
+ _HyperLiquidSubscriptionService_dexAssetCtxsCache.set(this, new Map()); // Per-DEX asset contexts
94
+ _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises.set(this, new Map()); // Track in-progress subscriptions
95
+ _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
96
+ _HyperLiquidSubscriptionService_openOrdersSubscriptions.set(this, new Map()); // Key: dex name ('' for main)
97
+ // Pending subscription promises to prevent race conditions
98
+ // When multiple calls to ensure*Subscription happen concurrently, this ensures
99
+ // only one subscription is created per DEX (others wait for the pending promise)
100
+ _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions.set(this, new Map());
101
+ _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions.set(this, new Map());
102
+ // Meta cache per DEX - populated by metaAndAssetCtxs, used by createAssetCtxsSubscription
103
+ // This avoids redundant meta() API calls since metaAndAssetCtxs already returns meta data
104
+ _HyperLiquidSubscriptionService_dexMetaCache.set(this, new Map());
105
+ // Order book data cache
106
+ _HyperLiquidSubscriptionService_orderBookCache.set(this, new Map());
107
+ // Market data caching for multi-channel consolidation
108
+ _HyperLiquidSubscriptionService_marketDataCache.set(this, new Map());
109
+ // Flag to suppress error logging during intentional disconnect
110
+ // Set in clearAll() and never reset (service instance is discarded after disconnect)
111
+ _HyperLiquidSubscriptionService_isClearing.set(this, false);
112
+ // Platform dependencies for logging
113
+ _HyperLiquidSubscriptionService_deps.set(this, void 0);
114
+ // Cache hashes to avoid recomputation
115
+ _HyperLiquidSubscriptionService_cachedPositionsHash.set(this, '');
116
+ _HyperLiquidSubscriptionService_cachedOrdersHash.set(this, '');
117
+ _HyperLiquidSubscriptionService_cachedAccountHash.set(this, '');
118
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_clientService, clientService, "f");
119
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_walletService, walletService, "f");
120
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_deps, platformDependencies, "f");
121
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_hip3Enabled, hip3Enabled ?? false, "f");
122
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_enabledDexs, enabledDexs ?? [], "f");
123
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoveredDexNames, enabledDexs ?? [], "f");
124
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_allowlistMarkets, allowlistMarkets ?? [], "f");
125
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_blocklistMarkets, blocklistMarkets ?? [], "f");
126
+ }
127
+ /**
128
+ * Populate DEX meta cache with pre-fetched meta data
129
+ * Called by Provider after buildAssetMapping to share cached meta,
130
+ * avoiding redundant metaAndAssetCtxs/meta API calls during subscription setup
131
+ *
132
+ * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
133
+ * @param meta - Meta response containing universe data
134
+ * @param meta.universe - The array of asset universe entries from the meta response.
135
+ */
136
+ setDexMetaCache(dex, meta) {
137
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").set(dex, meta);
138
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('[SubscriptionService] DEX meta cache populated', {
139
+ dex: dex || 'main',
140
+ universeSize: meta.universe.length,
141
+ });
142
+ }
143
+ /**
144
+ * Cache asset contexts for a specific DEX from API response
145
+ * This allows buildAssetMapping() to populate cache for getMarketDataWithPrices() to use
146
+ *
147
+ * @param dex - DEX name ('' for main perps)
148
+ * @param assetCtxs - Asset contexts from metaAndAssetCtxs response
149
+ */
150
+ setDexAssetCtxsCache(dex, assetCtxs) {
151
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").set(dex, assetCtxs);
152
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('[SubscriptionService] DEX assetCtxs cache populated', {
153
+ dex: dex || 'main',
154
+ ctxsCount: assetCtxs.length,
155
+ });
156
+ }
157
+ /**
158
+ * Get cached assetCtxs for a DEX
159
+ * Returns the cached asset contexts from WebSocket subscription if available
160
+ *
161
+ * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
162
+ * @returns Array of asset contexts or undefined if not cached
163
+ */
164
+ getDexAssetCtxsCache(dex) {
165
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").get(dex);
166
+ }
167
+ /**
168
+ * Update feature flags for HIP-3 support
169
+ * Called when provider configuration changes at runtime
170
+ * Note: Market filtering is NOT applied in subscription service - only in Provider
171
+ *
172
+ * @param hip3Enabled - Whether HIP-3 multi-DEX support is enabled.
173
+ * @param enabledDexs - The array of enabled DEX identifiers.
174
+ * @param allowlistMarkets - The array of allowed market patterns.
175
+ * @param blocklistMarkets - The array of blocked market patterns.
176
+ */
177
+ async updateFeatureFlags(hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets) {
178
+ const previousEnabledDexs = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f")];
179
+ const previousAllowlistMarkets = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_allowlistMarkets, "f")];
180
+ const previousBlocklistMarkets = [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_blocklistMarkets, "f")];
181
+ const previousHip3Enabled = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f");
182
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_hip3Enabled, hip3Enabled, "f");
183
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_enabledDexs, enabledDexs, "f");
184
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_allowlistMarkets, allowlistMarkets, "f");
185
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_blocklistMarkets, blocklistMarkets, "f");
186
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_discoveredDexNames, enabledDexs, "f"); // Store DEX order for webData3 index mapping
187
+ // Resolve any pending DEX discovery wait now that DEXs are available
188
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, "f") && enabledDexs.length > 0) {
189
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, "f").call(this);
190
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, null, "f");
191
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, null, "f");
192
+ }
193
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Feature flags updated:', {
194
+ previousHip3Enabled,
195
+ hip3Enabled,
196
+ previousEnabledDexs,
197
+ enabledDexs,
198
+ previousAllowlistMarkets,
199
+ allowlistMarkets,
200
+ previousBlocklistMarkets,
201
+ blocklistMarkets,
202
+ });
203
+ // If equity was just enabled or new DEXs were added
204
+ const newDexs = enabledDexs.filter((dex) => !previousEnabledDexs.includes(dex));
205
+ if ((!previousHip3Enabled && hip3Enabled && enabledDexs.length > 0) ||
206
+ newDexs.length > 0) {
207
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Establishing subscriptions for new DEXs:', newDexs);
208
+ // Establish assetCtxs subscriptions for new DEXs (for market data)
209
+ const hasMarketDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0;
210
+ if (hasMarketDataSubscribers) {
211
+ await Promise.all(newDexs.map(async (dex) => {
212
+ try {
213
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dex);
214
+ }
215
+ catch (error) {
216
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.ensureAssetCtxsSubscription', {
217
+ dex,
218
+ }));
219
+ }
220
+ }));
221
+ }
222
+ // Establish clearinghouseState/openOrders subscriptions for new DEXs
223
+ // (needed for positions, orders, and account data when using individual subscriptions)
224
+ const hasUserDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0 ||
225
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") > 0 ||
226
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") > 0;
227
+ if (hasUserDataSubscribers && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")) {
228
+ try {
229
+ const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault();
230
+ await Promise.all(newDexs.map(async (dex) => {
231
+ try {
232
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription).call(this, userAddress, dex);
233
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription).call(this, userAddress, dex);
234
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Established user data subscriptions for new DEX: ${dex}`);
235
+ }
236
+ catch (error) {
237
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.ensureUserDataSubscription', { dex }));
238
+ }
239
+ }));
240
+ }
241
+ catch (error) {
242
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.updateFeatureFlags'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'updateFeatureFlags.getUserAddress'));
243
+ }
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * Subscribe to live price updates with singleton subscription architecture
249
+ * Uses allMids for fast price updates and predictedFundings for accurate funding rates
250
+ *
251
+ * @param params - The subscription parameters including symbols and callbacks.
252
+ * @returns A cleanup function to unsubscribe from price updates.
253
+ */
254
+ async subscribeToPrices(params) {
255
+ const { symbols, callback, includeOrderBook = false, includeMarketData = false, } = params;
256
+ const unsubscribers = [];
257
+ symbols.forEach((symbol) => {
258
+ unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f"), callback, symbol));
259
+ // Track market data subscribers separately
260
+ if (includeMarketData) {
261
+ unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f"), callback, symbol));
262
+ }
263
+ // Track order book subscribers separately
264
+ if (includeOrderBook) {
265
+ unsubscribers.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f"), callback, symbol));
266
+ }
267
+ });
268
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
269
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
270
+ if (!subscriptionClient) {
271
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('SubscriptionClient not available for price subscription');
272
+ return () => unsubscribers.forEach((fn) => fn());
273
+ }
274
+ // Ensure global subscriptions are established
275
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription).call(this);
276
+ // HIP-3: Establish assetCtxs subscriptions ONLY for DEXs with requested symbols
277
+ // Performance: Avoid unnecessary WebSocket connections for unused DEXs
278
+ if (includeMarketData) {
279
+ // Extract unique DEXs from requested symbols
280
+ const dexsNeeded = new Set();
281
+ symbols.forEach((symbol) => {
282
+ const { dex } = (0, hyperLiquidAdapter_1.parseAssetName)(symbol);
283
+ dexsNeeded.add(dex);
284
+ });
285
+ // Only subscribe to DEXs that have requested symbols
286
+ dexsNeeded.forEach((dex) => {
287
+ const dexName = dex ?? '';
288
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dexName).catch((error) => {
289
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToPrices'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToPrices.ensureAssetCtxsSubscription', { dex: dexName }));
290
+ });
291
+ });
292
+ }
293
+ // Note: Funding rates are now cached via assetCtxs WebSocket subscription
294
+ // (ensureAssetCtxsSubscription above), eliminating the need for a separate
295
+ // metaAndAssetCtxs API call here. The WebSocket callback in createAssetCtxsSubscription
296
+ // populates marketDataCache with funding rates as they arrive.
297
+ symbols.forEach((symbol) => {
298
+ // Subscribe to activeAssetCtx only when market data is requested
299
+ if (includeMarketData) {
300
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureActiveAssetSubscription).call(this, symbol);
301
+ }
302
+ if (includeOrderBook) {
303
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureBboSubscription).call(this, symbol);
304
+ }
305
+ });
306
+ // Send cached data immediately if available
307
+ symbols.forEach((symbol) => {
308
+ const cachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol);
309
+ if (cachedPrice) {
310
+ callback([cachedPrice]);
311
+ }
312
+ });
313
+ // Return cleanup function
314
+ return () => {
315
+ unsubscribers.forEach((fn) => fn());
316
+ // Cleanup subscriptions with reference counting
317
+ symbols.forEach((symbol) => {
318
+ if (includeMarketData) {
319
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription).call(this, symbol);
320
+ }
321
+ if (includeOrderBook) {
322
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupBboSubscription).call(this, symbol);
323
+ }
324
+ });
325
+ // Cleanup DEX-level assetCtxs subscriptions
326
+ if (includeMarketData) {
327
+ // Extract unique DEXs from requested symbols
328
+ const dexsNeeded = new Set();
329
+ symbols.forEach((symbol) => {
330
+ const { dex } = (0, hyperLiquidAdapter_1.parseAssetName)(symbol);
331
+ dexsNeeded.add(dex);
332
+ });
333
+ // Cleanup assetCtxs subscription for each DEX
334
+ dexsNeeded.forEach((dex) => {
335
+ const dexName = dex ?? '';
336
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription).call(this, dexName);
337
+ });
338
+ }
339
+ };
340
+ }
341
+ /**
342
+ * Subscribe to live position updates with TP/SL data
343
+ *
344
+ * @param params - The subscription parameters including callback and account ID.
345
+ * @returns A cleanup function to unsubscribe from position updates.
346
+ */
347
+ subscribeToPositions(params) {
348
+ const { callback, accountId } = params;
349
+ const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f"), callback);
350
+ // Increment position subscriber count
351
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") + 1, "f");
352
+ // Immediately provide cached data if available
353
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f")) {
354
+ callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f"));
355
+ }
356
+ // Ensure shared subscription is active
357
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
358
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToPositions'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToPositions'));
359
+ });
360
+ return () => {
361
+ unsubscribe();
362
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") - 1, "f");
363
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
364
+ };
365
+ }
366
+ /**
367
+ * Subscribe to open interest cap updates
368
+ * OI caps are extracted from webData2 subscription (zero additional overhead)
369
+ *
370
+ * @param params - The subscription parameters including callback and account ID.
371
+ * @returns A cleanup function to unsubscribe from OI cap updates.
372
+ */
373
+ subscribeToOICaps(params) {
374
+ const { callback, accountId } = params;
375
+ // Create subscription
376
+ const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f"), callback);
377
+ // Increment OI cap subscriber count
378
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f") + 1, "f");
379
+ // Immediately provide cached data if available
380
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICaps, "f")) {
381
+ callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICaps, "f"));
382
+ }
383
+ // Ensure webData3 subscription is active (OI caps come from webData3)
384
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
385
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOICaps'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOICaps'));
386
+ });
387
+ return () => {
388
+ unsubscribe();
389
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f") - 1, "f");
390
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
391
+ };
392
+ }
393
+ /**
394
+ * Check if OI caps cache has been initialized
395
+ * Useful for preventing UI flashing before first data arrives
396
+ *
397
+ * @returns True if the condition is met.
398
+ */
399
+ isOICapsCacheInitialized() {
400
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, "f");
401
+ }
402
+ /**
403
+ * Subscribe to live order fill updates
404
+ * Shares subscriptions per accountId to avoid duplicate WebSocket connections
405
+ *
406
+ * @param params - The subscription parameters including callback and account ID.
407
+ * @returns A cleanup function to unsubscribe from order fill updates.
408
+ */
409
+ subscribeToOrderFills(params) {
410
+ const { callback, accountId } = params;
411
+ // Normalize accountId: undefined -> 'default' for Map key
412
+ const normalizedAccountId = accountId ?? 'default';
413
+ const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f"), callback, normalizedAccountId);
414
+ // Ensure subscription is established for this accountId
415
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId).catch((error) => {
416
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderFills'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderFills'));
417
+ });
418
+ return () => {
419
+ unsubscribe();
420
+ // If no more subscribers for this accountId, clean up subscription
421
+ const subscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").get(normalizedAccountId);
422
+ if (!subscribers || subscribers.size === 0) {
423
+ const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").get(normalizedAccountId);
424
+ if (subscription) {
425
+ subscription.unsubscribe().catch((error) => {
426
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderFills'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderFills.unsubscribe'));
427
+ });
428
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").delete(normalizedAccountId);
429
+ }
430
+ }
431
+ };
432
+ }
433
+ /**
434
+ * Subscribe to live order updates
435
+ * Uses the shared webData2 subscription to avoid duplicate connections
436
+ *
437
+ * @param params - The subscription parameters including callback and account ID.
438
+ * @returns A cleanup function to unsubscribe from order updates.
439
+ */
440
+ subscribeToOrders(params) {
441
+ const { callback, accountId } = params;
442
+ const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f"), callback);
443
+ // Increment order subscriber count
444
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") + 1, "f");
445
+ // Immediately provide cached data if available
446
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")) {
447
+ callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f"));
448
+ }
449
+ // Ensure shared subscription is active
450
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
451
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrders'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrders'));
452
+ });
453
+ return () => {
454
+ unsubscribe();
455
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") - 1, "f");
456
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
457
+ };
458
+ }
459
+ /**
460
+ * Subscribe to live account updates
461
+ * Uses the shared webData2 subscription to avoid duplicate connections
462
+ *
463
+ * @param params - The subscription parameters including callback and account ID.
464
+ * @returns A cleanup function to unsubscribe from account updates.
465
+ */
466
+ subscribeToAccount(params) {
467
+ const { callback, accountId } = params;
468
+ const unsubscribe = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createSubscription).call(this, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f"), callback);
469
+ // Increment account subscriber count
470
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") + 1, "f");
471
+ // Immediately provide cached data if available
472
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccount, "f")) {
473
+ callback(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccount, "f"));
474
+ }
475
+ // Ensure shared subscription is active (reuses existing connection)
476
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this, accountId).catch((error) => {
477
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToAccount'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToAccount'));
478
+ });
479
+ return () => {
480
+ unsubscribe();
481
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") - 1, "f");
482
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription).call(this);
483
+ };
484
+ }
485
+ /**
486
+ * Check if orders cache has been initialized from WebSocket
487
+ *
488
+ * @returns true if WebSocket has sent at least one update, false otherwise
489
+ */
490
+ isOrdersCacheInitialized() {
491
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, "f");
492
+ }
493
+ /**
494
+ * Check if positions cache has been initialized from WebSocket
495
+ *
496
+ * @returns true if WebSocket has sent at least one update, false otherwise
497
+ */
498
+ isPositionsCacheInitialized() {
499
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, "f");
500
+ }
501
+ /**
502
+ * Get cached positions from WebSocket subscription
503
+ *
504
+ * @returns Cached positions array, or null if not initialized
505
+ */
506
+ getCachedPositions() {
507
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositions, "f");
508
+ }
509
+ /**
510
+ * Get cached orders from WebSocket subscription
511
+ *
512
+ * @returns Cached orders array, or null if not initialized
513
+ */
514
+ getCachedOrders() {
515
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f");
516
+ }
517
+ /**
518
+ * Atomically get cached orders if initialized
519
+ * Prevents race condition between checking initialization and getting data
520
+ *
521
+ * @returns Cached orders array if initialized, null otherwise
522
+ */
523
+ getOrdersCacheIfInitialized() {
524
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, "f")) {
525
+ return null;
526
+ }
527
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrders, "f")] : [];
528
+ }
529
+ /**
530
+ * Get cached price for a symbol from WebSocket allMids subscription
531
+ * OPTIMIZATION: Use this instead of REST infoClient.allMids() to avoid rate limiting
532
+ *
533
+ * @param symbol - Asset symbol (e.g., 'BTC', 'ETH', 'xyz:TSLA')
534
+ * @returns Price string, or undefined if not cached
535
+ */
536
+ getCachedPrice(symbol) {
537
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol)?.price;
538
+ }
539
+ /**
540
+ * Get cached fills from WebSocket userFills subscription
541
+ * OPTIMIZATION: Use this instead of REST userFills() to avoid rate limiting
542
+ *
543
+ * @returns Copy of cached fills array, or null if not cached
544
+ */
545
+ getCachedFills() {
546
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f")] : null;
547
+ }
548
+ /**
549
+ * Get cached fills only if the cache has been initialized from WebSocket
550
+ * OPTIMIZATION: Distinguishes between "not initialized" (null) and "initialized but empty" ([])
551
+ * - Returns null if cache hasn't received WebSocket snapshot yet (caller should use REST)
552
+ * - Returns empty array [] if cache is initialized but user has no fills (caller can skip REST)
553
+ * - Returns fills array if cache has data
554
+ *
555
+ * @returns Fills array or empty array if initialized, null if not yet initialized
556
+ */
557
+ getFillsCacheIfInitialized() {
558
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, "f")) {
559
+ return null;
560
+ }
561
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ? [...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f")] : [];
562
+ }
563
+ /**
564
+ * Subscribe to full order book updates with multiple depth levels
565
+ * Creates a dedicated L2Book subscription for the requested symbol
566
+ * and processes data into OrderBookData format for UI consumption
567
+ *
568
+ * @param params - Subscription parameters
569
+ * @returns Cleanup function to unsubscribe
570
+ */
571
+ subscribeToOrderBook(params) {
572
+ const { symbol, levels = 10, nSigFigs = 5, mantissa, callback, onError, } = params;
573
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f")
574
+ .ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter())
575
+ .catch(() => {
576
+ // Handled by getSubscriptionClient check below
577
+ });
578
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
579
+ if (!subscriptionClient) {
580
+ const error = new Error('Subscription client not available');
581
+ onError?.(error);
582
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('subscribeToOrderBook: Subscription client not available');
583
+ return () => {
584
+ // No-op cleanup
585
+ };
586
+ }
587
+ let subscription;
588
+ let cancelled = false;
589
+ subscriptionClient
590
+ .l2Book({ coin: symbol, nSigFigs, mantissa }, (data) => {
591
+ if (cancelled || data?.coin !== symbol || !data?.levels) {
592
+ return;
593
+ }
594
+ const orderBookData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_processOrderBookData).call(this, data, levels);
595
+ callback(orderBookData);
596
+ })
597
+ .then(async (sub) => {
598
+ if (cancelled) {
599
+ try {
600
+ await sub.unsubscribe();
601
+ }
602
+ catch (unsubError) {
603
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(unsubError, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook.cleanup', { symbol }));
604
+ }
605
+ return undefined;
606
+ }
607
+ subscription = sub;
608
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: Order book subscription established for ${symbol}`);
609
+ return undefined;
610
+ })
611
+ .catch((error) => {
612
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook', { symbol }));
613
+ onError?.((0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'));
614
+ });
615
+ return () => {
616
+ cancelled = true;
617
+ if (subscription) {
618
+ subscription.unsubscribe().catch((error) => {
619
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.subscribeToOrderBook'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'subscribeToOrderBook.unsubscribe', {
620
+ symbol,
621
+ }));
622
+ });
623
+ }
624
+ };
625
+ }
626
+ /**
627
+ * Restore all active subscriptions after WebSocket reconnection
628
+ * Re-establishes WebSocket subscriptions for all active subscribers
629
+ *
630
+ * IMPORTANT: This method verifies transport readiness before attempting
631
+ * any subscriptions to prevent "subscribe error: undefined" errors.
632
+ */
633
+ async restoreSubscriptions() {
634
+ // CRITICAL: Verify transport is ready before attempting any subscriptions
635
+ // This prevents race conditions where subscriptions are attempted while
636
+ // the WebSocket is still in CONNECTING state
637
+ try {
638
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureTransportReady({ timeoutMs: 5000 });
639
+ }
640
+ catch (error) {
641
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Transport not ready during subscription restore, will retry on next reconnect', { error: error instanceof Error ? error.message : String(error) });
642
+ return;
643
+ }
644
+ // Re-establish global allMids subscription if there are price subscribers
645
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").size > 0) {
646
+ // Clear existing subscription reference (it's dead after reconnection)
647
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, undefined, "f");
648
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, undefined, "f");
649
+ // Re-establish the subscription
650
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription).call(this);
651
+ }
652
+ // Re-establish order fill subscriptions if there are fill subscribers
653
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").size > 0) {
654
+ // Clear existing subscription references (they're dead after reconnection)
655
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").clear();
656
+ // Re-establish subscriptions for all accountIds with subscribers
657
+ // Note: normalizedAccountId is 'default' for undefined, need to convert back
658
+ const normalizedAccountIds = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").keys());
659
+ await Promise.all(normalizedAccountIds.map((normalizedAccountId) => {
660
+ // Convert normalized key back to original accountId (undefined if 'default')
661
+ const accountId = normalizedAccountId === 'default'
662
+ ? undefined
663
+ : normalizedAccountId;
664
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId).catch(() => {
665
+ // Ignore errors during order fill subscription restoration
666
+ });
667
+ }));
668
+ }
669
+ // Re-establish user data subscriptions if there are user data subscribers
670
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").size > 0 ||
671
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").size > 0 ||
672
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").size > 0 ||
673
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f").size > 0) {
674
+ // Clear existing subscription references (they're dead after reconnection)
675
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
676
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
677
+ // Clear individual subscriptions (clearinghouseState + openOrders) for HIP-3 mode
678
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
679
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
680
+ // Re-establish the subscription (will use current account)
681
+ // This will set up webData2 for non-HIP-3, or individual subscriptions + webData3 (OI caps only) for HIP-3
682
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription).call(this);
683
+ }
684
+ // Re-establish activeAsset subscriptions if there are market data subscribers
685
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0) {
686
+ // Clear existing subscriptions (they're dead after reconnection)
687
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").clear();
688
+ // Clear reference counts to prevent double-counting after reconnection
689
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").clear();
690
+ // Re-establish subscriptions for all symbols with market data subscribers
691
+ const symbolsNeedingMarketData = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").keys());
692
+ symbolsNeedingMarketData.forEach((symbol) => {
693
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureActiveAssetSubscription).call(this, symbol);
694
+ });
695
+ }
696
+ // Re-establish BBO subscriptions if there are order book subscribers
697
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").size > 0) {
698
+ // Clear existing subscriptions (they're dead after reconnection)
699
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").clear();
700
+ // Re-establish subscriptions for all symbols with order book subscribers
701
+ const symbolsNeedingOrderBook = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").keys());
702
+ symbolsNeedingOrderBook.forEach((symbol) => {
703
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureBboSubscription).call(this, symbol);
704
+ });
705
+ }
706
+ // Re-establish assetCtxs subscriptions if there are market data subscribers
707
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").size > 0) {
708
+ // Clear existing subscriptions (they're dead after reconnection)
709
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").clear();
710
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").clear();
711
+ // Clear reference counts to prevent double-counting after reconnection
712
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").clear();
713
+ // Re-establish subscriptions for all DEXs with market data subscribers
714
+ const dexsNeeded = new Set();
715
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").forEach((_subscribers, symbol) => {
716
+ const { dex } = (0, hyperLiquidAdapter_1.parseAssetName)(symbol);
717
+ if (dex) {
718
+ dexsNeeded.add(dex);
719
+ }
720
+ });
721
+ // Add main DEX if any main DEX symbols have subscribers
722
+ const hasMainDexSubscribers = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").keys()).some((symbol) => {
723
+ const { dex } = (0, hyperLiquidAdapter_1.parseAssetName)(symbol);
724
+ return !dex;
725
+ });
726
+ if (hasMainDexSubscribers) {
727
+ dexsNeeded.add('');
728
+ }
729
+ // Re-establish subscriptions
730
+ await Promise.all(Array.from(dexsNeeded).map((dex) => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription).call(this, dex).catch(() => {
731
+ // Ignore errors during assetCtxs subscription restoration
732
+ })));
733
+ }
734
+ }
735
+ /**
736
+ * Clear all subscriptions and cached data (multi-DEX support)
737
+ */
738
+ clearAll() {
739
+ // Suppress error logging for pending unsubscribe requests during intentional disconnect.
740
+ // The WebSocket will be closed after this, causing pending unsubscribe promises to reject
741
+ // with WebSocketRequestError - these are expected and should not be logged to Sentry.
742
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_isClearing, true, "f");
743
+ // Clear all local subscriber collections
744
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").clear();
745
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").clear();
746
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").clear();
747
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").clear();
748
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").clear();
749
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").clear();
750
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").clear();
751
+ // Clear order fill subscriptions
752
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").forEach((subscription) => {
753
+ subscription.unsubscribe().catch(() => {
754
+ // Ignore errors during cleanup
755
+ });
756
+ });
757
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").clear();
758
+ // Clear cached data
759
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, null, "f");
760
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, null, "f");
761
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, null, "f");
762
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, null, "f");
763
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, null, "f");
764
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, false, "f"); // Reset cache initialization flag
765
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, false, "f"); // Reset cache initialization flag
766
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, false, "f"); // Reset fills cache initialization flag
767
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").clear();
768
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").clear();
769
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").clear();
770
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").clear();
771
+ // Clear hash caches
772
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, '', "f");
773
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, '', "f");
774
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, '', "f");
775
+ // Clear multi-DEX caches
776
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquidSubscriptionService: Clearing per-DEX caches', {
777
+ dexPositionsCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").size,
778
+ dexOrdersCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").size,
779
+ dexAccountCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").size,
780
+ dexAssetCtxsCacheSize: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").size,
781
+ dexPositionsCacheKeys: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").keys()),
782
+ dexAssetCtxsCacheKeys: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").keys()),
783
+ });
784
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").clear();
785
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").clear();
786
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").clear();
787
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").clear();
788
+ // Clear subscription references (actual cleanup handled by client service)
789
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, undefined, "f");
790
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").clear();
791
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").clear();
792
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
793
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
794
+ // HIP-3: Clear assetCtxs subscriptions (clearinghouseState no longer needed with webData3)
795
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").clear();
796
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").clear();
797
+ // Cleanup individual subscriptions (clearinghouseState + openOrders)
798
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").size > 0) {
799
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").forEach((subscription, dexName) => {
800
+ subscription.unsubscribe().catch((error) => {
801
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.clearinghouseState', {
802
+ dex: dexName,
803
+ }));
804
+ });
805
+ });
806
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
807
+ }
808
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").size > 0) {
809
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").forEach((subscription, dexName) => {
810
+ subscription.unsubscribe().catch((error) => {
811
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.clearAll'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'clearAll.openOrders', {
812
+ dex: dexName,
813
+ }));
814
+ });
815
+ });
816
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
817
+ }
818
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquid: Subscription service cleared (multi-DEX with individual subscriptions)', {
819
+ timestamp: new Date().toISOString(),
820
+ });
821
+ }
822
+ }
823
+ exports.HyperLiquidSubscriptionService = HyperLiquidSubscriptionService;
824
+ _HyperLiquidSubscriptionService_clientService = new WeakMap(), _HyperLiquidSubscriptionService_walletService = new WeakMap(), _HyperLiquidSubscriptionService_hip3Enabled = new WeakMap(), _HyperLiquidSubscriptionService_enabledDexs = new WeakMap(), _HyperLiquidSubscriptionService_allowlistMarkets = new WeakMap(), _HyperLiquidSubscriptionService_blocklistMarkets = new WeakMap(), _HyperLiquidSubscriptionService_discoveredDexNames = new WeakMap(), _HyperLiquidSubscriptionService_dexDiscoveryPromise = new WeakMap(), _HyperLiquidSubscriptionService_dexDiscoveryResolver = new WeakMap(), _HyperLiquidSubscriptionService_expectedDexs = new WeakMap(), _HyperLiquidSubscriptionService_initializedDexs = new WeakMap(), _HyperLiquidSubscriptionService_priceSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_positionSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderFillSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_accountSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_marketDataSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_orderBookSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_globalAllMidsSubscription = new WeakMap(), _HyperLiquidSubscriptionService_globalAllMidsPromise = new WeakMap(), _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_globalBboSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_orderFillSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_symbolSubscriberCounts = new WeakMap(), _HyperLiquidSubscriptionService_dexSubscriberCounts = new WeakMap(), _HyperLiquidSubscriptionService_webData3Subscriptions = new WeakMap(), _HyperLiquidSubscriptionService_webData3SubscriptionPromise = new WeakMap(), _HyperLiquidSubscriptionService_positionSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_orderSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_accountSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_oiCapSubscriberCount = new WeakMap(), _HyperLiquidSubscriptionService_dexPositionsCache = new WeakMap(), _HyperLiquidSubscriptionService_dexOrdersCache = new WeakMap(), _HyperLiquidSubscriptionService_dexAccountCache = new WeakMap(), _HyperLiquidSubscriptionService_cachedPositions = new WeakMap(), _HyperLiquidSubscriptionService_cachedOrders = new WeakMap(), _HyperLiquidSubscriptionService_cachedAccount = new WeakMap(), _HyperLiquidSubscriptionService_ordersCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_positionsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_oiCapSubscribers = new WeakMap(), _HyperLiquidSubscriptionService_cachedOICaps = new WeakMap(), _HyperLiquidSubscriptionService_cachedOICapsHash = new WeakMap(), _HyperLiquidSubscriptionService_oiCapsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_cachedPriceData = new WeakMap(), _HyperLiquidSubscriptionService_cachedFills = new WeakMap(), _HyperLiquidSubscriptionService_fillsCacheInitialized = new WeakMap(), _HyperLiquidSubscriptionService_assetCtxsSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_dexAssetCtxsCache = new WeakMap(), _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises = new WeakMap(), _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_openOrdersSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions = new WeakMap(), _HyperLiquidSubscriptionService_dexMetaCache = new WeakMap(), _HyperLiquidSubscriptionService_orderBookCache = new WeakMap(), _HyperLiquidSubscriptionService_marketDataCache = new WeakMap(), _HyperLiquidSubscriptionService_isClearing = new WeakMap(), _HyperLiquidSubscriptionService_deps = new WeakMap(), _HyperLiquidSubscriptionService_cachedPositionsHash = new WeakMap(), _HyperLiquidSubscriptionService_cachedOrdersHash = new WeakMap(), _HyperLiquidSubscriptionService_cachedAccountHash = new WeakMap(), _HyperLiquidSubscriptionService_instances = new WeakSet(), _HyperLiquidSubscriptionService_logErrorUnlessClearing = function _HyperLiquidSubscriptionService_logErrorUnlessClearing(error, context) {
825
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_isClearing, "f")) {
826
+ return;
827
+ }
828
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").logger.error(error, context);
829
+ }, _HyperLiquidSubscriptionService_getErrorContext = function _HyperLiquidSubscriptionService_getErrorContext(method, extra) {
830
+ return {
831
+ tags: {
832
+ feature: perpsConfig_1.PERPS_CONSTANTS.FeatureName,
833
+ provider: 'hyperliquid',
834
+ network: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").isTestnetMode() ? 'testnet' : 'mainnet',
835
+ },
836
+ context: {
837
+ name: 'HyperLiquidSubscriptionService',
838
+ data: {
839
+ method,
840
+ ...extra,
841
+ },
842
+ },
843
+ };
844
+ }, _HyperLiquidSubscriptionService_isDexEnabled = function _HyperLiquidSubscriptionService_isDexEnabled(dex) {
845
+ if (dex === null) {
846
+ return true; // Main DEX always enabled
847
+ }
848
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")) {
849
+ return false; // HIP-3 disabled entirely
850
+ }
851
+ return __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").includes(dex);
852
+ }, _HyperLiquidSubscriptionService_waitForDexDiscovery =
853
+ /**
854
+ * Wait for DEX discovery to complete (with timeout)
855
+ * Used when HIP-3 is enabled but enabledDexs hasn't been populated yet.
856
+ * This allows subscriptions to wait for DEX discovery before creating per-DEX subscriptions.
857
+ *
858
+ * @param timeoutMs - The maximum time in milliseconds to wait for DEX discovery.
859
+ */
860
+ async function _HyperLiquidSubscriptionService_waitForDexDiscovery(timeoutMs = 5000) {
861
+ // Already have DEXs, no need to wait
862
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").length > 0) {
863
+ return;
864
+ }
865
+ // Create promise if not exists
866
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, "f")) {
867
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, new Promise((resolve) => {
868
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_dexDiscoveryResolver, resolve, "f");
869
+ }), "f");
870
+ }
871
+ // Wait with timeout
872
+ let timeoutId;
873
+ const timeoutPromise = new Promise((_resolve, reject) => {
874
+ timeoutId = setTimeout(() => reject(new Error('DEX discovery timeout')), timeoutMs);
875
+ });
876
+ try {
877
+ await Promise.race([__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexDiscoveryPromise, "f"), timeoutPromise]);
878
+ }
879
+ catch {
880
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('DEX discovery wait timed out, proceeding with main DEX only');
881
+ }
882
+ finally {
883
+ if (timeoutId) {
884
+ clearTimeout(timeoutId);
885
+ }
886
+ }
887
+ }, _HyperLiquidSubscriptionService_hashPositions = function _HyperLiquidSubscriptionService_hashPositions(positions) {
888
+ if (!positions || positions.length === 0) {
889
+ return '0';
890
+ }
891
+ return positions
892
+ .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 || ''}`)
893
+ .join('|');
894
+ }, _HyperLiquidSubscriptionService_hashOrders = function _HyperLiquidSubscriptionService_hashOrders(orders) {
895
+ if (!orders || orders.length === 0) {
896
+ return '0';
897
+ }
898
+ return orders
899
+ .map((ord) => `${ord.symbol}:${ord.side}:${ord.size}:${ord.price}:${ord.orderType}`)
900
+ .join('|');
901
+ }, _HyperLiquidSubscriptionService_hashAccountState = function _HyperLiquidSubscriptionService_hashAccountState(account) {
902
+ return `${account.availableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}`;
903
+ }, _HyperLiquidSubscriptionService_extractTPSLFromOrders = function _HyperLiquidSubscriptionService_extractTPSLFromOrders(orders, positions, cachedProcessedOrders) {
904
+ const tpslMap = new Map();
905
+ const tpslCountMap = new Map();
906
+ // If cached processed orders provided, extract TP/SL from them directly
907
+ if (cachedProcessedOrders) {
908
+ cachedProcessedOrders.forEach((order) => {
909
+ // Use triggerPrice for TP/SL (trigger condition price), falling back to price
910
+ // This ensures consistency with raw SDK order processing which uses triggerPx
911
+ const tpslPrice = order.triggerPrice ?? order.price;
912
+ if (order.isTrigger && tpslPrice) {
913
+ const isTakeProfit = order.detailedOrderType?.includes('Take Profit');
914
+ const isStop = order.detailedOrderType?.includes('Stop');
915
+ const matchingPosition = positions.find((pos) => pos.symbol === order.symbol);
916
+ // Determine TP vs SL classification for count and price updates
917
+ // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
918
+ let classifiedAsTakeProfit = isTakeProfit;
919
+ let classifiedAsStop = isStop;
920
+ if (!isTakeProfit && !isStop && matchingPosition) {
921
+ // Fallback: determine based on trigger price vs entry price
922
+ // This handles orders with ambiguous type 'Trigger'
923
+ const triggerPrice = parseFloat(tpslPrice);
924
+ const entryPrice = parseFloat(matchingPosition.entryPrice || '0');
925
+ const isLong = parseFloat(matchingPosition.size) > 0;
926
+ if (isLong) {
927
+ if (triggerPrice > entryPrice) {
928
+ classifiedAsTakeProfit = true;
929
+ }
930
+ else {
931
+ classifiedAsStop = true;
932
+ }
933
+ }
934
+ else if (triggerPrice < entryPrice) {
935
+ classifiedAsTakeProfit = true;
936
+ }
937
+ else {
938
+ classifiedAsStop = true;
939
+ }
940
+ }
941
+ const currentTakeProfitCount = tpslCountMap.get(order.symbol)?.takeProfitCount ?? 0;
942
+ const currentStopLossCount = tpslCountMap.get(order.symbol)?.stopLossCount ?? 0;
943
+ tpslCountMap.set(order.symbol, {
944
+ takeProfitCount: classifiedAsTakeProfit
945
+ ? currentTakeProfitCount + 1
946
+ : currentTakeProfitCount,
947
+ stopLossCount: classifiedAsStop
948
+ ? currentStopLossCount + 1
949
+ : currentStopLossCount,
950
+ });
951
+ if (matchingPosition) {
952
+ const existing = tpslMap.get(order.symbol) ?? {};
953
+ if (classifiedAsTakeProfit) {
954
+ existing.takeProfitPrice = tpslPrice;
955
+ }
956
+ else if (classifiedAsStop) {
957
+ existing.stopLossPrice = tpslPrice;
958
+ }
959
+ tpslMap.set(order.symbol, existing);
960
+ }
961
+ }
962
+ });
963
+ return { tpslMap, tpslCountMap, processedOrders: cachedProcessedOrders };
964
+ }
965
+ // Process raw SDK orders
966
+ const processedOrders = [];
967
+ orders.forEach((order) => {
968
+ let position;
969
+ let positionForCoin;
970
+ const matchPositionToTpsl = (pos) => {
971
+ if (perpsConfig_1.TP_SL_CONFIG.UsePositionBoundTpsl) {
972
+ return (pos.symbol === order.coin &&
973
+ order.reduceOnly &&
974
+ order.isPositionTpsl);
975
+ }
976
+ return (pos.symbol === order.coin &&
977
+ Math.abs(parseFloat(order.sz)) >= Math.abs(parseFloat(pos.size)));
978
+ };
979
+ const matchPositionToCoin = (pos) => pos.symbol === order.coin;
980
+ // Process trigger orders for TP/SL extraction
981
+ if (order.triggerPx) {
982
+ const isTakeProfit = order.orderType?.includes('Take Profit');
983
+ const isStop = order.orderType?.includes('Stop');
984
+ const { coin } = order;
985
+ position = positions.find(matchPositionToTpsl);
986
+ positionForCoin = positions.find(matchPositionToCoin);
987
+ // Determine TP vs SL classification for count and price updates
988
+ // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
989
+ // This matches the cached order processing logic for consistency
990
+ let classifiedAsTakeProfit = isTakeProfit;
991
+ let classifiedAsStop = isStop;
992
+ if (!isTakeProfit && !isStop && position) {
993
+ // Fallback: determine based on trigger price vs entry price
994
+ // This handles orders with ambiguous type 'Trigger'
995
+ const triggerPrice = parseFloat(order.triggerPx);
996
+ const entryPrice = parseFloat(position.entryPrice || '0');
997
+ const isLong = parseFloat(position.size) > 0;
998
+ if (isLong) {
999
+ if (triggerPrice > entryPrice) {
1000
+ classifiedAsTakeProfit = true;
1001
+ }
1002
+ else {
1003
+ classifiedAsStop = true;
1004
+ }
1005
+ }
1006
+ else if (triggerPrice < entryPrice) {
1007
+ classifiedAsTakeProfit = true;
1008
+ }
1009
+ else {
1010
+ classifiedAsStop = true;
1011
+ }
1012
+ }
1013
+ const currentTakeProfitCount = tpslCountMap.get(coin)?.takeProfitCount ?? 0;
1014
+ const currentStopLossCount = tpslCountMap.get(coin)?.stopLossCount ?? 0;
1015
+ tpslCountMap.set(coin, {
1016
+ takeProfitCount: classifiedAsTakeProfit
1017
+ ? currentTakeProfitCount + 1
1018
+ : currentTakeProfitCount,
1019
+ stopLossCount: classifiedAsStop
1020
+ ? currentStopLossCount + 1
1021
+ : currentStopLossCount,
1022
+ });
1023
+ if (position) {
1024
+ const existing = tpslMap.get(coin) ?? {};
1025
+ // Use classified values for price assignment (consistent with count logic)
1026
+ if (classifiedAsTakeProfit) {
1027
+ existing.takeProfitPrice = order.triggerPx;
1028
+ }
1029
+ else if (classifiedAsStop) {
1030
+ existing.stopLossPrice = order.triggerPx;
1031
+ }
1032
+ tpslMap.set(coin, existing);
1033
+ }
1034
+ }
1035
+ // Convert ALL open orders to Order format
1036
+ const convertedOrder = (0, hyperLiquidAdapter_1.adaptOrderFromSDK)(order, position ?? positionForCoin);
1037
+ processedOrders.push(convertedOrder);
1038
+ });
1039
+ return { tpslMap, tpslCountMap, processedOrders };
1040
+ }, _HyperLiquidSubscriptionService_mergeTPSLIntoPositions = function _HyperLiquidSubscriptionService_mergeTPSLIntoPositions(positions, tpslMap, tpslCountMap) {
1041
+ return positions.map((position) => {
1042
+ const tpsl = tpslMap.get(position.symbol) ?? {};
1043
+ const tpslCount = tpslCountMap.get(position.symbol) ?? {};
1044
+ return {
1045
+ ...position,
1046
+ takeProfitPrice: tpsl.takeProfitPrice ?? undefined,
1047
+ stopLossPrice: tpsl.stopLossPrice ?? undefined,
1048
+ takeProfitCount: tpslCount.takeProfitCount ?? 0,
1049
+ stopLossCount: tpslCount.stopLossCount ?? 0,
1050
+ };
1051
+ });
1052
+ }, _HyperLiquidSubscriptionService_aggregateAccountStates = function _HyperLiquidSubscriptionService_aggregateAccountStates() {
1053
+ const subAccountBreakdown = {};
1054
+ let totalAvailableBalance = 0;
1055
+ let totalBalance = 0;
1056
+ let totalMarginUsed = 0;
1057
+ let totalUnrealizedPnl = 0;
1058
+ // Collect account states for weighted ROE calculation
1059
+ const accountStatesForROE = [];
1060
+ // Aggregate all cached account states
1061
+ Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").entries()).forEach(([currentDex, state]) => {
1062
+ const dexKey = currentDex === '' ? 'main' : currentDex;
1063
+ subAccountBreakdown[dexKey] = {
1064
+ availableBalance: state.availableBalance,
1065
+ totalBalance: state.totalBalance,
1066
+ };
1067
+ totalAvailableBalance += parseFloat(state.availableBalance);
1068
+ totalBalance += parseFloat(state.totalBalance);
1069
+ totalMarginUsed += parseFloat(state.marginUsed);
1070
+ totalUnrealizedPnl += parseFloat(state.unrealizedPnl);
1071
+ // Collect data for weighted ROE calculation
1072
+ accountStatesForROE.push({
1073
+ unrealizedPnl: state.unrealizedPnl,
1074
+ returnOnEquity: state.returnOnEquity,
1075
+ });
1076
+ });
1077
+ // Use first DEX's account state as base and override aggregated values
1078
+ const firstDexAccount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").values().next().value ?? {};
1079
+ // Calculate weighted returnOnEquity across all DEXs
1080
+ const returnOnEquity = (0, accountUtils_1.calculateWeightedReturnOnEquity)(accountStatesForROE);
1081
+ return {
1082
+ ...firstDexAccount,
1083
+ availableBalance: totalAvailableBalance.toString(),
1084
+ totalBalance: totalBalance.toString(),
1085
+ marginUsed: totalMarginUsed.toString(),
1086
+ unrealizedPnl: totalUnrealizedPnl.toString(),
1087
+ subAccountBreakdown,
1088
+ returnOnEquity,
1089
+ };
1090
+ }, _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription =
1091
+ /**
1092
+ * Ensure shared webData3 subscription is active (singleton pattern with multi-DEX support)
1093
+ * webData3 provides data for all DEXs (main + HIP-3) in a single subscription
1094
+ *
1095
+ * @param accountId - Optional CAIP account ID to subscribe for.
1096
+ */
1097
+ async function _HyperLiquidSubscriptionService_ensureSharedWebData3Subscription(accountId) {
1098
+ // Establish webData3 subscription (if not exists)
1099
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").has('')) {
1100
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f")) {
1101
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f");
1102
+ }
1103
+ else {
1104
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createUserDataSubscription).call(this, accountId), "f");
1105
+ try {
1106
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, "f");
1107
+ }
1108
+ catch (error) {
1109
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
1110
+ throw error;
1111
+ }
1112
+ }
1113
+ }
1114
+ // Note: webData3 includes all DEX data, so no separate HIP-3 subscriptions needed
1115
+ }, _HyperLiquidSubscriptionService_createUserDataSubscription =
1116
+ /**
1117
+ * Create WebSocket subscription for user data (positions, orders, account)
1118
+ * - Uses webData2 when HIP-3 disabled (main DEX only)
1119
+ * - Uses webData3 when HIP-3 enabled (main + HIP-3 DEXs)
1120
+ *
1121
+ * webData2 provides data for main DEX only
1122
+ * webData3 provides perpDexStates[] array containing data for all DEXs:
1123
+ * - Index 0: Main DEX (dexName = '')
1124
+ * - Index 1+: HIP-3 DEXs in order of enabledDexs array
1125
+ *
1126
+ * @param accountId - Optional CAIP account ID to subscribe for.
1127
+ * @returns A promise that resolves when the operation completes.
1128
+ */
1129
+ async function _HyperLiquidSubscriptionService_createUserDataSubscription(accountId) {
1130
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1131
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1132
+ if (!subscriptionClient) {
1133
+ throw new Error('Subscription client not initialized');
1134
+ }
1135
+ const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
1136
+ const dexName = ''; // Use empty string as key for single subscription
1137
+ // Skip if subscription already exists
1138
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").has(dexName)) {
1139
+ return undefined;
1140
+ }
1141
+ // Wait for DEX discovery if HIP-3 is enabled but DEXs haven't been discovered yet
1142
+ // This ensures HIP-3 subscriptions are created together with main DEX
1143
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f") && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").length === 0) {
1144
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Waiting for DEX discovery before creating subscriptions...');
1145
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_waitForDexDiscovery).call(this);
1146
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('DEX discovery complete, proceeding with subscriptions', {
1147
+ enabledDexs: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f"),
1148
+ });
1149
+ }
1150
+ return new Promise((resolve, reject) => {
1151
+ // Choose channel based on HIP-3 master switch
1152
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_hip3Enabled, "f")) {
1153
+ // HIP-3 enabled: Use individual subscriptions for positions/orders/account
1154
+ // webData3 is only used for OI caps extraction
1155
+ // Determine which DEXs to subscribe to
1156
+ const dexsToSubscribe = [
1157
+ '', // Main DEX
1158
+ ...__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_enabledDexs, "f").filter((dexId) => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isDexEnabled).call(this, dexId)),
1159
+ ];
1160
+ // Track expected DEXs for synchronized notifications
1161
+ // Clear previous tracking and set new expected DEXs
1162
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_expectedDexs, new Set(dexsToSubscribe), "f");
1163
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_initializedDexs, new Set(), "f");
1164
+ // Set up individual subscriptions for each DEX
1165
+ const subscriptionPromises = [];
1166
+ for (const currentDexName of dexsToSubscribe) {
1167
+ // Set up clearinghouseState subscription for positions + account
1168
+ subscriptionPromises.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription).call(this, userAddress, currentDexName));
1169
+ // Set up openOrders subscription for orders
1170
+ subscriptionPromises.push(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription).call(this, userAddress, currentDexName));
1171
+ }
1172
+ // Also set up webData3 for OI caps only
1173
+ const webData3Promise = subscriptionClient
1174
+ .webData3({ user: userAddress }, (data) => {
1175
+ try {
1176
+ // webData3 is ONLY used for OI caps extraction
1177
+ // Positions, orders, and account data come from individual subscriptions
1178
+ const allOICaps = [];
1179
+ data.perpDexStates.forEach((dexState, index) => {
1180
+ // Map webData3 index to DEX name
1181
+ // Index 0 = main DEX (null), Index 1+ = HIP-3 DEXs from discoveredDexNames
1182
+ const dexIdentifier = index === 0 ? null : __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_discoveredDexNames, "f")[index - 1];
1183
+ // Skip unknown DEXs (not in discoveredDexNames) to prevent main DEX cache corruption
1184
+ if (index > 0 && dexIdentifier === undefined) {
1185
+ return; // Unknown DEX - skip to prevent misidentifying as main DEX
1186
+ }
1187
+ // Only process DEXs we care about (skip others silently)
1188
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_isDexEnabled).call(this, dexIdentifier ?? null)) {
1189
+ return; // Skip this DEX - not enabled in our configuration
1190
+ }
1191
+ const currentDexName = dexIdentifier ?? '';
1192
+ const oiCaps = dexState.perpsAtOpenInterestCap ?? [];
1193
+ // Add DEX prefix for HIP-3 symbols (e.g., "xyz:TSLA")
1194
+ if (currentDexName) {
1195
+ allOICaps.push(...oiCaps.map((symbol) => `${currentDexName}:${symbol}`));
1196
+ }
1197
+ else {
1198
+ // Main DEX - no prefix needed
1199
+ allOICaps.push(...oiCaps);
1200
+ }
1201
+ });
1202
+ // Update OI caps cache and notify if changed
1203
+ const oiCapsHash = [...allOICaps]
1204
+ .sort((a, b) => a.localeCompare(b))
1205
+ .join(',');
1206
+ if (oiCapsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, "f")) {
1207
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICaps, allOICaps, "f");
1208
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, oiCapsHash, "f");
1209
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, true, "f");
1210
+ // Notify all subscribers
1211
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f").forEach((callback) => callback(allOICaps));
1212
+ }
1213
+ }
1214
+ catch (error) {
1215
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'webData3 callback error', {
1216
+ user: userAddress,
1217
+ hasPerpDexStates: data?.perpDexStates !== undefined,
1218
+ perpDexStatesLength: data?.perpDexStates?.length ?? 0,
1219
+ }));
1220
+ }
1221
+ })
1222
+ .then((sub) => {
1223
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").set(dexName, sub);
1224
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`webData3 subscription established for OI caps (main + HIP-3)`);
1225
+ return undefined;
1226
+ })
1227
+ .catch((error) => {
1228
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createUserDataSubscription (webData3)', {
1229
+ dex: dexName,
1230
+ }));
1231
+ throw error;
1232
+ });
1233
+ subscriptionPromises.push(webData3Promise);
1234
+ // Wait for all subscriptions to be established
1235
+ Promise.all(subscriptionPromises)
1236
+ .then(() => {
1237
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HIP-3 user data subscriptions established for ${dexsToSubscribe.length} DEXs`);
1238
+ resolve();
1239
+ return undefined;
1240
+ })
1241
+ .catch((error) => {
1242
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createUserDataSubscription (HIP-3)', {
1243
+ dexs: dexsToSubscribe,
1244
+ }));
1245
+ reject((0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'));
1246
+ });
1247
+ }
1248
+ else {
1249
+ // HIP-3 disabled: Use webData2 (main DEX only)
1250
+ subscriptionClient
1251
+ .webData2({ user: userAddress }, (data) => {
1252
+ try {
1253
+ // webData2 returns clearinghouseState for main DEX only
1254
+ const currentDexName = ''; // Main DEX
1255
+ // Check for removed fields before accessing
1256
+ if (!data.clearinghouseState) {
1257
+ return;
1258
+ }
1259
+ // Extract and process positions from clearinghouseState
1260
+ const positions = data.clearinghouseState.assetPositions
1261
+ .filter((assetPos) => assetPos.position.szi !== '0')
1262
+ .map((assetPos) => (0, hyperLiquidAdapter_1.adaptPositionFromSDK)(assetPos));
1263
+ // Extract TP/SL from orders
1264
+ const { tpslMap, tpslCountMap, processedOrders: orders, } = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_extractTPSLFromOrders).call(this, data.openOrders || [], positions);
1265
+ // Merge TP/SL data into positions
1266
+ const positionsWithTPSL = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_mergeTPSLIntoPositions).call(this, positions, tpslMap, tpslCountMap);
1267
+ // Extract account data (webData2 provides clearinghouseState)
1268
+ const accountState = (0, hyperLiquidAdapter_1.adaptAccountStateFromSDK)(data.clearinghouseState, undefined);
1269
+ // Store in caches (main DEX only)
1270
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").set(currentDexName, positionsWithTPSL);
1271
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").set(currentDexName, orders);
1272
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").set(currentDexName, accountState);
1273
+ // OI caps (main DEX only)
1274
+ const oiCaps = data.perpsAtOpenInterestCap ?? [];
1275
+ const oiCapsHash = [...oiCaps]
1276
+ .sort((a, b) => a.localeCompare(b))
1277
+ .join(',');
1278
+ if (oiCapsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, "f")) {
1279
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICaps, oiCaps, "f");
1280
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOICapsHash, oiCapsHash, "f");
1281
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapsCacheInitialized, true, "f");
1282
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscribers, "f").forEach((callback) => callback(oiCaps));
1283
+ }
1284
+ // Notify subscribers (no aggregation needed - only main DEX)
1285
+ const positionsHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashPositions).call(this, positionsWithTPSL);
1286
+ const ordersHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashOrders).call(this, orders);
1287
+ const accountHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashAccountState).call(this, accountState);
1288
+ if (positionsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, "f")) {
1289
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, positionsWithTPSL, "f");
1290
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, positionsHash, "f");
1291
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, true, "f");
1292
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").forEach((callback) => callback(positionsWithTPSL));
1293
+ }
1294
+ if (ordersHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, "f")) {
1295
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, orders, "f");
1296
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, ordersHash, "f");
1297
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, true, "f");
1298
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").forEach((callback) => callback(orders));
1299
+ }
1300
+ if (accountHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccountHash, "f")) {
1301
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, accountState, "f");
1302
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, accountHash, "f");
1303
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").forEach((callback) => callback(accountState));
1304
+ }
1305
+ }
1306
+ catch (error) {
1307
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'webData2 callback error', {
1308
+ user: userAddress,
1309
+ dataKeys: data ? Object.keys(data) : 'data is null/undefined',
1310
+ hasClearinghouseState: data?.clearinghouseState !== undefined,
1311
+ hasOpenOrders: data?.openOrders !== undefined,
1312
+ hasPerpsAtOpenInterestCap: data?.perpsAtOpenInterestCap !== undefined,
1313
+ }));
1314
+ }
1315
+ })
1316
+ .then((subscription) => {
1317
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").set(dexName, subscription);
1318
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('webData2 subscription established for main DEX only');
1319
+ resolve();
1320
+ return undefined;
1321
+ })
1322
+ .catch((error) => {
1323
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createUserDataSubscription (webData2)', {
1324
+ dex: dexName,
1325
+ }));
1326
+ reject((0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createUserDataSubscription'));
1327
+ });
1328
+ }
1329
+ });
1330
+ }, _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription =
1331
+ /**
1332
+ * Ensure clearinghouseState subscription exists for a DEX
1333
+ * Uses pending promise tracking to prevent race conditions where multiple
1334
+ * concurrent calls could create duplicate subscriptions
1335
+ *
1336
+ * @param userAddress - The user's wallet address.
1337
+ * @param dexName - The DEX identifier (empty string for main DEX).
1338
+ * @returns A promise that resolves when the subscription is established.
1339
+ */
1340
+ async function _HyperLiquidSubscriptionService_ensureClearinghouseStateSubscription(userAddress, dexName) {
1341
+ // Already subscribed
1342
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").has(dexName)) {
1343
+ return;
1344
+ }
1345
+ // Another call is already in progress - wait for it instead of creating duplicate
1346
+ const pending = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").get(dexName);
1347
+ if (pending) {
1348
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`[ensureClearinghouseStateSubscription] Waiting for pending subscription for DEX: ${dexName || 'main'}`);
1349
+ await pending;
1350
+ return;
1351
+ }
1352
+ // Create subscription promise and track it
1353
+ const subscriptionPromise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createClearinghouseSubscription).call(this, userAddress, dexName);
1354
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").set(dexName, subscriptionPromise);
1355
+ try {
1356
+ await subscriptionPromise;
1357
+ }
1358
+ finally {
1359
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").delete(dexName);
1360
+ }
1361
+ }, _HyperLiquidSubscriptionService_createClearinghouseSubscription =
1362
+ /**
1363
+ * Create the actual clearinghouseState subscription
1364
+ * Separated from ensureClearinghouseStateSubscription to enable promise deduplication
1365
+ *
1366
+ * @param userAddress - The user's wallet address.
1367
+ * @param dexName - The DEX identifier (empty string for main DEX).
1368
+ */
1369
+ async function _HyperLiquidSubscriptionService_createClearinghouseSubscription(userAddress, dexName) {
1370
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1371
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1372
+ if (!subscriptionClient) {
1373
+ throw new Error('Subscription client not available');
1374
+ }
1375
+ try {
1376
+ const subscription = await subscriptionClient.clearinghouseState({
1377
+ user: userAddress,
1378
+ dex: dexName || undefined, // Empty string -> undefined for main DEX
1379
+ }, (data) => {
1380
+ const cacheKey = data.dex || '';
1381
+ // Update caches and notify subscribers if we have positions/account subscribers
1382
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0 ||
1383
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") > 0) {
1384
+ // Process positions from clearinghouse state
1385
+ const positions = data.clearinghouseState.assetPositions
1386
+ .filter((assetPos) => assetPos.position.szi !== '0')
1387
+ .map((assetPos) => (0, hyperLiquidAdapter_1.adaptPositionFromSDK)(assetPos));
1388
+ // Get cached orders to preserve TP/SL data (prevents flickering)
1389
+ // Orders are cached by openOrders subscription
1390
+ const cachedOrders = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").get(cacheKey) ?? [];
1391
+ // Re-extract TP/SL from cached orders for the new positions
1392
+ // This ensures TP/SL data persists across clearinghouseState updates
1393
+ let positionsWithTPSL = positions;
1394
+ if (cachedOrders.length > 0) {
1395
+ const { tpslMap, tpslCountMap } = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_extractTPSLFromOrders).call(this, [], positions, cachedOrders);
1396
+ positionsWithTPSL = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_mergeTPSLIntoPositions).call(this, positions, tpslMap, tpslCountMap);
1397
+ }
1398
+ // Update account state
1399
+ const accountState = (0, hyperLiquidAdapter_1.adaptAccountStateFromSDK)(data.clearinghouseState, undefined);
1400
+ // Update caches
1401
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").set(cacheKey, positionsWithTPSL);
1402
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").set(cacheKey, accountState);
1403
+ // Mark this DEX as initialized (has sent first data)
1404
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").add(cacheKey);
1405
+ // Trigger aggregation and notify subscribers
1406
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1407
+ }
1408
+ });
1409
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").set(dexName, subscription);
1410
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`clearinghouseState subscription established for DEX: ${dexName || 'main'}`);
1411
+ }
1412
+ catch (error) {
1413
+ // Remove this DEX from expected set so it doesn't block notifications for other DEXs
1414
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").delete(dexName);
1415
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createClearinghouseSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureClearinghouseStateSubscription', {
1416
+ dex: dexName,
1417
+ }));
1418
+ throw error;
1419
+ }
1420
+ }, _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription =
1421
+ /**
1422
+ * Ensure openOrders subscription exists for a DEX
1423
+ * Uses pending promise tracking to prevent race conditions where multiple
1424
+ * concurrent calls could create duplicate subscriptions
1425
+ *
1426
+ * @param userAddress - The user's wallet address.
1427
+ * @param dexName - The DEX identifier (empty string for main DEX).
1428
+ * @returns A promise that resolves when the subscription is established.
1429
+ */
1430
+ async function _HyperLiquidSubscriptionService_ensureOpenOrdersSubscription(userAddress, dexName) {
1431
+ // Already subscribed
1432
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").has(dexName)) {
1433
+ return;
1434
+ }
1435
+ // Another call is already in progress - wait for it instead of creating duplicate
1436
+ const pending = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").get(dexName);
1437
+ if (pending) {
1438
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`[ensureOpenOrdersSubscription] Waiting for pending subscription for DEX: ${dexName || 'main'}`);
1439
+ await pending;
1440
+ return;
1441
+ }
1442
+ // Create subscription promise and track it
1443
+ const subscriptionPromise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createOpenOrdersSubscription).call(this, userAddress, dexName);
1444
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").set(dexName, subscriptionPromise);
1445
+ try {
1446
+ await subscriptionPromise;
1447
+ }
1448
+ finally {
1449
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").delete(dexName);
1450
+ }
1451
+ }, _HyperLiquidSubscriptionService_createOpenOrdersSubscription =
1452
+ /**
1453
+ * Create the actual openOrders subscription
1454
+ * Separated from ensureOpenOrdersSubscription to enable promise deduplication
1455
+ *
1456
+ * @param userAddress - The user's wallet address.
1457
+ * @param dexName - The DEX identifier (empty string for main DEX).
1458
+ */
1459
+ async function _HyperLiquidSubscriptionService_createOpenOrdersSubscription(userAddress, dexName) {
1460
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1461
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1462
+ if (!subscriptionClient) {
1463
+ throw new Error('Subscription client not available');
1464
+ }
1465
+ try {
1466
+ const subscription = await subscriptionClient.openOrders({
1467
+ user: userAddress,
1468
+ dex: dexName || undefined, // Empty string -> undefined for main DEX
1469
+ }, (data) => {
1470
+ const cacheKey = data.dex || '';
1471
+ // Update caches and notify subscribers if we have order subscribers
1472
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") > 0 ||
1473
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") > 0) {
1474
+ // Get cached positions for TP/SL processing
1475
+ const cachedPositions = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").get(cacheKey) ?? [];
1476
+ // Extract TP/SL and process orders
1477
+ const { tpslMap, tpslCountMap, processedOrders: orders, } = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_extractTPSLFromOrders).call(this, data.orders, cachedPositions);
1478
+ // Update orders cache with processed orders
1479
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").set(cacheKey, orders);
1480
+ // Update positions with TP/SL if we have positions
1481
+ if (cachedPositions.length > 0) {
1482
+ const positionsWithTPSL = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_mergeTPSLIntoPositions).call(this, cachedPositions, tpslMap, tpslCountMap);
1483
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").set(cacheKey, positionsWithTPSL);
1484
+ }
1485
+ // Mark this DEX as initialized (has sent first data)
1486
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").add(cacheKey);
1487
+ // Trigger aggregation and notify subscribers
1488
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers).call(this);
1489
+ }
1490
+ });
1491
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").set(dexName, subscription);
1492
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`openOrders subscription established for DEX: ${dexName || 'main'}`);
1493
+ }
1494
+ catch (error) {
1495
+ // Remove this DEX from expected set so it doesn't block notifications for other DEXs
1496
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").delete(dexName);
1497
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createOpenOrdersSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureOpenOrdersSubscription', {
1498
+ dex: dexName,
1499
+ }));
1500
+ throw error;
1501
+ }
1502
+ }, _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers = function _HyperLiquidSubscriptionService_aggregateAndNotifySubscribers() {
1503
+ // Wait for all expected DEXs to send initial data before notifying
1504
+ // This ensures positions from all DEXs appear simultaneously
1505
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").size > 0) {
1506
+ const allDexsInitialized = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f")).every((dex) => __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").has(dex));
1507
+ if (!allDexsInitialized) {
1508
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('Waiting for all DEXs to send initial data', {
1509
+ expected: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f")),
1510
+ initialized: Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f")),
1511
+ });
1512
+ return; // Don't notify yet - waiting for more DEXs
1513
+ }
1514
+ }
1515
+ // Aggregate data from all DEX caches
1516
+ // Order: Main DEX (crypto perps) first, then HIP-3 DEXs
1517
+ const mainDexPositions = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").get('') ?? [];
1518
+ const hip3DexPositions = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").entries())
1519
+ .filter(([key]) => key !== '')
1520
+ .flatMap(([, positions]) => positions);
1521
+ const aggregatedPositions = [...mainDexPositions, ...hip3DexPositions];
1522
+ const mainDexOrders = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").get('') ?? [];
1523
+ const hip3DexOrders = Array.from(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").entries())
1524
+ .filter(([key]) => key !== '')
1525
+ .flatMap(([, orders]) => orders);
1526
+ const aggregatedOrders = [...mainDexOrders, ...hip3DexOrders];
1527
+ const aggregatedAccount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_aggregateAccountStates).call(this);
1528
+ // Check if aggregated data changed using fast hash comparison
1529
+ const positionsHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashPositions).call(this, aggregatedPositions);
1530
+ const ordersHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashOrders).call(this, aggregatedOrders);
1531
+ const accountHash = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_hashAccountState).call(this, aggregatedAccount);
1532
+ const positionsChanged = positionsHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, "f");
1533
+ const ordersChanged = ordersHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, "f");
1534
+ const accountChanged = accountHash !== __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedAccountHash, "f");
1535
+ // Only notify subscribers if aggregated data changed
1536
+ if (positionsChanged) {
1537
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, aggregatedPositions, "f");
1538
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, positionsHash, "f");
1539
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, true, "f"); // Mark cache as initialized
1540
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscribers, "f").forEach((callback) => {
1541
+ callback(aggregatedPositions);
1542
+ });
1543
+ }
1544
+ if (ordersChanged) {
1545
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, aggregatedOrders, "f");
1546
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, ordersHash, "f");
1547
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, true, "f"); // Mark cache as initialized
1548
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscribers, "f").forEach((callback) => {
1549
+ callback(aggregatedOrders);
1550
+ });
1551
+ }
1552
+ if (accountChanged) {
1553
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, aggregatedAccount, "f");
1554
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, accountHash, "f");
1555
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscribers, "f").forEach((callback) => {
1556
+ callback(aggregatedAccount);
1557
+ });
1558
+ }
1559
+ }, _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription = function _HyperLiquidSubscriptionService_cleanupSharedWebData3ISubscription() {
1560
+ const totalSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, "f") +
1561
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, "f") +
1562
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, "f") +
1563
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, "f");
1564
+ if (totalSubscribers <= 0) {
1565
+ // Cleanup webData3 subscription (covers all DEXs)
1566
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").size > 0) {
1567
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").forEach((subscription, dexName) => {
1568
+ subscription.unsubscribe().catch((error) => {
1569
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.webData3', {
1570
+ dex: dexName,
1571
+ }));
1572
+ });
1573
+ });
1574
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_webData3Subscriptions, "f").clear();
1575
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_webData3SubscriptionPromise, undefined, "f");
1576
+ }
1577
+ // Cleanup individual subscriptions (clearinghouseState + openOrders)
1578
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").size > 0) {
1579
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").forEach((subscription, dexName) => {
1580
+ subscription.unsubscribe().catch((error) => {
1581
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.clearinghouseState', {
1582
+ dex: dexName,
1583
+ }));
1584
+ });
1585
+ });
1586
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clearinghouseStateSubscriptions, "f").clear();
1587
+ }
1588
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").size > 0) {
1589
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").forEach((subscription, dexName) => {
1590
+ subscription.unsubscribe().catch((error) => {
1591
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupSharedWebData3ISubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupSharedWebData3ISubscription.openOrders', {
1592
+ dex: dexName,
1593
+ }));
1594
+ });
1595
+ });
1596
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_openOrdersSubscriptions, "f").clear();
1597
+ }
1598
+ // Clear pending subscription promises (race condition prevention)
1599
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingClearinghouseSubscriptions, "f").clear();
1600
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_pendingOpenOrdersSubscriptions, "f").clear();
1601
+ // Clear subscriber counts
1602
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionSubscriberCount, 0, "f");
1603
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_orderSubscriberCount, 0, "f");
1604
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_accountSubscriberCount, 0, "f");
1605
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_oiCapSubscriberCount, 0, "f");
1606
+ // Clear per-DEX caches
1607
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexPositionsCache, "f").clear();
1608
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexOrdersCache, "f").clear();
1609
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAccountCache, "f").clear();
1610
+ // Clear DEX tracking for synchronized notifications
1611
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_expectedDexs, "f").clear();
1612
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_initializedDexs, "f").clear();
1613
+ // Clear aggregated caches
1614
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositions, null, "f");
1615
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrders, null, "f");
1616
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccount, null, "f");
1617
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_ordersCacheInitialized, false, "f"); // Reset cache initialization flag
1618
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_positionsCacheInitialized, false, "f"); // Reset cache initialization flag
1619
+ // Clear hash caches
1620
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPositionsHash, '', "f");
1621
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedOrdersHash, '', "f");
1622
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedAccountHash, '', "f");
1623
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('All multi-DEX subscriptions cleaned up (webData2/3 + individual subscriptions)');
1624
+ }
1625
+ }, _HyperLiquidSubscriptionService_ensureOrderFillISubscription =
1626
+ /**
1627
+ * Ensure order fill subscription is active for the given accountId
1628
+ * Shares subscription across all callbacks for the same accountId
1629
+ *
1630
+ * @param accountId - Optional CAIP account ID to subscribe for.
1631
+ * @returns A promise that resolves when the subscription is established.
1632
+ */
1633
+ async function _HyperLiquidSubscriptionService_ensureOrderFillISubscription(accountId) {
1634
+ // Normalize accountId: undefined -> 'default' for Map key
1635
+ const normalizedAccountId = accountId ?? 'default';
1636
+ // If subscription already exists, no need to create another
1637
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").has(normalizedAccountId)) {
1638
+ return;
1639
+ }
1640
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1641
+ if (!subscriptionClient) {
1642
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1643
+ const client = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1644
+ if (!client) {
1645
+ throw new Error('SubscriptionClient not available');
1646
+ }
1647
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_ensureOrderFillISubscription).call(this, accountId);
1648
+ return;
1649
+ }
1650
+ const userAddress = await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").getUserAddressWithDefault(accountId);
1651
+ // userFills returns a Promise<ISubscription>, need to await it
1652
+ const subscription = await subscriptionClient.userFills({ user: userAddress }, (data) => {
1653
+ const orderFills = data.fills.map((fill) => ({
1654
+ orderId: fill.oid.toString(),
1655
+ symbol: fill.coin,
1656
+ side: fill.side,
1657
+ size: fill.sz,
1658
+ price: fill.px,
1659
+ fee: fill.fee,
1660
+ timestamp: fill.time,
1661
+ pnl: fill.closedPnl,
1662
+ direction: fill.dir,
1663
+ feeToken: fill.feeToken,
1664
+ startPosition: fill.startPosition,
1665
+ liquidation: fill.liquidation
1666
+ ? {
1667
+ liquidatedUser: fill.liquidation.liquidatedUser,
1668
+ markPx: fill.liquidation.markPx,
1669
+ method: fill.liquidation.method,
1670
+ }
1671
+ : undefined,
1672
+ }));
1673
+ // Cache fills for cache-first pattern (similar to price caching)
1674
+ // This allows getOrFetchFills() to return cached data without REST API calls
1675
+ if (data.isSnapshot) {
1676
+ // Snapshot: replace cache with initial historical data, sorted newest first
1677
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, [...orderFills]
1678
+ .sort((a, b) => b.timestamp - a.timestamp)
1679
+ .slice(0, 100), "f");
1680
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_fillsCacheInitialized, true, "f");
1681
+ }
1682
+ else {
1683
+ // Streaming: prepend new fills to existing (newest first)
1684
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedFills, [
1685
+ ...orderFills,
1686
+ ...(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedFills, "f") ?? []),
1687
+ ].slice(0, 100), "f");
1688
+ }
1689
+ // Distribute to all callbacks for this accountId
1690
+ const subscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscribers, "f").get(normalizedAccountId);
1691
+ if (subscribers) {
1692
+ subscribers.forEach((callback) => {
1693
+ callback(orderFills, data.isSnapshot);
1694
+ });
1695
+ }
1696
+ });
1697
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderFillSubscriptions, "f").set(normalizedAccountId, subscription);
1698
+ }, _HyperLiquidSubscriptionService_createSubscription = function _HyperLiquidSubscriptionService_createSubscription(subscribers, callback, key) {
1699
+ if (subscribers instanceof Map && key) {
1700
+ if (!subscribers.has(key)) {
1701
+ subscribers.set(key, new Set());
1702
+ }
1703
+ subscribers.get(key)?.add(callback);
1704
+ }
1705
+ else if (subscribers instanceof Set) {
1706
+ subscribers.add(callback);
1707
+ }
1708
+ return () => {
1709
+ if (subscribers instanceof Map && key) {
1710
+ const set = subscribers.get(key);
1711
+ set?.delete(callback);
1712
+ if (set?.size === 0) {
1713
+ subscribers.delete(key);
1714
+ }
1715
+ }
1716
+ else if (subscribers instanceof Set) {
1717
+ subscribers.delete(callback);
1718
+ }
1719
+ };
1720
+ }, _HyperLiquidSubscriptionService_createPriceUpdate = function _HyperLiquidSubscriptionService_createPriceUpdate(symbol, price) {
1721
+ const marketData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").get(symbol);
1722
+ const orderBookData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").get(symbol);
1723
+ const currentPrice = parseFloat(price);
1724
+ let percentChange24h;
1725
+ if (marketData?.prevDayPx !== undefined) {
1726
+ const change = ((currentPrice - marketData.prevDayPx) / marketData.prevDayPx) * 100;
1727
+ percentChange24h = change.toFixed(2);
1728
+ }
1729
+ // Check if any subscriber for this symbol wants market data
1730
+ const hasMarketDataSubscribers = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").has(symbol) &&
1731
+ (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataSubscribers, "f").get(symbol)?.size ?? 0) > 0;
1732
+ const priceUpdate = {
1733
+ symbol,
1734
+ price, // This is the mid price from allMids
1735
+ timestamp: Date.now(),
1736
+ percentChange24h,
1737
+ // Add mark price from activeAssetCtx
1738
+ markPrice: marketData?.oraclePrice
1739
+ ? marketData.oraclePrice.toString()
1740
+ : undefined,
1741
+ // Add order book data if available
1742
+ bestBid: orderBookData?.bestBid,
1743
+ bestAsk: orderBookData?.bestAsk,
1744
+ spread: orderBookData?.spread,
1745
+ // Always include funding when available (don't default to 0, preserve undefined)
1746
+ funding: marketData?.funding,
1747
+ // Add market data only if requested by at least one subscriber
1748
+ openInterest: hasMarketDataSubscribers
1749
+ ? marketData?.openInterest
1750
+ : undefined,
1751
+ volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,
1752
+ };
1753
+ return priceUpdate;
1754
+ }, _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription = function _HyperLiquidSubscriptionService_ensureGlobalAllMidsSubscription() {
1755
+ // Check both the subscription AND the promise to prevent race conditions
1756
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, "f") ?? __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, "f")) {
1757
+ return;
1758
+ }
1759
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1760
+ if (!subscriptionClient) {
1761
+ return;
1762
+ }
1763
+ // Track WebSocket metrics
1764
+ const wsMetrics = {
1765
+ messagesReceived: 0,
1766
+ lastMessageTime: Date.now(),
1767
+ reconnectCount: 0,
1768
+ startTime: Date.now(),
1769
+ };
1770
+ // Store the promise immediately to prevent duplicate calls
1771
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, subscriptionClient
1772
+ .allMids((data) => {
1773
+ wsMetrics.messagesReceived += 1;
1774
+ wsMetrics.lastMessageTime = Date.now();
1775
+ // Initialize cache if needed
1776
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
1777
+ const subscribedSymbols = new Set();
1778
+ // Collect all symbols that have subscribers
1779
+ for (const [symbol, subscriberSet,] of __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").entries()) {
1780
+ if (subscriberSet.size > 0) {
1781
+ subscribedSymbols.add(symbol);
1782
+ }
1783
+ }
1784
+ // Track if any subscribed symbol was updated
1785
+ let hasUpdates = false;
1786
+ // Only process symbols that are actually subscribed to
1787
+ for (const symbol in data.mids) {
1788
+ // Skip if nobody is subscribed to this symbol
1789
+ if (!subscribedSymbols.has(symbol)) {
1790
+ continue;
1791
+ }
1792
+ const price = data.mids[symbol].toString();
1793
+ const cachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").get(symbol);
1794
+ // Skip if price hasn't changed
1795
+ if (cachedPrice?.price === price) {
1796
+ continue;
1797
+ }
1798
+ // Price changed or new symbol - update cache
1799
+ const priceUpdate = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, price);
1800
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, priceUpdate);
1801
+ hasUpdates = true;
1802
+ }
1803
+ // Only notify subscribers if we actually have updates
1804
+ // This prevents unnecessary React re-renders when prices haven't changed
1805
+ if (hasUpdates) {
1806
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
1807
+ }
1808
+ })
1809
+ .then((sub) => {
1810
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsSubscription, sub, "f");
1811
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log('HyperLiquid: Global allMids subscription established');
1812
+ // Notify existing subscribers with any cached data now that subscription is established
1813
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") && __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").size > 0) {
1814
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
1815
+ }
1816
+ return undefined;
1817
+ })
1818
+ .catch((error) => {
1819
+ // Clear the promise on error so it can be retried
1820
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_globalAllMidsPromise, undefined, "f");
1821
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureGlobalAllMidsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureGlobalAllMidsSubscription'));
1822
+ }), "f");
1823
+ }, _HyperLiquidSubscriptionService_ensureActiveAssetSubscription = function _HyperLiquidSubscriptionService_ensureActiveAssetSubscription(symbol) {
1824
+ // Increment subscriber count
1825
+ const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").get(symbol) ?? 0;
1826
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").set(symbol, currentCount + 1);
1827
+ // If subscription already exists, just return
1828
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").has(symbol)) {
1829
+ return;
1830
+ }
1831
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1832
+ if (!subscriptionClient) {
1833
+ return;
1834
+ }
1835
+ // Track metrics for this subscription
1836
+ const subscriptionMetrics = {
1837
+ messagesReceived: 0,
1838
+ startTime: Date.now(),
1839
+ };
1840
+ subscriptionClient
1841
+ .activeAssetCtx({ coin: symbol }, (data) => {
1842
+ subscriptionMetrics.messagesReceived += 1;
1843
+ if (data.coin === symbol && data.ctx) {
1844
+ // Type guard using SDK types: check if this is perps (has funding) or spot (no funding)
1845
+ const isPerpsContext = (event) => 'funding' in event.ctx &&
1846
+ 'openInterest' in event.ctx &&
1847
+ 'oraclePx' in event.ctx;
1848
+ const { ctx } = data;
1849
+ // Cache market data for consolidation with price updates
1850
+ const ctxPrice = ctx.midPx ?? ctx.markPx;
1851
+ const openInterestUSD = isPerpsContext(data) && ctxPrice
1852
+ ? (0, marketDataTransform_1.calculateOpenInterestUSD)(data.ctx.openInterest, ctxPrice)
1853
+ : NaN;
1854
+ const marketData = {
1855
+ prevDayPx: ctx.prevDayPx
1856
+ ? parseFloat(ctx.prevDayPx.toString())
1857
+ : undefined,
1858
+ // Cache funding rate from activeAssetCtx for real-time updates
1859
+ // SDK defines funding as string (not nullable) in ActiveAssetCtxEvent
1860
+ funding: isPerpsContext(data)
1861
+ ? parseFloat(data.ctx.funding.toString())
1862
+ : undefined,
1863
+ openInterest: isNaN(openInterestUSD)
1864
+ ? undefined
1865
+ : openInterestUSD,
1866
+ volume24h: ctx.dayNtlVlm
1867
+ ? parseFloat(ctx.dayNtlVlm.toString())
1868
+ : undefined,
1869
+ oraclePrice: isPerpsContext(data)
1870
+ ? parseFloat(data.ctx.oraclePx.toString())
1871
+ : undefined,
1872
+ lastUpdated: Date.now(),
1873
+ };
1874
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").set(symbol, marketData);
1875
+ // Update cached price data with new 24h change if we have current price
1876
+ const currentCachedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")?.get(symbol);
1877
+ if (currentCachedPrice) {
1878
+ const updatedPrice = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, currentCachedPrice.price);
1879
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
1880
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, updatedPrice);
1881
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
1882
+ }
1883
+ }
1884
+ })
1885
+ .then((sub) => {
1886
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").set(symbol, sub);
1887
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: Market data subscription established for ${symbol}`);
1888
+ return undefined;
1889
+ })
1890
+ .catch((error) => {
1891
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureActiveAssetSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureActiveAssetSubscription', { symbol }));
1892
+ });
1893
+ }, _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription = function _HyperLiquidSubscriptionService_cleanupActiveAssetSubscription(symbol) {
1894
+ const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").get(symbol) ?? 0;
1895
+ if (currentCount <= 1) {
1896
+ // Last subscriber, cleanup subscription
1897
+ const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").get(symbol);
1898
+ if (subscription && typeof subscription.unsubscribe === 'function') {
1899
+ const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
1900
+ unsubscribeResult.catch(() => {
1901
+ // Ignore errors during cleanup
1902
+ });
1903
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").delete(symbol);
1904
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").delete(symbol);
1905
+ }
1906
+ else if (subscription) {
1907
+ // Subscription exists but unsubscribe is not a function or doesn't return a Promise
1908
+ // Just clean up the reference
1909
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalActiveAssetSubscriptions, "f").delete(symbol);
1910
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").delete(symbol);
1911
+ }
1912
+ }
1913
+ else {
1914
+ // Still has subscribers, just decrement count
1915
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_symbolSubscriberCounts, "f").set(symbol, currentCount - 1);
1916
+ }
1917
+ }, _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription =
1918
+ /**
1919
+ * Ensure assetCtxs subscription for specific DEX (HIP-3 support)
1920
+ * Uses WebSocket instead of REST polling for market data
1921
+ * Implements reference counting to track active subscribers per DEX
1922
+ *
1923
+ * @param dex - The DEX identifier (empty string for main DEX).
1924
+ */
1925
+ async function _HyperLiquidSubscriptionService_ensureAssetCtxsSubscription(dex) {
1926
+ const dexKey = dex || '';
1927
+ // Increment subscriber count for this DEX
1928
+ const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").get(dexKey) ?? 0;
1929
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").set(dexKey, currentCount + 1);
1930
+ // Return if subscription already exists
1931
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").has(dexKey)) {
1932
+ return;
1933
+ }
1934
+ // Await existing promise if subscription is being established
1935
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").has(dexKey)) {
1936
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").get(dexKey);
1937
+ return;
1938
+ }
1939
+ // Create new subscription promise
1940
+ const promise = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createAssetCtxsSubscription).call(this, dex);
1941
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").set(dexKey, promise);
1942
+ try {
1943
+ await promise;
1944
+ }
1945
+ catch (error) {
1946
+ // Clear promise on error so it can be retried
1947
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").delete(dexKey);
1948
+ throw error;
1949
+ }
1950
+ }, _HyperLiquidSubscriptionService_createAssetCtxsSubscription =
1951
+ /**
1952
+ * Create assetCtxs subscription for specific DEX
1953
+ * Provides real-time market data for all assets on the DEX
1954
+ *
1955
+ * Performance: Uses cached meta from dexMetaCache (populated by metaAndAssetCtxs)
1956
+ * to avoid redundant meta() API calls during subscription setup
1957
+ *
1958
+ * @param dex - The DEX identifier (empty string for main DEX).
1959
+ */
1960
+ async function _HyperLiquidSubscriptionService_createAssetCtxsSubscription(dex) {
1961
+ await __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").ensureSubscriptionClient(__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_walletService, "f").createWalletAdapter());
1962
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
1963
+ if (!subscriptionClient) {
1964
+ throw new Error('Subscription client not initialized');
1965
+ }
1966
+ const dexKey = dex || '';
1967
+ const dexIdentifier = dex ?? 'main DEX';
1968
+ // Check cache first - populated by metaAndAssetCtxs in ensureAssetCtxsSubscription
1969
+ let perpsMeta = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").get(dexKey);
1970
+ if (!perpsMeta) {
1971
+ // Fallback: fetch meta if not in cache (shouldn't happen in normal flow)
1972
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Meta cache miss for ${dexIdentifier}, fetching from API`);
1973
+ const infoClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getInfoClient();
1974
+ const fetchedMeta = await infoClient.meta({ dex: dex || undefined });
1975
+ if (fetchedMeta?.universe) {
1976
+ perpsMeta = fetchedMeta;
1977
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").set(dexKey, fetchedMeta);
1978
+ }
1979
+ }
1980
+ if (!perpsMeta?.universe) {
1981
+ const errorMessage = `No universe data available for ${dexIdentifier}`;
1982
+ throw new Error(errorMessage);
1983
+ }
1984
+ // Capture narrowed perpsMeta in a const for use inside closures
1985
+ const validatedMeta = perpsMeta;
1986
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Using ${__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexMetaCache, "f").has(dexKey) ? 'cached' : 'fetched'} meta for ${dexIdentifier}`, {
1987
+ dex,
1988
+ universeCount: validatedMeta.universe.length,
1989
+ firstAssetSample: validatedMeta.universe[0]?.name,
1990
+ });
1991
+ return new Promise((resolve, reject) => {
1992
+ const subscriptionParams = dex ? { dex } : {};
1993
+ subscriptionClient
1994
+ .assetCtxs(subscriptionParams, (data) => {
1995
+ // Cache asset contexts for this DEX
1996
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").set(dexKey, data.ctxs);
1997
+ // Use cached meta to map ctxs array indices to symbols (no REST API call!)
1998
+ validatedMeta.universe.forEach((asset, index) => {
1999
+ const ctx = data.ctxs[index];
2000
+ if (ctx && 'funding' in ctx) {
2001
+ // This is a perps context
2002
+ const ctxPrice = ctx.midPx ?? ctx.markPx;
2003
+ const openInterestUSD = (0, marketDataTransform_1.calculateOpenInterestUSD)(ctx.openInterest, ctxPrice);
2004
+ const marketData = {
2005
+ prevDayPx: ctx.prevDayPx
2006
+ ? parseFloat(ctx.prevDayPx.toString())
2007
+ : undefined,
2008
+ funding: parseFloat(ctx.funding.toString()),
2009
+ openInterest: isNaN(openInterestUSD)
2010
+ ? undefined
2011
+ : openInterestUSD,
2012
+ volume24h: ctx.dayNtlVlm
2013
+ ? parseFloat(ctx.dayNtlVlm.toString())
2014
+ : undefined,
2015
+ oraclePrice: parseFloat(ctx.oraclePx.toString()),
2016
+ lastUpdated: Date.now(),
2017
+ };
2018
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_marketDataCache, "f").set(asset.name, marketData);
2019
+ // HIP-3: Extract price from assetCtx and update cached prices
2020
+ const price = ctx.midPx?.toString() ?? ctx.markPx?.toString();
2021
+ if (price) {
2022
+ // For HIP-3 DEXs, meta() returns asset.name already containing the DEX prefix
2023
+ // (e.g., "xyz:XYZ100"), so use it directly
2024
+ const symbol = asset.name;
2025
+ const priceUpdate = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).call(this, symbol, price);
2026
+ __classPrivateFieldSet(this, _HyperLiquidSubscriptionService_cachedPriceData, __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f") ?? new Map(), "f");
2027
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f").set(symbol, priceUpdate);
2028
+ }
2029
+ }
2030
+ });
2031
+ // Notify price subscribers with updated market data
2032
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).call(this);
2033
+ })
2034
+ .then((sub) => {
2035
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").set(dexKey, sub);
2036
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`assetCtxs subscription established for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
2037
+ resolve();
2038
+ return undefined;
2039
+ })
2040
+ .catch((error) => {
2041
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createAssetCtxsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'createAssetCtxsSubscription', { dex }));
2042
+ reject((0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.createAssetCtxsSubscription'));
2043
+ });
2044
+ });
2045
+ }, _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription = function _HyperLiquidSubscriptionService_cleanupAssetCtxsSubscription(dex) {
2046
+ const dexKey = dex || '';
2047
+ // Decrement subscriber count for this DEX
2048
+ const currentCount = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").get(dexKey) ?? 0;
2049
+ if (currentCount <= 1) {
2050
+ // Last subscriber - cleanup the subscription
2051
+ const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").get(dexKey);
2052
+ if (subscription) {
2053
+ subscription.unsubscribe().catch((error) => {
2054
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.cleanupAssetCtxsSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'cleanupAssetCtxsSubscription', { dex }));
2055
+ });
2056
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptions, "f").delete(dexKey);
2057
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexAssetCtxsCache, "f").delete(dexKey);
2058
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_assetCtxsSubscriptionPromises, "f").delete(dexKey);
2059
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").delete(dexKey);
2060
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`Cleaned up assetCtxs subscription for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
2061
+ }
2062
+ }
2063
+ else {
2064
+ // Still has subscribers - just decrement count
2065
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_dexSubscriberCounts, "f").set(dexKey, currentCount - 1);
2066
+ }
2067
+ }, _HyperLiquidSubscriptionService_ensureBboSubscription = function _HyperLiquidSubscriptionService_ensureBboSubscription(symbol) {
2068
+ if (__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").has(symbol)) {
2069
+ return;
2070
+ }
2071
+ const subscriptionClient = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_clientService, "f").getSubscriptionClient();
2072
+ if (!subscriptionClient) {
2073
+ return;
2074
+ }
2075
+ subscriptionClient
2076
+ .bbo({ coin: symbol }, (data) => {
2077
+ (0, hyperLiquidOrderBookProcessor_1.processBboData)({
2078
+ symbol,
2079
+ data,
2080
+ orderBookCache: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f"),
2081
+ cachedPriceData: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f"),
2082
+ createPriceUpdate: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_createPriceUpdate).bind(this),
2083
+ notifySubscribers: __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_notifyAllPriceSubscribers).bind(this),
2084
+ });
2085
+ })
2086
+ .then((sub) => {
2087
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").set(symbol, sub);
2088
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_deps, "f").debugLogger.log(`HyperLiquid: BBO subscription established for ${symbol}`);
2089
+ return undefined;
2090
+ })
2091
+ .catch((error) => {
2092
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_logErrorUnlessClearing).call(this, (0, errorUtils_1.ensureError)(error, 'HyperLiquidSubscriptionService.ensureBboSubscription'), __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_instances, "m", _HyperLiquidSubscriptionService_getErrorContext).call(this, 'ensureBboSubscription', { symbol }));
2093
+ });
2094
+ }, _HyperLiquidSubscriptionService_cleanupBboSubscription = function _HyperLiquidSubscriptionService_cleanupBboSubscription(symbol) {
2095
+ // If anyone still wants order book (top-of-book) data for this symbol, keep the subscription alive.
2096
+ if ((__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookSubscribers, "f").get(symbol)?.size ?? 0) > 0) {
2097
+ return;
2098
+ }
2099
+ const subscription = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").get(symbol);
2100
+ if (subscription && typeof subscription.unsubscribe === 'function') {
2101
+ const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
2102
+ unsubscribeResult.catch(() => {
2103
+ // Ignore errors during cleanup
2104
+ });
2105
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").delete(symbol);
2106
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").delete(symbol);
2107
+ }
2108
+ else if (subscription) {
2109
+ // Subscription exists but unsubscribe is not a function or doesn't return a Promise
2110
+ // Just clean up the reference
2111
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_globalBboSubscriptions, "f").delete(symbol);
2112
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_orderBookCache, "f").delete(symbol);
2113
+ }
2114
+ }, _HyperLiquidSubscriptionService_processOrderBookData = function _HyperLiquidSubscriptionService_processOrderBookData(data, levels) {
2115
+ const bidsRaw = data?.levels?.[0] ?? [];
2116
+ const asksRaw = data?.levels?.[1] ?? [];
2117
+ // Process bids (buy orders) - highest price first
2118
+ let bidCumulativeSize = 0;
2119
+ let bidCumulativeNotional = 0;
2120
+ const bids = bidsRaw.slice(0, levels).map((level) => {
2121
+ const price = parseFloat(level.px);
2122
+ const size = parseFloat(level.sz);
2123
+ const notional = price * size;
2124
+ bidCumulativeSize += size;
2125
+ bidCumulativeNotional += notional;
2126
+ return {
2127
+ price: level.px,
2128
+ size: level.sz,
2129
+ total: bidCumulativeSize.toString(),
2130
+ notional: notional.toFixed(2),
2131
+ totalNotional: bidCumulativeNotional.toFixed(2),
2132
+ };
2133
+ });
2134
+ // Process asks (sell orders) - lowest price first
2135
+ let askCumulativeSize = 0;
2136
+ let askCumulativeNotional = 0;
2137
+ const asks = asksRaw.slice(0, levels).map((level) => {
2138
+ const price = parseFloat(level.px);
2139
+ const size = parseFloat(level.sz);
2140
+ const notional = price * size;
2141
+ askCumulativeSize += size;
2142
+ askCumulativeNotional += notional;
2143
+ return {
2144
+ price: level.px,
2145
+ size: level.sz,
2146
+ total: askCumulativeSize.toString(),
2147
+ notional: notional.toFixed(2),
2148
+ totalNotional: askCumulativeNotional.toFixed(2),
2149
+ };
2150
+ });
2151
+ // Calculate spread and mid price
2152
+ const bestBid = bids[0];
2153
+ const bestAsk = asks[0];
2154
+ const bidPrice = bestBid ? parseFloat(bestBid.price) : 0;
2155
+ const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;
2156
+ const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
2157
+ const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
2158
+ const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
2159
+ // Calculate max total for depth chart scaling
2160
+ const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
2161
+ return {
2162
+ bids,
2163
+ asks,
2164
+ spread: spread.toFixed(5),
2165
+ spreadPercentage,
2166
+ midPrice: midPrice.toFixed(5),
2167
+ lastUpdated: Date.now(),
2168
+ maxTotal,
2169
+ };
2170
+ }, _HyperLiquidSubscriptionService_notifyAllPriceSubscribers = function _HyperLiquidSubscriptionService_notifyAllPriceSubscribers() {
2171
+ // If no price data exists yet, don't notify
2172
+ if (!__classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f")) {
2173
+ return;
2174
+ }
2175
+ const priceData = __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_cachedPriceData, "f");
2176
+ // Group updates by subscriber to batch notifications
2177
+ const subscriberUpdates = new Map();
2178
+ __classPrivateFieldGet(this, _HyperLiquidSubscriptionService_priceSubscribers, "f").forEach((subscriberSet, symbol) => {
2179
+ const priceUpdate = priceData.get(symbol);
2180
+ if (priceUpdate) {
2181
+ subscriberSet.forEach((callback) => {
2182
+ if (!subscriberUpdates.has(callback)) {
2183
+ subscriberUpdates.set(callback, []);
2184
+ }
2185
+ const updates = subscriberUpdates.get(callback);
2186
+ if (updates) {
2187
+ updates.push(priceUpdate);
2188
+ }
2189
+ });
2190
+ }
2191
+ });
2192
+ // Send batched updates to each subscriber
2193
+ subscriberUpdates.forEach((updates, callback) => {
2194
+ if (updates.length > 0) {
2195
+ callback(updates);
2196
+ }
2197
+ });
2198
+ };
2199
+ //# sourceMappingURL=HyperLiquidSubscriptionService.cjs.map