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