@metamask-previews/perps-controller 0.0.0-preview-567bc78af → 0.0.0-preview-3d4d0d0ef

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 (474) hide show
  1. package/CHANGELOG.md +0 -25
  2. package/dist/PerpsController.cjs +65 -3036
  3. package/dist/PerpsController.cjs.map +1 -1
  4. package/dist/PerpsController.d.cts +82 -967
  5. package/dist/PerpsController.d.cts.map +1 -1
  6. package/dist/PerpsController.d.mts +82 -967
  7. package/dist/PerpsController.d.mts.map +1 -1
  8. package/dist/PerpsController.mjs +62 -3032
  9. package/dist/PerpsController.mjs.map +1 -1
  10. package/dist/index.cjs +1 -63
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +2 -38
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +2 -38
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +1 -46
  17. package/dist/index.mjs.map +1 -1
  18. package/package.json +3 -10
  19. package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -441
  20. package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
  21. package/dist/aggregation/SubscriptionMultiplexer.d.cts +0 -171
  22. package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
  23. package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -171
  24. package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
  25. package/dist/aggregation/SubscriptionMultiplexer.mjs +0 -437
  26. package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
  27. package/dist/aggregation/index.cjs +0 -9
  28. package/dist/aggregation/index.cjs.map +0 -1
  29. package/dist/aggregation/index.d.cts +0 -6
  30. package/dist/aggregation/index.d.cts.map +0 -1
  31. package/dist/aggregation/index.d.mts +0 -6
  32. package/dist/aggregation/index.d.mts.map +0 -1
  33. package/dist/aggregation/index.mjs +0 -5
  34. package/dist/aggregation/index.mjs.map +0 -1
  35. package/dist/constants/chartConfig.cjs +0 -227
  36. package/dist/constants/chartConfig.cjs.map +0 -1
  37. package/dist/constants/chartConfig.d.cts +0 -216
  38. package/dist/constants/chartConfig.d.cts.map +0 -1
  39. package/dist/constants/chartConfig.d.mts +0 -216
  40. package/dist/constants/chartConfig.d.mts.map +0 -1
  41. package/dist/constants/chartConfig.mjs +0 -221
  42. package/dist/constants/chartConfig.mjs.map +0 -1
  43. package/dist/constants/eventNames.cjs +0 -435
  44. package/dist/constants/eventNames.cjs.map +0 -1
  45. package/dist/constants/eventNames.d.cts +0 -386
  46. package/dist/constants/eventNames.d.cts.map +0 -1
  47. package/dist/constants/eventNames.d.mts +0 -386
  48. package/dist/constants/eventNames.d.mts.map +0 -1
  49. package/dist/constants/eventNames.mjs +0 -432
  50. package/dist/constants/eventNames.mjs.map +0 -1
  51. package/dist/constants/hyperLiquidConfig.cjs +0 -380
  52. package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
  53. package/dist/constants/hyperLiquidConfig.d.cts +0 -236
  54. package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
  55. package/dist/constants/hyperLiquidConfig.d.mts +0 -236
  56. package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
  57. package/dist/constants/hyperLiquidConfig.mjs +0 -371
  58. package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
  59. package/dist/constants/index.cjs +0 -28
  60. package/dist/constants/index.cjs.map +0 -1
  61. package/dist/constants/index.d.cts +0 -12
  62. package/dist/constants/index.d.cts.map +0 -1
  63. package/dist/constants/index.d.mts +0 -12
  64. package/dist/constants/index.d.mts.map +0 -1
  65. package/dist/constants/index.mjs +0 -12
  66. package/dist/constants/index.mjs.map +0 -1
  67. package/dist/constants/myxConfig.cjs +0 -229
  68. package/dist/constants/myxConfig.cjs.map +0 -1
  69. package/dist/constants/myxConfig.d.cts +0 -106
  70. package/dist/constants/myxConfig.d.cts.map +0 -1
  71. package/dist/constants/myxConfig.d.mts +0 -106
  72. package/dist/constants/myxConfig.d.mts.map +0 -1
  73. package/dist/constants/myxConfig.mjs +0 -219
  74. package/dist/constants/myxConfig.mjs.map +0 -1
  75. package/dist/constants/orderTypes.cjs +0 -31
  76. package/dist/constants/orderTypes.cjs.map +0 -1
  77. package/dist/constants/orderTypes.d.cts +0 -19
  78. package/dist/constants/orderTypes.d.cts.map +0 -1
  79. package/dist/constants/orderTypes.d.mts +0 -19
  80. package/dist/constants/orderTypes.d.mts.map +0 -1
  81. package/dist/constants/orderTypes.mjs +0 -27
  82. package/dist/constants/orderTypes.mjs.map +0 -1
  83. package/dist/constants/performanceMetrics.cjs +0 -63
  84. package/dist/constants/performanceMetrics.cjs.map +0 -1
  85. package/dist/constants/performanceMetrics.d.cts +0 -46
  86. package/dist/constants/performanceMetrics.d.cts.map +0 -1
  87. package/dist/constants/performanceMetrics.d.mts +0 -46
  88. package/dist/constants/performanceMetrics.d.mts.map +0 -1
  89. package/dist/constants/performanceMetrics.mjs +0 -60
  90. package/dist/constants/performanceMetrics.mjs.map +0 -1
  91. package/dist/constants/perpsConfig.cjs +0 -295
  92. package/dist/constants/perpsConfig.cjs.map +0 -1
  93. package/dist/constants/perpsConfig.d.cts +0 -221
  94. package/dist/constants/perpsConfig.d.cts.map +0 -1
  95. package/dist/constants/perpsConfig.d.mts +0 -221
  96. package/dist/constants/perpsConfig.d.mts.map +0 -1
  97. package/dist/constants/perpsConfig.mjs +0 -292
  98. package/dist/constants/perpsConfig.mjs.map +0 -1
  99. package/dist/constants/transactionsHistoryConfig.cjs +0 -19
  100. package/dist/constants/transactionsHistoryConfig.cjs.map +0 -1
  101. package/dist/constants/transactionsHistoryConfig.d.cts +0 -16
  102. package/dist/constants/transactionsHistoryConfig.d.cts.map +0 -1
  103. package/dist/constants/transactionsHistoryConfig.d.mts +0 -16
  104. package/dist/constants/transactionsHistoryConfig.d.mts.map +0 -1
  105. package/dist/constants/transactionsHistoryConfig.mjs +0 -16
  106. package/dist/constants/transactionsHistoryConfig.mjs.map +0 -1
  107. package/dist/perpsErrorCodes.cjs +0 -80
  108. package/dist/perpsErrorCodes.cjs.map +0 -1
  109. package/dist/perpsErrorCodes.d.cts +0 -65
  110. package/dist/perpsErrorCodes.d.cts.map +0 -1
  111. package/dist/perpsErrorCodes.d.mts +0 -65
  112. package/dist/perpsErrorCodes.d.mts.map +0 -1
  113. package/dist/perpsErrorCodes.mjs +0 -77
  114. package/dist/perpsErrorCodes.mjs.map +0 -1
  115. package/dist/providers/AggregatedPerpsProvider.cjs +0 -508
  116. package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
  117. package/dist/providers/AggregatedPerpsProvider.d.cts +0 -171
  118. package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
  119. package/dist/providers/AggregatedPerpsProvider.d.mts +0 -171
  120. package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
  121. package/dist/providers/AggregatedPerpsProvider.mjs +0 -504
  122. package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
  123. package/dist/providers/HyperLiquidProvider.cjs +0 -5677
  124. package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
  125. package/dist/providers/HyperLiquidProvider.d.cts +0 -514
  126. package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
  127. package/dist/providers/HyperLiquidProvider.d.mts +0 -514
  128. package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
  129. package/dist/providers/HyperLiquidProvider.mjs +0 -5673
  130. package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
  131. package/dist/providers/MYXProvider.cjs +0 -514
  132. package/dist/providers/MYXProvider.cjs.map +0 -1
  133. package/dist/providers/MYXProvider.d.cts +0 -105
  134. package/dist/providers/MYXProvider.d.cts.map +0 -1
  135. package/dist/providers/MYXProvider.d.mts +0 -105
  136. package/dist/providers/MYXProvider.d.mts.map +0 -1
  137. package/dist/providers/MYXProvider.mjs +0 -510
  138. package/dist/providers/MYXProvider.mjs.map +0 -1
  139. package/dist/routing/ProviderRouter.cjs +0 -154
  140. package/dist/routing/ProviderRouter.cjs.map +0 -1
  141. package/dist/routing/ProviderRouter.d.cts +0 -112
  142. package/dist/routing/ProviderRouter.d.cts.map +0 -1
  143. package/dist/routing/ProviderRouter.d.mts +0 -112
  144. package/dist/routing/ProviderRouter.d.mts.map +0 -1
  145. package/dist/routing/ProviderRouter.mjs +0 -150
  146. package/dist/routing/ProviderRouter.mjs.map +0 -1
  147. package/dist/routing/index.cjs +0 -9
  148. package/dist/routing/index.cjs.map +0 -1
  149. package/dist/routing/index.d.cts +0 -6
  150. package/dist/routing/index.d.cts.map +0 -1
  151. package/dist/routing/index.d.mts +0 -6
  152. package/dist/routing/index.d.mts.map +0 -1
  153. package/dist/routing/index.mjs +0 -5
  154. package/dist/routing/index.mjs.map +0 -1
  155. package/dist/selectors.cjs +0 -166
  156. package/dist/selectors.cjs.map +0 -1
  157. package/dist/selectors.d.cts +0 -362
  158. package/dist/selectors.d.cts.map +0 -1
  159. package/dist/selectors.d.mts +0 -362
  160. package/dist/selectors.d.mts.map +0 -1
  161. package/dist/selectors.mjs +0 -158
  162. package/dist/selectors.mjs.map +0 -1
  163. package/dist/services/AccountService.cjs +0 -321
  164. package/dist/services/AccountService.cjs.map +0 -1
  165. package/dist/services/AccountService.d.cts +0 -54
  166. package/dist/services/AccountService.d.cts.map +0 -1
  167. package/dist/services/AccountService.d.mts +0 -54
  168. package/dist/services/AccountService.d.mts.map +0 -1
  169. package/dist/services/AccountService.mjs +0 -317
  170. package/dist/services/AccountService.mjs.map +0 -1
  171. package/dist/services/DataLakeService.cjs +0 -230
  172. package/dist/services/DataLakeService.cjs.map +0 -1
  173. package/dist/services/DataLakeService.d.cts +0 -49
  174. package/dist/services/DataLakeService.d.cts.map +0 -1
  175. package/dist/services/DataLakeService.d.mts +0 -49
  176. package/dist/services/DataLakeService.d.mts.map +0 -1
  177. package/dist/services/DataLakeService.mjs +0 -226
  178. package/dist/services/DataLakeService.mjs.map +0 -1
  179. package/dist/services/DepositService.cjs +0 -95
  180. package/dist/services/DepositService.cjs.map +0 -1
  181. package/dist/services/DepositService.d.cts +0 -37
  182. package/dist/services/DepositService.d.cts.map +0 -1
  183. package/dist/services/DepositService.d.mts +0 -37
  184. package/dist/services/DepositService.d.mts.map +0 -1
  185. package/dist/services/DepositService.mjs +0 -91
  186. package/dist/services/DepositService.mjs.map +0 -1
  187. package/dist/services/EligibilityService.cjs +0 -173
  188. package/dist/services/EligibilityService.cjs.map +0 -1
  189. package/dist/services/EligibilityService.d.cts +0 -39
  190. package/dist/services/EligibilityService.d.cts.map +0 -1
  191. package/dist/services/EligibilityService.d.mts +0 -39
  192. package/dist/services/EligibilityService.d.mts.map +0 -1
  193. package/dist/services/EligibilityService.mjs +0 -169
  194. package/dist/services/EligibilityService.mjs.map +0 -1
  195. package/dist/services/FeatureFlagConfigurationService.cjs +0 -257
  196. package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
  197. package/dist/services/FeatureFlagConfigurationService.d.cts +0 -73
  198. package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
  199. package/dist/services/FeatureFlagConfigurationService.d.mts +0 -73
  200. package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
  201. package/dist/services/FeatureFlagConfigurationService.mjs +0 -253
  202. package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
  203. package/dist/services/HyperLiquidClientService.cjs +0 -867
  204. package/dist/services/HyperLiquidClientService.cjs.map +0 -1
  205. package/dist/services/HyperLiquidClientService.d.cts +0 -214
  206. package/dist/services/HyperLiquidClientService.d.cts.map +0 -1
  207. package/dist/services/HyperLiquidClientService.d.mts +0 -214
  208. package/dist/services/HyperLiquidClientService.d.mts.map +0 -1
  209. package/dist/services/HyperLiquidClientService.mjs +0 -862
  210. package/dist/services/HyperLiquidClientService.mjs.map +0 -1
  211. package/dist/services/HyperLiquidSubscriptionService.cjs +0 -2204
  212. package/dist/services/HyperLiquidSubscriptionService.cjs.map +0 -1
  213. package/dist/services/HyperLiquidSubscriptionService.d.cts +0 -187
  214. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +0 -1
  215. package/dist/services/HyperLiquidSubscriptionService.d.mts +0 -187
  216. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +0 -1
  217. package/dist/services/HyperLiquidSubscriptionService.mjs +0 -2200
  218. package/dist/services/HyperLiquidSubscriptionService.mjs.map +0 -1
  219. package/dist/services/HyperLiquidWalletService.cjs +0 -155
  220. package/dist/services/HyperLiquidWalletService.cjs.map +0 -1
  221. package/dist/services/HyperLiquidWalletService.d.cts +0 -77
  222. package/dist/services/HyperLiquidWalletService.d.cts.map +0 -1
  223. package/dist/services/HyperLiquidWalletService.d.mts +0 -77
  224. package/dist/services/HyperLiquidWalletService.d.mts.map +0 -1
  225. package/dist/services/HyperLiquidWalletService.mjs +0 -151
  226. package/dist/services/HyperLiquidWalletService.mjs.map +0 -1
  227. package/dist/services/MYXClientService.cjs +0 -304
  228. package/dist/services/MYXClientService.cjs.map +0 -1
  229. package/dist/services/MYXClientService.d.cts +0 -81
  230. package/dist/services/MYXClientService.d.cts.map +0 -1
  231. package/dist/services/MYXClientService.d.mts +0 -81
  232. package/dist/services/MYXClientService.d.mts.map +0 -1
  233. package/dist/services/MYXClientService.mjs +0 -300
  234. package/dist/services/MYXClientService.mjs.map +0 -1
  235. package/dist/services/MarketDataService.cjs +0 -848
  236. package/dist/services/MarketDataService.cjs.map +0 -1
  237. package/dist/services/MarketDataService.d.cts +0 -291
  238. package/dist/services/MarketDataService.d.cts.map +0 -1
  239. package/dist/services/MarketDataService.d.mts +0 -291
  240. package/dist/services/MarketDataService.d.mts.map +0 -1
  241. package/dist/services/MarketDataService.mjs +0 -844
  242. package/dist/services/MarketDataService.mjs.map +0 -1
  243. package/dist/services/RewardsIntegrationService.cjs +0 -117
  244. package/dist/services/RewardsIntegrationService.cjs.map +0 -1
  245. package/dist/services/RewardsIntegrationService.d.cts +0 -26
  246. package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
  247. package/dist/services/RewardsIntegrationService.d.mts +0 -26
  248. package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
  249. package/dist/services/RewardsIntegrationService.mjs +0 -113
  250. package/dist/services/RewardsIntegrationService.mjs.map +0 -1
  251. package/dist/services/ServiceContext.cjs +0 -3
  252. package/dist/services/ServiceContext.cjs.map +0 -1
  253. package/dist/services/ServiceContext.d.cts +0 -86
  254. package/dist/services/ServiceContext.d.cts.map +0 -1
  255. package/dist/services/ServiceContext.d.mts +0 -86
  256. package/dist/services/ServiceContext.d.mts.map +0 -1
  257. package/dist/services/ServiceContext.mjs +0 -2
  258. package/dist/services/ServiceContext.mjs.map +0 -1
  259. package/dist/services/TradingReadinessCache.cjs +0 -288
  260. package/dist/services/TradingReadinessCache.cjs.map +0 -1
  261. package/dist/services/TradingReadinessCache.d.cts +0 -174
  262. package/dist/services/TradingReadinessCache.d.cts.map +0 -1
  263. package/dist/services/TradingReadinessCache.d.mts +0 -174
  264. package/dist/services/TradingReadinessCache.d.mts.map +0 -1
  265. package/dist/services/TradingReadinessCache.mjs +0 -285
  266. package/dist/services/TradingReadinessCache.mjs.map +0 -1
  267. package/dist/services/TradingService.cjs +0 -1453
  268. package/dist/services/TradingService.cjs.map +0 -1
  269. package/dist/services/TradingService.d.cts +0 -195
  270. package/dist/services/TradingService.d.cts.map +0 -1
  271. package/dist/services/TradingService.d.mts +0 -195
  272. package/dist/services/TradingService.d.mts.map +0 -1
  273. package/dist/services/TradingService.mjs +0 -1449
  274. package/dist/services/TradingService.mjs.map +0 -1
  275. package/dist/types/config.cjs +0 -3
  276. package/dist/types/config.cjs.map +0 -1
  277. package/dist/types/config.d.cts +0 -49
  278. package/dist/types/config.d.cts.map +0 -1
  279. package/dist/types/config.d.mts +0 -49
  280. package/dist/types/config.d.mts.map +0 -1
  281. package/dist/types/config.mjs +0 -2
  282. package/dist/types/config.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 -20
  286. package/dist/types/hyperliquid-types.d.cts.map +0 -1
  287. package/dist/types/hyperliquid-types.d.mts +0 -20
  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 -115
  292. package/dist/types/index.cjs.map +0 -1
  293. package/dist/types/index.d.cts +0 -1299
  294. package/dist/types/index.d.cts.map +0 -1
  295. package/dist/types/index.d.mts +0 -1299
  296. package/dist/types/index.d.mts.map +0 -1
  297. package/dist/types/index.mjs +0 -97
  298. package/dist/types/index.mjs.map +0 -1
  299. package/dist/types/myx-types.cjs +0 -25
  300. package/dist/types/myx-types.cjs.map +0 -1
  301. package/dist/types/myx-types.d.cts +0 -63
  302. package/dist/types/myx-types.d.cts.map +0 -1
  303. package/dist/types/myx-types.d.mts +0 -63
  304. package/dist/types/myx-types.d.mts.map +0 -1
  305. package/dist/types/myx-types.mjs +0 -22
  306. package/dist/types/myx-types.mjs.map +0 -1
  307. package/dist/types/perps-types.cjs +0 -4
  308. package/dist/types/perps-types.cjs.map +0 -1
  309. package/dist/types/perps-types.d.cts +0 -105
  310. package/dist/types/perps-types.d.cts.map +0 -1
  311. package/dist/types/perps-types.d.mts +0 -105
  312. package/dist/types/perps-types.d.mts.map +0 -1
  313. package/dist/types/perps-types.mjs +0 -2
  314. package/dist/types/perps-types.mjs.map +0 -1
  315. package/dist/types/token.cjs +0 -3
  316. package/dist/types/token.cjs.map +0 -1
  317. package/dist/types/token.d.cts +0 -25
  318. package/dist/types/token.d.cts.map +0 -1
  319. package/dist/types/token.d.mts +0 -25
  320. package/dist/types/token.d.mts.map +0 -1
  321. package/dist/types/token.mjs +0 -2
  322. package/dist/types/token.mjs.map +0 -1
  323. package/dist/types/transactionTypes.cjs +0 -28
  324. package/dist/types/transactionTypes.cjs.map +0 -1
  325. package/dist/types/transactionTypes.d.cts +0 -64
  326. package/dist/types/transactionTypes.d.cts.map +0 -1
  327. package/dist/types/transactionTypes.d.mts +0 -64
  328. package/dist/types/transactionTypes.d.mts.map +0 -1
  329. package/dist/types/transactionTypes.mjs +0 -23
  330. package/dist/types/transactionTypes.mjs.map +0 -1
  331. package/dist/utils/accountUtils.cjs +0 -101
  332. package/dist/utils/accountUtils.cjs.map +0 -1
  333. package/dist/utils/accountUtils.d.cts +0 -34
  334. package/dist/utils/accountUtils.d.cts.map +0 -1
  335. package/dist/utils/accountUtils.d.mts +0 -34
  336. package/dist/utils/accountUtils.d.mts.map +0 -1
  337. package/dist/utils/accountUtils.mjs +0 -93
  338. package/dist/utils/accountUtils.mjs.map +0 -1
  339. package/dist/utils/errorUtils.cjs +0 -35
  340. package/dist/utils/errorUtils.cjs.map +0 -1
  341. package/dist/utils/errorUtils.d.cts +0 -15
  342. package/dist/utils/errorUtils.d.cts.map +0 -1
  343. package/dist/utils/errorUtils.d.mts +0 -15
  344. package/dist/utils/errorUtils.d.mts.map +0 -1
  345. package/dist/utils/errorUtils.mjs +0 -31
  346. package/dist/utils/errorUtils.mjs.map +0 -1
  347. package/dist/utils/hyperLiquidAdapter.cjs +0 -302
  348. package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
  349. package/dist/utils/hyperLiquidAdapter.d.cts +0 -42
  350. package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
  351. package/dist/utils/hyperLiquidAdapter.d.mts +0 -42
  352. package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
  353. package/dist/utils/hyperLiquidAdapter.mjs +0 -287
  354. package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
  355. package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -83
  356. package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
  357. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -55
  358. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
  359. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +0 -55
  360. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
  361. package/dist/utils/hyperLiquidOrderBookProcessor.mjs +0 -78
  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 -18
  372. package/dist/utils/idUtils.cjs.map +0 -1
  373. package/dist/utils/idUtils.d.cts +0 -6
  374. package/dist/utils/idUtils.d.cts.map +0 -1
  375. package/dist/utils/idUtils.d.mts +0 -6
  376. package/dist/utils/idUtils.d.mts.map +0 -1
  377. package/dist/utils/idUtils.mjs +0 -10
  378. package/dist/utils/idUtils.mjs.map +0 -1
  379. package/dist/utils/index.cjs +0 -59
  380. package/dist/utils/index.cjs.map +0 -1
  381. package/dist/utils/index.d.cts +0 -25
  382. package/dist/utils/index.d.cts.map +0 -1
  383. package/dist/utils/index.d.mts +0 -25
  384. package/dist/utils/index.d.mts.map +0 -1
  385. package/dist/utils/index.mjs +0 -30
  386. package/dist/utils/index.mjs.map +0 -1
  387. package/dist/utils/marketDataTransform.cjs +0 -211
  388. package/dist/utils/marketDataTransform.cjs.map +0 -1
  389. package/dist/utils/marketDataTransform.d.cts +0 -40
  390. package/dist/utils/marketDataTransform.d.cts.map +0 -1
  391. package/dist/utils/marketDataTransform.d.mts +0 -40
  392. package/dist/utils/marketDataTransform.d.mts.map +0 -1
  393. package/dist/utils/marketDataTransform.mjs +0 -205
  394. package/dist/utils/marketDataTransform.mjs.map +0 -1
  395. package/dist/utils/marketUtils.cjs +0 -151
  396. package/dist/utils/marketUtils.cjs.map +0 -1
  397. package/dist/utils/marketUtils.d.cts +0 -30
  398. package/dist/utils/marketUtils.d.cts.map +0 -1
  399. package/dist/utils/marketUtils.d.mts +0 -30
  400. package/dist/utils/marketUtils.d.mts.map +0 -1
  401. package/dist/utils/marketUtils.mjs +0 -138
  402. package/dist/utils/marketUtils.mjs.map +0 -1
  403. package/dist/utils/myxAdapter.cjs +0 -224
  404. package/dist/utils/myxAdapter.cjs.map +0 -1
  405. package/dist/utils/myxAdapter.d.cts +0 -81
  406. package/dist/utils/myxAdapter.d.cts.map +0 -1
  407. package/dist/utils/myxAdapter.d.mts +0 -81
  408. package/dist/utils/myxAdapter.d.mts.map +0 -1
  409. package/dist/utils/myxAdapter.mjs +0 -213
  410. package/dist/utils/myxAdapter.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/rewardsUtils.cjs +0 -95
  420. package/dist/utils/rewardsUtils.cjs.map +0 -1
  421. package/dist/utils/rewardsUtils.d.cts +0 -33
  422. package/dist/utils/rewardsUtils.d.cts.map +0 -1
  423. package/dist/utils/rewardsUtils.d.mts +0 -33
  424. package/dist/utils/rewardsUtils.d.mts.map +0 -1
  425. package/dist/utils/rewardsUtils.mjs +0 -89
  426. package/dist/utils/rewardsUtils.mjs.map +0 -1
  427. package/dist/utils/significantFigures.cjs +0 -88
  428. package/dist/utils/significantFigures.cjs.map +0 -1
  429. package/dist/utils/significantFigures.d.cts +0 -25
  430. package/dist/utils/significantFigures.d.cts.map +0 -1
  431. package/dist/utils/significantFigures.d.mts +0 -25
  432. package/dist/utils/significantFigures.d.mts.map +0 -1
  433. package/dist/utils/significantFigures.mjs +0 -82
  434. package/dist/utils/significantFigures.mjs.map +0 -1
  435. package/dist/utils/sortMarkets.cjs +0 -93
  436. package/dist/utils/sortMarkets.cjs.map +0 -1
  437. package/dist/utils/sortMarkets.d.cts +0 -27
  438. package/dist/utils/sortMarkets.d.cts.map +0 -1
  439. package/dist/utils/sortMarkets.d.mts +0 -27
  440. package/dist/utils/sortMarkets.d.mts.map +0 -1
  441. package/dist/utils/sortMarkets.mjs +0 -88
  442. package/dist/utils/sortMarkets.mjs.map +0 -1
  443. package/dist/utils/standaloneInfoClient.cjs +0 -70
  444. package/dist/utils/standaloneInfoClient.cjs.map +0 -1
  445. package/dist/utils/standaloneInfoClient.d.cts +0 -37
  446. package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
  447. package/dist/utils/standaloneInfoClient.d.mts +0 -37
  448. package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
  449. package/dist/utils/standaloneInfoClient.mjs +0 -64
  450. package/dist/utils/standaloneInfoClient.mjs.map +0 -1
  451. package/dist/utils/stringParseUtils.cjs +0 -18
  452. package/dist/utils/stringParseUtils.cjs.map +0 -1
  453. package/dist/utils/stringParseUtils.d.cts +0 -3
  454. package/dist/utils/stringParseUtils.d.cts.map +0 -1
  455. package/dist/utils/stringParseUtils.d.mts +0 -3
  456. package/dist/utils/stringParseUtils.d.mts.map +0 -1
  457. package/dist/utils/stringParseUtils.mjs +0 -13
  458. package/dist/utils/stringParseUtils.mjs.map +0 -1
  459. package/dist/utils/transferData.cjs +0 -33
  460. package/dist/utils/transferData.cjs.map +0 -1
  461. package/dist/utils/transferData.d.cts +0 -9
  462. package/dist/utils/transferData.d.cts.map +0 -1
  463. package/dist/utils/transferData.d.mts +0 -9
  464. package/dist/utils/transferData.d.mts.map +0 -1
  465. package/dist/utils/transferData.mjs +0 -29
  466. package/dist/utils/transferData.mjs.map +0 -1
  467. package/dist/utils/wait.cjs +0 -6
  468. package/dist/utils/wait.cjs.map +0 -1
  469. package/dist/utils/wait.d.cts +0 -2
  470. package/dist/utils/wait.d.cts.map +0 -1
  471. package/dist/utils/wait.d.mts +0 -2
  472. package/dist/utils/wait.d.mts.map +0 -1
  473. package/dist/utils/wait.mjs +0 -2
  474. package/dist/utils/wait.mjs.map +0 -1
