@metamask-previews/perps-controller 0.0.0-preview-e4aa1532 → 0.0.0-preview-6dfa4aeba

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 (498) hide show
  1. package/CHANGELOG.md +1 -11
  2. package/dist/PerpsController.cjs +66 -2224
  3. package/dist/PerpsController.cjs.map +1 -1
  4. package/dist/PerpsController.d.cts +79 -933
  5. package/dist/PerpsController.d.cts.map +1 -1
  6. package/dist/PerpsController.d.mts +79 -933
  7. package/dist/PerpsController.d.mts.map +1 -1
  8. package/dist/PerpsController.mjs +64 -2221
  9. package/dist/PerpsController.mjs.map +1 -1
  10. package/dist/index.cjs +1 -32
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +2 -6
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +2 -6
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +1 -9
  17. package/dist/index.mjs.map +1 -1
  18. package/package.json +4 -19
  19. package/dist/__mocks__/hyperliquidMock.cjs +0 -68
  20. package/dist/__mocks__/hyperliquidMock.cjs.map +0 -1
  21. package/dist/__mocks__/hyperliquidMock.d.cts +0 -15
  22. package/dist/__mocks__/hyperliquidMock.d.cts.map +0 -1
  23. package/dist/__mocks__/hyperliquidMock.d.mts +0 -15
  24. package/dist/__mocks__/hyperliquidMock.d.mts.map +0 -1
  25. package/dist/__mocks__/hyperliquidMock.mjs +0 -65
  26. package/dist/__mocks__/hyperliquidMock.mjs.map +0 -1
  27. package/dist/__mocks__/providerMocks.cjs +0 -144
  28. package/dist/__mocks__/providerMocks.cjs.map +0 -1
  29. package/dist/__mocks__/providerMocks.d.cts +0 -44
  30. package/dist/__mocks__/providerMocks.d.cts.map +0 -1
  31. package/dist/__mocks__/providerMocks.d.mts +0 -44
  32. package/dist/__mocks__/providerMocks.d.mts.map +0 -1
  33. package/dist/__mocks__/providerMocks.mjs +0 -136
  34. package/dist/__mocks__/providerMocks.mjs.map +0 -1
  35. package/dist/__mocks__/serviceMocks.cjs +0 -187
  36. package/dist/__mocks__/serviceMocks.cjs.map +0 -1
  37. package/dist/__mocks__/serviceMocks.d.cts +0 -58
  38. package/dist/__mocks__/serviceMocks.d.cts.map +0 -1
  39. package/dist/__mocks__/serviceMocks.d.mts +0 -58
  40. package/dist/__mocks__/serviceMocks.d.mts.map +0 -1
  41. package/dist/__mocks__/serviceMocks.mjs +0 -180
  42. package/dist/__mocks__/serviceMocks.mjs.map +0 -1
  43. package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -459
  44. package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
  45. package/dist/aggregation/SubscriptionMultiplexer.d.cts +0 -222
  46. package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
  47. package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -222
  48. package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
  49. package/dist/aggregation/SubscriptionMultiplexer.mjs +0 -455
  50. package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
  51. package/dist/aggregation/index.cjs +0 -9
  52. package/dist/aggregation/index.cjs.map +0 -1
  53. package/dist/aggregation/index.d.cts +0 -6
  54. package/dist/aggregation/index.d.cts.map +0 -1
  55. package/dist/aggregation/index.d.mts +0 -6
  56. package/dist/aggregation/index.d.mts.map +0 -1
  57. package/dist/aggregation/index.mjs +0 -5
  58. package/dist/aggregation/index.mjs.map +0 -1
  59. package/dist/constants/eventNames.cjs +0 -117
  60. package/dist/constants/eventNames.cjs.map +0 -1
  61. package/dist/constants/eventNames.d.cts +0 -106
  62. package/dist/constants/eventNames.d.cts.map +0 -1
  63. package/dist/constants/eventNames.d.mts +0 -106
  64. package/dist/constants/eventNames.d.mts.map +0 -1
  65. package/dist/constants/eventNames.mjs +0 -114
  66. package/dist/constants/eventNames.mjs.map +0 -1
  67. package/dist/constants/hyperLiquidConfig.cjs +0 -366
  68. package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
  69. package/dist/constants/hyperLiquidConfig.d.cts +0 -276
  70. package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
  71. package/dist/constants/hyperLiquidConfig.d.mts +0 -276
  72. package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
  73. package/dist/constants/hyperLiquidConfig.mjs +0 -357
  74. package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
  75. package/dist/constants/index.cjs +0 -23
  76. package/dist/constants/index.cjs.map +0 -1
  77. package/dist/constants/index.d.cts +0 -7
  78. package/dist/constants/index.d.cts.map +0 -1
  79. package/dist/constants/index.d.mts +0 -7
  80. package/dist/constants/index.d.mts.map +0 -1
  81. package/dist/constants/index.mjs +0 -7
  82. package/dist/constants/index.mjs.map +0 -1
  83. package/dist/constants/orderTypes.cjs +0 -31
  84. package/dist/constants/orderTypes.cjs.map +0 -1
  85. package/dist/constants/orderTypes.d.cts +0 -19
  86. package/dist/constants/orderTypes.d.cts.map +0 -1
  87. package/dist/constants/orderTypes.d.mts +0 -19
  88. package/dist/constants/orderTypes.d.mts.map +0 -1
  89. package/dist/constants/orderTypes.mjs +0 -27
  90. package/dist/constants/orderTypes.mjs.map +0 -1
  91. package/dist/constants/performanceMetrics.cjs +0 -61
  92. package/dist/constants/performanceMetrics.cjs.map +0 -1
  93. package/dist/constants/performanceMetrics.d.cts +0 -44
  94. package/dist/constants/performanceMetrics.d.cts.map +0 -1
  95. package/dist/constants/performanceMetrics.d.mts +0 -44
  96. package/dist/constants/performanceMetrics.d.mts.map +0 -1
  97. package/dist/constants/performanceMetrics.mjs +0 -58
  98. package/dist/constants/performanceMetrics.mjs.map +0 -1
  99. package/dist/constants/perpsConfig.cjs +0 -461
  100. package/dist/constants/perpsConfig.cjs.map +0 -1
  101. package/dist/constants/perpsConfig.d.cts +0 -343
  102. package/dist/constants/perpsConfig.d.cts.map +0 -1
  103. package/dist/constants/perpsConfig.d.mts +0 -343
  104. package/dist/constants/perpsConfig.d.mts.map +0 -1
  105. package/dist/constants/perpsConfig.mjs +0 -458
  106. package/dist/constants/perpsConfig.mjs.map +0 -1
  107. package/dist/constants/perpsErrorCodes.cjs +0 -79
  108. package/dist/constants/perpsErrorCodes.cjs.map +0 -1
  109. package/dist/constants/perpsErrorCodes.d.cts +0 -64
  110. package/dist/constants/perpsErrorCodes.d.cts.map +0 -1
  111. package/dist/constants/perpsErrorCodes.d.mts +0 -64
  112. package/dist/constants/perpsErrorCodes.d.mts.map +0 -1
  113. package/dist/constants/perpsErrorCodes.mjs +0 -76
  114. package/dist/constants/perpsErrorCodes.mjs.map +0 -1
  115. package/dist/platform-services/HyperLiquidClientService.cjs +0 -857
  116. package/dist/platform-services/HyperLiquidClientService.cjs.map +0 -1
  117. package/dist/platform-services/HyperLiquidClientService.d.cts +0 -263
  118. package/dist/platform-services/HyperLiquidClientService.d.cts.map +0 -1
  119. package/dist/platform-services/HyperLiquidClientService.d.mts +0 -263
  120. package/dist/platform-services/HyperLiquidClientService.d.mts.map +0 -1
  121. package/dist/platform-services/HyperLiquidClientService.mjs +0 -853
  122. package/dist/platform-services/HyperLiquidClientService.mjs.map +0 -1
  123. package/dist/platform-services/HyperLiquidSubscriptionService.cjs +0 -2170
  124. package/dist/platform-services/HyperLiquidSubscriptionService.cjs.map +0 -1
  125. package/dist/platform-services/HyperLiquidSubscriptionService.d.cts +0 -424
  126. package/dist/platform-services/HyperLiquidSubscriptionService.d.cts.map +0 -1
  127. package/dist/platform-services/HyperLiquidSubscriptionService.d.mts +0 -424
  128. package/dist/platform-services/HyperLiquidSubscriptionService.d.mts.map +0 -1
  129. package/dist/platform-services/HyperLiquidSubscriptionService.mjs +0 -2166
  130. package/dist/platform-services/HyperLiquidSubscriptionService.mjs.map +0 -1
  131. package/dist/platform-services/HyperLiquidWalletService.cjs +0 -140
  132. package/dist/platform-services/HyperLiquidWalletService.cjs.map +0 -1
  133. package/dist/platform-services/HyperLiquidWalletService.d.cts +0 -78
  134. package/dist/platform-services/HyperLiquidWalletService.d.cts.map +0 -1
  135. package/dist/platform-services/HyperLiquidWalletService.d.mts +0 -78
  136. package/dist/platform-services/HyperLiquidWalletService.d.mts.map +0 -1
  137. package/dist/platform-services/HyperLiquidWalletService.mjs +0 -136
  138. package/dist/platform-services/HyperLiquidWalletService.mjs.map +0 -1
  139. package/dist/providers/AggregatedPerpsProvider.cjs +0 -777
  140. package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
  141. package/dist/providers/AggregatedPerpsProvider.d.cts +0 -466
  142. package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
  143. package/dist/providers/AggregatedPerpsProvider.d.mts +0 -466
  144. package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
  145. package/dist/providers/AggregatedPerpsProvider.mjs +0 -773
  146. package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
  147. package/dist/providers/HyperLiquidProvider.cjs +0 -5172
  148. package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
  149. package/dist/providers/HyperLiquidProvider.d.cts +0 -881
  150. package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
  151. package/dist/providers/HyperLiquidProvider.d.mts +0 -881
  152. package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
  153. package/dist/providers/HyperLiquidProvider.mjs +0 -5168
  154. package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
  155. package/dist/providers/index.cjs +0 -11
  156. package/dist/providers/index.cjs.map +0 -1
  157. package/dist/providers/index.d.cts +0 -6
  158. package/dist/providers/index.d.cts.map +0 -1
  159. package/dist/providers/index.d.mts +0 -6
  160. package/dist/providers/index.d.mts.map +0 -1
  161. package/dist/providers/index.mjs +0 -6
  162. package/dist/providers/index.mjs.map +0 -1
  163. package/dist/routing/ProviderRouter.cjs +0 -148
  164. package/dist/routing/ProviderRouter.cjs.map +0 -1
  165. package/dist/routing/ProviderRouter.d.cts +0 -124
  166. package/dist/routing/ProviderRouter.d.cts.map +0 -1
  167. package/dist/routing/ProviderRouter.d.mts +0 -124
  168. package/dist/routing/ProviderRouter.d.mts.map +0 -1
  169. package/dist/routing/ProviderRouter.mjs +0 -144
  170. package/dist/routing/ProviderRouter.mjs.map +0 -1
  171. package/dist/routing/index.cjs +0 -9
  172. package/dist/routing/index.cjs.map +0 -1
  173. package/dist/routing/index.d.cts +0 -6
  174. package/dist/routing/index.d.cts.map +0 -1
  175. package/dist/routing/index.d.mts +0 -6
  176. package/dist/routing/index.d.mts.map +0 -1
  177. package/dist/routing/index.mjs +0 -5
  178. package/dist/routing/index.mjs.map +0 -1
  179. package/dist/selectors.cjs +0 -161
  180. package/dist/selectors.cjs.map +0 -1
  181. package/dist/selectors.d.cts +0 -345
  182. package/dist/selectors.d.cts.map +0 -1
  183. package/dist/selectors.d.mts +0 -345
  184. package/dist/selectors.d.mts.map +0 -1
  185. package/dist/selectors.mjs +0 -153
  186. package/dist/selectors.mjs.map +0 -1
  187. package/dist/services/AccountService.cjs +0 -313
  188. package/dist/services/AccountService.cjs.map +0 -1
  189. package/dist/services/AccountService.d.cts +0 -53
  190. package/dist/services/AccountService.d.cts.map +0 -1
  191. package/dist/services/AccountService.d.mts +0 -53
  192. package/dist/services/AccountService.d.mts.map +0 -1
  193. package/dist/services/AccountService.mjs +0 -309
  194. package/dist/services/AccountService.mjs.map +0 -1
  195. package/dist/services/DataLakeService.cjs +0 -219
  196. package/dist/services/DataLakeService.cjs.map +0 -1
  197. package/dist/services/DataLakeService.d.cts +0 -49
  198. package/dist/services/DataLakeService.d.cts.map +0 -1
  199. package/dist/services/DataLakeService.d.mts +0 -49
  200. package/dist/services/DataLakeService.d.mts.map +0 -1
  201. package/dist/services/DataLakeService.mjs +0 -215
  202. package/dist/services/DataLakeService.mjs.map +0 -1
  203. package/dist/services/DepositService.cjs +0 -96
  204. package/dist/services/DepositService.cjs.map +0 -1
  205. package/dist/services/DepositService.d.cts +0 -37
  206. package/dist/services/DepositService.d.cts.map +0 -1
  207. package/dist/services/DepositService.d.mts +0 -37
  208. package/dist/services/DepositService.d.mts.map +0 -1
  209. package/dist/services/DepositService.mjs +0 -92
  210. package/dist/services/DepositService.mjs.map +0 -1
  211. package/dist/services/EligibilityService.cjs +0 -156
  212. package/dist/services/EligibilityService.cjs.map +0 -1
  213. package/dist/services/EligibilityService.d.cts +0 -48
  214. package/dist/services/EligibilityService.d.cts.map +0 -1
  215. package/dist/services/EligibilityService.d.mts +0 -48
  216. package/dist/services/EligibilityService.d.mts.map +0 -1
  217. package/dist/services/EligibilityService.mjs +0 -152
  218. package/dist/services/EligibilityService.mjs.map +0 -1
  219. package/dist/services/FeatureFlagConfigurationService.cjs +0 -258
  220. package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
  221. package/dist/services/FeatureFlagConfigurationService.d.cts +0 -100
  222. package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
  223. package/dist/services/FeatureFlagConfigurationService.d.mts +0 -100
  224. package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
  225. package/dist/services/FeatureFlagConfigurationService.mjs +0 -254
  226. package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
  227. package/dist/services/MarketDataService.cjs +0 -875
  228. package/dist/services/MarketDataService.cjs.map +0 -1
  229. package/dist/services/MarketDataService.d.cts +0 -289
  230. package/dist/services/MarketDataService.d.cts.map +0 -1
  231. package/dist/services/MarketDataService.d.mts +0 -289
  232. package/dist/services/MarketDataService.d.mts.map +0 -1
  233. package/dist/services/MarketDataService.mjs +0 -871
  234. package/dist/services/MarketDataService.mjs.map +0 -1
  235. package/dist/services/RewardsIntegrationService.cjs +0 -94
  236. package/dist/services/RewardsIntegrationService.cjs.map +0 -1
  237. package/dist/services/RewardsIntegrationService.d.cts +0 -30
  238. package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
  239. package/dist/services/RewardsIntegrationService.d.mts +0 -30
  240. package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
  241. package/dist/services/RewardsIntegrationService.mjs +0 -90
  242. package/dist/services/RewardsIntegrationService.mjs.map +0 -1
  243. package/dist/services/ServiceContext.cjs +0 -3
  244. package/dist/services/ServiceContext.cjs.map +0 -1
  245. package/dist/services/ServiceContext.d.cts +0 -110
  246. package/dist/services/ServiceContext.d.cts.map +0 -1
  247. package/dist/services/ServiceContext.d.mts +0 -110
  248. package/dist/services/ServiceContext.d.mts.map +0 -1
  249. package/dist/services/ServiceContext.mjs +0 -2
  250. package/dist/services/ServiceContext.mjs.map +0 -1
  251. package/dist/services/TradingService.cjs +0 -1481
  252. package/dist/services/TradingService.cjs.map +0 -1
  253. package/dist/services/TradingService.d.cts +0 -308
  254. package/dist/services/TradingService.d.cts.map +0 -1
  255. package/dist/services/TradingService.d.mts +0 -308
  256. package/dist/services/TradingService.d.mts.map +0 -1
  257. package/dist/services/TradingService.mjs +0 -1477
  258. package/dist/services/TradingService.mjs.map +0 -1
  259. package/dist/services/index.cjs +0 -26
  260. package/dist/services/index.cjs.map +0 -1
  261. package/dist/services/index.d.cts +0 -11
  262. package/dist/services/index.d.cts.map +0 -1
  263. package/dist/services/index.d.mts +0 -11
  264. package/dist/services/index.d.mts.map +0 -1
  265. package/dist/services/index.mjs +0 -10
  266. package/dist/services/index.mjs.map +0 -1
  267. package/dist/services/utils.cjs +0 -16
  268. package/dist/services/utils.cjs.map +0 -1
  269. package/dist/services/utils.d.cts +0 -8
  270. package/dist/services/utils.d.cts.map +0 -1
  271. package/dist/services/utils.d.mts +0 -8
  272. package/dist/services/utils.d.mts.map +0 -1
  273. package/dist/services/utils.mjs +0 -12
  274. package/dist/services/utils.mjs.map +0 -1
  275. package/dist/types/chart.cjs +0 -42
  276. package/dist/types/chart.cjs.map +0 -1
  277. package/dist/types/chart.d.cts +0 -62
  278. package/dist/types/chart.d.cts.map +0 -1
  279. package/dist/types/chart.d.mts +0 -62
  280. package/dist/types/chart.d.mts.map +0 -1
  281. package/dist/types/chart.mjs +0 -39
  282. package/dist/types/chart.mjs.map +0 -1
  283. package/dist/types/hyperliquid-types.cjs +0 -3
  284. package/dist/types/hyperliquid-types.cjs.map +0 -1
  285. package/dist/types/hyperliquid-types.d.cts +0 -52
  286. package/dist/types/hyperliquid-types.d.cts.map +0 -1
  287. package/dist/types/hyperliquid-types.d.mts +0 -52
  288. package/dist/types/hyperliquid-types.d.mts.map +0 -1
  289. package/dist/types/hyperliquid-types.mjs +0 -2
  290. package/dist/types/hyperliquid-types.mjs.map +0 -1
  291. package/dist/types/index.cjs +0 -96
  292. package/dist/types/index.cjs.map +0 -1
  293. package/dist/types/index.d.cts +0 -1153
  294. package/dist/types/index.d.cts.map +0 -1
  295. package/dist/types/index.d.mts +0 -1153
  296. package/dist/types/index.d.mts.map +0 -1
  297. package/dist/types/index.mjs +0 -79
  298. package/dist/types/index.mjs.map +0 -1
  299. package/dist/types/transactionTypes.cjs +0 -28
  300. package/dist/types/transactionTypes.cjs.map +0 -1
  301. package/dist/types/transactionTypes.d.cts +0 -64
  302. package/dist/types/transactionTypes.d.cts.map +0 -1
  303. package/dist/types/transactionTypes.d.mts +0 -64
  304. package/dist/types/transactionTypes.d.mts.map +0 -1
  305. package/dist/types/transactionTypes.mjs +0 -23
  306. package/dist/types/transactionTypes.mjs.map +0 -1
  307. package/dist/utils/accountUtils.cjs +0 -65
  308. package/dist/utils/accountUtils.cjs.map +0 -1
  309. package/dist/utils/accountUtils.d.cts +0 -26
  310. package/dist/utils/accountUtils.d.cts.map +0 -1
  311. package/dist/utils/accountUtils.d.mts +0 -26
  312. package/dist/utils/accountUtils.d.mts.map +0 -1
  313. package/dist/utils/accountUtils.mjs +0 -61
  314. package/dist/utils/accountUtils.mjs.map +0 -1
  315. package/dist/utils/amountConversion.cjs +0 -61
  316. package/dist/utils/amountConversion.cjs.map +0 -1
  317. package/dist/utils/amountConversion.d.cts +0 -16
  318. package/dist/utils/amountConversion.d.cts.map +0 -1
  319. package/dist/utils/amountConversion.d.mts +0 -16
  320. package/dist/utils/amountConversion.d.mts.map +0 -1
  321. package/dist/utils/amountConversion.mjs +0 -54
  322. package/dist/utils/amountConversion.mjs.map +0 -1
  323. package/dist/utils/chartUtils.cjs +0 -98
  324. package/dist/utils/chartUtils.cjs.map +0 -1
  325. package/dist/utils/chartUtils.d.cts +0 -14
  326. package/dist/utils/chartUtils.d.cts.map +0 -1
  327. package/dist/utils/chartUtils.d.mts +0 -14
  328. package/dist/utils/chartUtils.d.mts.map +0 -1
  329. package/dist/utils/chartUtils.mjs +0 -94
  330. package/dist/utils/chartUtils.mjs.map +0 -1
  331. package/dist/utils/errorUtils.cjs +0 -22
  332. package/dist/utils/errorUtils.cjs.map +0 -1
  333. package/dist/utils/errorUtils.d.cts +0 -13
  334. package/dist/utils/errorUtils.d.cts.map +0 -1
  335. package/dist/utils/errorUtils.d.mts +0 -13
  336. package/dist/utils/errorUtils.d.mts.map +0 -1
  337. package/dist/utils/errorUtils.mjs +0 -18
  338. package/dist/utils/errorUtils.mjs.map +0 -1
  339. package/dist/utils/formatUtils.cjs +0 -987
  340. package/dist/utils/formatUtils.cjs.map +0 -1
  341. package/dist/utils/formatUtils.d.cts +0 -387
  342. package/dist/utils/formatUtils.d.cts.map +0 -1
  343. package/dist/utils/formatUtils.d.mts +0 -387
  344. package/dist/utils/formatUtils.d.mts.map +0 -1
  345. package/dist/utils/formatUtils.mjs +0 -966
  346. package/dist/utils/formatUtils.mjs.map +0 -1
  347. package/dist/utils/hyperLiquidAdapter.cjs +0 -454
  348. package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
  349. package/dist/utils/hyperLiquidAdapter.d.cts +0 -158
  350. package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
  351. package/dist/utils/hyperLiquidAdapter.d.mts +0 -158
  352. package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
  353. package/dist/utils/hyperLiquidAdapter.mjs +0 -439
  354. package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
  355. package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -89
  356. package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
  357. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -58
  358. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
  359. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +0 -58
  360. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
  361. package/dist/utils/hyperLiquidOrderBookProcessor.mjs +0 -84
  362. package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +0 -1
  363. package/dist/utils/hyperLiquidValidation.cjs +0 -426
  364. package/dist/utils/hyperLiquidValidation.cjs.map +0 -1
  365. package/dist/utils/hyperLiquidValidation.d.cts +0 -143
  366. package/dist/utils/hyperLiquidValidation.d.cts.map +0 -1
  367. package/dist/utils/hyperLiquidValidation.d.mts +0 -143
  368. package/dist/utils/hyperLiquidValidation.d.mts.map +0 -1
  369. package/dist/utils/hyperLiquidValidation.mjs +0 -413
  370. package/dist/utils/hyperLiquidValidation.mjs.map +0 -1
  371. package/dist/utils/idUtils.cjs +0 -50
  372. package/dist/utils/idUtils.cjs.map +0 -1
  373. package/dist/utils/idUtils.d.cts +0 -38
  374. package/dist/utils/idUtils.d.cts.map +0 -1
  375. package/dist/utils/idUtils.d.mts +0 -38
  376. package/dist/utils/idUtils.d.mts.map +0 -1
  377. package/dist/utils/idUtils.mjs +0 -42
  378. package/dist/utils/idUtils.mjs.map +0 -1
  379. package/dist/utils/marginUtils.cjs +0 -137
  380. package/dist/utils/marginUtils.cjs.map +0 -1
  381. package/dist/utils/marginUtils.d.cts +0 -64
  382. package/dist/utils/marginUtils.d.cts.map +0 -1
  383. package/dist/utils/marginUtils.d.mts +0 -64
  384. package/dist/utils/marginUtils.d.mts.map +0 -1
  385. package/dist/utils/marginUtils.mjs +0 -131
  386. package/dist/utils/marginUtils.mjs.map +0 -1
  387. package/dist/utils/marketDataTransform.cjs +0 -227
  388. package/dist/utils/marketDataTransform.cjs.map +0 -1
  389. package/dist/utils/marketDataTransform.d.cts +0 -45
  390. package/dist/utils/marketDataTransform.d.cts.map +0 -1
  391. package/dist/utils/marketDataTransform.d.mts +0 -45
  392. package/dist/utils/marketDataTransform.d.mts.map +0 -1
  393. package/dist/utils/marketDataTransform.mjs +0 -220
  394. package/dist/utils/marketDataTransform.mjs.map +0 -1
  395. package/dist/utils/marketUtils.cjs +0 -420
  396. package/dist/utils/marketUtils.cjs.map +0 -1
  397. package/dist/utils/marketUtils.d.cts +0 -227
  398. package/dist/utils/marketUtils.d.cts.map +0 -1
  399. package/dist/utils/marketUtils.d.mts +0 -227
  400. package/dist/utils/marketUtils.d.mts.map +0 -1
  401. package/dist/utils/marketUtils.mjs +0 -404
  402. package/dist/utils/marketUtils.mjs.map +0 -1
  403. package/dist/utils/orderBookGrouping.cjs +0 -151
  404. package/dist/utils/orderBookGrouping.cjs.map +0 -1
  405. package/dist/utils/orderBookGrouping.d.cts +0 -76
  406. package/dist/utils/orderBookGrouping.d.cts.map +0 -1
  407. package/dist/utils/orderBookGrouping.d.mts +0 -76
  408. package/dist/utils/orderBookGrouping.d.mts.map +0 -1
  409. package/dist/utils/orderBookGrouping.mjs +0 -143
  410. package/dist/utils/orderBookGrouping.mjs.map +0 -1
  411. package/dist/utils/orderCalculations.cjs +0 -283
  412. package/dist/utils/orderCalculations.cjs.map +0 -1
  413. package/dist/utils/orderCalculations.d.cts +0 -107
  414. package/dist/utils/orderCalculations.d.cts.map +0 -1
  415. package/dist/utils/orderCalculations.d.mts +0 -107
  416. package/dist/utils/orderCalculations.d.mts.map +0 -1
  417. package/dist/utils/orderCalculations.mjs +0 -274
  418. package/dist/utils/orderCalculations.mjs.map +0 -1
  419. package/dist/utils/orderUtils.cjs +0 -159
  420. package/dist/utils/orderUtils.cjs.map +0 -1
  421. package/dist/utils/orderUtils.d.cts +0 -66
  422. package/dist/utils/orderUtils.d.cts.map +0 -1
  423. package/dist/utils/orderUtils.d.mts +0 -66
  424. package/dist/utils/orderUtils.d.mts.map +0 -1
  425. package/dist/utils/orderUtils.mjs +0 -151
  426. package/dist/utils/orderUtils.mjs.map +0 -1
  427. package/dist/utils/pnlCalculations.cjs +0 -107
  428. package/dist/utils/pnlCalculations.cjs.map +0 -1
  429. package/dist/utils/pnlCalculations.d.cts +0 -79
  430. package/dist/utils/pnlCalculations.d.cts.map +0 -1
  431. package/dist/utils/pnlCalculations.d.mts +0 -79
  432. package/dist/utils/pnlCalculations.d.mts.map +0 -1
  433. package/dist/utils/pnlCalculations.mjs +0 -97
  434. package/dist/utils/pnlCalculations.mjs.map +0 -1
  435. package/dist/utils/positionCalculations.cjs +0 -176
  436. package/dist/utils/positionCalculations.cjs.map +0 -1
  437. package/dist/utils/positionCalculations.d.cts +0 -85
  438. package/dist/utils/positionCalculations.d.cts.map +0 -1
  439. package/dist/utils/positionCalculations.d.mts +0 -85
  440. package/dist/utils/positionCalculations.d.mts.map +0 -1
  441. package/dist/utils/positionCalculations.mjs +0 -165
  442. package/dist/utils/positionCalculations.mjs.map +0 -1
  443. package/dist/utils/sortMarkets.cjs +0 -88
  444. package/dist/utils/sortMarkets.cjs.map +0 -1
  445. package/dist/utils/sortMarkets.d.cts +0 -21
  446. package/dist/utils/sortMarkets.d.cts.map +0 -1
  447. package/dist/utils/sortMarkets.d.mts +0 -21
  448. package/dist/utils/sortMarkets.d.mts.map +0 -1
  449. package/dist/utils/sortMarkets.mjs +0 -84
  450. package/dist/utils/sortMarkets.mjs.map +0 -1
  451. package/dist/utils/standaloneInfoClient.cjs +0 -34
  452. package/dist/utils/standaloneInfoClient.cjs.map +0 -1
  453. package/dist/utils/standaloneInfoClient.d.cts +0 -31
  454. package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
  455. package/dist/utils/standaloneInfoClient.d.mts +0 -31
  456. package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
  457. package/dist/utils/standaloneInfoClient.mjs +0 -30
  458. package/dist/utils/standaloneInfoClient.mjs.map +0 -1
  459. package/dist/utils/stringParseUtils.cjs +0 -49
  460. package/dist/utils/stringParseUtils.cjs.map +0 -1
  461. package/dist/utils/stringParseUtils.d.cts +0 -35
  462. package/dist/utils/stringParseUtils.d.cts.map +0 -1
  463. package/dist/utils/stringParseUtils.d.mts +0 -35
  464. package/dist/utils/stringParseUtils.d.mts.map +0 -1
  465. package/dist/utils/stringParseUtils.mjs +0 -44
  466. package/dist/utils/stringParseUtils.mjs.map +0 -1
  467. package/dist/utils/time.cjs +0 -37
  468. package/dist/utils/time.cjs.map +0 -1
  469. package/dist/utils/time.d.cts +0 -17
  470. package/dist/utils/time.d.cts.map +0 -1
  471. package/dist/utils/time.d.mts +0 -17
  472. package/dist/utils/time.d.mts.map +0 -1
  473. package/dist/utils/time.mjs +0 -33
  474. package/dist/utils/time.mjs.map +0 -1
  475. package/dist/utils/tpslValidation.cjs +0 -505
  476. package/dist/utils/tpslValidation.cjs.map +0 -1
  477. package/dist/utils/tpslValidation.d.cts +0 -182
  478. package/dist/utils/tpslValidation.d.cts.map +0 -1
  479. package/dist/utils/tpslValidation.d.mts +0 -182
  480. package/dist/utils/tpslValidation.d.mts.map +0 -1
  481. package/dist/utils/tpslValidation.mjs +0 -482
  482. package/dist/utils/tpslValidation.mjs.map +0 -1
  483. package/dist/utils/transactionUtils.cjs +0 -36
  484. package/dist/utils/transactionUtils.cjs.map +0 -1
  485. package/dist/utils/transactionUtils.d.cts +0 -17
  486. package/dist/utils/transactionUtils.d.cts.map +0 -1
  487. package/dist/utils/transactionUtils.d.mts +0 -17
  488. package/dist/utils/transactionUtils.d.mts.map +0 -1
  489. package/dist/utils/transactionUtils.mjs +0 -32
  490. package/dist/utils/transactionUtils.mjs.map +0 -1
  491. package/dist/utils/wait.cjs +0 -12
  492. package/dist/utils/wait.cjs.map +0 -1
  493. package/dist/utils/wait.d.cts +0 -8
  494. package/dist/utils/wait.d.cts.map +0 -1
  495. package/dist/utils/wait.d.mts +0 -8
  496. package/dist/utils/wait.d.mts.map +0 -1
  497. package/dist/utils/wait.mjs +0 -8
  498. package/dist/utils/wait.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"HyperLiquidSubscriptionService.mjs","sourceRoot":"","sources":["../../src/platform-services/HyperLiquidSubscriptionService.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,qCAAiC;AAkBzE,OAAO,EAAE,+BAA+B,EAAE,kCAA8B;AACxE,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,wBAAwB,EACxB,cAAc,EACf,wCAAoC;AACrC,OAAO,EAAE,cAAc,EAAE,mDAA+C;AACxE,OAAO,EAAE,wBAAwB,EAAE,yCAAqC;AAExE;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,8BAA8B;IA8LzC,YACE,aAAuC,EACvC,aAAuC,EACvC,oBAA+C,EAC/C,WAAqB,EACrB,WAAsB,EACtB,gBAA2B,EAC3B,gBAA2B;QAtLrB,uBAAkB,GAAa,EAAE,CAAC,CAAC,uDAAuD;QAElG,uFAAuF;QAC/E,wBAAmB,GAAyB,IAAI,CAAC;QAEjD,yBAAoB,GAAwB,IAAI,CAAC;QAEzD,qDAAqD;QACrD,kEAAkE;QAC1D,iBAAY,GAAgB,IAAI,GAAG,EAAE,CAAC;QAEtC,oBAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;QAEjD,yBAAyB;QACR,qBAAgB,GAAG,IAAI,GAAG,EAGxC,CAAC;QAEa,wBAAmB,GAAG,IAAI,GAAG,EAE3C,CAAC;QAEJ,iFAAiF;QAChE,yBAAoB,GAAG,IAAI,GAAG,EAG5C,CAAC;QAEa,qBAAgB,GAAG,IAAI,GAAG,EAA6B,CAAC;QAExD,uBAAkB,GAAG,IAAI,GAAG,EAE1C,CAAC;QA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AC,UAAU,CAAC,EACvB,IAAI,CAAC,eAAe,CAAC,qBAAqB,EAAE;wBAC1C,GAAG,EAAE,UAAU;qBAChB,CAAC,CACH,CAAC;gBACJ,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,uBAAuB,CAAC,KAAK,EAAE,CAAC;QACvC,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CACvB,qFAAqF,EACrF;YACE,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACpC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["/* eslint-disable no-restricted-syntax, @typescript-eslint/prefer-nullish-coalescing, promise/always-return, promise/no-nesting, @typescript-eslint/no-floating-promises, jsdoc/require-param-description, jsdoc/require-returns, no-plusplus, no-negated-condition, consistent-return, @typescript-eslint/explicit-function-return-type, promise/param-names */\n// TODO: Fix ESLint errors in this file - tracked for Phase 4 cleanup\nimport type { CaipAccountId } from '@metamask/utils';\nimport type {\n ISubscription,\n AllMidsWsEvent,\n WebData2WsEvent,\n WebData3WsEvent,\n UserFillsWsEvent,\n ActiveAssetCtxWsEvent,\n ActiveSpotAssetCtxWsEvent,\n BboWsEvent,\n L2BookResponse,\n AssetCtxsWsEvent,\n FrontendOpenOrdersResponse,\n ClearinghouseStateWsEvent,\n OpenOrdersWsEvent,\n} from '@nktkas/hyperliquid';\n\nimport type { HyperLiquidClientService } from './HyperLiquidClientService';\nimport type { HyperLiquidWalletService } from './HyperLiquidWalletService';\nimport { TP_SL_CONFIG, PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PriceUpdate,\n Position,\n OrderFill,\n Order,\n AccountState,\n SubscribePricesParams,\n SubscribePositionsParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribeAccountParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n OrderBookData,\n OrderBookLevel,\n PerpsPlatformDependencies,\n} from '../types';\nimport { calculateWeightedReturnOnEquity } from '../utils/accountUtils';\nimport {\n adaptPositionFromSDK,\n adaptOrderFromSDK,\n adaptAccountStateFromSDK,\n parseAssetName,\n} from '../utils/hyperLiquidAdapter';\nimport { processBboData } from '../utils/hyperLiquidOrderBookProcessor';\nimport { calculateOpenInterestUSD } from '../utils/marketDataTransform';\n\n/**\n * Ensures we have a proper Error object for logging.\n * Converts unknown/string errors to proper Error instances.\n *\n * @param error - The caught error (could be Error, string, or unknown)\n * @returns A proper Error instance\n */\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n/**\n * Service for managing HyperLiquid WebSocket subscriptions\n * Implements singleton subscription architecture with reference counting\n */\nexport class HyperLiquidSubscriptionService {\n // Service dependencies\n private readonly clientService: HyperLiquidClientService;\n\n private readonly walletService: HyperLiquidWalletService;\n\n // HIP-3 feature flag support\n private hip3Enabled: boolean;\n\n private enabledDexs: string[]; // DEX identification (maps webData3 indices to DEX names)\n\n private allowlistMarkets: string[]; // Market filtering (allowlist)\n\n private blocklistMarkets: string[]; // Market filtering (blocklist)\n\n private discoveredDexNames: string[] = []; // DEX order for mapping webData3 perpDexStates indices\n\n // DEX discovery synchronization - allows subscriptions to wait for HIP-3 DEX discovery\n private dexDiscoveryPromise: Promise<void> | null = null;\n\n private dexDiscoveryResolver: (() => void) | null = null;\n\n // Track DEXs for synchronized position notifications\n // Ensures all DEXs send initial data before notifying subscribers\n private expectedDexs: Set<string> = new Set();\n\n private initializedDexs: Set<string> = new Set();\n\n // Subscriber collections\n private readonly priceSubscribers = new Map<\n string,\n Set<(prices: PriceUpdate[]) => void>\n >();\n\n private readonly positionSubscribers = new Set<\n (positions: Position[]) => void\n >();\n\n // Order fill subscribers keyed by accountId (normalized: undefined -> 'default')\n private readonly orderFillSubscribers = new Map<\n string,\n Set<(fills: OrderFill[], isSnapshot?: boolean) => void>\n >();\n\n private readonly orderSubscribers = new Set<(orders: Order[]) => void>();\n\n private readonly accountSubscribers = new Set<\n (account: AccountState) => void\n >();\n\n // Track which subscribers want market data\n private readonly marketDataSubscribers = new Map<\n string,\n Set<(prices: PriceUpdate[]) => void>\n >();\n\n // Track which subscribers want top-of-book (best bid/ask) data\n private readonly orderBookSubscribers = new Map<\n string,\n Set<(prices: PriceUpdate[]) => void>\n >();\n\n // Global singleton subscriptions\n private globalAllMidsSubscription?: ISubscription;\n\n private globalAllMidsPromise?: Promise<void>; // Track in-progress subscription\n\n private readonly globalActiveAssetSubscriptions = new Map<\n string,\n ISubscription\n >();\n\n private readonly globalBboSubscriptions = new Map<string, ISubscription>();\n\n // Order fill subscriptions keyed by accountId (normalized: undefined -> 'default')\n private readonly orderFillSubscriptions = new Map<string, ISubscription>();\n\n private readonly symbolSubscriberCounts = new Map<string, number>();\n\n private readonly dexSubscriberCounts = new Map<string, number>(); // Track subscribers per DEX for assetCtxs\n\n // Multi-DEX webData3 subscription for all user data (positions, orders, account, OI caps)\n private readonly webData3Subscriptions = new Map<string, ISubscription>(); // Key: dex name ('' for main)\n\n private webData3SubscriptionPromise?: Promise<void>;\n\n private positionSubscriberCount = 0;\n\n private orderSubscriberCount = 0;\n\n private accountSubscriberCount = 0;\n\n private oiCapSubscriberCount = 0;\n\n // Multi-DEX data caches\n private readonly dexPositionsCache = new Map<string, Position[]>(); // Per-DEX positions\n\n private readonly dexOrdersCache = new Map<string, Order[]>(); // Per-DEX orders\n\n private readonly dexAccountCache = new Map<string, AccountState>(); // Per-DEX account state\n\n private cachedPositions: Position[] | null = null; // Aggregated positions\n\n private cachedOrders: Order[] | null = null; // Aggregated orders\n\n private cachedAccount: AccountState | null = null; // Aggregated account\n\n private ordersCacheInitialized = false; // Track if orders cache has received WebSocket data\n\n private positionsCacheInitialized = false; // Track if positions cache has received WebSocket data\n\n // OI Cap tracking (from webData3.perpDexStates[].perpsAtOpenInterestCap)\n private readonly oiCapSubscribers = new Set<(caps: string[]) => void>();\n\n private cachedOICaps: string[] = [];\n\n private cachedOICapsHash = '';\n\n private oiCapsCacheInitialized = false;\n\n // Global price data cache\n private cachedPriceData: Map<string, PriceUpdate> | null = null;\n\n // HIP-3: assetCtxs subscriptions for multi-DEX market data\n private readonly assetCtxsSubscriptions = new Map<string, ISubscription>(); // Key: dex name ('' for main)\n\n private readonly dexAssetCtxsCache = new Map<\n string,\n AssetCtxsWsEvent['ctxs']\n >(); // Per-DEX asset contexts\n\n private readonly assetCtxsSubscriptionPromises = new Map<\n string,\n Promise<void>\n >(); // Track in-progress subscriptions\n\n private readonly clearinghouseStateSubscriptions = new Map<\n string,\n ISubscription\n >(); // Key: dex name ('' for main)\n\n private readonly openOrdersSubscriptions = new Map<string, ISubscription>(); // Key: dex name ('' for main)\n\n // Meta cache per DEX - populated by metaAndAssetCtxs, used by createAssetCtxsSubscription\n // This avoids redundant meta() API calls since metaAndAssetCtxs already returns meta data\n private readonly dexMetaCache = new Map<\n string,\n {\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n }[];\n }\n >();\n\n // Order book data cache\n private readonly orderBookCache = new Map<\n string,\n {\n bestBid?: string;\n bestAsk?: string;\n spread?: string;\n lastUpdated: number;\n }\n >();\n\n // Market data caching for multi-channel consolidation\n private readonly marketDataCache = new Map<\n string,\n {\n prevDayPx?: number;\n funding?: number;\n openInterest?: number;\n volume24h?: number;\n oraclePrice?: number;\n lastUpdated: number;\n }\n >();\n\n // Platform dependencies for logging\n private readonly deps: PerpsPlatformDependencies;\n\n // Cache hashes to avoid recomputation\n private cachedPositionsHash = '';\n\n private cachedOrdersHash = '';\n\n private cachedAccountHash = '';\n\n constructor(\n clientService: HyperLiquidClientService,\n walletService: HyperLiquidWalletService,\n platformDependencies: PerpsPlatformDependencies,\n hip3Enabled?: boolean,\n enabledDexs?: string[],\n allowlistMarkets?: string[],\n blocklistMarkets?: string[],\n ) {\n this.clientService = clientService;\n this.walletService = walletService;\n this.deps = platformDependencies;\n this.hip3Enabled = hip3Enabled ?? false;\n this.enabledDexs = enabledDexs ?? [];\n this.discoveredDexNames = enabledDexs ?? [];\n this.allowlistMarkets = allowlistMarkets ?? [];\n this.blocklistMarkets = blocklistMarkets ?? [];\n }\n\n /**\n * Get error context for logging with searchable tags and context.\n * Enables Sentry dashboard filtering by feature, provider, and network.\n *\n * @param method - The method name where the error occurred\n * @param extra - Optional additional context fields (merged into searchable context.data)\n * @returns Error options with tags (searchable) and context (searchable)\n */\n private getErrorContext(\n method: string,\n extra?: Record<string, unknown>,\n ): {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n } {\n return {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: 'hyperliquid',\n network: this.clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n },\n context: {\n name: 'HyperLiquidSubscriptionService',\n data: {\n method,\n ...extra,\n },\n },\n };\n }\n\n /**\n * Check if a DEX is enabled in our configuration\n * Used to filter webData3 callback data to only process DEXs we care about\n *\n * @param dex - DEX name (null for main DEX, string for HIP-3)\n * @returns true if this DEX should be processed\n */\n private isDexEnabled(dex: string | null): boolean {\n if (dex === null) {\n return true; // Main DEX always enabled\n }\n if (!this.hip3Enabled) {\n return false; // HIP-3 disabled entirely\n }\n return this.enabledDexs.includes(dex);\n }\n\n /**\n * Populate DEX meta cache with pre-fetched meta data\n * Called by Provider after buildAssetMapping to share cached meta,\n * avoiding redundant metaAndAssetCtxs/meta API calls during subscription setup\n *\n * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)\n * @param meta - Meta response containing universe data\n * @param meta.universe\n */\n public setDexMetaCache(\n dex: string,\n meta: {\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n }[];\n },\n ): void {\n this.dexMetaCache.set(dex, meta);\n this.deps.debugLogger.log(\n '[SubscriptionService] DEX meta cache populated',\n {\n dex: dex || 'main',\n universeSize: meta.universe.length,\n },\n );\n }\n\n /**\n * Cache asset contexts for a specific DEX from API response\n * This allows buildAssetMapping() to populate cache for getMarketDataWithPrices() to use\n *\n * @param dex - DEX name ('' for main perps)\n * @param assetCtxs - Asset contexts from metaAndAssetCtxs response\n */\n public setDexAssetCtxsCache(\n dex: string,\n assetCtxs: AssetCtxsWsEvent['ctxs'],\n ): void {\n this.dexAssetCtxsCache.set(dex, assetCtxs);\n this.deps.debugLogger.log(\n '[SubscriptionService] DEX assetCtxs cache populated',\n {\n dex: dex || 'main',\n ctxsCount: assetCtxs.length,\n },\n );\n }\n\n /**\n * Get cached assetCtxs for a DEX\n * Returns the cached asset contexts from WebSocket subscription if available\n *\n * @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)\n * @returns Array of asset contexts or undefined if not cached\n */\n public getDexAssetCtxsCache(\n dex: string,\n ): AssetCtxsWsEvent['ctxs'] | undefined {\n return this.dexAssetCtxsCache.get(dex);\n }\n\n /**\n * Wait for DEX discovery to complete (with timeout)\n * Used when HIP-3 is enabled but enabledDexs hasn't been populated yet.\n * This allows subscriptions to wait for DEX discovery before creating per-DEX subscriptions.\n *\n * @param timeoutMs - Timeout in milliseconds (default: 5000)\n */\n private async waitForDexDiscovery(timeoutMs: number = 5000): Promise<void> {\n // Already have DEXs, no need to wait\n if (this.enabledDexs.length > 0) {\n return;\n }\n\n // Create promise if not exists\n if (!this.dexDiscoveryPromise) {\n this.dexDiscoveryPromise = new Promise<void>((resolve) => {\n this.dexDiscoveryResolver = resolve;\n });\n }\n\n // Wait with timeout\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error('DEX discovery timeout')),\n timeoutMs,\n );\n });\n\n try {\n await Promise.race([this.dexDiscoveryPromise, timeoutPromise]);\n } catch {\n this.deps.debugLogger.log(\n 'DEX discovery wait timed out, proceeding with main DEX only',\n );\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n /**\n * Update feature flags for HIP-3 support\n * Called when provider configuration changes at runtime\n * Note: Market filtering is NOT applied in subscription service - only in Provider\n *\n * @param hip3Enabled - Whether HIP-3 is enabled\n * @param enabledDexs - List of enabled DEX identifiers\n * @param allowlistMarkets - List of allowed markets\n * @param blocklistMarkets - List of blocked markets\n */\n public async updateFeatureFlags(\n hip3Enabled: boolean,\n enabledDexs: string[],\n allowlistMarkets: string[],\n blocklistMarkets: string[],\n ): Promise<void> {\n const previousEnabledDexs = [...this.enabledDexs];\n const previousAllowlistMarkets = [...this.allowlistMarkets];\n const previousBlocklistMarkets = [...this.blocklistMarkets];\n const previousHip3Enabled = this.hip3Enabled;\n\n this.hip3Enabled = hip3Enabled;\n this.enabledDexs = enabledDexs;\n this.allowlistMarkets = allowlistMarkets;\n this.blocklistMarkets = blocklistMarkets;\n this.discoveredDexNames = enabledDexs; // Store DEX order for webData3 index mapping\n\n // Resolve any pending DEX discovery wait now that DEXs are available\n if (this.dexDiscoveryResolver && enabledDexs.length > 0) {\n this.dexDiscoveryResolver();\n this.dexDiscoveryPromise = null;\n this.dexDiscoveryResolver = null;\n }\n\n this.deps.debugLogger.log('Feature flags updated:', {\n previousHip3Enabled,\n hip3Enabled,\n previousEnabledDexs,\n enabledDexs,\n previousAllowlistMarkets,\n allowlistMarkets,\n previousBlocklistMarkets,\n blocklistMarkets,\n });\n\n // If equity was just enabled or new DEXs were added\n const newDexs = enabledDexs.filter(\n (dex) => !previousEnabledDexs.includes(dex),\n );\n if (\n (!previousHip3Enabled && hip3Enabled && enabledDexs.length > 0) ||\n newDexs.length > 0\n ) {\n this.deps.debugLogger.log(\n 'Establishing subscriptions for new DEXs:',\n newDexs,\n );\n\n // Establish assetCtxs subscriptions for new DEXs (for market data)\n const hasMarketDataSubscribers = this.marketDataSubscribers.size > 0;\n if (hasMarketDataSubscribers) {\n await Promise.all(\n newDexs.map(async (dex) => {\n try {\n await this.ensureAssetCtxsSubscription(dex);\n } catch (assetCtxsError) {\n this.deps.logger.error(\n ensureError(assetCtxsError),\n this.getErrorContext(\n 'updateFeatureFlags.ensureAssetCtxsSubscription',\n {\n dex,\n },\n ),\n );\n }\n }),\n );\n }\n\n // Establish clearinghouseState/openOrders subscriptions for new DEXs\n // (needed for positions, orders, and account data when using individual subscriptions)\n const hasUserDataSubscribers =\n this.positionSubscriberCount > 0 ||\n this.orderSubscriberCount > 0 ||\n this.accountSubscriberCount > 0;\n\n if (hasUserDataSubscribers && this.hip3Enabled) {\n try {\n const userAddress =\n await this.walletService.getUserAddressWithDefault();\n\n await Promise.all(\n newDexs.map(async (dex) => {\n try {\n await this.ensureClearinghouseStateSubscription(\n userAddress,\n dex,\n );\n await this.ensureOpenOrdersSubscription(userAddress, dex);\n this.deps.debugLogger.log(\n `Established user data subscriptions for new DEX: ${dex}`,\n );\n } catch (userDataError) {\n this.deps.logger.error(\n ensureError(userDataError),\n this.getErrorContext(\n 'updateFeatureFlags.ensureUserDataSubscription',\n { dex },\n ),\n );\n }\n }),\n );\n } catch (addressError) {\n this.deps.logger.error(\n ensureError(addressError),\n this.getErrorContext('updateFeatureFlags.getUserAddress'),\n );\n }\n }\n }\n }\n\n /**\n * Fast hash function for change detection\n * Uses string concatenation of key fields instead of JSON.stringify()\n * Performance: ~100x faster than JSON.stringify() for typical objects\n * Tracks structural changes (coin, size, entryPrice, leverage, TP/SL prices/counts)\n * and value changes (unrealizedPnl, returnOnEquity) for live P&L updates\n *\n * @param positions - Positions to hash\n * @returns Hash string\n */\n private hashPositions(positions: Position[]): string {\n if (!positions || positions.length === 0) {\n return '0';\n }\n return positions\n .map(\n (pos) =>\n `${pos.symbol}:${pos.size}:${pos.entryPrice}:${pos.leverage.value}:${\n pos.takeProfitPrice || ''\n }:${pos.stopLossPrice || ''}:${pos.takeProfitCount}:${pos.stopLossCount}:${\n pos.unrealizedPnl\n }:${pos.returnOnEquity}`,\n )\n .join('|');\n }\n\n /**\n * Fast hash function for orders\n *\n * @param orders - Orders to hash\n * @returns Hash string\n */\n private hashOrders(orders: Order[]): string {\n if (!orders || orders.length === 0) {\n return '0';\n }\n return orders\n .map(\n (ord) =>\n `${ord.symbol}:${ord.side}:${ord.size}:${ord.price}:${ord.orderType}`,\n )\n .join('|');\n }\n\n /**\n * Fast hash function for account state\n *\n * @param account - Account state to hash\n * @returns Hash string\n */\n private hashAccountState(account: AccountState): string {\n return `${account.availableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}`;\n }\n\n /**\n * Extract TP/SL from orders and optionally convert raw SDK orders to Order format.\n * DRY helper used by both webData2 and clearinghouseState callbacks.\n *\n * @param orders - Raw SDK orders from WebSocket event\n * @param positions - Current positions for TP/SL matching\n * @param cachedProcessedOrders - Optional pre-processed orders (skips conversion if provided)\n * @returns Maps for TP/SL prices and counts, plus processed Order array\n */\n private extractTPSLFromOrders(\n orders: FrontendOpenOrdersResponse,\n positions: Position[],\n cachedProcessedOrders?: Order[],\n ): {\n tpslMap: Map<string, { takeProfitPrice?: string; stopLossPrice?: string }>;\n tpslCountMap: Map<\n string,\n { takeProfitCount?: number; stopLossCount?: number }\n >;\n processedOrders: Order[];\n } {\n const tpslMap = new Map<\n string,\n { takeProfitPrice?: string; stopLossPrice?: string }\n >();\n\n const tpslCountMap = new Map<\n string,\n { takeProfitCount?: number; stopLossCount?: number }\n >();\n\n // If cached processed orders provided, extract TP/SL from them directly\n if (cachedProcessedOrders) {\n cachedProcessedOrders.forEach((order) => {\n // Use triggerPrice for TP/SL (trigger condition price), falling back to price\n // This ensures consistency with raw SDK order processing which uses triggerPx\n const tpslPrice = order.triggerPrice || order.price;\n if (order.isTrigger && tpslPrice) {\n const isTakeProfit = order.detailedOrderType?.includes('Take Profit');\n const isStop = order.detailedOrderType?.includes('Stop');\n\n const matchingPosition = positions.find(\n (pos) => pos.symbol === order.symbol,\n );\n\n // Determine TP vs SL classification for count and price updates\n // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types\n let classifiedAsTakeProfit = isTakeProfit;\n let classifiedAsStop = isStop;\n\n if (!isTakeProfit && !isStop && matchingPosition) {\n // Fallback: determine based on trigger price vs entry price\n // This handles orders with ambiguous type 'Trigger'\n const triggerPrice = parseFloat(tpslPrice);\n const entryPrice = parseFloat(matchingPosition.entryPrice || '0');\n const isLong = parseFloat(matchingPosition.size) > 0;\n\n if (isLong) {\n if (triggerPrice > entryPrice) {\n classifiedAsTakeProfit = true;\n } else {\n classifiedAsStop = true;\n }\n } else if (triggerPrice < entryPrice) {\n classifiedAsTakeProfit = true;\n } else {\n classifiedAsStop = true;\n }\n }\n\n const currentTakeProfitCount =\n tpslCountMap.get(order.symbol)?.takeProfitCount || 0;\n const currentStopLossCount =\n tpslCountMap.get(order.symbol)?.stopLossCount || 0;\n\n tpslCountMap.set(order.symbol, {\n takeProfitCount: classifiedAsTakeProfit\n ? currentTakeProfitCount + 1\n : currentTakeProfitCount,\n stopLossCount: classifiedAsStop\n ? currentStopLossCount + 1\n : currentStopLossCount,\n });\n\n if (matchingPosition) {\n const existing = tpslMap.get(order.symbol) || {};\n if (classifiedAsTakeProfit) {\n existing.takeProfitPrice = tpslPrice;\n } else if (classifiedAsStop) {\n existing.stopLossPrice = tpslPrice;\n }\n tpslMap.set(order.symbol, existing);\n }\n }\n });\n\n return { tpslMap, tpslCountMap, processedOrders: cachedProcessedOrders };\n }\n\n // Process raw SDK orders\n const processedOrders: Order[] = [];\n\n orders.forEach((order) => {\n let position: Position | undefined;\n let positionForCoin: Position | undefined;\n\n const matchPositionToTpsl = (pos: Position) => {\n if (TP_SL_CONFIG.UsePositionBoundTpsl) {\n return (\n pos.symbol === order.coin &&\n order.reduceOnly &&\n order.isPositionTpsl\n );\n }\n\n return (\n pos.symbol === order.coin &&\n Math.abs(parseFloat(order.sz)) >= Math.abs(parseFloat(pos.size))\n );\n };\n\n const matchPositionToCoin = (pos: Position) => pos.symbol === order.coin;\n\n // Process trigger orders for TP/SL extraction\n if (order.triggerPx) {\n const isTakeProfit = order.orderType?.includes('Take Profit');\n const isStop = order.orderType?.includes('Stop');\n\n const { coin } = order;\n position = positions.find(matchPositionToTpsl);\n positionForCoin = positions.find(matchPositionToCoin);\n\n // Determine TP vs SL classification for count and price updates\n // Use order type first, fallback to price-based detection for ambiguous 'Trigger' types\n // This matches the cached order processing logic for consistency\n let classifiedAsTakeProfit = isTakeProfit;\n let classifiedAsStop = isStop;\n\n if (!isTakeProfit && !isStop && position) {\n // Fallback: determine based on trigger price vs entry price\n // This handles orders with ambiguous type 'Trigger'\n const triggerPrice = parseFloat(order.triggerPx);\n const entryPrice = parseFloat(position.entryPrice || '0');\n const isLong = parseFloat(position.size) > 0;\n\n if (isLong) {\n if (triggerPrice > entryPrice) {\n classifiedAsTakeProfit = true;\n } else {\n classifiedAsStop = true;\n }\n } else if (triggerPrice < entryPrice) {\n classifiedAsTakeProfit = true;\n } else {\n classifiedAsStop = true;\n }\n }\n\n const currentTakeProfitCount =\n tpslCountMap.get(coin)?.takeProfitCount || 0;\n const currentStopLossCount = tpslCountMap.get(coin)?.stopLossCount || 0;\n\n tpslCountMap.set(coin, {\n takeProfitCount: classifiedAsTakeProfit\n ? currentTakeProfitCount + 1\n : currentTakeProfitCount,\n stopLossCount: classifiedAsStop\n ? currentStopLossCount + 1\n : currentStopLossCount,\n });\n\n if (position) {\n const existing = tpslMap.get(coin) || {};\n\n // Use classified values for price assignment (consistent with count logic)\n if (classifiedAsTakeProfit) {\n existing.takeProfitPrice = order.triggerPx;\n } else if (classifiedAsStop) {\n existing.stopLossPrice = order.triggerPx;\n }\n\n tpslMap.set(coin, existing);\n }\n }\n\n // Convert ALL open orders to Order format\n const convertedOrder = adaptOrderFromSDK(\n order,\n position || positionForCoin,\n );\n processedOrders.push(convertedOrder);\n });\n\n return { tpslMap, tpslCountMap, processedOrders };\n }\n\n /**\n * Merge TP/SL data into positions\n * DRY helper used by both webData2 and clearinghouseState callbacks\n *\n * @param positions - Base positions without TP/SL\n * @param tpslMap - Map of coin -> TP/SL prices\n * @param tpslCountMap - Map of coin -> TP/SL counts\n * @returns Positions enhanced with TP/SL data\n */\n private mergeTPSLIntoPositions(\n positions: Position[],\n tpslMap: Map<string, { takeProfitPrice?: string; stopLossPrice?: string }>,\n tpslCountMap: Map<\n string,\n { takeProfitCount?: number; stopLossCount?: number }\n >,\n ): Position[] {\n return positions.map((position) => {\n const tpsl = tpslMap.get(position.symbol) || {};\n const tpslCount = tpslCountMap.get(position.symbol) || {};\n return {\n ...position,\n takeProfitPrice: tpsl.takeProfitPrice || undefined,\n stopLossPrice: tpsl.stopLossPrice || undefined,\n takeProfitCount: tpslCount.takeProfitCount || 0,\n stopLossCount: tpslCount.stopLossCount || 0,\n };\n });\n }\n\n /**\n * Aggregate account states from all cached DEXs\n * Sums balances and creates per-DEX breakdown for multi-DEX portfolio view\n *\n * @returns Aggregated account state with dexBreakdown field\n */\n private aggregateAccountStates(): AccountState {\n const subAccountBreakdown: Record<\n string,\n { availableBalance: string; totalBalance: string }\n > = {};\n let totalAvailableBalance = 0;\n let totalBalance = 0;\n let totalMarginUsed = 0;\n let totalUnrealizedPnl = 0;\n\n // Collect account states for weighted ROE calculation\n const accountStatesForROE: {\n unrealizedPnl: string;\n returnOnEquity: string;\n }[] = [];\n\n // Aggregate all cached account states\n Array.from(this.dexAccountCache.entries()).forEach(\n ([currentDex, state]) => {\n const dexKey = currentDex === '' ? 'main' : currentDex;\n subAccountBreakdown[dexKey] = {\n availableBalance: state.availableBalance,\n totalBalance: state.totalBalance,\n };\n totalAvailableBalance += parseFloat(state.availableBalance);\n totalBalance += parseFloat(state.totalBalance);\n totalMarginUsed += parseFloat(state.marginUsed);\n totalUnrealizedPnl += parseFloat(state.unrealizedPnl);\n\n // Collect data for weighted ROE calculation\n accountStatesForROE.push({\n unrealizedPnl: state.unrealizedPnl,\n returnOnEquity: state.returnOnEquity,\n });\n },\n );\n\n // Use first DEX's account state as base and override aggregated values\n const firstDexAccount =\n this.dexAccountCache.values().next().value || ({} as AccountState);\n\n // Calculate weighted returnOnEquity across all DEXs\n const returnOnEquity = calculateWeightedReturnOnEquity(accountStatesForROE);\n\n return {\n ...firstDexAccount,\n availableBalance: totalAvailableBalance.toString(),\n totalBalance: totalBalance.toString(),\n marginUsed: totalMarginUsed.toString(),\n unrealizedPnl: totalUnrealizedPnl.toString(),\n subAccountBreakdown,\n returnOnEquity,\n };\n }\n\n /**\n * Subscribe to live price updates with singleton subscription architecture\n * Uses allMids for fast price updates and predictedFundings for accurate funding rates\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public async subscribeToPrices(\n params: SubscribePricesParams,\n ): Promise<() => void> {\n const {\n symbols,\n callback,\n includeOrderBook = false,\n includeMarketData = false,\n } = params;\n const unsubscribers: (() => void)[] = [];\n\n symbols.forEach((symbol) => {\n unsubscribers.push(\n this.createSubscription(this.priceSubscribers, callback, symbol),\n );\n // Track market data subscribers separately\n if (includeMarketData) {\n unsubscribers.push(\n this.createSubscription(this.marketDataSubscribers, callback, symbol),\n );\n }\n // Track order book subscribers separately\n if (includeOrderBook) {\n unsubscribers.push(\n this.createSubscription(this.orderBookSubscribers, callback, symbol),\n );\n }\n });\n\n await this.clientService.ensureSubscriptionClient(\n this.walletService.createWalletAdapter(),\n );\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n this.deps.debugLogger.log(\n 'SubscriptionClient not available for price subscription',\n );\n return () => unsubscribers.forEach((fn) => fn());\n }\n\n // Ensure global subscriptions are established\n this.ensureGlobalAllMidsSubscription();\n\n // HIP-3: Establish assetCtxs subscriptions ONLY for DEXs with requested symbols\n // Performance: Avoid unnecessary WebSocket connections for unused DEXs\n if (includeMarketData) {\n // Extract unique DEXs from requested symbols\n const dexsNeeded = new Set<string | null>();\n symbols.forEach((symbol) => {\n const { dex } = parseAssetName(symbol);\n dexsNeeded.add(dex);\n });\n\n // Only subscribe to DEXs that have requested symbols\n dexsNeeded.forEach((dex) => {\n const dexName = dex ?? '';\n this.ensureAssetCtxsSubscription(dexName).catch((assetCtxsError) => {\n this.deps.logger.error(\n ensureError(assetCtxsError),\n this.getErrorContext(\n 'subscribeToPrices.ensureAssetCtxsSubscription',\n { dex: dexName },\n ),\n );\n });\n });\n }\n\n // Note: Funding rates are now cached via assetCtxs WebSocket subscription\n // (ensureAssetCtxsSubscription above), eliminating the need for a separate\n // metaAndAssetCtxs API call here. The WebSocket callback in createAssetCtxsSubscription\n // populates marketDataCache with funding rates as they arrive.\n\n symbols.forEach((symbol) => {\n // Subscribe to activeAssetCtx only when market data is requested\n if (includeMarketData) {\n this.ensureActiveAssetSubscription(symbol);\n }\n if (includeOrderBook) {\n this.ensureBboSubscription(symbol);\n }\n });\n\n // Send cached data immediately if available\n symbols.forEach((symbol) => {\n const cachedPrice = this.cachedPriceData?.get(symbol);\n if (cachedPrice) {\n callback([cachedPrice]);\n }\n });\n\n // Return cleanup function\n return () => {\n unsubscribers.forEach((fn) => fn());\n // Cleanup subscriptions with reference counting\n symbols.forEach((symbol) => {\n if (includeMarketData) {\n this.cleanupActiveAssetSubscription(symbol);\n }\n if (includeOrderBook) {\n this.cleanupBboSubscription(symbol);\n }\n });\n\n // Cleanup DEX-level assetCtxs subscriptions\n if (includeMarketData) {\n // Extract unique DEXs from requested symbols\n const dexsNeeded = new Set<string | null>();\n symbols.forEach((symbol) => {\n const { dex } = parseAssetName(symbol);\n dexsNeeded.add(dex);\n });\n\n // Cleanup assetCtxs subscription for each DEX\n dexsNeeded.forEach((dex) => {\n const dexName = dex ?? '';\n this.cleanupAssetCtxsSubscription(dexName);\n });\n }\n };\n }\n\n /**\n * Ensure shared webData3 subscription is active (singleton pattern with multi-DEX support)\n * webData3 provides data for all DEXs (main + HIP-3) in a single subscription\n *\n * @param accountId - Optional account ID\n */\n private async ensureSharedWebData3Subscription(\n accountId?: CaipAccountId,\n ): Promise<void> {\n // Establish webData3 subscription (if not exists)\n if (!this.webData3Subscriptions.has('')) {\n if (!this.webData3SubscriptionPromise) {\n this.webData3SubscriptionPromise =\n this.createUserDataSubscription(accountId);\n\n try {\n await this.webData3SubscriptionPromise;\n } catch {\n this.webData3SubscriptionPromise = undefined;\n throw new Error('Failed to create user data subscription');\n }\n } else {\n await this.webData3SubscriptionPromise;\n }\n }\n // Note: webData3 includes all DEX data, so no separate HIP-3 subscriptions needed\n }\n\n /**\n * Create WebSocket subscription for user data (positions, orders, account)\n * - Uses webData2 when HIP-3 disabled (main DEX only)\n * - Uses webData3 when HIP-3 enabled (main + HIP-3 DEXs)\n *\n * webData2 provides data for main DEX only\n * webData3 provides perpDexStates[] array containing data for all DEXs:\n * - Index 0: Main DEX (dexName = '')\n * - Index 1+: HIP-3 DEXs in order of enabledDexs array\n *\n * @param accountId - Optional account ID\n */\n private async createUserDataSubscription(\n accountId?: CaipAccountId,\n ): Promise<void> {\n await this.clientService.ensureSubscriptionClient(\n this.walletService.createWalletAdapter(),\n );\n const subscriptionClient = this.clientService.getSubscriptionClient();\n\n if (!subscriptionClient) {\n throw new Error('Subscription client not initialized');\n }\n\n const userAddress =\n await this.walletService.getUserAddressWithDefault(accountId);\n\n const dexName = ''; // Use empty string as key for single subscription\n\n // Skip if subscription already exists\n if (this.webData3Subscriptions.has(dexName)) {\n return;\n }\n\n // Wait for DEX discovery if HIP-3 is enabled but DEXs haven't been discovered yet\n // This ensures HIP-3 subscriptions are created together with main DEX\n if (this.hip3Enabled && this.enabledDexs.length === 0) {\n this.deps.debugLogger.log(\n 'Waiting for DEX discovery before creating subscriptions...',\n );\n await this.waitForDexDiscovery();\n this.deps.debugLogger.log(\n 'DEX discovery complete, proceeding with subscriptions',\n {\n enabledDexs: this.enabledDexs,\n },\n );\n }\n\n return new Promise<void>((resolve, reject) => {\n // Choose channel based on HIP-3 master switch\n if (!this.hip3Enabled) {\n // HIP-3 disabled: Use webData2 (main DEX only)\n subscriptionClient\n .webData2({ user: userAddress }, (data: WebData2WsEvent) => {\n try {\n // webData2 returns clearinghouseState for main DEX only\n const currentDexName = ''; // Main DEX\n\n // Check for removed fields before accessing\n if (!data.clearinghouseState) {\n return;\n }\n\n // Extract and process positions from clearinghouseState\n const positions = data.clearinghouseState.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos));\n\n // Extract TP/SL from orders\n const {\n tpslMap,\n tpslCountMap,\n processedOrders: processedOrdersData,\n } = this.extractTPSLFromOrders(data.openOrders || [], positions);\n\n // Merge TP/SL data into positions\n const positionsWithTPSL = this.mergeTPSLIntoPositions(\n positions,\n tpslMap,\n tpslCountMap,\n );\n\n // Extract account data (webData2 provides clearinghouseState)\n const accountState: AccountState = adaptAccountStateFromSDK(\n data.clearinghouseState,\n undefined, // webData2 doesn't include spotState\n );\n\n // Store in caches (main DEX only)\n this.dexPositionsCache.set(currentDexName, positionsWithTPSL);\n this.dexOrdersCache.set(currentDexName, processedOrdersData);\n this.dexAccountCache.set(currentDexName, accountState);\n\n // OI caps (main DEX only)\n const oiCaps = data.perpsAtOpenInterestCap || [];\n const oiCapsHash = [...oiCaps]\n .sort((a: string, b: string) => a.localeCompare(b))\n .join(',');\n if (oiCapsHash !== this.cachedOICapsHash) {\n this.cachedOICaps = oiCaps;\n this.cachedOICapsHash = oiCapsHash;\n this.oiCapsCacheInitialized = true;\n this.oiCapSubscribers.forEach((oiCallback) =>\n oiCallback(oiCaps),\n );\n }\n\n // Notify subscribers (no aggregation needed - only main DEX)\n const positionsHash = this.hashPositions(positionsWithTPSL);\n const ordersHash = this.hashOrders(processedOrdersData);\n const accountHash = this.hashAccountState(accountState);\n\n if (positionsHash !== this.cachedPositionsHash) {\n this.cachedPositions = positionsWithTPSL;\n this.cachedPositionsHash = positionsHash;\n this.positionsCacheInitialized = true;\n this.positionSubscribers.forEach((posCallback) =>\n posCallback(positionsWithTPSL),\n );\n }\n\n if (ordersHash !== this.cachedOrdersHash) {\n this.cachedOrders = processedOrdersData;\n this.cachedOrdersHash = ordersHash;\n this.ordersCacheInitialized = true;\n this.orderSubscribers.forEach((ordCallback) =>\n ordCallback(processedOrdersData),\n );\n }\n\n if (accountHash !== this.cachedAccountHash) {\n this.cachedAccount = accountState;\n this.cachedAccountHash = accountHash;\n this.accountSubscribers.forEach((accCallback) =>\n accCallback(accountState),\n );\n }\n } catch (callbackError) {\n this.deps.logger.error(\n ensureError(callbackError),\n this.getErrorContext('webData2 callback error', {\n user: userAddress,\n dataKeys: data ? Object.keys(data) : 'data is null/undefined',\n hasClearinghouseState: data?.clearinghouseState !== undefined,\n hasOpenOrders: data?.openOrders !== undefined,\n hasPerpsAtOpenInterestCap:\n data?.perpsAtOpenInterestCap !== undefined,\n }),\n );\n }\n })\n .then((subscription) => {\n this.webData3Subscriptions.set(dexName, subscription);\n this.deps.debugLogger.log(\n 'webData2 subscription established for main DEX only',\n );\n resolve();\n })\n .catch((subscribeError) => {\n this.deps.logger.error(\n ensureError(subscribeError),\n this.getErrorContext('createUserDataSubscription (webData2)', {\n dex: dexName,\n }),\n );\n reject(ensureError(subscribeError));\n });\n } else {\n // HIP-3 enabled: Use individual subscriptions for positions/orders/account\n // webData3 is only used for OI caps extraction\n\n // Determine which DEXs to subscribe to\n const dexsToSubscribe = [\n '', // Main DEX\n ...this.enabledDexs.filter((dex) => this.isDexEnabled(dex)),\n ];\n\n // Track expected DEXs for synchronized notifications\n // Clear previous tracking and set new expected DEXs\n this.expectedDexs = new Set(dexsToSubscribe);\n this.initializedDexs = new Set();\n\n // Set up individual subscriptions for each DEX\n const subscriptionPromises: Promise<void>[] = [];\n\n for (const currentDexName of dexsToSubscribe) {\n // Set up clearinghouseState subscription for positions + account\n subscriptionPromises.push(\n this.ensureClearinghouseStateSubscription(\n userAddress,\n currentDexName,\n ),\n );\n\n // Set up openOrders subscription for orders\n subscriptionPromises.push(\n this.ensureOpenOrdersSubscription(userAddress, currentDexName),\n );\n }\n\n // Also set up webData3 for OI caps only\n const webData3Promise = subscriptionClient\n .webData3({ user: userAddress }, (data: WebData3WsEvent) => {\n try {\n // webData3 is ONLY used for OI caps extraction\n // Positions, orders, and account data come from individual subscriptions\n const allOICaps: string[] = [];\n data.perpDexStates.forEach((dexState, index) => {\n // Map webData3 index to DEX name\n // Index 0 = main DEX (null), Index 1+ = HIP-3 DEXs from discoveredDexNames\n const dexIdentifier =\n index === 0 ? null : this.discoveredDexNames[index - 1];\n\n // Skip unknown DEXs (not in discoveredDexNames) to prevent main DEX cache corruption\n if (index > 0 && dexIdentifier === undefined) {\n return; // Unknown DEX - skip to prevent misidentifying as main DEX\n }\n\n // Only process DEXs we care about (skip others silently)\n if (!this.isDexEnabled(dexIdentifier ?? null)) {\n return; // Skip this DEX - not enabled in our configuration\n }\n\n const currentDexNameInLoop = dexIdentifier ?? '';\n\n const oiCaps = dexState.perpsAtOpenInterestCap || [];\n\n // Add DEX prefix for HIP-3 symbols (e.g., \"xyz:TSLA\")\n if (currentDexNameInLoop) {\n allOICaps.push(\n ...oiCaps.map(\n (symbolName) => `${currentDexNameInLoop}:${symbolName}`,\n ),\n );\n } else {\n // Main DEX - no prefix needed\n allOICaps.push(...oiCaps);\n }\n });\n\n // Update OI caps cache and notify if changed\n const oiCapsHash = [...allOICaps]\n .sort((a: string, b: string) => a.localeCompare(b))\n .join(',');\n if (oiCapsHash !== this.cachedOICapsHash) {\n this.cachedOICaps = allOICaps;\n this.cachedOICapsHash = oiCapsHash;\n this.oiCapsCacheInitialized = true;\n\n // Notify all subscribers\n this.oiCapSubscribers.forEach((oiCallback) =>\n oiCallback(allOICaps),\n );\n }\n } catch (callbackError) {\n this.deps.logger.error(\n ensureError(callbackError),\n this.getErrorContext('webData3 callback error', {\n user: userAddress,\n hasPerpDexStates: data?.perpDexStates !== undefined,\n perpDexStatesLength: data?.perpDexStates?.length ?? 0,\n }),\n );\n }\n })\n .then((sub) => {\n this.webData3Subscriptions.set(dexName, sub);\n this.deps.debugLogger.log(\n `webData3 subscription established for OI caps (main + HIP-3)`,\n );\n })\n .catch((subscribeError) => {\n this.deps.logger.error(\n ensureError(subscribeError),\n this.getErrorContext('createUserDataSubscription (webData3)', {\n dex: dexName,\n }),\n );\n throw subscribeError;\n });\n\n subscriptionPromises.push(webData3Promise);\n\n // Wait for all subscriptions to be established\n Promise.all(subscriptionPromises)\n .then(() => {\n this.deps.debugLogger.log(\n `HIP-3 user data subscriptions established for ${dexsToSubscribe.length} DEXs`,\n );\n resolve();\n })\n .catch((allError) => {\n this.deps.logger.error(\n ensureError(allError),\n this.getErrorContext('createUserDataSubscription (HIP-3)', {\n dexs: dexsToSubscribe,\n }),\n );\n reject(ensureError(allError));\n });\n }\n });\n }\n\n /**\n * Ensure clearinghouseState subscription exists for a DEX\n *\n * @param userAddress - User address\n * @param dexName - DEX name ('' for main)\n */\n private async ensureClearinghouseStateSubscription(\n userAddress: string,\n dexName: string,\n ): Promise<void> {\n if (this.clearinghouseStateSubscriptions.has(dexName)) {\n return; // Already subscribed\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n throw new Error('Subscription client not available');\n }\n\n try {\n const subscription = await subscriptionClient.clearinghouseState(\n {\n user: userAddress,\n dex: dexName || undefined, // Empty string -> undefined for main DEX\n },\n (data: ClearinghouseStateWsEvent) => {\n const cacheKey = data.dex || '';\n\n // Update caches and notify subscribers if we have positions/account subscribers\n if (\n this.positionSubscriberCount > 0 ||\n this.accountSubscriberCount > 0\n ) {\n // Process positions from clearinghouse state\n const positions = data.clearinghouseState.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos));\n\n // Get cached orders to preserve TP/SL data (prevents flickering)\n // Orders are cached by openOrders subscription\n const cachedOrdersForDex = this.dexOrdersCache.get(cacheKey) || [];\n\n // Re-extract TP/SL from cached orders for the new positions\n // This ensures TP/SL data persists across clearinghouseState updates\n let positionsWithTPSL = positions;\n if (cachedOrdersForDex.length > 0) {\n const { tpslMap, tpslCountMap } = this.extractTPSLFromOrders(\n [],\n positions,\n cachedOrdersForDex,\n );\n\n positionsWithTPSL = this.mergeTPSLIntoPositions(\n positions,\n tpslMap,\n tpslCountMap,\n );\n }\n\n // Update account state\n const accountState: AccountState = adaptAccountStateFromSDK(\n data.clearinghouseState,\n undefined,\n );\n\n // Update caches\n this.dexPositionsCache.set(cacheKey, positionsWithTPSL);\n this.dexAccountCache.set(cacheKey, accountState);\n\n // Mark this DEX as initialized (has sent first data)\n this.initializedDexs.add(cacheKey);\n\n // Trigger aggregation and notify subscribers\n this.aggregateAndNotifySubscribers();\n }\n },\n );\n\n this.clearinghouseStateSubscriptions.set(dexName, subscription);\n this.deps.debugLogger.log(\n `clearinghouseState subscription established for DEX: ${dexName || 'main'}`,\n );\n } catch (subscribeError) {\n // Remove this DEX from expected set so it doesn't block notifications for other DEXs\n this.expectedDexs.delete(dexName);\n\n this.deps.logger.error(\n ensureError(subscribeError),\n this.getErrorContext('ensureClearinghouseStateSubscription', {\n dex: dexName,\n }),\n );\n throw subscribeError;\n }\n }\n\n /**\n * Ensure openOrders subscription exists for a DEX\n *\n * @param userAddress - User address\n * @param dexName - DEX name ('' for main)\n */\n private async ensureOpenOrdersSubscription(\n userAddress: string,\n dexName: string,\n ): Promise<void> {\n if (this.openOrdersSubscriptions.has(dexName)) {\n return; // Already subscribed\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n throw new Error('Subscription client not available');\n }\n\n try {\n const subscription = await subscriptionClient.openOrders(\n {\n user: userAddress,\n dex: dexName || undefined, // Empty string -> undefined for main DEX\n },\n (data: OpenOrdersWsEvent) => {\n const cacheKey = data.dex || '';\n\n // Update caches and notify subscribers if we have order subscribers\n if (\n this.orderSubscriberCount > 0 ||\n this.positionSubscriberCount > 0\n ) {\n // Get cached positions for TP/SL processing\n const cachedPositionsForDex =\n this.dexPositionsCache.get(cacheKey) || [];\n\n // Extract TP/SL and process orders\n const {\n tpslMap,\n tpslCountMap,\n processedOrders: ordersProcessed,\n } = this.extractTPSLFromOrders(data.orders, cachedPositionsForDex);\n\n // Update orders cache with processed orders\n this.dexOrdersCache.set(cacheKey, ordersProcessed);\n\n // Update positions with TP/SL if we have positions\n if (cachedPositionsForDex.length > 0) {\n const positionsWithTPSL = this.mergeTPSLIntoPositions(\n cachedPositionsForDex,\n tpslMap,\n tpslCountMap,\n );\n this.dexPositionsCache.set(cacheKey, positionsWithTPSL);\n }\n\n // Mark this DEX as initialized (has sent first data)\n this.initializedDexs.add(cacheKey);\n\n // Trigger aggregation and notify subscribers\n this.aggregateAndNotifySubscribers();\n }\n },\n );\n\n this.openOrdersSubscriptions.set(dexName, subscription);\n this.deps.debugLogger.log(\n `openOrders subscription established for DEX: ${dexName || 'main'}`,\n );\n } catch (subscribeError) {\n // Remove this DEX from expected set so it doesn't block notifications for other DEXs\n this.expectedDexs.delete(dexName);\n\n this.deps.logger.error(\n ensureError(subscribeError),\n this.getErrorContext('ensureOpenOrdersSubscription', {\n dex: dexName,\n }),\n );\n throw subscribeError;\n }\n }\n\n /**\n * Aggregate data from all DEX caches and notify subscribers if data changed\n * Used by both webData3 callback and fallback subscription callbacks\n */\n private aggregateAndNotifySubscribers(): void {\n // Wait for all expected DEXs to send initial data before notifying\n // This ensures positions from all DEXs appear simultaneously\n if (this.expectedDexs.size > 0) {\n const allDexsInitialized = Array.from(this.expectedDexs).every((dex) =>\n this.initializedDexs.has(dex),\n );\n if (!allDexsInitialized) {\n this.deps.debugLogger.log('Waiting for all DEXs to send initial data', {\n expected: Array.from(this.expectedDexs),\n initialized: Array.from(this.initializedDexs),\n });\n return; // Don't notify yet - waiting for more DEXs\n }\n }\n\n // Aggregate data from all DEX caches\n // Order: Main DEX (crypto perps) first, then HIP-3 DEXs\n const mainDexPositions = this.dexPositionsCache.get('') || [];\n const hip3DexPositions = Array.from(this.dexPositionsCache.entries())\n .filter(([key]) => key !== '')\n .flatMap(([, positionsForDex]) => positionsForDex);\n const aggregatedPositions = [...mainDexPositions, ...hip3DexPositions];\n\n const mainDexOrders = this.dexOrdersCache.get('') || [];\n const hip3DexOrders = Array.from(this.dexOrdersCache.entries())\n .filter(([key]) => key !== '')\n .flatMap(([, ordersForDex]) => ordersForDex);\n const aggregatedOrders = [...mainDexOrders, ...hip3DexOrders];\n\n const aggregatedAccount = this.aggregateAccountStates();\n\n // Check if aggregated data changed using fast hash comparison\n const positionsHash = this.hashPositions(aggregatedPositions);\n const ordersHash = this.hashOrders(aggregatedOrders);\n const accountHash = this.hashAccountState(aggregatedAccount);\n\n const positionsChanged = positionsHash !== this.cachedPositionsHash;\n const ordersChanged = ordersHash !== this.cachedOrdersHash;\n const accountChanged = accountHash !== this.cachedAccountHash;\n\n // Only notify subscribers if aggregated data changed\n if (positionsChanged) {\n this.cachedPositions = aggregatedPositions;\n this.cachedPositionsHash = positionsHash;\n this.positionsCacheInitialized = true; // Mark cache as initialized\n this.positionSubscribers.forEach((posCallback) => {\n posCallback(aggregatedPositions);\n });\n }\n\n if (ordersChanged) {\n this.cachedOrders = aggregatedOrders;\n this.cachedOrdersHash = ordersHash;\n this.ordersCacheInitialized = true; // Mark cache as initialized\n this.orderSubscribers.forEach((ordCallback) => {\n ordCallback(aggregatedOrders);\n });\n }\n\n if (accountChanged) {\n this.cachedAccount = aggregatedAccount;\n this.cachedAccountHash = accountHash;\n this.accountSubscribers.forEach((accCallback) => {\n accCallback(aggregatedAccount);\n });\n }\n }\n\n /**\n * Clean up webData3 subscription when no longer needed\n */\n private cleanupSharedWebData3ISubscription(): void {\n const totalSubscribers =\n this.positionSubscriberCount +\n this.orderSubscriberCount +\n this.accountSubscriberCount +\n this.oiCapSubscriberCount;\n\n if (totalSubscribers <= 0) {\n // Cleanup webData3 subscription (covers all DEXs)\n if (this.webData3Subscriptions.size > 0) {\n this.webData3Subscriptions.forEach((subscription, dexNameKey) => {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext(\n 'cleanupSharedWebData3ISubscription.webData3',\n {\n dex: dexNameKey,\n },\n ),\n );\n });\n });\n this.webData3Subscriptions.clear();\n this.webData3SubscriptionPromise = undefined;\n }\n\n // Cleanup individual subscriptions (clearinghouseState + openOrders)\n if (this.clearinghouseStateSubscriptions.size > 0) {\n this.clearinghouseStateSubscriptions.forEach(\n (subscription, dexNameKey) => {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext(\n 'cleanupSharedWebData3ISubscription.clearinghouseState',\n {\n dex: dexNameKey,\n },\n ),\n );\n });\n },\n );\n this.clearinghouseStateSubscriptions.clear();\n }\n\n if (this.openOrdersSubscriptions.size > 0) {\n this.openOrdersSubscriptions.forEach((subscription, dexNameKey) => {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext(\n 'cleanupSharedWebData3ISubscription.openOrders',\n {\n dex: dexNameKey,\n },\n ),\n );\n });\n });\n this.openOrdersSubscriptions.clear();\n }\n\n // Clear subscriber counts\n this.positionSubscriberCount = 0;\n this.orderSubscriberCount = 0;\n this.accountSubscriberCount = 0;\n this.oiCapSubscriberCount = 0;\n\n // Clear per-DEX caches\n this.dexPositionsCache.clear();\n this.dexOrdersCache.clear();\n this.dexAccountCache.clear();\n\n // Clear DEX tracking for synchronized notifications\n this.expectedDexs.clear();\n this.initializedDexs.clear();\n\n // Clear aggregated caches\n this.cachedPositions = null;\n this.cachedOrders = null;\n this.cachedAccount = null;\n this.ordersCacheInitialized = false; // Reset cache initialization flag\n this.positionsCacheInitialized = false; // Reset cache initialization flag\n\n // Clear hash caches\n this.cachedPositionsHash = '';\n this.cachedOrdersHash = '';\n this.cachedAccountHash = '';\n\n this.deps.debugLogger.log(\n 'All multi-DEX subscriptions cleaned up (webData2/3 + individual subscriptions)',\n );\n }\n }\n\n /**\n * Subscribe to live position updates with TP/SL data\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public subscribeToPositions(params: SubscribePositionsParams): () => void {\n const { callback, accountId } = params;\n const unsubscribe = this.createSubscription(\n this.positionSubscribers,\n callback,\n );\n\n // Increment position subscriber count\n this.positionSubscriberCount++;\n\n // Immediately provide cached data if available\n if (this.cachedPositions) {\n callback(this.cachedPositions);\n }\n\n // Ensure shared subscription is active\n this.ensureSharedWebData3Subscription(accountId).catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToPositions'),\n );\n });\n\n return () => {\n unsubscribe();\n this.positionSubscriberCount--;\n this.cleanupSharedWebData3ISubscription();\n };\n }\n\n /**\n * Subscribe to open interest cap updates\n * OI caps are extracted from webData2 subscription (zero additional overhead)\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public subscribeToOICaps(params: SubscribeOICapsParams): () => void {\n const { callback, accountId } = params;\n\n // Create subscription\n const unsubscribe = this.createSubscription(\n this.oiCapSubscribers,\n callback,\n );\n\n // Increment OI cap subscriber count\n this.oiCapSubscriberCount++;\n\n // Immediately provide cached data if available\n if (this.cachedOICaps) {\n callback(this.cachedOICaps);\n }\n\n // Ensure webData3 subscription is active (OI caps come from webData3)\n this.ensureSharedWebData3Subscription(accountId).catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToOICaps'),\n );\n });\n\n return () => {\n unsubscribe();\n this.oiCapSubscriberCount--;\n this.cleanupSharedWebData3ISubscription();\n };\n }\n\n /**\n * Check if OI caps cache has been initialized\n * Useful for preventing UI flashing before first data arrives\n *\n * @returns True if cache is initialized\n */\n public isOICapsCacheInitialized(): boolean {\n return this.oiCapsCacheInitialized;\n }\n\n /**\n * Subscribe to live order fill updates\n * Shares subscriptions per accountId to avoid duplicate WebSocket connections\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void {\n const { callback, accountId } = params;\n // Normalize accountId: undefined -> 'default' for Map key\n const normalizedAccountId = accountId ?? 'default';\n const unsubscribe = this.createSubscription(\n this.orderFillSubscribers,\n callback,\n normalizedAccountId,\n );\n\n // Ensure subscription is established for this accountId\n this.ensureOrderFillISubscription(accountId).catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToOrderFills'),\n );\n });\n\n return () => {\n unsubscribe();\n\n // If no more subscribers for this accountId, clean up subscription\n const subscribers = this.orderFillSubscribers.get(normalizedAccountId);\n if (!subscribers || subscribers.size === 0) {\n const subscription =\n this.orderFillSubscriptions.get(normalizedAccountId);\n if (subscription) {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('subscribeToOrderFills.unsubscribe'),\n );\n });\n this.orderFillSubscriptions.delete(normalizedAccountId);\n }\n }\n };\n }\n\n /**\n * Ensure order fill subscription is active for the given accountId\n * Shares subscription across all callbacks for the same accountId\n *\n * @param accountId - Optional account ID\n */\n private async ensureOrderFillISubscription(\n accountId?: CaipAccountId,\n ): Promise<void> {\n // Normalize accountId: undefined -> 'default' for Map key\n const normalizedAccountId = accountId ?? 'default';\n\n // If subscription already exists, no need to create another\n if (this.orderFillSubscriptions.has(normalizedAccountId)) {\n return;\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n await this.clientService.ensureSubscriptionClient(\n this.walletService.createWalletAdapter(),\n );\n const client = this.clientService.getSubscriptionClient();\n if (!client) {\n throw new Error('SubscriptionClient not available');\n }\n return this.ensureOrderFillISubscription(accountId);\n }\n\n const userAddress =\n await this.walletService.getUserAddressWithDefault(accountId);\n\n // userFills returns a Promise<ISubscription>, need to await it\n const subscription = await subscriptionClient.userFills(\n { user: userAddress },\n (data: UserFillsWsEvent) => {\n const orderFills: OrderFill[] = data.fills.map((fill) => ({\n orderId: fill.oid.toString(),\n symbol: fill.coin,\n side: fill.side,\n size: fill.sz,\n price: fill.px,\n fee: fill.fee,\n timestamp: fill.time,\n pnl: fill.closedPnl,\n direction: fill.dir,\n feeToken: fill.feeToken,\n startPosition: fill.startPosition,\n liquidation: fill.liquidation\n ? {\n liquidatedUser: fill.liquidation.liquidatedUser,\n markPx: fill.liquidation.markPx,\n method: fill.liquidation.method,\n }\n : undefined,\n }));\n\n // Distribute to all callbacks for this accountId\n const subscribers = this.orderFillSubscribers.get(normalizedAccountId);\n if (subscribers) {\n subscribers.forEach((fillCallback) => {\n fillCallback(orderFills, data.isSnapshot);\n });\n }\n },\n );\n\n this.orderFillSubscriptions.set(normalizedAccountId, subscription);\n }\n\n /**\n * Subscribe to live order updates\n * Uses the shared webData2 subscription to avoid duplicate connections\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public subscribeToOrders(params: SubscribeOrdersParams): () => void {\n const { callback, accountId } = params;\n const unsubscribe = this.createSubscription(\n this.orderSubscribers,\n callback,\n );\n\n // Increment order subscriber count\n this.orderSubscriberCount++;\n\n // Immediately provide cached data if available\n if (this.cachedOrders) {\n callback(this.cachedOrders);\n }\n\n // Ensure shared subscription is active\n this.ensureSharedWebData3Subscription(accountId).catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToOrders'),\n );\n });\n\n return () => {\n unsubscribe();\n this.orderSubscriberCount--;\n this.cleanupSharedWebData3ISubscription();\n };\n }\n\n /**\n * Subscribe to live account updates\n * Uses the shared webData2 subscription to avoid duplicate connections\n *\n * @param params - Subscription parameters\n * @returns Cleanup function\n */\n public subscribeToAccount(params: SubscribeAccountParams): () => void {\n const { callback, accountId } = params;\n const unsubscribe = this.createSubscription(\n this.accountSubscribers,\n callback,\n );\n\n // Increment account subscriber count\n this.accountSubscriberCount++;\n\n // Immediately provide cached data if available\n if (this.cachedAccount) {\n callback(this.cachedAccount);\n }\n\n // Ensure shared subscription is active (reuses existing connection)\n this.ensureSharedWebData3Subscription(accountId).catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToAccount'),\n );\n });\n\n return () => {\n unsubscribe();\n this.accountSubscriberCount--;\n this.cleanupSharedWebData3ISubscription();\n };\n }\n\n /**\n * Check if orders cache has been initialized from WebSocket\n *\n * @returns true if WebSocket has sent at least one update, false otherwise\n */\n public isOrdersCacheInitialized(): boolean {\n return this.ordersCacheInitialized;\n }\n\n /**\n * Check if positions cache has been initialized from WebSocket\n *\n * @returns true if WebSocket has sent at least one update, false otherwise\n */\n public isPositionsCacheInitialized(): boolean {\n return this.positionsCacheInitialized;\n }\n\n /**\n * Get cached positions from WebSocket subscription\n *\n * @returns Cached positions array, or null if not initialized\n */\n public getCachedPositions(): Position[] | null {\n return this.cachedPositions;\n }\n\n /**\n * Get cached orders from WebSocket subscription\n *\n * @returns Cached orders array, or null if not initialized\n */\n public getCachedOrders(): Order[] | null {\n return this.cachedOrders;\n }\n\n /**\n * Create subscription with common error handling\n *\n * @param subscribers - Subscriber collection\n * @param callback - Callback to add\n * @param key - Optional key for Map-based collections\n * @returns Unsubscribe function\n */\n private createSubscription<TCallback>(\n subscribers: Set<TCallback> | Map<string, Set<TCallback>>,\n callback: TCallback,\n key?: string,\n ): () => void {\n if (subscribers instanceof Map && key) {\n if (!subscribers.has(key)) {\n subscribers.set(key, new Set());\n }\n subscribers.get(key)?.add(callback);\n } else if (subscribers instanceof Set) {\n subscribers.add(callback);\n }\n\n return () => {\n if (subscribers instanceof Map && key) {\n const set = subscribers.get(key);\n set?.delete(callback);\n if (set?.size === 0) {\n subscribers.delete(key);\n }\n } else if (subscribers instanceof Set) {\n subscribers.delete(callback);\n }\n };\n }\n\n /**\n * Helper function to create consolidated price updates with 24h change calculation\n *\n * @param symbol - Asset symbol\n * @param price - Current price\n * @returns Price update object\n */\n private createPriceUpdate(symbol: string, price: string): PriceUpdate {\n const marketData = this.marketDataCache.get(symbol);\n const orderBookData = this.orderBookCache.get(symbol);\n const currentPrice = parseFloat(price);\n\n let percentChange24h: string | undefined;\n if (marketData?.prevDayPx !== undefined) {\n const change =\n ((currentPrice - marketData.prevDayPx) / marketData.prevDayPx) * 100;\n percentChange24h = change.toFixed(2);\n }\n\n // Check if any subscriber for this symbol wants market data\n const hasMarketDataSubscribers =\n this.marketDataSubscribers.has(symbol) &&\n (this.marketDataSubscribers.get(symbol)?.size ?? 0) > 0;\n\n const priceUpdate = {\n symbol,\n price, // This is the mid price from allMids\n timestamp: Date.now(),\n percentChange24h,\n // Add mark price from activeAssetCtx\n markPrice: marketData?.oraclePrice\n ? marketData.oraclePrice.toString()\n : undefined,\n // Add order book data if available\n bestBid: orderBookData?.bestBid,\n bestAsk: orderBookData?.bestAsk,\n spread: orderBookData?.spread,\n // Always include funding when available (don't default to 0, preserve undefined)\n funding: marketData?.funding,\n // Add market data only if requested by at least one subscriber\n openInterest: hasMarketDataSubscribers\n ? marketData?.openInterest\n : undefined,\n volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,\n };\n\n return priceUpdate;\n }\n\n /**\n * Ensure global allMids subscription is active (singleton pattern)\n */\n private ensureGlobalAllMidsSubscription(): void {\n // Check both the subscription AND the promise to prevent race conditions\n if (this.globalAllMidsSubscription || this.globalAllMidsPromise) {\n return;\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n return;\n }\n\n // Track WebSocket metrics\n const wsMetrics = {\n messagesReceived: 0,\n lastMessageTime: Date.now(),\n reconnectCount: 0,\n startTime: Date.now(),\n };\n\n // Store the promise immediately to prevent duplicate calls\n this.globalAllMidsPromise = subscriptionClient\n .allMids((data: AllMidsWsEvent) => {\n wsMetrics.messagesReceived++;\n wsMetrics.lastMessageTime = Date.now();\n\n // Initialize cache if needed\n this.cachedPriceData ??= new Map<string, PriceUpdate>();\n\n const subscribedSymbols = new Set<string>();\n\n // Collect all symbols that have subscribers\n for (const [symbol, subscriberSet] of this.priceSubscribers.entries()) {\n if (subscriberSet.size > 0) {\n subscribedSymbols.add(symbol);\n }\n }\n\n // Track if any subscribed symbol was updated\n let hasUpdates = false;\n\n // Only process symbols that are actually subscribed to\n for (const symbol in data.mids) {\n // Skip if nobody is subscribed to this symbol\n if (!subscribedSymbols.has(symbol)) {\n continue;\n }\n\n const priceValue = data.mids[symbol].toString();\n const cachedPrice = this.cachedPriceData.get(symbol);\n\n // Skip if price hasn't changed\n if (cachedPrice?.price === priceValue) {\n continue;\n }\n\n // Price changed or new symbol - update cache\n const priceUpdate = this.createPriceUpdate(symbol, priceValue);\n this.cachedPriceData.set(symbol, priceUpdate);\n hasUpdates = true;\n }\n\n // Only notify subscribers if we actually have updates\n // This prevents unnecessary React re-renders when prices haven't changed\n if (hasUpdates) {\n this.notifyAllPriceSubscribers();\n }\n })\n .then((sub) => {\n this.globalAllMidsSubscription = sub;\n this.deps.debugLogger.log(\n 'HyperLiquid: Global allMids subscription established',\n );\n\n // Notify existing subscribers with any cached data now that subscription is established\n if (this.cachedPriceData && this.cachedPriceData.size > 0) {\n this.notifyAllPriceSubscribers();\n }\n })\n .catch((subError) => {\n // Clear the promise on error so it can be retried\n this.globalAllMidsPromise = undefined;\n\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('ensureGlobalAllMidsSubscription'),\n );\n });\n }\n\n /**\n * Ensure activeAssetCtx subscription for specific symbol (with reference counting)\n *\n * @param symbol - Asset symbol\n */\n private ensureActiveAssetSubscription(symbol: string): void {\n // Increment subscriber count\n const currentCount = this.symbolSubscriberCounts.get(symbol) || 0;\n this.symbolSubscriberCounts.set(symbol, currentCount + 1);\n\n // If subscription already exists, just return\n if (this.globalActiveAssetSubscriptions.has(symbol)) {\n return;\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n return;\n }\n\n // Track metrics for this subscription\n const subscriptionMetrics = {\n messagesReceived: 0,\n startTime: Date.now(),\n };\n\n subscriptionClient\n .activeAssetCtx(\n { coin: symbol },\n (data: ActiveAssetCtxWsEvent | ActiveSpotAssetCtxWsEvent) => {\n subscriptionMetrics.messagesReceived++;\n\n if (data.coin === symbol && data.ctx) {\n // Type guard using SDK types: check if this is perps (has funding) or spot (no funding)\n const isPerpsContext = (\n event: ActiveAssetCtxWsEvent | ActiveSpotAssetCtxWsEvent,\n ): event is ActiveAssetCtxWsEvent =>\n 'funding' in event.ctx &&\n 'openInterest' in event.ctx &&\n 'oraclePx' in event.ctx;\n\n const { ctx } = data;\n\n // Cache market data for consolidation with price updates\n const ctxPrice = ctx.midPx || ctx.markPx;\n const openInterestUSD =\n isPerpsContext(data) && ctxPrice\n ? calculateOpenInterestUSD(data.ctx.openInterest, ctxPrice)\n : NaN;\n const marketDataEntry = {\n prevDayPx: ctx.prevDayPx\n ? parseFloat(ctx.prevDayPx.toString())\n : undefined,\n // Cache funding rate from activeAssetCtx for real-time updates\n // SDK defines funding as string (not nullable) in ActiveAssetCtxEvent\n funding: isPerpsContext(data)\n ? parseFloat(data.ctx.funding.toString())\n : undefined,\n openInterest: !isNaN(openInterestUSD)\n ? openInterestUSD\n : undefined,\n volume24h: ctx.dayNtlVlm\n ? parseFloat(ctx.dayNtlVlm.toString())\n : undefined,\n oraclePrice: isPerpsContext(data)\n ? parseFloat(data.ctx.oraclePx.toString())\n : undefined,\n lastUpdated: Date.now(),\n };\n\n this.marketDataCache.set(symbol, marketDataEntry);\n\n // Update cached price data with new 24h change if we have current price\n const currentCachedPrice = this.cachedPriceData?.get(symbol);\n if (currentCachedPrice) {\n const updatedPrice = this.createPriceUpdate(\n symbol,\n currentCachedPrice.price,\n );\n\n this.cachedPriceData ??= new Map<string, PriceUpdate>();\n this.cachedPriceData.set(symbol, updatedPrice);\n this.notifyAllPriceSubscribers();\n }\n }\n },\n )\n .then((sub) => {\n this.globalActiveAssetSubscriptions.set(symbol, sub);\n this.deps.debugLogger.log(\n `HyperLiquid: Market data subscription established for ${symbol}`,\n );\n })\n .catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('ensureActiveAssetSubscription', { symbol }),\n );\n });\n }\n\n /**\n * Cleanup activeAssetCtx subscription when no longer needed\n *\n * @param symbol - Asset symbol\n */\n private cleanupActiveAssetSubscription(symbol: string): void {\n const currentCount = this.symbolSubscriberCounts.get(symbol) || 0;\n if (currentCount <= 1) {\n // Last subscriber, cleanup subscription\n const subscription = this.globalActiveAssetSubscriptions.get(symbol);\n if (subscription && typeof subscription.unsubscribe === 'function') {\n const unsubscribeResult = Promise.resolve(subscription.unsubscribe());\n\n unsubscribeResult.catch(() => {\n // Ignore errors during cleanup\n });\n this.globalActiveAssetSubscriptions.delete(symbol);\n this.symbolSubscriberCounts.delete(symbol);\n } else if (subscription) {\n // Subscription exists but unsubscribe is not a function or doesn't return a Promise\n // Just clean up the reference\n this.globalActiveAssetSubscriptions.delete(symbol);\n this.symbolSubscriberCounts.delete(symbol);\n }\n } else {\n // Still has subscribers, just decrement count\n this.symbolSubscriberCounts.set(symbol, currentCount - 1);\n }\n }\n\n /**\n * Ensure assetCtxs subscription for specific DEX (HIP-3 support)\n * Uses WebSocket instead of REST polling for market data\n * Implements reference counting to track active subscribers per DEX\n *\n * @param dex - DEX identifier ('' for main)\n */\n private async ensureAssetCtxsSubscription(dex: string): Promise<void> {\n const dexKey = dex || '';\n\n // Increment subscriber count for this DEX\n const currentCount = this.dexSubscriberCounts.get(dexKey) || 0;\n this.dexSubscriberCounts.set(dexKey, currentCount + 1);\n\n // Return if subscription already exists\n if (this.assetCtxsSubscriptions.has(dexKey)) {\n return;\n }\n\n // Return existing promise if subscription is being established\n if (this.assetCtxsSubscriptionPromises.has(dexKey)) {\n return this.assetCtxsSubscriptionPromises.get(dexKey);\n }\n\n // Create new subscription promise\n const promise = this.createAssetCtxsSubscription(dex);\n this.assetCtxsSubscriptionPromises.set(dexKey, promise);\n\n try {\n await promise;\n } catch {\n // Clear promise on error so it can be retried\n this.assetCtxsSubscriptionPromises.delete(dexKey);\n throw new Error(\n `Failed to create assetCtxs subscription for DEX: ${dex}`,\n );\n }\n }\n\n /**\n * Create assetCtxs subscription for specific DEX\n * Provides real-time market data for all assets on the DEX\n *\n * Performance: Uses cached meta from dexMetaCache (populated by metaAndAssetCtxs)\n * to avoid redundant meta() API calls during subscription setup\n *\n * @param dex - DEX identifier ('' for main)\n */\n private async createAssetCtxsSubscription(dex: string): Promise<void> {\n await this.clientService.ensureSubscriptionClient(\n this.walletService.createWalletAdapter(),\n );\n const subscriptionClient = this.clientService.getSubscriptionClient();\n\n if (!subscriptionClient) {\n throw new Error('Subscription client not initialized');\n }\n\n const dexKey = dex || '';\n const dexIdentifier = dex ?? 'main DEX';\n\n // Check cache first - populated by metaAndAssetCtxs in ensureAssetCtxsSubscription\n let perpsMeta = this.dexMetaCache.get(dexKey);\n\n if (!perpsMeta) {\n // Fallback: fetch meta if not in cache (shouldn't happen in normal flow)\n this.deps.debugLogger.log(\n `Meta cache miss for ${dexIdentifier}, fetching from API`,\n );\n const infoClient = this.clientService.getInfoClient();\n const fetchedMeta = await infoClient.meta({ dex: dex || undefined });\n if (fetchedMeta?.universe) {\n perpsMeta = fetchedMeta;\n this.dexMetaCache.set(dexKey, fetchedMeta);\n }\n }\n\n if (!perpsMeta?.universe) {\n const errorMessage = `No universe data available for ${dexIdentifier}`;\n throw new Error(errorMessage);\n }\n\n this.deps.debugLogger.log(\n `Using ${this.dexMetaCache.has(dexKey) ? 'cached' : 'fetched'} meta for ${dexIdentifier}`,\n {\n dex,\n universeCount: perpsMeta.universe.length,\n firstAssetSample: perpsMeta.universe[0]?.name,\n },\n );\n\n // Capture perpsMeta in closure for callback\n const metaForCallback = perpsMeta;\n\n return new Promise<void>((resolve, reject) => {\n const subscriptionParams = dex ? { dex } : {};\n\n subscriptionClient\n .assetCtxs(subscriptionParams, (data: AssetCtxsWsEvent) => {\n // Cache asset contexts for this DEX\n this.dexAssetCtxsCache.set(dexKey, data.ctxs);\n\n // Use cached meta to map ctxs array indices to symbols (no REST API call!)\n metaForCallback.universe.forEach((asset, index) => {\n const ctx = data.ctxs[index];\n if (ctx && 'funding' in ctx) {\n // This is a perps context\n const ctxPrice = ctx.midPx || ctx.markPx;\n const openInterestUSD = calculateOpenInterestUSD(\n ctx.openInterest,\n ctxPrice,\n );\n const marketDataEntry = {\n prevDayPx: ctx.prevDayPx\n ? parseFloat(ctx.prevDayPx.toString())\n : undefined,\n funding: parseFloat(ctx.funding.toString()),\n openInterest: !isNaN(openInterestUSD)\n ? openInterestUSD\n : undefined,\n volume24h: ctx.dayNtlVlm\n ? parseFloat(ctx.dayNtlVlm.toString())\n : undefined,\n oraclePrice: parseFloat(ctx.oraclePx.toString()),\n lastUpdated: Date.now(),\n };\n\n this.marketDataCache.set(asset.name, marketDataEntry);\n\n // HIP-3: Extract price from assetCtx and update cached prices\n const priceValue =\n ctx.midPx?.toString() || ctx.markPx?.toString();\n if (priceValue) {\n // For HIP-3 DEXs, meta() returns asset.name already containing the DEX prefix\n // (e.g., \"xyz:XYZ100\"), so use it directly\n const assetSymbol = asset.name;\n const priceUpdate = this.createPriceUpdate(\n assetSymbol,\n priceValue,\n );\n this.cachedPriceData ??= new Map<string, PriceUpdate>();\n this.cachedPriceData.set(assetSymbol, priceUpdate);\n }\n }\n });\n\n // Notify price subscribers with updated market data\n this.notifyAllPriceSubscribers();\n })\n .then((sub) => {\n this.assetCtxsSubscriptions.set(dexKey, sub);\n this.deps.debugLogger.log(\n `assetCtxs subscription established for ${\n dex ? `DEX: ${dex}` : 'main DEX'\n }`,\n );\n resolve();\n })\n .catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('createAssetCtxsSubscription', { dex }),\n );\n reject(ensureError(subError));\n });\n });\n }\n\n /**\n * Cleanup assetCtxs subscription for specific DEX with reference counting\n * Only unsubscribes when the last subscriber for this DEX is removed\n *\n * @param dex - DEX identifier ('' for main)\n */\n private cleanupAssetCtxsSubscription(dex: string): void {\n const dexKey = dex || '';\n\n // Decrement subscriber count for this DEX\n const currentCount = this.dexSubscriberCounts.get(dexKey) || 0;\n\n if (currentCount <= 1) {\n // Last subscriber - cleanup the subscription\n const subscription = this.assetCtxsSubscriptions.get(dexKey);\n\n if (subscription) {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('cleanupAssetCtxsSubscription', { dex }),\n );\n });\n\n this.assetCtxsSubscriptions.delete(dexKey);\n this.dexAssetCtxsCache.delete(dexKey);\n this.assetCtxsSubscriptionPromises.delete(dexKey);\n this.dexSubscriberCounts.delete(dexKey);\n\n this.deps.debugLogger.log(\n `Cleaned up assetCtxs subscription for ${\n dex ? `DEX: ${dex}` : 'main DEX'\n }`,\n );\n }\n } else {\n // Still has subscribers - just decrement count\n this.dexSubscriberCounts.set(dexKey, currentCount - 1);\n }\n }\n\n /**\n * Ensure BBO subscription for specific symbol (singleton)\n *\n * BBO provides best bid/ask without being affected by L2Book aggregation parameters,\n * keeping spread consistent across order book grouping selections (matches Hyperliquid UI).\n *\n * @param symbol - Asset symbol\n */\n private ensureBboSubscription(symbol: string): void {\n if (this.globalBboSubscriptions.has(symbol)) {\n return;\n }\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n return;\n }\n\n subscriptionClient\n .bbo({ coin: symbol }, (data: BboWsEvent) => {\n processBboData({\n symbol,\n data,\n orderBookCache: this.orderBookCache,\n cachedPriceData: this.cachedPriceData,\n createPriceUpdate: this.createPriceUpdate.bind(this),\n notifySubscribers: this.notifyAllPriceSubscribers.bind(this),\n });\n })\n .then((sub) => {\n this.globalBboSubscriptions.set(symbol, sub);\n this.deps.debugLogger.log(\n `HyperLiquid: BBO subscription established for ${symbol}`,\n );\n })\n .catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('ensureBboSubscription', { symbol }),\n );\n });\n }\n\n /**\n * Cleanup BBO subscription when no longer needed\n *\n * @param symbol - Asset symbol\n */\n private cleanupBboSubscription(symbol: string): void {\n // If anyone still wants order book (top-of-book) data for this symbol, keep the subscription alive.\n if ((this.orderBookSubscribers.get(symbol)?.size ?? 0) > 0) {\n return;\n }\n\n const subscription = this.globalBboSubscriptions.get(symbol);\n if (subscription && typeof subscription.unsubscribe === 'function') {\n const unsubscribeResult = Promise.resolve(subscription.unsubscribe());\n unsubscribeResult.catch(() => {\n // Ignore errors during cleanup\n });\n\n this.globalBboSubscriptions.delete(symbol);\n this.orderBookCache.delete(symbol);\n } else if (subscription) {\n // Subscription exists but unsubscribe is not a function or doesn't return a Promise\n // Just clean up the reference\n this.globalBboSubscriptions.delete(symbol);\n this.orderBookCache.delete(symbol);\n }\n }\n\n /**\n * Subscribe to full order book updates with multiple depth levels\n * Creates a dedicated L2Book subscription for the requested symbol\n * and processes data into OrderBookData format for UI consumption\n *\n * @param params - Subscription parameters\n * @returns Cleanup function to unsubscribe\n */\n public subscribeToOrderBook(params: SubscribeOrderBookParams): () => void {\n const {\n symbol,\n levels = 10,\n nSigFigs = 5,\n mantissa,\n callback,\n onError,\n } = params;\n\n this.clientService.ensureSubscriptionClient(\n this.walletService.createWalletAdapter(),\n );\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n const subError = new Error('Subscription client not available');\n onError?.(subError);\n this.deps.debugLogger.log(\n 'subscribeToOrderBook: Subscription client not available',\n );\n return () => {\n // No-op cleanup\n };\n }\n\n let subscription: ISubscription | undefined;\n let cancelled = false;\n\n subscriptionClient\n .l2Book({ coin: symbol, nSigFigs, mantissa }, (data: L2BookResponse) => {\n if (cancelled || data?.coin !== symbol || !data?.levels) {\n return;\n }\n\n const orderBookData = this.processOrderBookData(data, levels);\n callback(orderBookData);\n })\n .then((sub) => {\n if (cancelled) {\n sub.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('subscribeToOrderBook.cleanup', { symbol }),\n );\n });\n } else {\n subscription = sub;\n this.deps.debugLogger.log(\n `HyperLiquid: Order book subscription established for ${symbol}`,\n );\n }\n })\n .catch((subError) => {\n this.deps.logger.error(\n ensureError(subError),\n this.getErrorContext('subscribeToOrderBook', { symbol }),\n );\n onError?.(ensureError(subError));\n });\n\n return () => {\n cancelled = true;\n if (subscription) {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('subscribeToOrderBook.unsubscribe', {\n symbol,\n }),\n );\n });\n }\n };\n }\n\n /**\n * Process raw L2Book data into OrderBookData format\n * Calculates cumulative totals, notional values, and spread metrics\n *\n * @param data - Raw L2Book response from WebSocket\n * @param levels - Number of levels to return per side\n * @returns Processed OrderBookData\n */\n private processOrderBookData(\n data: L2BookResponse,\n levels: number,\n ): OrderBookData {\n const bidsRaw = data?.levels?.[0] || [];\n const asksRaw = data?.levels?.[1] || [];\n\n // Process bids (buy orders) - highest price first\n let bidCumulativeSize = 0;\n let bidCumulativeNotional = 0;\n const bids: OrderBookLevel[] = bidsRaw.slice(0, levels).map((level) => {\n const price = parseFloat(level.px);\n const size = parseFloat(level.sz);\n const notional = price * size;\n bidCumulativeSize += size;\n bidCumulativeNotional += notional;\n\n return {\n price: level.px,\n size: level.sz,\n total: bidCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: bidCumulativeNotional.toFixed(2),\n };\n });\n\n // Process asks (sell orders) - lowest price first\n let askCumulativeSize = 0;\n let askCumulativeNotional = 0;\n const asks: OrderBookLevel[] = asksRaw.slice(0, levels).map((level) => {\n const price = parseFloat(level.px);\n const size = parseFloat(level.sz);\n const notional = price * size;\n askCumulativeSize += size;\n askCumulativeNotional += notional;\n\n return {\n price: level.px,\n size: level.sz,\n total: askCumulativeSize.toString(),\n notional: notional.toFixed(2),\n totalNotional: askCumulativeNotional.toFixed(2),\n };\n });\n\n // Calculate spread and mid price\n const bestBid = bids[0];\n const bestAsk = asks[0];\n const bidPrice = bestBid ? parseFloat(bestBid.price) : 0;\n const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;\n const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;\n const midPrice =\n askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;\n const spreadPercentage =\n midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';\n\n // Calculate max total for depth chart scaling\n const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();\n\n return {\n bids,\n asks,\n spread: spread.toFixed(5),\n spreadPercentage,\n midPrice: midPrice.toFixed(5),\n lastUpdated: Date.now(),\n maxTotal,\n };\n }\n\n /**\n * Notify all price subscribers with their requested symbols from cache\n * Optimized to batch updates per subscriber\n */\n private notifyAllPriceSubscribers(): void {\n // If no price data exists yet, don't notify\n if (!this.cachedPriceData) {\n return;\n }\n\n const priceData = this.cachedPriceData;\n\n // Group updates by subscriber to batch notifications\n const subscriberUpdates = new Map<\n (prices: PriceUpdate[]) => void,\n PriceUpdate[]\n >();\n\n this.priceSubscribers.forEach((subscriberSet, symbol) => {\n const priceUpdate = priceData.get(symbol);\n if (priceUpdate) {\n subscriberSet.forEach((priceCallback) => {\n if (!subscriberUpdates.has(priceCallback)) {\n subscriberUpdates.set(priceCallback, []);\n }\n const updates = subscriberUpdates.get(priceCallback);\n if (updates) {\n updates.push(priceUpdate);\n }\n });\n }\n });\n\n // Send batched updates to each subscriber\n subscriberUpdates.forEach((updates, priceCallback) => {\n if (updates.length > 0) {\n priceCallback(updates);\n }\n });\n }\n\n /**\n * Restore all active subscriptions after WebSocket reconnection\n * Re-establishes WebSocket subscriptions for all active subscribers\n *\n * IMPORTANT: This method verifies transport readiness before attempting\n * any subscriptions to prevent \"subscribe error: undefined\" errors.\n */\n public async restoreSubscriptions(): Promise<void> {\n // CRITICAL: Verify transport is ready before attempting any subscriptions\n // This prevents race conditions where subscriptions are attempted while\n // the WebSocket is still in CONNECTING state\n try {\n await this.clientService.ensureTransportReady(5000);\n } catch (transportError) {\n this.deps.debugLogger.log(\n 'Transport not ready during subscription restore, will retry on next reconnect',\n {\n error:\n transportError instanceof Error\n ? transportError.message\n : String(transportError),\n },\n );\n return;\n }\n\n // Re-establish global allMids subscription if there are price subscribers\n if (this.priceSubscribers.size > 0) {\n // Clear existing subscription reference (it's dead after reconnection)\n this.globalAllMidsSubscription = undefined;\n this.globalAllMidsPromise = undefined;\n\n // Re-establish the subscription\n this.ensureGlobalAllMidsSubscription();\n }\n\n // Re-establish order fill subscriptions if there are fill subscribers\n if (this.orderFillSubscribers.size > 0) {\n // Clear existing subscription references (they're dead after reconnection)\n this.orderFillSubscriptions.clear();\n\n // Re-establish subscriptions for all accountIds with subscribers\n // Note: normalizedAccountId is 'default' for undefined, need to convert back\n const normalizedAccountIds = Array.from(this.orderFillSubscribers.keys());\n await Promise.all(\n normalizedAccountIds.map((normalizedAccountId) => {\n // Convert normalized key back to original accountId (undefined if 'default')\n const originalAccountId =\n normalizedAccountId === 'default'\n ? undefined\n : (normalizedAccountId as CaipAccountId);\n return this.ensureOrderFillISubscription(originalAccountId).catch(\n () => {\n // Ignore errors during order fill subscription restoration\n },\n );\n }),\n );\n }\n\n // Re-establish user data subscriptions if there are user data subscribers\n if (\n this.positionSubscribers.size > 0 ||\n this.orderSubscribers.size > 0 ||\n this.accountSubscribers.size > 0 ||\n this.oiCapSubscribers.size > 0\n ) {\n // Clear existing subscription references (they're dead after reconnection)\n this.webData3Subscriptions.clear();\n this.webData3SubscriptionPromise = undefined;\n\n // Clear individual subscriptions (clearinghouseState + openOrders) for HIP-3 mode\n this.clearinghouseStateSubscriptions.clear();\n this.openOrdersSubscriptions.clear();\n\n // Re-establish the subscription (will use current account)\n // This will set up webData2 for non-HIP-3, or individual subscriptions + webData3 (OI caps only) for HIP-3\n await this.ensureSharedWebData3Subscription();\n }\n\n // Re-establish activeAsset subscriptions if there are market data subscribers\n if (this.marketDataSubscribers.size > 0) {\n // Clear existing subscriptions (they're dead after reconnection)\n this.globalActiveAssetSubscriptions.clear();\n // Clear reference counts to prevent double-counting after reconnection\n this.symbolSubscriberCounts.clear();\n\n // Re-establish subscriptions for all symbols with market data subscribers\n const symbolsNeedingMarketData = Array.from(\n this.marketDataSubscribers.keys(),\n );\n symbolsNeedingMarketData.forEach((symbol) => {\n this.ensureActiveAssetSubscription(symbol);\n });\n }\n\n // Re-establish BBO subscriptions if there are order book subscribers\n if (this.orderBookSubscribers.size > 0) {\n // Clear existing subscriptions (they're dead after reconnection)\n this.globalBboSubscriptions.clear();\n\n // Re-establish subscriptions for all symbols with order book subscribers\n const symbolsNeedingOrderBook = Array.from(\n this.orderBookSubscribers.keys(),\n );\n symbolsNeedingOrderBook.forEach((symbol) => {\n this.ensureBboSubscription(symbol);\n });\n }\n\n // Re-establish assetCtxs subscriptions if there are market data subscribers\n if (this.marketDataSubscribers.size > 0) {\n // Clear existing subscriptions (they're dead after reconnection)\n this.assetCtxsSubscriptions.clear();\n this.assetCtxsSubscriptionPromises.clear();\n // Clear reference counts to prevent double-counting after reconnection\n this.dexSubscriberCounts.clear();\n\n // Re-establish subscriptions for all DEXs with market data subscribers\n const dexsNeeded = new Set<string>();\n this.marketDataSubscribers.forEach((_subscribers, symbol) => {\n const { dex } = parseAssetName(symbol);\n if (dex) {\n dexsNeeded.add(dex);\n }\n });\n\n // Add main DEX if any main DEX symbols have subscribers\n const hasMainDexSubscribers = Array.from(\n this.marketDataSubscribers.keys(),\n ).some((symbol) => {\n const { dex } = parseAssetName(symbol);\n return !dex;\n });\n if (hasMainDexSubscribers) {\n dexsNeeded.add('');\n }\n\n // Re-establish subscriptions\n await Promise.all(\n Array.from(dexsNeeded).map((dex) =>\n this.ensureAssetCtxsSubscription(dex).catch(() => {\n // Ignore errors during assetCtxs subscription restoration\n }),\n ),\n );\n }\n }\n\n /**\n * Clear all subscriptions and cached data (multi-DEX support)\n */\n public clearAll(): void {\n // Clear all local subscriber collections\n this.priceSubscribers.clear();\n this.positionSubscribers.clear();\n this.orderFillSubscribers.clear();\n this.orderSubscribers.clear();\n this.accountSubscribers.clear();\n this.marketDataSubscribers.clear();\n this.orderBookSubscribers.clear();\n\n // Clear order fill subscriptions\n this.orderFillSubscriptions.forEach((subscription) => {\n subscription.unsubscribe().catch(() => {\n // Ignore errors during cleanup\n });\n });\n this.orderFillSubscriptions.clear();\n\n // Clear cached data\n this.cachedPriceData = null;\n this.cachedPositions = null;\n this.cachedOrders = null;\n this.cachedAccount = null;\n this.ordersCacheInitialized = false; // Reset cache initialization flag\n this.positionsCacheInitialized = false; // Reset cache initialization flag\n this.marketDataCache.clear();\n this.orderBookCache.clear();\n this.symbolSubscriberCounts.clear();\n this.dexSubscriberCounts.clear();\n\n // Clear hash caches\n this.cachedPositionsHash = '';\n this.cachedOrdersHash = '';\n this.cachedAccountHash = '';\n\n // Clear multi-DEX caches\n this.deps.debugLogger.log(\n 'HyperLiquidSubscriptionService: Clearing per-DEX caches',\n {\n dexPositionsCacheSize: this.dexPositionsCache.size,\n dexOrdersCacheSize: this.dexOrdersCache.size,\n dexAccountCacheSize: this.dexAccountCache.size,\n dexAssetCtxsCacheSize: this.dexAssetCtxsCache.size,\n dexPositionsCacheKeys: Array.from(this.dexPositionsCache.keys()),\n dexAssetCtxsCacheKeys: Array.from(this.dexAssetCtxsCache.keys()),\n },\n );\n\n this.dexPositionsCache.clear();\n this.dexOrdersCache.clear();\n this.dexAccountCache.clear();\n this.dexAssetCtxsCache.clear();\n\n // Clear subscription references (actual cleanup handled by client service)\n this.globalAllMidsSubscription = undefined;\n this.globalActiveAssetSubscriptions.clear();\n this.globalBboSubscriptions.clear();\n this.webData3Subscriptions.clear();\n this.webData3SubscriptionPromise = undefined;\n\n // HIP-3: Clear assetCtxs subscriptions (clearinghouseState no longer needed with webData3)\n this.assetCtxsSubscriptions.clear();\n this.assetCtxsSubscriptionPromises.clear();\n\n // Cleanup individual subscriptions (clearinghouseState + openOrders)\n if (this.clearinghouseStateSubscriptions.size > 0) {\n this.clearinghouseStateSubscriptions.forEach(\n (subscription, dexNameKey) => {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('clearAll.clearinghouseState', {\n dex: dexNameKey,\n }),\n );\n });\n },\n );\n this.clearinghouseStateSubscriptions.clear();\n }\n\n if (this.openOrdersSubscriptions.size > 0) {\n this.openOrdersSubscriptions.forEach((subscription, dexNameKey) => {\n subscription.unsubscribe().catch((unsubError: Error) => {\n this.deps.logger.error(\n ensureError(unsubError),\n this.getErrorContext('clearAll.openOrders', {\n dex: dexNameKey,\n }),\n );\n });\n });\n this.openOrdersSubscriptions.clear();\n }\n\n this.deps.debugLogger.log(\n 'HyperLiquid: Subscription service cleared (multi-DEX with individual subscriptions)',\n {\n timestamp: new Date().toISOString(),\n },\n );\n }\n}\n"]}
@@ -1,140 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _HyperLiquidWalletService_isTestnet, _HyperLiquidWalletService_deps;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.HyperLiquidWalletService = void 0;
16
- const utils_1 = require("@metamask/utils");
17
- const hyperLiquidConfig_1 = require("../constants/hyperLiquidConfig.cjs");
18
- const perpsErrorCodes_1 = require("../constants/perpsErrorCodes.cjs");
19
- /**
20
- * Service for MetaMask wallet integration with HyperLiquid SDK
21
- * Provides wallet adapter that implements AbstractWindowEthereum interface
22
- */
23
- class HyperLiquidWalletService {
24
- /**
25
- * Creates a new HyperLiquidWalletService instance.
26
- *
27
- * @param deps - Platform dependencies for account access and signing
28
- * @param options - Configuration options
29
- * @param options.isTestnet - Whether to use testnet mode
30
- */
31
- constructor(deps, options = {}) {
32
- _HyperLiquidWalletService_isTestnet.set(this, void 0);
33
- // Platform dependencies for account access and signing
34
- _HyperLiquidWalletService_deps.set(this, void 0);
35
- __classPrivateFieldSet(this, _HyperLiquidWalletService_deps, deps, "f");
36
- __classPrivateFieldSet(this, _HyperLiquidWalletService_isTestnet, options.isTestnet ?? false, "f");
37
- }
38
- /**
39
- * Create wallet adapter that implements AbstractViemJsonRpcAccount interface
40
- * Required by @nktkas/hyperliquid SDK for signing transactions
41
- *
42
- * @returns Wallet adapter object with address, signTypedData, and getChainId
43
- */
44
- createWalletAdapter() {
45
- // Get current EVM account using the injected controllers.accounts
46
- const evmAccount = __classPrivateFieldGet(this, _HyperLiquidWalletService_deps, "f").controllers.accounts.getSelectedEvmAccount();
47
- if (!evmAccount?.address) {
48
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);
49
- }
50
- const address = evmAccount.address;
51
- return {
52
- address,
53
- signTypedData: async (params) => {
54
- // Get FRESH account on every sign to handle account switches
55
- // This prevents race conditions where wallet adapter was created with old account
56
- const currentEvmAccount = __classPrivateFieldGet(this, _HyperLiquidWalletService_deps, "f").controllers.accounts.getSelectedEvmAccount();
57
- if (!currentEvmAccount?.address) {
58
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);
59
- }
60
- const currentAddress = currentEvmAccount.address;
61
- // Construct EIP-712 typed data
62
- const typedData = {
63
- domain: params.domain,
64
- types: params.types,
65
- primaryType: params.primaryType,
66
- message: params.message,
67
- };
68
- __classPrivateFieldGet(this, _HyperLiquidWalletService_deps, "f").debugLogger.log('HyperLiquidWalletService: Signing typed data', {
69
- address: currentAddress,
70
- primaryType: params.primaryType,
71
- domain: params.domain,
72
- });
73
- // Use injected controllers.keyring to sign
74
- const signature = await __classPrivateFieldGet(this, _HyperLiquidWalletService_deps, "f").controllers.keyring.signTypedMessage({
75
- from: currentAddress,
76
- data: typedData,
77
- }, 'V4');
78
- return signature;
79
- },
80
- getChainId: async () => parseInt((0, hyperLiquidConfig_1.getChainId)(__classPrivateFieldGet(this, _HyperLiquidWalletService_isTestnet, "f")), 10),
81
- };
82
- }
83
- /**
84
- * Get current account ID using the injected controllers.accounts
85
- *
86
- * @returns The current account ID in CAIP-10 format
87
- */
88
- async getCurrentAccountId() {
89
- const evmAccount = __classPrivateFieldGet(this, _HyperLiquidWalletService_deps, "f").controllers.accounts.getSelectedEvmAccount();
90
- if (!evmAccount?.address) {
91
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);
92
- }
93
- const chainId = (0, hyperLiquidConfig_1.getChainId)(__classPrivateFieldGet(this, _HyperLiquidWalletService_isTestnet, "f"));
94
- const caipAccountId = `eip155:${chainId}:${evmAccount.address}`;
95
- return caipAccountId;
96
- }
97
- /**
98
- * Get validated user address as Hex from account ID
99
- *
100
- * @param accountId - The CAIP-10 account ID
101
- * @returns The validated Hex address
102
- */
103
- getUserAddress(accountId) {
104
- const parsed = (0, utils_1.parseCaipAccountId)(accountId);
105
- const address = parsed.address;
106
- if (!(0, utils_1.isValidHexAddress)(address)) {
107
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.INVALID_ADDRESS_FORMAT);
108
- }
109
- return address;
110
- }
111
- /**
112
- * Get user address with default fallback to current account
113
- *
114
- * @param accountId - Optional CAIP-10 account ID
115
- * @returns The validated Hex address
116
- */
117
- async getUserAddressWithDefault(accountId) {
118
- const id = accountId ?? (await this.getCurrentAccountId());
119
- return this.getUserAddress(id);
120
- }
121
- /**
122
- * Update testnet mode
123
- *
124
- * @param isTestnet - Whether to enable testnet mode
125
- */
126
- setTestnetMode(isTestnet) {
127
- __classPrivateFieldSet(this, _HyperLiquidWalletService_isTestnet, isTestnet, "f");
128
- }
129
- /**
130
- * Check if running on testnet
131
- *
132
- * @returns True if testnet mode is enabled
133
- */
134
- isTestnetMode() {
135
- return __classPrivateFieldGet(this, _HyperLiquidWalletService_isTestnet, "f");
136
- }
137
- }
138
- exports.HyperLiquidWalletService = HyperLiquidWalletService;
139
- _HyperLiquidWalletService_isTestnet = new WeakMap(), _HyperLiquidWalletService_deps = new WeakMap();
140
- //# sourceMappingURL=HyperLiquidWalletService.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HyperLiquidWalletService.cjs","sourceRoot":"","sources":["../../src/platform-services/HyperLiquidWalletService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAwE;AAGxE,0EAA4D;AAC5D,sEAAiE;AAGjE;;;GAGG;AACH,MAAa,wBAAwB;IAMnC;;;;;;OAMG;IACH,YACE,IAA+B,EAC/B,UAAmC,EAAE;QAdvC,sDAAoB;QAEpB,uDAAuD;QAC9C,iDAAiC;QAaxC,uBAAA,IAAI,kCAAS,IAAI,MAAA,CAAC;QAClB,uBAAA,IAAI,uCAAc,OAAO,CAAC,SAAS,IAAI,KAAK,MAAA,CAAC;IAC/C,CAAC;IAED;;;;;OAKG;IACI,mBAAmB;QAiBxB,kEAAkE;QAClE,MAAM,UAAU,GAAG,uBAAA,IAAI,sCAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,qBAAqB,EAAE,CAAC;QAE3E,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,mCAAiB,CAAC,mBAAmB,CAAC,CAAC;QACzD,CAAC;QAED,MAAM,OAAO,GAAG,UAAU,CAAC,OAAc,CAAC;QAE1C,OAAO;YACL,OAAO;YACP,aAAa,EAAE,KAAK,EAAE,MAYrB,EAAgB,EAAE;gBACjB,6DAA6D;gBAC7D,kFAAkF;gBAClF,MAAM,iBAAiB,GACrB,uBAAA,IAAI,sCAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,qBAAqB,EAAE,CAAC;gBAE1D,IAAI,CAAC,iBAAiB,EAAE,OAAO,EAAE,CAAC;oBAChC,MAAM,IAAI,KAAK,CAAC,mCAAiB,CAAC,mBAAmB,CAAC,CAAC;gBACzD,CAAC;gBAED,MAAM,cAAc,GAAG,iBAA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IACvB,CAAC;IAED;;;;;OAKG;IACI,cAAc,CAAC,SAAwB;QAC5C,MAAM,MAAM,GAAG,IAAA,0BAAkB,EAAC,SAAS,CAAC,CAAC;QAC7C,MAAM,OAAO,GAAG,MAAM,CAAC,OAAc,CAAC;QAEtC,IAAI,CAAC,IAAA,yBAAiB,EAAC,OAAO,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,mCAAiB,CAAC,sBAAsB,CAAC,CAAC;QAC5D,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACI,KAAK,CAAC,yBAAyB,CACpC,SAAyB;QAEzB,MAAM,EAAE,GAAG,SAAS,IAAI,CAAC,MAAM,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAED;;;;OAIG;IACI,cAAc,CAAC,SAAkB;QACtC,uBAAA,IAAI,uCAAc,SAAS,MAAA,CAAC;IAC9B,CAAC;IAED;;;;OAIG;IACI,aAAa;QAClB,OAAO,uBAAA,IAAI,2CAAW,CAAC;IACzB,CAAC;CACF;AAjLD,4DAiLC","sourcesContent":["import { parseCaipAccountId, isValidHexAddress } from '@metamask/utils';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\n\nimport { getChainId } from '../constants/hyperLiquidConfig';\nimport { PERPS_ERROR_CODES } from '../constants/perpsErrorCodes';\nimport type { PerpsPlatformDependencies } from '../types';\n\n/**\n * Service for MetaMask wallet integration with HyperLiquid SDK\n * Provides wallet adapter that implements AbstractWindowEthereum interface\n */\nexport class HyperLiquidWalletService {\n #isTestnet: boolean;\n\n // Platform dependencies for account access and signing\n readonly #deps: PerpsPlatformDependencies;\n\n /**\n * Creates a new HyperLiquidWalletService instance.\n *\n * @param deps - Platform dependencies for account access and signing\n * @param options - Configuration options\n * @param options.isTestnet - Whether to use testnet mode\n */\n constructor(\n deps: PerpsPlatformDependencies,\n options: { isTestnet?: boolean } = {},\n ) {\n this.#deps = deps;\n this.#isTestnet = options.isTestnet ?? false;\n }\n\n /**\n * Create wallet adapter that implements AbstractViemJsonRpcAccount interface\n * Required by @nktkas/hyperliquid SDK for signing transactions\n *\n * @returns Wallet adapter object with address, signTypedData, and getChainId\n */\n public createWalletAdapter(): {\n address: Hex;\n signTypedData: (params: {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Hex;\n };\n types: {\n [key: string]: { name: string; type: string }[];\n };\n primaryType: string;\n message: Record<string, unknown>;\n }) => Promise<Hex>;\n getChainId?: () => Promise<number>;\n } {\n // Get current EVM account using the injected controllers.accounts\n const evmAccount = this.#deps.controllers.accounts.getSelectedEvmAccount();\n\n if (!evmAccount?.address) {\n throw new Error(PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);\n }\n\n const address = evmAccount.address as Hex;\n\n return {\n address,\n signTypedData: async (params: {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Hex;\n };\n types: {\n [key: string]: { name: string; type: string }[];\n };\n primaryType: string;\n message: Record<string, unknown>;\n }): Promise<Hex> => {\n // Get FRESH account on every sign to handle account switches\n // This prevents race conditions where wallet adapter was created with old account\n const currentEvmAccount =\n this.#deps.controllers.accounts.getSelectedEvmAccount();\n\n if (!currentEvmAccount?.address) {\n throw new Error(PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);\n }\n\n const currentAddress = currentEvmAccount.address as Hex;\n\n // Construct EIP-712 typed data\n const typedData = {\n domain: params.domain,\n types: params.types,\n primaryType: params.primaryType,\n message: params.message,\n };\n\n this.#deps.debugLogger.log(\n 'HyperLiquidWalletService: Signing typed data',\n {\n address: currentAddress,\n primaryType: params.primaryType,\n domain: params.domain,\n },\n );\n\n // Use injected controllers.keyring to sign\n const signature = await this.#deps.controllers.keyring.signTypedMessage(\n {\n from: currentAddress,\n data: typedData,\n },\n 'V4',\n );\n\n return signature as Hex;\n },\n getChainId: async (): Promise<number> =>\n parseInt(getChainId(this.#isTestnet), 10),\n };\n }\n\n /**\n * Get current account ID using the injected controllers.accounts\n *\n * @returns The current account ID in CAIP-10 format\n */\n public async getCurrentAccountId(): Promise<CaipAccountId> {\n const evmAccount = this.#deps.controllers.accounts.getSelectedEvmAccount();\n\n if (!evmAccount?.address) {\n throw new Error(PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED);\n }\n\n const chainId = getChainId(this.#isTestnet);\n const caipAccountId: CaipAccountId = `eip155:${chainId}:${evmAccount.address}`;\n\n return caipAccountId;\n }\n\n /**\n * Get validated user address as Hex from account ID\n *\n * @param accountId - The CAIP-10 account ID\n * @returns The validated Hex address\n */\n public getUserAddress(accountId: CaipAccountId): Hex {\n const parsed = parseCaipAccountId(accountId);\n const address = parsed.address as Hex;\n\n if (!isValidHexAddress(address)) {\n throw new Error(PERPS_ERROR_CODES.INVALID_ADDRESS_FORMAT);\n }\n\n return address;\n }\n\n /**\n * Get user address with default fallback to current account\n *\n * @param accountId - Optional CAIP-10 account ID\n * @returns The validated Hex address\n */\n public async getUserAddressWithDefault(\n accountId?: CaipAccountId,\n ): Promise<Hex> {\n const id = accountId ?? (await this.getCurrentAccountId());\n return this.getUserAddress(id);\n }\n\n /**\n * Update testnet mode\n *\n * @param isTestnet - Whether to enable testnet mode\n */\n public setTestnetMode(isTestnet: boolean): void {\n this.#isTestnet = isTestnet;\n }\n\n /**\n * Check if running on testnet\n *\n * @returns True if testnet mode is enabled\n */\n public isTestnetMode(): boolean {\n return this.#isTestnet;\n }\n}\n"]}