@velocity-exchange/sdk 0.3.0 → 0.6.0

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 (1127) hide show
  1. package/README.md +3 -3
  2. package/lib/browser/accounts/basicUserAccountSubscriber.d.ts +18 -0
  3. package/lib/browser/accounts/basicUserAccountSubscriber.js +18 -0
  4. package/lib/browser/accounts/basicUserStatsAccountSubscriber.d.ts +18 -0
  5. package/lib/browser/accounts/basicUserStatsAccountSubscriber.js +18 -0
  6. package/lib/browser/accounts/bulkAccountLoader.d.ts +52 -0
  7. package/lib/browser/accounts/bulkAccountLoader.js +51 -0
  8. package/lib/browser/accounts/bulkUserStatsSubscription.d.ts +9 -2
  9. package/lib/browser/accounts/bulkUserStatsSubscription.js +9 -2
  10. package/lib/browser/accounts/bulkUserSubscription.d.ts +8 -2
  11. package/lib/browser/accounts/bulkUserSubscription.js +8 -2
  12. package/lib/browser/accounts/customizedCadenceBulkAccountLoader.d.ts +37 -0
  13. package/lib/browser/accounts/customizedCadenceBulkAccountLoader.js +37 -0
  14. package/lib/browser/accounts/fetch.d.ts +59 -2
  15. package/lib/browser/accounts/fetch.js +57 -2
  16. package/lib/browser/accounts/grpcAccountSubscriber.d.ts +30 -0
  17. package/lib/browser/accounts/grpcAccountSubscriber.js +30 -0
  18. package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +16 -0
  19. package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.js +16 -0
  20. package/lib/browser/accounts/grpcMultiAccountSubscriber.d.ts +60 -1
  21. package/lib/browser/accounts/grpcMultiAccountSubscriber.js +118 -37
  22. package/lib/browser/accounts/grpcMultiUserAccountSubscriber.d.ts +32 -0
  23. package/lib/browser/accounts/grpcMultiUserAccountSubscriber.js +40 -12
  24. package/lib/browser/accounts/grpcProgramAccountSubscriber.d.ts +33 -0
  25. package/lib/browser/accounts/grpcProgramAccountSubscriber.js +33 -0
  26. package/lib/browser/accounts/grpcUserAccountSubscriber.d.ts +15 -0
  27. package/lib/browser/accounts/grpcUserAccountSubscriber.js +15 -0
  28. package/lib/browser/accounts/grpcUserStatsAccountSubscriber.d.ts +15 -0
  29. package/lib/browser/accounts/grpcUserStatsAccountSubscriber.js +15 -0
  30. package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.d.ts +41 -0
  31. package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.js +41 -0
  32. package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +116 -0
  33. package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.js +152 -1
  34. package/lib/browser/accounts/laserProgramAccountSubscriber.d.ts +34 -0
  35. package/lib/browser/accounts/laserProgramAccountSubscriber.js +34 -0
  36. package/lib/browser/accounts/oneShotUserAccountSubscriber.d.ts +19 -0
  37. package/lib/browser/accounts/oneShotUserAccountSubscriber.js +19 -0
  38. package/lib/browser/accounts/oneShotUserStatsAccountSubscriber.d.ts +19 -0
  39. package/lib/browser/accounts/oneShotUserStatsAccountSubscriber.js +19 -0
  40. package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +31 -0
  41. package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.js +31 -0
  42. package/lib/browser/accounts/pollingOracleAccountSubscriber.d.ts +19 -0
  43. package/lib/browser/accounts/pollingOracleAccountSubscriber.js +21 -2
  44. package/lib/browser/accounts/pollingTokenAccountSubscriber.d.ts +22 -0
  45. package/lib/browser/accounts/pollingTokenAccountSubscriber.js +22 -0
  46. package/lib/browser/accounts/pollingUserAccountSubscriber.d.ts +32 -0
  47. package/lib/browser/accounts/pollingUserAccountSubscriber.js +32 -0
  48. package/lib/browser/accounts/pollingUserStatsAccountSubscriber.d.ts +22 -0
  49. package/lib/browser/accounts/pollingUserStatsAccountSubscriber.js +22 -0
  50. package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.d.ts +83 -0
  51. package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.js +84 -1
  52. package/lib/browser/accounts/testBulkAccountLoader.d.ts +8 -0
  53. package/lib/browser/accounts/testBulkAccountLoader.js +8 -0
  54. package/lib/browser/accounts/types.d.ts +149 -0
  55. package/lib/browser/accounts/types.js +13 -0
  56. package/lib/browser/accounts/utils.d.ts +18 -0
  57. package/lib/browser/accounts/utils.js +32 -16
  58. package/lib/browser/accounts/webSocketAccountSubscriber.d.ts +41 -0
  59. package/lib/browser/accounts/webSocketAccountSubscriber.js +41 -0
  60. package/lib/browser/accounts/webSocketAccountSubscriberV2.d.ts +31 -0
  61. package/lib/browser/accounts/webSocketAccountSubscriberV2.js +31 -23
  62. package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +27 -0
  63. package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +27 -0
  64. package/lib/browser/accounts/webSocketProgramAccountSubscriber.d.ts +36 -0
  65. package/lib/browser/accounts/webSocketProgramAccountSubscriber.js +36 -0
  66. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.d.ts +21 -0
  67. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.js +25 -0
  68. package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.d.ts +21 -0
  69. package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.js +21 -0
  70. package/lib/browser/accounts/webSocketUserAccountSubscriber.d.ts +26 -0
  71. package/lib/browser/accounts/webSocketUserAccountSubscriber.js +26 -0
  72. package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  73. package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.js +20 -0
  74. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.d.ts +121 -0
  75. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.js +123 -2
  76. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +96 -0
  77. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.js +108 -0
  78. package/lib/browser/accounts/websocketProgramUserAccountSubscriber.d.ts +28 -0
  79. package/lib/browser/accounts/websocketProgramUserAccountSubscriber.js +33 -0
  80. package/lib/browser/addresses/marketAddresses.d.ts +10 -0
  81. package/lib/browser/addresses/marketAddresses.js +10 -0
  82. package/lib/browser/addresses/pda.d.ts +214 -2
  83. package/lib/browser/addresses/pda.js +217 -5
  84. package/lib/browser/adminClient.d.ts +2171 -4
  85. package/lib/browser/adminClient.js +2215 -4
  86. package/lib/browser/auctionSubscriber/auctionSubscriber.d.ts +15 -0
  87. package/lib/browser/auctionSubscriber/auctionSubscriber.js +15 -0
  88. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.d.ts +19 -0
  89. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.js +19 -0
  90. package/lib/browser/auctionSubscriber/index.d.ts +6 -0
  91. package/lib/browser/auctionSubscriber/index.js +6 -0
  92. package/lib/browser/auctionSubscriber/types.d.ts +7 -0
  93. package/lib/browser/blockhashSubscriber/BlockhashSubscriber.d.ts +33 -0
  94. package/lib/browser/blockhashSubscriber/BlockhashSubscriber.js +33 -0
  95. package/lib/browser/blockhashSubscriber/index.d.ts +5 -0
  96. package/lib/browser/blockhashSubscriber/index.js +5 -0
  97. package/lib/browser/blockhashSubscriber/types.d.ts +5 -0
  98. package/lib/browser/clock/clockSubscriber.d.ts +24 -0
  99. package/lib/browser/clock/clockSubscriber.js +22 -0
  100. package/lib/browser/config.d.ts +58 -4
  101. package/lib/browser/config.js +94 -28
  102. package/lib/browser/constants/numericConstants.d.ts +67 -0
  103. package/lib/browser/constants/numericConstants.js +68 -1
  104. package/lib/browser/constants/perpMarkets.d.ts +10 -0
  105. package/lib/browser/constants/perpMarkets.js +40 -908
  106. package/lib/browser/constants/spotMarkets.d.ts +13 -0
  107. package/lib/browser/constants/spotMarkets.js +16 -742
  108. package/lib/browser/constants/txConstants.d.ts +1 -0
  109. package/lib/browser/constants/txConstants.js +1 -0
  110. package/lib/browser/core/VelocityCore.d.ts +285 -8
  111. package/lib/browser/core/VelocityCore.js +281 -8
  112. package/lib/browser/core/instructions/deposit.d.ts +22 -0
  113. package/lib/browser/core/instructions/deposit.js +22 -0
  114. package/lib/browser/core/instructions/fill.d.ts +17 -0
  115. package/lib/browser/core/instructions/fill.js +17 -0
  116. package/lib/browser/core/instructions/funding.d.ts +12 -0
  117. package/lib/browser/core/instructions/funding.js +12 -0
  118. package/lib/browser/core/instructions/liquidation.d.ts +18 -0
  119. package/lib/browser/core/instructions/liquidation.js +18 -0
  120. package/lib/browser/core/instructions/orders.d.ts +28 -0
  121. package/lib/browser/core/instructions/orders.js +28 -0
  122. package/lib/browser/core/instructions/perpOrders.d.ts +106 -0
  123. package/lib/browser/core/instructions/perpOrders.js +106 -0
  124. package/lib/browser/core/instructions/settlement.d.ts +14 -0
  125. package/lib/browser/core/instructions/settlement.js +14 -0
  126. package/lib/browser/core/instructions/trigger.d.ts +15 -0
  127. package/lib/browser/core/instructions/trigger.js +15 -0
  128. package/lib/browser/core/instructions/withdraw.d.ts +21 -0
  129. package/lib/browser/core/instructions/withdraw.js +21 -0
  130. package/lib/browser/core/remainingAccounts.d.ts +47 -3
  131. package/lib/browser/core/remainingAccounts.js +20 -0
  132. package/lib/browser/core/signedMsg.d.ts +38 -0
  133. package/lib/browser/core/signedMsg.js +33 -0
  134. package/lib/browser/decode/customCoder.d.ts +39 -3
  135. package/lib/browser/decode/customCoder.js +45 -3
  136. package/lib/browser/decode/user.d.ts +22 -0
  137. package/lib/browser/decode/user.js +27 -1
  138. package/lib/browser/dlob/DLOB.d.ts +502 -53
  139. package/lib/browser/dlob/DLOB.js +540 -98
  140. package/lib/browser/dlob/DLOBNode.d.ts +86 -4
  141. package/lib/browser/dlob/DLOBNode.js +37 -4
  142. package/lib/browser/dlob/DLOBSubscriber.d.ts +39 -12
  143. package/lib/browser/dlob/DLOBSubscriber.js +42 -12
  144. package/lib/browser/dlob/NodeList.d.ts +69 -0
  145. package/lib/browser/dlob/NodeList.js +66 -0
  146. package/lib/browser/dlob/orderBookLevels.d.ts +106 -13
  147. package/lib/browser/dlob/orderBookLevels.js +84 -14
  148. package/lib/browser/dlob/types.d.ts +15 -0
  149. package/lib/browser/events/eventList.d.ts +14 -0
  150. package/lib/browser/events/eventList.js +14 -0
  151. package/lib/browser/events/eventSubscriber.d.ts +87 -10
  152. package/lib/browser/events/eventSubscriber.js +93 -8
  153. package/lib/browser/events/eventsServerLogProvider.d.ts +22 -0
  154. package/lib/browser/events/eventsServerLogProvider.js +27 -0
  155. package/lib/browser/events/fetchLogs.d.ts +31 -0
  156. package/lib/browser/events/fetchLogs.js +46 -1
  157. package/lib/browser/events/parse.d.ts +23 -0
  158. package/lib/browser/events/parse.js +23 -0
  159. package/lib/browser/events/pollingLogProvider.d.ts +24 -0
  160. package/lib/browser/events/pollingLogProvider.js +24 -0
  161. package/lib/browser/events/sort.d.ts +11 -0
  162. package/lib/browser/events/sort.js +12 -0
  163. package/lib/browser/events/txEventCache.d.ts +13 -3
  164. package/lib/browser/events/txEventCache.js +19 -7
  165. package/lib/browser/events/types.d.ts +118 -2
  166. package/lib/browser/events/types.js +11 -0
  167. package/lib/browser/events/webSocketLogProvider.d.ts +23 -0
  168. package/lib/browser/events/webSocketLogProvider.js +28 -0
  169. package/lib/browser/factory/oracleClient.js +2 -2
  170. package/lib/browser/idl/velocity.d.ts +150 -7
  171. package/lib/browser/idl/velocity.json +151 -8
  172. package/lib/browser/keypair.d.ts +8 -0
  173. package/lib/browser/keypair.js +8 -0
  174. package/lib/browser/marginCalculation.d.ts +134 -2
  175. package/lib/browser/marginCalculation.js +121 -0
  176. package/lib/browser/math/amm.d.ts +348 -29
  177. package/lib/browser/math/amm.js +310 -32
  178. package/lib/browser/math/auction.d.ts +95 -19
  179. package/lib/browser/math/auction.js +118 -28
  180. package/lib/browser/math/bankruptcy.d.ts +46 -0
  181. package/lib/browser/math/bankruptcy.js +89 -1
  182. package/lib/browser/math/builder.d.ts +64 -8
  183. package/lib/browser/math/builder.js +71 -9
  184. package/lib/browser/math/conversion.d.ts +21 -0
  185. package/lib/browser/math/conversion.js +21 -0
  186. package/lib/browser/math/exchangeStatus.d.ts +91 -0
  187. package/lib/browser/math/exchangeStatus.js +106 -3
  188. package/lib/browser/math/funding.d.ts +57 -20
  189. package/lib/browser/math/funding.js +63 -23
  190. package/lib/browser/math/insurance.d.ts +62 -0
  191. package/lib/browser/math/insurance.js +62 -0
  192. package/lib/browser/math/liquidation.d.ts +127 -11
  193. package/lib/browser/math/liquidation.js +182 -19
  194. package/lib/browser/math/margin.d.ts +79 -13
  195. package/lib/browser/math/margin.js +80 -14
  196. package/lib/browser/math/market.d.ts +135 -15
  197. package/lib/browser/math/market.js +145 -17
  198. package/lib/browser/math/oracles.d.ts +113 -0
  199. package/lib/browser/math/oracles.js +118 -1
  200. package/lib/browser/math/orders.d.ts +115 -10
  201. package/lib/browser/math/orders.js +130 -19
  202. package/lib/browser/math/position.d.ts +80 -33
  203. package/lib/browser/math/position.js +80 -33
  204. package/lib/browser/math/repeg.d.ts +48 -10
  205. package/lib/browser/math/repeg.js +48 -10
  206. package/lib/browser/math/spotBalance.d.ts +200 -5
  207. package/lib/browser/math/spotBalance.js +239 -10
  208. package/lib/browser/math/spotMarket.d.ts +36 -3
  209. package/lib/browser/math/spotMarket.js +36 -3
  210. package/lib/browser/math/spotPosition.d.ts +72 -0
  211. package/lib/browser/math/spotPosition.js +62 -0
  212. package/lib/browser/math/state.d.ts +31 -0
  213. package/lib/browser/math/state.js +31 -0
  214. package/lib/browser/math/superStake.d.ts +126 -2
  215. package/lib/browser/math/superStake.js +123 -3
  216. package/lib/browser/math/tiers.d.ts +29 -0
  217. package/lib/browser/math/tiers.js +29 -0
  218. package/lib/browser/math/trade.d.ts +102 -51
  219. package/lib/browser/math/trade.js +101 -55
  220. package/lib/browser/math/utils.d.ts +71 -9
  221. package/lib/browser/math/utils.js +71 -9
  222. package/lib/browser/memcmp.d.ts +94 -0
  223. package/lib/browser/memcmp.js +103 -2
  224. package/lib/browser/oracles/oracleClientCache.d.ts +16 -0
  225. package/lib/browser/oracles/oracleClientCache.js +16 -0
  226. package/lib/browser/oracles/oracleId.d.ts +31 -0
  227. package/lib/browser/oracles/oracleId.js +39 -8
  228. package/lib/browser/oracles/prelaunchOracleClient.d.ts +20 -0
  229. package/lib/browser/oracles/prelaunchOracleClient.js +20 -0
  230. package/lib/browser/oracles/pythClient.d.ts +31 -0
  231. package/lib/browser/oracles/pythClient.js +32 -1
  232. package/lib/browser/oracles/pythLazerClient.d.ts +34 -0
  233. package/lib/browser/oracles/pythLazerClient.js +35 -1
  234. package/lib/browser/oracles/quoteAssetOracleClient.d.ts +18 -0
  235. package/lib/browser/oracles/quoteAssetOracleClient.js +18 -0
  236. package/lib/browser/oracles/strictOraclePrice.d.ts +21 -0
  237. package/lib/browser/oracles/strictOraclePrice.js +21 -0
  238. package/lib/browser/oracles/types.d.ts +45 -0
  239. package/lib/browser/oracles/utils.d.ts +20 -0
  240. package/lib/browser/oracles/utils.js +20 -0
  241. package/lib/browser/orderParams.d.ts +42 -4
  242. package/lib/browser/orderParams.js +42 -4
  243. package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +56 -0
  244. package/lib/browser/orderSubscriber/OrderSubscriber.js +59 -0
  245. package/lib/browser/orderSubscriber/PollingSubscription.d.ts +11 -0
  246. package/lib/browser/orderSubscriber/PollingSubscription.js +11 -0
  247. package/lib/browser/orderSubscriber/WebsocketSubscription.d.ts +18 -0
  248. package/lib/browser/orderSubscriber/WebsocketSubscription.js +18 -0
  249. package/lib/browser/orderSubscriber/grpcSubscription.d.ts +16 -0
  250. package/lib/browser/orderSubscriber/grpcSubscription.js +16 -0
  251. package/lib/browser/orderSubscriber/types.d.ts +9 -0
  252. package/lib/browser/priorityFee/averageOverSlotsStrategy.d.ts +1 -0
  253. package/lib/browser/priorityFee/averageOverSlotsStrategy.js +1 -0
  254. package/lib/browser/priorityFee/averageStrategy.d.ts +1 -0
  255. package/lib/browser/priorityFee/averageStrategy.js +1 -0
  256. package/lib/browser/priorityFee/ewmaStrategy.d.ts +10 -0
  257. package/lib/browser/priorityFee/ewmaStrategy.js +10 -0
  258. package/lib/browser/priorityFee/heliusPriorityFeeMethod.d.ts +13 -0
  259. package/lib/browser/priorityFee/heliusPriorityFeeMethod.js +9 -2
  260. package/lib/browser/priorityFee/maxOverSlotsStrategy.d.ts +1 -0
  261. package/lib/browser/priorityFee/maxOverSlotsStrategy.js +1 -0
  262. package/lib/browser/priorityFee/maxStrategy.d.ts +1 -0
  263. package/lib/browser/priorityFee/maxStrategy.js +1 -0
  264. package/lib/browser/priorityFee/priorityFeeSubscriber.d.ts +39 -0
  265. package/lib/browser/priorityFee/priorityFeeSubscriber.js +39 -0
  266. package/lib/browser/priorityFee/priorityFeeSubscriberMap.d.ts +20 -1
  267. package/lib/browser/priorityFee/priorityFeeSubscriberMap.js +21 -2
  268. package/lib/browser/priorityFee/solanaPriorityFeeMethod.d.ts +12 -0
  269. package/lib/browser/priorityFee/solanaPriorityFeeMethod.js +10 -0
  270. package/lib/browser/priorityFee/types.d.ts +32 -0
  271. package/lib/browser/priorityFee/types.js +5 -0
  272. package/lib/browser/priorityFee/velocityPriorityFeeMethod.d.ts +11 -0
  273. package/lib/browser/priorityFee/velocityPriorityFeeMethod.js +8 -0
  274. package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
  275. package/lib/browser/slot/SlotSubscriber.d.ts +18 -0
  276. package/lib/browser/slot/SlotSubscriber.js +16 -0
  277. package/lib/browser/slot/SlothashSubscriber.d.ts +26 -0
  278. package/lib/browser/slot/SlothashSubscriber.js +25 -1
  279. package/lib/browser/tx/baseTxSender.d.ts +163 -0
  280. package/lib/browser/tx/baseTxSender.js +174 -6
  281. package/lib/browser/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +12 -0
  282. package/lib/browser/tx/blockhashFetcher/baseBlockhashFetcher.js +12 -0
  283. package/lib/browser/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +15 -0
  284. package/lib/browser/tx/blockhashFetcher/cachedBlockhashFetcher.js +15 -0
  285. package/lib/browser/tx/blockhashFetcher/types.d.ts +4 -0
  286. package/lib/browser/tx/fastSingleTxSender.d.ts +47 -0
  287. package/lib/browser/tx/fastSingleTxSender.js +48 -1
  288. package/lib/browser/tx/forwardOnlyTxSender.d.ts +48 -0
  289. package/lib/browser/tx/forwardOnlyTxSender.js +48 -0
  290. package/lib/browser/tx/reportTransactionError.d.ts +18 -6
  291. package/lib/browser/tx/reportTransactionError.js +18 -6
  292. package/lib/browser/tx/retryTxSender.d.ts +40 -0
  293. package/lib/browser/tx/retryTxSender.js +39 -0
  294. package/lib/browser/tx/txHandler.d.ts +146 -35
  295. package/lib/browser/tx/txHandler.js +132 -32
  296. package/lib/browser/tx/txParamProcessor.d.ts +47 -0
  297. package/lib/browser/tx/txParamProcessor.js +47 -0
  298. package/lib/browser/tx/types.d.ts +46 -0
  299. package/lib/browser/tx/types.js +5 -0
  300. package/lib/browser/tx/utils.d.ts +26 -0
  301. package/lib/browser/tx/utils.js +26 -0
  302. package/lib/browser/tx/whileValidTxSender.d.ts +82 -0
  303. package/lib/browser/tx/whileValidTxSender.js +81 -0
  304. package/lib/browser/types.d.ts +785 -13
  305. package/lib/browser/types.js +126 -9
  306. package/lib/browser/user.d.ts +660 -84
  307. package/lib/browser/user.js +816 -97
  308. package/lib/browser/userMap/PollingSubscription.d.ts +10 -0
  309. package/lib/browser/userMap/PollingSubscription.js +14 -2
  310. package/lib/browser/userMap/WebsocketSubscription.d.ts +9 -0
  311. package/lib/browser/userMap/WebsocketSubscription.js +9 -0
  312. package/lib/browser/userMap/grpcSubscription.d.ts +8 -0
  313. package/lib/browser/userMap/grpcSubscription.js +8 -0
  314. package/lib/browser/userMap/referrerMap.d.ts +72 -2
  315. package/lib/browser/userMap/referrerMap.js +84 -2
  316. package/lib/browser/userMap/revenueShareEscrowMap.d.ts +37 -10
  317. package/lib/browser/userMap/revenueShareEscrowMap.js +38 -11
  318. package/lib/browser/userMap/userMap.d.ts +81 -3
  319. package/lib/browser/userMap/userMap.js +81 -4
  320. package/lib/browser/userMap/userMapConfig.d.ts +23 -0
  321. package/lib/browser/userMap/userStatsMap.d.ts +22 -0
  322. package/lib/browser/userMap/userStatsMap.js +22 -0
  323. package/lib/browser/userName.d.ts +16 -0
  324. package/lib/browser/userName.js +16 -0
  325. package/lib/browser/userStats.d.ts +28 -1
  326. package/lib/browser/userStats.js +28 -1
  327. package/lib/browser/util/TransactionConfirmationManager.d.ts +33 -0
  328. package/lib/browser/util/TransactionConfirmationManager.js +33 -0
  329. package/lib/browser/util/chainClock.d.ts +24 -0
  330. package/lib/browser/util/chainClock.js +20 -0
  331. package/lib/browser/util/computeUnits.d.ts +32 -0
  332. package/lib/browser/util/computeUnits.js +32 -0
  333. package/lib/browser/util/digest.d.ts +17 -0
  334. package/lib/browser/util/digest.js +17 -0
  335. package/lib/browser/util/ed25519Utils.d.ts +12 -2
  336. package/lib/browser/util/ed25519Utils.js +12 -2
  337. package/lib/browser/util/promiseTimeout.d.ts +9 -0
  338. package/lib/browser/util/promiseTimeout.js +9 -0
  339. package/lib/browser/velocityClient.d.ts +3363 -220
  340. package/lib/browser/velocityClient.js +3514 -275
  341. package/lib/browser/wallet.d.ts +37 -0
  342. package/lib/browser/wallet.js +37 -0
  343. package/lib/node/accounts/basicUserAccountSubscriber.d.ts +18 -0
  344. package/lib/node/accounts/basicUserAccountSubscriber.d.ts.map +1 -1
  345. package/lib/node/accounts/basicUserAccountSubscriber.js +18 -0
  346. package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts +18 -0
  347. package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts.map +1 -1
  348. package/lib/node/accounts/basicUserStatsAccountSubscriber.js +18 -0
  349. package/lib/node/accounts/bulkAccountLoader.d.ts +52 -0
  350. package/lib/node/accounts/bulkAccountLoader.d.ts.map +1 -1
  351. package/lib/node/accounts/bulkAccountLoader.js +51 -0
  352. package/lib/node/accounts/bulkUserStatsSubscription.d.ts +9 -2
  353. package/lib/node/accounts/bulkUserStatsSubscription.d.ts.map +1 -1
  354. package/lib/node/accounts/bulkUserStatsSubscription.js +9 -2
  355. package/lib/node/accounts/bulkUserSubscription.d.ts +8 -2
  356. package/lib/node/accounts/bulkUserSubscription.d.ts.map +1 -1
  357. package/lib/node/accounts/bulkUserSubscription.js +8 -2
  358. package/lib/node/accounts/customizedCadenceBulkAccountLoader.d.ts +37 -0
  359. package/lib/node/accounts/customizedCadenceBulkAccountLoader.d.ts.map +1 -1
  360. package/lib/node/accounts/customizedCadenceBulkAccountLoader.js +37 -0
  361. package/lib/node/accounts/fetch.d.ts +59 -2
  362. package/lib/node/accounts/fetch.d.ts.map +1 -1
  363. package/lib/node/accounts/fetch.js +57 -2
  364. package/lib/node/accounts/grpcAccountSubscriber.d.ts +30 -0
  365. package/lib/node/accounts/grpcAccountSubscriber.d.ts.map +1 -1
  366. package/lib/node/accounts/grpcAccountSubscriber.js +30 -0
  367. package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +16 -0
  368. package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts.map +1 -1
  369. package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.js +16 -0
  370. package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts +60 -1
  371. package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts.map +1 -1
  372. package/lib/node/accounts/grpcMultiAccountSubscriber.js +118 -37
  373. package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts +32 -0
  374. package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts.map +1 -1
  375. package/lib/node/accounts/grpcMultiUserAccountSubscriber.js +40 -12
  376. package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts +33 -0
  377. package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts.map +1 -1
  378. package/lib/node/accounts/grpcProgramAccountSubscriber.js +33 -0
  379. package/lib/node/accounts/grpcUserAccountSubscriber.d.ts +15 -0
  380. package/lib/node/accounts/grpcUserAccountSubscriber.d.ts.map +1 -1
  381. package/lib/node/accounts/grpcUserAccountSubscriber.js +15 -0
  382. package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts +15 -0
  383. package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts.map +1 -1
  384. package/lib/node/accounts/grpcUserStatsAccountSubscriber.js +15 -0
  385. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts +41 -0
  386. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts.map +1 -1
  387. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.js +41 -0
  388. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +116 -0
  389. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts.map +1 -1
  390. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.js +152 -1
  391. package/lib/node/accounts/laserProgramAccountSubscriber.d.ts +34 -0
  392. package/lib/node/accounts/laserProgramAccountSubscriber.d.ts.map +1 -1
  393. package/lib/node/accounts/laserProgramAccountSubscriber.js +34 -0
  394. package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts +19 -0
  395. package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts.map +1 -1
  396. package/lib/node/accounts/oneShotUserAccountSubscriber.js +19 -0
  397. package/lib/node/accounts/oneShotUserStatsAccountSubscriber.d.ts +19 -0
  398. package/lib/node/accounts/oneShotUserStatsAccountSubscriber.d.ts.map +1 -1
  399. package/lib/node/accounts/oneShotUserStatsAccountSubscriber.js +19 -0
  400. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +31 -0
  401. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts.map +1 -1
  402. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.js +31 -0
  403. package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts +19 -0
  404. package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts.map +1 -1
  405. package/lib/node/accounts/pollingOracleAccountSubscriber.js +21 -2
  406. package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts +22 -0
  407. package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts.map +1 -1
  408. package/lib/node/accounts/pollingTokenAccountSubscriber.js +22 -0
  409. package/lib/node/accounts/pollingUserAccountSubscriber.d.ts +32 -0
  410. package/lib/node/accounts/pollingUserAccountSubscriber.d.ts.map +1 -1
  411. package/lib/node/accounts/pollingUserAccountSubscriber.js +32 -0
  412. package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts +22 -0
  413. package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts.map +1 -1
  414. package/lib/node/accounts/pollingUserStatsAccountSubscriber.js +22 -0
  415. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts +83 -0
  416. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts.map +1 -1
  417. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.js +84 -1
  418. package/lib/node/accounts/testBulkAccountLoader.d.ts +8 -0
  419. package/lib/node/accounts/testBulkAccountLoader.d.ts.map +1 -1
  420. package/lib/node/accounts/testBulkAccountLoader.js +8 -0
  421. package/lib/node/accounts/types.d.ts +149 -0
  422. package/lib/node/accounts/types.d.ts.map +1 -1
  423. package/lib/node/accounts/types.js +13 -0
  424. package/lib/node/accounts/utils.d.ts +18 -0
  425. package/lib/node/accounts/utils.d.ts.map +1 -1
  426. package/lib/node/accounts/utils.js +32 -16
  427. package/lib/node/accounts/webSocketAccountSubscriber.d.ts +41 -0
  428. package/lib/node/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  429. package/lib/node/accounts/webSocketAccountSubscriber.js +41 -0
  430. package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts +31 -0
  431. package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts.map +1 -1
  432. package/lib/node/accounts/webSocketAccountSubscriberV2.js +31 -23
  433. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +27 -0
  434. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts.map +1 -1
  435. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +27 -0
  436. package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts +36 -0
  437. package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts.map +1 -1
  438. package/lib/node/accounts/webSocketProgramAccountSubscriber.js +36 -0
  439. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts +21 -0
  440. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts.map +1 -1
  441. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.js +25 -0
  442. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts +21 -0
  443. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts.map +1 -1
  444. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.js +21 -0
  445. package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts +26 -0
  446. package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts.map +1 -1
  447. package/lib/node/accounts/webSocketUserAccountSubscriber.js +26 -0
  448. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  449. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts.map +1 -1
  450. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.js +20 -0
  451. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts +121 -0
  452. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts.map +1 -1
  453. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.js +123 -2
  454. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +96 -0
  455. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts.map +1 -1
  456. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.js +108 -0
  457. package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts +28 -0
  458. package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts.map +1 -1
  459. package/lib/node/accounts/websocketProgramUserAccountSubscriber.js +33 -0
  460. package/lib/node/addresses/marketAddresses.d.ts +10 -0
  461. package/lib/node/addresses/marketAddresses.d.ts.map +1 -1
  462. package/lib/node/addresses/marketAddresses.js +10 -0
  463. package/lib/node/addresses/pda.d.ts +214 -2
  464. package/lib/node/addresses/pda.d.ts.map +1 -1
  465. package/lib/node/addresses/pda.js +217 -5
  466. package/lib/node/adminClient.d.ts +2171 -4
  467. package/lib/node/adminClient.d.ts.map +1 -1
  468. package/lib/node/adminClient.js +2215 -4
  469. package/lib/node/auctionSubscriber/auctionSubscriber.d.ts +15 -0
  470. package/lib/node/auctionSubscriber/auctionSubscriber.d.ts.map +1 -1
  471. package/lib/node/auctionSubscriber/auctionSubscriber.js +15 -0
  472. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts +19 -0
  473. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts.map +1 -1
  474. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.js +19 -0
  475. package/lib/node/auctionSubscriber/index.d.ts +6 -0
  476. package/lib/node/auctionSubscriber/index.d.ts.map +1 -1
  477. package/lib/node/auctionSubscriber/index.js +6 -0
  478. package/lib/node/auctionSubscriber/types.d.ts +7 -0
  479. package/lib/node/auctionSubscriber/types.d.ts.map +1 -1
  480. package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts +33 -0
  481. package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts.map +1 -1
  482. package/lib/node/blockhashSubscriber/BlockhashSubscriber.js +33 -0
  483. package/lib/node/blockhashSubscriber/index.d.ts +5 -0
  484. package/lib/node/blockhashSubscriber/index.d.ts.map +1 -1
  485. package/lib/node/blockhashSubscriber/index.js +5 -0
  486. package/lib/node/blockhashSubscriber/types.d.ts +5 -0
  487. package/lib/node/blockhashSubscriber/types.d.ts.map +1 -1
  488. package/lib/node/clock/clockSubscriber.d.ts +24 -0
  489. package/lib/node/clock/clockSubscriber.d.ts.map +1 -1
  490. package/lib/node/clock/clockSubscriber.js +22 -0
  491. package/lib/node/config.d.ts +58 -4
  492. package/lib/node/config.d.ts.map +1 -1
  493. package/lib/node/config.js +94 -28
  494. package/lib/node/constants/numericConstants.d.ts +67 -0
  495. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  496. package/lib/node/constants/numericConstants.js +68 -1
  497. package/lib/node/constants/perpMarkets.d.ts +10 -0
  498. package/lib/node/constants/perpMarkets.d.ts.map +1 -1
  499. package/lib/node/constants/perpMarkets.js +40 -908
  500. package/lib/node/constants/spotMarkets.d.ts +13 -0
  501. package/lib/node/constants/spotMarkets.d.ts.map +1 -1
  502. package/lib/node/constants/spotMarkets.js +16 -742
  503. package/lib/node/constants/txConstants.d.ts +1 -0
  504. package/lib/node/constants/txConstants.d.ts.map +1 -1
  505. package/lib/node/constants/txConstants.js +1 -0
  506. package/lib/node/core/VelocityCore.d.ts +285 -8
  507. package/lib/node/core/VelocityCore.d.ts.map +1 -1
  508. package/lib/node/core/VelocityCore.js +281 -8
  509. package/lib/node/core/instructions/deposit.d.ts +22 -0
  510. package/lib/node/core/instructions/deposit.d.ts.map +1 -1
  511. package/lib/node/core/instructions/deposit.js +22 -0
  512. package/lib/node/core/instructions/fill.d.ts +17 -0
  513. package/lib/node/core/instructions/fill.d.ts.map +1 -1
  514. package/lib/node/core/instructions/fill.js +17 -0
  515. package/lib/node/core/instructions/funding.d.ts +12 -0
  516. package/lib/node/core/instructions/funding.d.ts.map +1 -1
  517. package/lib/node/core/instructions/funding.js +12 -0
  518. package/lib/node/core/instructions/liquidation.d.ts +18 -0
  519. package/lib/node/core/instructions/liquidation.d.ts.map +1 -1
  520. package/lib/node/core/instructions/liquidation.js +18 -0
  521. package/lib/node/core/instructions/orders.d.ts +28 -0
  522. package/lib/node/core/instructions/orders.d.ts.map +1 -1
  523. package/lib/node/core/instructions/orders.js +28 -0
  524. package/lib/node/core/instructions/perpOrders.d.ts +106 -0
  525. package/lib/node/core/instructions/perpOrders.d.ts.map +1 -1
  526. package/lib/node/core/instructions/perpOrders.js +106 -0
  527. package/lib/node/core/instructions/settlement.d.ts +14 -0
  528. package/lib/node/core/instructions/settlement.d.ts.map +1 -1
  529. package/lib/node/core/instructions/settlement.js +14 -0
  530. package/lib/node/core/instructions/trigger.d.ts +15 -0
  531. package/lib/node/core/instructions/trigger.d.ts.map +1 -1
  532. package/lib/node/core/instructions/trigger.js +15 -0
  533. package/lib/node/core/instructions/withdraw.d.ts +21 -0
  534. package/lib/node/core/instructions/withdraw.d.ts.map +1 -1
  535. package/lib/node/core/instructions/withdraw.js +21 -0
  536. package/lib/node/core/remainingAccounts.d.ts +47 -3
  537. package/lib/node/core/remainingAccounts.d.ts.map +1 -1
  538. package/lib/node/core/remainingAccounts.js +20 -0
  539. package/lib/node/core/signedMsg.d.ts +38 -0
  540. package/lib/node/core/signedMsg.d.ts.map +1 -1
  541. package/lib/node/core/signedMsg.js +33 -0
  542. package/lib/node/decode/customCoder.d.ts +39 -3
  543. package/lib/node/decode/customCoder.d.ts.map +1 -1
  544. package/lib/node/decode/customCoder.js +45 -3
  545. package/lib/node/decode/user.d.ts +22 -0
  546. package/lib/node/decode/user.d.ts.map +1 -1
  547. package/lib/node/decode/user.js +27 -1
  548. package/lib/node/dlob/DLOB.d.ts +502 -53
  549. package/lib/node/dlob/DLOB.d.ts.map +1 -1
  550. package/lib/node/dlob/DLOB.js +540 -98
  551. package/lib/node/dlob/DLOBNode.d.ts +86 -4
  552. package/lib/node/dlob/DLOBNode.d.ts.map +1 -1
  553. package/lib/node/dlob/DLOBNode.js +37 -4
  554. package/lib/node/dlob/DLOBSubscriber.d.ts +39 -12
  555. package/lib/node/dlob/DLOBSubscriber.d.ts.map +1 -1
  556. package/lib/node/dlob/DLOBSubscriber.js +42 -12
  557. package/lib/node/dlob/NodeList.d.ts +69 -0
  558. package/lib/node/dlob/NodeList.d.ts.map +1 -1
  559. package/lib/node/dlob/NodeList.js +66 -0
  560. package/lib/node/dlob/orderBookLevels.d.ts +106 -13
  561. package/lib/node/dlob/orderBookLevels.d.ts.map +1 -1
  562. package/lib/node/dlob/orderBookLevels.js +84 -14
  563. package/lib/node/dlob/types.d.ts +15 -0
  564. package/lib/node/dlob/types.d.ts.map +1 -1
  565. package/lib/node/events/eventList.d.ts +14 -0
  566. package/lib/node/events/eventList.d.ts.map +1 -1
  567. package/lib/node/events/eventList.js +14 -0
  568. package/lib/node/events/eventSubscriber.d.ts +87 -10
  569. package/lib/node/events/eventSubscriber.d.ts.map +1 -1
  570. package/lib/node/events/eventSubscriber.js +93 -8
  571. package/lib/node/events/eventsServerLogProvider.d.ts +22 -0
  572. package/lib/node/events/eventsServerLogProvider.d.ts.map +1 -1
  573. package/lib/node/events/eventsServerLogProvider.js +27 -0
  574. package/lib/node/events/fetchLogs.d.ts +31 -0
  575. package/lib/node/events/fetchLogs.d.ts.map +1 -1
  576. package/lib/node/events/fetchLogs.js +46 -1
  577. package/lib/node/events/parse.d.ts +23 -0
  578. package/lib/node/events/parse.d.ts.map +1 -1
  579. package/lib/node/events/parse.js +23 -0
  580. package/lib/node/events/pollingLogProvider.d.ts +24 -0
  581. package/lib/node/events/pollingLogProvider.d.ts.map +1 -1
  582. package/lib/node/events/pollingLogProvider.js +24 -0
  583. package/lib/node/events/sort.d.ts +11 -0
  584. package/lib/node/events/sort.d.ts.map +1 -1
  585. package/lib/node/events/sort.js +12 -0
  586. package/lib/node/events/txEventCache.d.ts +13 -3
  587. package/lib/node/events/txEventCache.d.ts.map +1 -1
  588. package/lib/node/events/txEventCache.js +19 -7
  589. package/lib/node/events/types.d.ts +118 -2
  590. package/lib/node/events/types.d.ts.map +1 -1
  591. package/lib/node/events/types.js +11 -0
  592. package/lib/node/events/webSocketLogProvider.d.ts +23 -0
  593. package/lib/node/events/webSocketLogProvider.d.ts.map +1 -1
  594. package/lib/node/events/webSocketLogProvider.js +28 -0
  595. package/lib/node/factory/oracleClient.js +2 -2
  596. package/lib/node/idl/velocity.d.ts +150 -7
  597. package/lib/node/idl/velocity.d.ts.map +1 -1
  598. package/lib/node/idl/velocity.json +151 -8
  599. package/lib/node/keypair.d.ts +8 -0
  600. package/lib/node/keypair.d.ts.map +1 -1
  601. package/lib/node/keypair.js +8 -0
  602. package/lib/node/marginCalculation.d.ts +134 -2
  603. package/lib/node/marginCalculation.d.ts.map +1 -1
  604. package/lib/node/marginCalculation.js +121 -0
  605. package/lib/node/math/amm.d.ts +348 -29
  606. package/lib/node/math/amm.d.ts.map +1 -1
  607. package/lib/node/math/amm.js +310 -32
  608. package/lib/node/math/auction.d.ts +95 -19
  609. package/lib/node/math/auction.d.ts.map +1 -1
  610. package/lib/node/math/auction.js +118 -28
  611. package/lib/node/math/bankruptcy.d.ts +46 -0
  612. package/lib/node/math/bankruptcy.d.ts.map +1 -1
  613. package/lib/node/math/bankruptcy.js +89 -1
  614. package/lib/node/math/builder.d.ts +64 -8
  615. package/lib/node/math/builder.d.ts.map +1 -1
  616. package/lib/node/math/builder.js +71 -9
  617. package/lib/node/math/conversion.d.ts +21 -0
  618. package/lib/node/math/conversion.d.ts.map +1 -1
  619. package/lib/node/math/conversion.js +21 -0
  620. package/lib/node/math/exchangeStatus.d.ts +91 -0
  621. package/lib/node/math/exchangeStatus.d.ts.map +1 -1
  622. package/lib/node/math/exchangeStatus.js +106 -3
  623. package/lib/node/math/funding.d.ts +57 -20
  624. package/lib/node/math/funding.d.ts.map +1 -1
  625. package/lib/node/math/funding.js +63 -23
  626. package/lib/node/math/insurance.d.ts +62 -0
  627. package/lib/node/math/insurance.d.ts.map +1 -1
  628. package/lib/node/math/insurance.js +62 -0
  629. package/lib/node/math/liquidation.d.ts +127 -11
  630. package/lib/node/math/liquidation.d.ts.map +1 -1
  631. package/lib/node/math/liquidation.js +182 -19
  632. package/lib/node/math/margin.d.ts +79 -13
  633. package/lib/node/math/margin.d.ts.map +1 -1
  634. package/lib/node/math/margin.js +80 -14
  635. package/lib/node/math/market.d.ts +135 -15
  636. package/lib/node/math/market.d.ts.map +1 -1
  637. package/lib/node/math/market.js +145 -17
  638. package/lib/node/math/oracles.d.ts +113 -0
  639. package/lib/node/math/oracles.d.ts.map +1 -1
  640. package/lib/node/math/oracles.js +118 -1
  641. package/lib/node/math/orders.d.ts +115 -10
  642. package/lib/node/math/orders.d.ts.map +1 -1
  643. package/lib/node/math/orders.js +130 -19
  644. package/lib/node/math/position.d.ts +80 -33
  645. package/lib/node/math/position.d.ts.map +1 -1
  646. package/lib/node/math/position.js +80 -33
  647. package/lib/node/math/repeg.d.ts +48 -10
  648. package/lib/node/math/repeg.d.ts.map +1 -1
  649. package/lib/node/math/repeg.js +48 -10
  650. package/lib/node/math/spotBalance.d.ts +200 -5
  651. package/lib/node/math/spotBalance.d.ts.map +1 -1
  652. package/lib/node/math/spotBalance.js +239 -10
  653. package/lib/node/math/spotMarket.d.ts +36 -3
  654. package/lib/node/math/spotMarket.d.ts.map +1 -1
  655. package/lib/node/math/spotMarket.js +36 -3
  656. package/lib/node/math/spotPosition.d.ts +72 -0
  657. package/lib/node/math/spotPosition.d.ts.map +1 -1
  658. package/lib/node/math/spotPosition.js +62 -0
  659. package/lib/node/math/state.d.ts +31 -0
  660. package/lib/node/math/state.d.ts.map +1 -1
  661. package/lib/node/math/state.js +31 -0
  662. package/lib/node/math/superStake.d.ts +126 -2
  663. package/lib/node/math/superStake.d.ts.map +1 -1
  664. package/lib/node/math/superStake.js +123 -3
  665. package/lib/node/math/tiers.d.ts +29 -0
  666. package/lib/node/math/tiers.d.ts.map +1 -1
  667. package/lib/node/math/tiers.js +29 -0
  668. package/lib/node/math/trade.d.ts +102 -51
  669. package/lib/node/math/trade.d.ts.map +1 -1
  670. package/lib/node/math/trade.js +101 -55
  671. package/lib/node/math/utils.d.ts +71 -9
  672. package/lib/node/math/utils.d.ts.map +1 -1
  673. package/lib/node/math/utils.js +71 -9
  674. package/lib/node/memcmp.d.ts +94 -0
  675. package/lib/node/memcmp.d.ts.map +1 -1
  676. package/lib/node/memcmp.js +103 -2
  677. package/lib/node/oracles/oracleClientCache.d.ts +16 -0
  678. package/lib/node/oracles/oracleClientCache.d.ts.map +1 -1
  679. package/lib/node/oracles/oracleClientCache.js +16 -0
  680. package/lib/node/oracles/oracleId.d.ts +31 -0
  681. package/lib/node/oracles/oracleId.d.ts.map +1 -1
  682. package/lib/node/oracles/oracleId.js +39 -8
  683. package/lib/node/oracles/prelaunchOracleClient.d.ts +20 -0
  684. package/lib/node/oracles/prelaunchOracleClient.d.ts.map +1 -1
  685. package/lib/node/oracles/prelaunchOracleClient.js +20 -0
  686. package/lib/node/oracles/pythClient.d.ts +31 -0
  687. package/lib/node/oracles/pythClient.d.ts.map +1 -1
  688. package/lib/node/oracles/pythClient.js +32 -1
  689. package/lib/node/oracles/pythLazerClient.d.ts +34 -0
  690. package/lib/node/oracles/pythLazerClient.d.ts.map +1 -1
  691. package/lib/node/oracles/pythLazerClient.js +35 -1
  692. package/lib/node/oracles/quoteAssetOracleClient.d.ts +18 -0
  693. package/lib/node/oracles/quoteAssetOracleClient.d.ts.map +1 -1
  694. package/lib/node/oracles/quoteAssetOracleClient.js +18 -0
  695. package/lib/node/oracles/strictOraclePrice.d.ts +21 -0
  696. package/lib/node/oracles/strictOraclePrice.d.ts.map +1 -1
  697. package/lib/node/oracles/strictOraclePrice.js +21 -0
  698. package/lib/node/oracles/types.d.ts +45 -0
  699. package/lib/node/oracles/types.d.ts.map +1 -1
  700. package/lib/node/oracles/utils.d.ts +20 -0
  701. package/lib/node/oracles/utils.d.ts.map +1 -1
  702. package/lib/node/oracles/utils.js +20 -0
  703. package/lib/node/orderParams.d.ts +42 -4
  704. package/lib/node/orderParams.d.ts.map +1 -1
  705. package/lib/node/orderParams.js +42 -4
  706. package/lib/node/orderSubscriber/OrderSubscriber.d.ts +56 -0
  707. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  708. package/lib/node/orderSubscriber/OrderSubscriber.js +59 -0
  709. package/lib/node/orderSubscriber/PollingSubscription.d.ts +11 -0
  710. package/lib/node/orderSubscriber/PollingSubscription.d.ts.map +1 -1
  711. package/lib/node/orderSubscriber/PollingSubscription.js +11 -0
  712. package/lib/node/orderSubscriber/WebsocketSubscription.d.ts +18 -0
  713. package/lib/node/orderSubscriber/WebsocketSubscription.d.ts.map +1 -1
  714. package/lib/node/orderSubscriber/WebsocketSubscription.js +18 -0
  715. package/lib/node/orderSubscriber/grpcSubscription.d.ts +16 -0
  716. package/lib/node/orderSubscriber/grpcSubscription.d.ts.map +1 -1
  717. package/lib/node/orderSubscriber/grpcSubscription.js +16 -0
  718. package/lib/node/orderSubscriber/types.d.ts +9 -0
  719. package/lib/node/orderSubscriber/types.d.ts.map +1 -1
  720. package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts +1 -0
  721. package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts.map +1 -1
  722. package/lib/node/priorityFee/averageOverSlotsStrategy.js +1 -0
  723. package/lib/node/priorityFee/averageStrategy.d.ts +1 -0
  724. package/lib/node/priorityFee/averageStrategy.d.ts.map +1 -1
  725. package/lib/node/priorityFee/averageStrategy.js +1 -0
  726. package/lib/node/priorityFee/ewmaStrategy.d.ts +10 -0
  727. package/lib/node/priorityFee/ewmaStrategy.d.ts.map +1 -1
  728. package/lib/node/priorityFee/ewmaStrategy.js +10 -0
  729. package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts +13 -0
  730. package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts.map +1 -1
  731. package/lib/node/priorityFee/heliusPriorityFeeMethod.js +9 -2
  732. package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts +1 -0
  733. package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts.map +1 -1
  734. package/lib/node/priorityFee/maxOverSlotsStrategy.js +1 -0
  735. package/lib/node/priorityFee/maxStrategy.d.ts +1 -0
  736. package/lib/node/priorityFee/maxStrategy.d.ts.map +1 -1
  737. package/lib/node/priorityFee/maxStrategy.js +1 -0
  738. package/lib/node/priorityFee/priorityFeeSubscriber.d.ts +39 -0
  739. package/lib/node/priorityFee/priorityFeeSubscriber.d.ts.map +1 -1
  740. package/lib/node/priorityFee/priorityFeeSubscriber.js +39 -0
  741. package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts +20 -1
  742. package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts.map +1 -1
  743. package/lib/node/priorityFee/priorityFeeSubscriberMap.js +21 -2
  744. package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts +12 -0
  745. package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts.map +1 -1
  746. package/lib/node/priorityFee/solanaPriorityFeeMethod.js +10 -0
  747. package/lib/node/priorityFee/types.d.ts +32 -0
  748. package/lib/node/priorityFee/types.d.ts.map +1 -1
  749. package/lib/node/priorityFee/types.js +5 -0
  750. package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts +11 -0
  751. package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts.map +1 -1
  752. package/lib/node/priorityFee/velocityPriorityFeeMethod.js +8 -0
  753. package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
  754. package/lib/node/pyth/pythLazerSubscriber.js +37 -27
  755. package/lib/node/slot/SlotSubscriber.d.ts +18 -0
  756. package/lib/node/slot/SlotSubscriber.d.ts.map +1 -1
  757. package/lib/node/slot/SlotSubscriber.js +16 -0
  758. package/lib/node/slot/SlothashSubscriber.d.ts +26 -0
  759. package/lib/node/slot/SlothashSubscriber.d.ts.map +1 -1
  760. package/lib/node/slot/SlothashSubscriber.js +25 -1
  761. package/lib/node/tx/baseTxSender.d.ts +163 -0
  762. package/lib/node/tx/baseTxSender.d.ts.map +1 -1
  763. package/lib/node/tx/baseTxSender.js +174 -6
  764. package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +12 -0
  765. package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts.map +1 -1
  766. package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.js +12 -0
  767. package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +15 -0
  768. package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts.map +1 -1
  769. package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.js +15 -0
  770. package/lib/node/tx/blockhashFetcher/types.d.ts +4 -0
  771. package/lib/node/tx/blockhashFetcher/types.d.ts.map +1 -1
  772. package/lib/node/tx/fastSingleTxSender.d.ts +47 -0
  773. package/lib/node/tx/fastSingleTxSender.d.ts.map +1 -1
  774. package/lib/node/tx/fastSingleTxSender.js +48 -1
  775. package/lib/node/tx/forwardOnlyTxSender.d.ts +48 -0
  776. package/lib/node/tx/forwardOnlyTxSender.d.ts.map +1 -1
  777. package/lib/node/tx/forwardOnlyTxSender.js +48 -0
  778. package/lib/node/tx/reportTransactionError.d.ts +18 -6
  779. package/lib/node/tx/reportTransactionError.d.ts.map +1 -1
  780. package/lib/node/tx/reportTransactionError.js +18 -6
  781. package/lib/node/tx/retryTxSender.d.ts +40 -0
  782. package/lib/node/tx/retryTxSender.d.ts.map +1 -1
  783. package/lib/node/tx/retryTxSender.js +39 -0
  784. package/lib/node/tx/txHandler.d.ts +146 -35
  785. package/lib/node/tx/txHandler.d.ts.map +1 -1
  786. package/lib/node/tx/txHandler.js +132 -32
  787. package/lib/node/tx/txParamProcessor.d.ts +47 -0
  788. package/lib/node/tx/txParamProcessor.d.ts.map +1 -1
  789. package/lib/node/tx/txParamProcessor.js +47 -0
  790. package/lib/node/tx/types.d.ts +46 -0
  791. package/lib/node/tx/types.d.ts.map +1 -1
  792. package/lib/node/tx/types.js +5 -0
  793. package/lib/node/tx/utils.d.ts +26 -0
  794. package/lib/node/tx/utils.d.ts.map +1 -1
  795. package/lib/node/tx/utils.js +26 -0
  796. package/lib/node/tx/whileValidTxSender.d.ts +82 -0
  797. package/lib/node/tx/whileValidTxSender.d.ts.map +1 -1
  798. package/lib/node/tx/whileValidTxSender.js +81 -0
  799. package/lib/node/types.d.ts +785 -13
  800. package/lib/node/types.d.ts.map +1 -1
  801. package/lib/node/types.js +126 -9
  802. package/lib/node/user.d.ts +660 -84
  803. package/lib/node/user.d.ts.map +1 -1
  804. package/lib/node/user.js +816 -97
  805. package/lib/node/userMap/PollingSubscription.d.ts +10 -0
  806. package/lib/node/userMap/PollingSubscription.d.ts.map +1 -1
  807. package/lib/node/userMap/PollingSubscription.js +14 -2
  808. package/lib/node/userMap/WebsocketSubscription.d.ts +9 -0
  809. package/lib/node/userMap/WebsocketSubscription.d.ts.map +1 -1
  810. package/lib/node/userMap/WebsocketSubscription.js +9 -0
  811. package/lib/node/userMap/grpcSubscription.d.ts +8 -0
  812. package/lib/node/userMap/grpcSubscription.d.ts.map +1 -1
  813. package/lib/node/userMap/grpcSubscription.js +8 -0
  814. package/lib/node/userMap/referrerMap.d.ts +72 -2
  815. package/lib/node/userMap/referrerMap.d.ts.map +1 -1
  816. package/lib/node/userMap/referrerMap.js +84 -2
  817. package/lib/node/userMap/revenueShareEscrowMap.d.ts +37 -10
  818. package/lib/node/userMap/revenueShareEscrowMap.d.ts.map +1 -1
  819. package/lib/node/userMap/revenueShareEscrowMap.js +38 -11
  820. package/lib/node/userMap/userMap.d.ts +81 -3
  821. package/lib/node/userMap/userMap.d.ts.map +1 -1
  822. package/lib/node/userMap/userMap.js +81 -4
  823. package/lib/node/userMap/userMapConfig.d.ts +23 -0
  824. package/lib/node/userMap/userMapConfig.d.ts.map +1 -1
  825. package/lib/node/userMap/userStatsMap.d.ts +22 -0
  826. package/lib/node/userMap/userStatsMap.d.ts.map +1 -1
  827. package/lib/node/userMap/userStatsMap.js +22 -0
  828. package/lib/node/userName.d.ts +16 -0
  829. package/lib/node/userName.d.ts.map +1 -1
  830. package/lib/node/userName.js +16 -0
  831. package/lib/node/userStats.d.ts +28 -1
  832. package/lib/node/userStats.d.ts.map +1 -1
  833. package/lib/node/userStats.js +28 -1
  834. package/lib/node/util/TransactionConfirmationManager.d.ts +33 -0
  835. package/lib/node/util/TransactionConfirmationManager.d.ts.map +1 -1
  836. package/lib/node/util/TransactionConfirmationManager.js +33 -0
  837. package/lib/node/util/chainClock.d.ts +24 -0
  838. package/lib/node/util/chainClock.d.ts.map +1 -1
  839. package/lib/node/util/chainClock.js +20 -0
  840. package/lib/node/util/computeUnits.d.ts +32 -0
  841. package/lib/node/util/computeUnits.d.ts.map +1 -1
  842. package/lib/node/util/computeUnits.js +32 -0
  843. package/lib/node/util/digest.d.ts +17 -0
  844. package/lib/node/util/digest.d.ts.map +1 -1
  845. package/lib/node/util/digest.js +17 -0
  846. package/lib/node/util/ed25519Utils.d.ts +12 -2
  847. package/lib/node/util/ed25519Utils.d.ts.map +1 -1
  848. package/lib/node/util/ed25519Utils.js +12 -2
  849. package/lib/node/util/promiseTimeout.d.ts +9 -0
  850. package/lib/node/util/promiseTimeout.d.ts.map +1 -1
  851. package/lib/node/util/promiseTimeout.js +9 -0
  852. package/lib/node/velocityClient.d.ts +3363 -220
  853. package/lib/node/velocityClient.d.ts.map +1 -1
  854. package/lib/node/velocityClient.js +3514 -275
  855. package/lib/node/wallet.d.ts +37 -0
  856. package/lib/node/wallet.d.ts.map +1 -1
  857. package/lib/node/wallet.js +37 -0
  858. package/package.json +8 -3
  859. package/.prettierignore +0 -1
  860. package/CHANGELOG.md +0 -81
  861. package/build-browser.js +0 -58
  862. package/bunfig.toml +0 -3
  863. package/esbuild-shims.js +0 -12
  864. package/scripts/deposit-isolated-positions.ts +0 -110
  865. package/scripts/find-flagged-users.ts +0 -213
  866. package/scripts/grpc-client-test-comparison.ts +0 -372
  867. package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
  868. package/scripts/postbuild.js +0 -95
  869. package/scripts/single-grpc-client-test.ts +0 -284
  870. package/scripts/withdraw-isolated-positions.ts +0 -174
  871. package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
  872. package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
  873. package/src/accounts/basicUserAccountSubscriber.ts +0 -61
  874. package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -69
  875. package/src/accounts/bulkAccountLoader.ts +0 -306
  876. package/src/accounts/bulkUserStatsSubscription.ts +0 -33
  877. package/src/accounts/bulkUserSubscription.ts +0 -33
  878. package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -213
  879. package/src/accounts/fetch.ts +0 -143
  880. package/src/accounts/grpcAccountSubscriber.ts +0 -195
  881. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -57
  882. package/src/accounts/grpcMultiAccountSubscriber.ts +0 -483
  883. package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -290
  884. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -231
  885. package/src/accounts/grpcUserAccountSubscriber.ts +0 -48
  886. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -50
  887. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -216
  888. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -782
  889. package/src/accounts/laserProgramAccountSubscriber.ts +0 -232
  890. package/src/accounts/oneShotUserAccountSubscriber.ts +0 -69
  891. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -75
  892. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -192
  893. package/src/accounts/pollingOracleAccountSubscriber.ts +0 -132
  894. package/src/accounts/pollingTokenAccountSubscriber.ts +0 -125
  895. package/src/accounts/pollingUserAccountSubscriber.ts +0 -166
  896. package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -158
  897. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -691
  898. package/src/accounts/testBulkAccountLoader.ts +0 -51
  899. package/src/accounts/types.ts +0 -279
  900. package/src/accounts/utils.ts +0 -72
  901. package/src/accounts/webSocketAccountSubscriber.ts +0 -263
  902. package/src/accounts/webSocketAccountSubscriberV2.ts +0 -528
  903. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -144
  904. package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -208
  905. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1022
  906. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1021
  907. package/src/accounts/webSocketUserAccountSubscriber.ts +0 -113
  908. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -111
  909. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -740
  910. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -787
  911. package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -94
  912. package/src/addresses/marketAddresses.ts +0 -18
  913. package/src/addresses/pda.ts +0 -404
  914. package/src/adminClient.ts +0 -5984
  915. package/src/assert/assert.ts +0 -5
  916. package/src/auctionSubscriber/auctionSubscriber.ts +0 -71
  917. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -80
  918. package/src/auctionSubscriber/index.ts +0 -3
  919. package/src/auctionSubscriber/types.ts +0 -23
  920. package/src/bankrun/bankrunConnection.ts +0 -630
  921. package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -127
  922. package/src/blockhashSubscriber/index.ts +0 -1
  923. package/src/blockhashSubscriber/types.ts +0 -12
  924. package/src/clock/clockSubscriber.ts +0 -122
  925. package/src/config.ts +0 -225
  926. package/src/constants/index.ts +0 -9
  927. package/src/constants/numericConstants.ts +0 -124
  928. package/src/constants/perpMarkets.ts +0 -1042
  929. package/src/constants/spotMarkets.ts +0 -874
  930. package/src/constants/txConstants.ts +0 -1
  931. package/src/constituentMap/constituentMap.ts +0 -305
  932. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
  933. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
  934. package/src/core/VelocityCore.ts +0 -328
  935. package/src/core/index.ts +0 -12
  936. package/src/core/instructions/deposit.ts +0 -42
  937. package/src/core/instructions/fill.ts +0 -34
  938. package/src/core/instructions/funding.ts +0 -21
  939. package/src/core/instructions/liquidation.ts +0 -37
  940. package/src/core/instructions/orders.ts +0 -56
  941. package/src/core/instructions/perpOrders.ts +0 -206
  942. package/src/core/instructions/settlement.ts +0 -26
  943. package/src/core/instructions/trigger.ts +0 -26
  944. package/src/core/instructions/withdraw.ts +0 -44
  945. package/src/core/remainingAccounts.ts +0 -276
  946. package/src/core/signedMsg.ts +0 -71
  947. package/src/decode/customCoder.ts +0 -105
  948. package/src/decode/user.ts +0 -379
  949. package/src/dlob/DLOB.ts +0 -2222
  950. package/src/dlob/DLOBNode.ts +0 -213
  951. package/src/dlob/DLOBSubscriber.ts +0 -232
  952. package/src/dlob/NodeList.ts +0 -175
  953. package/src/dlob/orderBookLevels.ts +0 -601
  954. package/src/dlob/types.ts +0 -22
  955. package/src/events/eventList.ts +0 -100
  956. package/src/events/eventSubscriber.ts +0 -440
  957. package/src/events/eventsServerLogProvider.ts +0 -161
  958. package/src/events/fetchLogs.ts +0 -169
  959. package/src/events/parse.ts +0 -248
  960. package/src/events/pollingLogProvider.ts +0 -89
  961. package/src/events/sort.ts +0 -39
  962. package/src/events/txEventCache.ts +0 -80
  963. package/src/events/types.ts +0 -217
  964. package/src/events/webSocketLogProvider.ts +0 -123
  965. package/src/factory/bigNum.ts +0 -709
  966. package/src/factory/oracleClient.ts +0 -73
  967. package/src/idl/pyth.json +0 -142
  968. package/src/idl/pyth.ts +0 -97
  969. package/src/idl/pyth_solana_receiver.json +0 -628
  970. package/src/idl/token_faucet.json +0 -229
  971. package/src/idl/token_faucet.ts +0 -197
  972. package/src/idl/velocity.json +0 -23974
  973. package/src/idl/velocity.ts +0 -23980
  974. package/src/index.ts +0 -150
  975. package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
  976. package/src/isomorphic/README.md +0 -19
  977. package/src/isomorphic/anchor.browser.ts +0 -44
  978. package/src/isomorphic/anchor.node.ts +0 -1
  979. package/src/isomorphic/anchor.ts +0 -1
  980. package/src/isomorphic/anchor29.browser.ts +0 -24
  981. package/src/isomorphic/anchor29.node.ts +0 -1
  982. package/src/isomorphic/anchor29.ts +0 -1
  983. package/src/isomorphic/grpc.browser.ts +0 -4
  984. package/src/isomorphic/grpc.node.ts +0 -130
  985. package/src/isomorphic/grpc.ts +0 -1
  986. package/src/jupiter/jupiterClient.ts +0 -502
  987. package/src/keypair.ts +0 -24
  988. package/src/margin/README.md +0 -138
  989. package/src/marginCalculation.ts +0 -256
  990. package/src/marinade/idl/idl.json +0 -1962
  991. package/src/marinade/index.ts +0 -73
  992. package/src/marinade/types.ts +0 -3925
  993. package/src/math/amm.ts +0 -1423
  994. package/src/math/auction.ts +0 -371
  995. package/src/math/bankruptcy.ts +0 -35
  996. package/src/math/builder.ts +0 -64
  997. package/src/math/conversion.ts +0 -24
  998. package/src/math/exchangeStatus.ts +0 -146
  999. package/src/math/funding.ts +0 -458
  1000. package/src/math/insurance.ts +0 -109
  1001. package/src/math/liquidation.ts +0 -223
  1002. package/src/math/margin.ts +0 -261
  1003. package/src/math/market.ts +0 -356
  1004. package/src/math/oracles.ts +0 -353
  1005. package/src/math/orders.ts +0 -378
  1006. package/src/math/position.ts +0 -334
  1007. package/src/math/repeg.ts +0 -185
  1008. package/src/math/spotBalance.ts +0 -756
  1009. package/src/math/spotMarket.ts +0 -82
  1010. package/src/math/spotPosition.ts +0 -191
  1011. package/src/math/state.ts +0 -40
  1012. package/src/math/superStake.ts +0 -479
  1013. package/src/math/tiers.ts +0 -44
  1014. package/src/math/trade.ts +0 -809
  1015. package/src/math/utils.ts +0 -121
  1016. package/src/memcmp.ts +0 -177
  1017. package/src/oracles/oracleClientCache.ts +0 -25
  1018. package/src/oracles/oracleId.ts +0 -66
  1019. package/src/oracles/prelaunchOracleClient.ts +0 -43
  1020. package/src/oracles/pythClient.ts +0 -94
  1021. package/src/oracles/pythLazerClient.ts +0 -107
  1022. package/src/oracles/quoteAssetOracleClient.ts +0 -25
  1023. package/src/oracles/strictOraclePrice.ts +0 -19
  1024. package/src/oracles/types.ts +0 -37
  1025. package/src/oracles/utils.ts +0 -25
  1026. package/src/orderParams.ts +0 -79
  1027. package/src/orderSubscriber/OrderSubscriber.ts +0 -322
  1028. package/src/orderSubscriber/PollingSubscription.ts +0 -39
  1029. package/src/orderSubscriber/WebsocketSubscription.ts +0 -119
  1030. package/src/orderSubscriber/grpcSubscription.ts +0 -139
  1031. package/src/orderSubscriber/index.ts +0 -7
  1032. package/src/orderSubscriber/types.ts +0 -55
  1033. package/src/priorityFee/averageOverSlotsStrategy.ts +0 -16
  1034. package/src/priorityFee/averageStrategy.ts +0 -12
  1035. package/src/priorityFee/ewmaStrategy.ts +0 -41
  1036. package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -57
  1037. package/src/priorityFee/index.ts +0 -16
  1038. package/src/priorityFee/maxOverSlotsStrategy.ts +0 -17
  1039. package/src/priorityFee/maxStrategy.ts +0 -7
  1040. package/src/priorityFee/priorityFeeSubscriber.ts +0 -289
  1041. package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -115
  1042. package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -34
  1043. package/src/priorityFee/types.ts +0 -64
  1044. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -42
  1045. package/src/pyth/constants.ts +0 -9
  1046. package/src/pyth/index.ts +0 -15
  1047. package/src/pyth/pythLazerSubscriber.ts +0 -365
  1048. package/src/pyth/types.ts +0 -4451
  1049. package/src/pyth/utils.ts +0 -13
  1050. package/src/slot/SlotSubscriber.ts +0 -108
  1051. package/src/slot/SlothashSubscriber.ts +0 -137
  1052. package/src/swap/UnifiedSwapClient.ts +0 -315
  1053. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
  1054. package/src/swift/index.ts +0 -10
  1055. package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
  1056. package/src/swift/swiftOrderSubscriber.ts +0 -351
  1057. package/src/testClient.ts +0 -42
  1058. package/src/titan/titanClient.ts +0 -438
  1059. package/src/token/index.ts +0 -13
  1060. package/src/tokenFaucet.ts +0 -296
  1061. package/src/tx/baseTxSender.ts +0 -471
  1062. package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -19
  1063. package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -90
  1064. package/src/tx/blockhashFetcher/types.ts +0 -5
  1065. package/src/tx/fastSingleTxSender.ts +0 -146
  1066. package/src/tx/forwardOnlyTxSender.ts +0 -145
  1067. package/src/tx/priorityFeeCalculator.ts +0 -117
  1068. package/src/tx/reportTransactionError.ts +0 -164
  1069. package/src/tx/retryTxSender.ts +0 -137
  1070. package/src/tx/txHandler.ts +0 -898
  1071. package/src/tx/txParamProcessor.ts +0 -178
  1072. package/src/tx/types.ts +0 -71
  1073. package/src/tx/utils.ts +0 -107
  1074. package/src/tx/whileValidTxSender.ts +0 -295
  1075. package/src/types.ts +0 -1822
  1076. package/src/user.ts +0 -4557
  1077. package/src/userConfig.ts +0 -38
  1078. package/src/userMap/PollingSubscription.ts +0 -47
  1079. package/src/userMap/WebsocketSubscription.ts +0 -84
  1080. package/src/userMap/grpcSubscription.ts +0 -85
  1081. package/src/userMap/referrerMap.ts +0 -271
  1082. package/src/userMap/revenueShareEscrowMap.ts +0 -315
  1083. package/src/userMap/userMap.ts +0 -706
  1084. package/src/userMap/userMapConfig.ts +0 -69
  1085. package/src/userMap/userStatsMap.ts +0 -371
  1086. package/src/userName.ts +0 -21
  1087. package/src/userStats.ts +0 -132
  1088. package/src/userStatsConfig.ts +0 -35
  1089. package/src/util/TransactionConfirmationManager.ts +0 -300
  1090. package/src/util/chainClock.ts +0 -41
  1091. package/src/util/computeUnits.ts +0 -69
  1092. package/src/util/digest.ts +0 -16
  1093. package/src/util/ed25519Utils.ts +0 -85
  1094. package/src/util/promiseTimeout.ts +0 -14
  1095. package/src/velocityClient.ts +0 -11612
  1096. package/src/velocityClientConfig.ts +0 -119
  1097. package/src/wallet.ts +0 -54
  1098. package/tests/VelocityCore/decode.test.ts +0 -16
  1099. package/tests/VelocityCore/fill_trigger.test.ts +0 -73
  1100. package/tests/VelocityCore/instructions.test.ts +0 -46
  1101. package/tests/VelocityCore/pdas.test.ts +0 -30
  1102. package/tests/VelocityCore/perp_orders.test.ts +0 -205
  1103. package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
  1104. package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
  1105. package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
  1106. package/tests/amm/test.ts +0 -2300
  1107. package/tests/auctions/test.ts +0 -81
  1108. package/tests/bn/test.ts +0 -355
  1109. package/tests/ci/verifyConstants.ts +0 -393
  1110. package/tests/decode/test.ts +0 -262
  1111. package/tests/decode/userAccountBufferStrings.ts +0 -102
  1112. package/tests/dlob/helpers.ts +0 -748
  1113. package/tests/dlob/test.ts +0 -6969
  1114. package/tests/events/parseLogsForCuUsage.ts +0 -139
  1115. package/tests/insurance/test.ts +0 -40
  1116. package/tests/spot/test.ts +0 -226
  1117. package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
  1118. package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
  1119. package/tests/tx/priorityFeeCalculator.ts +0 -77
  1120. package/tests/tx/priorityFeeStrategy.ts +0 -95
  1121. package/tests/user/getMarginCalculation.ts +0 -361
  1122. package/tests/user/helpers.ts +0 -184
  1123. package/tests/user/liquidations.ts +0 -129
  1124. package/tests/user/marginCalculations.test.ts +0 -321
  1125. package/tests/user/test.ts +0 -829
  1126. package/tsconfig.browser.json +0 -18
  1127. package/tsconfig.json +0 -36