@@ -1,3059 +1,88 @@
1
1
  "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- 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");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8
- if (kind === "m") throw new TypeError("Private method is not writable");
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
10
- 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");
11
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
- };
13
- var _PerpsController_instances, _a, _PerpsController_initializationPromise, _PerpsController_isReinitializing, _PerpsController_blockedRegionListVersion, _PerpsController_hip3Enabled, _PerpsController_hip3AllowlistMarkets, _PerpsController_hip3BlocklistMarkets, _PerpsController_hip3ConfigSource, _PerpsController_isMYXProviderEnabled, _PerpsController_standaloneProvider, _PerpsController_standaloneProviderIsTestnet, _PerpsController_standaloneProviderHip3Version, _PerpsController_options, _PerpsController_tradingService, _PerpsController_marketDataService, _PerpsController_accountService, _PerpsController_eligibilityService, _PerpsController_dataLakeService, _PerpsController_depositService, _PerpsController_featureFlagConfigurationService, _PerpsController_rewardsIntegrationService, _PerpsController_logError, _PerpsController_debugLog, _PerpsController_getOrCreateStandaloneProvider, _PerpsController_cleanupStandaloneProvider, _PerpsController_getMetrics, _PerpsController_findNetworkClientIdForChain, _PerpsController_submitTransaction, _PerpsController_migrateRequestsIfNeeded, _PerpsController_withStreamPause, _PerpsController_performInitialization, _PerpsController_getErrorContext, _PerpsController_getControllerState, _PerpsController_createServiceContext, _PerpsController_ensureTradingServiceDeps, _PerpsController_preloadWatchedPaths, _PerpsController_preloadTimer, _PerpsController_isPreloading, _PerpsController_isPreloadingUserData, _PerpsController_preloadStateUnsubscribe, _PerpsController_accountChangeUnsubscribe, _PerpsController_previousIsTestnet, _PerpsController_previousHip3ConfigVersion, _PerpsController_preloadRefreshMs, _PerpsController_preloadGuardMs, _PerpsController_performMarketDataPreload, _PerpsController_performUserDataPreload;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.PerpsController = exports.getDefaultPerpsControllerState = exports.InitializationState = exports.PERPS_ERROR_CODES = void 0;
3
+ exports.PerpsController = exports.getDefaultPerpsControllerState = exports.controllerName = void 0;
16
4
  const base_controller_1 = require("@metamask/base-controller");
17
- const controller_utils_1 = require("@metamask/controller-utils");
18
- const uuid_1 = require("uuid");
19
- const chartConfig_1 = require("./constants/chartConfig.cjs");
20
- const eventNames_1 = require("./constants/eventNames.cjs");
21
- const hyperLiquidConfig_1 = require("./constants/hyperLiquidConfig.cjs");
22
- const performanceMetrics_1 = require("./constants/performanceMetrics.cjs");
23
- const perpsConfig_1 = require("./constants/perpsConfig.cjs");
24
- const perpsErrorCodes_1 = require("./perpsErrorCodes.cjs");
25
- const AggregatedPerpsProvider_1 = require("./providers/AggregatedPerpsProvider.cjs");
26
- const HyperLiquidProvider_1 = require("./providers/HyperLiquidProvider.cjs");
27
- const MYXProvider_1 = require("./providers/MYXProvider.cjs");
28
- const AccountService_1 = require("./services/AccountService.cjs");
29
- const DataLakeService_1 = require("./services/DataLakeService.cjs");
30
- const DepositService_1 = require("./services/DepositService.cjs");
31
- const EligibilityService_1 = require("./services/EligibilityService.cjs");
32
- const FeatureFlagConfigurationService_1 = require("./services/FeatureFlagConfigurationService.cjs");
33
- const MarketDataService_1 = require("./services/MarketDataService.cjs");
34
- const RewardsIntegrationService_1 = require("./services/RewardsIntegrationService.cjs");
35
- const TradingService_1 = require("./services/TradingService.cjs");
36
- // PerpsStreamChannelKey removed: using string for channel keys (PerpsStreamManager.pauseChannel takes string)
37
- const types_1 = require("./types/index.cjs");
38
- const accountUtils_1 = require("./utils/accountUtils.cjs");
39
- const errorUtils_1 = require("./utils/errorUtils.cjs");
40
- const wait_1 = require("./utils/wait.cjs");
41
- // Re-export error codes from separate file to avoid circular dependencies
42
- var perpsErrorCodes_2 = require("./perpsErrorCodes.cjs");
43
- Object.defineProperty(exports, "PERPS_ERROR_CODES", { enumerable: true, get: function () { return perpsErrorCodes_2.PERPS_ERROR_CODES; } });
44
5
  /**
45
- * Initialization state enum for state machine tracking
6
+ * The name of the {@link PerpsController}, used to namespace the
7
+ * controller's actions and events and to namespace the controller's state data
8
+ * when composed with other controllers.
46
9
  */
47
- var InitializationState;
48
- (function (InitializationState) {
49
- InitializationState["Uninitialized"] = "uninitialized";
50
- InitializationState["Initializing"] = "initializing";
51
- InitializationState["Initialized"] = "initialized";
52
- InitializationState["Failed"] = "failed";
53
- })(InitializationState || (exports.InitializationState = InitializationState = {}));
10
+ exports.controllerName = 'PerpsController';
54
11
  /**
55
- * Get default PerpsController state
56
- *
57
- * To change the active provider, modify the `activeProvider` value below:
58
- * - 'hyperliquid': HyperLiquid provider (default, production)
59
- * - 'aggregated': Multi-provider aggregation mode
60
- * - 'myx': MYX provider (future implementation)
61
- *
62
- * @returns The default perps controller state.
63
- */
64
- const getDefaultPerpsControllerState = () => ({
65
- activeProvider: 'hyperliquid',
66
- isTestnet: false, // Default to mainnet
67
- initializationState: InitializationState.Uninitialized,
68
- initializationError: null,
69
- initializationAttempts: 0,
70
- accountState: null,
71
- perpsBalances: {},
72
- depositInProgress: false,
73
- lastDepositResult: null,
74
- withdrawInProgress: false,
75
- lastDepositTransactionId: null,
76
- lastWithdrawResult: null,
77
- withdrawalRequests: [],
78
- withdrawalProgress: {
79
- progress: 0,
80
- lastUpdated: 0,
81
- activeWithdrawalId: null,
82
- },
83
- depositRequests: [],
84
- lastError: null,
85
- lastUpdateTimestamp: 0,
86
- isEligible: false,
87
- isFirstTimeUser: {
88
- testnet: true,
89
- mainnet: true,
90
- },
91
- hasPlacedFirstOrder: {
92
- testnet: false,
93
- mainnet: false,
94
- },
95
- watchlistMarkets: {
96
- testnet: [],
97
- mainnet: [],
98
- },
99
- tradeConfigurations: {
100
- testnet: {},
101
- mainnet: {},
102
- },
103
- marketFilterPreferences: {
104
- optionId: perpsConfig_1.MARKET_SORTING_CONFIG.DefaultSortOptionId,
105
- direction: perpsConfig_1.MARKET_SORTING_CONFIG.DefaultDirection,
106
- },
107
- hip3ConfigVersion: 0,
108
- selectedPaymentToken: null,
109
- cachedMarketData: null,
110
- cachedMarketDataTimestamp: 0,
111
- cachedPositions: null,
112
- cachedOrders: null,
113
- cachedAccountState: null,
114
- cachedUserDataTimestamp: 0,
115
- cachedUserDataAddress: null,
116
- });
117
- exports.getDefaultPerpsControllerState = getDefaultPerpsControllerState;
118
- /**
119
- * State metadata for the PerpsController
12
+ * The metadata for each property in {@link PerpsControllerState}.
120
13
  */
