@metamask-previews/perps-controller 13.1.0-preview-8c2a2eeb2 → 13.1.0-preview-4f4c98e

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 (716) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/{PerpsController-method-action-types.d.mts → PerpsController-method-action-types.d.ts} +2 -2
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -0
  4. package/dist/{PerpsController-method-action-types.mjs → PerpsController-method-action-types.js} +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -0
  6. package/dist/{PerpsController.d.mts → PerpsController.d.ts} +17 -17
  7. package/dist/PerpsController.d.ts.map +1 -0
  8. package/dist/{PerpsController.mjs → PerpsController.js} +33 -31
  9. package/dist/PerpsController.js.map +1 -0
  10. package/dist/aggregation/{SubscriptionMultiplexer.d.cts → SubscriptionMultiplexer.d.ts} +2 -2
  11. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -0
  12. package/dist/aggregation/{SubscriptionMultiplexer.mjs → SubscriptionMultiplexer.js} +3 -3
  13. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -0
  14. package/dist/aggregation/index.d.ts +6 -0
  15. package/dist/aggregation/index.d.ts.map +1 -0
  16. package/dist/aggregation/index.js +5 -0
  17. package/dist/aggregation/index.js.map +1 -0
  18. package/dist/constants/{chartConfig.d.mts → chartConfig.d.ts} +34 -34
  19. package/dist/constants/chartConfig.d.ts.map +1 -0
  20. package/dist/constants/{chartConfig.mjs → chartConfig.js} +1 -1
  21. package/dist/constants/chartConfig.js.map +1 -0
  22. package/dist/constants/eventNames.d.ts +555 -0
  23. package/dist/constants/eventNames.d.ts.map +1 -0
  24. package/dist/constants/{eventNames.mjs → eventNames.js} +1 -1
  25. package/dist/constants/eventNames.js.map +1 -0
  26. package/dist/constants/{hyperLiquidConfig.d.cts → hyperLiquidConfig.d.ts} +12 -12
  27. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -0
  28. package/dist/constants/{hyperLiquidConfig.mjs → hyperLiquidConfig.js} +4 -4
  29. package/dist/constants/hyperLiquidConfig.js.map +1 -0
  30. package/dist/constants/index.d.ts +12 -0
  31. package/dist/constants/index.d.ts.map +1 -0
  32. package/dist/constants/index.js +12 -0
  33. package/dist/constants/index.js.map +1 -0
  34. package/dist/constants/{myxConfig.d.mts → myxConfig.d.ts} +9 -8
  35. package/dist/constants/myxConfig.d.ts.map +1 -0
  36. package/dist/constants/{myxConfig.mjs → myxConfig.js} +2 -2
  37. package/dist/constants/myxConfig.js.map +1 -0
  38. package/dist/constants/{orderTypes.d.cts → orderTypes.d.ts} +7 -7
  39. package/dist/constants/orderTypes.d.ts.map +1 -0
  40. package/dist/constants/{orderTypes.mjs → orderTypes.js} +1 -1
  41. package/dist/constants/orderTypes.js.map +1 -0
  42. package/dist/constants/{performanceMetrics.d.cts → performanceMetrics.d.ts} +1 -1
  43. package/dist/constants/performanceMetrics.d.ts.map +1 -0
  44. package/dist/constants/{performanceMetrics.mjs → performanceMetrics.js} +1 -1
  45. package/dist/constants/performanceMetrics.js.map +1 -0
  46. package/dist/constants/{perpsConfig.d.mts → perpsConfig.d.ts} +56 -56
  47. package/dist/constants/perpsConfig.d.ts.map +1 -0
  48. package/dist/constants/{perpsConfig.mjs → perpsConfig.js} +1 -1
  49. package/dist/constants/perpsConfig.js.map +1 -0
  50. package/dist/constants/{transactionsHistoryConfig.d.cts → transactionsHistoryConfig.d.ts} +1 -1
  51. package/dist/constants/transactionsHistoryConfig.d.ts.map +1 -0
  52. package/dist/constants/{transactionsHistoryConfig.mjs → transactionsHistoryConfig.js} +1 -1
  53. package/dist/constants/transactionsHistoryConfig.js.map +1 -0
  54. package/dist/{index.d.mts → index.d.ts} +64 -64
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/{index.mjs → index.js} +41 -41
  57. package/dist/index.js.map +1 -0
  58. package/dist/perpsErrorCodes.d.ts +104 -0
  59. package/dist/perpsErrorCodes.d.ts.map +1 -0
  60. package/dist/{perpsErrorCodes.mjs → perpsErrorCodes.js} +1 -1
  61. package/dist/perpsErrorCodes.js.map +1 -0
  62. package/dist/providers/{AggregatedPerpsProvider.d.cts → AggregatedPerpsProvider.d.ts} +5 -5
  63. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -0
  64. package/dist/providers/{AggregatedPerpsProvider.mjs → AggregatedPerpsProvider.js} +5 -5
  65. package/dist/providers/AggregatedPerpsProvider.js.map +1 -0
  66. package/dist/providers/{HyperLiquidProvider.d.mts → HyperLiquidProvider.d.ts} +7 -7
  67. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -0
  68. package/dist/providers/{HyperLiquidProvider.mjs → HyperLiquidProvider.js} +48 -50
  69. package/dist/providers/HyperLiquidProvider.js.map +1 -0
  70. package/dist/routing/{ProviderRouter.d.mts → ProviderRouter.d.ts} +2 -2
  71. package/dist/routing/ProviderRouter.d.ts.map +1 -0
  72. package/dist/routing/{ProviderRouter.mjs → ProviderRouter.js} +1 -1
  73. package/dist/routing/ProviderRouter.js.map +1 -0
  74. package/dist/routing/index.d.ts +6 -0
  75. package/dist/routing/index.d.ts.map +1 -0
  76. package/dist/routing/index.js +5 -0
  77. package/dist/routing/index.js.map +1 -0
  78. package/dist/{selectors.d.mts → selectors.d.ts} +97 -97
  79. package/dist/selectors.d.ts.map +1 -0
  80. package/dist/{selectors.mjs → selectors.js} +4 -4
  81. package/dist/selectors.js.map +1 -0
  82. package/dist/services/{AccountService.d.cts → AccountService.d.ts} +4 -4
  83. package/dist/services/AccountService.d.ts.map +1 -0
  84. package/dist/services/{AccountService.mjs → AccountService.js} +9 -9
  85. package/dist/services/AccountService.js.map +1 -0
  86. package/dist/services/{AggregatedOrderBookConnection.d.cts → AggregatedOrderBookConnection.d.ts} +2 -2
  87. package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -0
  88. package/dist/services/{AggregatedOrderBookConnection.mjs → AggregatedOrderBookConnection.js} +3 -3
  89. package/dist/services/AggregatedOrderBookConnection.js.map +1 -0
  90. package/dist/services/{DataLakeService.d.cts → DataLakeService.d.ts} +4 -4
  91. package/dist/services/DataLakeService.d.ts.map +1 -0
  92. package/dist/services/{DataLakeService.mjs → DataLakeService.js} +7 -7
  93. package/dist/services/DataLakeService.js.map +1 -0
  94. package/dist/services/{DepositService.d.cts → DepositService.d.ts} +4 -4
  95. package/dist/services/DepositService.d.ts.map +1 -0
  96. package/dist/services/{DepositService.mjs → DepositService.js} +7 -7
  97. package/dist/services/DepositService.js.map +1 -0
  98. package/dist/services/{DexDiscoveryCacheManager.d.cts → DexDiscoveryCacheManager.d.ts} +2 -2
  99. package/dist/services/DexDiscoveryCacheManager.d.ts.map +1 -0
  100. package/dist/services/{DexDiscoveryCacheManager.mjs → DexDiscoveryCacheManager.js} +2 -2
  101. package/dist/services/DexDiscoveryCacheManager.js.map +1 -0
  102. package/dist/services/{EligibilityService.d.cts → EligibilityService.d.ts} +2 -2
  103. package/dist/services/EligibilityService.d.ts.map +1 -0
  104. package/dist/services/{EligibilityService.mjs → EligibilityService.js} +3 -3
  105. package/dist/services/EligibilityService.js.map +1 -0
  106. package/dist/services/{FeatureFlagConfigurationService.d.cts → FeatureFlagConfigurationService.d.ts} +3 -3
  107. package/dist/services/FeatureFlagConfigurationService.d.ts.map +1 -0
  108. package/dist/services/{FeatureFlagConfigurationService.mjs → FeatureFlagConfigurationService.js} +7 -7
  109. package/dist/services/FeatureFlagConfigurationService.js.map +1 -0
  110. package/dist/services/{HyperLiquidClientService.d.cts → HyperLiquidClientService.d.ts} +10 -10
  111. package/dist/services/HyperLiquidClientService.d.ts.map +1 -0
  112. package/dist/services/{HyperLiquidClientService.mjs → HyperLiquidClientService.js} +11 -11
  113. package/dist/services/HyperLiquidClientService.js.map +1 -0
  114. package/dist/services/{HyperLiquidSubscriptionService.d.cts → HyperLiquidSubscriptionService.d.ts} +6 -6
  115. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -0
  116. package/dist/services/{HyperLiquidSubscriptionService.mjs → HyperLiquidSubscriptionService.js} +12 -12
  117. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -0
  118. package/dist/services/{HyperLiquidWalletService.d.cts → HyperLiquidWalletService.d.ts} +4 -4
  119. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -0
  120. package/dist/services/{HyperLiquidWalletService.mjs → HyperLiquidWalletService.js} +5 -5
  121. package/dist/services/HyperLiquidWalletService.js.map +1 -0
  122. package/dist/services/{MarketDataService.d.cts → MarketDataService.d.ts} +5 -5
  123. package/dist/services/MarketDataService.d.ts.map +1 -0
  124. package/dist/services/{MarketDataService.mjs → MarketDataService.js} +9 -9
  125. package/dist/services/MarketDataService.js.map +1 -0
  126. package/dist/services/{RewardsIntegrationService.d.cts → RewardsIntegrationService.d.ts} +3 -3
  127. package/dist/services/RewardsIntegrationService.d.ts.map +1 -0
  128. package/dist/services/{RewardsIntegrationService.mjs → RewardsIntegrationService.js} +6 -6
  129. package/dist/services/RewardsIntegrationService.js.map +1 -0
  130. package/dist/services/{ServiceContext.d.cts → ServiceContext.d.ts} +3 -3
  131. package/dist/services/ServiceContext.d.ts.map +1 -0
  132. package/dist/services/ServiceContext.js +2 -0
  133. package/dist/services/ServiceContext.js.map +1 -0
  134. package/dist/services/{TerminalMarketService.d.cts → TerminalMarketService.d.ts} +2 -2
  135. package/dist/services/TerminalMarketService.d.ts.map +1 -0
  136. package/dist/services/{TerminalMarketService.mjs → TerminalMarketService.js} +9 -9
  137. package/dist/services/TerminalMarketService.js.map +1 -0
  138. package/dist/services/{TradingReadinessCache.d.mts → TradingReadinessCache.d.ts} +1 -1
  139. package/dist/services/TradingReadinessCache.d.ts.map +1 -0
  140. package/dist/services/{TradingReadinessCache.mjs → TradingReadinessCache.js} +1 -1
  141. package/dist/services/TradingReadinessCache.js.map +1 -0
  142. package/dist/services/{TradingService.d.cts → TradingService.d.ts} +4 -4
  143. package/dist/services/TradingService.d.ts.map +1 -0
  144. package/dist/services/{TradingService.mjs → TradingService.js} +10 -10
  145. package/dist/services/TradingService.js.map +1 -0
  146. package/dist/types/{config.d.cts → config.d.ts} +2 -2
  147. package/dist/types/config.d.ts.map +1 -0
  148. package/dist/types/config.js +2 -0
  149. package/dist/types/config.js.map +1 -0
  150. package/dist/types/{hyperliquid-types.d.cts → hyperliquid-types.d.ts} +6 -6
  151. package/dist/types/hyperliquid-types.d.ts.map +1 -0
  152. package/dist/types/{hyperliquid-types.mjs → hyperliquid-types.js} +1 -1
  153. package/dist/types/hyperliquid-types.js.map +1 -0
  154. package/dist/types/{index.d.cts → index.d.ts} +41 -41
  155. package/dist/types/index.d.ts.map +1 -0
  156. package/dist/types/{index.mjs → index.js} +3 -3
  157. package/dist/types/index.js.map +1 -0
  158. package/dist/types/{messenger.d.mts → messenger.d.ts} +11 -11
  159. package/dist/types/messenger.d.ts.map +1 -0
  160. package/dist/types/messenger.js +2 -0
  161. package/dist/types/messenger.js.map +1 -0
  162. package/dist/types/{myx-types.d.mts → myx-types.d.ts} +16 -16
  163. package/dist/types/myx-types.d.ts.map +1 -0
  164. package/dist/types/{myx-types.mjs → myx-types.js} +3 -3
  165. package/dist/types/myx-types.js.map +1 -0
  166. package/dist/types/{perps-types.d.cts → perps-types.d.ts} +4 -4
  167. package/dist/types/perps-types.d.ts.map +1 -0
  168. package/dist/types/perps-types.js +2 -0
  169. package/dist/types/perps-types.js.map +1 -0
  170. package/dist/types/{token.d.cts → token.d.ts} +2 -2
  171. package/dist/types/token.d.ts.map +1 -0
  172. package/dist/types/token.js +2 -0
  173. package/dist/types/token.js.map +1 -0
  174. package/dist/types/{transactionTypes.d.cts → transactionTypes.d.ts} +1 -1
  175. package/dist/types/transactionTypes.d.ts.map +1 -0
  176. package/dist/types/{transactionTypes.mjs → transactionTypes.js} +2 -2
  177. package/dist/types/transactionTypes.js.map +1 -0
  178. package/dist/utils/{accountUtils.d.cts → accountUtils.d.ts} +4 -4
  179. package/dist/utils/accountUtils.d.ts.map +1 -0
  180. package/dist/utils/{accountUtils.mjs → accountUtils.js} +2 -2
  181. package/dist/utils/accountUtils.js.map +1 -0
  182. package/dist/utils/{capabilitySymbols.d.mts → capabilitySymbols.d.ts} +1 -1
  183. package/dist/utils/capabilitySymbols.d.ts.map +1 -0
  184. package/dist/utils/{capabilitySymbols.mjs → capabilitySymbols.js} +1 -1
  185. package/dist/utils/capabilitySymbols.js.map +1 -0
  186. package/dist/utils/{coalescePerpsRestRequest.d.cts → coalescePerpsRestRequest.d.ts} +1 -1
  187. package/dist/utils/coalescePerpsRestRequest.d.ts.map +1 -0
  188. package/dist/utils/{coalescePerpsRestRequest.mjs → coalescePerpsRestRequest.js} +2 -2
  189. package/dist/utils/coalescePerpsRestRequest.js.map +1 -0
  190. package/dist/utils/{errorUtils.d.mts → errorUtils.d.ts} +1 -1
  191. package/dist/utils/errorUtils.d.ts.map +1 -0
  192. package/dist/utils/{errorUtils.mjs → errorUtils.js} +3 -3
  193. package/dist/utils/errorUtils.js.map +1 -0
  194. package/dist/utils/{hyperLiquidAbstraction.d.cts → hyperLiquidAbstraction.d.ts} +2 -2
  195. package/dist/utils/hyperLiquidAbstraction.d.ts.map +1 -0
  196. package/dist/utils/{hyperLiquidAbstraction.mjs → hyperLiquidAbstraction.js} +1 -1
  197. package/dist/utils/hyperLiquidAbstraction.js.map +1 -0
  198. package/dist/utils/{hyperLiquidAdapter.d.cts → hyperLiquidAdapter.d.ts} +4 -4
  199. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -0
  200. package/dist/utils/{hyperLiquidAdapter.mjs → hyperLiquidAdapter.js} +9 -9
  201. package/dist/utils/hyperLiquidAdapter.js.map +1 -0
  202. package/dist/utils/{hyperLiquidOrderBookProcessor.d.mts → hyperLiquidOrderBookProcessor.d.ts} +3 -3
  203. package/dist/utils/hyperLiquidOrderBookProcessor.d.ts.map +1 -0
  204. package/dist/utils/{hyperLiquidOrderBookProcessor.mjs → hyperLiquidOrderBookProcessor.js} +1 -1
  205. package/dist/utils/hyperLiquidOrderBookProcessor.js.map +1 -0
  206. package/dist/utils/{hyperLiquidValidation.d.cts → hyperLiquidValidation.d.ts} +4 -4
  207. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -0
  208. package/dist/utils/{hyperLiquidValidation.mjs → hyperLiquidValidation.js} +6 -6
  209. package/dist/utils/hyperLiquidValidation.js.map +1 -0
  210. package/dist/utils/{idUtils.d.cts → idUtils.d.ts} +1 -1
  211. package/dist/utils/idUtils.d.ts.map +1 -0
  212. package/dist/utils/{idUtils.mjs → idUtils.js} +2 -2
  213. package/dist/utils/idUtils.js.map +1 -0
  214. package/dist/utils/index.d.ts +28 -0
  215. package/dist/utils/index.d.ts.map +1 -0
  216. package/dist/utils/{index.mjs → index.js} +21 -21
  217. package/dist/utils/index.js.map +1 -0
  218. package/dist/utils/{marketDataTransform.d.cts → marketDataTransform.d.ts} +3 -3
  219. package/dist/utils/marketDataTransform.d.ts.map +1 -0
  220. package/dist/utils/{marketDataTransform.mjs → marketDataTransform.js} +5 -5
  221. package/dist/utils/marketDataTransform.js.map +1 -0
  222. package/dist/utils/{marketSearch.d.cts → marketSearch.d.ts} +2 -2
  223. package/dist/utils/marketSearch.d.ts.map +1 -0
  224. package/dist/utils/{marketSearch.mjs → marketSearch.js} +1 -1
  225. package/dist/utils/marketSearch.js.map +1 -0
  226. package/dist/utils/{marketUtils.d.cts → marketUtils.d.ts} +3 -3
  227. package/dist/utils/marketUtils.d.ts.map +1 -0
  228. package/dist/utils/{marketUtils.mjs → marketUtils.js} +2 -2
  229. package/dist/utils/marketUtils.js.map +1 -0
  230. package/dist/utils/{myxAdapter.d.cts → myxAdapter.d.ts} +3 -3
  231. package/dist/utils/myxAdapter.d.ts.map +1 -0
  232. package/dist/utils/{myxAdapter.mjs → myxAdapter.js} +3 -3
  233. package/dist/utils/myxAdapter.js.map +1 -0
  234. package/dist/utils/{orderCalculations.d.cts → orderCalculations.d.ts} +4 -4
  235. package/dist/utils/orderCalculations.d.ts.map +1 -0
  236. package/dist/utils/{orderCalculations.mjs → orderCalculations.js} +6 -6
  237. package/dist/utils/orderCalculations.js.map +1 -0
  238. package/dist/utils/{orderTypes.d.mts → orderTypes.d.ts} +3 -3
  239. package/dist/utils/orderTypes.d.ts.map +1 -0
  240. package/dist/utils/{orderTypes.mjs → orderTypes.js} +1 -1
  241. package/dist/utils/orderTypes.js.map +1 -0
  242. package/dist/utils/{perpsConnectionAttemptContext.d.mts → perpsConnectionAttemptContext.d.ts} +1 -1
  243. package/dist/utils/perpsConnectionAttemptContext.d.ts.map +1 -0
  244. package/dist/utils/{perpsConnectionAttemptContext.mjs → perpsConnectionAttemptContext.js} +1 -1
  245. package/dist/utils/perpsConnectionAttemptContext.js.map +1 -0
  246. package/dist/utils/{perpsDiskPersistence.d.cts → perpsDiskPersistence.d.ts} +2 -2
  247. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -0
  248. package/dist/utils/{perpsDiskPersistence.mjs → perpsDiskPersistence.js} +2 -2
  249. package/dist/utils/perpsDiskPersistence.js.map +1 -0
  250. package/dist/utils/{perpsFormatters.d.cts → perpsFormatters.d.ts} +1 -1
  251. package/dist/utils/perpsFormatters.d.ts.map +1 -0
  252. package/dist/utils/{perpsFormatters.mjs → perpsFormatters.js} +2 -2
  253. package/dist/utils/perpsFormatters.js.map +1 -0
  254. package/dist/utils/{rewardsUtils.d.cts → rewardsUtils.d.ts} +4 -4
  255. package/dist/utils/rewardsUtils.d.ts.map +1 -0
  256. package/dist/utils/{rewardsUtils.mjs → rewardsUtils.js} +4 -4
  257. package/dist/utils/rewardsUtils.js.map +1 -0
  258. package/dist/utils/{significantFigures.d.cts → significantFigures.d.ts} +1 -1
  259. package/dist/utils/significantFigures.d.ts.map +1 -0
  260. package/dist/utils/{significantFigures.mjs → significantFigures.js} +2 -2
  261. package/dist/utils/significantFigures.js.map +1 -0
  262. package/dist/utils/{sortMarkets.d.cts → sortMarkets.d.ts} +2 -2
  263. package/dist/utils/sortMarkets.d.ts.map +1 -0
  264. package/dist/utils/{sortMarkets.mjs → sortMarkets.js} +2 -2
  265. package/dist/utils/sortMarkets.js.map +1 -0
  266. package/dist/utils/{standaloneInfoClient.d.cts → standaloneInfoClient.d.ts} +3 -3
  267. package/dist/utils/standaloneInfoClient.d.ts.map +1 -0
  268. package/dist/utils/{standaloneInfoClient.mjs → standaloneInfoClient.js} +3 -3
  269. package/dist/utils/standaloneInfoClient.js.map +1 -0
  270. package/dist/utils/{stringParseUtils.d.cts → stringParseUtils.d.ts} +1 -1
  271. package/dist/utils/stringParseUtils.d.ts.map +1 -0
  272. package/dist/utils/{stringParseUtils.mjs → stringParseUtils.js} +1 -1
  273. package/dist/utils/stringParseUtils.js.map +1 -0
  274. package/dist/utils/{transferData.d.cts → transferData.d.ts} +1 -1
  275. package/dist/utils/transferData.d.ts.map +1 -0
  276. package/dist/utils/{transferData.mjs → transferData.js} +3 -3
  277. package/dist/utils/transferData.js.map +1 -0
  278. package/dist/utils/{wait.d.cts → wait.d.ts} +1 -1
  279. package/dist/utils/wait.d.ts.map +1 -0
  280. package/dist/utils/{wait.mjs → wait.js} +1 -1
  281. package/dist/utils/wait.js.map +1 -0
  282. package/package.json +20 -48
  283. package/dist/PerpsController-method-action-types.cjs +0 -7
  284. package/dist/PerpsController-method-action-types.cjs.map +0 -1
  285. package/dist/PerpsController-method-action-types.d.cts +0 -1163
  286. package/dist/PerpsController-method-action-types.d.cts.map +0 -1
  287. package/dist/PerpsController-method-action-types.d.mts.map +0 -1
  288. package/dist/PerpsController-method-action-types.mjs.map +0 -1
  289. package/dist/PerpsController.cjs +0 -5063
  290. package/dist/PerpsController.cjs.map +0 -1
  291. package/dist/PerpsController.d.cts +0 -1274
  292. package/dist/PerpsController.d.cts.map +0 -1
  293. package/dist/PerpsController.d.mts.map +0 -1
  294. package/dist/PerpsController.mjs.map +0 -1
  295. package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -441
  296. package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
  297. package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
  298. package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -171
  299. package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
  300. package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
  301. package/dist/aggregation/index.cjs +0 -9
  302. package/dist/aggregation/index.cjs.map +0 -1
  303. package/dist/aggregation/index.d.cts +0 -6
  304. package/dist/aggregation/index.d.cts.map +0 -1
  305. package/dist/aggregation/index.d.mts +0 -6
  306. package/dist/aggregation/index.d.mts.map +0 -1
  307. package/dist/aggregation/index.mjs +0 -5
  308. package/dist/aggregation/index.mjs.map +0 -1
  309. package/dist/constants/chartConfig.cjs +0 -239
  310. package/dist/constants/chartConfig.cjs.map +0 -1
  311. package/dist/constants/chartConfig.d.cts +0 -228
  312. package/dist/constants/chartConfig.d.cts.map +0 -1
  313. package/dist/constants/chartConfig.d.mts.map +0 -1
  314. package/dist/constants/chartConfig.mjs.map +0 -1
  315. package/dist/constants/eventNames.cjs +0 -650
  316. package/dist/constants/eventNames.cjs.map +0 -1
  317. package/dist/constants/eventNames.d.cts +0 -555
  318. package/dist/constants/eventNames.d.cts.map +0 -1
  319. package/dist/constants/eventNames.d.mts +0 -555
  320. package/dist/constants/eventNames.d.mts.map +0 -1
  321. package/dist/constants/eventNames.mjs.map +0 -1
  322. package/dist/constants/hyperLiquidConfig.cjs +0 -607
  323. package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
  324. package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
  325. package/dist/constants/hyperLiquidConfig.d.mts +0 -280
  326. package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
  327. package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
  328. package/dist/constants/index.cjs +0 -28
  329. package/dist/constants/index.cjs.map +0 -1
  330. package/dist/constants/index.d.cts +0 -12
  331. package/dist/constants/index.d.cts.map +0 -1
  332. package/dist/constants/index.d.mts +0 -12
  333. package/dist/constants/index.d.mts.map +0 -1
  334. package/dist/constants/index.mjs +0 -12
  335. package/dist/constants/index.mjs.map +0 -1
  336. package/dist/constants/myxConfig.cjs +0 -253
  337. package/dist/constants/myxConfig.cjs.map +0 -1
  338. package/dist/constants/myxConfig.d.cts +0 -145
  339. package/dist/constants/myxConfig.d.cts.map +0 -1
  340. package/dist/constants/myxConfig.d.mts.map +0 -1
  341. package/dist/constants/myxConfig.mjs.map +0 -1
  342. package/dist/constants/orderTypes.cjs +0 -31
  343. package/dist/constants/orderTypes.cjs.map +0 -1
  344. package/dist/constants/orderTypes.d.cts.map +0 -1
  345. package/dist/constants/orderTypes.d.mts +0 -19
  346. package/dist/constants/orderTypes.d.mts.map +0 -1
  347. package/dist/constants/orderTypes.mjs.map +0 -1
  348. package/dist/constants/performanceMetrics.cjs +0 -63
  349. package/dist/constants/performanceMetrics.cjs.map +0 -1
  350. package/dist/constants/performanceMetrics.d.cts.map +0 -1
  351. package/dist/constants/performanceMetrics.d.mts +0 -46
  352. package/dist/constants/performanceMetrics.d.mts.map +0 -1
  353. package/dist/constants/performanceMetrics.mjs.map +0 -1
  354. package/dist/constants/perpsConfig.cjs +0 -553
  355. package/dist/constants/perpsConfig.cjs.map +0 -1
  356. package/dist/constants/perpsConfig.d.cts +0 -474
  357. package/dist/constants/perpsConfig.d.cts.map +0 -1
  358. package/dist/constants/perpsConfig.d.mts.map +0 -1
  359. package/dist/constants/perpsConfig.mjs.map +0 -1
  360. package/dist/constants/transactionsHistoryConfig.cjs +0 -38
  361. package/dist/constants/transactionsHistoryConfig.cjs.map +0 -1
  362. package/dist/constants/transactionsHistoryConfig.d.cts.map +0 -1
  363. package/dist/constants/transactionsHistoryConfig.d.mts +0 -35
  364. package/dist/constants/transactionsHistoryConfig.d.mts.map +0 -1
  365. package/dist/constants/transactionsHistoryConfig.mjs.map +0 -1
  366. package/dist/index.cjs +0 -344
  367. package/dist/index.cjs.map +0 -1
  368. package/dist/index.d.cts +0 -92
  369. package/dist/index.d.cts.map +0 -1
  370. package/dist/index.d.mts.map +0 -1
  371. package/dist/index.mjs.map +0 -1
  372. package/dist/perpsErrorCodes.cjs +0 -127
  373. package/dist/perpsErrorCodes.cjs.map +0 -1
  374. package/dist/perpsErrorCodes.d.cts +0 -104
  375. package/dist/perpsErrorCodes.d.cts.map +0 -1
  376. package/dist/perpsErrorCodes.d.mts +0 -104
  377. package/dist/perpsErrorCodes.d.mts.map +0 -1
  378. package/dist/perpsErrorCodes.mjs.map +0 -1
  379. package/dist/providers/AggregatedPerpsProvider.cjs +0 -689
  380. package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
  381. package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
  382. package/dist/providers/AggregatedPerpsProvider.d.mts +0 -232
  383. package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
  384. package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
  385. package/dist/providers/HyperLiquidProvider.cjs +0 -10416
  386. package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
  387. package/dist/providers/HyperLiquidProvider.d.cts +0 -625
  388. package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
  389. package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
  390. package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
  391. package/dist/routing/ProviderRouter.cjs +0 -154
  392. package/dist/routing/ProviderRouter.cjs.map +0 -1
  393. package/dist/routing/ProviderRouter.d.cts +0 -112
  394. package/dist/routing/ProviderRouter.d.cts.map +0 -1
  395. package/dist/routing/ProviderRouter.d.mts.map +0 -1
  396. package/dist/routing/ProviderRouter.mjs.map +0 -1
  397. package/dist/routing/index.cjs +0 -9
  398. package/dist/routing/index.cjs.map +0 -1
  399. package/dist/routing/index.d.cts +0 -6
  400. package/dist/routing/index.d.cts.map +0 -1
  401. package/dist/routing/index.d.mts +0 -6
  402. package/dist/routing/index.d.mts.map +0 -1
  403. package/dist/routing/index.mjs +0 -5
  404. package/dist/routing/index.mjs.map +0 -1
  405. package/dist/selectors.cjs +0 -264
  406. package/dist/selectors.cjs.map +0 -1
  407. package/dist/selectors.d.cts +0 -336
  408. package/dist/selectors.d.cts.map +0 -1
  409. package/dist/selectors.d.mts.map +0 -1
  410. package/dist/selectors.mjs.map +0 -1
  411. package/dist/services/AccountService.cjs +0 -324
  412. package/dist/services/AccountService.cjs.map +0 -1
  413. package/dist/services/AccountService.d.cts.map +0 -1
  414. package/dist/services/AccountService.d.mts +0 -56
  415. package/dist/services/AccountService.d.mts.map +0 -1
  416. package/dist/services/AccountService.mjs.map +0 -1
  417. package/dist/services/AggregatedOrderBookConnection.cjs +0 -405
  418. package/dist/services/AggregatedOrderBookConnection.cjs.map +0 -1
  419. package/dist/services/AggregatedOrderBookConnection.d.cts.map +0 -1
  420. package/dist/services/AggregatedOrderBookConnection.d.mts +0 -106
  421. package/dist/services/AggregatedOrderBookConnection.d.mts.map +0 -1
  422. package/dist/services/AggregatedOrderBookConnection.mjs.map +0 -1
  423. package/dist/services/DataLakeService.cjs +0 -233
  424. package/dist/services/DataLakeService.cjs.map +0 -1
  425. package/dist/services/DataLakeService.d.cts.map +0 -1
  426. package/dist/services/DataLakeService.d.mts +0 -51
  427. package/dist/services/DataLakeService.d.mts.map +0 -1
  428. package/dist/services/DataLakeService.mjs.map +0 -1
  429. package/dist/services/DepositService.cjs +0 -99
  430. package/dist/services/DepositService.cjs.map +0 -1
  431. package/dist/services/DepositService.d.cts.map +0 -1
  432. package/dist/services/DepositService.d.mts +0 -39
  433. package/dist/services/DepositService.d.mts.map +0 -1
  434. package/dist/services/DepositService.mjs.map +0 -1
  435. package/dist/services/DexDiscoveryCacheManager.cjs +0 -147
  436. package/dist/services/DexDiscoveryCacheManager.cjs.map +0 -1
  437. package/dist/services/DexDiscoveryCacheManager.d.cts.map +0 -1
  438. package/dist/services/DexDiscoveryCacheManager.d.mts +0 -52
  439. package/dist/services/DexDiscoveryCacheManager.d.mts.map +0 -1
  440. package/dist/services/DexDiscoveryCacheManager.mjs.map +0 -1
  441. package/dist/services/EligibilityService.cjs +0 -78
  442. package/dist/services/EligibilityService.cjs.map +0 -1
  443. package/dist/services/EligibilityService.d.cts.map +0 -1
  444. package/dist/services/EligibilityService.d.mts +0 -28
  445. package/dist/services/EligibilityService.d.mts.map +0 -1
  446. package/dist/services/EligibilityService.mjs.map +0 -1
  447. package/dist/services/FeatureFlagConfigurationService.cjs +0 -257
  448. package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
  449. package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
  450. package/dist/services/FeatureFlagConfigurationService.d.mts +0 -73
  451. package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
  452. package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
  453. package/dist/services/HyperLiquidClientService.cjs +0 -1045
  454. package/dist/services/HyperLiquidClientService.cjs.map +0 -1
  455. package/dist/services/HyperLiquidClientService.d.cts.map +0 -1
  456. package/dist/services/HyperLiquidClientService.d.mts +0 -239
  457. package/dist/services/HyperLiquidClientService.d.mts.map +0 -1
  458. package/dist/services/HyperLiquidClientService.mjs.map +0 -1
  459. package/dist/services/HyperLiquidSubscriptionService.cjs +0 -3196
  460. package/dist/services/HyperLiquidSubscriptionService.cjs.map +0 -1
  461. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +0 -1
  462. package/dist/services/HyperLiquidSubscriptionService.d.mts +0 -227
  463. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +0 -1
  464. package/dist/services/HyperLiquidSubscriptionService.mjs.map +0 -1
  465. package/dist/services/HyperLiquidWalletService.cjs +0 -186
  466. package/dist/services/HyperLiquidWalletService.cjs.map +0 -1
  467. package/dist/services/HyperLiquidWalletService.d.cts.map +0 -1
  468. package/dist/services/HyperLiquidWalletService.d.mts +0 -84
  469. package/dist/services/HyperLiquidWalletService.d.mts.map +0 -1
  470. package/dist/services/HyperLiquidWalletService.mjs.map +0 -1
  471. package/dist/services/MarketDataService.cjs +0 -1138
  472. package/dist/services/MarketDataService.cjs.map +0 -1
  473. package/dist/services/MarketDataService.d.cts.map +0 -1
  474. package/dist/services/MarketDataService.d.mts +0 -334
  475. package/dist/services/MarketDataService.d.mts.map +0 -1
  476. package/dist/services/MarketDataService.mjs.map +0 -1
  477. package/dist/services/RewardsIntegrationService.cjs +0 -391
  478. package/dist/services/RewardsIntegrationService.cjs.map +0 -1
  479. package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
  480. package/dist/services/RewardsIntegrationService.d.mts +0 -84
  481. package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
  482. package/dist/services/RewardsIntegrationService.mjs.map +0 -1
  483. package/dist/services/ServiceContext.cjs +0 -3
  484. package/dist/services/ServiceContext.cjs.map +0 -1
  485. package/dist/services/ServiceContext.d.cts.map +0 -1
  486. package/dist/services/ServiceContext.d.mts +0 -102
  487. package/dist/services/ServiceContext.d.mts.map +0 -1
  488. package/dist/services/ServiceContext.mjs +0 -2
  489. package/dist/services/ServiceContext.mjs.map +0 -1
  490. package/dist/services/TerminalMarketService.cjs +0 -623
  491. package/dist/services/TerminalMarketService.cjs.map +0 -1
  492. package/dist/services/TerminalMarketService.d.cts.map +0 -1
  493. package/dist/services/TerminalMarketService.d.mts +0 -45
  494. package/dist/services/TerminalMarketService.d.mts.map +0 -1
  495. package/dist/services/TerminalMarketService.mjs.map +0 -1
  496. package/dist/services/TradingReadinessCache.cjs +0 -329
  497. package/dist/services/TradingReadinessCache.cjs.map +0 -1
  498. package/dist/services/TradingReadinessCache.d.cts +0 -204
  499. package/dist/services/TradingReadinessCache.d.cts.map +0 -1
  500. package/dist/services/TradingReadinessCache.d.mts.map +0 -1
  501. package/dist/services/TradingReadinessCache.mjs.map +0 -1
  502. package/dist/services/TradingService.cjs +0 -1865
  503. package/dist/services/TradingService.cjs.map +0 -1
  504. package/dist/services/TradingService.d.cts.map +0 -1
  505. package/dist/services/TradingService.d.mts +0 -201
  506. package/dist/services/TradingService.d.mts.map +0 -1
  507. package/dist/services/TradingService.mjs.map +0 -1
  508. package/dist/types/config.cjs +0 -3
  509. package/dist/types/config.cjs.map +0 -1
  510. package/dist/types/config.d.cts.map +0 -1
  511. package/dist/types/config.d.mts +0 -49
  512. package/dist/types/config.d.mts.map +0 -1
  513. package/dist/types/config.mjs +0 -2
  514. package/dist/types/config.mjs.map +0 -1
  515. package/dist/types/hyperliquid-types.cjs +0 -45
  516. package/dist/types/hyperliquid-types.cjs.map +0 -1
  517. package/dist/types/hyperliquid-types.d.cts.map +0 -1
  518. package/dist/types/hyperliquid-types.d.mts +0 -67
  519. package/dist/types/hyperliquid-types.d.mts.map +0 -1
  520. package/dist/types/hyperliquid-types.mjs.map +0 -1
  521. package/dist/types/index.cjs +0 -151
  522. package/dist/types/index.cjs.map +0 -1
  523. package/dist/types/index.d.cts.map +0 -1
  524. package/dist/types/index.d.mts +0 -1951
  525. package/dist/types/index.d.mts.map +0 -1
  526. package/dist/types/index.mjs.map +0 -1
  527. package/dist/types/messenger.cjs +0 -3
  528. package/dist/types/messenger.cjs.map +0 -1
  529. package/dist/types/messenger.d.cts +0 -30
  530. package/dist/types/messenger.d.cts.map +0 -1
  531. package/dist/types/messenger.d.mts.map +0 -1
  532. package/dist/types/messenger.mjs +0 -2
  533. package/dist/types/messenger.mjs.map +0 -1
  534. package/dist/types/myx-types.cjs +0 -41
  535. package/dist/types/myx-types.cjs.map +0 -1
  536. package/dist/types/myx-types.d.cts +0 -94
  537. package/dist/types/myx-types.d.cts.map +0 -1
  538. package/dist/types/myx-types.d.mts.map +0 -1
  539. package/dist/types/myx-types.mjs.map +0 -1
  540. package/dist/types/perps-types.cjs +0 -7
  541. package/dist/types/perps-types.cjs.map +0 -1
  542. package/dist/types/perps-types.d.cts.map +0 -1
  543. package/dist/types/perps-types.d.mts +0 -184
  544. package/dist/types/perps-types.d.mts.map +0 -1
  545. package/dist/types/perps-types.mjs +0 -5
  546. package/dist/types/perps-types.mjs.map +0 -1
  547. package/dist/types/token.cjs +0 -3
  548. package/dist/types/token.cjs.map +0 -1
  549. package/dist/types/token.d.cts.map +0 -1
  550. package/dist/types/token.d.mts +0 -25
  551. package/dist/types/token.d.mts.map +0 -1
  552. package/dist/types/token.mjs +0 -2
  553. package/dist/types/token.mjs.map +0 -1
  554. package/dist/types/transactionTypes.cjs +0 -29
  555. package/dist/types/transactionTypes.cjs.map +0 -1
  556. package/dist/types/transactionTypes.d.cts.map +0 -1
  557. package/dist/types/transactionTypes.d.mts +0 -60
  558. package/dist/types/transactionTypes.d.mts.map +0 -1
  559. package/dist/types/transactionTypes.mjs.map +0 -1
  560. package/dist/utils/accountUtils.cjs +0 -236
  561. package/dist/utils/accountUtils.cjs.map +0 -1
  562. package/dist/utils/accountUtils.d.cts.map +0 -1
  563. package/dist/utils/accountUtils.d.mts +0 -72
  564. package/dist/utils/accountUtils.d.mts.map +0 -1
  565. package/dist/utils/accountUtils.mjs.map +0 -1
  566. package/dist/utils/capabilitySymbols.cjs +0 -25
  567. package/dist/utils/capabilitySymbols.cjs.map +0 -1
  568. package/dist/utils/capabilitySymbols.d.cts +0 -15
  569. package/dist/utils/capabilitySymbols.d.cts.map +0 -1
  570. package/dist/utils/capabilitySymbols.d.mts.map +0 -1
  571. package/dist/utils/capabilitySymbols.mjs.map +0 -1
  572. package/dist/utils/coalescePerpsRestRequest.cjs +0 -71
  573. package/dist/utils/coalescePerpsRestRequest.cjs.map +0 -1
  574. package/dist/utils/coalescePerpsRestRequest.d.cts.map +0 -1
  575. package/dist/utils/coalescePerpsRestRequest.d.mts +0 -32
  576. package/dist/utils/coalescePerpsRestRequest.d.mts.map +0 -1
  577. package/dist/utils/coalescePerpsRestRequest.mjs.map +0 -1
  578. package/dist/utils/errorUtils.cjs +0 -104
  579. package/dist/utils/errorUtils.cjs.map +0 -1
  580. package/dist/utils/errorUtils.d.cts +0 -50
  581. package/dist/utils/errorUtils.d.cts.map +0 -1
  582. package/dist/utils/errorUtils.d.mts.map +0 -1
  583. package/dist/utils/errorUtils.mjs.map +0 -1
  584. package/dist/utils/hyperLiquidAbstraction.cjs +0 -23
  585. package/dist/utils/hyperLiquidAbstraction.cjs.map +0 -1
  586. package/dist/utils/hyperLiquidAbstraction.d.cts.map +0 -1
  587. package/dist/utils/hyperLiquidAbstraction.d.mts +0 -11
  588. package/dist/utils/hyperLiquidAbstraction.d.mts.map +0 -1
  589. package/dist/utils/hyperLiquidAbstraction.mjs.map +0 -1
  590. package/dist/utils/hyperLiquidAdapter.cjs +0 -512
  591. package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
  592. package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
  593. package/dist/utils/hyperLiquidAdapter.d.mts +0 -77
  594. package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
  595. package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
  596. package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -83
  597. package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
  598. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -55
  599. package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
  600. package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
  601. package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +0 -1
  602. package/dist/utils/hyperLiquidValidation.cjs +0 -799
  603. package/dist/utils/hyperLiquidValidation.cjs.map +0 -1
  604. package/dist/utils/hyperLiquidValidation.d.cts.map +0 -1
  605. package/dist/utils/hyperLiquidValidation.d.mts +0 -192
  606. package/dist/utils/hyperLiquidValidation.d.mts.map +0 -1
  607. package/dist/utils/hyperLiquidValidation.mjs.map +0 -1
  608. package/dist/utils/idUtils.cjs +0 -18
  609. package/dist/utils/idUtils.cjs.map +0 -1
  610. package/dist/utils/idUtils.d.cts.map +0 -1
  611. package/dist/utils/idUtils.d.mts +0 -6
  612. package/dist/utils/idUtils.d.mts.map +0 -1
  613. package/dist/utils/idUtils.mjs.map +0 -1
  614. package/dist/utils/index.cjs +0 -65
  615. package/dist/utils/index.cjs.map +0 -1
  616. package/dist/utils/index.d.cts +0 -28
  617. package/dist/utils/index.d.cts.map +0 -1
  618. package/dist/utils/index.d.mts +0 -28
  619. package/dist/utils/index.d.mts.map +0 -1
  620. package/dist/utils/index.mjs.map +0 -1
  621. package/dist/utils/marketDataTransform.cjs +0 -250
  622. package/dist/utils/marketDataTransform.cjs.map +0 -1
  623. package/dist/utils/marketDataTransform.d.cts.map +0 -1
  624. package/dist/utils/marketDataTransform.d.mts +0 -71
  625. package/dist/utils/marketDataTransform.d.mts.map +0 -1
  626. package/dist/utils/marketDataTransform.mjs.map +0 -1
  627. package/dist/utils/marketSearch.cjs +0 -111
  628. package/dist/utils/marketSearch.cjs.map +0 -1
  629. package/dist/utils/marketSearch.d.cts.map +0 -1
  630. package/dist/utils/marketSearch.d.mts +0 -48
  631. package/dist/utils/marketSearch.d.mts.map +0 -1
  632. package/dist/utils/marketSearch.mjs.map +0 -1
  633. package/dist/utils/marketUtils.cjs +0 -266
  634. package/dist/utils/marketUtils.cjs.map +0 -1
  635. package/dist/utils/marketUtils.d.cts.map +0 -1
  636. package/dist/utils/marketUtils.d.mts +0 -73
  637. package/dist/utils/marketUtils.d.mts.map +0 -1
  638. package/dist/utils/marketUtils.mjs.map +0 -1
  639. package/dist/utils/myxAdapter.cjs +0 -569
  640. package/dist/utils/myxAdapter.cjs.map +0 -1
  641. package/dist/utils/myxAdapter.d.cts.map +0 -1
  642. package/dist/utils/myxAdapter.d.mts +0 -168
  643. package/dist/utils/myxAdapter.d.mts.map +0 -1
  644. package/dist/utils/myxAdapter.mjs.map +0 -1
  645. package/dist/utils/orderCalculations.cjs +0 -823
  646. package/dist/utils/orderCalculations.cjs.map +0 -1
  647. package/dist/utils/orderCalculations.d.cts.map +0 -1
  648. package/dist/utils/orderCalculations.d.mts +0 -298
  649. package/dist/utils/orderCalculations.d.mts.map +0 -1
  650. package/dist/utils/orderCalculations.mjs.map +0 -1
  651. package/dist/utils/orderTypes.cjs +0 -301
  652. package/dist/utils/orderTypes.cjs.map +0 -1
  653. package/dist/utils/orderTypes.d.cts +0 -166
  654. package/dist/utils/orderTypes.d.cts.map +0 -1
  655. package/dist/utils/orderTypes.d.mts.map +0 -1
  656. package/dist/utils/orderTypes.mjs.map +0 -1
  657. package/dist/utils/perpsConnectionAttemptContext.cjs +0 -20
  658. package/dist/utils/perpsConnectionAttemptContext.cjs.map +0 -1
  659. package/dist/utils/perpsConnectionAttemptContext.d.cts +0 -7
  660. package/dist/utils/perpsConnectionAttemptContext.d.cts.map +0 -1
  661. package/dist/utils/perpsConnectionAttemptContext.d.mts.map +0 -1
  662. package/dist/utils/perpsConnectionAttemptContext.mjs.map +0 -1
  663. package/dist/utils/perpsDiskPersistence.cjs +0 -259
  664. package/dist/utils/perpsDiskPersistence.cjs.map +0 -1
  665. package/dist/utils/perpsDiskPersistence.d.cts.map +0 -1
  666. package/dist/utils/perpsDiskPersistence.d.mts +0 -112
  667. package/dist/utils/perpsDiskPersistence.d.mts.map +0 -1
  668. package/dist/utils/perpsDiskPersistence.mjs.map +0 -1
  669. package/dist/utils/perpsFormatters.cjs +0 -509
  670. package/dist/utils/perpsFormatters.cjs.map +0 -1
  671. package/dist/utils/perpsFormatters.d.cts.map +0 -1
  672. package/dist/utils/perpsFormatters.d.mts +0 -204
  673. package/dist/utils/perpsFormatters.d.mts.map +0 -1
  674. package/dist/utils/perpsFormatters.mjs.map +0 -1
  675. package/dist/utils/rewardsUtils.cjs +0 -98
  676. package/dist/utils/rewardsUtils.cjs.map +0 -1
  677. package/dist/utils/rewardsUtils.d.cts.map +0 -1
  678. package/dist/utils/rewardsUtils.d.mts +0 -33
  679. package/dist/utils/rewardsUtils.d.mts.map +0 -1
  680. package/dist/utils/rewardsUtils.mjs.map +0 -1
  681. package/dist/utils/significantFigures.cjs +0 -88
  682. package/dist/utils/significantFigures.cjs.map +0 -1
  683. package/dist/utils/significantFigures.d.cts.map +0 -1
  684. package/dist/utils/significantFigures.d.mts +0 -25
  685. package/dist/utils/significantFigures.d.mts.map +0 -1
  686. package/dist/utils/significantFigures.mjs.map +0 -1
  687. package/dist/utils/sortMarkets.cjs +0 -93
  688. package/dist/utils/sortMarkets.cjs.map +0 -1
  689. package/dist/utils/sortMarkets.d.cts.map +0 -1
  690. package/dist/utils/sortMarkets.d.mts +0 -25
  691. package/dist/utils/sortMarkets.d.mts.map +0 -1
  692. package/dist/utils/sortMarkets.mjs.map +0 -1
  693. package/dist/utils/standaloneInfoClient.cjs +0 -70
  694. package/dist/utils/standaloneInfoClient.cjs.map +0 -1
  695. package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
  696. package/dist/utils/standaloneInfoClient.d.mts +0 -37
  697. package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
  698. package/dist/utils/standaloneInfoClient.mjs.map +0 -1
  699. package/dist/utils/stringParseUtils.cjs +0 -34
  700. package/dist/utils/stringParseUtils.cjs.map +0 -1
  701. package/dist/utils/stringParseUtils.d.cts.map +0 -1
  702. package/dist/utils/stringParseUtils.d.mts +0 -11
  703. package/dist/utils/stringParseUtils.d.mts.map +0 -1
  704. package/dist/utils/stringParseUtils.mjs.map +0 -1
  705. package/dist/utils/transferData.cjs +0 -33
  706. package/dist/utils/transferData.cjs.map +0 -1
  707. package/dist/utils/transferData.d.cts.map +0 -1
  708. package/dist/utils/transferData.d.mts +0 -9
  709. package/dist/utils/transferData.d.mts.map +0 -1
  710. package/dist/utils/transferData.mjs.map +0 -1
  711. package/dist/utils/wait.cjs +0 -6
  712. package/dist/utils/wait.cjs.map +0 -1
  713. package/dist/utils/wait.d.cts.map +0 -1
  714. package/dist/utils/wait.d.mts +0 -2
  715. package/dist/utils/wait.d.mts.map +0 -1
  716. package/dist/utils/wait.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"myxAdapter.js","sourceRoot":"","sources":["../../src/utils/myxAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,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AE,IAAI,CAAC,CAAC;QACb,MAAM,EAAE,IAAI,CAAC,CAAC;KACf,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,+BAA+B,GAA2B;IAC9D,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI,EAAE,iBAAiB;IAC7B,IAAI,EAAE,IAAI;IACV,KAAK,EAAE,KAAK;IACZ,KAAK,EAAE,KAAK;IACZ,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI,EAAE,iBAAiB;IAC7B,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI,EAAE,iBAAiB;IAC7B,KAAK,EAAE,IAAI,EAAE,kBAAkB;IAC/B,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI,EAAE,iBAAiB;IAC7B,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;CACX,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAc;IACjD,OAAO,+BAA+B,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC;AACzD,CAAC;AAED,+EAA+E;AAC/E,sBAAsB;AACtB,+EAA+E;AAE/E;;;;;;;;GAQG;AACH,MAAM,UAAU,gBAAgB,CAC9B,QAAmD,EACnD,OAAe;IAEf,IAAI,QAAQ,CAAC,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CACb,OAAO,OAAO,iBAAiB,QAAQ,CAAC,IAAI,YAAY,QAAQ,CAAC,OAAO,IAAI,SAAS,EAAE,CACxF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * MYX SDK Adapter Utilities\n *\n * Adapters for transforming between MetaMask Perps API types and MYX SDK types.\n * Includes adapters for market display, positions, orders, account state, and fills.\n *\n * Portable: no mobile-specific imports.\n * Formatters are injected via MarketDataFormatters interface (same pattern as marketDataTransform.ts).\n *\n * Key differences from HyperLiquid:\n * - API prices are normal floats (SDK contract layer uses 30 decimals internally)\n * - Sizes use 18 decimals (vs HyperLiquid's szDecimals per asset)\n * - Multiple pools can exist per symbol (MPM model)\n * - USDT collateral (vs USDC)\n */\n\nimport {\n fromMYXPrice,\n fromMYXSize,\n fromMYXCollateral,\n MYX_MAX_LEVERAGE,\n MYX_MINIMUM_ORDER_SIZE_USD,\n} from '../constants/myxConfig.js';\nimport type {\n AccountState,\n CandleStick,\n Funding,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n MarketDataFormatters,\n UserHistoryItem,\n} from '../types/index.js';\nimport {\n MYX_HL_OVERLAPPING_MARKETS,\n MYXDirection,\n MYXDirectionEnum,\n MYXOperationEnum,\n MYXOrderStatusEnum,\n MYXOrderTypeEnum,\n MYXExecTypeEnum,\n MYXTradeFlowTypeEnum,\n} from '../types/myx-types.js';\nimport type {\n MYXPoolSymbol,\n MYXTicker,\n MYXPositionType,\n MYXHistoryOrderItem,\n MYXTradeFlowItem,\n MYXKlineData,\n MYXKlineWsData,\n} from '../types/myx-types.js';\n\n/**\n * Format a price change value with sign prefix.\n * Uses injected formatters (same pattern as marketDataTransform.ts formatChange).\n *\n * @param change - The price change value to format.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns The formatted change string with sign and dollar symbol.\n */\nfunction formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change)) {\n return '$0.00';\n }\n if (change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n\n// ============================================================================\n// Market Transformation\n// ============================================================================\n\n/**\n * Transform MYX Pool/Market info to MetaMask Perps API MarketInfo format\n *\n * @param pool - Pool symbol data from MYX SDK (PoolSymbolAllResponse)\n * @returns MetaMask Perps API market info object\n */\nexport function adaptMarketFromMYX(pool: MYXPoolSymbol): MarketInfo {\n // Extract base symbol from pool data\n const symbol = pool.baseSymbol || extractSymbolFromPoolId(pool.poolId);\n\n // MYX uses fixed 18 decimals for sizes\n const szDecimals = 18;\n\n return {\n name: symbol,\n szDecimals,\n maxLeverage: MYX_MAX_LEVERAGE,\n marginTableId: 0, // MYX doesn't use margin tables like HyperLiquid\n minimumOrderSize: MYX_MINIMUM_ORDER_SIZE_USD,\n providerId: 'myx',\n };\n}\n\n/**\n * Convert MYX ticker data to price and change values\n *\n * @param ticker - Ticker data from MYX SDK\n * @returns Object with price string and 24h change percentage\n */\nexport function adaptPriceFromMYX(ticker: MYXTicker): {\n price: string;\n change24h: number;\n} {\n // MYX API returns normal float strings (e.g. \"64854.76\")\n const priceNum = fromMYXPrice(ticker.price);\n\n // Change is provided as a percentage string (e.g., \"2.5\" means 2.5%)\n const change24h = ticker.change ? parseFloat(ticker.change) : 0;\n\n return {\n price: priceNum.toString(),\n change24h,\n };\n}\n\n/**\n * Transform MYX pool and ticker to PerpsMarketData for UI display\n *\n * @param pool - Pool symbol data from MYX SDK\n * @param ticker - Optional ticker data for price info\n * @param formatters - Injectable formatters for platform-agnostic formatting\n * @returns Formatted market data for UI display\n */\nexport function adaptMarketDataFromMYX(\n pool: MYXPoolSymbol,\n ticker: MYXTicker | undefined,\n formatters: MarketDataFormatters,\n): PerpsMarketData {\n const symbol = pool.baseSymbol || extractSymbolFromPoolId(pool.poolId);\n\n // Get price data from ticker if available\n let price = '0';\n let change24h = 0;\n let volume = '0';\n\n if (ticker) {\n const priceData = adaptPriceFromMYX(ticker);\n price = priceData.price;\n change24h = priceData.change24h;\n // Volume is already in USD (not 30-decimal format)\n volume = ticker.volume || '0';\n }\n\n // Format using injected formatters (consistent with HyperLiquid via marketDataTransform.ts)\n const priceNum = parseFloat(price);\n const formattedPrice = formatters.formatPerpsFiat(priceNum);\n const priceChange = priceNum * (change24h / 100);\n const formattedChange = formatChange(priceChange, formatters);\n const formattedChangePercent = formatters.formatPercentage(change24h);\n const formattedVolume = formatters.formatVolume(parseFloat(volume));\n\n return {\n symbol,\n name: getTokenName(symbol),\n maxLeverage: `${MYX_MAX_LEVERAGE}x`,\n price: formattedPrice,\n change24h: formattedChange,\n change24hPercent: formattedChangePercent,\n volume: formattedVolume,\n providerId: 'myx',\n };\n}\n\n// ============================================================================\n// Market Filtering\n// ============================================================================\n\n/**\n * Filter MYX markets to only include MYX-exclusive markets\n * Removes markets that overlap with HyperLiquid\n *\n * @param pools - Array of MYX pool symbols\n * @returns Filtered array with only MYX-exclusive markets\n */\nexport function filterMYXExclusiveMarkets(\n pools: MYXPoolSymbol[],\n): MYXPoolSymbol[] {\n return pools.filter((pool) => {\n const symbol = pool.baseSymbol || extractSymbolFromPoolId(pool.poolId);\n // Exclude markets that overlap with HyperLiquid\n return !MYX_HL_OVERLAPPING_MARKETS.includes(\n symbol as (typeof MYX_HL_OVERLAPPING_MARKETS)[number],\n );\n });\n}\n\n/**\n * Check if a symbol overlaps with HyperLiquid markets\n *\n * @param symbol - Market symbol to check\n * @returns true if the symbol is available on both MYX and HyperLiquid\n */\nexport function isOverlappingMarket(symbol: string): boolean {\n return MYX_HL_OVERLAPPING_MARKETS.includes(\n symbol as (typeof MYX_HL_OVERLAPPING_MARKETS)[number],\n );\n}\n\n// ============================================================================\n// Pool ID Utilities\n// ============================================================================\n\n/**\n * Build a map of poolId to symbol for quick lookup\n *\n * @param pools - Array of MYX pool symbols\n * @returns Map of poolId to symbol\n */\nexport function buildPoolSymbolMap(\n pools: MYXPoolSymbol[],\n): Map<string, string> {\n const map = new Map<string, string>();\n for (const pool of pools) {\n const symbol = pool.baseSymbol || extractSymbolFromPoolId(pool.poolId);\n map.set(pool.poolId, symbol);\n }\n return map;\n}\n\n/**\n * Build a map of symbol to poolIds (for multi-pool support)\n *\n * @param pools - Array of MYX pool symbols\n * @returns Map of symbol to array of poolIds\n */\nexport function buildSymbolPoolsMap(\n pools: MYXPoolSymbol[],\n): Map<string, string[]> {\n const map = new Map<string, string[]>();\n for (const pool of pools) {\n const symbol = pool.baseSymbol || extractSymbolFromPoolId(pool.poolId);\n const existing = map.get(symbol) ?? [];\n existing.push(pool.poolId);\n map.set(symbol, existing);\n }\n return map;\n}\n\n/**\n * Extract symbol from pool ID\n * Pool IDs typically contain the symbol as a suffix or can be parsed.\n * When baseSymbol is unavailable, returns a truncated address for UI display.\n *\n * @param poolId - MYX pool ID string\n * @returns Extracted symbol or truncated poolId as fallback\n */\nexport function extractSymbolFromPoolId(poolId: string): string {\n // Pool IDs in MYX are hex addresses (\"0x...\")\n // The actual symbol comes from the pool's baseSymbol field\n // Truncate hex addresses so they're UI-friendly\n if (poolId.startsWith('0x') && poolId.length > 10) {\n return `${poolId.slice(0, 6)}...${poolId.slice(-4)}`;\n }\n return poolId;\n}\n\n/**\n * Get full token name from symbol\n * Returns the symbol as name if not found (MYX-specific tokens)\n *\n * @param symbol - The market symbol to look up.\n * @returns The human-readable token name, or the symbol itself if not found.\n */\nfunction getTokenName(symbol: string): string {\n const tokenNames: Record<string, string> = {\n BTC: 'Bitcoin',\n ETH: 'Ethereum',\n BNB: 'BNB',\n MYX: 'MYX Protocol',\n RHEA: 'Rhea Finance',\n PARTI: 'Particle Network',\n SKYAI: 'SkyAI',\n PUMP: 'PumpFun',\n WLFI: 'World Liberty Financial',\n };\n\n return tokenNames[symbol] || symbol;\n}\n\n// ============================================================================\n// Position Adapter\n// ============================================================================\n\n/**\n * Adapt MYX SDK PositionType to MetaMask Position\n *\n * @param pos - MYX position from SDK\n * @param poolSymbolMap - Map of poolId to symbol\n * @returns MetaMask Position object\n */\nexport function adaptPositionFromMYX(\n pos: MYXPositionType,\n poolSymbolMap: Map<string, string>,\n): Position {\n const symbol = poolSymbolMap.get(pos.poolId) ?? pos.poolId;\n const sizeNum = fromMYXSize(pos.size);\n const entryPriceNum = fromMYXPrice(pos.entryPrice);\n const collateralNum = fromMYXCollateral(pos.collateralAmount);\n\n // Direction: 0 = LONG (positive size), 1 = SHORT (negative size)\n const isLong = pos.direction === MYXDirection.LONG;\n const signedSize = isLong ? sizeNum : -sizeNum;\n\n // Position value = size * entry price\n const positionValue = Math.abs(sizeNum * entryPriceNum);\n\n // Leverage = position value / collateral (approximate)\n const leverage = collateralNum > 0 ? positionValue / collateralNum : 1;\n\n return {\n symbol,\n size: signedSize.toString(),\n entryPrice: entryPriceNum.toString(),\n positionValue: positionValue.toString(),\n unrealizedPnl: '0', // Requires mark price - will be enriched by WS or separate call\n marginUsed: collateralNum.toString(),\n leverage: {\n type: 'isolated',\n value: Math.round(leverage),\n rawUsd: collateralNum.toString(),\n },\n liquidationPrice: null, // Requires separate calculation\n maxLeverage: MYX_MAX_LEVERAGE,\n returnOnEquity: '0',\n cumulativeFunding: {\n allTime: '0',\n sinceOpen: '0',\n sinceChange: '0',\n },\n takeProfitPrice: undefined,\n stopLossPrice: undefined,\n takeProfitCount: 0,\n stopLossCount: 0,\n providerId: 'myx',\n };\n}\n\n// ============================================================================\n// Order Adapter\n// ============================================================================\n\n/**\n * Adapt MYX SDK open order (PositionType-shaped from getOrders) to MetaMask Order.\n * Note: getOrders returns PositionType[] per the SDK types.\n * For richer order data, use getOrderHistory.\n *\n * @param historyOrder - MYX history order item\n * @param poolSymbolMap - Map of poolId to symbol\n * @returns MetaMask Order object\n */\nexport function adaptOrderFromMYX(\n historyOrder: MYXHistoryOrderItem,\n poolSymbolMap: Map<string, string>,\n): Order {\n const symbol =\n historyOrder.baseSymbol ??\n poolSymbolMap.get(historyOrder.poolId) ??\n historyOrder.poolId;\n\n const priceNum = fromMYXPrice(historyOrder.price);\n const sizeNum = fromMYXSize(historyOrder.size);\n const filledSizeNum = fromMYXSize(historyOrder.filledSize);\n const remainingSize = Math.max(0, sizeNum - filledSizeNum);\n\n // Map direction\n const side: 'buy' | 'sell' =\n historyOrder.direction === MYXDirectionEnum.Long ? 'buy' : 'sell';\n\n // Map order type\n let orderType: 'market' | 'limit' = 'market';\n if (historyOrder.orderType === MYXOrderTypeEnum.Limit) {\n orderType = 'limit';\n }\n\n // Map status\n let status: Order['status'] = 'open';\n switch (historyOrder.orderStatus) {\n case MYXOrderStatusEnum.Successful:\n status = 'filled';\n break;\n case MYXOrderStatusEnum.Cancelled:\n status = 'canceled';\n break;\n case MYXOrderStatusEnum.Expired:\n status = 'canceled';\n break;\n default:\n status = 'open';\n }\n\n // Detect trigger orders\n const isTrigger =\n historyOrder.execType === MYXExecTypeEnum.TP ||\n historyOrder.execType === MYXExecTypeEnum.SL;\n let detailedOrderType: string | undefined;\n if (historyOrder.execType === MYXExecTypeEnum.TP) {\n detailedOrderType = 'Take Profit';\n } else if (historyOrder.execType === MYXExecTypeEnum.SL) {\n detailedOrderType = 'Stop Loss';\n } else if (historyOrder.execType === MYXExecTypeEnum.Liquidation) {\n detailedOrderType = 'Liquidation';\n }\n\n return {\n orderId: String(historyOrder.orderId),\n symbol,\n side,\n orderType,\n size: sizeNum.toString(),\n originalSize: sizeNum.toString(),\n price: priceNum.toString(),\n filledSize: filledSizeNum.toString(),\n remainingSize: remainingSize.toString(),\n status,\n timestamp: historyOrder.txTime,\n isTrigger,\n detailedOrderType,\n reduceOnly:\n historyOrder.operation === MYXOperationEnum.Decrease ? true : undefined,\n providerId: 'myx',\n };\n}\n\n// ============================================================================\n// Account State Adapter\n// ============================================================================\n\n/**\n * Adapt MYX account info response to MetaMask AccountState.\n *\n * @param accountInfo - Raw account info from MYX SDK\n * @param walletBalance - Wallet USDT balance (from getWalletQuoteTokenBalance)\n * @returns MetaMask AccountState\n */\nexport function adaptAccountStateFromMYX(\n accountInfo: Record<string, unknown> | undefined,\n walletBalance?: string,\n): AccountState {\n // accountInfo structure varies; extract what we can\n // TODO: Verify SDK semantics — if totalCollateral already includes unrealizedPnl,\n // the totalBalance formula below double-counts. Needs SDK documentation check.\n const rawCollateral = accountInfo?.totalCollateral ?? '0';\n const rawPnl = accountInfo?.unrealizedPnl ?? '0';\n const marginUsed = accountInfo ? fromMYXCollateral(String(rawCollateral)) : 0;\n const unrealizedPnl = accountInfo ? fromMYXCollateral(String(rawPnl)) : 0;\n const balance = walletBalance ? fromMYXCollateral(walletBalance) : 0;\n\n const totalBalance = balance + marginUsed + unrealizedPnl;\n\n return {\n spendableBalance: balance.toString(),\n withdrawableBalance: balance.toString(),\n totalBalance: totalBalance.toString(),\n marginUsed: marginUsed.toString(),\n unrealizedPnl: unrealizedPnl.toString(),\n returnOnEquity: '0',\n };\n}\n\n// ============================================================================\n// Order Fill Adapter\n// ============================================================================\n\n/**\n * Adapt MYX history order item (filled) to MetaMask OrderFill\n *\n * @param order - MYX history order item\n * @param poolSymbolMap - Map of poolId to symbol\n * @returns MetaMask OrderFill\n */\nexport function adaptOrderFillFromMYX(\n order: MYXHistoryOrderItem,\n poolSymbolMap: Map<string, string>,\n): OrderFill {\n const symbol =\n order.baseSymbol ?? poolSymbolMap.get(order.poolId) ?? order.poolId;\n const sizeNum = fromMYXSize(order.filledSize || order.size);\n const priceNum = fromMYXPrice(order.lastPrice || order.price);\n const side = order.direction === MYXDirectionEnum.Long ? 'buy' : 'sell';\n const feeNum = fromMYXCollateral(order.tradingFee || '0');\n const pnlNum = fromMYXCollateral(order.realizedPnl || '0');\n\n let orderType: OrderFill['orderType'] = 'regular';\n if (order.execType === MYXExecTypeEnum.TP) {\n orderType = 'take_profit';\n } else if (order.execType === MYXExecTypeEnum.SL) {\n orderType = 'stop_loss';\n } else if (order.execType === MYXExecTypeEnum.Liquidation) {\n orderType = 'liquidation';\n }\n\n return {\n orderId: String(order.orderId),\n symbol,\n side,\n size: sizeNum.toString(),\n price: priceNum.toString(),\n pnl: pnlNum.toString(),\n direction: side,\n fee: feeNum.toString(),\n feeToken: 'USDT',\n timestamp: order.txTime,\n success: order.orderStatus === MYXOrderStatusEnum.Successful,\n orderType,\n providerId: 'myx',\n };\n}\n\n// ============================================================================\n// Funding Adapter\n// ============================================================================\n\n/**\n * Adapt MYX trade flow items (funding type) to MetaMask Funding\n *\n * @param flows - MYX trade flow items filtered to funding type\n * @param poolSymbolMap - Map of poolId to symbol\n * @returns Array of MetaMask Funding objects\n */\nexport function adaptFundingFromMYX(\n flows: MYXTradeFlowItem[],\n poolSymbolMap: Map<string, string>,\n): Funding[] {\n return flows\n .filter(\n (flow) =>\n flow.fundingFee && flow.fundingFee !== '0' && flow.fundingFee !== '',\n )\n .map((flow) => {\n const symbol = poolSymbolMap.get(flow.poolId) ?? flow.poolId;\n const amountUsd = fromMYXCollateral(flow.fundingFee);\n return {\n symbol,\n amountUsd: amountUsd.toString(),\n rate: undefined, // Funding rate not available in MYX trade flow data\n timestamp: flow.txTime,\n transactionHash: flow.txHash,\n };\n });\n}\n\n// ============================================================================\n// User History Adapter\n// ============================================================================\n\n/**\n * Adapt MYX trade flow items to MetaMask UserHistoryItem\n *\n * @param flows - MYX trade flow items\n * @returns Array of UserHistoryItem\n */\nexport function adaptUserHistoryFromMYX(\n flows: MYXTradeFlowItem[],\n): UserHistoryItem[] {\n return flows\n .filter(\n (flow) =>\n flow.type === MYXTradeFlowTypeEnum.MarginAccountDeposit ||\n flow.type === MYXTradeFlowTypeEnum.TransferToWallet,\n )\n .map((flow) => {\n const isDeposit = flow.type === MYXTradeFlowTypeEnum.MarginAccountDeposit;\n const amount = fromMYXCollateral(flow.collateralAmount || '0');\n return {\n id: String(flow.orderId),\n timestamp: flow.txTime,\n type: isDeposit ? 'deposit' : 'withdrawal',\n amount: Math.abs(amount).toString(),\n asset: 'USDT',\n txHash: flow.txHash,\n status: 'completed' as const,\n details: {\n source: 'myx',\n },\n };\n });\n}\n\n// ============================================================================\n// Candle (Kline) Adapter\n// ============================================================================\n\n/**\n * Adapt MYX KlineDataItemType to MetaMask CandleStick.\n * KlineDataItemType fields (time, open, close, high, low) are already\n * human-readable strings — no 30-decimal conversion needed.\n *\n * @param item - MYX kline data item from SDK\n * @returns MetaMask CandleStick object\n */\nexport function adaptCandleFromMYX(item: MYXKlineData): CandleStick {\n return {\n time: item.time,\n open: item.open,\n high: item.high,\n low: item.low,\n close: item.close,\n volume: '0', // KlineDataItemType has no volume field\n };\n}\n\n/**\n * Adapt MYX WebSocket KlineData to MetaMask CandleStick.\n * WS KlineData uses single-letter fields: {t, o, h, l, c, v}.\n *\n * @param data - MYX WebSocket kline data\n * @returns MetaMask CandleStick object\n */\nexport function adaptCandleFromMYXWebSocket(data: MYXKlineWsData): CandleStick {\n return {\n time: data.t,\n open: data.o,\n high: data.h,\n low: data.l,\n close: data.c,\n volume: data.v,\n };\n}\n\n/**\n * Map CandlePeriod values to MYX KlineResolution.\n * MYX SDK supports: '1m', '5m', '15m', '30m', '1h', '4h', '1d', '1w', '1M'.\n * Unsupported CandlePeriod values are mapped to the nearest supported resolution.\n */\nconst CANDLE_PERIOD_TO_MYX_RESOLUTION: Record<string, string> = {\n '1m': '1m',\n '3m': '5m', // No 3m → use 5m\n '5m': '5m',\n '15m': '15m',\n '30m': '30m',\n '1h': '1h',\n '2h': '4h', // No 2h → use 4h\n '4h': '4h',\n '8h': '4h', // No 8h → use 4h\n '12h': '1d', // No 12h → use 1d\n '1d': '1d',\n '3d': '1w', // No 3d → use 1w\n '1w': '1w',\n '1M': '1M',\n};\n\n/**\n * Convert a CandlePeriod string to MYX KlineResolution.\n *\n * @param period - CandlePeriod value (e.g., '1m', '3m', '1h')\n * @returns MYX KlineResolution string\n */\nexport function toMYXKlineResolution(period: string): string {\n return CANDLE_PERIOD_TO_MYX_RESOLUTION[period] ?? '1h';\n}\n\n// ============================================================================\n// Response Validation\n// ============================================================================\n\n/**\n * Assert MYX API response is successful.\n * MYX uses code 9200 or 0 for success.\n *\n * @param response - MYX API response with code field\n * @param response.code - Response code (9200 or 0 = success)\n * @param response.message - Optional error message\n * @param context - Context string for error messages\n */\nexport function assertMYXSuccess(\n response: { code: number; message?: string | null },\n context: string,\n): void {\n if (response.code !== 9200 && response.code !== 0) {\n throw new Error(\n `MYX ${context} failed: code=${response.code} message=${response.message ?? 'unknown'}`,\n );\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import type { SDKOrderParams } from "../types/hyperliquid-types.cjs";
2
- import type { PerpsDebugLogger } from "../types/index.cjs";
3
- import type { OrdinaryOrderType } from "../types/perps-types.cjs";
1
+ import type { SDKOrderParams } from '../types/hyperliquid-types.js';
2
+ import type { PerpsDebugLogger } from '../types/index.js';
3
+ import type { OrdinaryOrderType } from '../types/perps-types.js';
4
4
  /**
5
5
  * Optional debug logger for order calculation functions.
6
6
  * When provided, enables detailed logging for debugging.
@@ -295,4 +295,4 @@ export declare function formatPartialTpslSize(params: {
295
295
  */
296
296
  export declare function buildOrdersArray(params: BuildOrdersArrayParams): BuildOrdersArrayResult;
297
297
  export {};
298
- //# sourceMappingURL=orderCalculations.d.cts.map
298
+ //# sourceMappingURL=orderCalculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/orderCalculations.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAa,MAAM,yBAAyB,CAAC;AAa5E;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG,gBAAgB,GAAG,SAAS,CAAC;AAQxE,KAAK,kBAAkB,GAAG;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,oBAAoB,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,KAAK,sBAAsB,GAAG;IAC5B,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IAIjB,SAAS,CAAC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1,8 +1,8 @@
1
- import { BASIS_POINTS_DIVISOR } from "../constants/hyperLiquidConfig.mjs";
2
- import { DECIMAL_PRECISION_CONFIG, MAX_ORDER_MARGIN_BUFFER, ORDER_SLIPPAGE_CONFIG } from "../constants/perpsConfig.mjs";
3
- import { PERPS_ERROR_CODES } from "../perpsErrorCodes.mjs";
4
- import { formatHyperLiquidPrice, formatHyperLiquidSize } from "./hyperLiquidAdapter.mjs";
5
- import { getTriggerDirection, isLimitExecutionOrderType, isTriggerOrderType, SCALE_ORDER_COUNT, toSDKTimeInForce } from "./orderTypes.mjs";
1
+ import { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';
2
+ import { DECIMAL_PRECISION_CONFIG, MAX_ORDER_MARGIN_BUFFER, ORDER_SLIPPAGE_CONFIG, } from '../constants/perpsConfig.js';
3
+ import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
4
+ import { formatHyperLiquidPrice, formatHyperLiquidSize, } from './hyperLiquidAdapter.js';
5
+ import { getTriggerDirection, isLimitExecutionOrderType, isTriggerOrderType, SCALE_ORDER_COUNT, toSDKTimeInForce, } from './orderTypes.js';
6
6
  /**
7
7
  * Tolerance used when deciding whether a scaled size is already on the size
8
8
  * grid, guarding against floating-point representation error.
@@ -804,4 +804,4 @@ export function buildOrdersArray(params) {
804
804
  const finalGrouping = grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');
805
805
  return { orders, grouping: finalGrouping };
806
806
  }
807
- //# sourceMappingURL=orderCalculations.mjs.map
807
+ //# sourceMappingURL=orderCalculations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderCalculations.js","sourceRoot":"","sources":["../../src/utils/orderCalculations.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,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ACX,CAAC;YACF,CAAC,EAAE,cAAc,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,CAAC;YACxE,CAAC,EAAE,IAAI;YACP,CAAC,EAAE;gBACD,OAAO,EAAE;oBACP,QAAQ,EAAE,IAAI;oBACd,SAAS,EAAE,kBAAkB,CAAC;wBAC5B,KAAK,EAAE,aAAa;wBACpB,UAAU;wBACV,KAAK,EAAE,iBAAiB,CAAC,oBAAoB;qBAC9C,CAAC;oBACF,IAAI,EAAE,IAAI;iBACX;aACF;SACF,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;IAED,qBAAqB;IACrB,MAAM,aAAa,GACjB,QAAQ,IAAI,CAAC,CAAC,eAAe,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAEzE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';\nimport {\n DECIMAL_PRECISION_CONFIG,\n MAX_ORDER_MARGIN_BUFFER,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { SDKOrderParams } from '../types/hyperliquid-types.js';\nimport type { PerpsDebugLogger } from '../types/index.js';\nimport type { OrdinaryOrderType, OrderType } from '../types/perps-types.js';\nimport {\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n} from './hyperLiquidAdapter.js';\nimport {\n getTriggerDirection,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n SCALE_ORDER_COUNT,\n toSDKTimeInForce,\n} from './orderTypes.js';\n\n/**\n * Optional debug logger for order calculation functions.\n * When provided, enables detailed logging for debugging.\n */\nexport type OrderCalculationsDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Tolerance used when deciding whether a scaled size is already on the size\n * grid, guarding against floating-point representation error.\n */\nconst FLOAT_TOLERANCE = 1e-6;\n\ntype PositionSizeParams = {\n amount: string;\n price: number;\n szDecimals: number;\n};\n\ntype MarginRequiredParams = {\n amount: string;\n leverage: number;\n};\n\ntype MaxAllowedAmountParams = {\n spendableBalance: number;\n assetPrice: number;\n assetSzDecimals: number;\n leverage: number;\n // Placement type. Only a resting order is margin-checked against its own\n // submitted price; a marketable order is charged at the fill price. Defaults\n // to 'market'.\n orderType?: 'market' | 'limit';\n // Price a limit order will rest at. Needed to size a limit order that rests\n // above the market price.\n limitPrice?: number;\n};\n\n// Advanced order calculation interfaces\nexport type CalculateFinalPositionSizeParams = {\n usdAmount?: string;\n size?: string;\n currentPrice: number;\n priceAtCalculation?: number;\n maxSlippageBps?: number;\n szDecimals: number;\n leverage?: number;\n // Reduce-only orders (position closes) may never round up: HyperLiquid\n // rejects a reduce-only order whose size exceeds the live position with\n // \"Reduce only order would increase position\".\n reduceOnly?: boolean;\n debugLogger?: OrderCalculationsDebugLogger;\n};\n\nexport type CalculateFinalPositionSizeResult = {\n finalPositionSize: number;\n};\n\nexport type CalculateOrderPriceAndSizeParams = {\n // Strategy placements are excluded: each derives its own prices and sizes and\n // never reaches this helper. Left in, `chase` would fall through as a\n // limit-priced order it carries no price for, and `twap`/`scale` would be\n // serialized as ordinary FrontendMarket orders.\n orderType: OrdinaryOrderType;\n isBuy: boolean;\n finalPositionSize: number;\n currentPrice: number;\n limitPrice?: string;\n // Trigger price for stop_*/take_profit_* placements. Required for those types:\n // `*_limit` executes at `limitPrice`, `*_market` derives a slippage-capped\n // limit price from this trigger price.\n triggerPrice?: string;\n // Max slippage in basis points (e.g. 300 = 3%). Applied to market orders and to\n // market-executing trigger orders (where it caps the limit price derived from\n // the trigger price); limit orders use limitPrice directly. Falls back to\n // ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps for market orders and\n // .DefaultTpslSlippageBps for market-executing triggers.\n maxSlippageBps?: number;\n szDecimals: number;\n};\n\nexport type CalculateOrderPriceAndSizeResult = {\n orderPrice: number;\n formattedSize: string;\n formattedPrice: string;\n};\n\nexport type BuildOrdersArrayParams = {\n assetId: number;\n isBuy: boolean;\n formattedPrice: string;\n formattedSize: string;\n reduceOnly: boolean;\n // Strategy placements never reach here; see `CalculateOrderPriceAndSizeParams`.\n orderType: OrdinaryOrderType;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n // Trigger price for stop_*/take_profit_* placements (required for those types)\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n // Partial TP/SL sizes; default to the full order size when omitted\n takeProfitSize?: string;\n stopLossSize?: string;\n szDecimals: number;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\nexport type BuildOrdersArrayResult = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n};\n\n/**\n * Calculate position size based on USD amount and asset price\n *\n * @param params - Amount in USD, current asset price, and required decimal precision\n * @returns Position size formatted to the asset's decimal precision\n */\nexport function calculatePositionSize(params: PositionSizeParams): string {\n const { amount, price, szDecimals } = params;\n\n // Validate required parameters\n if (szDecimals === undefined || szDecimals === null) {\n throw new Error('szDecimals is required for position size calculation');\n }\n if (szDecimals < 0) {\n throw new Error(`szDecimals must be >= 0, got: ${szDecimals}`);\n }\n\n const amountNum = parseFloat(amount || '0');\n\n if (isNaN(amountNum) || isNaN(price) || amountNum === 0 || price === 0) {\n return (0).toFixed(szDecimals);\n }\n\n const positionSize = amountNum / price;\n const multiplier = Math.pow(10, szDecimals);\n let rounded = Math.round(positionSize * multiplier) / multiplier;\n\n // Ensure rounded size meets requested USD (fix validation gap)\n const actualUsd = rounded * price;\n if (actualUsd < amountNum) {\n rounded += 1 / multiplier;\n }\n\n return rounded.toFixed(szDecimals);\n}\n\n/**\n * Calculate margin required for a position\n *\n * @param params - Position amount and leverage\n * @returns Margin required formatted to 2 decimal places\n */\nexport function calculateMarginRequired(params: MarginRequiredParams): string {\n const { amount, leverage } = params;\n const amountNum = parseFloat(amount || '0');\n\n if (\n isNaN(amountNum) ||\n isNaN(leverage) ||\n amountNum === 0 ||\n leverage === 0\n ) {\n return '0.00';\n }\n\n return (amountNum / leverage).toFixed(2);\n}\n\nexport function getMaxAllowedAmount(params: MaxAllowedAmountParams): number {\n const {\n spendableBalance,\n assetPrice,\n assetSzDecimals,\n leverage,\n orderType = 'market',\n limitPrice,\n } = params;\n if (spendableBalance === 0 || !assetPrice || assetSzDecimals === undefined) {\n return 0;\n }\n\n // HyperLiquid reserves initial margin for a RESTING order against the price\n // the order is submitted at, not the market price its size was derived from.\n // A limit order resting above the market price - typically a sell - therefore\n // needs more margin than a market-priced notional budgets for, and the\n // exchange refuses it with \"insufficient margin to place order\". Price the max\n // off that submitted price instead. A marketable order is charged at the fill\n // price, so it needs no adjustment.\n const executionPriceRatio =\n orderType === 'limit' && limitPrice && limitPrice > assetPrice\n ? limitPrice / assetPrice\n : 1;\n\n // The theoretical maximum is spendableBalance * leverage, expressed in the\n // market-price notional the caller works with.\n const theoreticalMax = (spendableBalance * leverage) / executionPriceRatio;\n\n // But we need to account for position size rounding\n // Find the largest whole dollar amount that fits within this limit\n let maxAmount = Math.floor(theoreticalMax);\n\n // Verify this amount doesn't exceed available balance after rounding\n const testPositionSize = calculatePositionSize({\n amount: maxAmount.toString(),\n price: assetPrice,\n szDecimals: assetSzDecimals,\n });\n\n const actualNotionalValue =\n parseFloat(testPositionSize) * assetPrice * executionPriceRatio;\n const requiredMargin = actualNotionalValue / leverage;\n\n // If rounding caused us to exceed available balance, step down by one position increment\n if (requiredMargin > spendableBalance) {\n const minPositionSizeIncrement = 1 / Math.pow(10, assetSzDecimals);\n const positionSizeIncrementUsd = Math.ceil(\n minPositionSizeIncrement * assetPrice,\n );\n maxAmount -= positionSizeIncrementUsd;\n }\n\n // Apply margin buffer to reduce \"Insufficient margin\" rejections from the exchange\n // (fees, rounding, and exchange-side checks can make 100% theoretical max fail)\n const bufferedMax = maxAmount * (1 - MAX_ORDER_MARGIN_BUFFER);\n\n return Math.max(0, Math.floor(bufferedMax));\n}\n\n/**\n * Round a size down onto the asset's size grid.\n *\n * Used for reduce-only orders, where rounding up would push the size past the\n * live position size. Values already on the grid are snapped rather than\n * truncated, because floating-point math can leave them just below a grid\n * point (0.0123 * 10000 === 122.99999999999999) and truncating would drop a\n * whole increment.\n *\n * The result is never greater than `size`, for negative sizes as well as\n * positive: the snap only ever recovers a grid point the input already\n * represents, so a value genuinely below a grid point is stepped down even when\n * the tolerance would have reached the point above it.\n *\n * A size whose scaled form reaches `2^53` is returned unchanged: doubles cannot\n * represent consecutive integers there, so the grid is finer than the spacing\n * between representable values and there is nothing to round down to.\n *\n * @param size - Size to round down.\n * @param szDecimals - The asset's size decimal precision.\n * @returns The size rounded down onto the size grid, never exceeding `size`.\n */\nexport function floorToSizeDecimals(size: number, szDecimals: number): number {\n const multiplier = Math.pow(10, szDecimals);\n const scaled = size * multiplier;\n\n // Past 2^53 a double cannot represent consecutive integers, so `units -= 1`\n // below would be a no-op and the step-down loop would never terminate. The\n // size grid is finer than the spacing between representable values at that\n // magnitude, so there is no increment to shave: return the input unchanged.\n if (!Number.isFinite(scaled) || Math.abs(scaled) >= Number.MAX_SAFE_INTEGER) {\n return size;\n }\n\n const nearest = Math.round(scaled);\n // The tolerance scales with the magnitude, because double-precision error\n // does too: a fixed epsilon would stop absorbing representation error for\n // sizes that scale past ~1e10 and would then shave off a whole increment.\n const tolerance = Math.max(\n FLOAT_TOLERANCE,\n Math.abs(scaled) * Number.EPSILON * 8,\n );\n let units =\n Math.abs(scaled - nearest) < tolerance ? nearest : Math.floor(scaled);\n\n // Step down until the result no longer exceeds the input. One pass is not\n // enough: a tolerance wide enough to absorb representation error at large\n // magnitudes also reaches the next grid point, and for an input less than half\n // an ulp below a grid point `size * multiplier` evaluates to exactly that grid\n // integer, so flooring the scaled value returns the same too-large result.\n // The comparison alone is the whole termination condition: for a non-negative\n // size the loop stops at or before zero, and for a negative size it stops once\n // the value is no longer above the input. Guarding on `units` instead would\n // skip a negative size below the tolerance, which snaps to `-0` — and\n // `-0 !== 0` is false. The 2^53 bail-out above keeps this bounded.\n while (units / multiplier > size) {\n units -= 1;\n }\n\n return units / multiplier;\n}\n\n/**\n * The smallest price increment the venue will represent at a given price.\n *\n * HyperLiquid bounds a perp price two ways at once — a decimal-place cap that\n * depends on the asset's size precision, and a significant-figure cap — so the\n * tick widens as the price grows. Whichever bound is coarser at this price is\n * the tick.\n *\n * @param params - Tick parameters.\n * @param params.price - Price to measure the increment at.\n * @param params.szDecimals - The asset's size decimal precision.\n * @returns The tick size at that price.\n */\nexport function getPriceTick(params: {\n price: number;\n szDecimals: number;\n}): number {\n const { price, szDecimals } = params;\n\n const byDecimals = Math.pow(\n 10,\n -(DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals),\n );\n const bySignificantFigures = Math.pow(\n 10,\n Math.floor(Math.log10(Math.abs(price))) -\n (DECIMAL_PRECISION_CONFIG.MaxSignificantFigures - 1),\n );\n\n return Math.max(byDecimals, bySignificantFigures);\n}\n\n/**\n * Price a chase order against the book it is chasing.\n *\n * The venue's own definition: a chase rests one tick *inside* the spread —\n * above the best bid for a buy, below the best ask for a sell — except when the\n * spread is already a single tick, where there is no room to improve and the\n * order joins the touch instead.\n *\n * Rests inside rather than at the touch because a chase is post-only: sitting\n * one tick ahead of the rest of the queue is the whole point, and joining the\n * touch would leave it behind every order already resting there.\n *\n * @param params - Quote parameters.\n * @param params.bestBid - Best bid, excluding the chase's own resting order.\n * @param params.bestAsk - Best ask, excluding the chase's own resting order.\n * @param params.isBuy - Which side the chase rests on.\n * @param params.szDecimals - The asset's size decimal precision.\n * @returns The formatted price the chase should rest at.\n */\nexport function computeChaseQuotePrice(params: {\n bestBid: number;\n bestAsk: number;\n isBuy: boolean;\n szDecimals: number;\n}): string {\n const { bestBid, bestAsk, isBuy, szDecimals } = params;\n\n const reference = isBuy ? bestBid : bestAsk;\n const tick = getPriceTick({ price: reference, szDecimals });\n const improved = isBuy ? bestBid + tick : bestAsk - tick;\n\n // A single-tick spread leaves nowhere to improve to: the improved price would\n // cross, which a post-only order cannot do. Join the touch instead.\n const crosses = isBuy ? improved >= bestAsk : improved <= bestBid;\n\n return formatHyperLiquidPrice({\n price: crosses ? reference : improved,\n szDecimals,\n });\n}\n\n/**\n * Compute the price ladder a scale placement fans out over.\n *\n * The ladder is inclusive of both ends — the first rung sits exactly on\n * `minPrice`, the last exactly on `maxPrice` — so the range the caller asked\n * for is the range that actually reaches the exchange.\n *\n * @param params - Ladder parameters.\n * @param params.minPrice - Lowest price in the ladder.\n * @param params.maxPrice - Highest price in the ladder; must exceed `minPrice`.\n * @param params.count - Number of rungs.\n * @returns The rung prices, ascending.\n */\nexport function computeScalePriceLadder(params: {\n minPrice: number;\n maxPrice: number;\n count: number;\n}): number[] {\n const { minPrice, maxPrice, count } = params;\n\n if (\n !Number.isInteger(count) ||\n count < SCALE_ORDER_COUNT.min ||\n count > SCALE_ORDER_COUNT.max\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);\n }\n if (\n !Number.isFinite(minPrice) ||\n !Number.isFinite(maxPrice) ||\n minPrice <= 0 ||\n maxPrice <= minPrice\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n\n const step = (maxPrice - minPrice) / (count - 1);\n // The top rung is assigned rather than accumulated: `minPrice + step * n`\n // drifts, and a ladder that stops short of the caller's maxPrice would quietly\n // narrow the range they asked for.\n return Array.from({ length: count }, (_unused, index) =>\n index === count - 1 ? maxPrice : minPrice + step * index,\n );\n}\n\n/**\n * Split a scale placement's total size across its ladder rungs.\n *\n * The split is done in whole units of the asset's size grid rather than in\n * decimal sizes: dividing and re-flooring in floating point loses a sub-unit of\n * dust on every rung, and a ladder that submits less than the size that was\n * validated is not the order the caller placed. Either allocation below sums to\n * exactly `totalSize` in grid units.\n *\n * This is the one place the ladder's sizes are decided. Clients previewing a\n * scale placement must call it rather than reproduce the ramp, or the preview\n * and the placement will disagree at the rounding.\n *\n * **Even (no `skew`, or `skew` exactly 1).** Every rung gets `floor(total /\n * count)` units and whatever does not divide evenly goes onto the first rung —\n * 11 units across 3 rungs is `5, 3, 3`, not three equal slices.\n *\n * **Skewed.** Rung weights ramp linearly from 1 at index 0 to `skew` at the last\n * index, in ladder order — which is ascending price, `scaleMinPrice` to\n * `scaleMaxPrice`, for a buy and a sell alike. Each rung takes\n * `floor(weight / sumOfWeights * totalUnits)` units, and the units left over go\n * to the rungs with the largest discarded fraction, ties broken by ascending\n * index. The leftover is deliberately *not* dumped on the first rung the way the\n * even split does it: on a `skew` above 1 that would push size back to the end\n * of the ladder the caller weighted away from.\n *\n * The total is expected to sit on the grid already — `calculateFinalPositionSize`\n * floors it there — so rounding onto the grid here only absorbs representation\n * error. A total too small to give every rung a whole unit is rejected: placing\n * fewer orders than asked for would silently change the strategy. A `skew` far\n * enough from 1 can starve a rung the same way, and is rejected the same way.\n *\n * @param params - Split parameters.\n * @param params.totalSize - Total size to distribute.\n * @param params.count - Number of rungs.\n * @param params.szDecimals - The asset's size decimal precision.\n * @param params.skew - Optional size weighting across the ladder; any finite\n * value above 0, used exactly as given.\n * @returns One size string per rung, in ladder order.\n */\nexport function splitScaleSizes(params: {\n totalSize: number;\n count: number;\n szDecimals: number;\n skew?: number;\n}): string[] {\n const { totalSize, count, szDecimals, skew } = params;\n\n // Checked here as well as in `computeScalePriceLadder`: this is exported on\n // its own, and a count of zero would otherwise return an empty split while a\n // fractional one would return slices that do not sum to the total.\n if (\n !Number.isInteger(count) ||\n count < SCALE_ORDER_COUNT.min ||\n count > SCALE_ORDER_COUNT.max\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);\n }\n\n // Checked here rather than left to the arithmetic: a non-finite or\n // non-positive skew produces weights that are NaN or run negative, and either\n // one would come back as a ladder of zero-size rungs instead of a rejection.\n if (skew !== undefined && (!Number.isFinite(skew) || skew <= 0)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n\n const multiplier = Math.pow(10, szDecimals);\n const totalUnits = Math.round(totalSize * multiplier);\n\n if (!Number.isSafeInteger(totalUnits) || totalUnits < count) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n\n const unitsPerRung =\n skew === undefined || skew === 1\n ? splitUnitsEvenly({ totalUnits, count })\n : splitUnitsBySkew({ totalUnits, count, skew });\n\n // A rung the ramp starved of every unit would be submitted as a zero-size\n // order. That is the same failure the total-size check above rejects, and it\n // is reported the same way, so a caller reads one reason for \"this ladder\n // cannot be cut this finely\" rather than two.\n if (unitsPerRung.some((units) => units === 0)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n\n return unitsPerRung.map((units) =>\n formatHyperLiquidSize({ size: units / multiplier, szDecimals }),\n );\n}\n\n/**\n * Spread the ladder's units evenly, leftover on the first rung.\n *\n * @param params - Split parameters.\n * @param params.totalUnits - Total size, in whole size-grid units.\n * @param params.count - Number of rungs.\n * @returns Units per rung, in ladder order.\n */\nfunction splitUnitsEvenly(params: {\n totalUnits: number;\n count: number;\n}): number[] {\n const { totalUnits, count } = params;\n\n const sliceUnits = Math.floor(totalUnits / count);\n const remainderUnits = totalUnits - sliceUnits * count;\n\n return Array.from({ length: count }, (_unused, index) =>\n index === 0 ? sliceUnits + remainderUnits : sliceUnits,\n );\n}\n\n/**\n * Spread the ladder's units along a linear weight ramp.\n *\n * Flooring every rung leaves up to `count - 1` units unallocated, and they go to\n * the rungs that lost the most to the floor — the standard largest-remainder\n * allocation. Ties go to the lower index, which keeps the result a function of\n * the inputs alone rather than of sort stability.\n *\n * @param params - Split parameters.\n * @param params.totalUnits - Total size, in whole size-grid units.\n * @param params.count - Number of rungs.\n * @param params.skew - Weight of the last rung relative to the first.\n * @returns Units per rung, in ladder order.\n */\nfunction splitUnitsBySkew(params: {\n totalUnits: number;\n count: number;\n skew: number;\n}): number[] {\n const { totalUnits, count, skew } = params;\n\n const weights = Array.from(\n { length: count },\n (_unused, index) => 1 + ((skew - 1) * index) / (count - 1),\n );\n const weightSum = weights.reduce((sum, weight) => sum + weight, 0);\n\n const ideal = weights.map((weight) => (weight / weightSum) * totalUnits);\n const unitsPerRung = ideal.map((units) => Math.floor(units));\n const leftoverUnits =\n totalUnits - unitsPerRung.reduce((sum, units) => sum + units, 0);\n\n Array.from({ length: count }, (_unused, index) => index)\n .sort((left, right) => {\n const fractionDelta =\n ideal[right] - unitsPerRung[right] - (ideal[left] - unitsPerRung[left]);\n return fractionDelta === 0 ? left - right : fractionDelta;\n })\n .slice(0, leftoverUnits)\n .forEach((index) => {\n unitsPerRung[index] += 1;\n });\n\n return unitsPerRung;\n}\n\n/**\n * Calculates final position size using USD as source of truth with price validation\n *\n * This function implements the hybrid approach where USD is the source of truth,\n * but includes price staleness validation and proper rounding to prevent precision loss.\n *\n * @param params - USD amount, size, prices, and configuration\n * @returns Final position size as a number\n */\nexport function calculateFinalPositionSize(\n params: CalculateFinalPositionSizeParams,\n): CalculateFinalPositionSizeResult {\n const {\n usdAmount,\n size,\n currentPrice,\n priceAtCalculation,\n maxSlippageBps,\n szDecimals,\n leverage,\n reduceOnly,\n debugLogger,\n } = params;\n\n let finalPositionSize: number;\n\n // Validate price staleness whenever the caller supplied a calculation-time\n // price. This runs before the sizing branches on purpose: a full close submits\n // the exact live position size rather than a USD-derived one, and it must still\n // be rejected when the price has moved past the caller's tolerance.\n if (priceAtCalculation) {\n const priceDeltaBps = Math.abs(\n ((currentPrice - priceAtCalculation) / priceAtCalculation) * 10000,\n );\n const maxSlippageBpsValue =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n\n if (priceDeltaBps > maxSlippageBpsValue) {\n throw new Error(\n `Price moved too much: ${priceDeltaBps.toFixed(0)} bps (max: ${maxSlippageBpsValue} bps). ` +\n `Expected: ${priceAtCalculation.toFixed(2)}, Current: ${currentPrice.toFixed(2)}`,\n );\n }\n\n debugLogger?.log('Price validation passed:', {\n priceAtCalculation,\n currentPrice,\n deltaBps: priceDeltaBps.toFixed(2),\n maxSlippageBps: maxSlippageBpsValue,\n });\n }\n\n if (usdAmount && parseFloat(usdAmount) > 0) {\n // USD amount provided - use it as source of truth\n const usdValue = parseFloat(usdAmount);\n\n // Recalculate position size with fresh price\n finalPositionSize = usdValue / currentPrice;\n\n // A reduce-only order may never exceed the size the caller asked to close:\n // that size is already clamped to the live position, while the USD amount was\n // computed against an older price and can imply a larger size after an\n // adverse move. Capping here keeps USD accuracy in the common case and makes\n // the caller's clamp binding.\n if (reduceOnly && size) {\n const requestedSize = parseFloat(size);\n\n // A supplied size must be positive, or the cap below would submit a\n // zero/negative order. Reject it rather than silently falling back to the\n // USD-derived size, matching how closePosition treats the same input.\n if (!Number.isFinite(requestedSize) || requestedSize <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n finalPositionSize = Math.min(finalPositionSize, requestedSize);\n }\n\n // 3. Apply size decimals rounding (reduce-only never rounds up)\n const multiplier = Math.pow(10, szDecimals);\n const sizeBeforeRounding = finalPositionSize;\n finalPositionSize = reduceOnly\n ? floorToSizeDecimals(finalPositionSize, szDecimals)\n : Math.round(finalPositionSize * multiplier) / multiplier;\n\n // Rounding down can zero out a reduce-only order whose USD value is worth\n // less than one size increment. Fail with a clear error instead of\n // submitting a size of \"0\" the exchange will reject.\n if (reduceOnly && finalPositionSize <= 0 && sizeBeforeRounding > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n // 4. Ensure rounded size meets requested USD (fix validation gap).\n // Skipped for reduce-only orders: adding an increment there would submit\n // more than the position holds and HyperLiquid rejects the order.\n let actualNotionalValue = finalPositionSize * currentPrice;\n if (!reduceOnly && actualNotionalValue < usdValue) {\n // Add 1 minimum increment to meet requested USD\n finalPositionSize += 1 / multiplier;\n actualNotionalValue = finalPositionSize * currentPrice;\n\n debugLogger?.log('Position size adjusted to meet USD minimum:', {\n requestedUsd: usdValue,\n beforeAdjustment: finalPositionSize - 1 / multiplier,\n afterAdjustment: finalPositionSize,\n actualUsd: actualNotionalValue,\n });\n }\n\n const requiredMargin = actualNotionalValue / (leverage ?? 1);\n\n // Log if rounding caused significant difference\n const usdDifference = Math.abs(actualNotionalValue - usdValue);\n if (usdDifference > 0.01) {\n debugLogger?.log(\n 'Position size rounding caused USD difference (acceptable):',\n {\n requestedUsd: usdValue,\n actualUsd: actualNotionalValue,\n difference: usdDifference,\n positionSize: finalPositionSize,\n },\n );\n }\n\n debugLogger?.log('Recalculated position size with fresh price:', {\n usdAmount: usdValue,\n priceAtCalculation,\n currentPrice,\n originalSize: size,\n recalculatedSize: finalPositionSize,\n requiredMargin,\n minIncrement: 1 / multiplier,\n });\n } else {\n // Legacy: Use provided size (backward compatibility)\n finalPositionSize = parseFloat(size ?? '0');\n\n // Reduce-only sizes are formatted with toFixed() further down, which rounds\n // up; truncate onto the size grid first so a close can never exceed the\n // position it is closing.\n if (reduceOnly) {\n // A supplied size must be positive, or formatHyperLiquidSize would render\n // a zero or negative order size. The USD branch above rejects the same\n // input.\n if (size && !(finalPositionSize > 0)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n const sizeBeforeFlooring = finalPositionSize;\n finalPositionSize = floorToSizeDecimals(finalPositionSize, szDecimals);\n\n // A positive size that floors to zero is worth less than one increment\n if (finalPositionSize <= 0 && sizeBeforeFlooring > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n }\n\n debugLogger?.log(\n 'Using legacy size calculation (no USD amount provided):',\n {\n providedSize: size,\n finalSize: finalPositionSize,\n },\n );\n }\n\n return { finalPositionSize };\n}\n\n/**\n * Calculates order price and formatted size based on order type\n *\n * @param params - Order parameters including type, direction, size, and prices\n * @returns Formatted order price, size, and price string\n */\nexport function calculateOrderPriceAndSize(\n params: CalculateOrderPriceAndSizeParams,\n): CalculateOrderPriceAndSizeResult {\n const {\n orderType,\n isBuy,\n finalPositionSize,\n currentPrice,\n limitPrice,\n triggerPrice,\n maxSlippageBps,\n szDecimals,\n } = params;\n\n let orderPrice: number;\n let formattedSize: string;\n\n if (isTriggerOrderType(orderType)) {\n // Trigger placements price off the trigger, not the live market: the order\n // rests off-book until the trigger fires.\n if (!triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n const triggerPriceNum = parseFloat(triggerPrice);\n if (isNaN(triggerPriceNum) || triggerPriceNum <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE);\n }\n\n if (isLimitExecutionOrderType(orderType)) {\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n } else {\n // Market execution on trigger: HyperLiquid still needs a limit price, used\n // as a slippage cap. The caller's tolerance wins when supplied; otherwise\n // the 10% convention of the existing TP/SL children applies.\n const effectiveBps =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n const slippageValue = effectiveBps / BASIS_POINTS_DIVISOR;\n orderPrice = isBuy\n ? triggerPriceNum * (1 + slippageValue)\n : triggerPriceNum * (1 - slippageValue);\n }\n\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else if (orderType === 'market') {\n // Market orders: apply slippage buffer to the live price so HyperLiquid\n // receives a worst-case acceptable limit price. Falls back to the\n // documented default if the caller does not provide one.\n const effectiveBps =\n maxSlippageBps ?? ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps;\n const slippageValue = effectiveBps / BASIS_POINTS_DIVISOR;\n orderPrice = isBuy\n ? currentPrice * (1 + slippageValue)\n : currentPrice * (1 - slippageValue);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n } else {\n // Limit orders: use provided price (no slippage applied)\n if (!limitPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(limitPrice);\n formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals,\n });\n }\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals,\n });\n\n return { orderPrice, formattedSize, formattedPrice };\n}\n\n/**\n * Build the SDK order-type field for the main order.\n *\n * Trigger placements map to the SDK's trigger shape; everything else keeps the\n * existing Gtc/FrontendMarket limit shape.\n *\n * @param params - Order type parameters\n * @param params.orderType - Placement type\n * @param params.timeInForce - Time in force; only limit orders may carry one\n * @param params.triggerPrice - Trigger price (required for trigger placements)\n * @param params.szDecimals - Asset size decimals, for price formatting\n * @returns The SDK `t` field for the main order\n */\nfunction buildMainOrderTypeField(params: {\n orderType: OrderType;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n triggerPrice?: string;\n szDecimals: number;\n}): SDKOrderParams['t'] {\n const { orderType, timeInForce, triggerPrice, szDecimals } = params;\n\n if (!isTriggerOrderType(orderType)) {\n if (orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(timeInForce) } };\n }\n if (timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n }\n\n if (timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n\n if (!triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(orderType),\n triggerPx: formatTriggerPrice({\n price: triggerPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n }),\n tpsl: getTriggerDirection(orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n}\n\n/**\n * Format a price that becomes a `triggerPx`, rejecting one that disappears at\n * the asset's precision.\n *\n * A positive price below the asset's tick (`0.0004` where the asset quotes to\n * three places) formats to `'0'`, which the exchange rejects. Callers validate\n * this up front via `validateOrderPrecision`; this is the guard on the build\n * path itself, so no caller can assemble an order that cannot be accepted.\n *\n * @param params - Price parameters\n * @param params.price - The requested price\n * @param params.szDecimals - Asset size decimals\n * @param params.error - Typed error to throw when the price rounds away\n * @returns The exchange-formatted price, guaranteed positive.\n */\nfunction formatTriggerPrice(params: {\n price: string;\n szDecimals: number;\n error: string;\n}): string {\n const { price, szDecimals, error } = params;\n const formatted = formatHyperLiquidPrice({ price, szDecimals });\n\n if (parseFloat(formatted) <= 0) {\n throw new Error(error);\n }\n\n return formatted;\n}\n\n/**\n * Resolve the size of an attached TP/SL order.\n *\n * @param params - Size parameters\n * @param params.tpslSize - Requested partial size, if any\n * @param params.formattedSize - Full order size, used when no partial size is given\n * @param params.szDecimals - Asset size decimals\n * @returns The exchange-formatted TP/SL order size\n */\nfunction formatTpslSize(params: {\n tpslSize?: string;\n formattedSize: string;\n szDecimals: number;\n}): string {\n const { tpslSize, formattedSize, szDecimals } = params;\n\n if (tpslSize === undefined) {\n return formattedSize;\n }\n\n // Validation compares the requested size against `params.size`, but a\n // usdAmount-based order is finally sized from a fresher price, so the parent\n // can end up smaller than the child that validated cleanly. Clamp so the\n // attached TP/SL never exceeds the order it protects.\n const requested = parseFloat(tpslSize);\n const parentSize = parseFloat(formattedSize);\n const size =\n Number.isFinite(parentSize) && Number.isFinite(requested)\n ? Math.min(requested, parentSize)\n : requested;\n\n return formatPartialTpslSize({ size, szDecimals });\n}\n\n/**\n * Check that an order's prices and partial sizes survive the asset's precision.\n *\n * Validation elsewhere sees the values the caller supplied; this sees what the\n * exchange will actually receive. A positive value below the asset's tick\n * formats to `'0'`, which either changes the order's meaning (a zero-sized\n * trigger covers the whole position) or is rejected outright (a zero\n * `triggerPx`).\n *\n * Callers run this before taking any side effect — cancelling the position's\n * existing triggers, changing leverage, moving HIP-3 margin — so a value that\n * would only fail once the orders are built cannot leave a position stripped of\n * its protection, or an account with leverage moved, for an order that was\n * never going to be accepted.\n *\n * @param params - Price and size parameters\n * @param params.triggerPrice - Trigger price for a trigger placement, if any\n * @param params.takeProfitPrice - Attached take profit price, if any\n * @param params.stopLossPrice - Attached stop loss price, if any\n * @param params.takeProfitSize - Requested partial take profit size, if any\n * @param params.stopLossSize - Requested partial stop loss size, if any\n * @param params.szDecimals - Asset size decimals\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderPrecision(params: {\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n szDecimals: number;\n}): { isValid: boolean; error?: string } {\n const {\n triggerPrice,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals,\n } = params;\n\n for (const size of [takeProfitSize, stopLossSize]) {\n if (size === undefined) {\n continue;\n }\n\n if (parseFloat(formatHyperLiquidSize({ size, szDecimals })) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n // Prices carry their own precision: an asset quotes to\n // `MaxPriceDecimals - szDecimals` places, so a positive price under that tick\n // formats to '0'. Every one of these becomes a `triggerPx` the exchange\n // rejects outright.\n const priceChecks: [string | undefined, string][] = [\n [triggerPrice, PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE],\n [takeProfitPrice, PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE],\n [stopLossPrice, PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE],\n ];\n\n for (const [price, error] of priceChecks) {\n if (price === undefined) {\n continue;\n }\n\n if (parseFloat(formatHyperLiquidPrice({ price, szDecimals })) <= 0) {\n return { isValid: false, error };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Format a partial TP/SL size, rejecting one that disappears at the asset\n * precision.\n *\n * Validation only sees the requested size, so a positive value below the\n * asset's precision (0.0004 against `szDecimals: 3`) passes and then formats to\n * `'0'`. HyperLiquid reads a zero-sized trigger as covering the whole position,\n * which would silently turn a partial TP/SL into a full close.\n *\n * @param params - Size parameters\n * @param params.size - The requested partial size\n * @param params.szDecimals - Asset size decimals\n * @returns The exchange-formatted size, guaranteed positive.\n */\nexport function formatPartialTpslSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const formatted = formatHyperLiquidSize(params);\n\n if (parseFloat(formatted) <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID);\n }\n\n return formatted;\n}\n\n/**\n * Builds orders array including main order and optional TP/SL orders\n *\n * @param params - Order construction parameters\n * @returns Array of SDK order params and grouping type\n */\nexport function buildOrdersArray(\n params: BuildOrdersArrayParams,\n): BuildOrdersArrayResult {\n const {\n assetId,\n isBuy,\n formattedPrice,\n formattedSize,\n reduceOnly,\n orderType,\n timeInForce,\n clientOrderId,\n triggerPrice,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals,\n grouping,\n } = params;\n\n const orders: SDKOrderParams[] = [];\n\n // 1. Main order\n const mainOrder: SDKOrderParams = {\n a: assetId,\n b: isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: reduceOnly || false,\n t: buildMainOrderTypeField({\n orderType,\n timeInForce,\n triggerPrice,\n szDecimals,\n }),\n c: clientOrderId ? (clientOrderId as Hex) : undefined,\n };\n orders.push(mainOrder);\n\n // 2. Take Profit order\n if (takeProfitPrice) {\n const tpOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals,\n }),\n s: formatTpslSize({\n tpslSize: takeProfitSize,\n formattedSize,\n szDecimals,\n }),\n r: true,\n t: {\n trigger: {\n isMarket: false,\n triggerPx: formatTriggerPrice({\n price: takeProfitPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n }),\n tpsl: 'tp',\n },\n },\n };\n orders.push(tpOrder);\n }\n\n // 3. Stop Loss order\n if (stopLossPrice) {\n // Apply 10% slippage to SL limit price (executes as market order when triggered)\n // HyperLiquid recommended: 10% for TP/SL orders\n const stopLossPriceNum = parseFloat(stopLossPrice);\n const slippageValue = ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps / 10000;\n const limitPriceWithSlippage = isBuy\n ? stopLossPriceNum * (1 - slippageValue) // Selling to close long: willing to accept LESS (slippage protection)\n : stopLossPriceNum * (1 + slippageValue); // Buying to close short: willing to pay MORE (slippage protection)\n\n const slOrder: SDKOrderParams = {\n a: assetId,\n b: !isBuy,\n p: formatHyperLiquidPrice({\n price: limitPriceWithSlippage,\n szDecimals,\n }),\n s: formatTpslSize({ tpslSize: stopLossSize, formattedSize, szDecimals }),\n r: true,\n t: {\n trigger: {\n isMarket: true,\n triggerPx: formatTriggerPrice({\n price: stopLossPrice,\n szDecimals,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n }),\n tpsl: 'sl',\n },\n },\n };\n orders.push(slOrder);\n }\n\n // Determine grouping\n const finalGrouping: 'na' | 'normalTpsl' | 'positionTpsl' =\n grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na');\n\n return { orders, grouping: finalGrouping };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { Order, PositionTriggerOrder } from "../types/index.mjs";
2
- import type { OrderExecution, OrderType, StrategyOrderType, TriggerDirection, TriggerOrderType } from "../types/perps-types.mjs";
1
+ import type { Order, PositionTriggerOrder } from '../types/index.js';
2
+ import type { OrderExecution, OrderType, StrategyOrderType, TriggerDirection, TriggerOrderType } from '../types/perps-types.js';
3
3
  /**
4
4
  * All trigger placement types, in a stable order suitable for iteration
5
5
  * (validation tables, e2e matrices).
@@ -163,4 +163,4 @@ export declare function toSDKTimeInForce(timeInForce?: 'GTC' | 'IOC' | 'ALO'): '
163
163
  * @returns A stable string; `'0'` for both empty and absent.
164
164
  */
165
165
  export declare function hashTriggerOrders(orders?: PositionTriggerOrder[]): string;
166
- //# sourceMappingURL=orderTypes.d.mts.map
166
+ //# sourceMappingURL=orderTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderTypes.d.ts","sourceRoot":"","sources":["../../src/utils/orderTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EACV,cAAc,EACd,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,yBAAyB,CAAC;AAEjC;;;GAGG;AACH,eAAO,MAAM,mBAAmB,mFAKgB,CAAC;AAEjD;;;GAGG;AACH,eAAO,MAAM,oBAAoB,qCAIgB,CAAC;AAElD;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB;aAAK,GAAG,EAAE,CAAC;aAAE,GAAG,EAAE,EAAE;CAAW,CAAC;AA8B9D;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,SAAS,GACnB,SAAS,IAAI,gBAAgB,CAE/B;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,SAAS,GACnB,SAAS,IAAI,iBAAiB,CAEhC;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAIvE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,SAAS,GAAG,cAAc,CAIxE;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,gBAAgB,GAC1B,gBAAgB,CAIlB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;CACtB,GAAG,gBAAgB,GAAG,SAAS,CAuB/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kCAAkC,CAAC,MAAM,EAAE;IACzD,KAAK,EAAE,KAAK,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,oBAAoB,GAAG,SAAS,CAqDnC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,kCAAkC,CAAC,MAAM,EAAE;IACzD,aAAa,EAAE,oBAAoB,EAAE,CAAC;IACtC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,MAAM,GAAG,SAAS,CAQrB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAC5C,SAAS,EAAE,gBAAgB,CAAC;IAC5B,SAAS,EAAE,cAAc,CAAC;CAC3B,GAAG,gBAAgB,CAQnB;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,WAAW,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,GAClC,KAAK,GAAG,KAAK,GAAG,KAAK,CASvB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,CAAC,EAAE,oBAAoB,EAAE,GAAG,MAAM,CAUzE"}
@@ -284,4 +284,4 @@ export function hashTriggerOrders(orders) {
284
284
  .map((order) => `${order.orderId}:${order.direction}:${order.orderType ?? '?'}@${order.triggerPrice}x${order.size}${order.isPartial ? 'p' : ''}`)
285
285
  .join(',');
286
286
  }
287
- //# sourceMappingURL=orderTypes.mjs.map
287
+ //# sourceMappingURL=orderTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orderTypes.js","sourceRoot":"","sources":["../../src/utils/order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C,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CACnI;SACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC","sourcesContent":["import type { Order, PositionTriggerOrder } from '../types/index.js';\nimport type {\n OrderExecution,\n OrderType,\n StrategyOrderType,\n TriggerDirection,\n TriggerOrderType,\n} from '../types/perps-types.js';\n\n/**\n * All trigger placement types, in a stable order suitable for iteration\n * (validation tables, e2e matrices).\n */\nexport const TRIGGER_ORDER_TYPES = [\n 'stop_market',\n 'stop_limit',\n 'take_profit_market',\n 'take_profit_limit',\n] as const satisfies readonly TriggerOrderType[];\n\n/**\n * All strategy placement types, in a stable order suitable for iteration\n * (validation tables, e2e matrices).\n */\nexport const STRATEGY_ORDER_TYPES = [\n 'twap',\n 'scale',\n 'chase',\n] as const satisfies readonly StrategyOrderType[];\n\n/**\n * Bounds on how many limit orders a scale placement may fan out into.\n *\n * A ladder needs at least two rungs to span a range at all; the upper bound\n * keeps a single placement from consuming a venue's per-account open-order\n * budget. Protocol-agnostic: a provider whose venue is stricter narrows this\n * further in its own validation.\n */\nexport const SCALE_ORDER_COUNT = { min: 2, max: 20 } as const;\n\n/**\n * Order types whose price field (`OrderParams.price`) is a real limit price the\n * exchange must honour, as opposed to a slippage cap derived from the market.\n */\nconst LIMIT_EXECUTION_ORDER_TYPES = [\n 'limit',\n 'stop_limit',\n 'take_profit_limit',\n] as const satisfies readonly OrderType[];\n\n/**\n * Order types that rest limit orders on the book, whatever decides their price.\n *\n * A superset of `LIMIT_EXECUTION_ORDER_TYPES`: a scale ladder and a chase both\n * rest limit orders, but they derive their own prices rather than taking one\n * from `OrderParams.price`, so they are limit *execution* without being\n * limit-*priced*. A TWAP is absent because its suborders cross the book.\n *\n * The distinction matters wherever execution is what is being charged or\n * bounded — fee tier, max order value — as opposed to where the caller's price\n * field is being read.\n */\nconst LIMIT_RESTING_ORDER_TYPES = [\n ...LIMIT_EXECUTION_ORDER_TYPES,\n 'scale',\n 'chase',\n] as const satisfies readonly OrderType[];\n\n/**\n * Check whether an order type is a trigger placement (stop / take profit).\n *\n * @param orderType - Order type to check.\n * @returns True when the type requires `OrderParams.triggerPrice`.\n */\nexport function isTriggerOrderType(\n orderType: OrderType,\n): orderType is TriggerOrderType {\n return (TRIGGER_ORDER_TYPES as readonly OrderType[]).includes(orderType);\n}\n\n/**\n * Check whether an order type is a strategy placement (TWAP / scale / chase).\n *\n * @param orderType - Order type to check.\n * @returns True when the placement expands into an execution schedule rather\n * than a single order.\n */\nexport function isStrategyOrderType(\n orderType: OrderType,\n): orderType is StrategyOrderType {\n return (STRATEGY_ORDER_TYPES as readonly OrderType[]).includes(orderType);\n}\n\n/**\n * Check whether an order type executes as a limit order.\n *\n * Covers plain limit orders and the `*_limit` trigger types, both of which\n * require `OrderParams.price`.\n *\n * @param orderType - Order type to check.\n * @returns True when the order executes as a limit order.\n */\nexport function isLimitExecutionOrderType(orderType: OrderType): boolean {\n return (LIMIT_EXECUTION_ORDER_TYPES as readonly OrderType[]).includes(\n orderType,\n );\n}\n\n/**\n * Get how an order executes, ignoring whether it is trigger-gated.\n *\n * This is also the coarse execution type that consumers predating trigger orders\n * understand (fee tiers, max order value, analytics). It answers \"does this rest\n * on the book or cross it\", which is not the same question as\n * `isLimitExecutionOrderType` — a scale ladder and a chase rest limit orders\n * without carrying an `OrderParams.price`.\n *\n * @param orderType - Order type to inspect.\n * @returns `'limit'` for limit, `*_limit`, `scale` and `chase`; `'market'`\n * otherwise, including `twap`, whose suborders cross the book.\n */\nexport function getTriggerExecution(orderType: OrderType): OrderExecution {\n return (LIMIT_RESTING_ORDER_TYPES as readonly OrderType[]).includes(orderType)\n ? 'limit'\n : 'market';\n}\n\n/**\n * Get the direction a trigger order fires in.\n *\n * @param orderType - Trigger order type.\n * @returns `'stop'` for `stop_*`, `'take_profit'` for `take_profit_*`.\n */\nexport function getTriggerDirection(\n orderType: TriggerOrderType,\n): TriggerDirection {\n return orderType === 'stop_market' || orderType === 'stop_limit'\n ? 'stop'\n : 'take_profit';\n}\n\n/**\n * Recover which way a trigger fires from its price relative to the entry.\n *\n * Used when the exchange reports a trigger without naming its placement type:\n * a long takes profit above its entry and stops out below, a short the other\n * way round. Shared by both transports so they classify identically.\n *\n * @param params - Classification parameters\n * @param params.triggerPrice - Price at which the order activates\n * @param params.entryPrice - Entry price of the position it is attached to\n * @param params.positionSize - Signed position size; its sign gives the side\n * @returns The direction, or undefined when there is nothing to compare against\n */\nexport function classifyTriggerDirection(params: {\n triggerPrice?: string;\n entryPrice?: string;\n positionSize: string;\n}): TriggerDirection | undefined {\n const { triggerPrice, entryPrice, positionSize } = params;\n\n const trigger = parseFloat(triggerPrice ?? '');\n const entry = parseFloat(entryPrice ?? '');\n const signedSize = parseFloat(positionSize || '0');\n\n if (!Number.isFinite(trigger) || !Number.isFinite(entry) || entry <= 0) {\n return undefined;\n }\n\n // A long takes profit above its entry and stops out below; a short is the\n // mirror image. A trigger sitting exactly at entry is neither, so both sides\n // fall to 'stop' — matching the legacy price fallback the scalar\n // takeProfitPrice/stopLossPrice fields still use. Splitting that tie the\n // other way would file the order under takeProfitOrders while the scalar\n // still reported it as a stop.\n const isLong = signedSize > 0;\n\n if (isLong) {\n return trigger > entry ? 'take_profit' : 'stop';\n }\n return trigger < entry ? 'take_profit' : 'stop';\n}\n\n/**\n * Project a normalized open order onto the position-state view of a trigger order.\n *\n * Returns undefined when the order is not a trigger, or when its direction can\n * be established neither from a named placement type nor from its price.\n *\n * @param params - Mapping parameters\n * @param params.order - Normalized open order\n * @param params.positionSize - Size of the position the trigger is attached to\n * @param params.entryPrice - Entry price, used to classify an unnamed trigger\n * @returns The position trigger order, or undefined\n */\nexport function buildPositionTriggerOrderFromOrder(params: {\n order: Order;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { order, positionSize, entryPrice } = params;\n\n if (!order.isTrigger) {\n return undefined;\n }\n\n // HyperLiquid sometimes reports a bare 'Trigger', naming neither direction\n // nor execution. The direction is still recoverable from the trigger price\n // against the entry, and it is what decides which array the order belongs\n // to — so an unnamed trigger is kept rather than dropped, with its execution\n // mode left unstated. Without a position to compare against there is nothing\n // to recover, and it is dropped.\n const direction =\n order.triggerOrderType === undefined\n ? classifyTriggerDirection({\n triggerPrice: order.triggerPrice ?? order.price,\n entryPrice,\n positionSize,\n })\n : getTriggerDirection(order.triggerOrderType);\n\n if (!direction) {\n return undefined;\n }\n\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(order.size || '0'));\n\n // A position-bound TP/SL covers whatever the position currently is. The\n // exchange encodes that as size 0, but `adaptOrderFromSDK` has already\n // resolved it against the position as it stood when the order was adapted,\n // so the size carried here goes stale as soon as the position is resized.\n // The flag is the durable statement of what the trigger covers; the number\n // is not. Reading the number instead would report the old size, and would\n // call the order partial whenever the position had since grown.\n const isPositionBound = order.isPositionTpsl === true;\n const size =\n isPositionBound || rawSize === 0 ? absolutePositionSize : rawSize;\n\n return {\n orderId: order.orderId,\n direction,\n orderType: order.triggerOrderType,\n triggerPrice: order.triggerPrice ?? order.price,\n size: size.toString(),\n isPartial:\n !isPositionBound &&\n rawSize > 0 &&\n absolutePositionSize > 0 &&\n rawSize < absolutePositionSize,\n reduceOnly: Boolean(order.reduceOnly),\n };\n}\n\n/**\n * Resolve the scalar TP/SL summary price a position reports for one direction.\n *\n * The scalar fields are only ever scanned from position-bound triggers, so a\n * position whose only take profit (or stop loss) is quantity-scoped reported a\n * count of 1 with no price — and a client that renders the scalar showed\n * nothing. When the direction has exactly one trigger order, that order is the\n * price, whether or not it is position-bound.\n *\n * Two or more triggers keep the scanned value: no single price describes them,\n * and clients render the count instead. Zero triggers keep it too, because it\n * still carries the TP/SL of a *pending* order on the market, which the arrays\n * deliberately exclude.\n *\n * @param params - Resolution parameters\n * @param params.triggerOrders - Trigger orders attached to the position for one direction\n * @param params.scannedPrice - Price scanned from position-bound triggers, if any\n * @returns The price to report, or undefined when there is none\n */\nexport function resolvePositionTriggerSummaryPrice(params: {\n triggerOrders: PositionTriggerOrder[];\n scannedPrice?: string;\n}): string | undefined {\n const { triggerOrders, scannedPrice } = params;\n\n if (triggerOrders.length === 1) {\n return triggerOrders[0].triggerPrice;\n }\n\n return scannedPrice;\n}\n\n/**\n * Build a trigger order type from its two independent dimensions.\n *\n * @param params - Trigger dimensions.\n * @param params.direction - Whether the trigger is a stop or a take profit.\n * @param params.execution - How the order executes once triggered.\n * @returns The matching trigger order type.\n */\nexport function buildTriggerOrderType(params: {\n direction: TriggerDirection;\n execution: OrderExecution;\n}): TriggerOrderType {\n const { direction, execution } = params;\n\n if (direction === 'stop') {\n return execution === 'limit' ? 'stop_limit' : 'stop_market';\n }\n\n return execution === 'limit' ? 'take_profit_limit' : 'take_profit_market';\n}\n\n/**\n * Map the controller's time in force onto the exchange's spelling.\n *\n * Shared by the two order-building paths so they cannot drift apart.\n *\n * @param timeInForce - Requested time in force; defaults to GTC.\n * @returns The SDK time-in-force value.\n */\nexport function toSDKTimeInForce(\n timeInForce?: 'GTC' | 'IOC' | 'ALO',\n): 'Gtc' | 'Ioc' | 'Alo' {\n switch (timeInForce) {\n case 'IOC':\n return 'Ioc';\n case 'ALO':\n return 'Alo';\n default:\n return 'Gtc';\n }\n}\n\n/**\n * Hash the identity of a position's trigger orders for change detection.\n *\n * Streamed positions only re-emit when their hash changes, so this has to move\n * when a trigger is added, removed, repriced, resized, or retyped — otherwise\n * subscribers never receive the updated arrays.\n *\n * The placement type is part of the identity because a trigger can be modified\n * in place: switching a stop from market to limit execution keeps its order ID,\n * trigger price, and size, so nothing else here would move even though the\n * execution semantics subscribers rely on have changed.\n *\n * @param orders - Trigger orders attached to a position, if any.\n * @returns A stable string; `'0'` for both empty and absent.\n */\nexport function hashTriggerOrders(orders?: PositionTriggerOrder[]): string {\n if (!orders || orders.length === 0) {\n return '0';\n }\n return orders\n .map(\n (order) =>\n `${order.orderId}:${order.direction}:${order.orderType ?? '?'}@${order.triggerPrice}x${order.size}${order.isPartial ? 'p' : ''}`,\n )\n .join(',');\n}\n"]}
@@ -4,4 +4,4 @@ export type PerpsConnectionAttemptContext = {
4
4
  };
5
5
  export declare function getPerpsConnectionAttemptContext(): PerpsConnectionAttemptContext | null;
6
6
  export declare function withPerpsConnectionAttemptContext<ValueType>(context: PerpsConnectionAttemptContext, callback: () => Promise<ValueType>): Promise<ValueType>;
7
- //# sourceMappingURL=perpsConnectionAttemptContext.d.mts.map
7
+ //# sourceMappingURL=perpsConnectionAttemptContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsConnectionAttemptContext.d.ts","sourceRoot":"","sources":["../../src/utils/perpsConnectionAttemptContext.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,6BAA6B,GAAG;IAC1C,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,OAAO,CAAC;CACxB,CAAC;AAIF,wBAAgB,gCAAgC,IAAI,6BAA6B,GAAG,IAAI,CAEvF;AAED,wBAAsB,iCAAiC,CAAC,SAAS,EAC/D,OAAO,EAAE,6BAA6B,EACtC,QAAQ,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,GACjC,OAAO,CAAC,SAAS,CAAC,CASpB"}
@@ -12,4 +12,4 @@ export async function withPerpsConnectionAttemptContext(context, callback) {
12
12
  currentAttemptContext = previousContext;
13
13
  }
14
14
  }
15
- //# sourceMappingURL=perpsConnectionAttemptContext.mjs.map
15
+ //# sourceMappingURL=perpsConnectionAttemptContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsConnectionAttemptContext.js","sourceRoot":"","sources":["../../src/utils/perpsConnectionAttemptContext.ts"],"names":[],"mappings":"AAKA,IAAI,qBAAqB,GAAyC,IAAI,CAAC;AAEvE,MAAM,UAAU,gCAAgC;IAC9C,OAAO,qBAAqB,CAAC;AAC/B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,OAAsC,EACtC,QAAkC;IAElC,MAAM,eAAe,GAAG,qBAAqB,CAAC;IAC9C,qBAAqB,GAAG,OAAO,CAAC;IAEhC,IAAI,CAAC;QACH,OAAO,MAAM,QAAQ,EAAE,CAAC;IAC1B,CAAC;YAAS,CAAC;QACT,qBAAqB,GAAG,eAAe,CAAC;IAC1C,CAAC;AACH,CAAC","sourcesContent":["export type PerpsConnectionAttemptContext = {\n source: string;\n suppressError: boolean;\n};\n\nlet currentAttemptContext: PerpsConnectionAttemptContext | null = null;\n\nexport function getPerpsConnectionAttemptContext(): PerpsConnectionAttemptContext | null {\n return currentAttemptContext;\n}\n\nexport async function withPerpsConnectionAttemptContext<ValueType>(\n context: PerpsConnectionAttemptContext,\n callback: () => Promise<ValueType>,\n): Promise<ValueType> {\n const previousContext = currentAttemptContext;\n currentAttemptContext = context;\n\n try {\n return await callback();\n } finally {\n currentAttemptContext = previousContext;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AccountState, Order, PerpsMarketData, Position } from "../types/index.cjs";
1
+ import type { AccountState, Order, PerpsMarketData, Position } from '../types/index.js';
2
2
  /** Minimal disk cache interface required by persistence utilities. */
3
3
  export type PerpsDiskCache = {
4
4
  getItem(key: string): Promise<string | null>;
@@ -109,4 +109,4 @@ export declare function hydrateFromDiskSync(diskCache: PerpsDiskCache, currentMa
109
109
  }>, currentUserCache: Record<string, {
110
110
  timestamp: number;
111
111
  }>, staleGuardMs: number): HydrateFromDiskResult;
112
- //# sourceMappingURL=perpsDiskPersistence.d.cts.map
112
+ //# sourceMappingURL=perpsDiskPersistence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsDiskPersistence.d.ts","sourceRoot":"","sources":["../../src/utils/perpsDiskPersistence.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,YAAY,EACZ,KAAK,EACL,eAAe,EACf,QAAQ,EACT,MAAM,mBAAmB,CAAC;AAU3B,sEAAsE;AACtE,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG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,EAAE;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,EACvD,YAAY,EAAE,MAAM,GACnB,qBAAqB,CAqHvB"}
@@ -1,4 +1,4 @@
1
- import { buildProviderCacheKey, PERPS_CONSTANTS, PERPS_DISK_CACHE_MARKETS, PERPS_DISK_CACHE_USER_DATA, PROVIDER_CONFIG } from "../constants/perpsConfig.mjs";
1
+ import { buildProviderCacheKey, PERPS_CONSTANTS, PERPS_DISK_CACHE_MARKETS, PERPS_DISK_CACHE_USER_DATA, PROVIDER_CONFIG, } from '../constants/perpsConfig.js';
2
2
  /**
3
3
  * Multiplier applied to staleGuardMs (preloadGuardMs, currently 30s) to compute
4
4
  * the staleness cap for disk-hydrated timestamps. A factor of 10 ensures hydrated
@@ -248,4 +248,4 @@ export function hydrateFromDiskSync(diskCache, currentMarketCache, currentUserCa
248
248
  },
249
249
  };
250
250
  }
251
- //# sourceMappingURL=perpsDiskPersistence.mjs.map
251
+ //# sourceMappingURL=perpsDiskPersistence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsDiskPersistence.js","sourceRoot":"","sources":["../../src/utils/perpsDiskPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,wBAAwB,EACxB,0BAA0B,EAC1B,eAAe,GAChB,MAAM,6BAA6B,CAAC;AAQrC;;;;;GAKG;AACH,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAqC3C;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAA0B,EAC1B,cAAsB,EACtB,SAAkB,EAClB,GAAW;IAEX,IAAI,cAAc,KAAK,YAAY,EAAE,CAAC;QACpC,MAAM,YAAY,GAAG,IAAI,GAAG,EAAgC,CAAC;QAC7D,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,eAAe,CAAC,eAAe,CAAC;YACxE,MAAM,GAAG,GAAG,q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E,MAAM,QAAQ,GAAG,gBAAgB,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;wBAC5D,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;4BACtD,WAAW,CAAC,KAAK,CAAC,kBAAkB,CAAC,GAAG;gCACtC,SAAS,EAAE,KAAK,CAAC,SAAS;gCAC1B,MAAM,EAAE,KAAK,CAAC,MAAM;gCACpB,YAAY,EAAE,KAAK,CAAC,YAAY;gCAChC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,sBAAsB,CAAC;gCAC5D,OAAO,EAAE,KAAK,CAAC,OAAO;gCACtB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;gCAC1C,KAAK,EAAE,KAAK,CAAC,KAAK;6BACnB,CAAC;4BACF,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;4BACxC,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;wBACpC,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,iCAAiC;YACnC,CAAC;QACH,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,mCAAmC;IACrC,CAAC;IAED,OAAO;QACL,aAAa;QACb,WAAW;QACX,KAAK,EAAE;YACL,WAAW;YACX,aAAa;YACb,UAAU;YACV,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildProviderCacheKey,\n PERPS_CONSTANTS,\n PERPS_DISK_CACHE_MARKETS,\n PERPS_DISK_CACHE_USER_DATA,\n PROVIDER_CONFIG,\n} from '../constants/perpsConfig.js';\nimport type {\n AccountState,\n Order,\n PerpsMarketData,\n Position,\n} from '../types/index.js';\n\n/**\n * Multiplier applied to staleGuardMs (preloadGuardMs, currently 30s) to compute\n * the staleness cap for disk-hydrated timestamps. A factor of 10 ensures hydrated\n * data is always TTL-expired so the stream manager overwrites it with live data,\n * while still being recent enough for a useful first paint.\n */\nconst DISK_HYDRATION_STALENESS_FACTOR = 10;\n\n/** Minimal disk cache interface required by persistence utilities. */\nexport type PerpsDiskCache = {\n getItem(key: string): Promise<string | null>;\n getItemSync?(key: string): string | null;\n setItem(key: string, value: string): Promise<void>;\n};\n\n/** Shape of a single market entry persisted to disk cache. */\nexport type DiskCacheMarketEntry = {\n providerNetworkKey: string;\n data: PerpsMarketData[];\n timestamp: number;\n};\n\n/** Shape of a single user-data entry persisted to disk cache. */\nexport type DiskCacheUserEntry = {\n providerNetworkKey: string;\n address: string;\n positions: Position[];\n orders: Order[];\n accountState: AccountState | null;\n timestamp: number;\n hip3ConfigVersion?: number;\n dexes?: string[];\n};\n\n/** Disk payload shape — either a single entry or a multi-provider wrapper. */\nexport type DiskCacheMarketPayload =\n | DiskCacheMarketEntry\n | { entries: DiskCacheMarketEntry[] };\n\nexport type DiskCacheUserPayload =\n | DiskCacheUserEntry\n | { entries: DiskCacheUserEntry[] };\n\n/**\n * Build the disk-cache payload for market data.\n * In aggregated mode, groups markets by provider into separate entries.\n *\n * @param markets - Current market data snapshot.\n * @param activeProvider - The active provider id (may be \"aggregated\").\n * @param isTestnet - Global testnet flag.\n * @param now - Timestamp to stamp entries with.\n * @returns Payload ready for JSON serialization.\n */\nexport function buildMarketDataPayload(\n markets: PerpsMarketData[],\n activeProvider: string,\n isTestnet: boolean,\n now: number,\n): DiskCacheMarketPayload {\n if (activeProvider === 'aggregated') {\n const entriesByKey = new Map<string, DiskCacheMarketEntry>();\n for (const market of markets) {\n const providerId = market.providerId ?? PROVIDER_CONFIG.DefaultProvider;\n const key = buildProviderCacheKey(providerId, isTestnet);\n const existing = entriesByKey.get(key);\n if (existing) {\n existing.data.push(market);\n } else {\n entriesByKey.set(key, {\n providerNetworkKey: key,\n data: [market],\n timestamp: now,\n });\n }\n }\n const entries = Array.from(entriesByKey.values());\n return entries.length === 1 ? entries[0] : { entries };\n }\n return {\n providerNetworkKey: buildProviderCacheKey(\n activeProvider ?? PROVIDER_CONFIG.DefaultProvider,\n isTestnet,\n ),\n data: markets,\n timestamp: now,\n };\n}\n\n/**\n * Build the disk-cache payload for user data (positions, orders, account).\n * In aggregated mode, groups entries by provider.\n *\n * @param positions - Current positions snapshot.\n * @param orders - Current orders snapshot.\n * @param accountState - Current account state snapshot.\n * @param address - EVM account address.\n * @param activeProvider - The active provider id (may be \"aggregated\").\n * @param isTestnet - Global testnet flag.\n * @param now - Timestamp to stamp entries with.\n * @returns Payload ready for JSON serialization.\n */\nexport function buildUserDataPayload(\n positions: Position[],\n orders: Order[],\n accountState: AccountState | null,\n address: string,\n activeProvider: string,\n isTestnet: boolean,\n now: number,\n): DiskCacheUserPayload {\n if (activeProvider === 'aggregated') {\n const entriesByKey = new Map<string, DiskCacheUserEntry>();\n const ensureEntry = (providerId: string): DiskCacheUserEntry => {\n const key = buildProviderCacheKey(providerId, isTestnet);\n let entry = entriesByKey.get(key);\n if (!entry) {\n entry = {\n providerNetworkKey: key,\n address,\n positions: [],\n orders: [],\n accountState: null,\n timestamp: now,\n };\n entriesByKey.set(key, entry);\n }\n return entry;\n };\n\n for (const position of positions) {\n ensureEntry(\n position.providerId ?? PROVIDER_CONFIG.DefaultProvider,\n ).positions.push(position);\n }\n for (const order of orders) {\n ensureEntry(\n order.providerId ?? PROVIDER_CONFIG.DefaultProvider,\n ).orders.push(order);\n }\n if (accountState) {\n ensureEntry(\n accountState.providerId ?? PROVIDER_CONFIG.DefaultProvider,\n ).accountState = accountState;\n }\n\n const entries = Array.from(entriesByKey.values()).filter(\n (entry) =>\n entry.positions.length > 0 ||\n entry.orders.length > 0 ||\n entry.accountState !== null,\n );\n return entries.length === 1 ? entries[0] : { entries };\n }\n return {\n providerNetworkKey: buildProviderCacheKey(\n activeProvider ?? PROVIDER_CONFIG.DefaultProvider,\n isTestnet,\n ),\n address,\n positions,\n orders,\n accountState,\n timestamp: now,\n };\n}\n\n/**\n * Write market entries to disk (best-effort, non-blocking).\n *\n * @param diskCache - Disk cache instance from controller infrastructure.\n * @param entries - Pre-assembled market cache entries to persist.\n */\nexport function persistMarketEntriesToDisk(\n diskCache: PerpsDiskCache,\n entries: DiskCacheMarketEntry[],\n): void {\n if (entries.length === 0) {\n return;\n }\n const payload = entries.length === 1 ? entries[0] : { entries };\n diskCache\n .setItem(PERPS_DISK_CACHE_MARKETS, JSON.stringify(payload))\n .catch(() => {\n // Disk persistence is best-effort and must never block preload.\n });\n}\n\n/**\n * Write user data entries to disk (best-effort, non-blocking).\n *\n * @param diskCache - Disk cache instance from controller infrastructure.\n * @param entries - Pre-assembled user cache entries to persist.\n */\nexport async function persistUserEntriesToDisk(\n diskCache: PerpsDiskCache,\n entries: DiskCacheUserEntry[],\n): Promise<void> {\n if (entries.length === 0) {\n return;\n }\n const payload = entries.length === 1 ? entries[0] : { entries };\n await diskCache.setItem(PERPS_DISK_CACHE_USER_DATA, JSON.stringify(payload));\n}\n\n/** Computed updates returned by hydrateFromDiskSync. */\nexport type HydrateFromDiskResult = {\n marketUpdates: Record<string, { data: PerpsMarketData[]; timestamp: number }>;\n userUpdates: Record<\n string,\n {\n positions: Position[];\n orders: Order[];\n accountState: AccountState | null;\n timestamp: number;\n address: string;\n hip3ConfigVersion?: number;\n dexes?: string[];\n }\n >;\n stats: {\n marketCount: number;\n userPositions: number;\n userOrders: number;\n durationMs: number;\n };\n};\n\n/**\n * Read disk-persisted cache snapshots and compute the state updates to apply.\n * Returns plain objects rather than mutating state directly, so the caller\n * can apply all changes in a single batched this.update() call.\n *\n * All returned timestamps are capped at DISK_HYDRATION_STALENESS_FACTOR * staleGuardMs\n * in the past so the stream manager always overwrites disk data with fresh live data.\n *\n * @param diskCache - Disk cache instance from controller infrastructure.\n * @param currentMarketCache - Current cachedMarketDataByProvider state.\n * @param currentUserCache - Current cachedUserDataByProvider state.\n * @param staleGuardMs - preloadGuardMs constant from the controller.\n * @returns Updates to apply plus stats for debug logging.\n */\nexport function hydrateFromDiskSync(\n diskCache: PerpsDiskCache,\n currentMarketCache: Record<string, { timestamp: number }>,\n currentUserCache: Record<string, { timestamp: number }>,\n staleGuardMs: number,\n): HydrateFromDiskResult {\n const hydrateT0 = Date.now();\n const marketUpdates: HydrateFromDiskResult['marketUpdates'] = {};\n const userUpdates: HydrateFromDiskResult['userUpdates'] = {};\n let marketCount = 0;\n let userPositions = 0;\n let userOrders = 0;\n\n if (!diskCache.getItemSync) {\n return {\n marketUpdates,\n userUpdates,\n stats: { marketCount, userPositions, userOrders, durationMs: 0 },\n };\n }\n\n const staleHydratedTimestamp =\n Date.now() - staleGuardMs * DISK_HYDRATION_STALENESS_FACTOR - 1;\n\n try {\n const marketsRaw = diskCache.getItemSync(PERPS_DISK_CACHE_MARKETS);\n const userRaw = diskCache.getItemSync(PERPS_DISK_CACHE_USER_DATA);\n\n if (marketsRaw) {\n try {\n const parsed = JSON.parse(marketsRaw) as\n | DiskCacheMarketEntry\n | { entries: DiskCacheMarketEntry[] };\n const entries = Array.isArray((parsed as { entries?: unknown }).entries)\n ? (parsed as { entries: DiskCacheMarketEntry[] }).entries\n : [parsed as DiskCacheMarketEntry];\n\n for (const entry of entries) {\n if (entry.providerNetworkKey && Array.isArray(entry.data)) {\n const existing = currentMarketCache[entry.providerNetworkKey];\n if (!existing || existing.timestamp < entry.timestamp) {\n const strippedData = entry.data.map((market) => {\n const structuralMarket = { ...market };\n if (\n structuralMarket.dataSource ===\n 'terminal-global-snapshot-mark'\n ) {\n delete structuralMarket.trend;\n }\n delete structuralMarket.dataSource;\n delete structuralMarket.sourceExpiresAt;\n return {\n ...structuralMarket,\n price: PERPS_CONSTANTS.FallbackPriceDisplay,\n change24h: PERPS_CONSTANTS.FallbackDataDisplay,\n change24hPercent: PERPS_CONSTANTS.FallbackPercentageDisplay,\n };\n });\n marketUpdates[entry.providerNetworkKey] = {\n data: strippedData,\n // Disk-hydrated market snapshots are only for structural\n // first paint. Keep them TTL-stale so the stream manager\n // still fetches fresh prices on connect.\n timestamp: Math.min(entry.timestamp, staleHydratedTimestamp),\n };\n marketCount += strippedData.length;\n }\n }\n }\n } catch {\n // Corrupt JSON — silently ignore\n }\n }\n\n if (userRaw) {\n try {\n const parsed = JSON.parse(userRaw) as\n | DiskCacheUserEntry\n | { entries: DiskCacheUserEntry[] };\n const entries = Array.isArray((parsed as { entries?: unknown }).entries)\n ? (parsed as { entries: DiskCacheUserEntry[] }).entries\n : [parsed as DiskCacheUserEntry];\n\n for (const entry of entries) {\n if (entry.providerNetworkKey && entry.address) {\n // Skip address check here — accounts may not be loaded yet at\n // constructor time. getCachedUserDataForActiveProvider validates\n // the address at read time, so stale-account data is never served.\n const existing = currentUserCache[entry.providerNetworkKey];\n if (!existing || existing.timestamp < entry.timestamp) {\n userUpdates[entry.providerNetworkKey] = {\n positions: entry.positions,\n orders: entry.orders,\n accountState: entry.accountState,\n timestamp: Math.min(entry.timestamp, staleHydratedTimestamp),\n address: entry.address,\n hip3ConfigVersion: entry.hip3ConfigVersion,\n dexes: entry.dexes,\n };\n userPositions += entry.positions.length;\n userOrders += entry.orders.length;\n }\n }\n }\n } catch {\n // Corrupt JSON — silently ignore\n }\n }\n } catch {\n // Disk read failure — non-critical\n }\n\n return {\n marketUpdates,\n userUpdates,\n stats: {\n marketCount,\n userPositions,\n userOrders,\n durationMs: Date.now() - hydrateT0,\n },\n };\n}\n"]}
@@ -201,4 +201,4 @@ export declare const formatPercentage: (value: string | number, decimals?: numbe
201
201
  export declare const formatFundingRate: (value?: number | null, options?: {
202
202
  showZero?: boolean;
203
203
  }) => string;
204
- //# sourceMappingURL=perpsFormatters.d.cts.map
204
+ //# sourceMappingURL=perpsFormatters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsFormatters.d.ts","sourceRoot":"","sources":["../../src/utils/perpsFormatters.ts"],"names":[],"mappings":"AAyEA;;;GAGG;AACH,eAAO,MAAM,eAAe;IAC1B,0CAA0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AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,eAAe,YACjB,MAAM,GAAG,MAAM,YACd;IACR,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,KACA,MA4GF,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,kBAAkB,SACvB,MAAM,GAAG,MAAM,eACR,MAAM,KAClB,MAiCF,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,SAAS,QAAS,MAAM,GAAG,MAAM,KAAG,MAahD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,gBAAgB,UACpB,MAAM,GAAG,MAAM,aACZ,MAAM,KACf,MAQF,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,iBAAiB,WACpB,MAAM,GAAG,IAAI,YACX;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,KAC/B,MAwBF,CAAC"}
@@ -8,7 +8,7 @@
8
8
  * Intl.NumberFormat instances are cached in a module-level Map keyed by
9
9
  * serialized options, avoiding repeated construction costs.
10
10
  */
11
- import { DECIMAL_PRECISION_CONFIG, FUNDING_RATE_CONFIG, PERPS_CONSTANTS } from "../constants/perpsConfig.mjs";
11
+ import { DECIMAL_PRECISION_CONFIG, FUNDING_RATE_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
12
12
  // Module-level Intl.NumberFormat cache (keyed by serialized options).
13
13
  const _fmtCache = new Map();
14
14
  function _formatCurrency(value, currency, opts) {
@@ -497,4 +497,4 @@ export const formatFundingRate = (value, options) => {
497
497
  }
498
498
  return `${formatted}%`;
499
499
  };
500
- //# sourceMappingURL=perpsFormatters.mjs.map
500
+ //# sourceMappingURL=perpsFormatters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perpsFormatters.js","sourceRoot":"","sources":["../../src/utils/perpsFormatters.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AAErC,sEAAsE;AACtE,MAAM,SAAS,GAAG,IAAI,GAAG,EAA6B,CAAC;AAEvD,SAAS,eAAe,CACtB,KAAa,EACb,QAAgB,EAChB,IAAsE;IAEtE,MAAM,GAAG,GAAG,GAAG,QAAQ,IAAI,IAAI,CAAC,qBAAqB,IAAI,IAAI,CAAC,qBAAqB,EAAE,CAAC;IACtF,IAAI,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE;YACzC,KAAK,EAAE,UAAU;YACjB,QAAQ;YACR,eAAe,EAAE,cAAc;YAC/B,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;YACjD,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC,CAAC;QACH,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,oBAAoB,CAC3B,MAAc,EACd,SAAiB,EACjB,OAIC;IAED,MAAM,UAAU,GAAG;QACjB,qBAAqB,EAAE,OAAO,CAAC,qBAAqB;QACpD,qBAAqB,EAAE,OAAO,CAAC,qBAAqB;QACpD,eAAe,EAAE,cAAuB;KACzC,CAAC;IACF,IAAI,MAAM,KAAK,CAAC,E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,CAC7B,CAAC;QACF,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,SAAS,GAAG,CAAC,CAAC,CAAC,KAAK,SAAS,GAAG,CAAC;IAC1D,CAAC;IAED,0CAA0C;IAC1C,IAAI,QAAQ,IAAI,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5C,OAAO,mBAAmB,CAAC,WAAW,CAAC;IACzC,CAAC;IAED,OAAO,GAAG,SAAS,GAAG,CAAC;AACzB,CAAC,CAAC","sourcesContent":["/**\n * Portable perps decimal formatters.\n *\n * These are the canonical implementations, exported from the controller so\n * extension and any future consumer can import them directly.\n * No mobile-specific imports — safe to sync to Core.\n *\n * Intl.NumberFormat instances are cached in a module-level Map keyed by\n * serialized options, avoiding repeated construction costs.\n */\nimport {\n DECIMAL_PRECISION_CONFIG,\n FUNDING_RATE_CONFIG,\n PERPS_CONSTANTS,\n} from '../constants/perpsConfig.js';\n\n// Module-level Intl.NumberFormat cache (keyed by serialized options).\nconst _fmtCache = new Map<string, Intl.NumberFormat>();\n\nfunction _formatCurrency(\n value: number,\n currency: string,\n opts: { minimumFractionDigits: number; maximumFractionDigits: number },\n): string {\n const key = `${currency}:${opts.minimumFractionDigits}:${opts.maximumFractionDigits}`;\n let formatter = _fmtCache.get(key);\n if (!formatter) {\n formatter = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency,\n currencyDisplay: 'narrowSymbol',\n minimumFractionDigits: opts.minimumFractionDigits,\n maximumFractionDigits: opts.maximumFractionDigits,\n });\n _fmtCache.set(key, formatter);\n }\n return formatter.format(value);\n}\n\n/**\n * Internal equivalent of the mobile formatWithThreshold utility.\n * Formats a currency value, returning \"<$X.XX\" for values below threshold.\n *\n * @param amount - The numeric amount to format.\n * @param threshold - The threshold below which the \"<\" prefix is shown.\n * @param options - Intl formatting options.\n * @param options.currency - ISO 4217 currency code.\n * @param options.minimumFractionDigits - Minimum decimal digits.\n * @param options.maximumFractionDigits - Maximum decimal digits.\n * @returns Formatted currency string.\n */\nfunction _formatWithThreshold(\n amount: number,\n threshold: number,\n options: {\n currency: string;\n minimumFractionDigits: number;\n maximumFractionDigits: number;\n },\n): string {\n const formatOpts = {\n minimumFractionDigits: options.minimumFractionDigits,\n maximumFractionDigits: options.maximumFractionDigits,\n currencyDisplay: 'narrowSymbol' as const,\n };\n if (amount === 0) {\n return _formatCurrency(0, options.currency, formatOpts);\n }\n return Math.abs(amount) < threshold\n ? `<${_formatCurrency(threshold, options.currency, formatOpts)}`\n : _formatCurrency(amount, options.currency, formatOpts);\n}\n\n/**\n * Price threshold constants for PRICE_RANGES_UNIVERSAL\n * These define the boundaries between different formatting ranges\n */\nexport const PRICE_THRESHOLD = {\n /** Very high values boundary (> $100k) */\n VERY_HIGH: 100_000,\n /** High values boundary (> $10k) */\n HIGH: 10_000,\n /** Large values boundary (> $1k) */\n LARGE: 1_000,\n /** Medium values boundary (> $100) */\n MEDIUM: 100,\n /** Medium-low values boundary (> $10) */\n MEDIUM_LOW: 10,\n /** Low values boundary (>= $0.01) */\n LOW: 0.01,\n /**\n * Very small values threshold (< $0.01)\n * This is the minimum value for formatWithThreshold and should align with\n * the 6 decimal maximum (0.000001 is the smallest representable value)\n */\n VERY_SMALL: 0.000001,\n} as const;\n\n/**\n * Configuration for a specific number range formatting\n */\nexport type FiatRangeConfig = {\n /**\n * The condition to match for this range (e.g., < 0.0001, < 1, >= 1000)\n * Function should return true if this config should be applied\n */\n condition: (value: number) => boolean;\n /** Minimum decimal places for this range */\n minimumDecimals: number;\n /** Maximum decimal places for this range */\n maximumDecimals: number;\n /** Optional threshold for formatWithThreshold (defaults to the range boundary) */\n threshold?: number;\n /** Optional significant digits for this range (overrides decimal places when set) */\n significantDigits?: number;\n /** Optional custom formatting logic for this range */\n customFormat?: (value: number, locale: string, currency: string) => string;\n /** Optional flag to strip trailing zeros for this range (overrides global stripTrailingZeros option) */\n stripTrailingZeros?: boolean;\n /**\n * Optional flag for fiat-style stripping (only strips .00, preserves meaningful decimals like .10, .40)\n * When true, \"$1,250.00\" → \"$1,250\" but \"$1,250.10\" stays \"$1,250.10\"\n * When false (default), strips all trailing zeros: \"$1,250.10\" → \"$1,250.1\"\n */\n fiatStyleStripping?: boolean;\n};\n\n/**\n * Formats a number to a specific number of significant digits\n * Strips trailing zeros unless minDecimals requires them\n *\n * @param value - The numeric value to format\n * @param significantDigits - Number of significant digits to maintain\n * @param minDecimals - Minimum decimal places to show (may add zeros)\n * @param maxDecimals - Maximum decimal places allowed\n * @returns Formatted number with appropriate precision, trailing zeros removed\n */\nexport function formatWithSignificantDigits(\n value: number,\n significantDigits: number,\n minDecimals?: number,\n maxDecimals?: number,\n): { value: number; decimals: number } {\n // Handle special cases\n if (value === 0) {\n // Return zero with no trailing decimals by default (matches stripTrailingZeros behavior)\n // Can be overridden by explicit minDecimals if needed\n return { value: 0, decimals: minDecimals ?? 0 };\n }\n\n const absValue = Math.abs(value);\n\n // For numbers >= 1, calculate decimals based on magnitude to achieve target significant figures\n // This ensures consistent precision across different price ranges:\n // Examples with 4 significant figures:\n // $123,456.78 → $123,456.78 (≥$1000: 2 decimals minimum, 8 sig figs)\n // $456.12 → $456.12 (≥$10: 2 decimals minimum, 5 sig figs)\n // $56.123 → $56.123 (≥$10: 2 decimals minimum, 5 sig figs)\n // $5.123 → $5.123 ($1-$10: 3 decimals = 4 sig figs)\n // $2.801 → $2.801 ($1-$10: 3 decimals = 4 sig figs)\n // $1.234 → $1.234 ($1-$10: 3 decimals = 4 sig figs)\n if (absValue >= 1) {\n let targetDecimals: number;\n\n // Calculate decimals needed based on integer digits to achieve target significant figures\n // For $38.388 with 5 sig figs: 2 integer digits, need 3 decimals (3,8,3,8,8)\n // For $123.45 with 5 sig figs: 3 integer digits, need 2 decimals (1,2,3,4,5)\n const integerDigits = Math.floor(Math.log10(absValue)) + 1;\n const decimalsNeeded = significantDigits - integerDigits;\n targetDecimals = Math.max(decimalsNeeded, 0); // Can't have negative decimals\n\n // Apply explicit minimum decimals constraint if provided (for special cases)\n if (minDecimals !== undefined && targetDecimals < minDecimals) {\n targetDecimals = minDecimals;\n }\n\n // Apply maximum decimals constraint if specified\n const finalDecimals =\n maxDecimals === undefined\n ? targetDecimals\n : Math.min(targetDecimals, maxDecimals);\n\n // Round to prevent floating-point artifacts (e.g., 2.820000000000003 → 2.82)\n const roundedValue = Number(value.toFixed(finalDecimals));\n\n return {\n value: roundedValue,\n decimals: finalDecimals,\n };\n }\n\n // For numbers < 1, use toPrecision to limit to significantDigits\n // Examples: 0.1234, 0.01234 should show exactly 4 sig figs\n const precisionStr = absValue.toPrecision(significantDigits);\n const precisionNum = parseFloat(precisionStr);\n\n // Convert to string to count actual decimals after trailing zeros are removed\n const valueStr = precisionNum.toString();\n const [, decPart = ''] = valueStr.split('.');\n let actualDecimals = decPart.length;\n\n // Apply min/max decimal constraints\n if (minDecimals !== undefined && actualDecimals < minDecimals) {\n actualDecimals = minDecimals; // Will add zeros if needed\n }\n if (maxDecimals !== undefined && actualDecimals > maxDecimals) {\n actualDecimals = maxDecimals;\n }\n\n // Return the value with sign restored and decimal count\n return {\n value: value < 0 ? -precisionNum : precisionNum,\n decimals: actualDecimals,\n };\n}\n\n/**\n * Minimal view fiat range configuration\n * Uses fiat-style stripping for clean currency display\n * Strips only .00 to avoid partial decimals like $1,250.1\n */\nexport const PRICE_RANGES_MINIMAL_VIEW: FiatRangeConfig[] = [\n {\n // Large values (>= $1000): Strip .00 only ($5,000 not $5,000.00, but $5,000.10 stays)\n condition: (val: number) => Math.abs(val) >= PRICE_THRESHOLD.LARGE,\n minimumDecimals: 2,\n maximumDecimals: 2,\n threshold: PRICE_THRESHOLD.LARGE,\n stripTrailingZeros: true,\n fiatStyleStripping: true,\n },\n {\n // Small values (< $1000): Also use fiat-style stripping ($100 not $100.00, but $13.40 stays)\n condition: () => true,\n minimumDecimals: 2,\n maximumDecimals: 2,\n threshold: PRICE_THRESHOLD.LOW,\n stripTrailingZeros: true,\n fiatStyleStripping: true,\n },\n];\n\n/**\n * Universal price range configuration following comprehensive rules from rules-decimals.md\n *\n * Rules:\n * - Max 6 decimals across all ranges (Hyperliquid limit)\n * - Strip trailing zeros by default\n * - Use |v| (absolute value) for conditions\n *\n * Significant digits by range:\n * - > $100,000: 6 sig digs\n * - $100,000 > x > $0.01: 5 sig digs\n * - < $0.01: 4 sig digs\n *\n * Decimal limits by price range:\n * - |v| > 10,000: min 0, max 0 decimals; 5 sig digs (6 if >100k)\n * - |v| > 1,000: min 0, max 1 decimal; 5 sig digs\n * - |v| > 100: min 0, max 2 decimals; 5 sig digs\n * - |v| > 10: min 0, max 4 decimals; 5 sig digs\n * - |v| ≥ 0.01: 5 sig digs, min 2, max 6 decimals\n * - |v| < 0.01: 4 sig digs, min 2, max 6 decimals\n *\n * Examples:\n * - $123,456.78 → $123,457 (>$10k: 0 decimals, 6 sig figs)\n * - $12,345.67 → $12,346 (>$10k: 0 decimals, 5 sig figs)\n * - $1,234.56 → $1,234.6 ($1k-$10k: 1 decimal, 5 sig figs)\n * - $123.456 → $123.46 ($100-$1k: 2 decimals, 5 sig figs)\n * - $12.34567 → $12.346 ($10-$100: 4 decimals, 5 sig figs)\n * - $1.3445555 → $1.3446 (≥$0.01: 5 sig figs)\n * - $0.333333 → $0.33333 (≥$0.01: 5 sig figs)\n * - $0.004236 → $0.004236 (<$0.01: 4 sig figs, max 6 decimals)\n * - $0.0000006 → $0.000001 (<$0.01: 4 sig figs, rounds with max 6 decimals)\n */\nexport const PRICE_RANGES_UNIVERSAL: FiatRangeConfig[] = [\n {\n // Very high values (> $100,000): No decimals, 6 significant figures\n // Ex: $123,456.78 → $123,457\n condition: (val) => Math.abs(val) > PRICE_THRESHOLD.VERY_HIGH,\n minimumDecimals: 0,\n maximumDecimals: 0,\n significantDigits: 6,\n threshold: PRICE_THRESHOLD.VERY_HIGH,\n },\n {\n // High values ($10,000-$100,000]: No decimals, 5 significant figures\n // Ex: $12,345.67 → $12,346\n condition: (val) => Math.abs(val) > PRICE_THRESHOLD.HIGH,\n minimumDecimals: 0,\n maximumDecimals: 0,\n significantDigits: 5,\n threshold: PRICE_THRESHOLD.HIGH,\n },\n {\n // Large values ($1,000-$10,000]: Max 1 decimal, 5 significant figures\n // Ex: $1,234.56 → $1,234.6\n condition: (val) => Math.abs(val) > PRICE_THRESHOLD.LARGE,\n minimumDecimals: 0,\n maximumDecimals: 1,\n significantDigits: 5,\n threshold: PRICE_THRESHOLD.LARGE,\n },\n {\n // Medium values ($100-$1,000]: Max 2 decimals, 5 significant figures\n // Ex: $123.456 → $123.46\n condition: (val) => Math.abs(val) > PRICE_THRESHOLD.MEDIUM,\n minimumDecimals: 0,\n maximumDecimals: 2,\n significantDigits: 5,\n threshold: PRICE_THRESHOLD.MEDIUM,\n },\n {\n // Medium-low values ($10-$100]: Max 4 decimals, 5 significant figures\n // Ex: $12.34567 → $12.346\n condition: (val) => Math.abs(val) > PRICE_THRESHOLD.MEDIUM_LOW,\n minimumDecimals: 0,\n maximumDecimals: 4,\n significantDigits: 5,\n threshold: PRICE_THRESHOLD.MEDIUM_LOW,\n },\n {\n // Low values ($0.01-$10]: 5 significant figures, min 2 max MAX_PRICE_DECIMALS decimals\n // Ex: $1.3445555 → $1.3446 | $0.333333 → $0.33333\n condition: (val) => Math.abs(val) >= PRICE_THRESHOLD.LOW,\n significantDigits: 5,\n minimumDecimals: 2,\n maximumDecimals: DECIMAL_PRECISION_CONFIG.MaxPriceDecimals,\n threshold: PRICE_THRESHOLD.LOW,\n },\n {\n // Very small values (< $0.01): 4 significant figures, min 2 max MAX_PRICE_DECIMALS decimals\n // Ex: $0.004236 → $0.004236 | $0.0000006 → $0.000001\n condition: () => true,\n significantDigits: 4,\n minimumDecimals: 2,\n maximumDecimals: DECIMAL_PRECISION_CONFIG.MaxPriceDecimals,\n threshold: PRICE_THRESHOLD.VERY_SMALL,\n },\n];\n\n/**\n * Formats a balance value as USD currency with appropriate decimal places\n *\n * @param balance - Raw numeric balance value (e.g., 1234.56, not token minimal denomination)\n * @param options - Optional formatting options\n * @param options.minimumDecimals - Global minimum decimal places (overrides range configs)\n * @param options.maximumDecimals - Global maximum decimal places (overrides range configs)\n * @param options.significantDigits - Global significant digits (overrides decimal settings when set)\n * @param options.ranges - Custom range configurations (defaults to PRICE_RANGES_MINIMAL_VIEW)\n * @param options.currency - Currency code (default: 'USD')\n * @param options.locale - Locale for formatting (default: 'en-US')\n * @param options.stripTrailingZeros - Strip trailing zeros from output (default: false via PRICE_RANGES_MINIMAL_VIEW). When true, overrides minimumDecimals constraint.\n * @returns Formatted currency string with variable decimals based on configured ranges\n * @example\n * // Using defaults (preserves trailing zeros for fiat)\n * formatPerpsFiat(1234.56) => \"$1,234.56\"\n * formatPerpsFiat(1250.00) => \"$1,250.00\" // Trailing zeros preserved\n * formatPerpsFiat(50000) => \"$50,000.00\" // Trailing zeros preserved\n *\n * // Stripping trailing zeros when needed (e.g., for crypto)\n * formatPerpsFiat(1250, { stripTrailingZeros: true }) => \"$1,250\"\n *\n * // With custom ranges\n * formatPerpsFiat(0.00001, {\n * ranges: [\n * { condition: (v) => v < 0.001, minimumDecimals: 6, maximumDecimals: 8 },\n * { condition: () => true, minimumDecimals: 2, maximumDecimals: 2 }\n * ]\n * }) => \"$0.00001\" // Trailing zero stripped\n *\n * // With significant digits\n * formatPerpsFiat(1234.56789, { significantDigits: 5 }) => \"$1,234.6\"\n * formatPerpsFiat(0.0001234, { significantDigits: 3 }) => \"$0.000123\"\n */\nexport const formatPerpsFiat = (\n balance: string | number,\n options?: {\n minimumDecimals?: number;\n maximumDecimals?: number;\n significantDigits?: number;\n ranges?: FiatRangeConfig[];\n currency?: string;\n locale?: string;\n stripTrailingZeros?: boolean;\n },\n): string => {\n const value = typeof balance === 'string' ? parseFloat(balance) : balance;\n const currency = options?.currency ?? 'USD';\n\n let formatted: string;\n\n if (isNaN(value)) {\n // Return placeholder for invalid values to avoid confusion with actual $0 values\n return PERPS_CONSTANTS.FallbackPriceDisplay;\n }\n\n // Use custom ranges or defaults\n const ranges = options?.ranges ?? PRICE_RANGES_MINIMAL_VIEW;\n\n // Find the first matching range configuration\n const rangeConfig = ranges.find((range) => range.condition(value));\n\n if (rangeConfig) {\n // Check for significant digits (global or range-specific)\n const sigDigits =\n options?.significantDigits ?? rangeConfig.significantDigits;\n\n // If significant digits are specified, use them\n if (sigDigits) {\n // Get min/max decimals (global overrides range, range overrides default)\n const minDecimals =\n options?.minimumDecimals ?? rangeConfig.minimumDecimals;\n const maxDecimals =\n options?.maximumDecimals ?? rangeConfig.maximumDecimals;\n\n // Calculate appropriate formatting based on significant digits\n const { value: formattedValue, decimals } = formatWithSignificantDigits(\n value,\n sigDigits,\n minDecimals,\n maxDecimals,\n );\n\n // Format with the calculated decimal places\n formatted = _formatWithThreshold(\n formattedValue,\n rangeConfig.threshold ?? 0.01,\n {\n currency,\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals,\n },\n );\n } else {\n // Standard decimal-based formatting (existing logic)\n const minDecimals =\n options?.minimumDecimals ?? rangeConfig.minimumDecimals;\n const maxDecimals =\n options?.maximumDecimals ?? rangeConfig.maximumDecimals;\n\n // Use custom formatting if provided\n if (rangeConfig.customFormat) {\n formatted = rangeConfig.customFormat(\n value,\n options?.locale ?? 'en-US',\n currency,\n );\n } else {\n // Use standard formatting with threshold\n formatted = _formatWithThreshold(value, rangeConfig.threshold ?? 0.01, {\n currency,\n minimumFractionDigits: minDecimals,\n maximumFractionDigits: maxDecimals,\n });\n }\n }\n } else {\n // Fallback if no range matches (shouldn't happen with proper default config)\n const fallbackMin = options?.minimumDecimals ?? 2;\n const fallbackMax = options?.maximumDecimals ?? 2;\n formatted = _formatWithThreshold(value, 0.01, {\n currency,\n minimumFractionDigits: fallbackMin,\n maximumFractionDigits: fallbackMax,\n });\n }\n\n // Post-process: strip trailing zeros unless explicitly disabled\n // Priority: explicit options.stripTrailingZeros false > rangeConfig > options default > true\n // If options.stripTrailingZeros is explicitly false, skip stripping entirely\n if (options?.stripTrailingZeros === false) {\n return formatted;\n }\n\n // Otherwise check range config or default to true\n const shouldStrip =\n rangeConfig?.stripTrailingZeros ?? options?.stripTrailingZeros ?? true;\n\n if (shouldStrip) {\n // Check if fiat-style stripping is enabled (only strips .00)\n const useFiatStyle = rangeConfig?.fiatStyleStripping ?? false;\n\n if (useFiatStyle) {\n // Fiat-style: Only strip .00 (no meaningful decimals), preserve 2-decimal format\n // Examples: $1,250.00 → $1,250 | $1,000.10 → $1,000.10 | $13.40 → $13.40\n return formatted.replace(/\\.00$/u, '');\n }\n // Standard: Strip all trailing zeros after decimal point\n // Examples: $1,250.00 → $1,250 | $100.0 → $100 | $10.5 → $10.5 | $1.234 → $1.234\n return formatted.replace(/(\\.\\d*?)0+$/u, '$1').replace(/\\.$/u, '');\n }\n\n return formatted;\n};\n\n/**\n * Formats position size with variable decimal precision based on magnitude or asset-specific decimals\n * Removes trailing zeros to match task requirements\n *\n * @param size - Raw position size value\n * @param szDecimals - Optional asset-specific decimal precision from Hyperliquid metadata (e.g., BTC=5, ETH=4, DOGE=1)\n * @returns Format varies by size or uses asset-specific decimals, with trailing zeros removed:\n * If szDecimals provided: Uses exact decimals (e.g., 0.00009 BTC with szDecimals=5 => \"0.00009\")\n * Otherwise falls back to magnitude-based logic:\n * - Size < 0.01: Up to 6 decimals (e.g., \"0.00009\" not \"0.000090\")\n * - Size < 1: Up to 4 decimals (e.g., \"0.0024\" not \"0.002400\")\n * - Size >= 1: Up to 2 decimals (e.g., \"44\" not \"44.00\")\n * @example formatPositionSize(0.00009, 5) => \"0.00009\" (uses szDecimals)\n * @example formatPositionSize(44.00, 1) => \"44\" (uses szDecimals, trailing zeros removed)\n * @example formatPositionSize(0.0024) => \"0.0024\" (no szDecimals, uses magnitude logic)\n * @example formatPositionSize(44.00) => \"44\" (no szDecimals, uses magnitude logic)\n */\nexport const formatPositionSize = (\n size: string | number,\n szDecimals?: number,\n): string => {\n const value = typeof size === 'string' ? parseFloat(size) : size;\n\n if (isNaN(value) || value === 0) {\n return '0';\n }\n\n // Use asset-specific decimals if provided (Hyperliquid metadata)\n if (szDecimals !== undefined) {\n const fixed = value.toFixed(szDecimals);\n // Only strip trailing zeros when a decimal point is present; toFixed(0)\n // returns an integer string and the regex would otherwise eat valid zeros\n // on whole-unit assets (szDecimals=0), e.g. \"100\" -> \"1\".\n return fixed.includes('.') ? fixed.replace(/\\.?0+$/u, '') : fixed;\n }\n\n // Fallback: magnitude-based decimal logic for backwards compatibility\n const abs = Math.abs(value);\n let formatted: string;\n\n if (abs < 0.01) {\n // For very small numbers, use more decimal places\n formatted = value.toFixed(6);\n } else if (abs < 1) {\n // For small numbers, use 4 decimal places\n formatted = value.toFixed(4);\n } else {\n // For normal numbers, use 2 decimal places\n formatted = value.toFixed(2);\n }\n\n // Remove trailing zeros and unnecessary decimal point\n return formatted.replace(/\\.?0+$/u, '');\n};\n\n/**\n * Formats a PnL (Profit and Loss) value with sign prefix\n *\n * @param pnl - Raw numeric PnL value (positive for profit, negative for loss)\n * @returns Format: \"+$X,XXX.XX\" or \"-$X,XXX.XX\" (always shows sign, 2 decimals)\n * @example formatPnl(1234.56) => \"+$1,234.56\"\n * @example formatPnl(-500) => \"-$500.00\"\n * @example formatPnl(0) => \"+$0.00\"\n */\nexport const formatPnl = (pnl: string | number): string => {\n const value = typeof pnl === 'string' ? parseFloat(pnl) : pnl;\n\n if (isNaN(value)) {\n return PERPS_CONSTANTS.ZeroAmountDetailedDisplay;\n }\n\n const formatted = _formatCurrency(Math.abs(value), 'USD', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n\n return value >= 0 ? `+${formatted}` : `-${formatted}`;\n};\n\n/**\n * Formats a percentage value with sign prefix\n *\n * @param value - Raw percentage value (e.g., 5.25 for 5.25%, not 0.0525)\n * @param decimals - Number of decimal places to show (default: 2)\n * @returns Format: \"+X.XX%\" or \"-X.XX%\" (always shows sign, 2 decimals)\n * @example formatPercentage(5.25) => \"+5.25%\"\n * @example formatPercentage(-2.75) => \"-2.75%\"\n * @example formatPercentage(0) => \"+0.00%\"\n */\nexport const formatPercentage = (\n value: string | number,\n decimals: number = 2,\n): string => {\n const parsed = typeof value === 'string' ? parseFloat(value) : value;\n\n if (isNaN(parsed)) {\n return '0.00%';\n }\n\n return `${parsed >= 0 ? '+' : ''}${parsed.toFixed(decimals)}%`;\n};\n\n/**\n * Formats funding rate for display\n *\n * @param value - Raw funding rate value (decimal, not percentage)\n * @param options - Optional formatting options\n * @param options.showZero - Whether to return zero display value for zero/undefined (default: true)\n * @returns Formatted funding rate as percentage string\n * @example formatFundingRate(0.0005) => \"0.0500%\"\n * @example formatFundingRate(-0.0001) => \"-0.0100%\"\n * @example formatFundingRate(0.000000059) => \"<0.0001%\"\n * @example formatFundingRate(-0.000000059) => \"-<0.0001%\"\n * @example formatFundingRate(undefined) => \"0.0000%\"\n */\nexport const formatFundingRate = (\n value?: number | null,\n options?: { showZero?: boolean },\n): string => {\n const showZero = options?.showZero ?? true;\n\n if (value === undefined || value === null) {\n return showZero ? FUNDING_RATE_CONFIG.ZeroDisplay : '';\n }\n\n const percentage = value * FUNDING_RATE_CONFIG.PercentageMultiplier;\n const formatted = percentage.toFixed(FUNDING_RATE_CONFIG.Decimals);\n const minimumDisplayPercentage = 10 ** -FUNDING_RATE_CONFIG.Decimals;\n\n if (value !== 0 && parseFloat(formatted) === 0) {\n const threshold = minimumDisplayPercentage.toFixed(\n FUNDING_RATE_CONFIG.Decimals,\n );\n return value > 0 ? `<${threshold}%` : `-<${threshold}%`;\n }\n\n // Check if the result is effectively zero\n if (showZero && parseFloat(formatted) === 0) {\n return FUNDING_RATE_CONFIG.ZeroDisplay;\n }\n\n return `${formatted}%`;\n};\n"]}