package/lib/node/user.js CHANGED
@@ -16,6 +16,7 @@ const spotBalance_1 = require("./math/spotBalance");
16
16
  const trade_1 = require("./math/trade");
17
17
  const types_2 = require("./types");
18
18
  const orders_1 = require("./math/orders");
19
+ const builder_1 = require("./math/builder");
19
20
  const websocketProgramUserAccountSubscriber_1 = require("./accounts/websocketProgramUserAccountSubscriber");
20
21
  const spotBalance_2 = require("./math/spotBalance");
21
22
  const margin_2 = require("./math/margin");
@@ -27,13 +28,35 @@ const tiers_1 = require("./math/tiers");
27
28
  const strictOraclePrice_1 = require("./oracles/strictOraclePrice");
28
29
  const grpcUserAccountSubscriber_1 = require("./accounts/grpcUserAccountSubscriber");
29
30
  const marginCalculation_1 = require("./marginCalculation");
31
+ /**
32
+ * Ports `get_proportion_u128` (math/helpers.rs) for the referee fee discount
33
+ * calculation. The Rust version routes large operands through a wider U192
34
+ * type purely to avoid u128 overflow; BN has no such ceiling, so that branch
35
+ * is elided here since it produces the same numeric result.
36
+ */
37
+ function getProportion128(value, numerator, denominator) {
38
+ if (numerator.eq(denominator)) {
39
+ return value;
40
+ }
41
+ if (numerator.gt(denominator.div(numericConstants_1.TWO)) && denominator.gt(numerator)) {
42
+ // ceiling division, mirroring standardize_value_with_remainder_i128
43
+ const scaled = value.mul(denominator.sub(numerator));
44
+ const remainder = scaled.mod(denominator);
45
+ const floorDiv = scaled.div(denominator);
46
+ const ceilDiv = remainder.isZero() ? floorDiv : floorDiv.add(numericConstants_1.ONE);
47
+ return value.sub(ceilDiv);
48
+ }
49
+ return value.mul(numerator).div(denominator);
50
+ }
30
51
  class User {
52
+ /** True only when both `subscribe()` has completed and the underlying `accountSubscriber` itself reports subscribed. */
31
53
  get isSubscribed() {
32
54
  return this._isSubscribed && this.accountSubscriber.isSubscribed;
33
55
  }
34
56
  set isSubscribed(val) {
35
57
  this._isSubscribed = val;
36
58
  }
59
+ /** Constructs a `User` for the account at `config.userAccountPublicKey`, wiring up the account subscriber selected by `config.accountSubscription` (`'websocket'`/`'polling'`/`'grpc'`/`'custom'`). Does not fetch or subscribe — call `subscribe()` next. */
37
60
  constructor(config) {
38
61
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
39
62
  this._isSubscribed = false;
@@ -74,19 +97,22 @@ class User {
74
97
  this.eventEmitter = this.accountSubscriber.eventEmitter;
75
98
  }
76
99
  /**
77
- * Subscribe to User state accounts
78
- * @returns SusbcriptionSuccess result
100
+ * Subscribes to this `User` account (websocket/polling/gRPC/custom per
101
+ * `UserConfig.accountSubscription`) and awaits the initial account fetch.
102
+ * Must resolve before any `get*`/margin/PnL accessor is called — those
103
+ * throw `NotSubscribedError` until this has completed.
104
+ * @param userAccount Optional pre-fetched account to seed the subscriber with, skipping the initial RPC fetch.
105
+ * @returns True once the underlying subscriber reports subscribed.
79
106
  */
80
107
  async subscribe(userAccount) {
81
108
  this.isSubscribed = await this.accountSubscriber.subscribe(userAccount);
82
109
  return this.isSubscribed;
83
110
  }
84
- /**
85
- * Forces the accountSubscriber to fetch account updates from rpc
86
- */
111
+ /** Forces the account subscriber to re-fetch the `User` account from RPC (bypassing any push/poll cadence). */
87
112
  async fetchAccounts() {
88
113
  await this.accountSubscriber.fetch();
89
114
  }
115
+ /** Removes all event listeners and tears down the account subscription. */
90
116
  async unsubscribe() {
91
117
  this.eventEmitter.removeAllListeners();
92
118
  await this.accountSubscriber.unsubscribe();
@@ -96,7 +122,7 @@ class User {
96
122
  * Returns the cached user account.
97
123
  *
98
124
  * - **Throws** `NotSubscribedError` if the subscriber has not been subscribed
99
- * yet — reading the account before {@link subscribe} resolves is a
125
+ * yet — reading the account before `subscribe()` resolves is a
100
126
  * programming error, not a missing-account condition.
101
127
  * - Returns `undefined` when subscribed but no account was found on chain.
102
128
  * Because `subscribe()` awaits the initial fetch, an `undefined` here means
@@ -108,13 +134,14 @@ class User {
108
134
  return (_a = this.accountSubscriber.getUserAccountAndSlot()) === null || _a === void 0 ? void 0 : _a.data;
109
135
  }
110
136
  /**
111
- * Like {@link getUserAccount} but throws instead of returning `undefined`
137
+ * Like `getUserAccount` but throws instead of returning `undefined`
112
138
  * when the account was not found. Use at call sites that structurally
113
139
  * require the account to exist. (Still propagates `NotSubscribedError` when
114
140
  * called before subscribing.)
115
141
  *
116
- * Delegates to {@link getUserAccount} (rather than the subscriber directly)
142
+ * Delegates to `getUserAccount` (rather than the subscriber directly)
117
143
  * so callers that override `getUserAccount` see the override here too.
144
+ * @returns The current `UserAccount`.
118
145
  */
119
146
  getUserAccountOrThrow() {
120
147
  const userAccount = this.getUserAccount();
@@ -123,16 +150,27 @@ class User {
123
150
  }
124
151
  return userAccount;
125
152
  }
153
+ /**
154
+ * Bypasses the cached subscriber state and force-fetches the `User` account
155
+ * directly from the RPC (via `fetchAccounts`), then returns the freshly
156
+ * cached value. Useful right after sending a transaction, when the
157
+ * websocket/polling subscriber may not yet have observed the update.
158
+ * @returns The freshly fetched `UserAccount`, or `undefined` if the account does not exist on chain.
159
+ */
126
160
  async forceGetUserAccount() {
127
161
  await this.fetchAccounts();
128
162
  const account = this.accountSubscriber.getUserAccountAndSlot();
129
163
  return account === null || account === void 0 ? void 0 : account.data;
130
164
  }
165
+ /**
166
+ * Returns the cached user account together with the slot at which it was
167
+ * last observed. Same `undefined`/`NotSubscribedError` contract as `getUserAccount`.
168
+ */
131
169
  getUserAccountAndSlot() {
132
170
  return this.accountSubscriber.getUserAccountAndSlot();
133
171
  }
134
172
  /**
135
- * Like {@link getUserAccountAndSlot} but throws instead of returning
173
+ * Like `getUserAccountAndSlot` but throws instead of returning
136
174
  * `undefined` when the account was not found. Use at call sites that
137
175
  * structurally require the account to exist. (Still propagates
138
176
  * `NotSubscribedError` when called before subscribing.)
@@ -140,6 +178,16 @@ class User {
140
178
  getUserAccountAndSlotOrThrow() {
141
179
  return (0, utils_1.assertDataAndSlot)(this.accountSubscriber.getUserAccountAndSlot(), `User account not found: ${this.getUserAccountPublicKey().toString()}`);
142
180
  }
181
+ /**
182
+ * Finds the perp position for `marketIndex` on an explicit `userAccount`
183
+ * snapshot rather than the cached account. Only matches "active" positions
184
+ * (see `getActivePerpPositionsForUserAccount`) — a market the user has never
185
+ * touched (or has fully closed and settled) returns `undefined` even though
186
+ * the on-chain array always has a fixed-size slot for every market.
187
+ * @param userAccount Account snapshot to search (does not have to be the subscribed account).
188
+ * @param marketIndex Perp market index to look up.
189
+ * @returns The matching `PerpPosition`, or `undefined` if the user has no active position in that market.
190
+ */
143
191
  getPerpPositionForUserAccount(userAccount, marketIndex) {
144
192
  return this.getActivePerpPositionsForUserAccount(userAccount).find((position) => position.marketIndex === marketIndex);
145
193
  }
@@ -152,11 +200,21 @@ class User {
152
200
  const userAccount = this.getUserAccountOrThrow();
153
201
  return this.getPerpPositionForUserAccount(userAccount, marketIndex);
154
202
  }
203
+ /**
204
+ * Like `getPerpPosition`, but returns a zeroed-out placeholder position
205
+ * (see `getEmptyPosition`) instead of `undefined` when the user has no
206
+ * active position in `marketIndex`. Convenient for math helpers that need a
207
+ * `PerpPosition` shape unconditionally (e.g. buying-power/leverage calcs).
208
+ */
155
209
  getPerpPositionOrEmpty(marketIndex) {
156
210
  var _a;
157
211
  const userAccount = this.getUserAccountOrThrow();
158
212
  return ((_a = this.getPerpPositionForUserAccount(userAccount, marketIndex)) !== null && _a !== void 0 ? _a : this.getEmptyPosition(marketIndex));
159
213
  }
214
+ /**
215
+ * Like `getPerpPosition`, but throws instead of returning `undefined` when
216
+ * the user has no active position in `marketIndex`.
217
+ */
160
218
  getPerpPositionOrThrow(marketIndex) {
161
219
  const position = this.getPerpPosition(marketIndex);
162
220
  if (!position) {
@@ -164,6 +222,10 @@ class User {
164
222
  }
165
223
  return position;
166
224
  }
225
+ /**
226
+ * Like `getPerpPosition`, but also returns the slot at which the underlying
227
+ * `UserAccount` was observed.
228
+ */
167
229
  getPerpPositionAndSlot(marketIndex) {
168
230
  const userAccount = this.getUserAccountAndSlotOrThrow();
169
231
  const perpPosition = this.getPerpPositionForUserAccount(userAccount.data, marketIndex);
@@ -172,6 +234,14 @@ class User {
172
234
  slot: userAccount.slot,
173
235
  };
174
236
  }
237
+ /**
238
+ * Finds the spot position for `marketIndex` on an explicit `userAccount`
239
+ * snapshot. Unlike `getPerpPositionForUserAccount`, this does not filter to
240
+ * "active" positions first — it returns whatever fixed-size slot entry
241
+ * exists for that market index, even if the position is empty/available.
242
+ * @param userAccount Account snapshot to search (does not have to be the subscribed account).
243
+ * @param marketIndex Spot market index to look up.
244
+ */
175
245
  getSpotPositionForUserAccount(userAccount, marketIndex) {
176
246
  return userAccount.spotPositions.find((position) => position.marketIndex === marketIndex);
177
247
  }
@@ -184,6 +254,10 @@ class User {
184
254
  const userAccount = this.getUserAccountOrThrow();
185
255
  return this.getSpotPositionForUserAccount(userAccount, marketIndex);
186
256
  }
257
+ /**
258
+ * Like `getSpotPosition`, but also returns the slot at which the underlying
259
+ * `UserAccount` was observed.
260
+ */
187
261
  getSpotPositionAndSlot(marketIndex) {
188
262
  const userAccount = this.getUserAccountAndSlotOrThrow();
189
263
  const spotPosition = this.getSpotPositionForUserAccount(userAccount.data, marketIndex);
@@ -192,6 +266,7 @@ class User {
192
266
  slot: userAccount.slot,
193
267
  };
194
268
  }
269
+ /** Returns a zeroed-out (no deposit/borrow) placeholder `SpotPosition` for `marketIndex`. */
195
270
  getEmptySpotPosition(marketIndex) {
196
271
  return {
197
272
  marketIndex,
@@ -208,6 +283,7 @@ class User {
208
283
  * Positive if it is a deposit, negative if it is a borrow.
209
284
  *
210
285
  * @param marketIndex
286
+ * @returns Signed token amount, in the spot market's own token decimals (not QUOTE_PRECISION). `ZERO` if the user has no position in the market.
211
287
  */
212
288
  getTokenAmount(marketIndex) {
213
289
  const spotPosition = this.getSpotPosition(marketIndex);
@@ -217,6 +293,7 @@ class User {
217
293
  const spotMarket = this.velocityClient.getSpotMarketAccountOrThrow(marketIndex);
218
294
  return (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
219
295
  }
296
+ /** Returns a zeroed-out placeholder `PerpPosition` for `marketIndex` (no size, no orders, cross margin). */
220
297
  getEmptyPosition(marketIndex) {
221
298
  return {
222
299
  baseAssetAmount: numericConstants_1.ZERO,
@@ -235,9 +312,18 @@ class User {
235
312
  positionFlag: 0,
236
313
  };
237
314
  }
315
+ /** Returns true if `position` has no size and no open orders (a market slot that can be treated as unused). */
238
316
  isPositionEmpty(position) {
239
317
  return position.baseAssetAmount.eq(numericConstants_1.ZERO) && position.openOrders === 0;
240
318
  }
319
+ /**
320
+ * Returns the isolated-margin quote deposit backing a given perp position,
321
+ * i.e. `PerpPosition.isolatedPositionScaledBalance` converted to a token
322
+ * amount. This is the collateral segregated to that single isolated
323
+ * position, separate from the user's cross-margin free collateral.
324
+ * @param perpMarketIndex
325
+ * @returns Quote token amount (the quote spot market's own decimals). `ZERO` if the user has no position or no isolated deposit in the market.
326
+ */
241
327
  getIsolatePerpPositionTokenAmount(perpMarketIndex) {
242
328
  var _a;
243
329
  const perpPosition = this.getPerpPosition(perpMarketIndex);
@@ -253,6 +339,7 @@ class User {
253
339
  }
254
340
  /**
255
341
  * Returns the total USD value of deposits across all isolated perp positions.
342
+ * @returns Precision QUOTE_PRECISION (1e6).
256
343
  */
257
344
  getTotalIsolatedPositionDeposits() {
258
345
  return this.getActivePerpPositions().reduce((total, perpPosition) => {
@@ -268,21 +355,25 @@ class User {
268
355
  return total.add((0, spotBalance_1.getStrictTokenValue)(tokenAmount, quoteSpotMarket.decimals, strictOracle));
269
356
  }, numericConstants_1.ZERO);
270
357
  }
358
+ /** Returns a shallow copy of `position`. Mutating the clone does not affect the cached account. */
271
359
  getClonedPosition(position) {
272
360
  const clonedPosition = Object.assign({}, position);
273
361
  return clonedPosition;
274
362
  }
363
+ /** Finds an order by its program-assigned `orderId` on an explicit `userAccount` snapshot. */
275
364
  getOrderForUserAccount(userAccount, orderId) {
276
365
  return userAccount.orders.find((order) => order.orderId === orderId);
277
366
  }
278
367
  /**
368
+ * Finds an order in the cached `UserAccount` by its program-assigned `orderId`.
279
369
  * @param orderId
280
- * @returns Order
370
+ * @returns The matching `Order`, or `undefined` if no order with that id exists.
281
371
  */
282
372
  getOrder(orderId) {
283
373
  const userAccount = this.getUserAccountOrThrow();
284
374
  return this.getOrderForUserAccount(userAccount, orderId);
285
375
  }
376
+ /** Like `getOrder`, but also returns the slot at which the underlying `UserAccount` was observed. */
286
377
  getOrderAndSlot(orderId) {
287
378
  const userAccount = this.getUserAccountAndSlotOrThrow();
288
379
  const order = this.getOrderForUserAccount(userAccount.data, orderId);
@@ -291,17 +382,25 @@ class User {
291
382
  slot: userAccount.slot,
292
383
  };
293
384
  }
385
+ /**
386
+ * Finds an order by its caller-assigned `userOrderId` (a client-chosen tag,
387
+ * distinct from the program-assigned `orderId`) on an explicit `userAccount`
388
+ * snapshot.
389
+ */
294
390
  getOrderByUserIdForUserAccount(userAccount, userOrderId) {
295
391
  return userAccount.orders.find((order) => order.userOrderId === userOrderId);
296
392
  }
297
393
  /**
394
+ * Finds an order in the cached `UserAccount` by its caller-assigned
395
+ * `userOrderId` (a client-chosen tag, distinct from the program-assigned `orderId`).
298
396
  * @param userOrderId
299
- * @returns Order
397
+ * @returns The matching `Order`, or `undefined` if no order with that tag exists.
300
398
  */
301
399
  getOrderByUserOrderId(userOrderId) {
302
400
  const userAccount = this.getUserAccountOrThrow();
303
401
  return this.getOrderByUserIdForUserAccount(userAccount, userOrderId);
304
402
  }
403
+ /** Like `getOrderByUserOrderId`, but also returns the slot at which the underlying `UserAccount` was observed. */
305
404
  getOrderByUserOrderIdAndSlot(userOrderId) {
306
405
  const userAccount = this.getUserAccountAndSlotOrThrow();
307
406
  const order = this.getOrderByUserIdForUserAccount(userAccount.data, userOrderId);
@@ -310,14 +409,21 @@ class User {
310
409
  slot: userAccount.slot,
311
410
  };
312
411
  }
412
+ /**
413
+ * Filters an explicit `userAccount` snapshot's orders down to those with
414
+ * `OrderStatus.Open`.
415
+ * @returns `undefined` if `userAccount` is `undefined` (i.e. no account loaded), otherwise the array of open orders (possibly empty).
416
+ */
313
417
  getOpenOrdersForUserAccount(userAccount) {
314
418
  return userAccount === null || userAccount === void 0 ? void 0 : userAccount.orders.filter((order) => (0, types_1.isVariant)(order.status, 'open'));
315
419
  }
420
+ /** Returns all of the user's orders with `OrderStatus.Open`. Empty array (not `undefined`) if there are none or no account is loaded. */
316
421
  getOpenOrders() {
317
422
  var _a;
318
423
  const userAccount = this.getUserAccount();
319
424
  return (_a = this.getOpenOrdersForUserAccount(userAccount)) !== null && _a !== void 0 ? _a : [];
320
425
  }
426
+ /** Like `getOpenOrders`, but also returns the slot at which the underlying `UserAccount` was observed. */
321
427
  getOpenOrdersAndSlot() {
322
428
  var _a;
323
429
  const userAccount = this.getUserAccountAndSlotOrThrow();
@@ -327,17 +433,19 @@ class User {
327
433
  slot: userAccount.slot,
328
434
  };
329
435
  }
436
+ /** Returns this `User`'s account address (does not require the account to be subscribed or to exist on chain). */
330
437
  getUserAccountPublicKey() {
331
438
  return this.userAccountPublicKey;
332
439
  }
440
+ /** Checks directly via RPC (bypassing the subscriber cache) whether the `User` account exists on chain. */
333
441
  async exists() {
334
442
  const userAccountRPCResponse = await this.velocityClient.connection.getParsedAccountInfo(this.userAccountPublicKey);
335
443
  return userAccountRPCResponse.value !== null;
336
444
  }
337
445
  /**
338
- * calculates the total open bids/asks in a perp market (including lps)
339
- * @returns : open bids
340
- * @returns : open asks
446
+ * Returns the position's total resting open-order bid/ask size in a perp market.
447
+ * @param marketIndex
448
+ * @returns Tuple of `[openBids, openAsks]`, both `BASE_PRECISION` (1e9). Throws (via `getPerpPositionOrThrow`) if the user has no active position in `marketIndex`.
341
449
  */
342
450
  getPerpBidAsks(marketIndex) {
343
451
  const position = this.getPerpPositionOrThrow(marketIndex);
@@ -347,7 +455,17 @@ class User {
347
455
  }
348
456
  /**
349
457
  * calculates Buying Power = free collateral / initial margin ratio
350
- * @returns : Precision QUOTE_PRECISION
458
+ *
459
+ * For `positionType: 'isolated'`, the buying power is capped by the
460
+ * lesser of (a) the user's cross free collateral and (b) the free quote
461
+ * asset value in the perp's quote spot market — mirroring that an isolated
462
+ * position can only draw down as much quote collateral as is actually
463
+ * available to isolate into it.
464
+ * @param marketIndex Perp market to size buying power for.
465
+ * @param collateralBuffer Amount (QUOTE_PRECISION) subtracted from free collateral before sizing, e.g. to reserve for fees. Defaults to zero.
466
+ * @param maxMarginRatio Optional override for the max margin ratio component (see `resolveMaxMarginRatio`); defaults to the position's/user's configured ratio.
467
+ * @param positionType Whether to size for a cross or isolated-margin position. Defaults to `'cross'`.
468
+ * @returns Precision QUOTE_PRECISION (1e6).
351
469
  */
352
470
  getPerpBuyingPower(marketIndex, collateralBuffer = numericConstants_1.ZERO, maxMarginRatio = undefined, positionType = 'cross') {
353
471
  const perpPosition = this.getPerpPositionOrEmpty(marketIndex);
@@ -375,6 +493,17 @@ class User {
375
493
  // userAccount.maxMarginRatio unchanged — the expected semantic.
376
494
  return Math.max(perpMarketMaxMarginRatio !== null && perpMarketMaxMarginRatio !== void 0 ? perpMarketMaxMarginRatio : 0, this.getUserAccountOrThrow().maxMarginRatio);
377
495
  }
496
+ /**
497
+ * Converts a free-collateral amount directly into buying power for a perp
498
+ * market, given the (hypothetical) resulting base position size — used
499
+ * internally so the margin ratio (which can vary with position size via the
500
+ * IMF factor) reflects the post-trade size rather than the current size.
501
+ * @param marketIndex
502
+ * @param freeCollateral QUOTE_PRECISION (1e6).
503
+ * @param baseAssetAmount Base size, BASE_PRECISION (1e9), used only to select the applicable margin ratio.
504
+ * @param perpMarketMaxMarginRatio Optional max-margin-ratio override, see `resolveMaxMarginRatio`.
505
+ * @returns Precision QUOTE_PRECISION (1e6).
506
+ */
378
507
  getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, baseAssetAmount, perpMarketMaxMarginRatio = undefined) {
379
508
  const maxMarginRatio = this.resolveMaxMarginRatio(perpMarketMaxMarginRatio);
380
509
  const marginRatio = (0, market_1.calculateMarketMarginRatio)(this.velocityClient.getPerpMarketAccountOrThrow(marketIndex), baseAssetAmount, 'Initial', maxMarginRatio);
@@ -382,7 +511,15 @@ class User {
382
511
  }
383
512
  /**
384
513
  * calculates Free Collateral = Total collateral - margin requirement
385
- * @returns : Precision QUOTE_PRECISION
514
+ *
515
+ * When `perpMarketIndex` is provided, returns the free collateral scoped to
516
+ * that market's isolated margin bucket (the isolated quote deposit plus its
517
+ * unrealized PnL, minus its own margin requirement) rather than the user's
518
+ * cross-margin free collateral. If the user has no isolated position open in
519
+ * that market, returns `ZERO` rather than throwing.
520
+ * @param marginCategory `'Initial'` or `'Maintenance'`. Defaults to `'Initial'`; `'Initial'` also enables strict (TWAP-bounded) oracle pricing.
521
+ * @param perpMarketIndex Optional isolated perp market to scope the calculation to; omit for cross margin.
522
+ * @returns Precision QUOTE_PRECISION (1e6). Can be negative (deficit).
386
523
  */
387
524
  getFreeCollateral(marginCategory = 'Initial', perpMarketIndex) {
388
525
  const calc = this.getMarginCalculation(marginCategory, {
@@ -432,19 +569,35 @@ class User {
432
569
  return marginCalc.marginRequirement;
433
570
  }
434
571
  /**
435
- * @returns The initial margin requirement in USDC. : QUOTE_PRECISION
572
+ * Initial margin requirement the collateral needed to open/maintain a
573
+ * position at initial (as opposed to maintenance) margin ratios, using
574
+ * strict (TWAP-bounded) oracle pricing. This is what gates new orders and
575
+ * increases in leverage.
576
+ * @param perpMarketIndex Optional isolated perp market to scope to; omit for the cross-margin requirement.
577
+ * @returns The initial margin requirement in USDC. : QUOTE_PRECISION (1e6)
436
578
  */
437
579
  getInitialMarginRequirement(perpMarketIndex) {
438
580
  return this.getMarginRequirement('Initial', undefined, true, undefined, perpMarketIndex);
439
581
  }
440
582
  /**
441
- * @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
583
+ * Maintenance margin requirement the minimum collateral below which the
584
+ * position becomes eligible for liquidation. Uses non-strict oracle pricing
585
+ * and includes open orders' worst-case impact by default.
586
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) added to the margin ratio, mirroring the state account's `liquidationMarginBufferRatio`.
587
+ * @param perpMarketIndex Optional isolated perp market to scope to; omit for the cross-margin requirement.
588
+ * @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION (1e6)
442
589
  */
443
590
  getMaintenanceMarginRequirement(liquidationBuffer, perpMarketIndex) {
444
591
  return this.getMarginRequirement('Maintenance', liquidationBuffer, false, // strict default
445
592
  true, // includeOpenOrders default
446
593
  perpMarketIndex);
447
594
  }
595
+ /**
596
+ * Filters an explicit `userAccount` snapshot's fixed-size perp position
597
+ * array down to slots that are actually "active": nonzero base or quote
598
+ * amount, an outstanding open order count, or a nonzero isolated-margin
599
+ * quote deposit (a position can be flat but still isolated-funded).
600
+ */
448
601
  getActivePerpPositionsForUserAccount(userAccount) {
449
602
  return userAccount.perpPositions.filter((pos) => {
450
603
  var _a;
@@ -454,10 +607,12 @@ class User {
454
607
  ((_a = pos.isolatedPositionScaledBalance) === null || _a === void 0 ? void 0 : _a.gt(numericConstants_1.ZERO));
455
608
  });
456
609
  }
610
+ /** Returns the cached account's active perp positions. See `getActivePerpPositionsForUserAccount` for the activity criteria. */
457
611
  getActivePerpPositions() {
458
612
  const userAccount = this.getUserAccountOrThrow();
459
613
  return this.getActivePerpPositionsForUserAccount(userAccount);
460
614
  }
615
+ /** Like `getActivePerpPositions`, but also returns the slot at which the underlying `UserAccount` was observed. */
461
616
  getActivePerpPositionsAndSlot() {
462
617
  const userAccount = this.getUserAccountAndSlotOrThrow();
463
618
  const positions = this.getActivePerpPositionsForUserAccount(userAccount.data);
@@ -466,13 +621,16 @@ class User {
466
621
  slot: userAccount.slot,
467
622
  };
468
623
  }
624
+ /** Filters an explicit `userAccount` snapshot's spot positions to those that are not `isSpotPositionAvailable` (i.e. have a nonzero balance, orders, or cumulative deposits). */
469
625
  getActiveSpotPositionsForUserAccount(userAccount) {
470
626
  return userAccount.spotPositions.filter((pos) => !(0, spotPosition_1.isSpotPositionAvailable)(pos));
471
627
  }
628
+ /** Returns the cached account's active spot positions. See `getActiveSpotPositionsForUserAccount` for the activity criteria. */
472
629
  getActiveSpotPositions() {
473
630
  const userAccount = this.getUserAccountOrThrow();
474
631
  return this.getActiveSpotPositionsForUserAccount(userAccount);
475
632
  }
633
+ /** Like `getActiveSpotPositions`, but also returns the slot at which the underlying `UserAccount` was observed. */
476
634
  getActiveSpotPositionsAndSlot() {
477
635
  const userAccount = this.getUserAccountAndSlotOrThrow();
478
636
  const positions = this.getActiveSpotPositionsForUserAccount(userAccount.data);
@@ -482,8 +640,25 @@ class User {
482
640
  };
483
641
  }
484
642
  /**
485
- * calculates unrealized position price pnl
486
- * @returns : Precision QUOTE_PRECISION
643
+ * Calculates unrealized position price PnL, summed across all active perp
644
+ * positions (or a single one if `marketIndex` is given).
645
+ *
646
+ * When `withWeightMarginCategory` is supplied, the PnL is asset-weighted
647
+ * for margin purposes: profitable positions are scaled down by
648
+ * `calculateUnrealizedAssetWeight` (an unrealized gain is a less-trusted
649
+ * asset than settled collateral), and — for `'Initial'` margin specifically
650
+ * — the *per-position* weighted gain is additionally capped at
651
+ * `MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN` (**$100**, QUOTE_PRECISION), a
652
+ * safety guard against a single dangerously-configured or manipulated
653
+ * market inflating buying power. Losses are never capped, and a
654
+ * `liquidationBuffer` (if provided) further inflates negative PnL to
655
+ * mirror the on-chain liquidation-buffer treatment.
656
+ * @param withFunding If true, includes unsettled funding in each position's PnL.
657
+ * @param marketIndex Optional single perp market to scope to; omit to sum across all active positions.
658
+ * @param withWeightMarginCategory Optional `'Initial'` or `'Maintenance'` — applies the asset-weighting (and, for `'Initial'`, the $100-per-position cap) described above. Omit for raw, unweighted PnL.
659
+ * @param strict Use the worse of live oracle price vs 5-minute TWAP per position (gains use the lower price, losses use the higher price). Defaults to false.
660
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) that further penalizes negative PnL; only applied when `withWeightMarginCategory` is set.
661
+ * @returns : Precision QUOTE_PRECISION (1e6)
487
662
  */
488
663
  getUnrealizedPNL(withFunding, marketIndex, withWeightMarginCategory, strict = false, liquidationBuffer) {
489
664
  return this.getActivePerpPositions()
@@ -513,6 +688,10 @@ class User {
513
688
  .mul((0, market_1.calculateUnrealizedAssetWeight)(market, quoteSpotMarket, positionUnrealizedPnl, withWeightMarginCategory, oraclePriceData))
514
689
  .div(new anchor_1.BN(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION));
515
690
  }
691
+ if (withWeightMarginCategory === 'Initial') {
692
+ // safety guard for dangerously configured perp market
693
+ positionUnrealizedPnl = anchor_1.BN.min(positionUnrealizedPnl, numericConstants_1.MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN);
694
+ }
516
695
  if (liquidationBuffer && positionUnrealizedPnl.lt(numericConstants_1.ZERO)) {
517
696
  positionUnrealizedPnl = positionUnrealizedPnl.add(positionUnrealizedPnl.mul(liquidationBuffer).div(numericConstants_1.MARGIN_PRECISION));
518
697
  }
@@ -521,8 +700,11 @@ class User {
521
700
  }, numericConstants_1.ZERO);
522
701
  }
523
702
  /**
524
- * calculates unrealized funding payment pnl
525
- * @returns : Precision QUOTE_PRECISION
703
+ * Calculates unrealized funding payment PnL — the funding accrued since
704
+ * each position's `lastCumulativeFundingRate` was last settled, not yet
705
+ * reflected in `quoteAssetAmount`.
706
+ * @param marketIndex Optional single perp market to scope to; omit to sum across all positions.
707
+ * @returns : Precision QUOTE_PRECISION (1e6)
526
708
  */
527
709
  getUnrealizedFundingPNL(marketIndex) {
528
710
  return this.getUserAccountOrThrow()
@@ -532,6 +714,20 @@ class User {
532
714
  return pnl.add((0, position_1.calculateUnsettledFundingPnl)(market, perpPosition));
533
715
  }, numericConstants_1.ZERO);
534
716
  }
717
+ /**
718
+ * Computes the combined weighted asset value and weighted liability value
719
+ * across the user's spot positions (worst-case, including open-order
720
+ * exposure by default), plus the net quote balance. This is the core spot
721
+ * side of the margin system that `getTotalCollateral`/`getMarginRequirement`
722
+ * build on.
723
+ * @param marketIndex Optional single spot market to scope to; omit to sum across all spot markets.
724
+ * @param marginCategory `'Initial'` or `'Maintenance'` asset/liability weights; omit for unweighted (100%) values.
725
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) added to the liability weight side.
726
+ * @param includeOpenOrders If false, ignores open bids/asks and only counts the current balance (faster, less conservative).
727
+ * @param strict Use the worse of live oracle price vs 5-minute TWAP. Defaults to false.
728
+ * @param now Unix timestamp (seconds) used for TWAP staleness when `strict` is set; defaults to current time.
729
+ * @returns `{ totalAssetValue, totalLiabilityValue }`, both QUOTE_PRECISION (1e6) and non-negative.
730
+ */
535
731
  getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, now) {
536
732
  now = now || new anchor_1.BN(new Date().getTime() / 1000);
537
733
  let netQuoteValue = numericConstants_1.ZERO;
@@ -616,24 +812,35 @@ class User {
616
812
  }
617
813
  return { totalAssetValue, totalLiabilityValue };
618
814
  }
815
+ /** Convenience wrapper around `getSpotMarketAssetAndLiabilityValue` returning only `totalLiabilityValue`. See that method for parameter semantics. Returns QUOTE_PRECISION (1e6). */
619
816
  getSpotMarketLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, now) {
620
817
  const { totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict, now);
621
818
  return totalLiabilityValue;
622
819
  }
820
+ /** Thin wrapper around the `math/spotBalance` `getSpotLiabilityValue` helper that supplies the user's `maxMarginRatio`. Returns QUOTE_PRECISION (1e6), negative. */
623
821
  getSpotLiabilityValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory, liquidationBuffer) {
624
822
  return (0, spotBalance_2.getSpotLiabilityValue)(tokenAmount, strictOraclePrice, spotMarketAccount, this.getUserAccountOrThrow().maxMarginRatio, marginCategory, liquidationBuffer);
625
823
  }
824
+ /** Convenience wrapper around `getSpotMarketAssetAndLiabilityValue` returning only `totalAssetValue`. See that method for parameter semantics. Returns QUOTE_PRECISION (1e6), non-negative. */
626
825
  getSpotMarketAssetValue(marketIndex, marginCategory, includeOpenOrders, strict = false, now) {
627
826
  const { totalAssetValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, undefined, includeOpenOrders, strict, now);
628
827
  return totalAssetValue;
629
828
  }
829
+ /** Thin wrapper around the `math/spotBalance` `getSpotAssetValue` helper that supplies the user's `maxMarginRatio`. Returns QUOTE_PRECISION (1e6), non-negative. */
630
830
  getSpotAssetValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory) {
631
831
  return (0, spotBalance_2.getSpotAssetValue)(tokenAmount, strictOraclePrice, spotMarketAccount, this.getUserAccountOrThrow().maxMarginRatio, marginCategory);
632
832
  }
833
+ /** Net spot value (`totalAssetValue - totalLiabilityValue`) for a single spot market. See `getSpotMarketAssetAndLiabilityValue` for parameter semantics. Returns QUOTE_PRECISION (1e6), can be negative. */
633
834
  getSpotPositionValue(marketIndex, marginCategory, includeOpenOrders, strict = false, now) {
634
835
  const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, undefined, includeOpenOrders, strict, now);
635
836
  return totalAssetValue.sub(totalLiabilityValue);
636
837
  }
838
+ /**
839
+ * Net spot value (`totalAssetValue - totalLiabilityValue`) across all spot
840
+ * markets combined.
841
+ * @param withWeightMarginCategory Optional `'Initial'`/`'Maintenance'` weighting; omit for unweighted values.
842
+ * @returns Precision QUOTE_PRECISION (1e6), can be negative.
843
+ */
637
844
  getNetSpotMarketValue(withWeightMarginCategory) {
638
845
  const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(undefined, withWeightMarginCategory);
639
846
  return totalAssetValue.sub(totalLiabilityValue);
@@ -642,6 +849,24 @@ class User {
642
849
  * calculates TotalCollateral: collateral + unrealized pnl
643
850
  * @returns : Precision QUOTE_PRECISION
644
851
  */
852
+ /**
853
+ * Calculates Total Collateral: net spot collateral value plus weighted
854
+ * unrealized perp PnL (see `getUnrealizedPNL`'s `$100`-per-position cap
855
+ * under `'Initial'` margin). This is the numerator side of the margin
856
+ * system; `getFreeCollateral`/`getMarginRequirement` are derived from it.
857
+ *
858
+ * When `perpMarketIndex` is provided, returns the isolated total collateral
859
+ * for that market's isolated position bucket instead of the cross-margin
860
+ * total — and **throws** if the user has no isolated margin calculation for
861
+ * that market (unlike `getFreeCollateral`, which swallows the same case and
862
+ * returns `ZERO`).
863
+ * @param marginCategory `'Initial'` or `'Maintenance'`. Defaults to `'Initial'`.
864
+ * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
865
+ * @param includeOpenOrders Include open orders' worst-case impact. Defaults to true.
866
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4); selects the buffered collateral variant when non-zero.
867
+ * @param perpMarketIndex Optional isolated perp market to scope to.
868
+ * @returns Precision QUOTE_PRECISION (1e6).
869
+ */
645
870
  getTotalCollateral(marginCategory = 'Initial', strict = false, includeOpenOrders = true, liquidationBuffer, perpMarketIndex) {
646
871
  const liquidationBufferMap = (() => {
647
872
  if (liquidationBuffer && perpMarketIndex !== undefined) {
@@ -673,6 +898,42 @@ class User {
673
898
  }
674
899
  return marginCalc.totalCollateral;
675
900
  }
901
+ /**
902
+ * True when the account has an admin-set `equityFloor` and its cross-margin
903
+ * total collateral is below it. While below the floor, the program rejects
904
+ * risk-increasing order placement and fills, withdrawals, and transfers out
905
+ * of the account (`EquityBelowFloor`); reduce-only activity stays allowed.
906
+ * Mirrors `User::is_below_equity_floor` on-chain.
907
+ * @param strict Use TWAP-bounded oracle pricing, matching the withdraw path. Defaults to false.
908
+ */
909
+ isBelowEquityFloor(strict = false) {
910
+ const equityFloor = this.getUserAccountOrThrow().equityFloor;
911
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
912
+ return false;
913
+ }
914
+ return this.getTotalCollateral('Initial', strict).lt(equityFloor);
915
+ }
916
+ /**
917
+ * Cross-margin total collateral in excess of the admin-set `equityFloor`,
918
+ * floored at zero (QUOTE_PRECISION). Unbounded (`null`) when no floor is set.
919
+ * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
920
+ */
921
+ getEquityAboveFloor(strict = false) {
922
+ const equityFloor = this.getUserAccountOrThrow().equityFloor;
923
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
924
+ return null;
925
+ }
926
+ return anchor_1.BN.max(this.getTotalCollateral('Initial', strict).sub(equityFloor), numericConstants_1.ZERO);
927
+ }
928
+ /**
929
+ * Builds the liquidation-buffer map to pass into margin calculations while
930
+ * a liquidation is in progress: `'cross'` is set to the state account's
931
+ * `liquidationMarginBufferRatio` if cross margin is being liquidated, and
932
+ * each isolated perp position currently flagged `BeingLiquidated` or
933
+ * `Bankruptcy` gets the same buffer under its market index. Positions not
934
+ * currently being liquidated are omitted (no buffer applied).
935
+ * @returns Map from `'cross'` or a perp market index to the buffer amount (MARGIN_PRECISION, 1e4).
936
+ */
676
937
  getLiquidationBuffer() {
677
938
  const liquidationBufferMap = new Map();
678
939
  if (this.isBeingLiquidated()) {
@@ -687,8 +948,19 @@ class User {
687
948
  return liquidationBufferMap;
688
949
  }
689
950
  /**
690
- * calculates User Health by comparing total collateral and maint. margin requirement
691
- * @returns : number (value from [0, 100])
951
+ * Calculates a user's health score by comparing total collateral against
952
+ * the maintenance margin requirement: `100 * (1 - maintenanceMarginReq / totalCollateral)`,
953
+ * clamped to `[0, 100]` and rounded to the nearest integer. `100` means no
954
+ * maintenance requirement (or a requirement of zero with non-negative
955
+ * collateral); `0` means at or past the maintenance threshold (liquidatable)
956
+ * or that collateral is non-positive.
957
+ *
958
+ * Short-circuits to `0` if the relevant scope is already flagged as being
959
+ * liquidated: cross margin via `isCrossMarginBeingLiquidated` (when
960
+ * `perpMarketIndex` is omitted), or the specific isolated position via
961
+ * `isIsolatedPositionBeingLiquidated` (when `perpMarketIndex` is given).
962
+ * @param perpMarketIndex Optional isolated perp market to scope health to; omit for the cross-margin account's health.
963
+ * @returns Health, an integer in `[0, 100]`.
692
964
  */
693
965
  getHealth(perpMarketIndex) {
694
966
  if (this.isCrossMarginBeingLiquidated() && !perpMarketIndex) {
@@ -725,6 +997,15 @@ class User {
725
997
  }
726
998
  return health;
727
999
  }
1000
+ /**
1001
+ * Computes a single perp position's margin-weighted liability value: worst-case
1002
+ * (or current, if `includeOpenOrders` is false) base amount, valued at the
1003
+ * oracle price (or `expiryPrice` if the market is in settlement, which also
1004
+ * zeroes the margin ratio), scaled by the applicable margin ratio for
1005
+ * `marginCategory`. Underlies `getPerpMarketLiabilityValue`,
1006
+ * `getTotalPerpPositionLiability`, and the leverage/liquidation-price math.
1007
+ * @returns Precision QUOTE_PRECISION (1e6); unweighted (raw notional, no margin ratio applied) if `marginCategory` is omitted.
1008
+ */
728
1009
  calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
729
1010
  const market = this.velocityClient.getPerpMarketAccountOrThrow(perpPosition.marketIndex);
730
1011
  let valuationPrice = this.getOracleDataForPerpMarket(market.marketIndex).price;
@@ -772,16 +1053,28 @@ class User {
772
1053
  return liabilityValue;
773
1054
  }
774
1055
  /**
775
- * calculates position value of a single perp market in margin system
776
- * @returns : Precision QUOTE_PRECISION
1056
+ * Margin-weighted liability value of a single perp position. Thin wrapper
1057
+ * around `calculateWeightedPerpPositionLiability` for the position in
1058
+ * `marketIndex`; see that method for the worst-case/margin-ratio semantics.
1059
+ * @param marketIndex
1060
+ * @param marginCategory `'Initial'`/`'Maintenance'` margin ratio to apply; omit for the raw unweighted notional.
1061
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) added to the margin ratio.
1062
+ * @param includeOpenOrders If true (recommended for margin checks), uses the worst-case base amount including open bids/asks.
1063
+ * @param strict Use TWAP-bounded quote pricing. Defaults to false.
1064
+ * @returns Precision QUOTE_PRECISION (1e6). Throws (via `getPerpPositionOrThrow`) if the user has no active position in `marketIndex`.
777
1065
  */
778
1066
  getPerpMarketLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
779
1067
  const perpPosition = this.getPerpPositionOrThrow(marketIndex);
780
1068
  return this.calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict);
781
1069
  }
782
1070
  /**
783
- * calculates sum of position value across all positions in margin system
784
- * @returns : Precision QUOTE_PRECISION
1071
+ * Sums `calculateWeightedPerpPositionLiability` across every active perp
1072
+ * position the perp side of the margin requirement (see `getMarginRequirement`).
1073
+ * @param marginCategory `'Initial'`/`'Maintenance'` margin ratio to apply; omit for the raw unweighted notional.
1074
+ * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) added to the margin ratio.
1075
+ * @param includeOpenOrders If true, uses each position's worst-case base amount including open bids/asks.
1076
+ * @param strict Use TWAP-bounded quote pricing. Defaults to false.
1077
+ * @returns Precision QUOTE_PRECISION (1e6).
785
1078
  */
786
1079
  getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
787
1080
  return this.getActivePerpPositions().reduce((totalPerpValue, perpPosition) => {
@@ -790,8 +1083,14 @@ class User {
790
1083
  }, numericConstants_1.ZERO);
791
1084
  }
792
1085
  /**
793
- * calculates position value based on oracle
794
- * @returns : Precision QUOTE_PRECISION
1086
+ * Values a perp position's base-asset notional at a caller-supplied oracle
1087
+ * price rather than looking one up internally — useful for pricing against
1088
+ * a simulated/custom price. Returns `ZERO` (via `getPerpPositionOrEmpty`) if
1089
+ * the user has no position in `marketIndex`.
1090
+ * @param marketIndex
1091
+ * @param oraclePriceData Price to value the position at, PRICE_PRECISION (1e6). Caller-supplied so callers can pass a custom/simulated price.
1092
+ * @param includeOpenOrders If true, uses the worst-case base amount (including open bids/asks) instead of the current position size. Defaults to false.
1093
+ * @returns Precision QUOTE_PRECISION (1e6).
795
1094
  */
796
1095
  getPerpPositionValue(marketIndex, oraclePriceData, includeOpenOrders = false) {
797
1096
  const userPosition = this.getPerpPositionOrEmpty(marketIndex);
@@ -799,8 +1098,13 @@ class User {
799
1098
  return (0, margin_2.calculateBaseAssetValueWithOracle)(market, userPosition, oraclePriceData, includeOpenOrders);
800
1099
  }
801
1100
  /**
802
- * calculates position liabiltiy value in margin system
803
- * @returns : Precision QUOTE_PRECISION
1101
+ * Unweighted (no margin ratio applied) perp liability notional at a
1102
+ * caller-supplied oracle price. Returns `ZERO` (via `getPerpPositionOrEmpty`)
1103
+ * if the user has no position in `marketIndex`.
1104
+ * @param marketIndex
1105
+ * @param oraclePriceData Price to value the position at, PRICE_PRECISION (1e6).
1106
+ * @param includeOpenOrders If true, uses the worst-case (including open bids/asks) liability value; otherwise just the current position. Defaults to false.
1107
+ * @returns Precision QUOTE_PRECISION (1e6).
804
1108
  */
805
1109
  getPerpLiabilityValue(marketIndex, oraclePriceData, includeOpenOrders = false) {
806
1110
  const userPosition = this.getPerpPositionOrEmpty(marketIndex);
@@ -812,6 +1116,7 @@ class User {
812
1116
  return (0, margin_1.calculatePerpLiabilityValue)(userPosition.baseAssetAmount, oraclePriceData.price);
813
1117
  }
814
1118
  }
1119
+ /** Returns `PositionDirection.LONG`/`SHORT` from the sign of `baseAssetAmount`, or `undefined` if the position is flat. */
815
1120
  getPositionSide(currentPosition) {
816
1121
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
817
1122
  return types_2.PositionDirection.LONG;
@@ -825,7 +1130,10 @@ class User {
825
1130
  }
826
1131
  /**
827
1132
  * calculates average exit price (optionally for closing up to 100% of position)
828
- * @returns : Precision PRICE_PRECISION
1133
+ * @param position Position to estimate the close for.
1134
+ * @param amountToClose Optional base amount (BASE_PRECISION, 1e9) to simulate closing; if omitted, closes the full position. Passing `ZERO` returns the current reserve price with zero PnL.
1135
+ * @param useAMMClose If true, values the close against the AMM's own reserves (`calculateBaseAssetValue`) instead of the oracle-referenced value (`calculateBaseAssetValueWithOracle`). Defaults to false.
1136
+ * @returns Tuple of `[exitPrice, pnl]` — exitPrice is PRICE_PRECISION (1e6), pnl is QUOTE_PRECISION (1e6).
829
1137
  */
830
1138
  getPositionEstimatedExitPriceAndPnl(position, amountToClose, useAMMClose = false) {
831
1139
  const market = this.velocityClient.getPerpMarketAccountOrThrow(position.marketIndex);
@@ -865,11 +1173,14 @@ class User {
865
1173
  }
866
1174
  /**
867
1175
  * calculates current user leverage which is (total liability size) / (net asset value)
868
- * @returns : Precision TEN_THOUSAND
1176
+ * @param includeOpenOrders If true, sizes the perp liability using worst-case open-order exposure. Defaults to true.
1177
+ * @param perpMarketIndex Optional single isolated perp market to scope leverage to (uses that position's own isolated deposit + PnL as its asset value); omit for account-wide leverage.
1178
+ * @returns : Precision TEN_THOUSAND (1e4, i.e. `10000` = 1x leverage). `ZERO` if net asset value is zero.
869
1179
  */
870
1180
  getLeverage(includeOpenOrders = true, perpMarketIndex) {
871
1181
  return this.calculateLeverageFromComponents(this.getLeverageComponents(includeOpenOrders, undefined, perpMarketIndex));
872
1182
  }
1183
+ /** Combines the components from `getLeverageComponents` into a single leverage ratio: `(perpLiability + spotLiability) / (spotAsset + perpPnl - spotLiability)`. Returns TEN_THOUSAND (1e4) precision; `ZERO` if net asset value is zero. */
873
1184
  calculateLeverageFromComponents({ perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue, }) {
874
1185
  const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
875
1186
  const totalAssetValue = spotAssetValue.add(perpPnl);
@@ -879,6 +1190,18 @@ class User {
879
1190
  }
880
1191
  return totalLiabilityValue.mul(numericConstants_1.TEN_THOUSAND).div(netAssetValue);
881
1192
  }
1193
+ /**
1194
+ * Gathers the four raw components (`perpLiabilityValue`, `perpPnl`,
1195
+ * `spotAssetValue`, `spotLiabilityValue`, all QUOTE_PRECISION/1e6) that
1196
+ * `calculateLeverageFromComponents` combines into a leverage ratio.
1197
+ *
1198
+ * When `perpMarketIndex` is given, scopes to a single isolated position:
1199
+ * `spotAssetValue` becomes that position's isolated quote deposit and
1200
+ * `spotLiabilityValue` is `ZERO` (isolated positions carry no spot
1201
+ * liability of their own). Otherwise sums across the whole account, and
1202
+ * folds in `getTotalIsolatedPositionDeposits` as additional spot asset
1203
+ * value when `marginCategory` is unweighted.
1204
+ */
882
1205
  getLeverageComponents(includeOpenOrders = true, marginCategory = undefined, perpMarketIndex) {
883
1206
  var _a;
884
1207
  if (perpMarketIndex) {
@@ -912,6 +1235,13 @@ class User {
912
1235
  spotLiabilityValue,
913
1236
  };
914
1237
  }
1238
+ /**
1239
+ * Returns true if the user's deposit position in `spotMarketAccount` is
1240
+ * non-empty but worth less than `DUST_POSITION_SIZE` (QUOTE_PRECISION) —
1241
+ * i.e. too small to be economically worth withdrawing/settling. Only
1242
+ * evaluates deposits (returns false for borrows or an empty position).
1243
+ * @throws If the user has no spot position slot for the market (should not happen for a valid `SpotMarketAccount`).
1244
+ */
915
1245
  isDustDepositPosition(spotMarketAccount) {
916
1246
  const marketIndex = spotMarketAccount.marketIndex;
917
1247
  const spotPosition = this.getSpotPosition(spotMarketAccount.marketIndex);
@@ -933,6 +1263,7 @@ class User {
933
1263
  }
934
1264
  return false;
935
1265
  }
1266
+ /** Returns every spot market where the user holds a dust-sized deposit; see `isDustDepositPosition`. */
936
1267
  getSpotMarketAccountsWithDustPosition() {
937
1268
  const spotMarketAccounts = this.velocityClient.getSpotMarketAccounts();
938
1269
  const dustPositionAccounts = [];
@@ -944,9 +1275,22 @@ class User {
944
1275
  }
945
1276
  return dustPositionAccounts;
946
1277
  }
1278
+ /**
1279
+ * Sum of the user's total perp position liability (worst-case, open orders
1280
+ * included) and total spot liability value (worst-case, open orders included).
1281
+ * @param marginCategory Optional `'Initial'`/`'Maintenance'` weighting; omit for unweighted values.
1282
+ * @returns Precision QUOTE_PRECISION (1e6), non-negative.
1283
+ */
947
1284
  getTotalLiabilityValue(marginCategory) {
948
1285
  return this.getTotalPerpPositionLiability(marginCategory, undefined, true).add(this.getSpotMarketLiabilityValue(undefined, marginCategory, undefined, true));
949
1286
  }
1287
+ /**
1288
+ * Sum of the user's total spot asset value and total unrealized perp PnL
1289
+ * (with funding). When `marginCategory` is omitted (unweighted), also
1290
+ * includes `getTotalIsolatedPositionDeposits`.
1291
+ * @param marginCategory Optional `'Initial'`/`'Maintenance'` weighting; omit for unweighted values.
1292
+ * @returns Precision QUOTE_PRECISION (1e6), non-negative.
1293
+ */
950
1294
  getTotalAssetValue(marginCategory) {
951
1295
  const value = this.getSpotMarketAssetValue(undefined, marginCategory, true).add(this.getUnrealizedPNL(true, undefined, marginCategory));
952
1296
  if (marginCategory === undefined) {
@@ -954,6 +1298,11 @@ class User {
954
1298
  }
955
1299
  return value;
956
1300
  }
1301
+ /**
1302
+ * Unweighted net USD value of the account: net spot market value, plus
1303
+ * unrealized (funding-inclusive) perp PnL, plus isolated position deposits.
1304
+ * @returns Precision QUOTE_PRECISION (1e6), can be negative.
1305
+ */
957
1306
  getNetUsdValue() {
958
1307
  const netSpotValue = this.getNetSpotMarketValue();
959
1308
  const unrealizedPnl = this.getUnrealizedPNL(true, undefined, undefined);
@@ -961,9 +1310,11 @@ class User {
961
1310
  return netSpotValue.add(unrealizedPnl).add(isolatedDeposits);
962
1311
  }
963
1312
  /**
964
- * Calculates the all time P&L of the user.
965
- *
966
- * Net withdraws + Net spot market value + Net unrealized P&L -
1313
+ * Calculates the all-time P&L of the user: current net USD value
1314
+ * (`getNetUsdValue`), plus lifetime total withdraws, minus lifetime total
1315
+ * deposits. Equivalent to "everything the account is worth now, plus
1316
+ * everything ever taken out, minus everything ever put in".
1317
+ * @returns Precision QUOTE_PRECISION (1e6), can be negative.
967
1318
  */
968
1319
  getTotalAllTimePnl() {
969
1320
  const netUsdValue = this.getNetUsdValue();
@@ -975,8 +1326,8 @@ class User {
975
1326
  /**
976
1327
  * calculates max allowable leverage exceeding hitting requirement category
977
1328
  * for large sizes where imf factor activates, result is a lower bound
978
- * @param marginCategory {Initial, Maintenance}
979
- * @returns : Precision TEN_THOUSAND
1329
+ * @param marginCategory {Initial, Maintenance} — currently unused; the calculation always uses the max-tradeable-size ('Initial') buying power.
1330
+ * @returns : Precision TEN_THOUSAND (1e4, i.e. `10000` = 1x)
980
1331
  */
981
1332
  getMaxLeverageForPerp(perpMarketIndex, _marginCategory = 'Initial') {
982
1333
  const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
@@ -997,8 +1348,8 @@ class User {
997
1348
  /**
998
1349
  * calculates max allowable leverage exceeding hitting requirement category
999
1350
  * @param spotMarketIndex
1000
- * @param direction
1001
- * @returns : Precision TEN_THOUSAND
1351
+ * @param direction Whether to simulate a long (deposit-increasing) or short (borrow-increasing) trade.
1352
+ * @returns : Precision TEN_THOUSAND (1e4, i.e. `10000` = 1x)
1002
1353
  */
1003
1354
  getMaxLeverageForSpot(spotMarketIndex, direction) {
1004
1355
  const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
@@ -1039,7 +1390,7 @@ class User {
1039
1390
  }
1040
1391
  /**
1041
1392
  * calculates margin ratio: 1 / leverage
1042
- * @returns : Precision TEN_THOUSAND
1393
+ * @returns : Precision TEN_THOUSAND (1e4, i.e. `10000` = 100% margin ratio / 1x leverage). Returns `BN_MAX` if the account has no liabilities.
1043
1394
  */
1044
1395
  getMarginRatio() {
1045
1396
  const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
@@ -1051,6 +1402,10 @@ class User {
1051
1402
  const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
1052
1403
  return netAssetValue.mul(numericConstants_1.TEN_THOUSAND).div(totalLiabilityValue);
1053
1404
  }
1405
+ /**
1406
+ * @deprecated Use `getLiquidationStatuses` for the full cross + per-isolated-market breakdown. This method returns only the cross-margin status (plus the same isolated map, for convenience) for backward compatibility.
1407
+ * @returns The cross-margin `AccountLiquidatableStatus`, plus `isolatedPositions` mapping each isolated perp market index to its own status.
1408
+ */
1054
1409
  canBeLiquidated() {
1055
1410
  // Deprecated signature retained for backward compatibility in type only
1056
1411
  // but implementation now delegates to the new Map-based API and returns cross margin status.
@@ -1073,6 +1428,14 @@ class User {
1073
1428
  * Map keys:
1074
1429
  * - 'cross' for cross margin
1075
1430
  * - marketIndex (number) for each isolated perp position
1431
+ *
1432
+ * Each `canBeLiquidated` compares maintenance total collateral against the
1433
+ * maintenance margin requirement for that scope. If `marginCalc` is not
1434
+ * supplied, one is computed under `'Maintenance'` with the account's
1435
+ * current `getLiquidationBuffer()` applied — i.e. this defaults to the same
1436
+ * buffered check the on-chain liquidation instructions use, not a bare
1437
+ * maintenance-margin comparison.
1438
+ * @param marginCalc Optional pre-computed `MarginCalculation` to reuse (avoids recomputing margin across repeated calls).
1076
1439
  */
1077
1440
  getLiquidationStatuses(marginCalc) {
1078
1441
  // If not provided, use buffer-aware calc for canBeLiquidated checks
@@ -1103,10 +1466,12 @@ class User {
1103
1466
  }
1104
1467
  return result;
1105
1468
  }
1469
+ /** Returns true if cross margin or any isolated perp position is currently flagged as being liquidated or bankrupt. */
1106
1470
  isBeingLiquidated() {
1107
1471
  return (this.isCrossMarginBeingLiquidated() ||
1108
1472
  this.hasIsolatedPositionBeingLiquidated());
1109
1473
  }
1474
+ /** Returns true if the account-level `UserStatus` has `BEING_LIQUIDATED` or `BANKRUPT` set (cross margin, not per-isolated-position). */
1110
1475
  isCrossMarginBeingLiquidated() {
1111
1476
  return ((this.getUserAccountOrThrow().status &
1112
1477
  (types_1.UserStatus.BEING_LIQUIDATED | types_1.UserStatus.BANKRUPT)) >
@@ -1117,11 +1482,13 @@ class User {
1117
1482
  const calc = marginCalc !== null && marginCalc !== void 0 ? marginCalc : this.getMarginCalculation('Maintenance');
1118
1483
  return calc.totalCollateral.lt(calc.marginRequirement);
1119
1484
  }
1485
+ /** Returns true if any active perp position has `PositionFlag.BeingLiquidated` or `PositionFlag.Bankruptcy` set. */
1120
1486
  hasIsolatedPositionBeingLiquidated() {
1121
1487
  return this.getActivePerpPositions().some((position) => (position.positionFlag &
1122
1488
  (types_2.PositionFlag.BeingLiquidated | types_2.PositionFlag.Bankruptcy)) >
1123
1489
  0);
1124
1490
  }
1491
+ /** Returns true if the specific perp position in `perpMarketIndex` has `PositionFlag.BeingLiquidated` or `PositionFlag.Bankruptcy` set. False (not throw) if the user has no position there. */
1125
1492
  isIsolatedPositionBeingLiquidated(perpMarketIndex) {
1126
1493
  var _a;
1127
1494
  const position = this.getActivePerpPositions().find((position) => position.marketIndex === perpMarketIndex);
@@ -1140,18 +1507,21 @@ class User {
1140
1507
  }
1141
1508
  return liquidatableIsolatedPositions;
1142
1509
  }
1510
+ /** Returns true if `isolatedMarginCalculation`'s collateral is below its margin requirement (no buffer). */
1143
1511
  canIsolatedPositionMarginBeLiquidated(isolatedMarginCalculation) {
1144
1512
  return isolatedMarginCalculation.totalCollateral.lt(isolatedMarginCalculation.marginRequirement);
1145
1513
  }
1514
+ /** Returns true if the account's `UserStatus` bitmask has `status` set. */
1146
1515
  hasStatus(status) {
1147
1516
  return (this.getUserAccountOrThrow().status & status) > 0;
1148
1517
  }
1518
+ /** Returns true if the account's `UserStatus` has `BANKRUPT` set (equity insufficient to cover liabilities; awaiting bankruptcy resolution). */
1149
1519
  isBankrupt() {
1150
1520
  return (this.getUserAccountOrThrow().status & types_1.UserStatus.BANKRUPT) > 0;
1151
1521
  }
1152
1522
  /**
1153
1523
  * Checks if any user position cumulative funding differs from respective market cumulative funding
1154
- * @returns
1524
+ * @returns True if at least one non-flat perp position has stale `lastCumulativeFundingRate` relative to the market's current long/short cumulative funding rate.
1155
1525
  */
1156
1526
  needsToSettleFundingPayment() {
1157
1527
  for (const userPosition of this.getUserAccountOrThrow().perpPositions) {
@@ -1168,9 +1538,16 @@ class User {
1168
1538
  return false;
1169
1539
  }
1170
1540
  /**
1171
- * Calculate the liquidation price of a spot position
1172
- * @param marketIndex
1173
- * @returns Precision : PRICE_PRECISION
1541
+ * Calculate the liquidation price of a spot position — the oracle price at
1542
+ * which maintenance free collateral would hit zero, extrapolating linearly
1543
+ * from the current free collateral and the position's per-unit-price
1544
+ * sensitivity (`calculateFreeCollateralDeltaForSpot`). If a perp market
1545
+ * shares the same oracle as this spot market, that perp position's
1546
+ * sensitivity is folded in too (scaled for any oracle-source unit
1547
+ * difference), since a single price move affects both simultaneously.
1548
+ * @param marketIndex Spot market to compute the liquidation price for.
1549
+ * @param positionBaseSizeChange Optional simulated change to the position size, in the spot market's own token decimals. Defaults to no change.
1550
+ * @returns Precision PRICE_PRECISION (1e6). Returns `new BN(-1)` as a sentinel when there is no position, the position (after `positionBaseSizeChange`) is flat, the price sensitivity is zero, or the computed liquidation price would be negative (position cannot be liquidated by a price move alone).
1174
1551
  */
1175
1552
  spotLiquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO) {
1176
1553
  const currentSpotPosition = this.getSpotPosition(marketIndex);
@@ -1218,14 +1595,23 @@ class User {
1218
1595
  return liqPrice;
1219
1596
  }
1220
1597
  /**
1221
- * Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
1598
+ * Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade.
1599
+ *
1600
+ * Like `spotLiquidationPrice`, this extrapolates linearly from current free
1601
+ * collateral (`totalCollateral - marginRequirement`, plus `offsetCollateral`)
1602
+ * and the position's price sensitivity; if a spot market shares the same
1603
+ * oracle, its sensitivity is folded in too. When `marginType === 'Isolated'`,
1604
+ * free collateral and the margin requirement are scoped to that market's
1605
+ * isolated bucket instead of the cross-margin account (and the spot-oracle
1606
+ * cross-contribution above is skipped).
1222
1607
  * @param marketIndex
1223
- * @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^9
1224
- * @param estimatedEntryPrice
1225
- * @param marginCategory // allow Initial to be passed in if we are trying to calculate price for DLP de-risking
1226
- * @param includeOpenOrders
1227
- * @param offsetCollateral // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)
1228
- * @returns Precision : PRICE_PRECISION
1608
+ * @param positionBaseSizeChange Change in position size to calculate the liquidation price for, standardized to the market's order step size. Precision BASE_PRECISION (1e9).
1609
+ * @param estimatedEntryPrice Entry price for `positionBaseSizeChange`, PRICE_PRECISION (1e6); only affects the result under `marginCategory: 'Maintenance'` (it adjusts free collateral for the estimated realized PnL and taker fee of entering at this price rather than at the oracle price).
1610
+ * @param marginCategory Allow `'Initial'` to be passed in if we are trying to calculate price for DLP de-risking. Defaults to `'Maintenance'` (the actual liquidation threshold).
1611
+ * @param includeOpenOrders Include open orders' worst-case exposure when sizing the position. Defaults to false.
1612
+ * @param offsetCollateral Allows calculating the liquidation price after this offset collateral (QUOTE_PRECISION, 1e6) is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral). Defaults to zero.
1613
+ * @param marginType `'Isolated'` to scope the calculation to `marketIndex`'s isolated margin bucket; omit/`'Cross'` for the cross-margin account.
1614
+ * @returns Precision : PRICE_PRECISION (1e6). Returns `new BN(-1)` as a sentinel when there is no isolated margin calculation for the market (isolated mode), the price sensitivity is zero, or the computed price would be negative (position cannot be liquidated by a price move alone).
1229
1615
  */
1230
1616
  liquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO, estimatedEntryPrice = numericConstants_1.ZERO, marginCategory = 'Maintenance', includeOpenOrders = false, offsetCollateral = numericConstants_1.ZERO, marginType) {
1231
1617
  const market = this.velocityClient.getPerpMarketAccountOrThrow(marketIndex);
@@ -1294,6 +1680,16 @@ class User {
1294
1680
  }
1295
1681
  return liqPrice;
1296
1682
  }
1683
+ /**
1684
+ * Helper for `liquidationPrice`: estimates the net change to free collateral
1685
+ * from simultaneously (a) realizing PnL on `positionBaseSizeChange` entered
1686
+ * at `estimatedEntryPrice` (assuming the worst/taker fee tier) versus the
1687
+ * oracle price, and (b) the resulting change in margin requirement from the
1688
+ * new position size. Only component (a) applies under `'Maintenance'`
1689
+ * (matching `liquidationPrice`'s default); under other margin categories
1690
+ * only the margin-requirement delta is applied.
1691
+ * @returns Precision QUOTE_PRECISION (1e6); can be negative.
1692
+ */
1297
1693
  calculateEntriesEffectOnFreeCollateral(market, oraclePrice, perpPosition, positionBaseSizeChange, estimatedEntryPrice, includeOpenOrders, marginCategory = 'Maintenance') {
1298
1694
  let freeCollateralChange = numericConstants_1.ZERO;
1299
1695
  // update free collateral to account for change in pnl from new position
@@ -1312,11 +1708,9 @@ class User {
1312
1708
  else {
1313
1709
  freeCollateralChange = newPositionValue.sub(costBasis);
1314
1710
  }
1315
- // assume worst fee tier
1711
+ // assume worst fee tier; ceil-divide to match calculate_taker_fee's safe_div_ceil
1316
1712
  const takerFeeTier = this.velocityClient.getStateAccount().perpFeeStructure.feeTiers[0];
1317
- const takerFee = newPositionValue
1318
- .muln(takerFeeTier.feeNumerator)
1319
- .divn(takerFeeTier.feeDenominator);
1713
+ const takerFee = (0, utils_2.divCeil)(newPositionValue.muln(takerFeeTier.feeNumerator), new anchor_1.BN(takerFeeTier.feeDenominator));
1320
1714
  freeCollateralChange = freeCollateralChange.sub(takerFee);
1321
1715
  }
1322
1716
  const calculateMarginRequirement = (perpPosition) => {
@@ -1341,6 +1735,14 @@ class User {
1341
1735
  const freeCollateralConsumptionAfter = calculateMarginRequirement(perpPositionAfter);
1342
1736
  return freeCollateralChange.sub(freeCollateralConsumptionAfter.sub(freeCollateralConsumptionBefore));
1343
1737
  }
1738
+ /**
1739
+ * Helper for `liquidationPrice`: the derivative of free collateral with
1740
+ * respect to the perp market's oracle price, for the proposed post-trade
1741
+ * position (`positionBaseSizeChange` applied to the current, or worst-case
1742
+ * if `includeOpenOrders`, base amount). Used as the linear-extrapolation
1743
+ * slope to solve for the price at which free collateral hits zero.
1744
+ * @returns Precision QUOTE_PRECISION (1e6) per unit of PRICE_PRECISION move, or `undefined` if the proposed position is flat (no defined liquidation price).
1745
+ */
1344
1746
  calculateFreeCollateralDeltaForPerp(market, perpPosition, positionBaseSizeChange, oraclePrice, marginCategory = 'Maintenance', includeOpenOrders = false) {
1345
1747
  const baseAssetAmount = includeOpenOrders
1346
1748
  ? (0, margin_2.calculateWorstCaseBaseAssetAmount)(perpPosition, market, oraclePrice)
@@ -1375,6 +1777,12 @@ class User {
1375
1777
  }
1376
1778
  return freeCollateralDelta;
1377
1779
  }
1780
+ /**
1781
+ * Helper for `spotLiquidationPrice`/`liquidationPrice`: the derivative of
1782
+ * free collateral with respect to the spot market's oracle price, for a
1783
+ * position of `signedTokenAmount` (positive = deposit, negative = borrow).
1784
+ * @returns Precision QUOTE_PRECISION (1e6) per unit of PRICE_PRECISION move.
1785
+ */
1378
1786
  calculateFreeCollateralDeltaForSpot(market, signedTokenAmount, marginCategory = 'Maintenance') {
1379
1787
  const tokenPrecision = new anchor_1.BN(Math.pow(10, market.decimals));
1380
1788
  if (signedTokenAmount.gt(numericConstants_1.ZERO)) {
@@ -1397,8 +1805,9 @@ class User {
1397
1805
  /**
1398
1806
  * Calculates the estimated liquidation price for a position after closing a quote amount of the position.
1399
1807
  * @param positionMarketIndex
1400
- * @param closeQuoteAmount
1401
- * @returns : Precision PRICE_PRECISION
1808
+ * @param closeQuoteAmount Quote-denominated amount of the position to close, QUOTE_PRECISION (1e6). Converted proportionally to a base-size reduction via the position's current cost basis.
1809
+ * @param estimatedEntryPrice Forwarded to `liquidationPrice` as the entry price for the (negative, i.e. closing) size change. PRICE_PRECISION (1e6). Defaults to zero.
1810
+ * @returns : Precision PRICE_PRECISION (1e6). See `liquidationPrice` for the `-1` sentinel cases.
1402
1811
  */
1403
1812
  liquidationPriceAfterClose(positionMarketIndex, closeQuoteAmount, estimatedEntryPrice = numericConstants_1.ZERO) {
1404
1813
  const currentPosition = this.getPerpPositionOrEmpty(positionMarketIndex);
@@ -1411,10 +1820,27 @@ class User {
1411
1820
  .neg();
1412
1821
  return this.liquidationPrice(positionMarketIndex, closeBaseAmount, estimatedEntryPrice);
1413
1822
  }
1823
+ /**
1824
+ * Calculates the margin required to open a trade of `baseSize` in `targetMarketIndex`, scalar only — does not account for trade direction or existing positions/whether the trade is actually risk-increasing.
1825
+ * @param baseSize BASE_PRECISION (1e9).
1826
+ * @param estEntryPrice Optional entry price to value the trade at, PRICE_PRECISION (1e6); defaults to the oracle price.
1827
+ * @param perpMarketMaxMarginRatio Optional max-margin-ratio override, see `resolveMaxMarginRatio`.
1828
+ * @returns Precision QUOTE_PRECISION (1e6).
1829
+ */
1414
1830
  getMarginUSDCRequiredForTrade(targetMarketIndex, baseSize, estEntryPrice, perpMarketMaxMarginRatio) {
1415
1831
  const maxMarginRatio = this.resolveMaxMarginRatio(perpMarketMaxMarginRatio);
1416
1832
  return (0, margin_2.calculateMarginUSDCRequiredForTrade)(this.velocityClient, targetMarketIndex, baseSize, maxMarginRatio, estEntryPrice);
1417
1833
  }
1834
+ /**
1835
+ * Converts `getMarginUSDCRequiredForTrade`'s USDC margin requirement into
1836
+ * how much of `collateralIndex`'s token a user would need to deposit to
1837
+ * cover it, accounting for that collateral's scaled initial asset weight
1838
+ * (a lower-weighted asset requires proportionally more deposited).
1839
+ * @param baseSize BASE_PRECISION (1e9).
1840
+ * @param collateralIndex Spot market to size the deposit in.
1841
+ * @param perpMarketMaxMarginRatio Optional max-margin-ratio override, see `resolveMaxMarginRatio`.
1842
+ * @returns Token amount in `collateralIndex`'s own decimals.
1843
+ */
1418
1844
  getCollateralDepositRequiredForTrade(targetMarketIndex, baseSize, collateralIndex, perpMarketMaxMarginRatio) {
1419
1845
  const maxMarginRatio = this.resolveMaxMarginRatio(perpMarketMaxMarginRatio);
1420
1846
  return (0, margin_2.calculateCollateralDepositRequiredForTrade)(this.velocityClient, targetMarketIndex, baseSize, collateralIndex, maxMarginRatio);
@@ -1425,7 +1851,9 @@ class User {
1425
1851
  * - oppositeSideTradeSize: the trade size for closing the opposite direction
1426
1852
  * @param targetMarketIndex
1427
1853
  * @param tradeSide
1428
- * @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION
1854
+ * @param maxMarginRatio Optional max-margin-ratio override, see `resolveMaxMarginRatio`.
1855
+ * @param positionType Whether to size for a cross or isolated-margin position (forwarded to `getPerpBuyingPower`). Defaults to `'cross'`.
1856
+ * @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION (1e6)
1429
1857
  */
1430
1858
  getMaxTradeSizeUSDCForPerp(targetMarketIndex, tradeSide, maxMarginRatio = undefined, positionType = 'cross') {
1431
1859
  let tradeSize = numericConstants_1.ZERO;
@@ -1504,10 +1932,10 @@ class User {
1504
1932
  * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
1505
1933
  *
1506
1934
  * @param targetMarketIndex
1507
- * @param direction
1508
- * @param currentQuoteAssetValue
1509
- * @param currentSpotMarketNetValue
1510
- * @returns tradeSizeAllowed : Precision QUOTE_PRECISION
1935
+ * @param direction Long (increase deposit / reduce borrow) or short (increase borrow / reduce deposit).
1936
+ * @param currentQuoteAssetValue Ignored — always recomputed internally from `getSpotMarketAssetValue(QUOTE_SPOT_MARKET_INDEX)`.
1937
+ * @param currentSpotMarketNetValue Optional pre-computed net value for `targetMarketIndex` (QUOTE_PRECISION, 1e6); if omitted, computed via `getSpotPositionValue`.
1938
+ * @returns tradeSizeAllowed : Precision QUOTE_PRECISION (1e6)
1511
1939
  */
1512
1940
  getMaxTradeSizeUSDCForSpot(targetMarketIndex, direction, currentQuoteAssetValue, currentSpotMarketNetValue) {
1513
1941
  const market = this.velocityClient.getSpotMarketAccountOrThrow(targetMarketIndex);
@@ -1549,8 +1977,9 @@ class User {
1549
1977
  *
1550
1978
  * @param inMarketIndex
1551
1979
  * @param outMarketIndex
1552
- * @param calculateSwap function to similate in to out swa
1553
- * @param iterationLimit how long to run appromixation before erroring out
1980
+ * @param calculateSwap Optional function to simulate the in-to-out conversion (e.g. to model swap fees/slippage); defaults to a 1:1 oracle-price conversion.
1981
+ * @param iterationLimit How many binary-search iterations to run before erroring out. Defaults to 1000.
1982
+ * @returns `inAmount`/`outAmount` in each market's own token decimals, and the resulting `leverage` (TEN_THOUSAND, 1e4 precision) after the swap.
1554
1983
  */
1555
1984
  getMaxSwapAmount({ inMarketIndex, outMarketIndex, calculateSwap, iterationLimit = 1000, }) {
1556
1985
  const inMarket = this.velocityClient.getSpotMarketAccountOrThrow(inMarketIndex);
@@ -1654,6 +2083,13 @@ class User {
1654
2083
  });
1655
2084
  return { inAmount: inSwap, outAmount: outSwap, leverage };
1656
2085
  }
2086
+ /**
2087
+ * Returns a cloned `SpotPosition` with `tokenAmount` (signed, positive =
2088
+ * deposit / negative = borrow) applied on top of the existing balance —
2089
+ * used to simulate the post-trade/post-swap position without mutating the
2090
+ * cached account.
2091
+ * @param tokenAmount Signed delta in `market`'s own token decimals.
2092
+ */
1657
2093
  cloneAndUpdateSpotPosition(position, tokenAmount, market) {
1658
2094
  const clonedPosition = Object.assign({}, position);
1659
2095
  if (tokenAmount.eq(numericConstants_1.ZERO)) {
@@ -1680,12 +2116,14 @@ class User {
1680
2116
  }
1681
2117
  return clonedPosition;
1682
2118
  }
2119
+ /** Worst-case free-collateral contribution (under `'Initial'` margin) of a single spot position. Returns QUOTE_PRECISION (1e6). */
1683
2120
  calculateSpotPositionFreeCollateralContribution(spotPosition, strictOraclePrice) {
1684
2121
  const marginCategory = 'Initial';
1685
2122
  const spotMarketAccount = this.velocityClient.getSpotMarketAccountOrThrow(spotPosition.marketIndex);
1686
2123
  const { freeCollateralContribution } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, strictOraclePrice, marginCategory, this.getUserAccountOrThrow().maxMarginRatio);
1687
2124
  return freeCollateralContribution;
1688
2125
  }
2126
+ /** Worst-case (under `'Initial'` margin) asset/liability value split of a single spot position, for use in leverage calculations. Both fields QUOTE_PRECISION (1e6), non-negative. */
1689
2127
  calculateSpotPositionLeverageContribution(spotPosition, strictOraclePrice) {
1690
2128
  let totalAssetValue = numericConstants_1.ZERO;
1691
2129
  let totalLiabilityValue = numericConstants_1.ZERO;
@@ -1710,10 +2148,11 @@ class User {
1710
2148
  }
1711
2149
  /**
1712
2150
  * Estimates what the user leverage will be after swap
1713
- * @param inMarketIndex
1714
- * @param outMarketIndex
1715
- * @param inAmount
1716
- * @param outAmount
2151
+ * @param inMarketIndex Market being sold/paid from.
2152
+ * @param outMarketIndex Market being bought/received.
2153
+ * @param inAmount Amount removed from `inMarketIndex`, that market's own token decimals.
2154
+ * @param outAmount Amount added to `outMarketIndex`, that market's own token decimals.
2155
+ * @returns Precision TEN_THOUSAND (1e4, i.e. `10000` = 1x).
1717
2156
  */
1718
2157
  accountLeverageAfterSwap({ inMarketIndex, outMarketIndex, inAmount, outAmount, }) {
1719
2158
  const inMarket = this.velocityClient.getSpotMarketAccountOrThrow(inMarketIndex);
@@ -1756,11 +2195,11 @@ class User {
1756
2195
  /**
1757
2196
  * Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
1758
2197
  * @param targetMarketIndex
1759
- * @param: targetMarketType
1760
- * @param tradeQuoteAmount
1761
- * @param tradeSide
1762
- * @param includeOpenOrders
1763
- * @returns leverageRatio : Precision TEN_THOUSAND
2198
+ * @param targetMarketType Whether the trade is on a perp or spot market — the two use different valuation paths.
2199
+ * @param tradeQuoteAmount Quote size of the simulated trade, QUOTE_PRECISION (1e6).
2200
+ * @param tradeSide Direction of the simulated trade.
2201
+ * @param includeOpenOrders Include existing open orders' worst-case impact in both the before/after values. Defaults to true.
2202
+ * @returns leverageRatio : Precision TEN_THOUSAND (1e4, i.e. `10000` = 1x)
1764
2203
  */
1765
2204
  accountLeverageRatioAfterTrade(targetMarketIndex, targetMarketType, tradeQuoteAmount, tradeSide, includeOpenOrders = true) {
1766
2205
  const tradeIsPerp = (0, types_1.isVariant)(targetMarketType, 'perp');
@@ -1837,6 +2276,19 @@ class User {
1837
2276
  .div(netAssetValue);
1838
2277
  return newLeverage;
1839
2278
  }
2279
+ /**
2280
+ * Looks up the user's fee tier from the state account's fee structure.
2281
+ *
2282
+ * For perp markets, the tier is selected by the user's rolling 30-day
2283
+ * volume (`getUser30dRollingVolumeEstimate`, QUOTE_PRECISION) against fixed
2284
+ * breakpoints — $2M, $10M, $20M, $80M, $200M — picking the lowest-index
2285
+ * tier whose breakpoint the user's volume is still under (tier 5, the
2286
+ * lowest fees, if volume meets or exceeds the top breakpoint). Spot markets
2287
+ * always use tier 0 (no volume-based discount).
2288
+ * @param marketType `MarketType.PERP` or `MarketType.SPOT`.
2289
+ * @param now Optional unix timestamp (seconds) to evaluate the rolling volume window as of; defaults to current time.
2290
+ * @returns The matching `FeeTier` (numerator/denominator fee fractions and referee-discount fractions).
2291
+ */
1840
2292
  getUserFeeTier(marketType, now) {
1841
2293
  const state = this.velocityClient.getStateAccount();
1842
2294
  if ((0, types_1.isVariant)(marketType, 'perp')) {
@@ -1863,28 +2315,64 @@ class User {
1863
2315
  return state.spotFeeStructure.feeTiers[0];
1864
2316
  }
1865
2317
  /**
1866
- * Calculates how much perp fee will be taken for a given sized trade
1867
- * @param quoteAmount
1868
- * @returns feeForQuote : Precision QUOTE_PRECISION
2318
+ * Calculates how much perp fee will be taken for a given sized trade.
2319
+ *
2320
+ * When `marketIndex` is provided, delegates to `VelocityClient.getMarketFees`
2321
+ * for that specific market's taker-fee multiplier (which itself applies the
2322
+ * market's `feeAdjustment`, the referee discount, and — when `builderInfo` is
2323
+ * passed — the builder fee). Otherwise uses the volume-based fee tier from
2324
+ * `getUserFeeTier(MarketType.PERP)`; if the user is a referee (determined
2325
+ * from `UserStats.referrerStatus`'s `IsReferred` flag unless `isReferee` is
2326
+ * explicitly passed), the tier's `refereeFeeNumerator`/`refereeFeeDenominator`
2327
+ * proportion is subtracted from the fee as a discount, and — when `builderInfo`
2328
+ * carries a builder code — the builder fee (`quoteAmount * builderFeeTenthBps /
2329
+ * 100_000`) is added on top, mirroring the program's `builder_fee` (`math/fees.rs`).
2330
+ * @param quoteAmount Trade size, QUOTE_PRECISION (1e6).
2331
+ * @param marketIndex Optional perp market to use `VelocityClient.getMarketFees` for instead of the volume-tier fee structure.
2332
+ * @param isReferee Optional override for whether the referee discount applies; defaults to the user's actual `UserStats` referred status. Ignored on the `marketIndex` path (which reads referee status inside `getMarketFees`).
2333
+ * @param builderInfo Optional builder code; when it carries `builderIdx` + `builderFeeTenthBps`, the builder fee is added on top of the tiered fee.
2334
+ * @returns feeForQuote : Precision QUOTE_PRECISION (1e6)
1869
2335
  */
1870
- calculateFeeForQuoteAmount(quoteAmount, marketIndex) {
2336
+ calculatePerpTakerFee(quoteAmount, marketIndex, isReferee, builderInfo) {
1871
2337
  if (marketIndex !== undefined) {
1872
- const takerFeeMultiplier = this.velocityClient.getMarketFees(types_2.MarketType.PERP, marketIndex, this).takerFee;
2338
+ const takerFeeMultiplier = this.velocityClient.getMarketFees(types_2.MarketType.PERP, marketIndex, this, builderInfo).takerFee;
1873
2339
  const feeAmountNum = bigNum_1.BigNum.from(quoteAmount, numericConstants_1.QUOTE_PRECISION_EXP).toNum() *
1874
2340
  takerFeeMultiplier;
1875
2341
  return bigNum_1.BigNum.fromPrint(feeAmountNum.toString(), numericConstants_1.QUOTE_PRECISION_EXP).val;
1876
2342
  }
1877
2343
  else {
1878
2344
  const feeTier = this.getUserFeeTier(types_2.MarketType.PERP);
1879
- return quoteAmount
1880
- .mul(new anchor_1.BN(feeTier.feeNumerator))
1881
- .div(new anchor_1.BN(feeTier.feeDenominator));
2345
+ let fee = (0, utils_2.divCeil)(quoteAmount.mul(new anchor_1.BN(feeTier.feeNumerator)), new anchor_1.BN(feeTier.feeDenominator));
2346
+ const isUserReferee = isReferee !== null && isReferee !== void 0 ? isReferee : (this.velocityClient.getUserStatsOrThrow().getAccountOrThrow()
2347
+ .referrerStatus &
2348
+ types_1.ReferrerStatus.IsReferred) >
2349
+ 0;
2350
+ if (isUserReferee) {
2351
+ const refereeDiscount = getProportion128(fee, new anchor_1.BN(feeTier.refereeFeeNumerator), new anchor_1.BN(feeTier.refereeFeeDenominator));
2352
+ fee = fee.sub(refereeDiscount);
2353
+ }
2354
+ // Builder fee (M12): charged on top of the tiered fee, on the raw quote
2355
+ // (independent of the referee discount), mirroring `builder_fee` in `math/fees.rs`.
2356
+ if (builderInfo && (0, builder_1.hasBuilderParams)(builderInfo)) {
2357
+ fee = fee.add((0, builder_1.calculateBuilderFee)(quoteAmount, builderInfo.builderFeeTenthBps));
2358
+ }
2359
+ return fee;
1882
2360
  }
1883
2361
  }
1884
2362
  /**
1885
2363
  * Calculates a user's max withdrawal amounts for a spot market. If reduceOnly is true,
1886
- * it will return the max withdrawal amount without opening a liability for the user
2364
+ * it will return the max withdrawal amount without opening a liability for the user.
2365
+ *
2366
+ * Combines three caps: the market-wide withdraw/borrow guard
2367
+ * (`calculateWithdrawLimit`, a rolling-window rate limit on the spot
2368
+ * market), the user's own deposit balance, and how much their free
2369
+ * collateral supports withdrawing/borrowing. If `canBypassWithdrawLimits`
2370
+ * returns `canBypass: true` (see that method), the market-wide withdraw
2371
+ * limit floor is raised to the user's full deposit amount — letting a
2372
+ * small, healthy, always-net-positive depositor withdraw in full even if
2373
+ * the market-wide guard would otherwise throttle them.
1887
2374
  * @param marketIndex
2375
+ * @param reduceOnly If true, caps the result so the withdrawal cannot open a borrow (never exceeds the user's current deposit). If false/omitted, may return an amount larger than the deposit, up to the user's max allowed new liability.
1888
2376
  * @returns withdrawalLimit : Precision is the token precision for the chosen SpotMarket
1889
2377
  */
1890
2378
  getWithdrawalLimit(marketIndex, reduceOnly) {
@@ -1892,7 +2380,16 @@ class User {
1892
2380
  const spotMarket = this.velocityClient.getSpotMarketAccountOrThrow(marketIndex);
1893
2381
  // eslint-disable-next-line prefer-const
1894
2382
  let { borrowLimit, withdrawLimit } = (0, spotBalance_2.calculateWithdrawLimit)(spotMarket, nowTs);
1895
- const freeCollateral = this.getFreeCollateral();
2383
+ // the withdraw path enforces the equity floor on post-withdraw total
2384
+ // collateral, so equity above the floor caps free collateral here
2385
+ const equityAboveFloor = this.getEquityAboveFloor(true);
2386
+ if (equityAboveFloor !== null && equityAboveFloor.eq(numericConstants_1.ZERO)) {
2387
+ return numericConstants_1.ZERO;
2388
+ }
2389
+ let freeCollateral = this.getFreeCollateral();
2390
+ if (equityAboveFloor !== null) {
2391
+ freeCollateral = anchor_1.BN.min(freeCollateral, equityAboveFloor);
2392
+ }
1896
2393
  const initialMarginRequirement = this.getInitialMarginRequirement();
1897
2394
  const oracleData = this.getOracleDataForSpotMarket(marketIndex);
1898
2395
  const { numeratorScale, denominatorScale } = spotMarket.decimals > 6
@@ -1941,6 +2438,24 @@ class User {
1941
2438
  return anchor_1.BN.max(maxBorrowValue, numericConstants_1.ZERO);
1942
2439
  }
1943
2440
  }
2441
+ /**
2442
+ * Determines whether the user can bypass the spot market's rolling
2443
+ * withdraw-guard limit for `marketIndex`. `canBypass` is true only when
2444
+ * **all** of the following hold:
2445
+ * - The user currently holds a deposit (not a borrow) in the market.
2446
+ * - Their lifetime net deposits (`totalDeposits - totalWithdraws`) are
2447
+ * non-negative — they have never net-withdrawn more than they net-deposited.
2448
+ * - Their `cumulativeDeposits` for the position has never gone negative
2449
+ * (no history of having borrowed and repaid in this market).
2450
+ * - Their current deposit amount is below `maxDepositAmount`, i.e. 10% of
2451
+ * the spot market's `withdrawGuardThreshold`.
2452
+ *
2453
+ * This lets a small, well-behaved depositor withdraw their own funds in
2454
+ * full even while the market-wide withdraw guard is actively throttling
2455
+ * larger movements. Used by `getWithdrawalLimit`.
2456
+ * @param marketIndex
2457
+ * @returns `canBypass`; `netDeposits` (lifetime `totalDeposits - totalWithdraws`, QUOTE_PRECISION, 1e6); `depositAmount` and `maxDepositAmount`, both in the spot market's own token decimals.
2458
+ */
1944
2459
  canBypassWithdrawLimits(marketIndex) {
1945
2460
  const spotMarket = this.velocityClient.getSpotMarketAccountOrThrow(marketIndex);
1946
2461
  const maxDepositAmount = spotMarket.withdrawGuardThreshold.div(new anchor_1.BN(10));
@@ -1971,6 +2486,14 @@ class User {
1971
2486
  netDeposits,
1972
2487
  };
1973
2488
  }
2489
+ if (position.cumulativeDeposits.lt(numericConstants_1.ZERO)) {
2490
+ return {
2491
+ canBypass: false,
2492
+ maxDepositAmount,
2493
+ depositAmount,
2494
+ netDeposits,
2495
+ };
2496
+ }
1974
2497
  return {
1975
2498
  canBypass: depositAmount.lt(maxDepositAmount),
1976
2499
  maxDepositAmount,
@@ -1978,6 +2501,15 @@ class User {
1978
2501
  depositAmount,
1979
2502
  };
1980
2503
  }
2504
+ /**
2505
+ * Determines whether the user can be marked idle (excluded from userMap
2506
+ * subscriptions by default, and skipped by most keeper crank passes) as of
2507
+ * `slot`. Requires: not already idle; inactive for the required window
2508
+ * since `lastActiveSlot` (1 hour / 9,000 slots if equity is under $1,000,
2509
+ * otherwise 1 week / 1,512,000 slots); not currently being liquidated; and
2510
+ * no open perp positions, borrows, spot open orders, or open orders of any kind.
2511
+ * @param slot Current slot to evaluate inactivity against.
2512
+ */
1981
2513
  canMakeIdle(slot) {
1982
2514
  const userAccount = this.getUserAccountOrThrow();
1983
2515
  if (userAccount.idle) {
@@ -2021,6 +2553,20 @@ class User {
2021
2553
  }
2022
2554
  return true;
2023
2555
  }
2556
+ /**
2557
+ * Determines whether this `User` (sub)account can be deleted (checked
2558
+ * before sending a delete-user instruction, to give a friendlier error than
2559
+ * an on-chain revert). Returns `canDelete: false` with a `reason` string if
2560
+ * any of the following hold: it's a referrer's sub-account 0 (referrers
2561
+ * cannot delete their primary account); the account is bankrupt or being
2562
+ * liquidated; it has any non-empty perp/spot position or open order; or
2563
+ * (when the state account charges an initialize-user fee) the account is a
2564
+ * "fresh" account — younger than `ACCOUNT_AGE_DELETION_CUTOFF_SECONDS`,
2565
+ * measured from its earliest recorded filler/maker/taker volume timestamp —
2566
+ * that is not currently idle.
2567
+ * @param userStatsAccount Optional pre-fetched `UserStatsAccount`; defaults to `VelocityClient.getUserStatsOrThrow().getAccount()`.
2568
+ * @param now Optional unix timestamp (seconds) to evaluate account age against; defaults to current time.
2569
+ */
2024
2570
  canBeDeleted(userStatsAccount, now) {
2025
2571
  const userAccount = this.getUserAccountOrThrow();
2026
2572
  const userStatsAccountToUse = userStatsAccount !== null && userStatsAccount !== void 0 ? userStatsAccount : this.velocityClient.getUserStatsOrThrow().getAccount();
@@ -2071,6 +2617,17 @@ class User {
2071
2617
  }
2072
2618
  return { canDelete: true };
2073
2619
  }
2620
+ /**
2621
+ * Returns the numerically-lowest (i.e. safest) contract/asset tier across
2622
+ * the user's active positions — perp tiers from active perp positions,
2623
+ * spot tiers only from spot **borrows** (deposits are skipped, since asset
2624
+ * tier only restricts borrowing exposure). Defaults to `4` (the
2625
+ * second-riskiest tier index) when the user has no positions of that kind —
2626
+ * this is a permissive default intended for callers doing tier-safety
2627
+ * comparisons (see `perpTierIsAsSafeAs` in `math/tiers`), not a claim that
2628
+ * "no position" is itself a risky tier.
2629
+ * @returns Lower `perpTier`/`spotTier` numbers indicate a safer tier; see `math/tiers` (`getPerpMarketTierNumber`/`getSpotMarketTierNumber`) for the numbering.
2630
+ */
2074
2631
  getSafestTiers() {
2075
2632
  let safestPerpTier = 4;
2076
2633
  let safestSpotTier = 4;
@@ -2088,6 +2645,21 @@ class User {
2088
2645
  spotTier: safestSpotTier,
2089
2646
  };
2090
2647
  }
2648
+ /**
2649
+ * Breaks down a single perp position's contribution to the margin system
2650
+ * as a `HealthComponent`: worst-case base size, its unweighted liability
2651
+ * value, the applicable margin ratio (`weight`), and the resulting
2652
+ * weighted margin requirement (`weightedValue`, which includes the
2653
+ * position's open-order margin add-on). Used to build up
2654
+ * `getHealthComponents`' `perpPositions` array (e.g. for UI breakdowns of
2655
+ * "what's consuming my margin").
2656
+ * @param marginCategory `'Initial'` or `'Maintenance'`.
2657
+ * @param perpPosition Position to evaluate.
2658
+ * @param oraclePriceData Optional oracle price override for the perp market; defaults to the live oracle price.
2659
+ * @param quoteOraclePriceData Optional oracle price override for the quote spot market; defaults to the live oracle price.
2660
+ * @param includeOpenOrders Include worst-case open-order exposure. Defaults to true.
2661
+ * @returns `size` is BASE_PRECISION (1e9); `value`/`weightedValue` are QUOTE_PRECISION (1e6); `weight` is MARGIN_PRECISION (1e4).
2662
+ */
2091
2663
  getPerpPositionHealth({ marginCategory, perpPosition, oraclePriceData, quoteOraclePriceData, includeOpenOrders = true, }) {
2092
2664
  const perpMarket = this.velocityClient.getPerpMarketAccountOrThrow(perpPosition.marketIndex);
2093
2665
  const _oraclePriceData = oraclePriceData ||
@@ -2122,6 +2694,18 @@ class User {
2122
2694
  weightedValue: marginRequirement,
2123
2695
  };
2124
2696
  }
2697
+ /**
2698
+ * Builds a full breakdown of every component feeding into the user's
2699
+ * margin calculation, for UI/diagnostic display: `deposits` and `borrows`
2700
+ * (one `HealthComponent` per non-quote spot market with a nonzero
2701
+ * worst-case position, plus a synthetic entry for the net quote balance),
2702
+ * `perpPositions` (via `getPerpPositionHealth`, one per active perp
2703
+ * position), and `perpPnl` (each position's weighted unrealized PnL — see
2704
+ * `getUnrealizedPNL` for the `'Initial'`-margin $100 cap that also applies
2705
+ * here).
2706
+ * @param marginCategory `'Initial'` or `'Maintenance'` — determines which asset/liability weights are applied.
2707
+ * @returns `HealthComponents` with `size`/`value`/`weightedValue` in each entry using the same precisions as `getPerpPositionHealth`.
2708
+ */
2125
2709
  getHealthComponents({ marginCategory, }) {
2126
2710
  const healthComponents = {
2127
2711
  deposits: [],
@@ -2246,6 +2830,7 @@ class User {
2246
2830
  }
2247
2831
  /**
2248
2832
  * Get the active perp and spot positions of the user.
2833
+ * @returns Market indices only (not full position objects); see `getActivePerpPositions`/`getActiveSpotPositions` for the "active" criteria.
2249
2834
  */
2250
2835
  getActivePositions() {
2251
2836
  const activePerpMarkets = this.getActivePerpPositions().map((position) => position.marketIndex);
@@ -2259,9 +2844,28 @@ class User {
2259
2844
  * Compute the full margin calculation for the user's account.
2260
2845
  * Prioritize using this function instead of calling getMarginRequirement or getTotalCollateral multiple times.
2261
2846
  * Consumers can use this to avoid duplicating work across separate calls.
2847
+ *
2848
+ * Mirrors the on-chain margin accumulation in `math/margin.rs`, splitting
2849
+ * contributions into cross-margin and per-market isolated buckets
2850
+ * (`MarginCalculation.isolatedMarginCalculations`, keyed by perp market
2851
+ * index — see `isPerpPositionIsolated`) and tracking whether the account
2852
+ * holds any isolated-tier liability (`withPerpIsolatedLiability` /
2853
+ * `withSpotIsolatedLiability`, consumed by
2854
+ * `validateAnyIsolatedTierRequirements`). A perp position's isolated
2855
+ * quote-deposit collateral only counts toward that position's own isolated
2856
+ * bucket, never the cross-margin total.
2857
+ *
2858
+ * Also enforces pool-id consistency: every spot/perp position's market must
2859
+ * match the user's `poolId`, **except** a pool-1 user is allowed to hold a
2860
+ * quote-asset deposit (not borrow) even though the quote spot market itself
2861
+ * belongs to pool 0 — throws `InvalidPoolId: ...` otherwise.
2862
+ * @param marginCategory `'Initial'` or `'Maintenance'`. Defaults to `'Initial'`.
2863
+ * @param opts.strict Apply TWAP-bounded (`StrictOraclePrice`) oracle pricing, mirroring the on-chain strict-price gating. Defaults to false.
2864
+ * @param opts.includeOpenOrders Include open orders' worst-case impact. Defaults to true.
2865
+ * @param opts.liquidationBufferMap Per-scope buffer (MARGIN_PRECISION, 1e4) to pad margin requirements with — `'cross'` for the cross-margin bucket, or a perp market index for that market's isolated bucket. See `getLiquidationBuffer`.
2262
2866
  */
2263
2867
  getMarginCalculation(marginCategory = 'Initial', opts) {
2264
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2868
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2265
2869
  const strict = (_a = opts === null || opts === void 0 ? void 0 : opts.strict) !== null && _a !== void 0 ? _a : false;
2266
2870
  const liquidationBufferMap = (_b = opts === null || opts === void 0 ? void 0 : opts.liquidationBufferMap) !== null && _b !== void 0 ? _b : new Map();
2267
2871
  const includeOpenOrders = (_c = opts === null || opts === void 0 ? void 0 : opts.includeOpenOrders) !== null && _c !== void 0 ? _c : true;
@@ -2281,12 +2885,29 @@ class User {
2281
2885
  .setCrossMarginBuffer((_f = (_e = opts === null || opts === void 0 ? void 0 : opts.liquidationBufferMap) === null || _e === void 0 ? void 0 : _e.get('cross')) !== null && _f !== void 0 ? _f : numericConstants_1.ZERO)
2282
2886
  .setIsolatedMarginBuffers(isolatedMarginBuffers);
2283
2887
  const calc = new marginCalculation_1.MarginCalculation(ctx);
2888
+ const userPoolId = this.getUserAccountOrThrow().poolId;
2284
2889
  // SPOT POSITIONS
2285
2890
  for (const spotPosition of this.getUserAccountOrThrow().spotPositions) {
2286
2891
  if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition))
2287
2892
  continue;
2288
2893
  const isQuote = spotPosition.marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX;
2894
+ const isBorrow = (0, types_1.isVariant)(spotPosition.balanceType, 'borrow');
2289
2895
  const spotMarket = this.velocityClient.getSpotMarketAccountOrThrow(spotPosition.marketIndex);
2896
+ // the pool-1/quote-deposit carve-out lets a pool-1 user *hold* a quote
2897
+ // deposit without matching the quote market's own pool id (no
2898
+ // InvalidPoolId throw); every other combination requires an exact pool
2899
+ // match. Note the deposit still contributes ZERO collateral in this case
2900
+ // (skipTokenValue below) — this faithfully mirrors margin.rs:319-321,
2901
+ // which sets token_value = 0 before add_cross_margin_total_collateral.
2902
+ let skipTokenValue = false;
2903
+ if (!(userPoolId === 1 && isQuote && !isBorrow)) {
2904
+ if (userPoolId !== spotMarket.poolId) {
2905
+ throw new Error(`InvalidPoolId: user pool id (${userPoolId}) does not match spot market pool id (${spotMarket.poolId}) for market index ${spotMarket.marketIndex}`);
2906
+ }
2907
+ }
2908
+ else {
2909
+ skipTokenValue = true;
2910
+ }
2290
2911
  const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
2291
2912
  const twap5 = strict
2292
2913
  ? (0, oracles_1.calculateLiveOracleTwap)(spotMarket.historicalOracleData, oraclePriceData, new anchor_1.BN(Math.floor(Date.now() / 1000)), numericConstants_1.FIVE_MINUTE)
@@ -2294,15 +2915,20 @@ class User {
2294
2915
  const strictOracle = new strictOraclePrice_1.StrictOraclePrice(oraclePriceData.price, twap5);
2295
2916
  if (isQuote) {
2296
2917
  const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
2918
+ // mirrors margin.rs's `market_index == 0` block: the quote market uses the
2919
+ // raw strict token value on both sides — no asset/liability weight, and the
2920
+ // cross-margin buffer is applied inside addCrossMarginRequirement (from
2921
+ // context.crossMarginBuffer), not folded into the value here
2922
+ const tokenValue = (0, spotBalance_1.getStrictTokenValue)(tokenAmount, spotMarket.decimals, strictOracle);
2297
2923
  if ((0, types_1.isVariant)(spotPosition.balanceType, 'deposit')) {
2298
2924
  // add deposit value to total collateral
2299
- const weightedTokenValue = this.getSpotAssetValue(tokenAmount, strictOracle, spotMarket, marginCategory);
2300
- calc.addCrossMarginTotalCollateral(weightedTokenValue);
2925
+ calc.addCrossMarginTotalCollateral(skipTokenValue ? numericConstants_1.ZERO : tokenValue);
2301
2926
  }
2302
2927
  else {
2303
2928
  // borrow on quote contributes to margin requirement
2304
- const tokenValueAbs = this.getSpotLiabilityValue(tokenAmount, strictOracle, spotMarket, marginCategory, (_g = liquidationBufferMap.get('cross')) !== null && _g !== void 0 ? _g : new anchor_1.BN(0)).abs();
2929
+ const tokenValueAbs = tokenValue.abs();
2305
2930
  calc.addCrossMarginRequirement(tokenValueAbs, tokenValueAbs);
2931
+ calc.addSpotLiability();
2306
2932
  }
2307
2933
  continue;
2308
2934
  }
@@ -2314,6 +2940,7 @@ class User {
2314
2940
  // open order IM
2315
2941
  calc.addCrossMarginRequirement(new anchor_1.BN(spotPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT), numericConstants_1.ZERO);
2316
2942
  }
2943
+ const isIsolatedSpotTier = (0, types_1.isVariant)(spotMarket.assetTier, 'isolated');
2317
2944
  if (worstCaseTokenAmount.gt(numericConstants_1.ZERO)) {
2318
2945
  const baseAssetValue = this.getSpotAssetValue(worstCaseTokenAmount, strictOracle, spotMarket, marginCategory);
2319
2946
  // asset side increases total collateral (weighted)
@@ -2323,6 +2950,14 @@ class User {
2323
2950
  // liability side increases margin requirement (weighted >= abs(token_value))
2324
2951
  const getSpotLiabilityValue = this.getSpotLiabilityValue(worstCaseTokenAmount, strictOracle, spotMarket, marginCategory, liquidationBufferMap.get('cross'));
2325
2952
  calc.addCrossMarginRequirement(getSpotLiabilityValue.abs(), getSpotLiabilityValue.abs());
2953
+ calc.addSpotLiability();
2954
+ calc.updateWithSpotIsolatedLiability(isIsolatedSpotTier);
2955
+ }
2956
+ else if (spotPosition.openOrders !== 0 ||
2957
+ !spotPosition.openBids.isZero() ||
2958
+ !spotPosition.openAsks.isZero()) {
2959
+ calc.addSpotLiability();
2960
+ calc.updateWithSpotIsolatedLiability(isIsolatedSpotTier);
2326
2961
  }
2327
2962
  // orders value contributes to collateral or requirement
2328
2963
  if (worstCaseOrdersValue.gt(numericConstants_1.ZERO)) {
@@ -2336,6 +2971,9 @@ class User {
2336
2971
  // PERP POSITIONS
2337
2972
  for (const marketPosition of this.getActivePerpPositions()) {
2338
2973
  const market = this.velocityClient.getPerpMarketAccountOrThrow(marketPosition.marketIndex);
2974
+ if (userPoolId !== market.poolId) {
2975
+ throw new Error(`InvalidPoolId: user pool id (${userPoolId}) does not match perp market pool id (${market.poolId}) for market index ${market.marketIndex}`);
2976
+ }
2339
2977
  const quoteSpotMarket = this.velocityClient.getSpotMarketAccountOrThrow(market.quoteSpotMarketIndex);
2340
2978
  const quoteOraclePriceData = this.getOracleDataForSpotMarket(market.quoteSpotMarketIndex);
2341
2979
  const oraclePriceData = this.getMMOracleDataForPerpMarket(market.marketIndex);
@@ -2348,13 +2986,15 @@ class User {
2348
2986
  if ((0, types_1.isVariant)(market.status, 'settlement')) {
2349
2987
  marginRatio = numericConstants_1.ZERO;
2350
2988
  }
2351
- // convert liability to quote value and apply margin ratio
2989
+ // convert liability to quote value and apply margin ratio; since this is
2990
+ // a liability, use the larger of the twap and current quote price
2352
2991
  const quotePrice = strict
2353
2992
  ? anchor_1.BN.max(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min)
2354
2993
  : quoteOraclePriceData.price;
2355
- let perpMarginRequirement = worstCaseLiabilityValue
2994
+ const worstCaseLiabilityValueQuote = worstCaseLiabilityValue
2356
2995
  .mul(quotePrice)
2357
- .div(numericConstants_1.PRICE_PRECISION)
2996
+ .div(numericConstants_1.PRICE_PRECISION);
2997
+ let perpMarginRequirement = worstCaseLiabilityValueQuote
2358
2998
  .mul(marginRatio)
2359
2999
  .div(numericConstants_1.MARGIN_PRECISION);
2360
3000
  // add open orders IM
@@ -2383,33 +3023,112 @@ class User {
2383
3023
  .div(new anchor_1.BN(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION));
2384
3024
  }
2385
3025
  }
3026
+ if (marginCategory === 'Initial') {
3027
+ // safety guard for dangerously configured perp market
3028
+ positionUnrealizedPnl = anchor_1.BN.min(positionUnrealizedPnl, numericConstants_1.MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN);
3029
+ }
3030
+ const hasPerpLiability = !marketPosition.baseAssetAmount.isZero() ||
3031
+ marketPosition.quoteAssetAmount.isNeg() ||
3032
+ marketPosition.openOrders !== 0 ||
3033
+ !marketPosition.openBids.isZero() ||
3034
+ !marketPosition.openAsks.isZero();
3035
+ if (hasPerpLiability) {
3036
+ calc.addPerpLiability();
3037
+ calc.updateWithPerpIsolatedLiability((0, types_1.isVariant)(market.contractTier, 'isolated'));
3038
+ }
2386
3039
  // Add perp contribution: isolated vs cross
2387
3040
  const isIsolated = this.isPerpPositionIsolated(marketPosition);
2388
3041
  if (isIsolated) {
2389
3042
  // derive isolated quote deposit value, mirroring on-chain logic
2390
3043
  let depositValue = numericConstants_1.ZERO;
2391
- if ((_h = marketPosition.isolatedPositionScaledBalance) === null || _h === void 0 ? void 0 : _h.gt(numericConstants_1.ZERO)) {
3044
+ if ((_g = marketPosition.isolatedPositionScaledBalance) === null || _g === void 0 ? void 0 : _g.gt(numericConstants_1.ZERO)) {
2392
3045
  const quoteSpotMarket = this.velocityClient.getSpotMarketAccountOrThrow(market.quoteSpotMarketIndex);
2393
3046
  const quoteOraclePriceData = this.getOracleDataForSpotMarket(market.quoteSpotMarketIndex);
2394
3047
  const strictQuote = new strictOraclePrice_1.StrictOraclePrice(quoteOraclePriceData.price, strict
2395
3048
  ? quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min
2396
3049
  : undefined);
2397
- const quoteTokenAmount = (0, spotBalance_2.getTokenAmount)((_j = marketPosition.isolatedPositionScaledBalance) !== null && _j !== void 0 ? _j : numericConstants_1.ZERO, quoteSpotMarket, types_2.SpotBalanceType.DEPOSIT);
3050
+ const quoteTokenAmount = (0, spotBalance_2.getTokenAmount)((_h = marketPosition.isolatedPositionScaledBalance) !== null && _h !== void 0 ? _h : numericConstants_1.ZERO, quoteSpotMarket, types_2.SpotBalanceType.DEPOSIT);
2398
3051
  depositValue = (0, spotBalance_1.getStrictTokenValue)(quoteTokenAmount, quoteSpotMarket.decimals, strictQuote);
2399
3052
  }
2400
- calc.addIsolatedMarginCalculation(market.marketIndex, depositValue, positionUnrealizedPnl, worstCaseLiabilityValue, perpMarginRequirement);
2401
- calc.addPerpLiabilityValue(worstCaseLiabilityValue);
3053
+ calc.addIsolatedMarginCalculation(market.marketIndex, depositValue, positionUnrealizedPnl, worstCaseLiabilityValueQuote, perpMarginRequirement);
2402
3054
  }
2403
3055
  else {
2404
3056
  // cross: add to global requirement and collateral
2405
- calc.addCrossMarginRequirement(perpMarginRequirement, worstCaseLiabilityValue);
3057
+ calc.addCrossMarginRequirement(perpMarginRequirement, worstCaseLiabilityValueQuote);
2406
3058
  calc.addCrossMarginTotalCollateral(positionUnrealizedPnl);
2407
3059
  }
3060
+ // mirrors margin.rs:616-617 — perp liability value accumulates for every
3061
+ // position regardless of the isolated/cross split, so it must run outside
3062
+ // the branch above (previously only the isolated branch accumulated it,
3063
+ // underreporting totalPerpLiabilityValue for cross positions)
3064
+ calc.addPerpLiabilityValue(worstCaseLiabilityValueQuote);
2408
3065
  }
2409
3066
  return calc;
2410
3067
  }
3068
+ /**
3069
+ * Returns true if `perpPosition` was opened/is held under isolated margin
3070
+ * (`PositionFlag.IsolatedPosition` set) — segregated to its own margin
3071
+ * bucket (see `getMarginCalculation`) rather than sharing cross-margin
3072
+ * collateral with the rest of the account.
3073
+ */
2411
3074
  isPerpPositionIsolated(perpPosition) {
2412
3075
  return (perpPosition.positionFlag & types_2.PositionFlag.IsolatedPosition) !== 0;
2413
3076
  }
3077
+ /**
3078
+ * Pre-flight check for `IsolatedAssetTierViolation`: mirrors
3079
+ * `validate_any_isolated_tier_requirements` in `math/margin.rs`. A user
3080
+ * holding an isolated-tier perp or spot liability may not simultaneously
3081
+ * carry other liabilities (besides a single usdc borrow, for a perp
3082
+ * isolated liability), unless they are reduce-only.
3083
+ *
3084
+ * Specifically, if `calculation.withPerpIsolatedLiability` is set (an
3085
+ * isolated-*contract-tier* perp liability exists) and the user is not
3086
+ * `UserStatus.REDUCE_ONLY`: more than one perp liability is invalid; margin
3087
+ * trading enabled is invalid; and any spot liability other than a single
3088
+ * USDC borrow is invalid. If `calculation.withSpotIsolatedLiability` is set
3089
+ * (an isolated-*asset-tier* spot liability exists) and not reduce-only: any
3090
+ * perp liability, or more than the one isolated-tier spot liability, is invalid.
3091
+ * @param calculation A `MarginCalculation` from `getMarginCalculation` (any margin category — only the isolated-liability flags and liability counts are read).
3092
+ * @returns `{ valid: true }` if the account satisfies isolated-tier requirements, else `{ valid: false, reason }` with a human-readable reason.
3093
+ */
3094
+ validateAnyIsolatedTierRequirements(calculation) {
3095
+ const userAccount = this.getUserAccountOrThrow();
3096
+ const isReduceOnly = this.hasStatus(types_1.UserStatus.REDUCE_ONLY);
3097
+ if (calculation.withPerpIsolatedLiability && !isReduceOnly) {
3098
+ if (calculation.numPerpLiabilities > 1) {
3099
+ return {
3100
+ valid: false,
3101
+ reason: 'User attempting to increase perp liabilities above 1 with a isolated tier liability',
3102
+ };
3103
+ }
3104
+ if (userAccount.isMarginTradingEnabled) {
3105
+ return {
3106
+ valid: false,
3107
+ reason: 'User attempting isolated tier liability with margin trading enabled',
3108
+ };
3109
+ }
3110
+ if (calculation.numSpotLiabilities > 0) {
3111
+ const quoteSpotPosition = this.getSpotPosition(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
3112
+ const quoteIsBorrow = !!quoteSpotPosition &&
3113
+ (0, types_1.isVariant)(quoteSpotPosition.balanceType, 'borrow');
3114
+ if (!(calculation.numSpotLiabilities === 1 && quoteIsBorrow)) {
3115
+ return {
3116
+ valid: false,
3117
+ reason: 'User attempting to increase spot liabilities beyond usdc with a isolated tier liability',
3118
+ };
3119
+ }
3120
+ }
3121
+ }
3122
+ if (calculation.withSpotIsolatedLiability && !isReduceOnly) {
3123
+ if (!(calculation.numPerpLiabilities === 0 &&
3124
+ calculation.numSpotLiabilities === 1)) {
3125
+ return {
3126
+ valid: false,
3127
+ reason: 'User attempting to increase perp liabilities above 0 with a isolated tier liability',
3128
+ };
3129
+ }
3130
+ }
3131
+ return { valid: true };
3132
+ }
2414
3133
  }
2415
3134
  exports.User = User;