121
- const metadata = {
122
- accountState: {
123
- includeInStateLogs: true,
124
- persist: true,
125
- includeInDebugSnapshot: false,
126
- usedInUi: true,
127
- },
128
- perpsBalances: {
129
- includeInStateLogs: true,
130
- persist: true,
131
- includeInDebugSnapshot: false,
132
- usedInUi: true,
133
- },
134
- isTestnet: {
135
- includeInStateLogs: true,
136
- persist: true,
137
- includeInDebugSnapshot: false,
138
- usedInUi: true,
139
- },
140
- activeProvider: {
141
- includeInStateLogs: true,
142
- persist: true,
143
- includeInDebugSnapshot: false,
144
- usedInUi: true,
145
- },
146
- initializationState: {
147
- includeInStateLogs: true,
148
- persist: false,
149
- includeInDebugSnapshot: false,
150
- usedInUi: true,
151
- },
152
- initializationError: {
153
- includeInStateLogs: true,
154
- persist: false,
155
- includeInDebugSnapshot: false,
156
- usedInUi: true,
157
- },
158
- initializationAttempts: {
159
- includeInStateLogs: true,
160
- persist: false,
161
- includeInDebugSnapshot: false,
162
- usedInUi: false,
163
- },
164
- depositInProgress: {
165
- includeInStateLogs: true,
166
- persist: false,
167
- includeInDebugSnapshot: false,
168
- usedInUi: true,
169
- },
170
- lastDepositTransactionId: {
171
- includeInStateLogs: true,
172
- persist: false,
173
- includeInDebugSnapshot: false,
174
- usedInUi: true,
175
- },
176
- lastDepositResult: {
177
- includeInStateLogs: true,
178
- persist: false,
179
- includeInDebugSnapshot: false,
180
- usedInUi: true,
181
- },
182
- withdrawInProgress: {
183
- includeInStateLogs: true,
184
- persist: false,
185
- includeInDebugSnapshot: false,
186
- usedInUi: true,
187
- },
188
- lastWithdrawResult: {
189
- includeInStateLogs: true,
190
- persist: false,
191
- includeInDebugSnapshot: false,
192
- usedInUi: true,
193
- },
194
- withdrawalRequests: {
195
- includeInStateLogs: true,
196
- persist: true,
197
- includeInDebugSnapshot: false,
198
- usedInUi: true,
199
- },
200
- withdrawalProgress: {
201
- includeInStateLogs: true,
202
- persist: true,
203
- includeInDebugSnapshot: false,
204
- usedInUi: true,
205
- },
206
- depositRequests: {
207
- includeInStateLogs: true,
208
- persist: true,
209
- includeInDebugSnapshot: false,
210
- usedInUi: true,
211
- },
212
- lastError: {
213
- includeInStateLogs: false,
214
- persist: false,
215
- includeInDebugSnapshot: false,
216
- usedInUi: false,
217
- },
218
- lastUpdateTimestamp: {
219
- includeInStateLogs: true,
220
- persist: false,
221
- includeInDebugSnapshot: false,
222
- usedInUi: false,
223
- },
224
- isEligible: {
225
- includeInStateLogs: true,
226
- persist: false,
227
- includeInDebugSnapshot: false,
228
- usedInUi: true,
229
- },
230
- isFirstTimeUser: {
231
- includeInStateLogs: true,
232
- persist: true,
233
- includeInDebugSnapshot: false,
234
- usedInUi: true,
235
- },
236
- hasPlacedFirstOrder: {
237
- includeInStateLogs: true,
238
- persist: true,
239
- includeInDebugSnapshot: false,
240
- usedInUi: true,
241
- },
242
- watchlistMarkets: {
243
- includeInStateLogs: true,
244
- persist: true,
245
- includeInDebugSnapshot: false,
246
- usedInUi: true,
247
- },
248
- tradeConfigurations: {
249
- includeInStateLogs: true,
250
- persist: true,
251
- includeInDebugSnapshot: false,
252
- usedInUi: true,
253
- },
254
- marketFilterPreferences: {
255
- includeInStateLogs: true,
256
- persist: true,
257
- includeInDebugSnapshot: false,
258
- usedInUi: true,
259
- },
260
- hip3ConfigVersion: {
261
- includeInStateLogs: true,
262
- persist: true,
263
- includeInDebugSnapshot: false,
264
- usedInUi: false,
265
- },
266
- selectedPaymentToken: {
267
- includeInStateLogs: false,
268
- persist: false,
269
- includeInDebugSnapshot: false,
270
- usedInUi: true,
271
- },
272
- cachedMarketData: {
273
- includeInStateLogs: false,
274
- persist: false,
275
- includeInDebugSnapshot: false,
276
- usedInUi: true,
277
- },
278
- cachedMarketDataTimestamp: {
279
- includeInStateLogs: false,
280
- persist: false,
281
- includeInDebugSnapshot: false,
282
- usedInUi: false,
283
- },
284
- cachedPositions: {
285
- includeInStateLogs: false,
286
- persist: false,
287
- includeInDebugSnapshot: false,
288
- usedInUi: true,
289
- },
290
- cachedOrders: {
291
- includeInStateLogs: false,
292
- persist: false,
293
- includeInDebugSnapshot: false,
294
- usedInUi: true,
295
- },
296
- cachedAccountState: {
297
- includeInStateLogs: false,
298
- persist: false,
299
- includeInDebugSnapshot: false,
300
- usedInUi: true,
301
- },
302
- cachedUserDataTimestamp: {
303
- includeInStateLogs: false,
304
- persist: false,
305
- includeInDebugSnapshot: false,
306
- usedInUi: false,
307
- },
308
- cachedUserDataAddress: {
309
- includeInStateLogs: false,
310
- persist: false,
311
- includeInDebugSnapshot: false,
312
- usedInUi: false,
313
- },
314
- };
315
- const MESSENGER_EXPOSED_METHODS = [
316
- 'placeOrder',
317
- 'editOrder',
318
- 'cancelOrder',
319
- 'cancelOrders',
320
- 'closePosition',
321
- 'closePositions',
322
- 'withdraw',
323
- 'getPositions',
324
- 'getOrderFills',
325
- 'getOrders',
326
- 'getOpenOrders',
327
- 'getFunding',
328
- 'getAccountState',
329
- 'getMarkets',
330
- 'refreshEligibility',
331
- 'toggleTestnet',
332
- 'disconnect',
333
- 'calculateFees',
334
- 'markTutorialCompleted',
335
- 'markFirstOrderCompleted',
336
- 'getHistoricalPortfolio',
337
- 'resetFirstTimeUserState',
338
- 'clearPendingTransactionRequests',
339
- 'saveTradeConfiguration',
340
- 'getTradeConfiguration',
341
- 'saveMarketFilterPreferences',
342
- 'getMarketFilterPreferences',
343
- 'savePendingTradeConfiguration',
344
- 'getPendingTradeConfiguration',
345
- 'clearPendingTradeConfiguration',
346
- 'getOrderBookGrouping',
347
- 'saveOrderBookGrouping',
348
- 'setSelectedPaymentToken',
349
- 'resetSelectedPaymentToken',
350
- ];
14
+ const perpsControllerMetadata = {};
351
15
  /**
352
- * PerpsController - Protocol-agnostic perpetuals trading controller
16
+ * Constructs the default {@link PerpsController} state. This allows
17
+ * consumers to provide a partial state object when initializing the controller
18
+ * and also helps in constructing complete state objects for this controller in
19
+ * tests.
353
20
  *
354
- * Provides a unified interface for perpetual futures trading across multiple protocols.
355
- * Features dual data flow architecture:
356
- * - Trading actions use Redux for persistence and optimistic updates
357
- * - Live data uses direct callbacks for maximum performance
21
+ * @returns The default {@link PerpsController} state.
358
22
  */
