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

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