359
- class PerpsController extends base_controller_1.BaseController {
360
- constructor({ messenger, state = {}, clientConfig = {}, infrastructure, }) {
361
- super({
362
- name: 'PerpsController',
363
- metadata,
364
- messenger,
365
- state: { ...(0, exports.getDefaultPerpsControllerState)(), ...state },
366
- });
367
- _PerpsController_instances.add(this);
368
- this.isInitialized = false;
369
- _PerpsController_initializationPromise.set(this, null);
370
- _PerpsController_isReinitializing.set(this, false);
371
- this.blockedRegionList = {
372
- list: [],
373
- source: 'fallback',
374
- };
375
- /**
376
- * Version counter for blocked region list.
377
- * Used to prevent race conditions where stale eligibility checks
378
- * (started with fallback config) overwrite results from newer checks
379
- * (started with remote config).
380
- */
381
- _PerpsController_blockedRegionListVersion.set(this, 0);
382
- // Store HIP-3 configuration (mutable for runtime updates from remote flags)
383
- _PerpsController_hip3Enabled.set(this, void 0);
384
- _PerpsController_hip3AllowlistMarkets.set(this, void 0);
385
- _PerpsController_hip3BlocklistMarkets.set(this, void 0);
386
- _PerpsController_hip3ConfigSource.set(this, 'fallback');
387
- /**
388
- * Active provider instance for routing operations.
389
- * When activeProvider is 'hyperliquid' or 'myx': points to specific provider directly
390
- * When activeProvider is 'aggregated': points to AggregatedPerpsProvider wrapper
391
- */
392
- this.activeProviderInstance = null;
393
- /**
394
- * Cached standalone provider for pre-initialization discovery queries.
395
- * Avoids creating a new HyperLiquidProvider (and potentially leaking WebSocket
396
- * connections) on every standalone call from the preload cycle.
397
- */
398
- _PerpsController_standaloneProvider.set(this, null);
399
- _PerpsController_standaloneProviderIsTestnet.set(this, null);
400
- _PerpsController_standaloneProviderHip3Version.set(this, null);
401
- // Store options for dependency injection (allows core package to inject platform-specific services)
402
- _PerpsController_options.set(this, void 0);
403
- // Service instances (instantiated with platform dependencies)
404
- _PerpsController_tradingService.set(this, void 0);
405
- _PerpsController_marketDataService.set(this, void 0);
406
- _PerpsController_accountService.set(this, void 0);
407
- _PerpsController_eligibilityService.set(this, void 0);
408
- _PerpsController_dataLakeService.set(this, void 0);
409
- _PerpsController_depositService.set(this, void 0);
410
- _PerpsController_featureFlagConfigurationService.set(this, void 0);
411
- _PerpsController_rewardsIntegrationService.set(this, void 0);
412
- _PerpsController_preloadTimer.set(this, null);
413
- _PerpsController_isPreloading.set(this, false);
414
- _PerpsController_isPreloadingUserData.set(this, false);
415
- _PerpsController_preloadStateUnsubscribe.set(this, null);
416
- _PerpsController_accountChangeUnsubscribe.set(this, null);
417
- _PerpsController_previousIsTestnet.set(this, null);
418
- _PerpsController_previousHip3ConfigVersion.set(this, null);
419
- // Store options for dependency injection
420
- __classPrivateFieldSet(this, _PerpsController_options, {
421
- messenger,
422
- state,
423
- clientConfig,
424
- infrastructure,
425
- }, "f");
426
- // Instantiate services with platform dependencies
427
- // All cross-controller access goes through infrastructure.controllers.*
428
- __classPrivateFieldSet(this, _PerpsController_tradingService, new TradingService_1.TradingService(infrastructure), "f");
429
- __classPrivateFieldSet(this, _PerpsController_marketDataService, new MarketDataService_1.MarketDataService(infrastructure), "f");
430
- __classPrivateFieldSet(this, _PerpsController_accountService, new AccountService_1.AccountService(infrastructure), "f");
431
- __classPrivateFieldSet(this, _PerpsController_eligibilityService, new EligibilityService_1.EligibilityService(infrastructure), "f");
432
- __classPrivateFieldSet(this, _PerpsController_dataLakeService, new DataLakeService_1.DataLakeService(infrastructure), "f");
433
- __classPrivateFieldSet(this, _PerpsController_depositService, new DepositService_1.DepositService(infrastructure), "f");
434
- __classPrivateFieldSet(this, _PerpsController_featureFlagConfigurationService, new FeatureFlagConfigurationService_1.FeatureFlagConfigurationService(infrastructure), "f");
435
- __classPrivateFieldSet(this, _PerpsController_rewardsIntegrationService, new RewardsIntegrationService_1.RewardsIntegrationService(infrastructure), "f");
436
- // Set HIP-3 fallback configuration from client (will be updated if remote flags available)
437
- __classPrivateFieldSet(this, _PerpsController_hip3Enabled, clientConfig.fallbackHip3Enabled ?? false, "f");
438
- __classPrivateFieldSet(this, _PerpsController_hip3AllowlistMarkets, [
439
- ...(clientConfig.fallbackHip3AllowlistMarkets ?? []),
440
- ], "f");
441
- __classPrivateFieldSet(this, _PerpsController_hip3BlocklistMarkets, [
442
- ...(clientConfig.fallbackHip3BlocklistMarkets ?? []),
443
- ], "f");
444
- // Immediately set the fallback region list since RemoteFeatureFlagController is empty by default and takes a moment to populate.
445
- this.setBlockedRegionList(clientConfig.fallbackBlockedRegions ?? [], 'fallback');
446
- /**
447
- * Immediately read current state to catch any flags already loaded
448
- * This is necessary to avoid race conditions where the RemoteFeatureFlagController fetches flags
449
- * before the PerpsController initializes its RemoteFeatureFlagController subscription.
450
- *
451
- * We still subscribe in case the RemoteFeatureFlagController is not yet populated and updates later.
452
- */
453
- try {
454
- const currentRemoteFeatureFlagState = infrastructure.controllers.remoteFeatureFlags.getState();
455
- this.refreshEligibilityOnFeatureFlagChange(currentRemoteFeatureFlagState);
456
- }
457
- catch (error) {
458
- // If we can't read the remote feature flags at construction time, we'll rely on:
459
- // 1. The fallback blocked regions already set above
460
- // 2. The subscription to catch updates when RemoteFeatureFlagController is ready
461
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.constructor'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'constructor', {
462
- operation: 'readRemoteFeatureFlags',
463
- }));
464
- }
465
- // Subscribe for the full controller lifetime — intentionally not stored;
466
- // geo-blocking and HIP-3 flag propagation must remain active across
467
- // disconnect → reconnect cycles and must never be torn down.
468
- infrastructure.controllers.remoteFeatureFlags.onStateChange(this.refreshEligibilityOnFeatureFlagChange.bind(this));
469
- this.providers = new Map();
470
- // Migrate old persisted data without accountAddress
471
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_migrateRequestsIfNeeded).call(this);
472
- this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
473
- }
474
- /**
475
- * Test-observable accessor for whether a standalone provider is cached.
476
- *
477
- * @returns True if a standalone provider instance exists.
478
- */
479
- hasStandaloneProvider() {
480
- return __classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f") !== null;
481
- }
482
- setBlockedRegionList(list, source) {
483
- __classPrivateFieldGet(this, _PerpsController_featureFlagConfigurationService, "f").setBlockedRegions({
484
- list,
485
- source,
486
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'setBlockedRegionList', {
487
- getBlockedRegionList: () => this.blockedRegionList,
488
- setBlockedRegionList: (newList, newSource) => {
489
- this.blockedRegionList = { list: newList, source: newSource };
490
- __classPrivateFieldSet(this, _PerpsController_blockedRegionListVersion, __classPrivateFieldGet(this, _PerpsController_blockedRegionListVersion, "f") + 1, "f");
491
- },
492
- refreshEligibility: () => this.refreshEligibility(),
493
- }),
494
- });
495
- }
496
- /**
497
- * Respond to RemoteFeatureFlagController state changes
498
- * Refreshes user eligibility based on geo-blocked regions defined in remote feature flag.
499
- * Uses fallback configuration when remote feature flag is undefined.
500
- * Note: Initial eligibility is set in the constructor if fallback regions are provided.
501
- *
502
- * @param remoteFeatureFlagControllerState - State from RemoteFeatureFlagController.
503
- */
504
- refreshEligibilityOnFeatureFlagChange(remoteFeatureFlagControllerState) {
505
- __classPrivateFieldGet(this, _PerpsController_featureFlagConfigurationService, "f").refreshEligibility({
506
- remoteFeatureFlagControllerState,
507
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'refreshEligibilityOnFeatureFlagChange', {
508
- getBlockedRegionList: () => this.blockedRegionList,
509
- setBlockedRegionList: (list, source) => {
510
- this.blockedRegionList = { list, source };
511
- __classPrivateFieldSet(this, _PerpsController_blockedRegionListVersion, __classPrivateFieldGet(this, _PerpsController_blockedRegionListVersion, "f") + 1, "f");
512
- },
513
- refreshEligibility: () => this.refreshEligibility(),
514
- getHip3Config: () => ({
515
- enabled: __classPrivateFieldGet(this, _PerpsController_hip3Enabled, "f"),
516
- allowlistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3AllowlistMarkets, "f"),
517
- blocklistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3BlocklistMarkets, "f"),
518
- source: __classPrivateFieldGet(this, _PerpsController_hip3ConfigSource, "f"),
519
- }),
520
- setHip3Config: (config) => {
521
- if (config.enabled !== undefined) {
522
- __classPrivateFieldSet(this, _PerpsController_hip3Enabled, config.enabled, "f");
523
- }
524
- if (config.allowlistMarkets !== undefined) {
525
- __classPrivateFieldSet(this, _PerpsController_hip3AllowlistMarkets, [...config.allowlistMarkets], "f");
526
- }
527
- if (config.blocklistMarkets !== undefined) {
528
- __classPrivateFieldSet(this, _PerpsController_hip3BlocklistMarkets, [...config.blocklistMarkets], "f");
529
- }
530
- if (config.source !== undefined) {
531
- __classPrivateFieldSet(this, _PerpsController_hip3ConfigSource, config.source, "f");
532
- }
533
- },
534
- incrementHip3ConfigVersion: () => {
535
- const newVersion = (this.state.hip3ConfigVersion || 0) + 1;
536
- this.update((state) => {
537
- state.hip3ConfigVersion = newVersion;
538
- });
539
- return newVersion;
540
- },
541
- }),
542
- });
543
- }
544
- /**
545
- * Initialize the PerpsController providers
546
- * Must be called before using any other methods
547
- * Prevents double initialization with promise caching
548
- *
549
- * @returns A promise that resolves when the operation completes.
550
- */
551
- async init() {
552
- if (this.isInitialized) {
553
- return undefined;
554
- }
555
- if (__classPrivateFieldGet(this, _PerpsController_initializationPromise, "f")) {
556
- return __classPrivateFieldGet(this, _PerpsController_initializationPromise, "f");
557
- }
558
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performInitialization).call(this), "f");
559
- return __classPrivateFieldGet(this, _PerpsController_initializationPromise, "f");
560
- }
561
- /**
562
- * Get the currently active provider.
563
- * In aggregated mode, returns AggregatedPerpsProvider which routes to underlying providers.
564
- * In single provider mode, returns HyperLiquidProvider directly.
565
- *
566
- * @returns The active provider (aggregated wrapper or direct provider based on mode)
567
- * @throws Error if provider is not initialized or reinitializing
568
- */
569
- getActiveProvider() {
570
- // Check if we're in the middle of reinitializing
571
- if (this.isCurrentlyReinitializing()) {
572
- this.update((state) => {
573
- state.lastError = perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_REINITIALIZING;
574
- state.lastUpdateTimestamp = Date.now();
575
- });
576
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_REINITIALIZING);
577
- }
578
- // Check if not initialized
579
- if (this.state.initializationState !== InitializationState.Initialized ||
580
- !this.isInitialized) {
581
- const errorMessage = this.state.initializationState === InitializationState.Failed
582
- ? `${perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_NOT_INITIALIZED}: ${this.state.initializationError ?? 'Initialization failed'}`
583
- : perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_NOT_INITIALIZED;
584
- this.update((state) => {
585
- state.lastError = errorMessage;
586
- state.lastUpdateTimestamp = Date.now();
587
- });
588
- throw new Error(errorMessage);
589
- }
590
- // Return the active provider instance (set during initialization based on providerMode)
591
- if (!this.activeProviderInstance) {
592
- this.update((state) => {
593
- state.lastError = perpsErrorCodes_1.PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE;
594
- state.lastUpdateTimestamp = Date.now();
595
- });
596
- throw new Error(perpsErrorCodes_1.PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
597
- }
598
- return this.activeProviderInstance;
599
- }
600
- /**
601
- * Get the currently active provider, returning null if not available
602
- * Use this method when the caller can gracefully handle a missing provider
603
- * (e.g., UI components during initialization or reconnection)
604
- *
605
- * @returns The active provider, or null if not initialized/reinitializing
606
- */
607
- getActiveProviderOrNull() {
608
- // Return null during reinitialization
609
- if (this.isCurrentlyReinitializing()) {
610
- return null;
611
- }
612
- // Return null if not initialized
613
- if (this.state.initializationState !== InitializationState.Initialized ||
614
- !this.isInitialized) {
615
- return null;
616
- }
617
- // Return the active provider instance or null if not found
618
- return this.activeProviderInstance ?? null;
619
- }
620
- /**
621
- * Place a new order
622
- * Thin delegation to TradingService
623
- *
624
- * @param params - The operation parameters.
625
- * @returns The order result with order ID and status.
626
- */
627
- async placeOrder(params) {
628
- const provider = this.getActiveProvider();
629
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
630
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").placeOrder({
631
- provider,
632
- params,
633
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'placeOrder', {
634
- saveTradeConfiguration: (symbol, leverage) => this.saveTradeConfiguration(symbol, leverage),
635
- }),
636
- reportOrderToDataLake: (dataLakeParams) => this.reportOrderToDataLake(dataLakeParams),
637
- });
638
- }
639
- /**
640
- * Edit an existing order
641
- * Thin delegation to TradingService
642
- *
643
- * @param params - The operation parameters.
644
- * @returns The updated order result with order ID and status.
645
- */
646
- async editOrder(params) {
647
- const provider = this.getActiveProvider();
648
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
649
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").editOrder({
650
- provider,
651
- params,
652
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'editOrder'),
653
- });
654
- }
655
- /**
656
- * Cancel an existing order
657
- *
658
- * @param params - The operation parameters.
659
- * @returns The cancellation result with status.
660
- */
661
- async cancelOrder(params) {
662
- const provider = this.getActiveProvider();
663
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").cancelOrder({
664
- provider,
665
- params,
666
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'cancelOrder'),
667
- });
668
- }
669
- /**
670
- * Cancel multiple orders in parallel
671
- * Batch version of cancelOrder() that cancels multiple orders simultaneously
672
- *
673
- * @param params - The operation parameters.
674
- * @returns The batch cancellation results for each order.
675
- */
676
- async cancelOrders(params) {
677
- const provider = this.getActiveProvider();
678
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").cancelOrders({
679
- provider,
680
- params,
681
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'cancelOrders', {
682
- getOpenOrders: () => this.getOpenOrders(),
683
- }),
684
- withStreamPause: (operation, channels) => __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_withStreamPause).call(this, operation, channels),
685
- });
686
- }
687
- /**
688
- * Close a position (partial or full)
689
- * Thin delegation to TradingService
690
- *
691
- * @param params - The operation parameters.
692
- * @returns The order result from the close position request.
693
- */
694
- async closePosition(params) {
695
- const provider = this.getActiveProvider();
696
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
697
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").closePosition({
698
- provider,
699
- params,
700
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'closePosition', {
701
- getPositions: () => this.getPositions(),
702
- }),
703
- reportOrderToDataLake: (dataLakeParams) => this.reportOrderToDataLake(dataLakeParams),
704
- });
705
- }
706
- /**
707
- * Close multiple positions in parallel
708
- * Batch version of closePosition() that closes multiple positions simultaneously
709
- *
710
- * @param params - The operation parameters.
711
- * @returns The batch close results for each position.
712
- */
713
- async closePositions(params) {
714
- const provider = this.getActiveProvider();
715
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
716
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").closePositions({
717
- provider,
718
- params,
719
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'closePositions', {
720
- getPositions: () => this.getPositions(),
721
- }),
722
- });
723
- }
724
- /**
725
- * Update TP/SL for an existing position
726
- *
727
- * @param params - The operation parameters.
728
- * @returns The order result from the TP/SL update.
729
- */
730
- async updatePositionTPSL(params) {
731
- const provider = this.getActiveProvider();
732
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
733
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").updatePositionTPSL({
734
- provider,
735
- params,
736
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'updatePositionTPSL'),
737
- });
738
- }
739
- /**
740
- * Update margin for an existing position (add or remove)
741
- *
742
- * @param params - The operation parameters.
743
- * @returns The margin update result.
744
- */
745
- async updateMargin(params) {
746
- const provider = this.getActiveProvider();
747
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
748
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").updateMargin({
749
- provider,
750
- symbol: params.symbol,
751
- amount: params.amount,
752
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'updateMargin'),
753
- });
754
- }
755
- /**
756
- * Flip position (reverse direction while keeping size and leverage)
757
- *
758
- * @param params - The operation parameters.
759
- * @returns The order result from the position flip.
760
- */
761
- async flipPosition(params) {
762
- const provider = this.getActiveProvider();
763
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_ensureTradingServiceDeps).call(this);
764
- return __classPrivateFieldGet(this, _PerpsController_tradingService, "f").flipPosition({
765
- provider,
766
- position: params.position,
767
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'flipPosition'),
768
- });
769
- }
770
- /**
771
- * Simplified deposit method that prepares transaction for confirmation screen
772
- * No complex state tracking - just sets a loading flag
773
- *
774
- * @param params - Parameters for the deposit flow
775
- * @param params.amount - Optional deposit amount
776
- * @param params.placeOrder - If true, uses addTransaction instead of submit to avoid navigation
777
- * @returns An object containing a promise that resolves to the transaction hash.
778
- */
779
- async depositWithConfirmation(params = {}) {
780
- const { amount, placeOrder } = params;
781
- let currentDepositId;
782
- try {
783
- // Clear any stale results when starting a new deposit flow
784
- // Don't set depositInProgress yet - wait until user confirms
785
- // Prepare deposit transaction using DepositService
786
- const provider = this.getActiveProvider();
787
- const { transaction, assetChainId, currentDepositId: depositId, } = await __classPrivateFieldGet(this, _PerpsController_depositService, "f").prepareTransaction({ provider });
788
- currentDepositId = depositId;
789
- // Get current account address via messenger (outside of update() for proper typing)
790
- const evmAccount = (0, accountUtils_1.getSelectedEvmAccount)(__classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.accountTree);
791
- const accountAddress = evmAccount?.address ?? 'unknown';
792
- this.update((state) => {
793
- state.lastDepositResult = null;
794
- // Add deposit request to tracking
795
- const depositRequest = {
796
- id: currentDepositId ?? (0, uuid_1.v4)(),
797
- timestamp: Date.now(),
798
- amount: amount ?? '0', // Use provided amount or default to '0'
799
- asset: hyperLiquidConfig_1.USDC_SYMBOL,
800
- accountAddress, // Track which account initiated deposit
801
- success: false, // Will be updated when transaction completes
802
- txHash: undefined,
803
- status: 'pending',
804
- source: undefined,
805
- transactionId: undefined, // Will be set to depositId when available
806
- };
807
- state.depositRequests.unshift(depositRequest); // Add to beginning of array
808
- });
809
- const networkClientId = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_findNetworkClientIdForChain).call(this, assetChainId);
810
- if (!networkClientId) {
811
- throw new Error(`No network client found for chain ${assetChainId}. Please add the network first.`);
812
- }
813
- let result;
814
- let transactionMeta;
815
- let depositOrderResult = null;
816
- const defaultTransactionOptions = {
817
- networkClientId,
818
- origin: controller_utils_1.ORIGIN_METAMASK,
819
- skipInitialGasEstimate: true,
820
- };
821
- if (placeOrder) {
822
- // Use addTransaction to create transaction without navigating to confirmation screen
823
- const addResult = await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_submitTransaction).call(this, transaction, {
824
- ...defaultTransactionOptions,
825
- type: 'perpsDepositAndOrder',
826
- });
827
- transactionMeta = addResult.transactionMeta;
828
- // Return transaction ID immediately (fire-and-forget for caller)
829
- result = Promise.resolve(transactionMeta.id);
830
- // Track deposit request lifecycle via the real transaction result
831
- depositOrderResult = addResult.result;
832
- }
833
- else {
834
- // submit shows the confirmation screen and returns a promise
835
- // The promise will resolve when transaction completes or reject if cancelled/failed
836
- const submitResult = await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_submitTransaction).call(this, transaction, {
837
- ...defaultTransactionOptions,
838
- type: 'perpsDeposit',
839
- });
840
- result = submitResult.result;
841
- transactionMeta = submitResult.transactionMeta;
842
- }
843
- // Store the transaction ID and try to get amount from transaction
844
- this.update((state) => {
845
- state.lastDepositTransactionId = transactionMeta.id;
846
- });
847
- // Track the transaction lifecycle only when using submit (deposit-only flow)
848
- if (!placeOrder) {
849
- // At this point, the confirmation modal is shown to the user
850
- // The result promise will resolve/reject based on user action and transaction outcome
851
- // Track the transaction lifecycle
852
- // The result promise will resolve/reject based on user action and transaction outcome
853
- // Note: We intentionally don't set depositInProgress immediately to avoid
854
- // showing toasts before the user confirms the transaction
855
- // TODO: @abretonc7s Find a better way to trigger our custom toast notification then having to toggle the state
856
- // How to replace the system notifications?
857
- result
858
- .then((actualTxHash) => {
859
- // Transaction was successfully completed
860
- // Set depositInProgress to true temporarily to show success
861
- this.update((state) => {
862
- state.depositInProgress = true;
863
- state.lastDepositResult = {
864
- success: true,
865
- txHash: actualTxHash,
866
- amount: amount ?? '0',
867
- asset: hyperLiquidConfig_1.USDC_SYMBOL, // Default asset for deposits
868
- timestamp: Date.now(),
869
- error: '',
870
- };
871
- // Update the deposit request by request ID to avoid race conditions
872
- if (state.depositRequests.length > 0) {
873
- const requestToUpdate = state.depositRequests.find((req) => req.id === currentDepositId);
874
- if (requestToUpdate) {
875
- // For deposits, we have a txHash immediately, so mark as completed
876
- // (the transaction hash means the deposit was successful)
877
- requestToUpdate.status = 'completed';
878
- requestToUpdate.success = true;
879
- requestToUpdate.txHash = actualTxHash;
880
- }
881
- }
882
- });
883
- // Clear depositInProgress after a short delay
884
- setTimeout(() => {
885
- this.update((state) => {
886
- state.depositInProgress = false;
887
- state.lastDepositTransactionId = null;
888
- });
889
- }, 100);
890
- return undefined;
891
- })
892
- .catch((error) => {
893
- // Check if user denied/cancelled the transaction
894
- const errorMessage = (0, errorUtils_1.ensureError)(error, 'PerpsController.initiateDeposit').message;
895
- const userCancelled = errorMessage.includes('User denied') ||
896
- errorMessage.includes('User rejected') ||
897
- errorMessage.includes('User cancelled') ||
898
- errorMessage.includes('User canceled');
899
- if (userCancelled) {
900
- // User cancelled - clear any state, no toast
901
- this.update((state) => {
902
- state.depositInProgress = false;
903
- state.lastDepositTransactionId = null;
904
- // Don't set lastDepositResult - no toast needed
905
- });
906
- }
907
- else {
908
- // Transaction failed after confirmation - show error toast
909
- this.update((state) => {
910
- state.depositInProgress = false;
911
- state.lastDepositTransactionId = null;
912
- state.lastDepositResult = {
913
- success: false,
914
- error: errorMessage,
915
- amount: amount ?? '0',
916
- asset: hyperLiquidConfig_1.USDC_SYMBOL, // Default asset for deposits
917
- timestamp: Date.now(),
918
- txHash: '',
919
- };
920
- // Update the deposit request by request ID to avoid race conditions
921
- if (state.depositRequests.length > 0) {
922
- const requestToUpdate = state.depositRequests.find((req) => req.id === currentDepositId);
923
- if (requestToUpdate) {
924
- requestToUpdate.status = 'failed';
925
- requestToUpdate.success = false;
926
- }
927
- }
928
- });
929
- }
930
- });
931
- }
932
- else if (depositOrderResult) {
933
- // Track deposit request lifecycle for deposit+order flow
934
- depositOrderResult
935
- .then((actualTxHash) => {
936
- this.update((state) => {
937
- const requestToUpdate = state.depositRequests.find((req) => req.id === currentDepositId);
938
- if (requestToUpdate) {
939
- requestToUpdate.status = 'completed';
940
- requestToUpdate.success = true;
941
- requestToUpdate.txHash = actualTxHash;
942
- }
943
- });
944
- return undefined;
945
- })
946
- .catch((error) => {
947
- const errorMessage = (0, errorUtils_1.ensureError)(error, 'PerpsController.depositWithOrder').message;
948
- const isCancellation = errorMessage.includes('User denied') ||
949
- errorMessage.includes('User rejected') ||
950
- errorMessage.includes('cancelled');
951
- this.update((state) => {
952
- const requestToUpdate = state.depositRequests.find((req) => req.id === currentDepositId);
953
- if (requestToUpdate) {
954
- requestToUpdate.status = (isCancellation ? 'cancelled' : 'failed');
955
- requestToUpdate.success = false;
956
- }
957
- });
958
- });
959
- }
960
- return {
961
- result,
962
- };
963
- }
964
- catch (error) {
965
- // Check if user denied/cancelled the transaction
966
- const errorMessage = (0, errorUtils_1.ensureError)(error, 'PerpsController.initiateDeposit').message;
967
- const userCancelled = errorMessage.includes('User denied') ||
968
- errorMessage.includes('User rejected') ||
969
- errorMessage.includes('User cancelled') ||
970
- errorMessage.includes('User canceled');
971
- if (!userCancelled) {
972
- // Only track actual errors, not user cancellations
973
- this.update((state) => {
974
- state.lastDepositTransactionId = null;
975
- // Note: lastDepositResult is already set in the catch block above
976
- // Mark deposit request as failed if one was created
977
- if (currentDepositId) {
978
- const request = state.depositRequests.find((req) => req.id === currentDepositId);
979
- if (request) {
980
- request.status = 'failed';
981
- request.success = false;
982
- }
983
- }
984
- });
985
- }
986
- throw error;
987
- }
988
- }
989
- /**
990
- * Same as depositWithConfirmation - prepares transaction for confirmation screen.
991
- *
992
- * @returns A promise that resolves to the string result.
993
- */
994
- async depositWithOrder() {
995
- return this.depositWithConfirmation({ placeOrder: true });
996
- }
997
- /**
998
- * Clear the last deposit result after it has been shown to the user
999
- */
1000
- clearDepositResult() {
1001
- this.update((state) => {
1002
- state.lastDepositResult = null;
1003
- });
1004
- }
1005
- clearWithdrawResult() {
1006
- this.update((state) => {
1007
- state.lastWithdrawResult = null;
1008
- });
1009
- }
1010
- /**
1011
- * Update withdrawal request status when it completes
1012
- * This is called when a withdrawal is matched with a completed withdrawal from the API
1013
- *
1014
- * @param withdrawalId - The withdrawal transaction ID.
1015
- * @param status - The current status.
1016
- * @param txHash - The transaction hash.
1017
- */
1018
- updateWithdrawalStatus(withdrawalId, status, txHash) {
1019
- let withdrawalAmount;
1020
- this.update((state) => {
1021
- const withdrawalIndex = state.withdrawalRequests.findIndex((request) => request.id === withdrawalId);
1022
- if (withdrawalIndex >= 0) {
1023
- const request = state.withdrawalRequests[withdrawalIndex];
1024
- withdrawalAmount = request.amount;
1025
- const originalStatus = request.status;
1026
- request.status = status;
1027
- request.success = status === 'completed';
1028
- if (txHash) {
1029
- request.txHash = txHash;
1030
- }
1031
- // Clear withdrawal progress when withdrawal completes
1032
- if (status === 'completed' || status === 'failed') {
1033
- state.withdrawalProgress = {
1034
- progress: 0,
1035
- lastUpdated: Date.now(),
1036
- activeWithdrawalId: null,
1037
- };
1038
- }
1039
- // Track withdrawal transaction completed/failed (confirmed via HyperLiquid API)
1040
- if (withdrawalAmount !== undefined && originalStatus !== status) {
1041
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getMetrics).call(this).trackPerpsEvent(types_1.PerpsAnalyticsEvent.WithdrawalTransaction, {
1042
- [eventNames_1.PERPS_EVENT_PROPERTY.STATUS]: status === 'completed'
1043
- ? eventNames_1.PERPS_EVENT_VALUE.STATUS.COMPLETED
1044
- : eventNames_1.PERPS_EVENT_VALUE.STATUS.FAILED,
1045
- [eventNames_1.PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: Number.parseFloat(withdrawalAmount),
1046
- });
1047
- }
1048
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Updated withdrawal status', {
1049
- withdrawalId,
1050
- status,
1051
- txHash,
1052
- });
1053
- }
1054
- });
1055
- }
1056
- /**
1057
- * Update withdrawal progress (persistent across navigation)
1058
- *
1059
- * @param progress - The progress indicator.
1060
- * @param activeWithdrawalId - The active withdrawal ID.
1061
- */
1062
- updateWithdrawalProgress(progress, activeWithdrawalId = null) {
1063
- this.update((state) => {
1064
- state.withdrawalProgress = {
1065
- progress,
1066
- lastUpdated: Date.now(),
1067
- activeWithdrawalId,
1068
- };
1069
- });
1070
- }
1071
- /**
1072
- * Get current withdrawal progress
1073
- *
1074
- * @returns The withdrawal progress, last update timestamp, and active withdrawal ID.
1075
- */
1076
- getWithdrawalProgress() {
1077
- return this.state.withdrawalProgress;
1078
- }
1079
- /**
1080
- * Withdraw funds from trading account
1081
- *
1082
- * The withdrawal process varies by provider and may involve:
1083
- * - Direct on-chain transfers
1084
- * - Bridge operations
1085
- * - Multi-step validation processes
1086
- *
1087
- * Check the specific provider documentation for detailed withdrawal flows.
1088
- *
1089
- * @param params Withdrawal parameters
1090
- * @returns WithdrawResult with withdrawal ID and tracking info
1091
- */
1092
- async withdraw(params) {
1093
- const provider = this.getActiveProvider();
1094
- return __classPrivateFieldGet(this, _PerpsController_accountService, "f").withdraw({
1095
- provider,
1096
- params,
1097
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'withdraw'),
1098
- refreshAccountState: async () => {
1099
- await this.getAccountState({ source: 'post_withdrawal' });
1100
- },
1101
- });
1102
- }
1103
- /**
1104
- * Get current positions
1105
- * Thin delegation to MarketDataService
1106
- *
1107
- * For standalone mode, bypasses getActiveProvider() to allow position queries
1108
- * without full perps initialization (e.g., for showing positions on token details page)
1109
- *
1110
- * @param params - The operation parameters.
1111
- * @returns Array of open positions for the active provider.
1112
- */
1113
- async getPositions(params) {
1114
- // For standalone mode, access provider directly without initialization check
1115
- // This allows discovery use cases (checking if user has positions) without full perps setup
1116
- if (params?.standalone && params.userAddress) {
1117
- // Use activeProviderInstance if available (respects provider abstraction)
1118
- // Fallback to cached standalone provider for pre-initialization discovery
1119
- // TODO: When adding new providers (MYX), consider a provider factory pattern
1120
- const provider = this.activeProviderInstance ?? __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getOrCreateStandaloneProvider).call(this);
1121
- return provider.getPositions(params);
1122
- }
1123
- const provider = this.getActiveProvider();
1124
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getPositions({
1125
- provider,
1126
- params,
1127
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getPositions'),
1128
- });
1129
- }
1130
- /**
1131
- * Get historical user fills (trade executions)
1132
- * Thin delegation to MarketDataService
1133
- *
1134
- * @param params - The operation parameters.
1135
- * @returns Array of historical trade executions (fills).
1136
- */
1137
- async getOrderFills(params) {
1138
- const provider = this.getActiveProvider();
1139
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getOrderFills({
1140
- provider,
1141
- params,
1142
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getOrderFills'),
1143
- });
1144
- }
1145
- /**
1146
- * Get historical user orders (order lifecycle)
1147
- * Thin delegation to MarketDataService
1148
- *
1149
- * @param params - The operation parameters.
1150
- * @returns Array of historical orders.
1151
- */
1152
- async getOrders(params) {
1153
- const provider = this.getActiveProvider();
1154
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getOrders({
1155
- provider,
1156
- params,
1157
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getOrders'),
1158
- });
1159
- }
1160
- /**
1161
- * Get currently open orders (real-time status)
1162
- * Thin delegation to MarketDataService
1163
- *
1164
- * For standalone mode, bypasses getActiveProvider() to allow open order queries
1165
- * without full perps initialization (e.g., for background preloading)
1166
- *
1167
- * @param params - The operation parameters.
1168
- * @returns A promise that resolves to the result.
1169
- */
1170
- async getOpenOrders(params) {
1171
- // For standalone mode, access provider directly without initialization check
1172
- if (params?.standalone && params.userAddress) {
1173
- const provider = this.activeProviderInstance ?? __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getOrCreateStandaloneProvider).call(this);
1174
- return provider.getOpenOrders(params);
1175
- }
1176
- const provider = this.getActiveProvider();
1177
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getOpenOrders({
1178
- provider,
1179
- params,
1180
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getOpenOrders'),
1181
- });
1182
- }
1183
- /**
1184
- * Get historical user funding history (funding payments)
1185
- * Thin delegation to MarketDataService
1186
- *
1187
- * @param params - The operation parameters.
1188
- * @returns Array of historical funding payments.
1189
- */
1190
- async getFunding(params) {
1191
- const provider = this.getActiveProvider();
1192
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getFunding({
1193
- provider,
1194
- params,
1195
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getFunding'),
1196
- });
1197
- }
1198
- /**
1199
- * Get account state (balances, etc.)
1200
- * Thin delegation to MarketDataService
1201
- *
1202
- * For standalone mode, bypasses getActiveProvider() to allow account state queries
1203
- * without full perps initialization (e.g., for checking if user has perps funds)
1204
- *
1205
- * @param params - The operation parameters.
1206
- * @returns A promise that resolves to the result.
1207
- */
1208
- async getAccountState(params) {
1209
- // For standalone mode, access provider directly without initialization check
1210
- // This allows discovery use cases (checking if user has perps funds) without full perps setup
1211
- if (params?.standalone && params.userAddress) {
1212
- // Use activeProviderInstance if available (respects provider abstraction)
1213
- // Fallback to cached standalone provider for pre-initialization discovery
1214
- const provider = this.activeProviderInstance ?? __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getOrCreateStandaloneProvider).call(this);
1215
- return provider.getAccountState(params);
1216
- }
1217
- const provider = this.getActiveProvider();
1218
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getAccountState({
1219
- provider,
1220
- params,
1221
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getAccountState'),
1222
- });
1223
- }
1224
- /**
1225
- * Get historical portfolio data
1226
- * Thin delegation to MarketDataService
1227
- *
1228
- * @param params - The operation parameters.
1229
- * @returns The historical portfolio data points.
1230
- */
1231
- async getHistoricalPortfolio(params) {
1232
- const provider = this.getActiveProvider();
1233
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getHistoricalPortfolio({
1234
- provider,
1235
- params,
1236
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getHistoricalPortfolio'),
1237
- });
1238
- }
1239
- /**
1240
- * Get available markets with optional filtering
1241
- * Thin delegation to MarketDataService
1242
- *
1243
- * For standalone mode, bypasses getActiveProvider() to allow market discovery
1244
- * without full perps initialization (e.g., for discovery banners on spot screens)
1245
- *
1246
- * @param params - The operation parameters.
1247
- * @returns Array of available markets matching the filter criteria.
1248
- */
1249
- async getMarkets(params) {
1250
- // For standalone mode, access provider directly without initialization check
1251
- // This allows discovery use cases (checking if market exists) without full perps setup
1252
- if (params?.standalone) {
1253
- // Use activeProviderInstance if available (respects provider abstraction)
1254
- // Fallback to cached standalone provider for pre-initialization discovery
1255
- const provider = this.activeProviderInstance ?? __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getOrCreateStandaloneProvider).call(this);
1256
- return provider.getMarkets(params);
1257
- }
1258
- const provider = this.getActiveProvider();
1259
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getMarkets({
1260
- provider,
1261
- params,
1262
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getMarkets'),
1263
- });
1264
- }
1265
- /**
1266
- * Get market data with prices (includes price, volume, 24h change)
1267
- *
1268
- * For standalone mode, bypasses getActiveProvider() to allow market data queries
1269
- * without full perps initialization (e.g., for background preloading on app start)
1270
- *
1271
- * @param params - The operation parameters.
1272
- * @param params.standalone - Whether to use standalone mode.
1273
- * @returns A promise that resolves to the market data.
1274
- */
1275
- async getMarketDataWithPrices(params) {
1276
- if (params?.standalone) {
1277
- // Use activeProviderInstance if available (respects provider abstraction)
1278
- // Fallback to cached standalone provider for pre-initialization discovery
1279
- const provider = this.activeProviderInstance ?? __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getOrCreateStandaloneProvider).call(this);
1280
- return provider.getMarketDataWithPrices();
1281
- }
1282
- const provider = this.getActiveProvider();
1283
- return provider.getMarketDataWithPrices();
1284
- }
1285
- /**
1286
- * Start background market data preloading.
1287
- * Fetches market data immediately and refreshes every 5 minutes.
1288
- * Watches for isTestnet and hip3ConfigVersion changes to re-preload.
1289
- */
1290
- startMarketDataPreload() {
1291
- if (__classPrivateFieldGet(this, _PerpsController_preloadTimer, "f")) {
1292
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Preload already started, skipping');
1293
- return;
1294
- }
1295
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Starting market data preload');
1296
- // Track current values for change detection
1297
- __classPrivateFieldSet(this, _PerpsController_previousIsTestnet, this.state.isTestnet, "f");
1298
- __classPrivateFieldSet(this, _PerpsController_previousHip3ConfigVersion, this.state.hip3ConfigVersion, "f");
1299
- // Immediate preload
1300
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performMarketDataPreload).call(this).catch(() => {
1301
- /* fire-and-forget */
1302
- });
1303
- // Periodic refresh
1304
- __classPrivateFieldSet(this, _PerpsController_preloadTimer, setInterval(() => {
1305
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performMarketDataPreload).call(this).catch(() => {
1306
- /* fire-and-forget */
1307
- });
1308
- }, __classPrivateFieldGet(_a, _a, "f", _PerpsController_preloadRefreshMs)), "f");
1309
- // Watch for isTestnet / hip3ConfigVersion / cachedUserDataAddress changes
1310
- const handler = (_state, patches) => {
1311
- // Early-return when no watched field changed (skips ~46 unrelated updates)
1312
- const hasRelevantChange = patches.some((patch) => typeof patch.path[0] === 'string' &&
1313
- __classPrivateFieldGet(_a, _a, "f", _PerpsController_preloadWatchedPaths).has(patch.path[0]));
1314
- if (!hasRelevantChange) {
1315
- return;
1316
- }
1317
- const currentIsTestnet = this.state.isTestnet;
1318
- const currentHip3Version = this.state.hip3ConfigVersion;
1319
- const testnetChanged = currentIsTestnet !== __classPrivateFieldGet(this, _PerpsController_previousIsTestnet, "f");
1320
- const hip3Changed = currentHip3Version !== __classPrivateFieldGet(this, _PerpsController_previousHip3ConfigVersion, "f");
1321
- if (testnetChanged || hip3Changed) {
1322
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Network/config changed, re-preloading', {
1323
- testnetChanged,
1324
- hip3Changed,
1325
- isTestnet: currentIsTestnet,
1326
- hip3ConfigVersion: currentHip3Version,
1327
- });
1328
- __classPrivateFieldSet(this, _PerpsController_previousIsTestnet, currentIsTestnet, "f");
1329
- __classPrivateFieldSet(this, _PerpsController_previousHip3ConfigVersion, currentHip3Version, "f");
1330
- // Clear stale cache (market + user data)
1331
- this.update((state) => {
1332
- state.cachedMarketData = null;
1333
- state.cachedMarketDataTimestamp = 0;
1334
- state.cachedPositions = null;
1335
- state.cachedOrders = null;
1336
- state.cachedAccountState = null;
1337
- state.cachedUserDataTimestamp = 0;
1338
- state.cachedUserDataAddress = null;
1339
- });
1340
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performMarketDataPreload).call(this).catch(() => {
1341
- /* fire-and-forget */
1342
- });
1343
- }
1344
- };
1345
- this.messenger.subscribe('PerpsController:stateChange', handler);
1346
- __classPrivateFieldSet(this, _PerpsController_preloadStateUnsubscribe, () => {
1347
- this.messenger.unsubscribe('PerpsController:stateChange', handler);
1348
- }, "f");
1349
- // Watch for account changes via AccountTreeController
1350
- const accountChangeHandler = () => {
1351
- const evmAccount = (0, accountUtils_1.getSelectedEvmAccount)(__classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.accountTree);
1352
- const currentAddress = evmAccount?.address ?? null;
1353
- // If there's cached data from a different account (or no EVM account now), clear it
1354
- if (this.state.cachedUserDataAddress !== null &&
1355
- currentAddress !== this.state.cachedUserDataAddress) {
1356
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Account changed, clearing user data cache');
1357
- this.update((state) => {
1358
- state.cachedPositions = null;
1359
- state.cachedOrders = null;
1360
- state.cachedAccountState = null;
1361
- state.cachedUserDataTimestamp = 0;
1362
- state.cachedUserDataAddress = null;
1363
- });
1364
- // Only preload if the new account is an EVM account
1365
- if (currentAddress) {
1366
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performUserDataPreload).call(this).catch(() => {
1367
- /* fire-and-forget */
1368
- });
1369
- }
1370
- }
1371
- };
1372
- __classPrivateFieldSet(this, _PerpsController_accountChangeUnsubscribe, __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.accountTree.onSelectedAccountGroupChange(accountChangeHandler), "f");
1373
- }
1374
- /**
1375
- * Stop background market data preloading.
1376
- */
1377
- stopMarketDataPreload() {
1378
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Stopping market data preload');
1379
- if (__classPrivateFieldGet(this, _PerpsController_preloadTimer, "f")) {
1380
- clearInterval(__classPrivateFieldGet(this, _PerpsController_preloadTimer, "f"));
1381
- __classPrivateFieldSet(this, _PerpsController_preloadTimer, null, "f");
1382
- }
1383
- if (__classPrivateFieldGet(this, _PerpsController_preloadStateUnsubscribe, "f")) {
1384
- __classPrivateFieldGet(this, _PerpsController_preloadStateUnsubscribe, "f").call(this);
1385
- __classPrivateFieldSet(this, _PerpsController_preloadStateUnsubscribe, null, "f");
1386
- }
1387
- if (__classPrivateFieldGet(this, _PerpsController_accountChangeUnsubscribe, "f")) {
1388
- __classPrivateFieldGet(this, _PerpsController_accountChangeUnsubscribe, "f").call(this);
1389
- __classPrivateFieldSet(this, _PerpsController_accountChangeUnsubscribe, null, "f");
1390
- }
1391
- __classPrivateFieldSet(this, _PerpsController_previousIsTestnet, null, "f");
1392
- __classPrivateFieldSet(this, _PerpsController_previousHip3ConfigVersion, null, "f");
1393
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_cleanupStandaloneProvider).call(this).catch(() => {
1394
- /* fire-and-forget to preserve sync signature */
1395
- });
1396
- }
1397
- /**
1398
- * Get list of available HIP-3 builder-deployed DEXs
1399
- *
1400
- * @param params - Optional parameters for filtering
1401
- * @returns Array of DEX names
1402
- */
1403
- async getAvailableDexs(params) {
1404
- const provider = this.getActiveProvider();
1405
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getAvailableDexs');
1406
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getAvailableDexs({
1407
- provider,
1408
- params,
1409
- context,
1410
- });
1411
- }
1412
- /**
1413
- * Fetch historical candle data
1414
- * Thin delegation to MarketDataService
1415
- *
1416
- * @param options - The configuration options.
1417
- * @param options.symbol - The trading pair symbol.
1418
- * @param options.interval - The candle interval period.
1419
- * @param options.limit - Maximum number of items to fetch.
1420
- * @param options.endTime - End timestamp in milliseconds.
1421
- * @returns The historical candle data for the requested symbol and interval.
1422
- */
1423
- async fetchHistoricalCandles(options) {
1424
- const { symbol, interval, limit = 100, endTime } = options;
1425
- const provider = this.getActiveProvider();
1426
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").fetchHistoricalCandles({
1427
- provider,
1428
- symbol,
1429
- interval,
1430
- limit,
1431
- endTime,
1432
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'fetchHistoricalCandles'),
1433
- });
1434
- }
1435
- /**
1436
- * Calculate liquidation price for a position
1437
- * Uses provider-specific formulas based on protocol rules
1438
- *
1439
- * @param params - The operation parameters.
1440
- * @returns A promise that resolves to the string result.
1441
- */
1442
- async calculateLiquidationPrice(params) {
1443
- const provider = this.getActiveProvider();
1444
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'calculateLiquidationPrice');
1445
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").calculateLiquidationPrice({
1446
- provider,
1447
- params,
1448
- context,
1449
- });
1450
- }
1451
- /**
1452
- * Calculate maintenance margin for a specific asset
1453
- * Returns a percentage (e.g., 0.0125 for 1.25%)
1454
- *
1455
- * @param params - The operation parameters.
1456
- * @returns A promise that resolves to the numeric result.
1457
- */
1458
- async calculateMaintenanceMargin(params) {
1459
- const provider = this.getActiveProvider();
1460
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'calculateMaintenanceMargin');
1461
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").calculateMaintenanceMargin({
1462
- provider,
1463
- params,
1464
- context,
1465
- });
1466
- }
1467
- /**
1468
- * Get maximum leverage allowed for an asset
1469
- *
1470
- * @param asset - The asset identifier.
1471
- * @returns A promise that resolves to the numeric result.
1472
- */
1473
- async getMaxLeverage(asset) {
1474
- const provider = this.getActiveProvider();
1475
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'getMaxLeverage');
1476
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getMaxLeverage({ provider, asset, context });
1477
- }
1478
- /**
1479
- * Validate order parameters according to protocol-specific rules
1480
- *
1481
- * @param params - The operation parameters.
1482
- * @returns True if the condition is met.
1483
- */
1484
- async validateOrder(params) {
1485
- const provider = this.getActiveProvider();
1486
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'validateOrder');
1487
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").validateOrder({ provider, params, context });
1488
- }
1489
- /**
1490
- * Validate close position parameters according to protocol-specific rules
1491
- *
1492
- * @param params - The operation parameters.
1493
- * @returns A promise that resolves to the result.
1494
- */
1495
- async validateClosePosition(params) {
1496
- const provider = this.getActiveProvider();
1497
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'validateClosePosition');
1498
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").validateClosePosition({
1499
- provider,
1500
- params,
1501
- context,
1502
- });
1503
- }
1504
- /**
1505
- * Validate withdrawal parameters according to protocol-specific rules
1506
- *
1507
- * @param params - The operation parameters.
1508
- * @returns True if the condition is met.
1509
- */
1510
- async validateWithdrawal(params) {
1511
- const provider = this.getActiveProvider();
1512
- return __classPrivateFieldGet(this, _PerpsController_accountService, "f").validateWithdrawal({ provider, params });
1513
- }
1514
- /**
1515
- * Get supported withdrawal routes - returns complete asset and routing information
1516
- *
1517
- * @returns Array of supported asset routes for withdrawals.
1518
- */
1519
- getWithdrawalRoutes() {
1520
- try {
1521
- const provider = this.getActiveProvider();
1522
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getWithdrawalRoutes({ provider });
1523
- }
1524
- catch (error) {
1525
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.getWithdrawalRoutes'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'getWithdrawalRoutes'));
1526
- // Return empty array if provider is not available
1527
- return [];
1528
- }
1529
- }
1530
- /**
1531
- * Toggle between testnet and mainnet
1532
- *
1533
- * @returns The toggle result with success status and current network mode.
1534
- */
1535
- async toggleTestnet() {
1536
- // Prevent concurrent reinitializations
1537
- if (this.isCurrentlyReinitializing()) {
1538
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Already reinitializing, skipping toggle', {
1539
- timestamp: new Date().toISOString(),
1540
- });
1541
- return {
1542
- success: false,
1543
- isTestnet: this.state.isTestnet,
1544
- error: perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_REINITIALIZING,
1545
- };
1546
- }
1547
- __classPrivateFieldSet(this, _PerpsController_isReinitializing, true, "f");
1548
- // Store previous isTestnet for rollback on failure
1549
- const previousIsTestnet = this.state.isTestnet;
1550
- try {
1551
- await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_cleanupStandaloneProvider).call(this);
1552
- const previousNetwork = previousIsTestnet ? 'testnet' : 'mainnet';
1553
- this.update((state) => {
1554
- state.isTestnet = !state.isTestnet;
1555
- });
1556
- const newNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
1557
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Network toggle initiated', {
1558
- from: previousNetwork,
1559
- to: newNetwork,
1560
- timestamp: new Date().toISOString(),
1561
- });
1562
- // Reset initialization state and reinitialize provider with new testnet setting
1563
- this.isInitialized = false;
1564
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, null, "f");
1565
- await this.init();
1566
- // Check if initialization actually succeeded — performInitialization()
1567
- // does not throw on failure, it sets state to Failed and resolves.
1568
- if (this.state.initializationState === InitializationState.Failed) {
1569
- throw new Error(this.state.initializationError ??
1570
- 'Network toggle initialization failed');
1571
- }
1572
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Network toggle completed', {
1573
- newNetwork,
1574
- isTestnet: this.state.isTestnet,
1575
- timestamp: new Date().toISOString(),
1576
- });
1577
- return { success: true, isTestnet: this.state.isTestnet };
1578
- }
1579
- catch (error) {
1580
- // Rollback isTestnet to previous value
1581
- this.update((state) => {
1582
- state.isTestnet = previousIsTestnet;
1583
- });
1584
- return {
1585
- success: false,
1586
- isTestnet: this.state.isTestnet,
1587
- error: (0, errorUtils_1.ensureError)(error, 'PerpsController.toggleTestnet').message,
1588
- };
1589
- }
1590
- finally {
1591
- __classPrivateFieldSet(this, _PerpsController_isReinitializing, false, "f");
1592
- }
1593
- }
1594
- /**
1595
- * Switch to a different provider
1596
- * Uses a full reinit approach: disconnect() → update state → init()
1597
- * This ensures complete state reset including WebSocket connections and caches.
1598
- *
1599
- * @param providerId - The provider identifier.
1600
- * @returns The switch result with success status and active provider.
1601
- */
1602
- async switchProvider(providerId) {
1603
- // No-op if already on this provider (regardless of init state)
1604
- if (this.state.activeProvider === providerId) {
1605
- return { success: true, providerId };
1606
- }
1607
- // Validate provider is available
1608
- // 'aggregated' is always valid, individual providers must exist in the map
1609
- const isValidProvider = providerId === 'aggregated' || this.providers.has(providerId);
1610
- if (!isValidProvider) {
1611
- return {
1612
- success: false,
1613
- providerId: this.state.activeProvider,
1614
- error: `Provider ${providerId} not available`,
1615
- };
1616
- }
1617
- // Prevent concurrent switches
1618
- if (this.isCurrentlyReinitializing()) {
1619
- return {
1620
- success: false,
1621
- providerId: this.state.activeProvider,
1622
- error: perpsErrorCodes_1.PERPS_ERROR_CODES.CLIENT_REINITIALIZING,
1623
- };
1624
- }
1625
- __classPrivateFieldSet(this, _PerpsController_isReinitializing, true, "f");
1626
- // Store previous provider for rollback on failure
1627
- const previousProvider = this.state.activeProvider;
1628
- try {
1629
- await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_cleanupStandaloneProvider).call(this);
1630
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Provider switch initiated', {
1631
- from: previousProvider,
1632
- to: providerId,
1633
- timestamp: new Date().toISOString(),
1634
- });
1635
- // Provider disconnect is handled by performInitialization() during
1636
- // reinitialization. The disconnect() method skips provider teardown
1637
- // when isReinitializing is true to prevent double-disconnect.
1638
- // Update state with new provider
1639
- this.update((state) => {
1640
- state.activeProvider = providerId;
1641
- state.accountState = null;
1642
- state.initializationState = InitializationState.Uninitialized;
1643
- });
1644
- // Reset initialization state and reinitialize
1645
- this.isInitialized = false;
1646
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, null, "f");
1647
- await this.init();
1648
- // Check if initialization actually succeeded — performInitialization()
1649
- // does not throw on failure, it sets state to Failed and resolves.
1650
- if (this.state.initializationState === InitializationState.Failed) {
1651
- throw new Error(this.state.initializationError ?? 'Provider initialization failed');
1652
- }
1653
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Provider switch completed', {
1654
- providerId,
1655
- timestamp: new Date().toISOString(),
1656
- });
1657
- return { success: true, providerId };
1658
- }
1659
- catch (error) {
1660
- // Rollback state to previous provider
1661
- this.update((state) => {
1662
- state.activeProvider = previousProvider;
1663
- });
1664
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.switchProvider'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'switchProvider', { providerId }));
1665
- // Attempt to reinitialize the previous provider via init(),
1666
- // which handles all provider modes including 'aggregated'.
1667
- try {
1668
- this.isInitialized = false;
1669
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, null, "f");
1670
- await this.init();
1671
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Rollback to previous provider succeeded', {
1672
- previousProvider,
1673
- timestamp: new Date().toISOString(),
1674
- });
1675
- }
1676
- catch (reinitError) {
1677
- // Reinit also failed — mark as failed
1678
- this.update((state) => {
1679
- state.initializationState = InitializationState.Failed;
1680
- });
1681
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(reinitError, 'PerpsController.switchProvider.rollback'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'switchProvider.rollback', {
1682
- previousProvider,
1683
- }));
1684
- }
1685
- return {
1686
- success: false,
1687
- providerId: previousProvider,
1688
- error: error instanceof Error
1689
- ? error.message
1690
- : perpsErrorCodes_1.PERPS_ERROR_CODES.UNKNOWN_ERROR,
1691
- };
1692
- }
1693
- finally {
1694
- __classPrivateFieldSet(this, _PerpsController_isReinitializing, false, "f");
1695
- }
1696
- }
1697
- /**
1698
- * Get current network (mainnet/testnet)
1699
- *
1700
- * @returns Either 'mainnet' or 'testnet' based on the current configuration.
1701
- */
1702
- getCurrentNetwork() {
1703
- return this.state.isTestnet ? 'testnet' : 'mainnet';
1704
- }
1705
- /**
1706
- * Get the current WebSocket connection state from the active provider.
1707
- * Used by the UI to monitor connection health and show notifications.
1708
- *
1709
- * @returns The current WebSocket connection state, or DISCONNECTED if not supported
1710
- */
1711
- getWebSocketConnectionState() {
1712
- try {
1713
- const provider = this.getActiveProvider();
1714
- if (provider.getWebSocketConnectionState) {
1715
- return provider.getWebSocketConnectionState();
1716
- }
1717
- // Fallback for providers that don't support this method
1718
- return types_1.WebSocketConnectionState.Disconnected;
1719
- }
1720
- catch {
1721
- // If no provider is active, return disconnected
1722
- return types_1.WebSocketConnectionState.Disconnected;
1723
- }
1724
- }
1725
- /**
1726
- * Subscribe to WebSocket connection state changes from the active provider.
1727
- * The listener will be called immediately with the current state and whenever the state changes.
1728
- *
1729
- * @param listener - Callback function that receives the new connection state and reconnection attempt
1730
- * @returns Unsubscribe function to remove the listener, or no-op if not supported
1731
- */
1732
- subscribeToConnectionState(listener) {
1733
- try {
1734
- const provider = this.getActiveProvider();
1735
- if (provider.subscribeToConnectionState) {
1736
- return provider.subscribeToConnectionState(listener);
1737
- }
1738
- // Fallback: immediately call with current state and return no-op unsubscribe
1739
- listener(this.getWebSocketConnectionState(), 0);
1740
- return () => {
1741
- // No-op
1742
- };
1743
- }
1744
- catch {
1745
- // If no provider is active, call with disconnected and return no-op
1746
- listener(types_1.WebSocketConnectionState.Disconnected, 0);
1747
- return () => {
1748
- // No-op
1749
- };
1750
- }
1751
- }
1752
- /**
1753
- * Manually trigger a WebSocket reconnection attempt.
1754
- * Used by the UI retry button when connection is lost.
1755
- */
1756
- async reconnect() {
1757
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, '[PerpsController] reconnect() called');
1758
- try {
1759
- const provider = this.getActiveProvider();
1760
- if (provider.reconnect) {
1761
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, '[PerpsController] Delegating to provider.reconnect()');
1762
- await provider.reconnect();
1763
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, '[PerpsController] provider.reconnect() completed');
1764
- }
1765
- else {
1766
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, '[PerpsController] Provider does not support reconnect()');
1767
- }
1768
- }
1769
- catch (error) {
1770
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.reconnect'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'reconnect', {
1771
- operation: 'websocket_reconnect',
1772
- }));
1773
- }
1774
- }
1775
- // Live data delegation (NO Redux) - delegates to active provider
1776
- /**
1777
- * Subscribe to live price updates
1778
- *
1779
- * @param params - The operation parameters.
1780
- * @returns A cleanup function to remove the subscription.
1781
- */
1782
- subscribeToPrices(params) {
1783
- const provider = this.getActiveProviderOrNull();
1784
- if (!provider) {
1785
- return () => {
1786
- // No-op: Provider not initialized
1787
- };
1788
- }
1789
- try {
1790
- return provider.subscribeToPrices(params);
1791
- }
1792
- catch (error) {
1793
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToPrices'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToPrices', {
1794
- symbols: params.symbols?.join(','),
1795
- }));
1796
- return () => {
1797
- // No-op
1798
- };
1799
- }
1800
- }
1801
- /**
1802
- * Subscribe to live position updates
1803
- *
1804
- * @param params - The operation parameters.
1805
- * @returns A cleanup function to remove the subscription.
1806
- */
1807
- subscribeToPositions(params) {
1808
- const provider = this.getActiveProviderOrNull();
1809
- if (!provider) {
1810
- return () => {
1811
- // No-op: Provider not initialized
1812
- };
1813
- }
1814
- try {
1815
- return provider.subscribeToPositions(params);
1816
- }
1817
- catch (error) {
1818
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToPositions'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToPositions', {
1819
- accountId: params.accountId,
1820
- }));
1821
- return () => {
1822
- // No-op
1823
- };
1824
- }
1825
- }
1826
- /**
1827
- * Subscribe to live order fill updates
1828
- *
1829
- * @param params - The operation parameters.
1830
- * @returns A cleanup function to remove the subscription.
1831
- */
1832
- subscribeToOrderFills(params) {
1833
- const provider = this.getActiveProviderOrNull();
1834
- if (!provider) {
1835
- return () => {
1836
- // No-op: Provider not initialized
1837
- };
1838
- }
1839
- try {
1840
- return provider.subscribeToOrderFills(params);
1841
- }
1842
- catch (error) {
1843
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToOrderFills'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToOrderFills', {
1844
- accountId: params.accountId,
1845
- }));
1846
- return () => {
1847
- // No-op
1848
- };
1849
- }
1850
- }
1851
- /**
1852
- * Subscribe to live order updates
1853
- *
1854
- * @param params - The operation parameters.
1855
- * @returns A cleanup function to remove the subscription.
1856
- */
1857
- subscribeToOrders(params) {
1858
- const provider = this.getActiveProviderOrNull();
1859
- if (!provider) {
1860
- return () => {
1861
- // No-op: Provider not initialized
1862
- };
1863
- }
1864
- try {
1865
- return provider.subscribeToOrders(params);
1866
- }
1867
- catch (error) {
1868
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToOrders'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToOrders', {
1869
- accountId: params.accountId,
1870
- }));
1871
- return () => {
1872
- // No-op
1873
- };
1874
- }
1875
- }
1876
- /**
1877
- * Subscribe to live account updates.
1878
- * Updates controller state (Redux) when new account data arrives so consumers
1879
- * like usePerpsBalanceTokenFilter (PayWithModal) see the latest balance.
1880
- *
1881
- * @param params - The operation parameters.
1882
- * @returns A cleanup function to remove the subscription.
1883
- */
1884
- subscribeToAccount(params) {
1885
- const provider = this.getActiveProviderOrNull();
1886
- if (!provider) {
1887
- return () => {
1888
- // No-op: Provider not initialized
1889
- };
1890
- }
1891
- try {
1892
- const originalCallback = params.callback;
1893
- return provider.subscribeToAccount({
1894
- ...params,
1895
- callback: (account) => {
1896
- if (account) {
1897
- this.update((state) => {
1898
- state.accountState = account;
1899
- state.lastUpdateTimestamp = Date.now();
1900
- state.lastError = null;
1901
- });
1902
- }
1903
- originalCallback(account);
1904
- },
1905
- });
1906
- }
1907
- catch (error) {
1908
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToAccount'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToAccount', {
1909
- accountId: params.accountId,
1910
- }));
1911
- return () => {
1912
- // No-op
1913
- };
1914
- }
1915
- }
1916
- /**
1917
- * Subscribe to full order book updates with multiple depth levels
1918
- * Creates a dedicated L2Book subscription for real-time order book data
1919
- *
1920
- * @param params - The operation parameters.
1921
- * @returns A cleanup function to remove the subscription.
1922
- */
1923
- subscribeToOrderBook(params) {
1924
- const provider = this.getActiveProviderOrNull();
1925
- if (!provider) {
1926
- return () => {
1927
- // No-op: Provider not initialized
1928
- };
1929
- }
1930
- try {
1931
- return provider.subscribeToOrderBook(params);
1932
- }
1933
- catch (error) {
1934
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToOrderBook'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToOrderBook', {
1935
- symbol: params.symbol,
1936
- levels: params.levels,
1937
- }));
1938
- return () => {
1939
- // No-op
1940
- };
1941
- }
1942
- }
1943
- /**
1944
- * Subscribe to live candle updates
1945
- *
1946
- * @param params - The operation parameters.
1947
- * @returns A cleanup function to remove the subscription.
1948
- */
1949
- subscribeToCandles(params) {
1950
- const provider = this.getActiveProviderOrNull();
1951
- if (!provider) {
1952
- return () => {
1953
- // No-op: Provider not initialized
1954
- };
1955
- }
1956
- try {
1957
- return provider.subscribeToCandles(params);
1958
- }
1959
- catch (error) {
1960
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToCandles'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToCandles', {
1961
- symbol: params.symbol,
1962
- interval: params.interval,
1963
- duration: params.duration,
1964
- }));
1965
- return () => {
1966
- // No-op
1967
- };
1968
- }
1969
- }
1970
- /**
1971
- * Subscribe to open interest cap updates
1972
- * Zero additional network overhead - data comes from existing webData3 subscription
1973
- *
1974
- * @param params - The operation parameters.
1975
- * @returns A cleanup function to remove the subscription.
1976
- */
1977
- subscribeToOICaps(params) {
1978
- const provider = this.getActiveProviderOrNull();
1979
- if (!provider) {
1980
- return () => {
1981
- // No-op: Provider not initialized
1982
- };
1983
- }
1984
- try {
1985
- return provider.subscribeToOICaps(params);
1986
- }
1987
- catch (error) {
1988
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.subscribeToOICaps'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'subscribeToOICaps', {
1989
- accountId: params.accountId,
1990
- }));
1991
- return () => {
1992
- // No-op
1993
- };
1994
- }
1995
- }
1996
- /**
1997
- * Configure live data throttling
1998
- *
1999
- * @param config - The configuration object.
2000
- */
2001
- setLiveDataConfig(config) {
2002
- try {
2003
- const provider = this.getActiveProvider();
2004
- provider.setLiveDataConfig(config);
2005
- }
2006
- catch (error) {
2007
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.setLiveDataConfig'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'setLiveDataConfig'));
2008
- }
2009
- }
2010
- /**
2011
- * Calculate trading fees for the active provider
2012
- * Each provider implements its own fee structure
2013
- *
2014
- * @param params - The operation parameters.
2015
- * @returns The fee calculation result for the trade.
2016
- */
2017
- async calculateFees(params) {
2018
- const provider = this.getActiveProvider();
2019
- const context = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'calculateFees');
2020
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").calculateFees({ provider, params, context });
2021
- }
2022
- /**
2023
- * Disconnect provider and cleanup subscriptions
2024
- * Call this when navigating away from Perps screens to prevent battery drain
2025
- */
2026
- async disconnect() {
2027
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Disconnecting provider to cleanup subscriptions', {
2028
- timestamp: new Date().toISOString(),
2029
- });
2030
- // Only disconnect the provider if we're initialized
2031
- if (this.isInitialized && !this.isCurrentlyReinitializing()) {
2032
- try {
2033
- const provider = this.getActiveProvider();
2034
- await provider.disconnect();
2035
- }
2036
- catch (error) {
2037
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.disconnect'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'disconnect'));
2038
- }
2039
- }
2040
- // Cleanup cached standalone provider (if any)
2041
- await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_cleanupStandaloneProvider).call(this);
2042
- // Note: Feature-flag subscription is NOT cleaned up here.
2043
- // It is a controller-lifetime concern (set once in the constructor),
2044
- // not a session-lifetime concern. Unsubscribing here would break
2045
- // geo-blocking / HIP-3 flag propagation after disconnect → reconnect.
2046
- // Reset initialization state to ensure proper reconnection
2047
- this.isInitialized = false;
2048
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, null, "f");
2049
- }
2050
- /**
2051
- * Eligibility (Geo-Blocking)
2052
- */
2053
- /**
2054
- * Fetch geo location
2055
- *
2056
- * Returned in Country or Country-Region format
2057
- * Example: FR, DE, US-MI, CA-ON
2058
- */
2059
- /**
2060
- * Refresh eligibility status
2061
- */
2062
- async refreshEligibility() {
2063
- // Capture the current version before starting the async operation.
2064
- // This prevents race conditions where stale eligibility checks
2065
- // (started with fallback config) overwrite results from newer checks
2066
- // (started with remote config after it was fetched).
2067
- const versionAtStart = __classPrivateFieldGet(this, _PerpsController_blockedRegionListVersion, "f");
2068
- try {
2069
- // TODO: It would be good to have this location before we call this async function to avoid the race condition
2070
- const isEligible = await __classPrivateFieldGet(this, _PerpsController_eligibilityService, "f").checkEligibility({
2071
- blockedRegions: this.blockedRegionList.list,
2072
- });
2073
- // Only update state if the blocked region list hasn't changed while we were awaiting.
2074
- // This prevents stale fallback-based eligibility checks from overwriting
2075
- // results from remote-based checks.
2076
- if (__classPrivateFieldGet(this, _PerpsController_blockedRegionListVersion, "f") !== versionAtStart) {
2077
- return;
2078
- }
2079
- this.update((state) => {
2080
- state.isEligible = isEligible;
2081
- });
2082
- }
2083
- catch (error) {
2084
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.refreshEligibility'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'refreshEligibility'));
2085
- // Only update on error if version is still current
2086
- if (__classPrivateFieldGet(this, _PerpsController_blockedRegionListVersion, "f") === versionAtStart) {
2087
- // Default to eligible on error
2088
- this.update((state) => {
2089
- state.isEligible = true;
2090
- });
2091
- }
2092
- }
2093
- }
2094
- /**
2095
- * Get block explorer URL for an address or just the base URL
2096
- *
2097
- * @param address - Optional address to append to the base URL
2098
- * @returns Block explorer URL
2099
- */
2100
- getBlockExplorerUrl(address) {
2101
- const provider = this.getActiveProvider();
2102
- return __classPrivateFieldGet(this, _PerpsController_marketDataService, "f").getBlockExplorerUrl({ provider, address });
2103
- }
2104
- /**
2105
- * Check if user is first-time for the current network
2106
- *
2107
- * @returns True if the condition is met.
2108
- */
2109
- isFirstTimeUserOnCurrentNetwork() {
2110
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2111
- return this.state.isFirstTimeUser[currentNetwork];
2112
- }
2113
- /**
2114
- * Mark that the user has completed the tutorial/onboarding
2115
- * This prevents the tutorial from showing again
2116
- */
2117
- markTutorialCompleted() {
2118
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2119
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Marking tutorial as completed', {
2120
- timestamp: new Date().toISOString(),
2121
- network: currentNetwork,
2122
- });
2123
- this.update((state) => {
2124
- state.isFirstTimeUser[currentNetwork] = false;
2125
- });
2126
- }
2127
- /*
2128
- * Mark that user has placed their first successful order
2129
- * This prevents the notification tooltip from showing again
2130
- */
2131
- markFirstOrderCompleted() {
2132
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2133
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Marking first order completed', {
2134
- timestamp: new Date().toISOString(),
2135
- network: currentNetwork,
2136
- });
2137
- this.update((state) => {
2138
- state.hasPlacedFirstOrder[currentNetwork] = true;
2139
- });
2140
- }
2141
- /**
2142
- * Reset first-time user state for both networks
2143
- * This is useful for testing the tutorial flow
2144
- * Called by Reset Account feature in settings
2145
- */
2146
- resetFirstTimeUserState() {
2147
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Resetting first-time user state', {
2148
- timestamp: new Date().toISOString(),
2149
- previousState: this.state.isFirstTimeUser,
2150
- });
2151
- this.update((state) => {
2152
- state.isFirstTimeUser = {
2153
- testnet: true,
2154
- mainnet: true,
2155
- };
2156
- state.hasPlacedFirstOrder = {
2157
- testnet: false,
2158
- mainnet: false,
2159
- };
2160
- });
2161
- }
2162
- /**
2163
- * Clear pending/bridging withdrawal and deposit requests
2164
- * This is useful when users want to clear stuck pending indicators
2165
- * Called by Reset Account feature in settings
2166
- */
2167
- clearPendingTransactionRequests() {
2168
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Clearing pending transaction requests', {
2169
- timestamp: new Date().toISOString(),
2170
- });
2171
- this.update((state) => {
2172
- // Filter out pending/bridging withdrawals, keep completed/failed for history
2173
- state.withdrawalRequests = state.withdrawalRequests.filter((req) => req.status !== 'pending' && req.status !== 'bridging');
2174
- // Filter out pending deposits, keep completed/failed for history
2175
- state.depositRequests = state.depositRequests.filter((req) => req.status !== 'pending' && req.status !== 'bridging');
2176
- // Reset withdrawal progress
2177
- state.withdrawalProgress = {
2178
- progress: 0,
2179
- lastUpdated: Date.now(),
2180
- activeWithdrawalId: null,
2181
- };
2182
- });
2183
- }
2184
- /**
2185
- * Get saved trade configuration for a market
2186
- *
2187
- * @param symbol - The trading pair symbol.
2188
- * @returns The resulting string value.
2189
- */
2190
- getTradeConfiguration(symbol) {
2191
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2192
- const config = this.state.tradeConfigurations[network]?.[symbol];
2193
- if (!config?.leverage) {
2194
- return undefined;
2195
- }
2196
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Retrieved trade config', {
2197
- symbol,
2198
- network,
2199
- leverage: config.leverage,
2200
- });
2201
- return { leverage: config.leverage };
2202
- }
2203
- /**
2204
- * Save trade configuration for a market
2205
- *
2206
- * @param symbol - Market symbol
2207
- * @param leverage - Leverage value
2208
- */
2209
- saveTradeConfiguration(symbol, leverage) {
2210
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2211
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Saving trade configuration', {
2212
- symbol,
2213
- network,
2214
- leverage,
2215
- timestamp: new Date().toISOString(),
2216
- });
2217
- this.update((state) => {
2218
- if (!state.tradeConfigurations[network]) {
2219
- state.tradeConfigurations[network] = {};
2220
- }
2221
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
2222
- state.tradeConfigurations[network][symbol] = {
2223
- ...existingConfig,
2224
- leverage,
2225
- };
2226
- });
2227
- }
2228
- /**
2229
- * Save pending trade configuration for a market
2230
- * This is a temporary configuration that expires after 5 minutes
2231
- *
2232
- * @param symbol - Market symbol
2233
- * @param config - Pending trade configuration (includes optional selected payment token from Pay row)
2234
- * @param config.amount - The amount value.
2235
- * @param config.leverage - The leverage multiplier.
2236
- * @param config.takeProfitPrice - The take profit price.
2237
- * @param config.stopLossPrice - The stop loss price.
2238
- * @param config.limitPrice - The limit price.
2239
- * @param config.orderType - The order type.
2240
- * @param config.selectedPaymentToken - The selected payment token.
2241
- */
2242
- savePendingTradeConfiguration(symbol, config) {
2243
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2244
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Saving pending trade configuration', {
2245
- symbol,
2246
- network,
2247
- config,
2248
- timestamp: new Date().toISOString(),
2249
- });
2250
- this.update((state) => {
2251
- if (!state.tradeConfigurations[network]) {
2252
- state.tradeConfigurations[network] = {};
2253
- }
2254
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
2255
- state.tradeConfigurations[network][symbol] = {
2256
- ...existingConfig,
2257
- pendingConfig: {
2258
- ...config,
2259
- timestamp: Date.now(),
2260
- },
2261
- };
2262
- });
2263
- }
2264
- /**
2265
- * Get pending trade configuration for a market
2266
- * Returns undefined if config doesn't exist or has expired (more than 5 minutes old)
2267
- *
2268
- * @param symbol - Market symbol
2269
- * @returns Pending trade configuration or undefined
2270
- */
2271
- getPendingTradeConfiguration(symbol) {
2272
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2273
- const config = this.state.tradeConfigurations[network]?.[symbol]?.pendingConfig;
2274
- if (!config) {
2275
- return undefined;
2276
- }
2277
- // Check if config has expired (5 minutes = 300,000 milliseconds)
2278
- const FIVE_MINUTES_MS = 5 * 60 * 1000;
2279
- const now = Date.now();
2280
- const age = now - config.timestamp;
2281
- if (age > FIVE_MINUTES_MS) {
2282
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Pending trade config expired', {
2283
- symbol,
2284
- network,
2285
- age,
2286
- timestamp: config.timestamp,
2287
- });
2288
- // Clear expired config
2289
- this.update((state) => {
2290
- if (state.tradeConfigurations[network]?.[symbol]?.pendingConfig) {
2291
- delete state.tradeConfigurations[network][symbol].pendingConfig;
2292
- }
2293
- });
2294
- return undefined;
2295
- }
2296
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Retrieved pending trade config', {
2297
- symbol,
2298
- network,
2299
- config,
2300
- age,
2301
- });
2302
- // Return config without timestamp
2303
- const { timestamp, ...configWithoutTimestamp } = config;
2304
- return configWithoutTimestamp;
2305
- }
2306
- /**
2307
- * Clear pending trade configuration for a market
2308
- *
2309
- * @param symbol - Market symbol
2310
- */
2311
- clearPendingTradeConfiguration(symbol) {
2312
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2313
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Clearing pending trade configuration', {
2314
- symbol,
2315
- network,
2316
- timestamp: new Date().toISOString(),
2317
- });
2318
- this.update((state) => {
2319
- if (state.tradeConfigurations[network]?.[symbol]?.pendingConfig) {
2320
- delete state.tradeConfigurations[network][symbol].pendingConfig;
2321
- }
2322
- });
2323
- }
2324
- /**
2325
- * Get saved market filter preferences
2326
- * Handles backward compatibility with legacy string format
2327
- *
2328
- * @returns The saved sort option ID and direction.
2329
- */
2330
- getMarketFilterPreferences() {
2331
- const pref = this.state.marketFilterPreferences;
2332
- // Handle legacy string format (backward compatibility)
2333
- if (typeof pref === 'string') {
2334
- // Map legacy compound IDs to new format
2335
- // Old format: 'priceChange-desc' or 'priceChange-asc'
2336
- // New format: { optionId: 'priceChange', direction: 'desc'/'asc' }
2337
- if (pref === 'priceChange-desc') {
2338
- return {
2339
- optionId: 'priceChange',
2340
- direction: 'desc',
2341
- };
2342
- }
2343
- if (pref === 'priceChange-asc') {
2344
- return {
2345
- optionId: 'priceChange',
2346
- direction: 'asc',
2347
- };
2348
- }
2349
- // Handle other simple legacy strings (e.g., 'volume', 'openInterest', etc.)
2350
- return {
2351
- optionId: pref,
2352
- direction: perpsConfig_1.MARKET_SORTING_CONFIG.DefaultDirection,
2353
- };
2354
- }
2355
- // Return new object format or default
2356
- return (pref ?? {
2357
- optionId: perpsConfig_1.MARKET_SORTING_CONFIG.DefaultSortOptionId,
2358
- direction: perpsConfig_1.MARKET_SORTING_CONFIG.DefaultDirection,
2359
- });
2360
- }
2361
- /**
2362
- * Save market filter preferences
2363
- *
2364
- * @param optionId - Sort/filter option ID
2365
- * @param direction - Sort direction ('asc' or 'desc')
2366
- */
2367
- saveMarketFilterPreferences(optionId, direction) {
2368
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Saving market filter preferences', {
2369
- optionId,
2370
- direction,
2371
- timestamp: new Date().toISOString(),
2372
- });
2373
- this.update((state) => {
2374
- state.marketFilterPreferences = { optionId, direction };
2375
- });
2376
- }
2377
- /**
2378
- * Set the selected payment token for the Perps order/deposit flow.
2379
- * Pass null or a token with description PERPS_CONSTANTS.PerpsBalanceTokenDescription to select Perps balance.
2380
- * Only required fields (address, chainId) are stored in state; description and symbol are optional.
2381
- *
2382
- * @param token - The token identifier.
2383
- */
2384
- setSelectedPaymentToken(token) {
2385
- let normalized = null;
2386
- if (token !== null &&
2387
- token.description !== perpsConfig_1.PERPS_CONSTANTS.PerpsBalanceTokenDescription) {
2388
- normalized = token;
2389
- }
2390
- const current = this.state.selectedPaymentToken;
2391
- const initialPaymentMethod = current === null ||
2392
- current === undefined ||
2393
- current?.description === perpsConfig_1.PERPS_CONSTANTS.PerpsBalanceTokenDescription
2394
- ? 'perps_balance'
2395
- : (current?.symbol ?? 'unknown');
2396
- const newPaymentMethod = token === null ||
2397
- token.description === perpsConfig_1.PERPS_CONSTANTS.PerpsBalanceTokenDescription
2398
- ? 'perps_balance'
2399
- : (token.symbol ?? 'unknown');
2400
- if (initialPaymentMethod !== newPaymentMethod) {
2401
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getMetrics).call(this).trackPerpsEvent(types_1.PerpsAnalyticsEvent.UiInteraction, {
2402
- [eventNames_1.PERPS_EVENT_PROPERTY.INTERACTION_TYPE]: eventNames_1.PERPS_EVENT_VALUE.INTERACTION_TYPE.PAYMENT_METHOD_CHANGED,
2403
- [eventNames_1.PERPS_EVENT_PROPERTY.INITIAL_PAYMENT_METHOD]: initialPaymentMethod,
2404
- [eventNames_1.PERPS_EVENT_PROPERTY.NEW_PAYMENT_METHOD]: newPaymentMethod,
2405
- });
2406
- }
2407
- let snapshot = null;
2408
- if (normalized !== null) {
2409
- snapshot = {
2410
- ...(normalized.description !== undefined && {
2411
- description: normalized.description,
2412
- }),
2413
- address: normalized.address,
2414
- chainId: normalized.chainId,
2415
- symbol: normalized.symbol,
2416
- };
2417
- }
2418
- this.update((state) => {
2419
- state.selectedPaymentToken = snapshot;
2420
- });
2421
- }
2422
- /**
2423
- * Reset the selected payment token to Perps balance (null).
2424
- * Call when leaving the Perps order view so the next visit defaults to Perps balance.
2425
- */
2426
- resetSelectedPaymentToken() {
2427
- this.update((state) => {
2428
- state.selectedPaymentToken = null;
2429
- });
2430
- }
2431
- /**
2432
- * Get saved order book grouping for a market
2433
- *
2434
- * @param symbol - Market symbol
2435
- * @returns The saved grouping value or undefined if not set
2436
- */
2437
- getOrderBookGrouping(symbol) {
2438
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2439
- const grouping = this.state.tradeConfigurations[network]?.[symbol]?.orderBookGrouping;
2440
- if (grouping !== undefined) {
2441
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Retrieved order book grouping', {
2442
- symbol,
2443
- network,
2444
- grouping,
2445
- });
2446
- }
2447
- return grouping;
2448
- }
2449
- /**
2450
- * Save order book grouping for a market
2451
- *
2452
- * @param symbol - Market symbol
2453
- * @param grouping - Price grouping value
2454
- */
2455
- saveOrderBookGrouping(symbol, grouping) {
2456
- const network = this.state.isTestnet ? 'testnet' : 'mainnet';
2457
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Saving order book grouping', {
2458
- symbol,
2459
- network,
2460
- grouping,
2461
- timestamp: new Date().toISOString(),
2462
- });
2463
- this.update((state) => {
2464
- if (!state.tradeConfigurations[network]) {
2465
- state.tradeConfigurations[network] = {};
2466
- }
2467
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
2468
- state.tradeConfigurations[network][symbol] = {
2469
- ...existingConfig,
2470
- orderBookGrouping: grouping,
2471
- };
2472
- });
2473
- }
2474
- /**
2475
- * Toggle watchlist status for a market
2476
- * Watchlist markets are stored per network (testnet/mainnet)
2477
- *
2478
- * @param symbol - The trading pair symbol.
2479
- */
2480
- toggleWatchlistMarket(symbol) {
2481
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2482
- const currentWatchlist = this.state.watchlistMarkets[currentNetwork];
2483
- const isWatchlisted = currentWatchlist.includes(symbol);
2484
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Toggling watchlist market', {
2485
- timestamp: new Date().toISOString(),
2486
- network: currentNetwork,
2487
- symbol,
2488
- action: isWatchlisted ? 'remove' : 'add',
2489
- });
2490
- this.update((state) => {
2491
- if (isWatchlisted) {
2492
- // Remove from watchlist
2493
- state.watchlistMarkets[currentNetwork] = currentWatchlist.filter((marketSymbol) => marketSymbol !== symbol);
2494
- }
2495
- else {
2496
- // Add to watchlist
2497
- state.watchlistMarkets[currentNetwork] = [...currentWatchlist, symbol];
2498
- }
2499
- });
2500
- }
2501
- /**
2502
- * Check if a market is in the watchlist on the current network
2503
- *
2504
- * @param symbol - The trading pair symbol.
2505
- * @returns True if the condition is met.
2506
- */
2507
- isWatchlistMarket(symbol) {
2508
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2509
- return this.state.watchlistMarkets[currentNetwork].includes(symbol);
2510
- }
2511
- /**
2512
- * Get all watchlist markets for the current network
2513
- *
2514
- * @returns The resulting string value.
2515
- */
2516
- getWatchlistMarkets() {
2517
- const currentNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
2518
- return this.state.watchlistMarkets[currentNetwork];
2519
- }
2520
- /**
2521
- * Report order events to data lake API with retry (non-blocking)
2522
- * Thin delegation to DataLakeService
2523
- *
2524
- * @param params - The operation parameters.
2525
- * @param params.action - The order action.
2526
- * @param params.symbol - The trading pair symbol.
2527
- * @param params.slPrice - The stop loss price.
2528
- * @param params.tpPrice - The take profit price.
2529
- * @param params.retryCount - Internal retry counter.
2530
- * @param params._traceId - Internal trace ID.
2531
- * @returns Whether the report was sent successfully, with an optional error message.
2532
- */
2533
- async reportOrderToDataLake(params) {
2534
- return __classPrivateFieldGet(this, _PerpsController_dataLakeService, "f").reportOrder({
2535
- action: params.action,
2536
- symbol: params.symbol,
2537
- slPrice: params.slPrice,
2538
- tpPrice: params.tpPrice,
2539
- isTestnet: this.state.isTestnet,
2540
- context: __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_createServiceContext).call(this, 'reportOrderToDataLake', {}),
2541
- retryCount: params.retryCount,
2542
- _traceId: params._traceId,
2543
- });
2544
- }
2545
- /**
2546
- * Check if the controller is currently reinitializing
2547
- *
2548
- * @returns true if providers are being reinitialized
2549
- */
2550
- isCurrentlyReinitializing() {
2551
- return __classPrivateFieldGet(this, _PerpsController_isReinitializing, "f");
2552
- }
23
+ function getDefaultPerpsControllerState() {
24
+ return {};
2553
25
  }
2554
- exports.PerpsController = PerpsController;
2555
- _a = PerpsController, _PerpsController_initializationPromise = new WeakMap(), _PerpsController_isReinitializing = new WeakMap(), _PerpsController_blockedRegionListVersion = new WeakMap(), _PerpsController_hip3Enabled = new WeakMap(), _PerpsController_hip3AllowlistMarkets = new WeakMap(), _PerpsController_hip3BlocklistMarkets = new WeakMap(), _PerpsController_hip3ConfigSource = new WeakMap(), _PerpsController_standaloneProvider = new WeakMap(), _PerpsController_standaloneProviderIsTestnet = new WeakMap(), _PerpsController_standaloneProviderHip3Version = new WeakMap(), _PerpsController_options = new WeakMap(), _PerpsController_tradingService = new WeakMap(), _PerpsController_marketDataService = new WeakMap(), _PerpsController_accountService = new WeakMap(), _PerpsController_eligibilityService = new WeakMap(), _PerpsController_dataLakeService = new WeakMap(), _PerpsController_depositService = new WeakMap(), _PerpsController_featureFlagConfigurationService = new WeakMap(), _PerpsController_rewardsIntegrationService = new WeakMap(), _PerpsController_preloadTimer = new WeakMap(), _PerpsController_isPreloading = new WeakMap(), _PerpsController_isPreloadingUserData = new WeakMap(), _PerpsController_preloadStateUnsubscribe = new WeakMap(), _PerpsController_accountChangeUnsubscribe = new WeakMap(), _PerpsController_previousIsTestnet = new WeakMap(), _PerpsController_previousHip3ConfigVersion = new WeakMap(), _PerpsController_instances = new WeakSet(), _PerpsController_isMYXProviderEnabled = function _PerpsController_isMYXProviderEnabled() {
2556
- const getLocalFlag = () => typeof globalThis.process !== 'undefined' &&
2557
- globalThis.process.env?.MM_PERPS_MYX_PROVIDER_ENABLED === 'true';
2558
- try {
2559
- const localFlag = getLocalFlag();
2560
- const remoteState = __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.remoteFeatureFlags.getState();
2561
- const remoteFlag = remoteState.remoteFeatureFlags?.perpsMyxProviderEnabled;
2562
- if ((0, types_1.isVersionGatedFeatureFlag)(remoteFlag)) {
2563
- const validated = __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.featureFlags.validateVersionGated(remoteFlag);
2564
- return validated ?? localFlag;
2565
- }
2566
- return localFlag;
2567
- }
2568
- catch {
2569
- // If RemoteFeatureFlagController not ready, use fallback
2570
- return getLocalFlag();
2571
- }
2572
- }, _PerpsController_logError = function _PerpsController_logError(error, options) {
2573
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.logger.error(error, options);
2574
- }, _PerpsController_debugLog = function _PerpsController_debugLog(...args) {
2575
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.debugLogger.log(...args);
2576
- }, _PerpsController_getOrCreateStandaloneProvider = function _PerpsController_getOrCreateStandaloneProvider() {
2577
- const currentIsTestnet = this.state.isTestnet;
2578
- const currentHip3Version = this.state.hip3ConfigVersion ?? 0;
2579
- if (__classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f") &&
2580
- __classPrivateFieldGet(this, _PerpsController_standaloneProviderIsTestnet, "f") === currentIsTestnet &&
2581
- __classPrivateFieldGet(this, _PerpsController_standaloneProviderHip3Version, "f") === currentHip3Version) {
2582
- return __classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f");
2583
- }
2584
- // Stale or missing — tear down old one (fire-and-forget)
2585
- if (__classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f")) {
2586
- const old = __classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f");
2587
- Promise.resolve(old.disconnect()).catch(() => {
2588
- /* best-effort */
2589
- });
2590
- }
2591
- __classPrivateFieldSet(this, _PerpsController_standaloneProvider, new HyperLiquidProvider_1.HyperLiquidProvider({
2592
- isTestnet: currentIsTestnet,
2593
- hip3Enabled: __classPrivateFieldGet(this, _PerpsController_hip3Enabled, "f"),
2594
- allowlistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3AllowlistMarkets, "f"),
2595
- blocklistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3BlocklistMarkets, "f"),
2596
- platformDependencies: __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure,
2597
- }), "f");
2598
- __classPrivateFieldSet(this, _PerpsController_standaloneProviderIsTestnet, currentIsTestnet, "f");
2599
- __classPrivateFieldSet(this, _PerpsController_standaloneProviderHip3Version, currentHip3Version, "f");
2600
- return __classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f");
2601
- }, _PerpsController_cleanupStandaloneProvider =
2602
- /**
2603
- * Disconnect and discard the cached standalone provider (if any).
2604
- * Best-effort — errors are silently caught.
2605
- */
2606
- async function _PerpsController_cleanupStandaloneProvider() {
2607
- if (!__classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f")) {
2608
- return;
2609
- }
2610
- try {
2611
- await __classPrivateFieldGet(this, _PerpsController_standaloneProvider, "f").disconnect();
2612
- }
2613
- catch {
2614
- /* best-effort */
2615
- }
2616
- __classPrivateFieldSet(this, _PerpsController_standaloneProvider, null, "f");
2617
- __classPrivateFieldSet(this, _PerpsController_standaloneProviderIsTestnet, null, "f");
2618
- __classPrivateFieldSet(this, _PerpsController_standaloneProviderHip3Version, null, "f");
2619
- }, _PerpsController_getMetrics = function _PerpsController_getMetrics() {
2620
- return __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.metrics;
2621
- }, _PerpsController_findNetworkClientIdForChain = function _PerpsController_findNetworkClientIdForChain(chainId) {
2622
- return __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.network.findNetworkClientIdByChainId(chainId);
2623
- }, _PerpsController_submitTransaction =
2624
- /**
2625
- * Submit a transaction via messenger (shows confirmation screen)
2626
- *
2627
- * @param txParams - The transaction parameters.
2628
- * @param txParams.from - The sender address.
2629
- * @param txParams.to - The recipient address.
2630
- * @param txParams.value - The transaction value.
2631
- * @param txParams.data - The transaction data payload.
2632
- * @param txParams.gas - The gas limit.
2633
- * @param options - The configuration options.
2634
- * @param options.networkClientId - The network client identifier.
2635
- * @param options.origin - The transaction origin.
2636
- * @param options.type - The transaction type.
2637
- * @param options.skipInitialGasEstimate - Whether to skip initial gas estimation.
2638
- * @returns The transaction result containing a hash promise and transaction metadata.
2639
- */
2640
- async function _PerpsController_submitTransaction(txParams, options) {
2641
- return __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.transaction.addTransaction(txParams, options);
2642
- }, _PerpsController_migrateRequestsIfNeeded = function _PerpsController_migrateRequestsIfNeeded() {
2643
- this.update((state) => {
2644
- // Remove withdrawal requests without accountAddress - they can't be attributed to any account
2645
- state.withdrawalRequests = state.withdrawalRequests.filter((req) => Boolean(req.accountAddress));
2646
- // Remove deposit requests without accountAddress - they can't be attributed to any account
2647
- state.depositRequests = state.depositRequests.filter((req) => Boolean(req.accountAddress));
2648
- });
2649
- }, _PerpsController_withStreamPause =
26
+ exports.getDefaultPerpsControllerState = getDefaultPerpsControllerState;
2650
27
  /**
2651
- * Execute an operation while temporarily pausing specified stream channels
2652
- * to prevent WebSocket updates from triggering UI re-renders during operations.
28
+ * `PerpsController` manages perpetual trading functionality in MetaMask.
2653
29
  *
2654
- * WebSocket connections remain alive but updates are not emitted to subscribers.
2655
- * This prevents race conditions where UI re-renders fetch stale data during operations.
30
+ * This controller provides platform-agnostic perps trading capabilities.
2656
31
  *
2657
- * @param operation - The async operation to execute
2658
- * @param channels - Array of stream channel names to pause
2659
- * @returns The result of the operation
2660
32
  * @example
2661
- * ```typescript
2662
- * // Cancel orders without stream interference
2663
- * await this.#withStreamPause(
2664
- * async () => this.provider.cancelOrders({ cancelAll: true }),
2665
- * ['orders']
2666
- * );
2667
33
  *
2668
- * // Close positions and pause multiple streams
2669
- * await this.#withStreamPause(
2670
- * async () => this.provider.closePositions(positions),
2671
- * ['positions', 'account', 'orders']
34
+ * ``` ts
35
+ * import { Messenger } from '@metamask/messenger';
36
+ * import type {
37
+ * PerpsControllerActions,
38
+ * PerpsControllerEvents,
39
+ * } from '@metamask/perps-controller';
40
+ * import { PerpsController } from '@metamask/perps-controller';
41
+ *
42
+ * const rootMessenger = new Messenger<
43
+ * 'Root',
44
+ * PerpsControllerActions,
45
+ * PerpsControllerEvents
46
+ * >({ namespace: 'Root' });
47
+ * const perpsControllerMessenger = new Messenger<
48
+ * 'PerpsController',
49
+ * PerpsControllerActions,
50
+ * PerpsControllerEvents,
51
+ * typeof rootMessenger,
52
+ * >({
53
+ * namespace: 'PerpsController',
54
+ * parent: rootMessenger,
55
+ * });
56
+ * // Instantiate the controller to register its actions on the messenger
57
+ * new PerpsController({
58
+ * messenger: perpsControllerMessenger,
59
+ * });
60
+ *
61
+ * const perpsControllerState = await rootMessenger.call(
62
+ * 'PerpsController:getState',
2672
63
  * );
2673
64
  * ```
2674
65
  */
2675
- async function _PerpsController_withStreamPause(operation, channels) {
2676
- const pausedChannels = [];
2677
- const { streamManager } = __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure;
2678
- // Pause emission on specified channels (WebSocket stays connected)
2679
- // Track which channels successfully paused to ensure proper cleanup
2680
- for (const channel of channels) {
2681
- try {
2682
- streamManager.pauseChannel(channel);
2683
- pausedChannels.push(channel);
2684
- }
2685
- catch (error) {
2686
- // Log error to Sentry but continue pausing remaining channels
2687
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.withStreamPause'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'withStreamPause', {
2688
- operation: 'pause',
2689
- channel: String(channel),
2690
- pausedChannels: pausedChannels.join(','),
2691
- }));
2692
- }
2693
- }
2694
- try {
2695
- // Execute operation without stream interference
2696
- return await operation();
2697
- }
2698
- finally {
2699
- // Resume only channels that were successfully paused
2700
- for (const channel of pausedChannels) {
2701
- try {
2702
- streamManager.resumeChannel(channel);
2703
- }
2704
- catch (error) {
2705
- // Log error to Sentry but continue resuming remaining channels
2706
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.withStreamPause'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'withStreamPause', {
2707
- operation: 'resume',
2708
- channel: String(channel),
2709
- pausedChannels: pausedChannels.join(','),
2710
- }));
2711
- }
2712
- }
2713
- }
2714
- }, _PerpsController_performInitialization =
2715
- /**
2716
- * Actual initialization implementation with retry logic
2717
- */
2718
- async function _PerpsController_performInitialization() {
2719
- const maxAttempts = 3;
2720
- const baseDelay = 1000;
2721
- this.update((state) => {
2722
- state.initializationState = InitializationState.Initializing;
2723
- state.initializationError = null;
2724
- state.initializationAttempts = 0;
2725
- });
2726
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Initializing providers', {
2727
- currentNetwork: this.state.isTestnet ? 'testnet' : 'mainnet',
2728
- existingProviders: Array.from(this.providers.keys()),
2729
- timestamp: new Date().toISOString(),
2730
- });
2731
- let lastError = null;
2732
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2733
- try {
2734
- this.update((state) => {
2735
- state.initializationAttempts = attempt;
2736
- });
2737
- // Disconnect existing providers to close WebSocket connections
2738
- const existingProviders = Array.from(this.providers.values());
2739
- if (existingProviders.length > 0) {
2740
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Disconnecting existing providers', {
2741
- count: existingProviders.length,
2742
- timestamp: new Date().toISOString(),
2743
- });
2744
- await Promise.all(existingProviders.map((provider) => provider.disconnect()));
2745
- }
2746
- this.providers.clear();
2747
- await __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_cleanupStandaloneProvider).call(this);
2748
- const { activeProvider } = this.state;
2749
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Creating provider with HIP-3 configuration', {
2750
- hip3Enabled: __classPrivateFieldGet(this, _PerpsController_hip3Enabled, "f"),
2751
- hip3AllowlistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3AllowlistMarkets, "f"),
2752
- hip3BlocklistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3BlocklistMarkets, "f"),
2753
- hip3ConfigSource: __classPrivateFieldGet(this, _PerpsController_hip3ConfigSource, "f"),
2754
- isTestnet: this.state.isTestnet,
2755
- activeProvider,
2756
- });
2757
- // Always create HyperLiquid provider as the base provider
2758
- const hyperLiquidProvider = new HyperLiquidProvider_1.HyperLiquidProvider({
2759
- isTestnet: this.state.isTestnet,
2760
- hip3Enabled: __classPrivateFieldGet(this, _PerpsController_hip3Enabled, "f"),
2761
- allowlistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3AllowlistMarkets, "f"),
2762
- blocklistMarkets: __classPrivateFieldGet(this, _PerpsController_hip3BlocklistMarkets, "f"),
2763
- platformDependencies: __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure,
2764
- });
2765
- this.providers.set('hyperliquid', hyperLiquidProvider);
2766
- // Register MYX provider if enabled via feature flag
2767
- const isMYXEnabled = __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_isMYXProviderEnabled).call(this);
2768
- if (isMYXEnabled) {
2769
- const myxProvider = new MYXProvider_1.MYXProvider({
2770
- isTestnet: perpsConfig_1.PROVIDER_CONFIG.MYX_TESTNET_ONLY || this.state.isTestnet,
2771
- platformDependencies: __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure,
2772
- });
2773
- this.providers.set('myx', myxProvider);
2774
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: MYX provider registered', {
2775
- isTestnet: perpsConfig_1.PROVIDER_CONFIG.MYX_TESTNET_ONLY || this.state.isTestnet,
2776
- });
2777
- }
2778
- // Set up active provider based on activeProvider value in state
2779
- // 'aggregated' is treated as just another provider that wraps others
2780
- if (activeProvider === 'aggregated') {
2781
- // Aggregated mode: wrap in AggregatedPerpsProvider for multi-provider support
2782
- this.activeProviderInstance = new AggregatedPerpsProvider_1.AggregatedPerpsProvider({
2783
- providers: this.providers,
2784
- defaultProvider: 'hyperliquid',
2785
- infrastructure: __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure,
2786
- });
2787
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Using aggregated provider (multi-provider)', { registeredProviders: Array.from(this.providers.keys()) });
2788
- }
2789
- else if (activeProvider === 'hyperliquid') {
2790
- // Direct provider mode: use HyperLiquid provider directly
2791
- this.activeProviderInstance = hyperLiquidProvider;
2792
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, `PerpsController: Using direct provider (${activeProvider})`);
2793
- }
2794
- else if (activeProvider === 'myx') {
2795
- // MYX provider mode
2796
- const myxProvider = this.providers.get('myx');
2797
- if (myxProvider) {
2798
- this.activeProviderInstance = myxProvider;
2799
- }
2800
- else {
2801
- // MYX feature flag is disabled — fall back to HyperLiquid
2802
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: MYX provider not available (feature flag disabled), falling back to hyperliquid');
2803
- this.activeProviderInstance = hyperLiquidProvider;
2804
- this.update((state) => {
2805
- state.activeProvider = 'hyperliquid';
2806
- });
2807
- }
2808
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, `PerpsController: Using direct provider (${this.activeProviderInstance === hyperLiquidProvider ? 'hyperliquid' : activeProvider})`);
2809
- }
2810
- else {
2811
- // Unsupported provider - throw error to prevent silent misconfiguration
2812
- throw new Error(`Unsupported provider: ${String(activeProvider)}. Currently only 'hyperliquid', 'myx', and 'aggregated' are supported.`);
2813
- }
2814
- // Future providers can be added here with their own authentication patterns:
2815
- // - Some might use API keys: new BinanceProvider({ apiKey, apiSecret })
2816
- // - Some might use different wallet patterns: new GMXProvider({ signer })
2817
- // - Some might not need auth at all: new DydxProvider()
2818
- // Wait for WebSocket transport to be ready before marking as initialized
2819
- await (0, wait_1.wait)(perpsConfig_1.PERPS_CONSTANTS.ReconnectionCleanupDelayMs);
2820
- this.isInitialized = true;
2821
- this.update((state) => {
2822
- state.initializationState = InitializationState.Initialized;
2823
- state.initializationError = null;
2824
- });
2825
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Providers initialized successfully', {
2826
- providerCount: this.providers.size,
2827
- activeProvider,
2828
- timestamp: new Date().toISOString(),
2829
- attempts: attempt,
2830
- });
2831
- return; // Exit retry loop on success
2832
- }
2833
- catch (error) {
2834
- lastError = (0, errorUtils_1.ensureError)(error, 'PerpsController.performInitialization');
2835
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, lastError, __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'performInitialization', {
2836
- attempt,
2837
- maxAttempts,
2838
- }));
2839
- // If not the last attempt, wait before retrying (exponential backoff)
2840
- if (attempt < maxAttempts) {
2841
- const delay = baseDelay * Math.pow(2, attempt - 1); // 1s, 2s, 4s
2842
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, `PerpsController: Retrying initialization in ${delay}ms`, {
2843
- attempt,
2844
- maxAttempts,
2845
- error: lastError.message,
2846
- });
2847
- await (0, wait_1.wait)(delay);
2848
- }
2849
- }
2850
- }
2851
- this.isInitialized = false;
2852
- this.update((state) => {
2853
- state.initializationState = InitializationState.Failed;
2854
- state.initializationError = lastError?.message ?? 'Unknown error';
2855
- });
2856
- __classPrivateFieldSet(this, _PerpsController_initializationPromise, null, "f"); // Clear promise to allow retry
2857
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Initialization failed', {
2858
- error: lastError?.message,
2859
- attempts: maxAttempts,
2860
- timestamp: new Date().toISOString(),
2861
- });
2862
- }, _PerpsController_getErrorContext = function _PerpsController_getErrorContext(method, extra) {
2863
- return {
2864
- tags: {
2865
- feature: perpsConfig_1.PERPS_CONSTANTS.FeatureName,
2866
- provider: this.state.activeProvider,
2867
- network: this.state.isTestnet ? 'testnet' : 'mainnet',
2868
- },
2869
- context: {
2870
- name: 'PerpsController',
2871
- data: {
2872
- method,
2873
- ...extra,
2874
- },
2875
- },
2876
- };
2877
- }, _PerpsController_getControllerState = function _PerpsController_getControllerState() {
2878
- return this.state;
2879
- }, _PerpsController_createServiceContext = function _PerpsController_createServiceContext(method, additionalContext) {
2880
- return {
2881
- tracingContext: {
2882
- provider: this.state.activeProvider,
2883
- isTestnet: this.state.isTestnet,
2884
- },
2885
- errorContext: {
2886
- controller: 'PerpsController',
2887
- method,
2888
- },
2889
- stateManager: {
2890
- update: (updater) =>
2891
- // @ts-expect-error TS2589 - excessively deep instantiation when inferring stateManager from BaseController
2892
- this.update(updater),
2893
- getState: () => __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getControllerState).call(this),
2894
- },
2895
- ...additionalContext,
2896
- };
2897
- }, _PerpsController_ensureTradingServiceDeps = function _PerpsController_ensureTradingServiceDeps() {
2898
- __classPrivateFieldGet(this, _PerpsController_tradingService, "f").setControllerDependencies({
2899
- rewardsIntegrationService: __classPrivateFieldGet(this, _PerpsController_rewardsIntegrationService, "f"),
2900
- });
2901
- }, _PerpsController_performMarketDataPreload =
2902
- /**
2903
- * Perform a single market data preload (best-effort, no throw).
2904
- */
2905
- async function _PerpsController_performMarketDataPreload() {
2906
- if (__classPrivateFieldGet(this, _PerpsController_isPreloading, "f")) {
2907
- return;
2908
- }
2909
- const now = Date.now();
2910
- if (now - this.state.cachedMarketDataTimestamp <
2911
- __classPrivateFieldGet(_a, _a, "f", _PerpsController_preloadGuardMs)) {
2912
- return;
2913
- }
2914
- __classPrivateFieldSet(this, _PerpsController_isPreloading, true, "f");
2915
- const traceId = (0, uuid_1.v4)();
2916
- const preloadStart = performance.now();
2917
- let traceData;
2918
- try {
2919
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.trace({
2920
- name: types_1.PerpsTraceNames.MarketDataPreload,
2921
- id: traceId,
2922
- op: types_1.PerpsTraceOperations.Operation,
2923
- tags: {
2924
- provider: this.state.activeProvider,
2925
- isTestnet: this.state.isTestnet,
2926
- },
2927
- });
2928
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Fetching market data in background');
2929
- const data = await this.getMarketDataWithPrices({ standalone: true });
2930
- this.update((state) => {
2931
- state.cachedMarketData = data;
2932
- state.cachedMarketDataTimestamp = Date.now();
2933
- });
2934
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Market data preloaded', {
2935
- marketCount: data.length,
2936
- });
2937
- traceData = { success: true, marketCount: data.length };
2938
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.setMeasurement(performanceMetrics_1.PerpsMeasurementName.PerpsMarketDataPreload, performance.now() - preloadStart, 'millisecond');
2939
- // Also preload user data (fire-and-forget, non-blocking)
2940
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_performUserDataPreload).call(this).catch(() => {
2941
- /* fire-and-forget */
2942
- });
2943
- }
2944
- catch (error) {
2945
- traceData = {
2946
- success: false,
2947
- error: (0, errorUtils_1.ensureError)(error, 'PerpsController.performMarketDataPreload')
2948
- .message,
2949
- };
2950
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.performMarketDataPreload'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'performMarketDataPreload', {
2951
- message: 'Background preload failed',
2952
- }));
2953
- }
2954
- finally {
2955
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.endTrace({
2956
- name: types_1.PerpsTraceNames.MarketDataPreload,
2957
- id: traceId,
2958
- data: traceData,
2959
- });
2960
- __classPrivateFieldSet(this, _PerpsController_isPreloading, false, "f");
2961
- }
2962
- }, _PerpsController_performUserDataPreload =
2963
- /**
2964
- * Perform a single user data preload (best-effort, no throw).
2965
- * Fetches positions, open orders, and account state via lightweight REST calls.
2966
- */
2967
- async function _PerpsController_performUserDataPreload() {
2968
- if (__classPrivateFieldGet(this, _PerpsController_isPreloadingUserData, "f")) {
2969
- return;
2970
- }
2971
- // Get current user address
2972
- const evmAccount = (0, accountUtils_1.getSelectedEvmAccount)(__classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.controllers.accountTree);
2973
- if (!evmAccount?.address) {
2974
- return;
2975
- }
2976
- const userAddress = evmAccount.address;
2977
- // Skip if cache is fresh and for same account
2978
- const now = Date.now();
2979
- if (this.state.cachedUserDataAddress === userAddress &&
2980
- now - this.state.cachedUserDataTimestamp < __classPrivateFieldGet(_a, _a, "f", _PerpsController_preloadGuardMs)) {
2981
- return;
2982
- }
2983
- // Skip standalone REST polling when WebSocket is connected — live data is streaming
2984
- if (this.getWebSocketConnectionState() === types_1.WebSocketConnectionState.Connected) {
2985
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Skipping user data preload — WebSocket connected');
2986
- return;
2987
- }
2988
- __classPrivateFieldSet(this, _PerpsController_isPreloadingUserData, true, "f");
2989
- const traceId = (0, uuid_1.v4)();
2990
- const preloadStart = performance.now();
2991
- let traceData;
2992
- try {
2993
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.trace({
2994
- name: types_1.PerpsTraceNames.UserDataPreload,
2995
- id: traceId,
2996
- op: types_1.PerpsTraceOperations.Operation,
2997
- tags: {
2998
- provider: this.state.activeProvider,
2999
- isTestnet: this.state.isTestnet,
66
+ class PerpsController extends base_controller_1.BaseController {
67
+ /**
68
+ * Constructs a new {@link PerpsController}.
69
+ *
70
+ * @param args - The arguments to this controller.
71
+ * @param args.messenger - The messenger suited for this controller.
72
+ * @param args.state - The desired state with which to initialize this
73
+ * controller. Missing properties will be filled in with defaults.
74
+ */
75
+ constructor({ messenger, state, }) {
76
+ super({
77
+ messenger,
78
+ metadata: perpsControllerMetadata,
79
+ name: exports.controllerName,
80
+ state: {
81
+ ...getDefaultPerpsControllerState(),
82
+ ...state,
3000
83
  },
3001
- data: { userAddress },
3002
- });
3003
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: Fetching user data in background', {
3004
- userAddress,
3005
84
  });
3006
- const [positions, orders, accountState] = await Promise.all([
3007
- this.getPositions({ standalone: true, userAddress }),
3008
- this.getOpenOrders({ standalone: true, userAddress }),
3009
- this.getAccountState({ standalone: true, userAddress }),
3010
- ]);
3011
- this.update((state) => {
3012
- state.cachedPositions = positions;
3013
- state.cachedOrders = orders;
3014
- state.cachedAccountState = accountState;
3015
- state.cachedUserDataTimestamp = Date.now();
3016
- state.cachedUserDataAddress = userAddress;
3017
- });
3018
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_debugLog).call(this, 'PerpsController: User data preloaded', {
3019
- positionCount: positions.length,
3020
- orderCount: orders.length,
3021
- totalBalance: accountState.totalBalance,
3022
- });
3023
- traceData = {
3024
- success: true,
3025
- positionCount: positions.length,
3026
- orderCount: orders.length,
3027
- };
3028
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.setMeasurement(performanceMetrics_1.PerpsMeasurementName.PerpsUserDataPreload, performance.now() - preloadStart, 'millisecond');
3029
85
  }
3030
- catch (error) {
3031
- traceData = {
3032
- success: false,
3033
- error: (0, errorUtils_1.ensureError)(error, 'PerpsController.performUserDataPreload')
3034
- .message,
3035
- };
3036
- __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_logError).call(this, (0, errorUtils_1.ensureError)(error, 'PerpsController.performUserDataPreload'), __classPrivateFieldGet(this, _PerpsController_instances, "m", _PerpsController_getErrorContext).call(this, 'performUserDataPreload', {
3037
- message: 'Background user data preload failed',
3038
- }));
3039
- }
3040
- finally {
3041
- __classPrivateFieldGet(this, _PerpsController_options, "f").infrastructure.tracer.endTrace({
3042
- name: types_1.PerpsTraceNames.UserDataPreload,
3043
- id: traceId,
3044
- data: traceData,
3045
- });
3046
- __classPrivateFieldSet(this, _PerpsController_isPreloadingUserData, false, "f");
3047
- }
3048
- };
3049
- // ============================================================================
3050
- // Market Data Preload (client-agnostic background caching)
3051
- // ============================================================================
3052
- /** State paths that the preload stateChange handler reads. */
3053
- _PerpsController_preloadWatchedPaths = { value: new Set([
3054
- 'isTestnet',
3055
- 'hip3ConfigVersion',
3056
- ]) };
3057
- _PerpsController_preloadRefreshMs = { value: 5 * 60 * 1000 }; // 5 min
3058
- _PerpsController_preloadGuardMs = { value: 30000 }; // 30s debounce
86
+ }
87
+ exports.PerpsController = PerpsController;
3059
88
  //# sourceMappingURL=PerpsController.cjs.map