@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
@@ -10,8 +10,8 @@
10
10
  * - Manages the program account subscription lifecycle (markets, oracles, user accounts).
11
11
  * - Provides oracle price reads, market config lookups, and PDA derivation helpers.
12
12
  *
13
- * Admin operations (market init, fee updates, oracle config) live in {@link AdminClient} (adminClient.ts).
14
- * Read-only user account queries (margin, positions, PnL) live in {@link User} (user.ts).
13
+ * Admin operations (market init, fee updates, oracle config) live in `AdminClient` (adminClient.ts).
14
+ * Read-only user account queries (margin, positions, PnL) live in `User` (user.ts).
15
15
  *
16
16
  * Instruction → on-chain handler mapping: see ARCHITECTURE.md § SDK↔Instruction Mapping.
17
17
  */
@@ -48,7 +48,22 @@ export type SwapClient = TitanClient | JupiterClient;
48
48
  type RemainingAccountParams = import('./core/remainingAccounts').RemainingAccountParams;
49
49
  /**
50
50
  * # VelocityClient
51
- * This class is the main way to interact with Velocity Exchange. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
51
+ * Main entry point for interacting with Velocity Exchange from TypeScript. A single instance wraps
52
+ * one `authority` wallet (optionally trading on behalf of multiple sub-accounts via
53
+ * `authoritySubAccountMap`, or as a delegate via `includeDelegates`) and owns:
54
+ * - the Anchor `program` handle and RPC `connection`/`provider`,
55
+ * - the account subscription (`accountSubscriber`) that streams State, PerpMarket, SpotMarket,
56
+ * and oracle accounts (websocket, polling, or grpc — selected via `VelocityClientConfig.accountSubscription`),
57
+ * - the set of loaded `User` / `UserStats` objects for this authority's sub-accounts,
58
+ * - the `txSender` / `txHandler` used to build, sign, and send every instruction the class exposes.
59
+ *
60
+ * Most instruction-building methods come in pairs: `doThing(...)` builds the instruction(s), wraps
61
+ * them in a transaction, signs, sends, and confirms; `getDoThingIx(...)` (or `getDoThingIxs(...)`)
62
+ * only builds and returns the raw `TransactionInstruction`(s) for callers composing their own
63
+ * transaction (e.g. bundling several instructions, or using a custom `txParams`/lookup-table setup).
64
+ *
65
+ * Almost every account-touching method requires `subscribe()` to have resolved and the target
66
+ * sub-account's `User` to be loaded first — see `subscribe`, `addUser`, `switchActiveUser`.
52
67
  */
53
68
  export declare class VelocityClient {
54
69
  connection: Connection;
@@ -83,95 +98,307 @@ export declare class VelocityClient {
83
98
  txParams: TxParams;
84
99
  enableMetricsEvents?: boolean;
85
100
  txHandler: TxHandler;
101
+ /**
102
+ * Whether this client has completed `subscribe()` and its underlying `accountSubscriber` is
103
+ * still actively streaming account updates. Most account-reading and instruction-building
104
+ * methods assume this is `true`; call `subscribe()` first if it is `false`.
105
+ */
86
106
  get isSubscribed(): boolean;
87
107
  private getPrePlaceOrderIxs;
108
+ /**
109
+ * Overrides the internal subscribed flag directly, without touching `accountSubscriber`. Intended
110
+ * for advanced/test callers managing subscription state manually; regular callers should use
111
+ * `subscribe()` / `unsubscribe()` instead.
112
+ * @param val - New value for the internal subscribed flag.
113
+ */
88
114
  set isSubscribed(val: boolean);
115
+ /**
116
+ * Constructs a `VelocityClient` from a `VelocityClientConfig`. Does not perform any network I/O —
117
+ * it wires up the Anchor `program`/`provider`, resolves the account-subscription strategy
118
+ * (websocket/polling/grpc), and constructs the `txSender`/`txHandler` used by every instruction
119
+ * method, but does not fetch or subscribe to any accounts. Call `subscribe()` afterwards before
120
+ * using the client.
121
+ *
122
+ * Config interplay of note:
123
+ * - `authority` defaults to `config.wallet.publicKey`; `activeSubAccountId` defaults to `0`.
124
+ * - Exactly one of `includeDelegates`, `subAccountIds`, or `authoritySubAccountMap` may be set —
125
+ * passing more than one throws. `subAccountIds` is shorthand for
126
+ * `authoritySubAccountMap = { [authority]: subAccountIds }`.
127
+ * - `txVersion` defaults based on whether `config.wallet` supports versioned transactions.
128
+ * - `txParams.computeUnits` defaults to `600_000` and `computeUnitsPrice` to `0` (no priority fee)
129
+ * when not provided.
130
+ * - `config.accountSubscription.type` selects `PollingVelocityClientAccountSubscriber`,
131
+ * a grpc subscriber, or (default) `WebSocketVelocityClientAccountSubscriber`.
132
+ * - `config.userStats` (default falsy) additionally constructs a `UserStats` instance for the
133
+ * authority.
134
+ * - `config.marketLookupTables` defaults to the lookup tables from `configs[env]` for the
135
+ * resolved `env` (default `'mainnet-beta'`).
136
+ * @param config - Client configuration; see `VelocityClientConfig` (velocityClientConfig.ts).
137
+ * @throws if more than one of `includeDelegates`/`subAccountIds`/`authoritySubAccountMap` is set.
138
+ */
89
139
  constructor(config: VelocityClientConfig);
140
+ /**
141
+ * Builds the internal `Map` key used to index `this.users` for a given sub-account/authority pair.
142
+ * @param subAccountId - Sub-account id.
143
+ * @param authority - Owning (or delegated) authority public key for the sub-account.
144
+ * @returns A string key of the form `"<subAccountId>_<authority>"`.
145
+ */
90
146
  getUserMapKey(subAccountId: number, authority: PublicKey): string;
147
+ /**
148
+ * Constructs (but does not subscribe) a `User` for the given sub-account/authority.
149
+ * @param subAccountId - Sub-account id to derive the user account PDA for.
150
+ * @param accountSubscriptionConfig - Subscription strategy to use for the new `User`.
151
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
152
+ * @returns An unsubscribed `User` instance.
153
+ */
91
154
  createUser(subAccountId: number, accountSubscriptionConfig: UserSubscriptionConfig, authority?: PublicKey): User;
155
+ /**
156
+ * Subscribes the client to on-chain state: loads and subscribes to the sub-account(s) implied by
157
+ * the constructor/`updateWallet` config (`addAndSubscribeToUsers`), subscribes the `accountSubscriber`
158
+ * (State, PerpMarket, SpotMarket, oracle accounts), and, if `userStats` was configured, subscribes
159
+ * it too. Must be called (and resolve `true`) before using most other methods on this class.
160
+ * @returns `true` if every subscription succeeded; `false` if any failed. Also updates `isSubscribed`.
161
+ */
92
162
  subscribe(): Promise<boolean>;
163
+ /**
164
+ * Subscribes every currently-loaded `User` in `this.users`. Does not add new users or subscribe
165
+ * `accountSubscriber`/`userStats` — see `subscribe()` for full client subscription.
166
+ * @returns One subscribe promise per loaded user, resolving to that user's subscribe success.
167
+ */
93
168
  subscribeUsers(): Promise<boolean>[];
94
169
  /**
95
- * Forces the accountSubscriber to fetch account updates from rpc
170
+ * Forces every loaded `User`, the `accountSubscriber`, and (if present) `userStats` to fetch fresh
171
+ * account data from RPC immediately, bypassing the normal websocket/polling cadence. Useful in
172
+ * tests (e.g. local validator) where a just-landed transaction's effects need to be visible
173
+ * without waiting for the next update.
96
174
  */
97
175
  fetchAccounts(): Promise<void>;
176
+ /**
177
+ * Unsubscribes all loaded users, the `accountSubscriber`, and (if present) `userStats`, and sets
178
+ * `isSubscribed` to `false`. Does not clear `this.users` — the `User` objects remain but stop
179
+ * receiving updates until re-subscribed.
180
+ */
98
181
  unsubscribe(): Promise<void>;
182
+ /**
183
+ * Unsubscribes every currently-loaded `User` in `this.users` without clearing the map or touching
184
+ * `accountSubscriber`/`userStats`.
185
+ * @returns One unsubscribe promise per loaded user.
186
+ */
99
187
  unsubscribeUsers(): Promise<void>[];
100
188
  statePublicKey?: PublicKey;
189
+ /**
190
+ * Returns the `State` account PDA for this program, computing and caching it on first call.
191
+ * @returns The `State` account public key.
192
+ */
101
193
  getStatePublicKey(): Promise<PublicKey>;
102
194
  signerPublicKey?: PublicKey;
195
+ /**
196
+ * Returns the program's PDA signer (used as the authority for vault CPIs), computing and caching
197
+ * it on first call. Synchronous — the signer PDA has no seeds that require an on-chain lookup.
198
+ * @returns The velocity signer public key.
199
+ */
103
200
  getSignerPublicKey(): PublicKey;
201
+ /**
202
+ * Returns the last account-subscriber-cached `State` account. Does not hit RPC.
203
+ * @returns The current `StateAccount` snapshot.
204
+ * @throws if `subscribe()` has not been called (or the state account has never loaded).
205
+ */
104
206
  getStateAccount(): StateAccount;
105
207
  /**
106
- * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
208
+ * Like `getStateAccount` but forces a fresh RPC fetch first. Useful for anchor tests where an
209
+ * update needs to be observed immediately rather than waiting for the next subscription push.
210
+ * @returns The freshly-fetched `StateAccount`.
107
211
  */
108
212
  forceGetStateAccount(): Promise<StateAccount>;
213
+ /**
214
+ * Returns the last account-subscriber-cached `PerpMarketAccount` for a market index. Does not hit
215
+ * RPC. The market must be one of the indexes/lookup-tables this client subscribed to.
216
+ * @param marketIndex - Perp market index.
217
+ * @returns The cached `PerpMarketAccount`, or `undefined` if not loaded/subscribed.
218
+ */
109
219
  getPerpMarketAccount(marketIndex: number): PerpMarketAccount | undefined;
110
220
  /**
111
- * Like {@link getPerpMarketAccount} but throws if the market is not loaded,
221
+ * Like `getPerpMarketAccount` but throws if the market is not loaded,
112
222
  * for call sites that require a guaranteed account.
223
+ * @param marketIndex - Perp market index.
224
+ * @returns The cached `PerpMarketAccount`.
225
+ * @throws if the market is not loaded.
113
226
  */
114
227
  getPerpMarketAccountOrThrow(marketIndex: number): PerpMarketAccount;
115
228
  /**
116
- * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
117
- * @param marketIndex
229
+ * Like `getPerpMarketAccount` but forces a fresh RPC fetch, retrying up to 10 times (one fetch per
230
+ * attempt) until the market account appears. Useful in anchor tests right after
231
+ * `initializePerpMarket` where the market may not yet be visible to the subscriber.
232
+ * @param marketIndex - Perp market index.
233
+ * @returns The `PerpMarketAccount`, or `undefined` if still not found after 10 attempts.
118
234
  */
119
235
  forceGetPerpMarketAccount(marketIndex: number): Promise<PerpMarketAccount | undefined>;
236
+ /**
237
+ * Returns all currently-loaded `PerpMarketAccount`s (does not hit RPC).
238
+ * @returns Array of loaded perp market accounts, in subscriber order.
239
+ */
120
240
  getPerpMarketAccounts(): PerpMarketAccount[];
241
+ /**
242
+ * Returns the last account-subscriber-cached `SpotMarketAccount` for a market index. Does not hit
243
+ * RPC.
244
+ * @param marketIndex - Spot market index.
245
+ * @returns The cached `SpotMarketAccount`, or `undefined` if not loaded/subscribed.
246
+ */
121
247
  getSpotMarketAccount(marketIndex: number): SpotMarketAccount | undefined;
122
248
  /**
123
- * Like {@link getSpotMarketAccount} but throws if the market is not loaded,
249
+ * Like `getSpotMarketAccount` but throws if the market is not loaded,
124
250
  * for call sites that require a guaranteed account.
251
+ * @param marketIndex - Spot market index.
252
+ * @returns The cached `SpotMarketAccount`.
253
+ * @throws if the market is not loaded.
125
254
  */
126
255
  getSpotMarketAccountOrThrow(marketIndex: number): SpotMarketAccount;
127
256
  /**
128
- * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
129
- * @param marketIndex
257
+ * Like `getSpotMarketAccount` but forces a fresh RPC fetch first. Useful for anchor tests where an
258
+ * update needs to be observed immediately.
259
+ * @param marketIndex - Spot market index.
260
+ * @returns The freshly-fetched `SpotMarketAccount`, or `undefined` if not found.
130
261
  */
131
262
  forceGetSpotMarketAccount(marketIndex: number): Promise<SpotMarketAccount | undefined>;
263
+ /**
264
+ * Returns all currently-loaded `SpotMarketAccount`s (does not hit RPC).
265
+ * @returns Array of loaded spot market accounts, in subscriber order.
266
+ */
132
267
  getSpotMarketAccounts(): SpotMarketAccount[];
268
+ /**
269
+ * Convenience accessor for the quote spot market (`QUOTE_SPOT_MARKET_INDEX`, always index 0), i.e.
270
+ * the USDC market used to denominate collateral/PnL across the protocol.
271
+ * @returns The quote `SpotMarketAccount`.
272
+ * @throws if the quote spot market is not loaded.
273
+ */
133
274
  getQuoteSpotMarketAccount(): SpotMarketAccount;
275
+ /**
276
+ * Returns the last subscriber-cached oracle price data for a given oracle account/source. Does not
277
+ * hit RPC.
278
+ * @param oraclePublicKey - Oracle account public key.
279
+ * @param oracleSource - Oracle protocol/feed variant (Pyth, Pyth Lazer, Switchboard, etc.) that
280
+ * determines how the account is decoded.
281
+ * @returns The cached oracle price data and the slot it was observed at, or `undefined` if this
282
+ * oracle isn't subscribed.
283
+ */
134
284
  getOraclePriceDataAndSlot(oraclePublicKey: PublicKey, oracleSource: OracleSource): DataAndSlot<OraclePriceData> | undefined;
285
+ /**
286
+ * Fetches and caches the `AddressLookupTableAccount`s for `this.marketLookupTables`, so
287
+ * transaction builders can include them to shrink versioned-transaction size. Subsequent calls
288
+ * return the cached result.
289
+ * @returns The resolved lookup table accounts (entries that don't exist on-chain are filtered out).
290
+ */
135
291
  fetchAllLookupTableAccounts(): Promise<AddressLookupTableAccount[]>;
136
292
  private getTxVersionForNewWallet;
137
293
  /**
138
- * Update the wallet to use for velocity transactions and linked user account
139
- * @param newWallet
140
- * @param subAccountIds
141
- * @param activeSubAccountId
142
- * @param includeDelegates
294
+ * Swaps the wallet/authority this client transacts and subscribes as, rebuilding the Anchor
295
+ * `provider`/`program`, `txSender`, `txHandler`, `userStats`, and (if already subscribed) every
296
+ * loaded `User` for the new authority. Use this instead of constructing a new `VelocityClient` when
297
+ * a UI wallet-adapter connection changes.
298
+ *
299
+ * At most one of `includeDelegates`, `subAccountIds`, or `authoritySubaccountMap` may be passed
300
+ * (mirrors the constructor's mutual-exclusion rule); `subAccountIds` is shorthand for
301
+ * `authoritySubaccountMap = { [newWallet.publicKey]: subAccountIds }`.
302
+ * @param newWallet - Wallet to switch to; becomes the new `authority`.
303
+ * @param subAccountIds - Sub-account ids to load for `newWallet`'s authority. Mutually exclusive
304
+ * with `includeDelegates` and `authoritySubaccountMap`.
305
+ * @param activeSubAccountId - Sub-account id to make active after the switch.
306
+ * @param includeDelegates - If `true`, load every sub-account this wallet is a delegate for, in
307
+ * addition to sub-accounts it owns directly. Mutually exclusive with `subAccountIds` and
308
+ * `authoritySubaccountMap`.
309
+ * @param authoritySubaccountMap - Explicit map of authority (as string) to sub-account ids to load,
310
+ * for managing multiple authorities from one wallet. Mutually exclusive with `subAccountIds` and
311
+ * `includeDelegates`.
312
+ * @returns `true` if re-subscribing users (when previously subscribed) succeeded; otherwise `false`.
313
+ * @throws if more than one of `includeDelegates`/`subAccountIds`/`authoritySubaccountMap` is set.
143
314
  */
144
315
  updateWallet(newWallet: IWallet, subAccountIds?: number[], activeSubAccountId?: number, includeDelegates?: boolean, authoritySubaccountMap?: Map<string, number[]>): Promise<boolean>;
145
316
  /**
146
317
  * Update the subscribed accounts to a given authority, while leaving the
147
318
  * connected wallet intact. This allows a user to emulate another user's
148
319
  * account on the UI and sign permissionless transactions with their own wallet.
149
- * @param emulateAuthority
320
+ *
321
+ * `authority` is repointed to `emulateAuthority` and `includeDelegates` is forced to `true`, but the
322
+ * connected `wallet` (and thus its signing key) is unchanged — instructions that require the
323
+ * emulated authority's own signature (e.g. deposits from its wallet) will still fail; only actions
324
+ * the connected wallet is independently authorized for (e.g. as a delegate, or read-only views)
325
+ * will succeed.
326
+ * @param emulateAuthority - Authority public key to view/act as.
327
+ * @returns `true` if re-subscribing users (when previously subscribed) succeeded; otherwise `false`.
150
328
  */
151
329
  emulateAccount(emulateAuthority: PublicKey): Promise<boolean>;
330
+ /**
331
+ * Sets the client's `activeSubAccountId`/`authority` (the sub-account used by default when a
332
+ * method's `subAccountId` param is omitted). If `authority` changes, re-derives and re-subscribes
333
+ * `userStats` for the new authority (assumed unnecessary when only the sub-account id changes for
334
+ * the same authority). Does not load or subscribe the target `User` itself — call `addUser` first
335
+ * if it isn't already loaded.
336
+ * @param subAccountId - Sub-account id to make active.
337
+ * @param authority - Authority to switch to; defaults to the current `this.authority` (no change).
338
+ */
152
339
  switchActiveUser(subAccountId: number, authority?: PublicKey): Promise<void>;
340
+ /**
341
+ * Loads and subscribes a `User` for a sub-account, adding it to `this.users`. If a subscribed
342
+ * `User` for this sub-account/authority is already loaded, returns `true` immediately without
343
+ * re-subscribing.
344
+ * @param subAccountId - Sub-account id to load.
345
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
346
+ * @param userAccount - Optional pre-fetched `UserAccount` data to seed the subscription with,
347
+ * avoiding an extra RPC round-trip (e.g. when the caller already has it from a prior fetch).
348
+ * @returns `true` if the user was already loaded or subscribed successfully; `false` if
349
+ * subscription failed (e.g. the on-chain user account doesn't exist).
350
+ */
153
351
  addUser(subAccountId: number, authority?: PublicKey, userAccount?: UserAccount): Promise<boolean>;
154
352
  /**
155
353
  * Adds and subscribes to users based on params set by the constructor or by updateWallet.
354
+ *
355
+ * If `authoritySubAccountMap` is non-empty, loads exactly the (authority, subAccountId) pairs it
356
+ * lists. Otherwise fetches every on-chain `UserAccount` owned by `authority` (defaulting to
357
+ * `this.wallet.publicKey`), plus (when `includeDelegates` is `true`) every account this authority
358
+ * is a delegate for, and loads all of them. If `activeSubAccountId` is not already set, the first
359
+ * loaded account becomes active. A no-op returning `true` if `skipLoadUsers` is set (e.g. no real
360
+ * wallet configured).
361
+ * @param authority - Authority to load accounts for; defaults to `this.wallet.publicKey`. Ignored
362
+ * when `authoritySubAccountMap` is set (its keys are used instead).
363
+ * @returns `true` if every implied user loaded/subscribed successfully.
156
364
  */
157
365
  addAndSubscribeToUsers(authority?: PublicKey): Promise<boolean>;
158
366
  /**
159
- * Returns the instructions to initialize a user account and the public key of the user account.
160
- * @param subAccountId
161
- * @param name
162
- * @param referrerInfo
163
- * @returns [instructions, userAccountPublicKey]
367
+ * Builds the instructions to initialize a user (sub-account) for `this.authority`, without sending
368
+ * a transaction. For `subAccountId === 0`, also prepends `initializeUserStats` if the authority's
369
+ * `UserStats` account doesn't already exist on-chain (every authority needs exactly one, created
370
+ * alongside its first sub-account).
371
+ * @param subAccountId - Sub-account id to create; defaults to `0`. Must not already exist.
372
+ * @param name - Display name (max 32 bytes, UTF-8), stored on-chain. Defaults to `DEFAULT_USER_NAME`
373
+ * for sub-account 0, or `"Subaccount {subAccountId + 1}"` otherwise.
374
+ * @param referrerInfo - Referrer's `referrer`/`referrerStats` public keys to attribute this account
375
+ * to a referrer at creation time (fee-share eligibility); omit if there is no referrer.
376
+ * @param poolId - If provided, appends an instruction to set the sub-account's isolated pool id
377
+ * after creation.
378
+ * @returns A tuple of `[instructions, userAccountPublicKey]` — the caller is responsible for
379
+ * building/sending the transaction.
164
380
  */
165
381
  getInitializeUserAccountIxs(subAccountId?: number, name?: string, referrerInfo?: ReferrerInfo, poolId?: number): Promise<[TransactionInstruction[], PublicKey]>;
166
382
  /**
167
- * Initializes a user account and returns the transaction signature and the public key of the user account.
168
- * @param subAccountId
169
- * @param name
170
- * @param referrerInfo
171
- * @param txParams
172
- * @returns [transactionSignature, userAccountPublicKey]
383
+ * Initializes a new user (sub-account) for `this.authority` on-chain, then loads and subscribes it
384
+ * into `this.users` via `addUser`. See `getInitializeUserAccountIxs` for parameter semantics and
385
+ * the implicit `UserStats` creation for `subAccountId === 0`.
386
+ * @param subAccountId - Sub-account id to create; defaults to `0`.
387
+ * @param name - Display name (max 32 bytes); see `getInitializeUserAccountIxs` for the default.
388
+ * @param referrerInfo - Referrer's `referrer`/`referrerStats` public keys, if attributing this
389
+ * account to a referrer.
390
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
391
+ * @returns A tuple of `[transactionSignature, userAccountPublicKey]`.
173
392
  */
174
393
  initializeUserAccount(subAccountId?: number, name?: string, referrerInfo?: ReferrerInfo, txParams?: TxParams): Promise<[TransactionSignature, PublicKey]>;
394
+ /**
395
+ * Builds the `initializeUserStats` instruction for `this.authority`. Every authority needs exactly
396
+ * one `UserStats` account (created automatically by `getInitializeUserAccountIxs`/
397
+ * `initializeUserAccount` alongside sub-account 0 if missing); call this directly only when
398
+ * building a custom initialization flow.
399
+ * @param overrides.externalWallet - Pays for account creation instead of `this.wallet`, if set.
400
+ * @returns The `initializeUserStats` instruction.
401
+ */
175
402
  getInitializeUserStatsIx(overrides?: {
176
403
  /**
177
404
  * Optional external wallet to use as payer. If provided, this wallet will pay
@@ -179,7 +406,25 @@ export declare class VelocityClient {
179
406
  */
180
407
  externalWallet?: PublicKey;
181
408
  }): Promise<TransactionInstruction>;
409
+ /**
410
+ * Initializes the `SignedMsgUserOrders` account for `authority`, which caches recently-submitted
411
+ * off-chain signed (SignedMsg / "swift") order messages so keepers can look them up and verify
412
+ * duplicates on-chain. Required once per authority before that authority's signed-message orders
413
+ * can be placed.
414
+ * @param authority - Authority the account is created for.
415
+ * @param numOrders - Number of order-message slots to allocate; determines account rent/size.
416
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
417
+ * @returns A tuple of `[transactionSignature, signedMsgUserAccountPublicKey]`.
418
+ */
182
419
  initializeSignedMsgUserOrders(authority: PublicKey, numOrders: number, txParams?: TxParams): Promise<[TransactionSignature, PublicKey]>;
420
+ /**
421
+ * Builds the `initializeSignedMsgUserOrders` instruction. See `initializeSignedMsgUserOrders` for
422
+ * semantics.
423
+ * @param authority - Authority the account is created for.
424
+ * @param numOrders - Number of order-message slots to allocate.
425
+ * @param overrides.externalWallet - Pays for account creation instead of `this.wallet`, if set.
426
+ * @returns A tuple of `[signedMsgUserAccountPublicKey, instruction]`.
427
+ */
183
428
  getInitializeSignedMsgUserOrdersAccountIx(authority: PublicKey, numOrders: number, overrides?: {
184
429
  /**
185
430
  * Optional external wallet to use as payer. If provided, this wallet will pay
@@ -187,102 +432,483 @@ export declare class VelocityClient {
187
432
  */
188
433
  externalWallet?: PublicKey;
189
434
  }): Promise<[PublicKey, TransactionInstruction]>;
435
+ /**
436
+ * Grows an existing `SignedMsgUserOrders` account to hold more order-message slots. The program
437
+ * only allows growing, never shrinking.
438
+ * @param authority - Authority whose account is resized.
439
+ * @param numOrders - New (larger) number of order-message slots.
440
+ * @param userSubaccountId - Sub-account id used to derive the `user` account passed to the
441
+ * instruction; defaults to `0`.
442
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
443
+ * @returns The transaction signature.
444
+ */
190
445
  resizeSignedMsgUserOrders(authority: PublicKey, numOrders: number, userSubaccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
446
+ /**
447
+ * Builds the `resizeSignedMsgUserOrders` instruction. See `resizeSignedMsgUserOrders` for
448
+ * semantics.
449
+ * @param authority - Authority whose account is resized.
450
+ * @param numOrders - New (larger) number of order-message slots.
451
+ * @param userSubaccountId - Sub-account id used to derive the `user` account; defaults to `0`.
452
+ * @returns The resize instruction.
453
+ */
191
454
  getResizeSignedMsgUserOrdersInstruction(authority: PublicKey, numOrders: number, userSubaccountId?: number): Promise<TransactionInstruction>;
455
+ /**
456
+ * Initializes `authority`'s `SignedMsgWsDelegates` account, which lists wallets authorized to
457
+ * co-sign/relay that authority's signed-message ("swift") orders over a websocket connection
458
+ * without holding general trading authority.
459
+ * @param authority - Authority the delegates account is created for.
460
+ * @param delegates - Initial set of delegate public keys; defaults to an empty list.
461
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
462
+ * @returns The transaction signature.
463
+ */
192
464
  initializeSignedMsgWsDelegatesAccount(authority: PublicKey, delegates?: PublicKey[], txParams?: TxParams): Promise<TransactionSignature>;
465
+ /**
466
+ * Builds the `initializeSignedMsgWsDelegates` instruction. See
467
+ * `initializeSignedMsgWsDelegatesAccount` for semantics.
468
+ * @param authority - Authority the delegates account is created for.
469
+ * @param delegates - Initial set of delegate public keys; defaults to an empty list.
470
+ * @returns The initialize instruction.
471
+ */
193
472
  getInitializeSignedMsgWsDelegatesAccountIx(authority: PublicKey, delegates?: PublicKey[]): Promise<TransactionInstruction>;
473
+ /**
474
+ * Initializes the per-authority `RevenueShare` account, which accumulates that authority's
475
+ * lifetime referrer and builder fee-share rewards. One per authority (not per sub-account); an
476
+ * authority must have this before it can earn referrer or builder revenue share.
477
+ * @param authority - Authority the account is created for.
478
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
479
+ * @returns The transaction signature.
480
+ */
194
481
  initializeRevenueShare(authority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
482
+ /**
483
+ * Builds the `initializeRevenueShare` instruction. See `initializeRevenueShare` for semantics.
484
+ * @param authority - Authority the account is created for.
485
+ * @param overrides.payer - Pays for account creation instead of `this.wallet`, if set.
486
+ * @returns The initialize instruction.
487
+ */
195
488
  getInitializeRevenueShareIx(authority: PublicKey, overrides?: {
196
489
  payer?: PublicKey;
197
490
  }): Promise<TransactionInstruction>;
491
+ /**
492
+ * Initializes `authority`'s `RevenueShareEscrow` account — the per-user account that tracks
493
+ * pending builder-fee orders and the list of builders this user has approved (`approvedBuilders`),
494
+ * required to place orders carrying a builder fee. On creation, `escrow.referrer` is copied from
495
+ * the authority's existing `UserStats.referrer`, if any.
496
+ * @param authority - Authority the escrow is created for.
497
+ * @param numOrders - Number of pending-order slots to allocate; determines account rent/size. Can
498
+ * be grown later with `resizeRevenueShareEscrowOrders` (never shrunk).
499
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
500
+ * @returns The transaction signature.
501
+ */
198
502
  initializeRevenueShareEscrow(authority: PublicKey, numOrders: number, txParams?: TxParams): Promise<TransactionSignature>;
503
+ /**
504
+ * Builds the `initializeRevenueShareEscrow` instruction. See `initializeRevenueShareEscrow` for
505
+ * semantics.
506
+ * @param authority - Authority the escrow is created for.
507
+ * @param numOrders - Number of pending-order slots to allocate.
508
+ * @param overrides.payer - Pays for account creation instead of `this.wallet`, if set.
509
+ * @returns The initialize instruction.
510
+ */
199
511
  getInitializeRevenueShareEscrowIx(authority: PublicKey, numOrders: number, overrides?: {
200
512
  payer?: PublicKey;
201
513
  }): Promise<TransactionInstruction>;
514
+ /**
515
+ * Grows `authority`'s `RevenueShareEscrow` order slots. On-chain rejects `numOrders` smaller than
516
+ * the current slot count (shrinking is not supported).
517
+ * @param authority - Authority whose escrow is resized.
518
+ * @param numOrders - New (larger or equal) number of pending-order slots.
519
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
520
+ * @returns The transaction signature.
521
+ * @throws (on-chain `InvalidRevenueShareResize`) if `numOrders` is less than the current slot count.
522
+ */
202
523
  resizeRevenueShareEscrowOrders(authority: PublicKey, numOrders: number, txParams?: TxParams): Promise<TransactionSignature>;
524
+ /**
525
+ * Builds the `resizeRevenueShareEscrowOrders` instruction. See `resizeRevenueShareEscrowOrders` for
526
+ * semantics.
527
+ * @param authority - Authority whose escrow is resized.
528
+ * @param numOrders - New (larger or equal) number of pending-order slots.
529
+ * @returns The resize instruction.
530
+ */
203
531
  getResizeRevenueShareEscrowOrdersIx(authority: PublicKey, numOrders: number): Promise<TransactionInstruction>;
204
532
  /**
205
- * Creates the transaction to add or update an approved builder.
206
- * This allows the builder to receive revenue share from referrals.
207
- *
208
- * @param builder - The public key of the builder to add or update.
209
- * @param maxFeeTenthBps - The maximum fee tenth bps to set for the builder.
533
+ * Adds, updates, or revokes an approved builder in the caller's own `RevenueShareEscrow`
534
+ * (`this.wallet.publicKey` unless `overrides.authority` is set on the underlying ix). This is the
535
+ * *user's* opt-in that lets `builder` attach a builder fee (capped at `maxFeeTenthBps`) to orders
536
+ * this user places it does not itself submit any order. `maxFeeTenthBps` is in tenths of a basis
537
+ * point (1 unit = 0.001%, i.e. `10_000` tenth-bps = 1%).
538
+ * @param builder - The public key of the builder to add or update. Must differ from the escrow's
539
+ * own authority.
540
+ * @param maxFeeTenthBps - The maximum fee, in tenths of a basis point, the builder may charge.
210
541
  * @param add - Whether to add or update the builder. If the builder already exists, `add = true` will update the `maxFeeTenthBps`, otherwise it will add the builder. If `add = false`, the builder's `maxFeeTenthBps` will be set to 0.
211
542
  * @param txParams - The transaction parameters to use for the transaction.
212
543
  * @returns The transaction to add or update an approved builder.
544
+ * @throws (on-chain `CannotRevokeBuilderWithOpenOrders`) if `add` is `false` and the builder has
545
+ * open (unsettled) orders outstanding — those must be cancelled/settled first.
213
546
  */
214
547
  changeApprovedBuilder(builder: PublicKey, maxFeeTenthBps: number, add: boolean, txParams?: TxParams): Promise<TransactionSignature>;
215
548
  /**
216
- * Creates the transaction instruction to add or update an approved builder.
217
- * This allows the builder to receive revenue share from referrals.
218
- *
549
+ * Builds the `changeApprovedBuilder` instruction. See `changeApprovedBuilder` for semantics; unlike
550
+ * the wrapper, `overrides.authority` lets you target an escrow other than the connected wallet's.
219
551
  * @param builder - The public key of the builder to add or update.
220
- * @param maxFeeTenthBps - The maximum fee tenth bps to set for the builder.
552
+ * @param maxFeeTenthBps - The maximum fee, in tenths of a basis point (1 unit = 0.001%).
221
553
  * @param add - Whether to add or update the builder. If the builder already exists, `add = true` will update the `maxFeeTenthBps`, otherwise it will add the builder. If `add = false`, the builder's `maxFeeTenthBps` will be set to 0.
554
+ * @param overrides.authority - Escrow authority to target; defaults to `this.wallet.publicKey`.
555
+ * @param overrides.payer - Pays for any account resize instead of `this.wallet`, if set.
222
556
  * @returns The transaction instruction to add or update an approved builder.
223
557
  */
224
558
  getChangeApprovedBuilderIx(builder: PublicKey, maxFeeTenthBps: number, add: boolean, overrides?: {
225
559
  authority?: PublicKey;
226
560
  payer?: PublicKey;
227
561
  }): Promise<TransactionInstruction>;
562
+ /**
563
+ * Authorizes `delegate` on `authority`'s existing `SignedMsgWsDelegates` account (must already be
564
+ * initialized via `initializeSignedMsgWsDelegatesAccount`). Signed by `this.wallet.publicKey`,
565
+ * which must be `authority`.
566
+ * @param authority - Authority whose delegates list is updated.
567
+ * @param delegate - Delegate public key to authorize.
568
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
569
+ * @returns The transaction signature.
570
+ */
228
571
  addSignedMsgWsDelegate(authority: PublicKey, delegate: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
572
+ /**
573
+ * Builds the `changeSignedMsgWsDelegateStatus` instruction with `add = true`. See
574
+ * `addSignedMsgWsDelegate` for semantics.
575
+ * @param authority - Authority whose delegates list is updated.
576
+ * @param delegate - Delegate public key to authorize.
577
+ * @returns The instruction.
578
+ */
229
579
  getAddSignedMsgWsDelegateIx(authority: PublicKey, delegate: PublicKey): Promise<TransactionInstruction>;
580
+ /**
581
+ * Revokes `delegate`'s authorization on `authority`'s `SignedMsgWsDelegates` account. Signed by
582
+ * `this.wallet.publicKey`, which must be `authority`.
583
+ * @param authority - Authority whose delegates list is updated.
584
+ * @param delegate - Delegate public key to revoke.
585
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
586
+ * @returns The transaction signature.
587
+ */
230
588
  removeSignedMsgWsDelegate(authority: PublicKey, delegate: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
589
+ /**
590
+ * Builds the `changeSignedMsgWsDelegateStatus` instruction with `add = false`. See
591
+ * `removeSignedMsgWsDelegate` for semantics.
592
+ * @param authority - Authority whose delegates list is updated.
593
+ * @param delegate - Delegate public key to revoke.
594
+ * @returns The instruction.
595
+ */
231
596
  getRemoveSignedMsgWsDelegateIx(authority: PublicKey, delegate: PublicKey): Promise<TransactionInstruction>;
232
597
  private getInitializeUserInstructions;
598
+ /**
599
+ * Returns the sub-account id that would be assigned to the next sub-account created for
600
+ * `this.wallet.publicKey` (i.e. `UserStats.numberOfSubAccountsCreated`, which increments on every
601
+ * `initializeUser` and never reuses ids after `deleteUser`). Prefers the already-loaded `userStats`
602
+ * subscription; falls back to an RPC fetch if it isn't loaded or has no cached account yet.
603
+ * @returns The next sub-account id to be created.
604
+ * @throws if no `UserStats` account exists on-chain for `this.wallet.publicKey` (i.e. sub-account 0
605
+ * has never been initialized).
606
+ */
233
607
  getNextSubAccountId(): Promise<number>;
608
+ /**
609
+ * Registers `this.wallet`'s sub-account 0 as a referrer under a human-readable `name`, creating a
610
+ * `ReferrerNameAccount` PDA keyed by that name. Other users can then look up this authority's
611
+ * `referrer`/`referrerStats` public keys by name (see `getReferrerNameAccountsForAuthority`) when
612
+ * passing `referrerInfo` to `initializeUserAccount`. Fails if the name is already taken (PDA
613
+ * already initialized).
614
+ * @param name - Referrer name to register (encoded/truncated the same way as user names).
615
+ * @returns The transaction signature.
616
+ */
234
617
  initializeReferrerName(name: string): Promise<TransactionSignature>;
618
+ /**
619
+ * Updates the display name stored on a sub-account. Signed by `this.wallet.publicKey`, which must
620
+ * be the sub-account's authority.
621
+ * @param name - New display name (max 32 bytes, UTF-8).
622
+ * @param subAccountId - Sub-account id to rename; defaults to `0`.
623
+ * @returns The transaction signature.
624
+ */
235
625
  updateUserName(name: string, subAccountId?: number): Promise<TransactionSignature>;
626
+ /**
627
+ * Sets a per-sub-account custom (higher) minimum margin ratio for one or more sub-accounts in a
628
+ * single transaction, self-imposing a lower max leverage than the market default. Signed by
629
+ * `this.wallet.publicKey` for each sub-account's authority.
630
+ * @param updates - List of `{ marginRatio, subAccountId }` updates to apply.
631
+ * `marginRatio` is in `MARGIN_PRECISION` (1e4 = 100%), e.g. `2000` = 20% margin ratio = 5x max
632
+ * leverage.
633
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
634
+ * @returns The transaction signature.
635
+ */
236
636
  updateUserCustomMarginRatio(updates: {
237
637
  marginRatio: number;
238
638
  subAccountId: number;
239
639
  }[], txParams?: TxParams): Promise<TransactionSignature>;
640
+ /**
641
+ * Builds the `updateUserCustomMarginRatio` instruction for a single sub-account. As a side effect,
642
+ * ensures the target sub-account is loaded via `addUser` before building the instruction. See
643
+ * `updateUserCustomMarginRatio` for unit/semantics.
644
+ * @param marginRatio - Minimum margin ratio, in `MARGIN_PRECISION` (1e4 = 100%).
645
+ * @param subAccountId - Sub-account id to update; defaults to `0`.
646
+ * @returns The instruction.
647
+ */
240
648
  getUpdateUserCustomMarginRatioIx(marginRatio: number, subAccountId?: number): Promise<TransactionInstruction>;
649
+ /**
650
+ * Builds the instruction to set a custom minimum margin ratio for a single open perp position
651
+ * (rather than the whole sub-account), letting a position use different effective max leverage than
652
+ * the sub-account default. Used internally by `getPrePlaceOrderIxs` to implement per-order
653
+ * `positionMaxLev`.
654
+ * @param perpMarketIndex - Perp market index of the position to constrain.
655
+ * @param marginRatio - Minimum margin ratio for this position, in `MARGIN_PRECISION` (1e4 = 100%).
656
+ * @param subAccountId - Sub-account id owning the position; defaults to `0`.
657
+ * @param overrides.userAccountPublicKey - Explicit user account PDA, skipping derivation.
658
+ * @param overrides.authority - Authority to derive the user account PDA for if
659
+ * `userAccountPublicKey` isn't given; defaults to `this.authority`.
660
+ * @param overrides.signingAuthority - Signer passed to the instruction; defaults to
661
+ * `this.wallet.publicKey`.
662
+ * @returns The instruction.
663
+ */
241
664
  getUpdateUserPerpPositionCustomMarginRatioIx(perpMarketIndex: number, marginRatio: number, subAccountId?: number, overrides?: {
242
665
  userAccountPublicKey?: PublicKey;
243
666
  authority?: PublicKey;
244
667
  signingAuthority?: PublicKey;
245
668
  }): Promise<TransactionInstruction>;
669
+ /**
670
+ * Sends the instruction built by `getUpdateUserPerpPositionCustomMarginRatioIx`. See that method
671
+ * for semantics/units.
672
+ * @param perpMarketIndex - Perp market index of the position to constrain.
673
+ * @param marginRatio - Minimum margin ratio for this position, in `MARGIN_PRECISION` (1e4 = 100%).
674
+ * @param subAccountId - Sub-account id owning the position; defaults to `0`.
675
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
676
+ * @returns The transaction signature.
677
+ */
246
678
  updateUserPerpPositionCustomMarginRatio(perpMarketIndex: number, marginRatio: number, subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
679
+ /**
680
+ * Builds the instruction to toggle a sub-account's "margin trading enabled" flag, which permits
681
+ * borrowing against spot collateral (multiple simultaneous spot borrows / cross-margined spot). It
682
+ * is incompatible with holding a position in an `Isolated`-tier perp market — enabling it while
683
+ * such a position is open, or opening one while it's enabled, is rejected on-chain. As a side
684
+ * effect, ensures the target sub-account is loaded via `addUser`.
685
+ * @param marginTradingEnabled - New value for the flag.
686
+ * @param subAccountId - Sub-account id to update; defaults to `0`.
687
+ * @param userAccountPublicKey - Explicit user account PDA, skipping derivation from
688
+ * `this.wallet.publicKey`/`subAccountId`.
689
+ * @returns The instruction.
690
+ */
247
691
  getUpdateUserMarginTradingEnabledIx(marginTradingEnabled: boolean, subAccountId?: number, userAccountPublicKey?: PublicKey): Promise<TransactionInstruction>;
692
+ /**
693
+ * Sends instructions built by `getUpdateUserMarginTradingEnabledIx` for one or more sub-accounts in
694
+ * a single transaction. See that method for semantics.
695
+ * @param updates - List of `{ marginTradingEnabled, subAccountId }` updates to apply.
696
+ * @returns The transaction signature.
697
+ */
248
698
  updateUserMarginTradingEnabled(updates: {
249
699
  marginTradingEnabled: boolean;
250
700
  subAccountId: number;
251
701
  }[]): Promise<TransactionSignature>;
702
+ /**
703
+ * Builds the instruction to set (or clear, with `PublicKey.default`) the delegate authority on a
704
+ * sub-account. The delegate can sign most trading instructions (place/cancel orders, etc.) on the
705
+ * sub-account's behalf, but `withdraw` always requires the true owning `authority`'s own signature
706
+ * (delegates can never withdraw). A delegate-initiated internal transfer of the sub-account's
707
+ * collateral to another of the owner's sub-accounts is possible only via `transferDepositByDelegate`,
708
+ * and only once the owner has separately opted in via `updateUserAllowDelegateTransfer`.
709
+ * @param delegate - New delegate public key; pass `PublicKey.default` to remove the delegate.
710
+ * @param overrides.subAccountId - Sub-account id to update; defaults to `this.activeSubAccountId`.
711
+ * @param overrides.userAccountPublicKey - Explicit user account PDA, skipping derivation.
712
+ * @param overrides.authority - Signer for the instruction; defaults to `this.wallet.publicKey`.
713
+ * @returns The instruction.
714
+ */
252
715
  getUpdateUserDelegateIx(delegate: PublicKey, overrides: {
253
716
  subAccountId?: number;
254
717
  userAccountPublicKey?: PublicKey;
255
718
  authority?: PublicKey;
256
719
  }): Promise<TransactionInstruction>;
720
+ /**
721
+ * Sends the `updateUserDelegate` instruction for `this.wallet.publicKey`'s sub-account. See
722
+ * `getUpdateUserDelegateIx` for full semantics.
723
+ * @param delegate - New delegate public key; pass `PublicKey.default` to remove the delegate.
724
+ * @param subAccountId - Sub-account id to update; defaults to `0`.
725
+ * @returns The transaction signature.
726
+ */
257
727
  updateUserDelegate(delegate: PublicKey, subAccountId?: number): Promise<TransactionSignature>;
728
+ /**
729
+ * Builds the instruction to set the `allowDelegateTransfer` opt-in flag on `this.wallet.publicKey`'s
730
+ * `UserStats` account. This flag gates `transferDepositByDelegate` across *all* of this authority's
731
+ * sub-accounts — if it is `false` (the default), any delegate-initiated internal transfer attempt
732
+ * is rejected on-chain regardless of that sub-account's delegate. It does not affect direct
733
+ * deposits/withdrawals, which are unaffected by delegate status.
734
+ * @param allowDelegateTransfer - New value for the flag.
735
+ * @returns The instruction.
736
+ */
258
737
  getUpdateUserAllowDelegateTransferIx(allowDelegateTransfer: boolean): Promise<TransactionInstruction>;
738
+ /**
739
+ * Sends the instruction built by `getUpdateUserAllowDelegateTransferIx`. See that method for
740
+ * semantics.
741
+ * @param allowDelegateTransfer - New value for the flag.
742
+ * @returns The transaction signature.
743
+ */
259
744
  updateUserAllowDelegateTransfer(allowDelegateTransfer: boolean): Promise<TransactionSignature>;
745
+ /**
746
+ * Sends instructions built by `getUpdateAdvancedDlpIx` for one or more sub-accounts.
747
+ *
748
+ * **Currently non-functional**: the on-chain `update_user_advanced_lp` instruction handler is
749
+ * commented out of the program's Anchor `#[program]` module (see `programs/velocity/src/lib.rs`)
750
+ * and is absent from the generated IDL, so `program.instruction.updateUserAdvancedLp` does not
751
+ * exist and this call will throw at runtime until the instruction is re-enabled on-chain.
752
+ * @param updates - List of `{ advancedLp, subAccountId }` updates to apply.
753
+ * @returns The transaction signature.
754
+ * @throws always, until `update_user_advanced_lp` is re-enabled on-chain and regenerated into the IDL.
755
+ */
260
756
  updateUserAdvancedLp(updates: {
261
757
  advancedLp: boolean;
262
758
  subAccountId: number;
263
759
  }[]): Promise<TransactionSignature>;
760
+ /**
761
+ * Builds the (currently unavailable — see `updateUserAdvancedLp`) `updateUserAdvancedLp`
762
+ * instruction, which would flag a sub-account as an "advanced LP" participant.
763
+ * @param advancedLp - New value for the flag.
764
+ * @param subAccountId - Sub-account id to update.
765
+ * @returns The instruction, if the on-chain ix existed.
766
+ * @throws always, since `program.instruction.updateUserAdvancedLp` is not defined in the current IDL.
767
+ */
264
768
  getUpdateAdvancedDlpIx(advancedLp: boolean, subAccountId: number): Promise<any>;
769
+ /**
770
+ * Sends instructions built by `getUpdateUserReduceOnlyIx` for one or more sub-accounts in a single
771
+ * transaction. See that method for semantics.
772
+ * @param updates - List of `{ reduceOnly, subAccountId }` updates to apply.
773
+ * @returns The transaction signature.
774
+ */
265
775
  updateUserReduceOnly(updates: {
266
776
  reduceOnly: boolean;
267
777
  subAccountId: number;
268
778
  }[]): Promise<TransactionSignature>;
779
+ /**
780
+ * Builds the instruction to toggle a sub-account's reduce-only status. When reduce-only, orders on
781
+ * the sub-account may only decrease existing positions, never open or increase one.
782
+ * @param reduceOnly - New value for the flag.
783
+ * @param subAccountId - Sub-account id to update.
784
+ * @returns The instruction.
785
+ * @throws (on-chain `LiquidationsOngoing`) if the sub-account is currently being liquidated.
786
+ */
269
787
  getUpdateUserReduceOnlyIx(reduceOnly: boolean, subAccountId: number): Promise<TransactionInstruction>;
788
+ /**
789
+ * Sends instructions built by `getUpdateUserPoolIdIx` for one or more sub-accounts in a single
790
+ * transaction. See that method for semantics.
791
+ * @param updates - List of `{ poolId, subAccountId }` updates to apply.
792
+ * @returns The transaction signature.
793
+ */
270
794
  updateUserPoolId(updates: {
271
795
  poolId: number;
272
796
  subAccountId: number;
273
797
  }[]): Promise<TransactionSignature>;
798
+ /**
799
+ * Builds the instruction to move a sub-account into a different isolated pool. On-chain,
800
+ * re-validates the sub-account still meets its initial margin requirement after the switch using
801
+ * only markets/oracles passed via `remaining_accounts` — the caller (this method doesn't add any)
802
+ * must supply those if the sub-account has open deposits/positions, or the ix will fail.
803
+ * @param poolId - New pool id for the sub-account.
804
+ * @param subAccountId - Sub-account id to update.
805
+ * @returns The instruction.
806
+ * @throws (on-chain) if the sub-account has deposits/positions in markets outside the new pool, or
807
+ * otherwise fails the initial margin check after the switch.
808
+ */
274
809
  getUpdateUserPoolIdIx(poolId: number, subAccountId: number): Promise<TransactionInstruction>;
810
+ /**
811
+ * Fetches every `User` account that exists on-chain for this program via `getProgramAccounts` (with
812
+ * a `memcmp` filter, not restricted to this client's authority). Expensive — intended for indexers/
813
+ * admin tooling, not per-trade calls.
814
+ * @param includeIdle - If `false`, filters out idle (inactive) user accounts server-side; defaults
815
+ * to `true` (return all).
816
+ * @returns All matching `User` program accounts with their addresses.
817
+ */
275
818
  fetchAllUserAccounts(includeIdle?: boolean): Promise<ProgramAccount<UserAccount>[]>;
819
+ /**
820
+ * Fetches (via RPC `memcmp` filter, not the account subscriber) every on-chain `User` account whose
821
+ * `delegate` field equals `delegate`, i.e. every sub-account this wallet can trade on behalf of as a
822
+ * delegate.
823
+ * @param delegate - Delegate public key to search for.
824
+ * @returns Matching `UserAccount`s, sorted by `subAccountId` ascending.
825
+ */
276
826
  getUserAccountsForDelegate(delegate: PublicKey): Promise<UserAccount[]>;
827
+ /**
828
+ * Fetches (via RPC, not the account subscriber) every on-chain `User` account owned by `authority`,
829
+ * with each account's PDA address included.
830
+ * @param authority - Authority to search for.
831
+ * @returns Matching `UserAccount`s and their addresses, in RPC-returned order (not sorted).
832
+ */
277
833
  getUserAccountsAndAddressesForAuthority(authority: PublicKey): Promise<ProgramAccount<UserAccount>[]>;
834
+ /**
835
+ * Fetches (via RPC, not the account subscriber) every on-chain `User` account owned by `authority`.
836
+ * Used internally by `addAndSubscribeToUsers` to discover an authority's sub-accounts.
837
+ * @param authority - Authority to search for.
838
+ * @returns Matching `UserAccount`s, sorted by `subAccountId` ascending.
839
+ */
278
840
  getUserAccountsForAuthority(authority: PublicKey): Promise<UserAccount[]>;
841
+ /**
842
+ * Fetches (via RPC `memcmp` filter) every `UserStats` account whose `referrer` field equals
843
+ * `referrer`, i.e. every authority that was referred by this referrer.
844
+ * @param referrer - Referrer authority public key to search for.
845
+ * @returns Matching `UserStatsAccount`s, in RPC-returned order.
846
+ */
279
847
  getReferredUserStatsAccountsByReferrer(referrer: PublicKey): Promise<UserStatsAccount[]>;
848
+ /**
849
+ * Fetches (via RPC `memcmp` filter) every `ReferrerNameAccount` registered by `authority` via
850
+ * `initializeReferrerName`.
851
+ * @param authority - Authority to search for.
852
+ * @returns Matching `ReferrerNameAccount`s, in RPC-returned order.
853
+ */
280
854
  getReferrerNameAccountsForAuthority(authority: PublicKey): Promise<ReferrerNameAccount[]>;
855
+ /**
856
+ * Deletes a sub-account owned by `this.wallet.publicKey` and unsubscribes/removes it from
857
+ * `this.users`. On-chain requires the sub-account to be fully closed out: no open perp/spot
858
+ * positions, no open orders, not bankrupt, not being liquidated, and (unless idle) sub-account 0 of
859
+ * a referrer cannot be deleted at all. If the protocol charges a `maxInitializeUserFee` and the
860
+ * account's `UserStats` is younger than ~13 days, the sub-account must also be marked `idle`.
861
+ * @param subAccountId - Sub-account id to delete; defaults to `0`.
862
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
863
+ * @returns The transaction signature.
864
+ * @throws (on-chain `UserCantBeDeleted`) if any of the above preconditions aren't met.
865
+ */
281
866
  deleteUser(subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
867
+ /**
868
+ * Builds the `deleteUser` instruction. See `deleteUser` for on-chain preconditions.
869
+ * @param userAccountPublicKey - User account PDA to delete.
870
+ * @returns The instruction.
871
+ */
282
872
  getUserDeletionIx(userAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
873
+ /**
874
+ * Keeper-only instruction: force-cancels all open orders and deletes/closes an inactive, near-zero
875
+ * equity user account, refunding remaining rent to `userAccount.authority`. Requires the signer
876
+ * (`this.wallet.publicKey`) to hold the `UserFlag` hot-role. On-chain, requires the account's
877
+ * total equity to be under `QUOTE_PRECISION / 20` (0.05 USDC, QUOTE_PRECISION = 1e6) and (outside
878
+ * `anchor-test` builds) at least ~3 months of inactivity since `lastActiveSlot`. Not for
879
+ * self-service account deletion — see `deleteUser` for that.
880
+ * @param userAccountPublicKey - PDA of the user account to force-delete.
881
+ * @param userAccount - The account's current on-chain data, used to build `remaining_accounts` for
882
+ * the markets it holds positions in.
883
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
884
+ * @returns The transaction signature.
885
+ * @throws (on-chain) if the signer lacks the `UserFlag` hot-role, if equity exceeds the dust
886
+ * threshold, or if the account has been active too recently.
887
+ */
283
888
  forceDeleteUser(userAccountPublicKey: PublicKey, userAccount: UserAccount, txParams?: TxParams): Promise<TransactionSignature>;
889
+ /**
890
+ * Builds the keeper-only `forceDeleteUser` instruction, assembling `remaining_accounts` for the
891
+ * account's non-empty spot positions, its revenue-share escrow (if any order carries a builder
892
+ * fee), and every mint/token-program needed for its open spot balances. See `forceDeleteUser` for
893
+ * on-chain preconditions.
894
+ * @param userAccountPublicKey - PDA of the user account to force-delete.
895
+ * @param userAccount - The account's current on-chain data.
896
+ * @returns The instruction.
897
+ */
284
898
  getForceDeleteUserIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
899
+ /**
900
+ * Closes `this.wallet.publicKey`'s `SignedMsgUserOrders` account, refunding its rent to the
901
+ * authority. Requires the account to exist (see `isSignedMsgUserOrdersAccountInitialized`).
902
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
903
+ * @returns The transaction signature.
904
+ */
285
905
  deleteSignedMsgUserOrders(txParams?: TxParams): Promise<TransactionSignature>;
906
+ /**
907
+ * Builds the `deleteSignedMsgUserOrders` instruction, signed by `this.wallet.publicKey`. See
908
+ * `deleteSignedMsgUserOrders` for semantics.
909
+ * @param authority - Authority whose `SignedMsgUserOrders` PDA is derived and closed.
910
+ * @returns The instruction.
911
+ */
286
912
  getSignedMsgUserOrdersDeletionIx(authority: PublicKey): Promise<any>;
287
913
  /**
288
914
  * Checks if a SignedMsg User Orders account exists for the given authority.
@@ -293,64 +919,180 @@ export declare class VelocityClient {
293
919
  * @returns Promise that resolves to true if the account exists, false otherwise
294
920
  */
295
921
  isSignedMsgUserOrdersAccountInitialized(authority: PublicKey): Promise<boolean>;
922
+ /**
923
+ * Reclaims any lamports on a sub-account's `User` PDA in excess of the rent-exempt minimum for its
924
+ * current size (e.g. left over after the account was resized smaller), transferring them to
925
+ * `this.wallet.publicKey`.
926
+ * @param subAccountId - Sub-account id to reclaim rent from; defaults to `0`.
927
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
928
+ * @returns The transaction signature.
929
+ * @throws (on-chain `CantReclaimRent`) if there are no excess lamports, or if the account's
930
+ * `UserStats` is younger than ~13 days while the protocol enforces a max sub-account count.
931
+ */
296
932
  reclaimRent(subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
933
+ /**
934
+ * Builds the `reclaimRent` instruction. See `reclaimRent` for semantics/preconditions.
935
+ * @param userAccountPublicKey - User account PDA to reclaim excess rent from.
936
+ * @returns The instruction.
937
+ */
297
938
  getReclaimRentIx(userAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
939
+ /**
940
+ * Looks up an already-loaded `User` from `this.users` (does not fetch or subscribe).
941
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
942
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
943
+ * @returns The loaded `User`.
944
+ * @throws if `subAccountId`/`authority` can't be resolved, or no matching user is loaded (call
945
+ * `addUser` first).
946
+ */
298
947
  getUser(subAccountId?: number, authority?: PublicKey): User;
948
+ /**
949
+ * Checks whether a `User` for the given sub-account/authority is currently loaded in `this.users`,
950
+ * without throwing. Safe to call with unresolvable `subAccountId`/`authority` (returns `false`).
951
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
952
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
953
+ * @returns `true` if a matching `User` is loaded.
954
+ */
299
955
  hasUser(subAccountId?: number, authority?: PublicKey): boolean;
956
+ /**
957
+ * Returns every currently-loaded `User`, with sub-accounts owned directly by `this.wallet.publicKey`
958
+ * first, followed by delegated sub-accounts (owned by other authorities this wallet delegates for).
959
+ * @returns All loaded `User`s in that order.
960
+ */
300
961
  getUsers(): User[];
962
+ /**
963
+ * Returns the `UserStats` instance for `this.authority`, if one was constructed (via
964
+ * `config.userStats`, `updateWallet`, `emulateAccount`, or `switchActiveUser`).
965
+ * @returns The `UserStats` instance, or `undefined` if none exists.
966
+ */
301
967
  getUserStats(): UserStats | undefined;
302
968
  /**
303
- * Like {@link getUserStats} but throws if there is no UserStats
969
+ * Like `getUserStats` but throws if there is no UserStats
304
970
  * subscription, for call sites that require a guaranteed account.
305
971
  */
306
972
  getUserStatsOrThrow(): UserStats;
973
+ /**
974
+ * Fetches (via RPC, not the account subscriber) the `ReferrerNameAccount` registered for a given
975
+ * name via `initializeReferrerName`.
976
+ * @param name - Referrer name to look up.
977
+ * @returns The `ReferrerNameAccount`.
978
+ * @throws if no `ReferrerNameAccount` is registered under `name`.
979
+ */
307
980
  fetchReferrerNameAccount(name: string): Promise<ReferrerNameAccount | undefined>;
981
+ /**
982
+ * Returns the `UserStats` account PDA for `this.authority`, computing and caching it on first call
983
+ * (or after `this.authority` changes, since callers like `updateWallet`/`switchActiveUser` reset the
984
+ * cache).
985
+ * @returns The `UserStats` account public key.
986
+ */
308
987
  getUserStatsAccountPublicKey(): PublicKey;
988
+ /**
989
+ * Returns the user account PDA for an already-loaded sub-account (does not derive/compute a PDA
990
+ * for a sub-account that hasn't been loaded).
991
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
992
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
993
+ * @returns The user account public key.
994
+ * @throws if no matching user is loaded — see `getUser`.
995
+ */
309
996
  getUserAccountPublicKey(subAccountId?: number, authority?: PublicKey): Promise<PublicKey>;
997
+ /**
998
+ * Returns the last subscriber-cached `UserAccount` data for a loaded sub-account. Does not hit RPC.
999
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
1000
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
1001
+ * @returns The cached `UserAccount`, or `undefined` if not yet loaded.
1002
+ * @throws if no matching `User` is loaded — see `getUser`.
1003
+ */
310
1004
  getUserAccount(subAccountId?: number, authority?: PublicKey): UserAccount | undefined;
311
1005
  /**
312
- * Like {@link getUserAccount} but throws a named error instead of returning
1006
+ * Like `getUserAccount` but throws a named error instead of returning
313
1007
  * `undefined` when the account has not been loaded yet. Use at call sites
314
1008
  * that structurally require a loaded account.
315
1009
  */
316
1010
  getUserAccountOrThrow(subAccountId?: number, authority?: PublicKey): UserAccount;
317
1011
  /**
318
- * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
319
- * @param subAccountId
1012
+ * Like `getUserAccount` but forces a fresh RPC fetch first. Useful for anchor tests where an
1013
+ * update needs to be observed immediately.
1014
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
1015
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
1016
+ * @returns The freshly-fetched `UserAccount`, or `undefined` if not found.
1017
+ * @throws if no matching `User` is loaded — see `getUser`.
320
1018
  */
321
1019
  forceGetUserAccount(subAccountId?: number, authority?: PublicKey): Promise<UserAccount | undefined>;
1020
+ /**
1021
+ * Like `getUserAccount` but also returns the slot the data was last observed at.
1022
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
1023
+ * @param authority - Authority owning the sub-account; defaults to `this.authority`.
1024
+ * @returns The cached `UserAccount` and its slot, or `undefined` if not yet loaded.
1025
+ * @throws if no matching `User` is loaded — see `getUser`.
1026
+ */
322
1027
  getUserAccountAndSlot(subAccountId?: number, authority?: PublicKey): DataAndSlot<UserAccount> | undefined;
1028
+ /**
1029
+ * Returns a sub-account's spot balance entry for a market, if it holds one.
1030
+ * @param marketIndex - Spot market index.
1031
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
1032
+ * @returns The `SpotPosition`, or `undefined` if the sub-account has no balance in this market.
1033
+ * @throws if the sub-account is not loaded — see `getUserAccountOrThrow`.
1034
+ */
323
1035
  getSpotPosition(marketIndex: number, subAccountId?: number): SpotPosition | undefined;
1036
+ /**
1037
+ * Convenience accessor for the active sub-account's quote (USDC) token amount.
1038
+ * @returns Signed token amount, in the quote spot market's token precision (positive if a deposit,
1039
+ * negative if a borrow). See `getTokenAmount`.
1040
+ */
324
1041
  getQuoteAssetTokenAmount(): BN;
1042
+ /**
1043
+ * Returns the isolated deposit token amount backing a sub-account's isolated perp position in a
1044
+ * given market (the collateral segregated into that position via
1045
+ * `transferIsolatedPerpPositionDeposit`, distinct from the sub-account's general/cross balances).
1046
+ * @param perpMarketIndex - Perp market index of the isolated position.
1047
+ * @param subAccountId - Sub-account id; defaults to `this.activeSubAccountId`.
1048
+ * @returns Token amount in the quote spot market's token precision.
1049
+ */
325
1050
  getIsolatedPerpPositionTokenAmount(perpMarketIndex: number, subAccountId?: number): BN;
326
1051
  /**
327
- * Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
328
- * Positive if it is a deposit, negative if it is a borrow.
329
- * @param marketIndex
1052
+ * Returns the active sub-account's balance in a spot market, converted from the internal scaled
1053
+ * balance representation to actual token units.
1054
+ * @param marketIndex - Spot market index.
1055
+ * @returns Token amount in the spot market's own token precision (`10^mint.decimals`, e.g.
1056
+ * QUOTE_PRECISION (1e6) for USDC). Positive if a deposit, negative if a borrow. `ZERO` if the
1057
+ * sub-account has no balance in this market.
330
1058
  */
331
1059
  getTokenAmount(marketIndex: number): BN;
332
1060
  /**
333
- * Converts an amount to the spot precision for a given market. The spot market precision is based on the token mint decimals.
334
- * @param marketIndex
335
- * @param amount
1061
+ * Converts a human-readable (UI) amount to a market's on-chain spot precision (`10^mint.decimals`).
1062
+ * A plain `number` is scaled up via `castNumberToSpotPrecision`; a `BN` is assumed to already be a
1063
+ * whole-token count and is scaled by the same factor.
1064
+ * @param marketIndex - Spot market index whose token decimals determine the scale factor.
1065
+ * @param amount - UI amount to convert.
1066
+ * @returns The amount in the spot market's token precision.
336
1067
  */
337
1068
  convertToSpotPrecision(marketIndex: number, amount: BN | number): BN;
338
1069
  /**
339
- * Converts an amount to the perp precision. The perp market precision is {@link BASE_PRECISION} (1e9).
340
- * @param amount
1070
+ * Converts a human-readable (UI) base-asset amount to `BASE_PRECISION` (1e9), the precision used for
1071
+ * perp/spot order base amounts.
1072
+ * @param amount - UI base amount to convert. A `number` is scaled via a precision-safe helper; a
1073
+ * `BN` is assumed to already be a whole-unit count and is multiplied directly by `BASE_PRECISION`.
1074
+ * @returns The amount in `BASE_PRECISION` (1e9).
341
1075
  */
342
1076
  convertToPerpPrecision(amount: BN | number): BN;
343
1077
  /**
344
- * Converts an amount to the price precision. The perp market precision is {@link PRICE_PRECISION} (1e6).
345
- * @param amount
1078
+ * Converts a human-readable (UI) price to `PRICE_PRECISION` (1e6).
1079
+ * @param amount - UI price to convert.
1080
+ * @returns The amount in `PRICE_PRECISION` (1e6) when `amount` is a `number` (uses
1081
+ * `numberToSafeBN(amount, PRICE_PRECISION)`).
1082
+ * **Note:** when `amount` is a `BN`, this multiplies by `BASE_PRECISION` (1e9), not
1083
+ * `PRICE_PRECISION` (1e6) — that is very likely a bug (1000x too large) rather than intended
1084
+ * behavior; pass a `number` for correct scaling until this is fixed.
346
1085
  */
347
1086
  convertToPricePrecision(amount: BN | number): BN;
348
1087
  /**
349
- * Each velocity instruction must include perp and sport market accounts in the ix remaining accounts.
1088
+ * Each velocity instruction must include perp and spot market accounts in the ix remaining accounts.
350
1089
  * Use this function to force a subset of markets to be included in the remaining accounts for every ix
351
- *
352
- * @param perpMarketIndexes
353
- * @param spotMarketIndexes
1090
+ * built by this client going forward (accumulates into `mustIncludePerpMarketIndexes` /
1091
+ * `mustIncludeSpotMarketIndexes`; there is no corresponding "unset" — construct a new client to
1092
+ * reset). Useful when an instruction's own logic can't infer every market/oracle it needs (e.g. a
1093
+ * cross-margin health check spanning markets the user has no position in yet).
1094
+ * @param perpMarketIndexes - Perp market indexes to always include.
1095
+ * @param spotMarketIndexes - Spot market indexes to always include.
354
1096
  */
355
1097
  mustIncludeMarketsInIx({ perpMarketIndexes, spotMarketIndexes, }: {
356
1098
  perpMarketIndexes: number[];
@@ -358,10 +1100,55 @@ export declare class VelocityClient {
358
1100
  }): void;
359
1101
  private cachePerpMarketSlot;
360
1102
  private cacheSpotMarketSlot;
1103
+ /**
1104
+ * Builds the `remaining_accounts` list (perp/spot market + oracle accounts, plus any accounts
1105
+ * derived from the given `userAccounts`) that most instructions need appended so the on-chain
1106
+ * handler can load the markets/oracles it touches. Always includes markets registered via
1107
+ * `mustIncludeMarketsInIx`, in addition to whatever `params` (e.g. `userAccounts`,
1108
+ * `writableSpotMarketIndexes`) implies. Used internally by nearly every instruction-building method
1109
+ * on this class; exposed publicly for callers assembling custom instructions.
1110
+ * @param params - Describes which markets/users to derive remaining accounts for; see
1111
+ * `RemainingAccountParams` (core/remainingAccounts.ts).
1112
+ * @returns The `AccountMeta[]` to append to an instruction's accounts.
1113
+ */
361
1114
  getRemainingAccounts(params: RemainingAccountParams): AccountMeta[];
1115
+ /**
1116
+ * Adds a perp market's account meta (and its oracle and quote spot market) into the shared maps used
1117
+ * to de-duplicate remaining accounts across multiple markets in one instruction. The oracle is
1118
+ * marked writable only for `prelaunch`-sourced oracles being written to.
1119
+ * @param marketIndex - Perp market index to include.
1120
+ * @param writable - Whether the perp market account meta should be writable.
1121
+ * @param oracleAccountMap - Shared map (keyed by oracle pubkey string) mutated in place.
1122
+ * @param spotMarketAccountMap - Shared map (keyed by spot market index) mutated in place.
1123
+ * @param perpMarketAccountMap - Shared map (keyed by perp market index) mutated in place.
1124
+ */
362
1125
  addPerpMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>, perpMarketAccountMap: Map<number, AccountMeta>): void;
1126
+ /**
1127
+ * Adds a spot market's account meta (and its oracle, if any) into the shared maps used to
1128
+ * de-duplicate remaining accounts across multiple markets in one instruction.
1129
+ * @param marketIndex - Spot market index to include.
1130
+ * @param writable - Whether the spot market account meta should be writable.
1131
+ * @param oracleAccountMap - Shared map (keyed by oracle pubkey string) mutated in place.
1132
+ * @param spotMarketAccountMap - Shared map (keyed by spot market index) mutated in place.
1133
+ */
363
1134
  addSpotMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>): void;
1135
+ /**
1136
+ * Appends each builder's `User` (sub-account 0) and `RevenueShare` account metas to
1137
+ * `remainingAccounts` (writable), deduping by pubkey so an authority that is both a builder and a
1138
+ * referrer isn't pushed twice — the on-chain revenue-share account loader rejects duplicates and
1139
+ * would abort the whole instruction.
1140
+ * @param builders - Builder authority public keys to include.
1141
+ * @param remainingAccounts - Array mutated in place by appending the builder account metas.
1142
+ */
364
1143
  addBuilderToRemainingAccounts(builders: PublicKey[], remainingAccounts: AccountMeta[]): void;
1144
+ /**
1145
+ * Builds the deduplicated oracle/spot-market/perp-market account-meta maps needed to cover every
1146
+ * non-empty position across a set of user accounts (e.g. taker + makers in a fill), including the
1147
+ * quote spot market whenever a spot position has open orders. All accounts are added read-only.
1148
+ * @param userAccounts - User accounts whose open positions determine which markets to include.
1149
+ * @returns The three account-meta maps, keyed by oracle pubkey string / spot market index / perp
1150
+ * market index respectively.
1151
+ */
365
1152
  getRemainingAccountMapsForUsers(userAccounts: UserAccount[]): {
366
1153
  oracleAccountMap: Map<string, AccountMeta>;
367
1154
  spotMarketAccountMap: Map<number, AccountMeta>;
@@ -372,7 +1159,7 @@ export declare class VelocityClient {
372
1159
  *
373
1160
  * `orderId` is the monotonically incrementing u32 counter that the program assigns at
374
1161
  * placement time — it is not known until the place instruction executes on-chain. Use
375
- * {@link getOrderByUserId} when you need to look up an order by the caller-supplied
1162
+ * `getOrderByUserId` when you need to look up an order by the caller-supplied
376
1163
  * `userOrderId` instead.
377
1164
  *
378
1165
  * Returns `undefined` when the order is not found (already filled, cancelled, or the
@@ -382,54 +1169,164 @@ export declare class VelocityClient {
382
1169
  /**
383
1170
  * Look up an open order by the caller-supplied `userOrderId` from the cached user account.
384
1171
  *
385
- * `userOrderId` is a 1-255 slot chosen by the caller in {@link OrderParams} and is stable
1172
+ * `userOrderId` is a 1-255 slot chosen by the caller in `OrderParams` and is stable
386
1173
  * across the life of the order — useful when you need to reference an order before the
387
- * program-assigned {@link Order.orderId} is known (e.g. immediately after placing without
388
- * waiting for confirmation). Use {@link getOrder} when you have the program-assigned ID.
1174
+ * program-assigned `Order.orderId` is known (e.g. immediately after placing without
1175
+ * waiting for confirmation). Use `getOrder` when you have the program-assigned ID.
389
1176
  *
390
1177
  * Returns `undefined` when the order is not found (already filled, cancelled, or the
391
1178
  * account cache is stale).
392
1179
  */
393
1180
  getOrderByUserId(userOrderId: number, subAccountId?: number): Order | undefined;
394
1181
  /**
395
- * Get the associated token address for the given spot market
396
- * @param marketIndex
397
- * @param useNative
398
- * @param tokenProgram
1182
+ * Resolves the token account to use for a spot market's mint. For the wrapped-SOL market with
1183
+ * `useNative = true` (the default), returns `authority` itself (native SOL, no wrapping) rather
1184
+ * than an SPL associated token account; for every other market (or `useNative = false`), returns
1185
+ * the derived associated token account address (not guaranteed to exist on-chain — see
1186
+ * `getAssociatedTokenAccountCreationIx`).
1187
+ * @param marketIndex - Spot market index whose mint the token account is for.
1188
+ * @param useNative - If `true` (default) and the market is wrapped SOL, return `authority` directly
1189
+ * instead of an ATA.
1190
+ * @param tokenProgram - Token program the mint belongs to; defaults to the classic SPL Token program.
1191
+ * @param authority - Wallet the token account belongs to; defaults to `this.wallet.publicKey`.
1192
+ * @param allowOwnerOffCurve - Passed through to `getAssociatedTokenAddress`; set `true` for PDA owners.
1193
+ * @returns The resolved token account address (or `authority`, for native SOL).
399
1194
  */
400
1195
  getAssociatedTokenAccount(marketIndex: number, useNative?: boolean, tokenProgram?: PublicKey, authority?: PublicKey, allowOwnerOffCurve?: boolean): Promise<PublicKey>;
1196
+ /**
1197
+ * Builds an `CreateIdempotent` associated-token-account instruction (creates `account` if it
1198
+ * doesn't already exist; no-ops without failing if it does), constructed manually rather than via
1199
+ * `@solana/spl-token`'s helper.
1200
+ * @param account - Associated token account address to create.
1201
+ * @param payer - Pays for the account creation; must sign the transaction.
1202
+ * @param owner - Token account owner.
1203
+ * @param mint - Mint the token account is for.
1204
+ * @param tokenProgram - Token program the mint belongs to; defaults to the classic SPL Token program.
1205
+ * @returns The `CreateIdempotent` instruction.
1206
+ */
401
1207
  createAssociatedTokenAccountIdempotentInstruction(account: PublicKey, payer: PublicKey, owner: PublicKey, mint: PublicKey, tokenProgram?: PublicKey): TransactionInstruction;
1208
+ /**
1209
+ * Builds the full instruction sequence for a deposit, without sending a transaction. If
1210
+ * `associatedTokenAccount` equals the signer and the market is wrapped SOL, transparently wraps
1211
+ * native SOL first (creates a temporary wrapped-SOL account funded with `amount`, deposits from it,
1212
+ * then closes it at the end of the same transaction, refunding rent to the signer) — otherwise
1213
+ * deposits directly from `associatedTokenAccount`.
1214
+ * @param amount - Amount to deposit, in the spot market's own token precision (`10^mint.decimals`).
1215
+ * @param marketIndex - Spot market index to deposit into.
1216
+ * @param associatedTokenAccount - Source token account (or the signer's own pubkey, for native SOL).
1217
+ * @param subAccountId - Sub-account id to credit; defaults to `this.activeSubAccountId`.
1218
+ * @param reduceOnly - If `true`, the deposit is capped so it cannot flip/increase a net borrow
1219
+ * position beyond what's needed to reach zero (used to repay a borrow without over-depositing).
1220
+ * @param overrides.authority - Signer/depositor authority; defaults to `this.wallet.publicKey`.
1221
+ * @returns The ordered list of instructions (wrap SOL, deposit, unwrap SOL as applicable).
1222
+ */
402
1223
  getDepositTxnIx(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, overrides?: {
403
1224
  authority?: PublicKey;
404
1225
  }): Promise<TransactionInstruction[]>;
1226
+ /**
1227
+ * Builds (but does not send) a single transaction that deposits collateral and then places a
1228
+ * pre-signed SignedMsg ("swift") taker perp order in one atomic bundle — useful for funding a new
1229
+ * or under-collateralized account immediately before submitting an off-chain-signed order.
1230
+ * Optionally also initializes the taker's `SignedMsgUserOrders` account (with 8 order slots) first,
1231
+ * if it doesn't already exist.
1232
+ * @param signedOrderParams - The pre-signed SignedMsg order message/params to place.
1233
+ * @param takerInfo - Taker's user/user-stats accounts, loaded `UserAccount` data, and the signing
1234
+ * authority for the order message.
1235
+ * @param depositAmount - Amount to deposit, in `depositSpotMarketIndex`'s token precision.
1236
+ * @param depositSpotMarketIndex - Spot market index to deposit into.
1237
+ * @param tradePerpMarketIndex - Perp market index the signed order trades.
1238
+ * @param subAccountId - Sub-account id to deposit into and place the order for.
1239
+ * @param takerAssociatedTokenAccount - Source token account for the deposit.
1240
+ * @param initSwiftAccount - If `true`, initializes the taker's `SignedMsgUserOrders` account first
1241
+ * when it doesn't already exist; defaults to `false`.
1242
+ * @returns Nothing — currently discards the built transaction rather than returning or sending it
1243
+ * (likely a bug: the built `VersionedTransaction`/`Transaction` from `buildTransaction` is neither
1244
+ * returned nor passed to `sendTransaction`).
1245
+ */
405
1246
  buildSwiftDepositTx(signedOrderParams: SignedMsgOrderParams, takerInfo: {
406
1247
  taker: PublicKey;
407
1248
  takerStats: PublicKey;
408
1249
  takerUserAccount: UserAccount;
409
1250
  signingAuthority: PublicKey;
410
1251
  }, depositAmount: BN, depositSpotMarketIndex: number, tradePerpMarketIndex: number, subAccountId: number, takerAssociatedTokenAccount: PublicKey, initSwiftAccount?: boolean): Promise<void>;
1252
+ /**
1253
+ * Builds (via `getDepositTxnIx`) and wraps a full deposit transaction, without sending it.
1254
+ * Optionally also initializes the depositor's `SignedMsgUserOrders` account first, if it doesn't
1255
+ * already exist. Forces `computeUnits` to `800_000` regardless of `txParams`/`this.txParams`.
1256
+ * @param amount - Amount to deposit, in the spot market's own token precision.
1257
+ * @param marketIndex - Spot market index to deposit into.
1258
+ * @param associatedTokenAccount - Source token account (or the signer's own pubkey, for native SOL).
1259
+ * @param subAccountId - Sub-account id to credit; defaults to `this.activeSubAccountId`.
1260
+ * @param reduceOnly - If `true`, caps the deposit so it cannot exceed what's needed to zero out an
1261
+ * existing borrow.
1262
+ * @param txParams - Optional compute-unit-price/other overrides; `computeUnits` is always
1263
+ * overridden to `800_000`.
1264
+ * @param initSwiftAccount - If `true`, initializes the signer's `SignedMsgUserOrders` account first
1265
+ * when it doesn't already exist; defaults to `false`.
1266
+ * @param overrides.authority - Signer/depositor authority; defaults to `this.wallet.publicKey`.
1267
+ * @returns The built (unsigned/unsent) transaction.
1268
+ */
411
1269
  createDepositTxn(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, txParams?: TxParams, initSwiftAccount?: boolean, overrides?: {
412
1270
  authority?: PublicKey;
413
1271
  }): Promise<VersionedTransaction | Transaction>;
414
1272
  /**
415
- * Deposit funds into the given spot market
416
- *
417
- * @param amount to deposit
418
- * @param marketIndex spot market index to deposit into
419
- * @param associatedTokenAccount can be the wallet public key if using native sol
420
- * @param subAccountId subaccountId to deposit
421
- * @param reduceOnly if true, deposit must not increase account risk
422
- * @param txParams transaction parameters
423
- * @param initSwiftAccount if true, initialize a swift account for the user
424
- * @param overrides allows overriding authority for the deposit transaction
1273
+ * Deposits collateral into a spot market for a sub-account: builds (`createDepositTxn`), signs, and
1274
+ * sends the transaction, then caches the confirming slot for this market so subsequent instructions
1275
+ * built by this client can use the freshest oracle/market data.
1276
+ * @param amount - Amount to deposit, in the spot market's own token precision (`10^mint.decimals`,
1277
+ * e.g. QUOTE_PRECISION (1e6) for USDC).
1278
+ * @param marketIndex - Spot market index to deposit into.
1279
+ * @param associatedTokenAccount - Source token account; can be the wallet's own public key when
1280
+ * depositing native SOL into the wrapped-SOL market (see `getAssociatedTokenAccount`).
1281
+ * @param subAccountId - Sub-account id to credit; defaults to `this.activeSubAccountId`.
1282
+ * @param reduceOnly - If `true`, caps the deposit so it cannot exceed what's needed to fully repay
1283
+ * an existing borrow (never opens/increases a deposit position); defaults to `false`.
1284
+ * @param txParams - Optional transaction parameters; `computeUnits` is always forced to `800_000`.
1285
+ * @param initSwiftAccount - If `true`, also initializes the signer's `SignedMsgUserOrders` account
1286
+ * first if it doesn't exist; defaults to `false`.
1287
+ * @param overrides.authority - Signer/depositor authority; defaults to `this.wallet.publicKey`.
1288
+ * @returns The transaction signature.
1289
+ * @throws (on-chain) if the sub-account's `poolId` doesn't match the spot market's pool, the market
1290
+ * is uninitialized/paused for deposits, or `amount` is `0`.
425
1291
  */
426
1292
  deposit(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, txParams?: TxParams, initSwiftAccount?: boolean, overrides?: {
427
1293
  authority?: PublicKey;
428
1294
  }): Promise<TransactionSignature>;
1295
+ /**
1296
+ * Builds the raw `deposit` instruction (no SOL-wrapping helpers — see `getDepositTxnIx` for the
1297
+ * full sequence). Assembles `remaining_accounts` from the target sub-account's current positions
1298
+ * (forcing a fresh fetch when `userInitialized` is `true`) plus the market's mint and, if the mint
1299
+ * uses a transfer hook, its extra account metas.
1300
+ * @param amount - Amount to deposit, in the spot market's own token precision.
1301
+ * @param marketIndex - Spot market index to deposit into.
1302
+ * @param userTokenAccount - Source token account for the deposit.
1303
+ * @param subAccountId - Sub-account id to credit; defaults to `this.activeSubAccountId`.
1304
+ * @param reduceOnly - If `true`, caps the deposit at what's needed to repay an existing borrow.
1305
+ * @param userInitialized - Set `false` only when depositing as part of creating a brand-new user
1306
+ * account in the same transaction (skips fetching/using existing position data).
1307
+ * @param overrides.authority - Signer/depositor authority; defaults to `this.wallet.publicKey`.
1308
+ * @returns The `deposit` instruction.
1309
+ * @throws if `userInitialized` is `true` but the user account fails to load after a forced fetch.
1310
+ */
429
1311
  getDepositInstruction(amount: BN, marketIndex: number, userTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, userInitialized?: boolean, overrides?: {
430
1312
  authority?: PublicKey;
431
1313
  }): Promise<TransactionInstruction>;
432
1314
  private checkIfAccountExists;
1315
+ /**
1316
+ * Builds the instructions to create and fund a temporary wrapped-SOL token account (via
1317
+ * `createAccountWithSeed` + `initializeAccount`, no keypair required — derived deterministically
1318
+ * from `authority` and a random seed). The caller is responsible for closing it after use (see the
1319
+ * `createCloseAccountInstruction` pattern in `getDepositTxnIx`).
1320
+ * @param amount - Lamport amount to wrap (native SOL to make available as wrapped SOL).
1321
+ * @param includeRent - If `true`, funds the account with `amount` plus an extra
1322
+ * `LAMPORTS_PER_SOL / 100` (0.01 SOL) rent buffer; if falsy, funds with only the rent buffer (no
1323
+ * `amount`).
1324
+ * @param overrides.authority - Owner/payer of the wrapped-SOL account; defaults to
1325
+ * `this.wallet.publicKey`.
1326
+ * @returns `ixs` (create + initialize instructions), `pubkey` (the new wrapped-SOL account
1327
+ * address), and `signers` (always empty — no keypair signature is needed for a seed-derived
1328
+ * account).
1329
+ */
433
1330
  getWrappedSolAccountCreationIxs(amount: BN, includeRent?: boolean, overrides?: {
434
1331
  authority?: PublicKey;
435
1332
  }): Promise<{
@@ -438,12 +1335,84 @@ export declare class VelocityClient {
438
1335
  signers: Signer[];
439
1336
  pubkey: PublicKey;
440
1337
  }>;
1338
+ /**
1339
+ * Returns the correct SPL token program (classic or Token-2022) for a spot market's mint, based on
1340
+ * its `tokenProgramFlag`.
1341
+ * @param spotMarketAccount - Spot market whose mint's token program is needed.
1342
+ * @returns `TOKEN_2022_PROGRAM_ID` or `TOKEN_PROGRAM_ID`.
1343
+ */
441
1344
  getTokenProgramForSpotMarket(spotMarketAccount: SpotMarketAccount): PublicKey;
1345
+ /**
1346
+ * Checks whether a spot market's mint belongs to the Token-2022 program.
1347
+ * @param spotMarketAccount - Spot market to check.
1348
+ * @returns `true` if the market's `tokenProgramFlag` has the `Token2022` bit set.
1349
+ */
442
1350
  isToken2022(spotMarketAccount: SpotMarketAccount): boolean;
1351
+ /**
1352
+ * Checks whether a spot market's mint has a Token-2022 transfer hook, requiring extra account
1353
+ * metas to be appended on any instruction that moves its tokens.
1354
+ * @param spotMarketAccount - Spot market to check.
1355
+ * @returns `true` if the market's `tokenProgramFlag` has the `TransferHook` bit set.
1356
+ */
443
1357
  isTransferHook(spotMarketAccount: SpotMarketAccount): boolean;
1358
+ /**
1359
+ * Appends a spot market's mint as a read-only remaining account, but only when the mint is
1360
+ * Token-2022 (the classic SPL Token program doesn't need the mint passed for transfers). No-op for
1361
+ * classic SPL Token mints.
1362
+ * @param spotMarketAccount - Spot market whose mint may need to be included.
1363
+ * @param remainingAccounts - Array mutated in place by appending the mint account meta, if needed.
1364
+ */
444
1365
  addTokenMintToRemainingAccounts(spotMarketAccount: SpotMarketAccount, remainingAccounts: AccountMeta[]): void;
1366
+ /**
1367
+ * Resolves and appends the Token-2022 transfer-hook program's extra required account metas for a
1368
+ * mint. Required on any instruction transferring tokens for a mint where `isTransferHook` is `true`
1369
+ * (e.g. deposits/withdrawals/transfers involving that market).
1370
+ * @param mint - Transfer-hook mint to resolve extra accounts for.
1371
+ * @param remainingAccounts - Array mutated in place by appending the resolved extra account metas.
1372
+ */
445
1373
  addExtraAccountMetasToRemainingAccounts(mint: PublicKey, remainingAccounts: AccountMeta[]): Promise<void>;
1374
+ /**
1375
+ * Builds a (non-idempotent) instruction to create an associated token account owned by
1376
+ * `this.wallet.publicKey`, paid for by `this.wallet.publicKey`.
1377
+ * @param tokenMintAddress - Mint the associated token account is for.
1378
+ * @param associatedTokenAddress - Associated token account address to create.
1379
+ * @param tokenProgram - Token program the mint belongs to.
1380
+ * @returns The create-associated-token-account instruction.
1381
+ */
446
1382
  getAssociatedTokenAccountCreationIx(tokenMintAddress: PublicKey, associatedTokenAddress: PublicKey, tokenProgram: PublicKey): TransactionInstruction;
1383
+ /**
1384
+ * Builds the full instruction sequence to create a new sub-account and fund it with an initial
1385
+ * deposit in one transaction, without sending it. Handles: initializing `UserStats` (for
1386
+ * `subAccountId === 0`) and the `SignedMsgUserOrders` account if missing, wrapping native SOL when
1387
+ * depositing/donating SOL, creating the depositor's associated token account for Token-2022 mints
1388
+ * if it doesn't exist, sourcing the deposit either from a token account or (if `fromSubAccountId` is
1389
+ * given) via an internal transfer from another of the authority's sub-accounts, an optional donation
1390
+ * to the market's revenue pool, an optional custom margin ratio, and unwrapping any temporary SOL
1391
+ * account at the end.
1392
+ * @param amount - Amount to deposit, in `marketIndex`'s token precision.
1393
+ * @param userTokenAccount - Source token account for the deposit (ignored if `fromSubAccountId` is
1394
+ * set, or replaced with a temporary wrapped-SOL account for a SOL deposit from the depositor).
1395
+ * @param marketIndex - Spot market index to deposit into; defaults to `0` (quote/USDC).
1396
+ * @param subAccountId - New sub-account id to create; defaults to `0`.
1397
+ * @param name - Display name for the new sub-account; see `getInitializeUserAccountIxs` for the
1398
+ * default.
1399
+ * @param fromSubAccountId - If set, sources the deposit via an internal transfer from this other
1400
+ * sub-account of the same authority instead of from `userTokenAccount`.
1401
+ * @param referrerInfo - Referrer's `referrer`/`referrerStats` public keys, if attributing this
1402
+ * account to a referrer.
1403
+ * @param donateAmount - Additional lamport amount to donate to spot market index `1`'s (SOL's, in
1404
+ * the default market configs) revenue pool in the same transaction, funded via a temporary
1405
+ * wrapped-SOL account regardless of `marketIndex`; defaults to none. Note the destination market for
1406
+ * the donation is hardcoded to index `1`, not derived from `marketIndex`.
1407
+ * @param customMaxMarginRatio - If set, also sets this sub-account's custom margin ratio (in
1408
+ * `MARGIN_PRECISION`, 1e4 = 100%) at creation time.
1409
+ * @param poolId - If set, also assigns the sub-account to this isolated pool at creation time.
1410
+ * @param overrides.externalWallet - Optional external wallet to deposit/pay from instead of
1411
+ * `this.wallet.publicKey` (the sub-account's owning `authority` is unaffected).
1412
+ * @returns The ordered instructions and the new user account's public key.
1413
+ * @throws if a SOL/donation amount requires a temporary wrapped-SOL account but it fails to be
1414
+ * created.
1415
+ */
447
1416
  createInitializeUserAccountAndDepositCollateralIxs(amount: BN, userTokenAccount: PublicKey, marketIndex?: number, subAccountId?: number, name?: string, fromSubAccountId?: number, referrerInfo?: ReferrerInfo, donateAmount?: BN, customMaxMarginRatio?: number, poolId?: number, overrides?: {
448
1417
  /**
449
1418
  * Optional external wallet to deposit from. If provided, the deposit will be made
@@ -454,74 +1423,461 @@ export declare class VelocityClient {
454
1423
  ixs: TransactionInstruction[];
455
1424
  userAccountPublicKey: PublicKey;
456
1425
  }>;
1426
+ /**
1427
+ * Builds (via `createInitializeUserAccountAndDepositCollateralIxs`) and wraps the full
1428
+ * initialize-and-deposit transaction, without sending it. See that method for parameter semantics.
1429
+ * @returns The built (unsigned/unsent) transaction and the new user account's public key.
1430
+ */
457
1431
  createInitializeUserAccountAndDepositCollateral(amount: BN, userTokenAccount: PublicKey, marketIndex?: number, subAccountId?: number, name?: string, fromSubAccountId?: number, referrerInfo?: ReferrerInfo, donateAmount?: BN, txParams?: TxParams, customMaxMarginRatio?: number, poolId?: number, overrides?: {
458
1432
  externalWallet?: PublicKey;
459
1433
  }): Promise<[Transaction | VersionedTransaction, PublicKey]>;
460
1434
  /**
461
- * Creates the User account for a user, and deposits some initial collateral
462
- * @param amount
463
- * @param userTokenAccount
464
- * @param marketIndex
465
- * @param subAccountId
466
- * @param name
467
- * @param fromSubAccountId
468
- * @param referrerInfo
469
- * @param donateAmount
470
- * @param txParams
471
- * @param customMaxMarginRatio
472
- * @param poolId
1435
+ * Creates a new sub-account and deposits initial collateral into it in a single transaction, then
1436
+ * loads and subscribes the new sub-account via `addUser`. See
1437
+ * `createInitializeUserAccountAndDepositCollateralIxs` for full parameter semantics.
1438
+ * @param amount - Amount to deposit, in `marketIndex`'s token precision.
1439
+ * @param userTokenAccount - Source token account for the deposit.
1440
+ * @param marketIndex - Spot market index to deposit into; defaults to `0` (quote/USDC).
1441
+ * @param subAccountId - New sub-account id to create; defaults to `0`.
1442
+ * @param name - Display name for the new sub-account.
1443
+ * @param fromSubAccountId - If set, sources the deposit via internal transfer from this sub-account
1444
+ * instead of `userTokenAccount`.
1445
+ * @param referrerInfo - Referrer's `referrer`/`referrerStats` public keys, if applicable.
1446
+ * @param donateAmount - Additional amount to donate to the (hardcoded index `1`) revenue pool.
1447
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1448
+ * @param customMaxMarginRatio - If set, custom margin ratio in `MARGIN_PRECISION` (1e4 = 100%).
1449
+ * @param poolId - If set, isolated pool id to assign the sub-account to at creation time.
473
1450
  * @param overrides - Optional overrides including externalWallet for depositing from a different wallet
474
- * @returns
1451
+ * @returns A tuple of `[transactionSignature, userAccountPublicKey]`.
475
1452
  */
476
1453
  initializeUserAccountAndDepositCollateral(amount: BN, userTokenAccount: PublicKey, marketIndex?: number, subAccountId?: number, name?: string, fromSubAccountId?: number, referrerInfo?: ReferrerInfo, donateAmount?: BN, txParams?: TxParams, customMaxMarginRatio?: number, poolId?: number, overrides?: {
477
1454
  externalWallet?: PublicKey;
478
1455
  }): Promise<[TransactionSignature, PublicKey]>;
1456
+ /**
1457
+ * Devnet/test-only convenience: mints test tokens from a `TokenFaucet` into a fresh associated
1458
+ * token account, then creates a new sub-account and deposits the minted amount, all in one
1459
+ * transaction. Not usable on mainnet (no faucet exists there).
1460
+ * @param subAccountId - New sub-account id to create; defaults to `0`.
1461
+ * @param name - Display name for the new sub-account; defaults to `DEFAULT_USER_NAME`.
1462
+ * @param marketIndex - Spot market index to deposit the minted tokens into.
1463
+ * @param tokenFaucet - Faucet client used to mint test tokens.
1464
+ * @param amount - Amount to mint and deposit, in `marketIndex`'s token precision.
1465
+ * @param referrerInfo - Referrer's `referrer`/`referrerStats` public keys, if applicable.
1466
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1467
+ * @returns A tuple of `[transactionSignature, userAccountPublicKey]`.
1468
+ */
479
1469
  initializeUserAccountForDevnet(subAccountId: number | undefined, name: string | undefined, marketIndex: number, tokenFaucet: TokenFaucet, amount: BN, referrerInfo?: ReferrerInfo, txParams?: TxParams): Promise<[TransactionSignature, PublicKey]>;
1470
+ /**
1471
+ * Builds the full instruction sequence for a withdrawal, without sending a transaction. If
1472
+ * `associatedTokenAddress` equals the signer and the market is wrapped SOL, creates a temporary
1473
+ * wrapped-SOL account to receive the withdrawal and closes it (unwrapping to native SOL) at the end
1474
+ * of the same transaction; otherwise, creates the destination associated token account first if it
1475
+ * doesn't already exist.
1476
+ * @param amount - Amount to withdraw, in the spot market's own token precision.
1477
+ * @param marketIndex - Spot market index to withdraw from.
1478
+ * @param associatedTokenAddress - Destination token account (or the signer's own pubkey, for native
1479
+ * SOL).
1480
+ * @param reduceOnly - If `true`, caps the withdrawal at the sub-account's existing deposit (and the
1481
+ * max amount withdrawable while remaining within margin requirements) so it can never flip the
1482
+ * position into a borrow; defaults to `false`.
1483
+ * @param subAccountId - Sub-account id to withdraw from; defaults to `this.activeSubAccountId`.
1484
+ * @returns The ordered list of instructions (create ATA / wrap SOL, withdraw, unwrap SOL as
1485
+ * applicable).
1486
+ */
480
1487
  getWithdrawalIxs(amount: BN, marketIndex: number, associatedTokenAddress: PublicKey, reduceOnly?: boolean, subAccountId?: number): Promise<TransactionInstruction[]>;
481
1488
  /**
482
- * Withdraws from a user account. If deposit doesn't already exist, creates a borrow
483
- * @param amount
484
- * @param marketIndex
1489
+ * Withdraws from a user account. If deposit doesn't already exist, creates a borrow (or increases an
1490
+ * existing one) — unless `reduceOnly` is set. Always requires the sub-account's true owning
1491
+ * authority to sign (`this.wallet.publicKey`); a delegate cannot withdraw at all, even with
1492
+ * `allowDelegateTransfer` enabled.
1493
+ * @param amount - Amount to withdraw, in the spot market's own token precision (`10^mint.decimals`,
1494
+ * e.g. QUOTE_PRECISION (1e6) for USDC).
1495
+ * @param marketIndex - Spot market index to withdraw from.
485
1496
  * @param associatedTokenAddress - the token account to withdraw to. can be the wallet public key if using native sol
486
- * @param reduceOnly
1497
+ * @param reduceOnly - If `true`, caps the withdrawal so it can never open/increase a borrow; the
1498
+ * on-chain amount is clamped to `min(requested, max withdrawable within margin, existing deposit)`.
1499
+ * @param subAccountId - Sub-account id to withdraw from; defaults to `this.activeSubAccountId`.
1500
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1501
+ * @returns The transaction signature.
1502
+ * @throws (on-chain `ReduceOnlyWithdrawIncreasedRisk`) if `reduceOnly` is set but the sub-account's
1503
+ * position in this market is already a borrow (nothing to reduce).
487
1504
  */
488
1505
  withdraw(amount: BN, marketIndex: number, associatedTokenAddress: PublicKey, reduceOnly?: boolean, subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
1506
+ /**
1507
+ * Fully withdraws every spot market position on a sub-account too small to be worth carrying
1508
+ * ("dust", as determined by `User.getSpotMarketAccountsWithDustPosition`), in one transaction. Each
1509
+ * withdrawal requests 2x the current token amount with `reduceOnly = true` so the on-chain clamp
1510
+ * (see `withdraw`) withdraws exactly the full balance without risking a borrow, regardless of
1511
+ * balance drift between calculation and execution.
1512
+ * @param subAccountId - Sub-account id to sweep; defaults to `this.activeSubAccountId`.
1513
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1514
+ * @param opts.dustPositionCountCallback - Called once with the number of dust positions found
1515
+ * (`0` if none), before building/sending the transaction.
1516
+ * @returns The transaction signature, or `undefined` if there were no dust positions to withdraw.
1517
+ */
489
1518
  withdrawAllDustPositions(subAccountId?: number, txParams?: TxParams, opts?: {
490
1519
  dustPositionCountCallback?: (count: number) => void;
491
1520
  }): Promise<TransactionSignature | undefined>;
492
- getWithdrawIx(amount: BN, marketIndex: number, userTokenAccount: PublicKey, reduceOnly?: boolean, subAccountId?: number): Promise<TransactionInstruction>;
493
1521
  /**
494
- * Withdraws from the fromSubAccount and deposits into the toSubAccount
495
- * @param amount
496
- * @param marketIndex
497
- * @param fromSubAccountId
498
- * @param toSubAccountId
499
- * @param txParams
1522
+ * Builds the raw `withdraw` instruction (no SOL-wrapping/ATA-creation helpers — see
1523
+ * `getWithdrawalIxs` for the full sequence). Signed by `this.wallet.publicKey`, which must be the
1524
+ * sub-account's true owning authority (delegates cannot withdraw).
1525
+ * @param amount - Amount to withdraw, in the spot market's own token precision.
1526
+ * @param marketIndex - Spot market index to withdraw from.
1527
+ * @param userTokenAccount - Destination token account for the withdrawal.
1528
+ * @param reduceOnly - If `true`, caps the withdrawal so it can never open/increase a borrow.
1529
+ * @param subAccountId - Sub-account id to withdraw from; defaults to `this.activeSubAccountId`.
1530
+ * @returns The `withdraw` instruction.
1531
+ */
1532
+ getWithdrawIx(amount: BN, marketIndex: number, userTokenAccount: PublicKey, reduceOnly?: boolean, subAccountId?: number, overrides?: {
1533
+ authority?: PublicKey;
1534
+ }): Promise<TransactionInstruction>;
1535
+ /**
1536
+ * Transfers a spot balance directly between two sub-accounts owned by `this.wallet.publicKey`
1537
+ * (withdraws from `fromSubAccountId`, deposits into `toSubAccountId`) without leaving the program —
1538
+ * no token account round-trip. Signed by `this.wallet.publicKey`, which must literally be the
1539
+ * `authority` on *both* sub-accounts (this is the owner-to-owner path; a delegate must use
1540
+ * `transferDepositByDelegate` instead).
1541
+ * @param amount - Amount to transfer, in the spot market's own token precision.
1542
+ * @param marketIndex - Spot market index of the balance to transfer.
1543
+ * @param fromSubAccountId - Sub-account id to debit.
1544
+ * @param toSubAccountId - Sub-account id to credit.
1545
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1546
+ * @returns The transaction signature.
1547
+ * @throws (on-chain `UserBankrupt`) if either sub-account is bankrupt, or
1548
+ * (`CantTransferBetweenSameUserAccount`) if `fromSubAccountId === toSubAccountId`.
500
1549
  */
501
1550
  transferDeposit(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, txParams?: TxParams): Promise<TransactionSignature>;
1551
+ /**
1552
+ * Builds the `transferDeposit` instruction. See `transferDeposit` for semantics/preconditions.
1553
+ * Uses an already-loaded `from` sub-account's cached data if available (to build
1554
+ * `remaining_accounts` from its current positions); otherwise fetches it directly via RPC.
1555
+ * @param amount - Amount to transfer, in the spot market's own token precision.
1556
+ * @param marketIndex - Spot market index of the balance to transfer.
1557
+ * @param fromSubAccountId - Sub-account id to debit.
1558
+ * @param toSubAccountId - Sub-account id to credit.
1559
+ * @returns The instruction.
1560
+ */
502
1561
  getTransferDepositIx(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number): Promise<TransactionInstruction>;
503
- transferDepositByDelegate(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, txParams?: TxParams): Promise<TransactionSignature>;
504
- getTransferDepositByDelegateIx(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number): Promise<TransactionInstruction>;
1562
+ /**
1563
+ * Like `transferDeposit`, but signed by a *delegate* (`this.wallet.publicKey`) rather than the
1564
+ * sub-accounts' owning authority. On-chain requires all of:
1565
+ * - the owner has opted in via `updateUserAllowDelegateTransfer(true)` on their `UserStats` — the
1566
+ * transfer is rejected outright otherwise, regardless of delegate status on the sub-accounts;
1567
+ * - `this.wallet.publicKey` is set as the `delegate` on **both** `fromSubAccountId` and
1568
+ * `toSubAccountId` (see `updateUserDelegate`) — a delegate for only one side is not sufficient;
1569
+ * - both sub-accounts share the same owning `authority` (this only moves funds within one owner's
1570
+ * sub-accounts, never across different owners);
1571
+ * - neither sub-account is bankrupt, and `fromSubAccountId !== toSubAccountId`.
1572
+ * @param amount - Amount to transfer, in the spot market's own token precision.
1573
+ * @param marketIndex - Spot market index of the balance to transfer.
1574
+ * @param fromSubAccountId - Sub-account id to debit.
1575
+ * @param toSubAccountId - Sub-account id to credit.
1576
+ * @param equityFloorDelta - Equity floor (QUOTE_PRECISION) to move from the debited to the credited
1577
+ * sub-account along with the funds, keeping the sum of floors constant. The debited side must stay
1578
+ * at/above its reduced floor and the credited side's collateral (after the transfer lands) must back
1579
+ * its increased floor, else the transfer reverts with `InvalidEquityFloorTransfer`. Pass `'auto'`
1580
+ * (quote market only) to move the minimal floor needed for the debited side to stay at/above its
1581
+ * floor: `max(0, amount - (collateral - floor))`, capped at the debited side's floor. The auto delta
1582
+ * never exceeds `amount`, so the credited side stays backed whenever it was before. Client-side
1583
+ * pricing can differ slightly from the on-chain strict check at the exact boundary; retry with an
1584
+ * explicit padded delta if an `'auto'` transfer reverts. Defaults to zero.
1585
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1586
+ * @returns The transaction signature.
1587
+ * @throws (on-chain) if `allowDelegateTransfer` is not enabled, if the signer is not the delegate on
1588
+ * both sub-accounts, if the sub-accounts have different owners, if either is bankrupt, or if
1589
+ * `fromSubAccountId === toSubAccountId`.
1590
+ */
1591
+ transferDepositByDelegate(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, equityFloorDelta?: BN | 'auto', txParams?: TxParams): Promise<TransactionSignature>;
1592
+ /**
1593
+ * Builds the `transferDepositByDelegate` instruction. See `transferDepositByDelegate` for the full
1594
+ * set of on-chain preconditions. Uses an already-loaded `from` sub-account's cached data if
1595
+ * available; otherwise fetches it directly via RPC. Sub-accounts are derived under `this.authority`
1596
+ * (the sub-accounts' owner), not `this.wallet.publicKey` (the delegate signer).
1597
+ * @param amount - Amount to transfer, in the spot market's own token precision.
1598
+ * @param marketIndex - Spot market index of the balance to transfer.
1599
+ * @param fromSubAccountId - Sub-account id to debit.
1600
+ * @param toSubAccountId - Sub-account id to credit.
1601
+ * @returns The instruction.
1602
+ */
1603
+ getTransferDepositByDelegateIx(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, equityFloorDelta?: BN | 'auto'): Promise<TransactionInstruction>;
1604
+ /**
1605
+ * Moves a deposit balance and/or a borrow balance for the same underlying mint between two
1606
+ * sub-accounts owned by `this.wallet.publicKey` that sit in *different* isolated pools, in one
1607
+ * on-chain instruction (`transferPools`). Unlike `transferDeposit` (which only moves a single spot
1608
+ * balance and requires same-pool markets), this requires: `depositFromMarketIndex`/
1609
+ * `depositToMarketIndex` to share a mint but different `poolId`s, `borrowFromMarketIndex`/
1610
+ * `borrowToMarketIndex` to likewise share a mint but different pool ids, and the deposit-from/
1611
+ * borrow-from markets to share `fromSubAccountId`'s pool while the deposit-to/borrow-to markets
1612
+ * share `toSubAccountId`'s pool. Both sub-accounts must be re-validated against their initial
1613
+ * margin requirement after the move.
1614
+ * @param depositFromMarketIndex - Spot market to debit the deposit leg from.
1615
+ * @param depositToMarketIndex - Spot market to credit the deposit leg to (same mint, different pool).
1616
+ * @param borrowFromMarketIndex - Spot market to credit (repay) the borrow leg from.
1617
+ * @param borrowToMarketIndex - Spot market to debit (re-open) the borrow leg on.
1618
+ * @param depositAmount - Deposit amount to move, in the deposit market's token precision;
1619
+ * `undefined`/omitted moves the entire existing deposit token amount; `0` skips the deposit leg
1620
+ * entirely.
1621
+ * @param borrowAmount - Borrow amount to move, in the borrow market's token precision; `undefined`
1622
+ * moves the entire existing borrow token amount; `0` skips the borrow leg entirely.
1623
+ * @param fromSubAccountId - Sub-account id to debit.
1624
+ * @param toSubAccountId - Sub-account id to credit.
1625
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1626
+ * @returns The transaction signature.
1627
+ * @throws (on-chain `InvalidPoolId`) if the mint/pool relationships above don't hold, or
1628
+ * (`UserBankrupt`/`CantTransferBetweenSameUserAccount`) for the same preconditions as `transferDeposit`.
1629
+ */
505
1630
  transferPools(depositFromMarketIndex: number, depositToMarketIndex: number, borrowFromMarketIndex: number, borrowToMarketIndex: number, depositAmount: BN | undefined, borrowAmount: BN | undefined, fromSubAccountId: number, toSubAccountId: number, txParams?: TxParams): Promise<TransactionSignature>;
1631
+ /**
1632
+ * Builds the `transferPools` instruction. See `transferPools` for full semantics/preconditions.
1633
+ * @param depositFromMarketIndex - Spot market to debit the deposit leg from.
1634
+ * @param depositToMarketIndex - Spot market to credit the deposit leg to.
1635
+ * @param borrowFromMarketIndex - Spot market to credit (repay) the borrow leg from.
1636
+ * @param borrowToMarketIndex - Spot market to debit (re-open) the borrow leg on.
1637
+ * @param depositAmount - Deposit amount to move, in the deposit market's token precision;
1638
+ * `undefined` moves the entire deposit, `0` skips the deposit leg.
1639
+ * @param borrowAmount - Borrow amount to move, in the borrow market's token precision; `undefined`
1640
+ * moves the entire borrow, `0` skips the borrow leg.
1641
+ * @param fromSubAccountId - Sub-account id to debit.
1642
+ * @param toSubAccountId - Sub-account id to credit.
1643
+ * @param isToNewSubAccount - If `true`, skips including `toSubAccountId`'s current `UserAccount` data
1644
+ * when building `remaining_accounts` (use when `toSubAccountId` is being created in the same
1645
+ * transaction and has no on-chain data yet).
1646
+ * @returns The instruction.
1647
+ */
506
1648
  getTransferPoolsIx(depositFromMarketIndex: number, depositToMarketIndex: number, borrowFromMarketIndex: number, borrowToMarketIndex: number, depositAmount: BN | undefined, borrowAmount: BN | undefined, fromSubAccountId: number, toSubAccountId: number, isToNewSubAccount?: boolean): Promise<TransactionInstruction>;
1649
+ /**
1650
+ * Moves all or part of an open perp position from one sub-account to another via the
1651
+ * `transferPerpPosition` instruction, settling funding on both sides first. The signer
1652
+ * (`this.wallet.publicKey`) must independently satisfy `can_sign_for_user` (be the owning
1653
+ * `authority` or the sub-account's `delegate`) on *both* `fromSubAccountId` and `toSubAccountId` —
1654
+ * unlike `transferDepositByDelegate`, there is no separate `allowDelegateTransfer` opt-in gate, and
1655
+ * the two sub-accounts are not required to share the same owning authority.
1656
+ * @param fromSubAccountId - Sub-account id to debit the position from.
1657
+ * @param toSubAccountId - Sub-account id to credit the position to.
1658
+ * @param marketIndex - Perp market index of the position to transfer.
1659
+ * @param amount - Signed base amount to transfer, in `BASE_PRECISION` (1e9). Must have the same sign
1660
+ * as `fromSubAccountId`'s existing position (i.e. it only reduces/closes that position, never
1661
+ * flips it) and a magnitude at most the position's size and a multiple of the market's step size;
1662
+ * pass `undefined` to transfer the entire position.
1663
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1664
+ * @returns The transaction signature.
1665
+ * @throws (on-chain `UserBankrupt`/`CantTransferBetweenSameUserAccount`) for the standard transfer
1666
+ * preconditions, or `InvalidTransferPerpPosition` if the oracle is invalid, fills are paused for
1667
+ * `marketIndex`, `amount`'s sign/magnitude/step-size don't satisfy the constraints above, or
1668
+ * `fromSubAccountId` has no position in `marketIndex`.
1669
+ */
507
1670
  transferPerpPosition(fromSubAccountId: number, toSubAccountId: number, marketIndex: number, amount: BN, txParams?: TxParams): Promise<TransactionSignature>;
1671
+ /**
1672
+ * Builds the `transferPerpPosition` instruction. See `transferPerpPosition` for full semantics.
1673
+ * @param fromSubAccountId - Sub-account id to debit the position from.
1674
+ * @param toSubAccountId - Sub-account id to credit the position to.
1675
+ * @param marketIndex - Perp market index of the position to transfer.
1676
+ * @param amount - Signed base amount to transfer, in `BASE_PRECISION` (1e9); `undefined`/`null`
1677
+ * transfers the entire position. See `transferPerpPosition` for sign/magnitude constraints.
1678
+ * @returns The instruction.
1679
+ */
508
1680
  getTransferPerpPositionIx(fromSubAccountId: number, toSubAccountId: number, marketIndex: number, amount: BN): Promise<TransactionInstruction>;
1681
+ /**
1682
+ * Special-account-only: transfers all or part of a position on the protocol's designated "vAMM
1683
+ * hedger" account directly into the AMM's own inventory, offsetting the vAMM's synthetic position.
1684
+ * On-chain requires `userAccountPublicKey`'s `specialUserStatus` to be `VammHedger`, the position's
1685
+ * direction to already be opposite the AMM's net inventory (`amm.baseAssetAmountWithAmm`), and the
1686
+ * transferred amount to fit within the AMM's available capacity for that direction. Not usable on a
1687
+ * regular trading sub-account.
1688
+ * @param userAccountPublicKey - The vAMM-hedger `User` PDA to transfer from; must already be loaded
1689
+ * in `this.users` (see `getUsers`).
1690
+ * @param marketIndex - Perp market index of the position to transfer.
1691
+ * @param amount - Signed base amount to transfer, in `BASE_PRECISION` (1e9), matching the position's
1692
+ * sign and capped at its size and a multiple of the market's step size; omit to transfer the entire
1693
+ * position.
1694
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1695
+ * @returns The transaction signature.
1696
+ * @throws (on-chain) if the account isn't a `VammHedger`, has no (or a same-direction-as-AMM)
1697
+ * position in `marketIndex`, or `amount` fails the sign/magnitude/step-size/AMM-capacity checks.
1698
+ */
509
1699
  specialTransferPerpPositionToVamm(userAccountPublicKey: PublicKey, marketIndex: number, amount?: BN, txParams?: TxParams): Promise<TransactionSignature>;
1700
+ /**
1701
+ * Builds the `specialTransferPerpPositionToVamm` instruction. See
1702
+ * `specialTransferPerpPositionToVamm` for full semantics/preconditions.
1703
+ * @param userAccountPublicKey - The vAMM-hedger `User` PDA to transfer from.
1704
+ * @param marketIndex - Perp market index of the position to transfer.
1705
+ * @param amount - Signed base amount to transfer, in `BASE_PRECISION` (1e9); omit to transfer the
1706
+ * entire position.
1707
+ * @returns The instruction.
1708
+ * @throws if `userAccountPublicKey` isn't among `this.getUsers()`.
1709
+ */
510
1710
  getSpecialTransferPerpPositionToVammIx(userAccountPublicKey: PublicKey, marketIndex: number, amount?: BN): Promise<TransactionInstruction>;
1711
+ /**
1712
+ * Deposits collateral from a token account directly into an isolated perp position's own segregated
1713
+ * balance (as opposed to `deposit`, which credits the sub-account's general/cross balance). The
1714
+ * position's quote spot market is derived from `perpMarketIndex`'s `quoteSpotMarketIndex`.
1715
+ * @param amount - Amount to deposit, in the position's quote spot market's token precision.
1716
+ * @param perpMarketIndex - Perp market index of the isolated position to fund.
1717
+ * @param userTokenAccount - Source token account for the deposit.
1718
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1719
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1720
+ * @returns The transaction signature.
1721
+ * @throws (on-chain `InvalidPoolId`) if the sub-account's pool doesn't match the spot/perp markets'.
1722
+ */
511
1723
  depositIntoIsolatedPerpPosition(amount: BN, perpMarketIndex: number, userTokenAccount: PublicKey, subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
1724
+ /**
1725
+ * Builds the `depositIntoIsolatedPerpPosition` instruction. See `depositIntoIsolatedPerpPosition` for
1726
+ * semantics.
1727
+ * @param amount - Amount to deposit, in the position's quote spot market's token precision.
1728
+ * @param perpMarketIndex - Perp market index of the isolated position to fund.
1729
+ * @param userTokenAccount - Source token account for the deposit.
1730
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1731
+ * @returns The instruction.
1732
+ */
512
1733
  getDepositIntoIsolatedPerpPositionIx(amount: BN, perpMarketIndex: number, userTokenAccount: PublicKey, subAccountId?: number): Promise<TransactionInstruction>;
1734
+ /**
1735
+ * Moves collateral between an isolated perp position's segregated balance and the sub-account's
1736
+ * general/cross balance, in the same underlying quote spot market (derived from `perpMarketIndex`).
1737
+ * Positive `amount` moves collateral **from general into the isolated position**; negative moves it
1738
+ * **from the isolated position back to general**. If the requested outflow from the isolated
1739
+ * position would exceed its current deposit (i.e. it needs unrealized PnL to be realized first, or
1740
+ * the caller wants to withdraw everything), prepends a `TRY_SETTLE` settle-PnL instruction for
1741
+ * `perpMarketIndex` before the transfer.
1742
+ * @param amount - Signed amount to move, in the quote spot market's token precision (e.g.
1743
+ * QUOTE_PRECISION (1e6) for USDC); positive = into the isolated position, negative = out of it. Pass
1744
+ * `MIN_I64` to move the entire isolated deposit back to general.
1745
+ * @param perpMarketIndex - Perp market index of the isolated position.
1746
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1747
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1748
+ * @param trySettle - If `true`, always prepends the `TRY_SETTLE` instruction even if not otherwise
1749
+ * inferred as necessary.
1750
+ * @param noBuffer - If `true`, sends `amount` unmodified; otherwise (default) adds a 0.5% buffer to
1751
+ * the requested amount to absorb price movement between build and execution. Has no effect when
1752
+ * `amount` is `MIN_I64`.
1753
+ * @returns The transaction signature. Sent with `skipPreflight: true`.
1754
+ */
513
1755
  transferIsolatedPerpPositionDeposit(amount: BN, perpMarketIndex: number, subAccountId?: number, txParams?: TxParams, trySettle?: boolean, noBuffer?: boolean): Promise<TransactionSignature>;
1756
+ /**
1757
+ * Builds the `transferIsolatedPerpPositionDeposit` instruction (without the `TRY_SETTLE` prepend —
1758
+ * see `transferIsolatedPerpPositionDeposit` for the full sequence). See that method for the
1759
+ * sign/precision convention of `amount`.
1760
+ * @param amount - Signed amount to move, in the quote spot market's token precision; positive = into
1761
+ * the isolated position, negative = out. Pass `MIN_I64` to move the entire isolated deposit out.
1762
+ * @param perpMarketIndex - Perp market index of the isolated position.
1763
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1764
+ * @param noAmountBuffer - If `true`, sends `amount` unmodified; otherwise adds a 0.5% buffer
1765
+ * (ignored when `amount` is `MIN_I64`).
1766
+ * @param signingAuthority - Signer for the instruction; defaults to `this.wallet.publicKey`.
1767
+ * @returns The instruction.
1768
+ */
514
1769
  getTransferIsolatedPerpPositionDepositIx(amount: BN, perpMarketIndex: number, subAccountId?: number, noAmountBuffer?: boolean, signingAuthority?: PublicKey): Promise<TransactionInstruction>;
1770
+ /**
1771
+ * Withdraws collateral out of the protocol directly from an isolated perp position's segregated
1772
+ * balance to a token account (as opposed to `withdraw`, which draws from the sub-account's
1773
+ * general/cross balance). See `getWithdrawFromIsolatedPerpPositionIxsBundle` for the settle-PnL and
1774
+ * amount-clamping logic applied first.
1775
+ * @param amount - Amount to withdraw, in the position's quote spot market's token precision.
1776
+ * @param perpMarketIndex - Perp market index of the isolated position to withdraw from.
1777
+ * @param userTokenAccount - Destination token account for the withdrawal.
1778
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1779
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1780
+ * @returns The transaction signature.
1781
+ */
515
1782
  withdrawFromIsolatedPerpPosition(amount: BN, perpMarketIndex: number, userTokenAccount: PublicKey, subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
1783
+ /**
1784
+ * Builds the full instruction sequence for `withdrawFromIsolatedPerpPosition`: computes the position's
1785
+ * claimable unrealized PnL, and clamps `amount` to the isolated deposit plus that claimable PnL —
1786
+ * the on-chain `amount` is `u64` with no "withdraw all" sentinel (unlike the sibling
1787
+ * `transferIsolatedPerpPositionDeposit`, whose `i64` `amount` treats `i64::MIN` as one), so passing
1788
+ * `BN` values larger than the withdrawable balance is how a caller requests "withdraw everything".
1789
+ * Also prepends a `TRY_SETTLE` settle-PnL instruction for `perpMarketIndex` whenever the request
1790
+ * draws into unrealized (unsettled) PnL. Note the clamp is a build-time estimate: if the settle
1791
+ * realizes less than the claimable PnL (e.g. the market's PnL pool is short), the withdraw can still
1792
+ * fail on-chain with `InsufficientCollateral`.
1793
+ * @param amount - Amount to withdraw, in the position's quote spot market's token precision. Values
1794
+ * exceeding the withdrawable balance are clamped to it (i.e. pass a huge value to withdraw all).
1795
+ * @param perpMarketIndex - Perp market index of the isolated position to withdraw from.
1796
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1797
+ * @param userTokenAccount - Destination token account; defaults to the signer's own associated token
1798
+ * account for the position's quote spot market.
1799
+ * @returns The ordered instructions (optional settle-PnL, then withdraw).
1800
+ * @throws if `subAccountId` has no perp position in `perpMarketIndex`, or if the position has no
1801
+ * withdrawable collateral (deposit plus claimable PnL is zero or negative).
1802
+ */
516
1803
  getWithdrawFromIsolatedPerpPositionIxsBundle(amount: BN, perpMarketIndex: number, subAccountId?: number, userTokenAccount?: PublicKey): Promise<TransactionInstruction[]>;
1804
+ /**
1805
+ * Builds the raw `withdrawFromIsolatedPerpPosition` instruction (no settle-PnL/clamping — see
1806
+ * `getWithdrawFromIsolatedPerpPositionIxsBundle` for the full sequence).
1807
+ * @param amount - Amount to withdraw, in the position's quote spot market's token precision.
1808
+ * The on-chain `amount` arg is `u64` (unsigned) with no "withdraw all" sentinel — the exact amount
1809
+ * is withdrawn, and it must not exceed the isolated position's token balance. Use
1810
+ * `getWithdrawFromIsolatedPerpPositionIxsBundle` for withdraw-all/clamping behavior.
1811
+ * @param perpMarketIndex - Perp market index of the isolated position to withdraw from.
1812
+ * @param userTokenAccount - Destination token account for the withdrawal.
1813
+ * @param subAccountId - Sub-account id owning the position; defaults to `this.activeSubAccountId`.
1814
+ * @returns The instruction.
1815
+ */
517
1816
  getWithdrawFromIsolatedPerpPositionIx(amount: BN, perpMarketIndex: number, userTokenAccount: PublicKey, subAccountId?: number): Promise<TransactionInstruction>;
1817
+ /**
1818
+ * Permissionless crank: forces a spot market to accrue interest (updating
1819
+ * `cumulativeDepositInterest`/`cumulativeBorrowInterest` and TWAP stats) up to the current slot. The
1820
+ * instruction's accounts impose no authority/hot-role check beyond the transaction fee payer —
1821
+ * anyone can call this to keep a market's interest current between organic deposit/withdraw/borrow
1822
+ * activity.
1823
+ * @param marketIndex - Spot market index to update.
1824
+ * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1825
+ * @returns The transaction signature.
1826
+ */
518
1827
  updateSpotMarketCumulativeInterest(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
1828
+ /**
1829
+ * Builds the `updateSpotMarketCumulativeInterest` instruction. See
1830
+ * `updateSpotMarketCumulativeInterest` for semantics.
1831
+ * @param marketIndex - Spot market index to update.
1832
+ * @returns The instruction.
1833
+ */
519
1834
  updateSpotMarketCumulativeInterestIx(marketIndex: number): Promise<TransactionInstruction>;
520
1835
  /**
521
- * @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
1836
+ * Opens/increases a perp position with a market order (or a limit order if `limitPrice` is
1837
+ * given), filled immediately against the AMM/makers via `placeAndTakePerpOrder`.
1838
+ * @deprecated use `placePerpOrder` or `placeAndTakePerpOrder` instead.
1839
+ * @param direction - `LONG` or `SHORT`.
1840
+ * @param amount - Base asset amount to trade, BASE_PRECISION (1e9).
1841
+ * @param marketIndex - Perp market index.
1842
+ * @param limitPrice - Optional limit price, PRICE_PRECISION (1e6); omit for a pure market order.
1843
+ * @param subAccountId - Sub-account to trade from; defaults to the active sub-account.
1844
+ * @returns The transaction signature.
522
1845
  */
523
1846
  openPosition(direction: PositionDirection, amount: BN, marketIndex: number, limitPrice?: BN, subAccountId?: number): Promise<TransactionSignature>;
1847
+ /**
1848
+ * Submits and confirms a transaction that has already been fully signed elsewhere (e.g. by an
1849
+ * external/hardware wallet flow), skipping this client's normal build-and-sign step entirely. Not
1850
+ * order/instruction-specific — works for any pre-signed `Transaction`/`VersionedTransaction`.
1851
+ * @param tx - The already-signed transaction to send.
1852
+ * @param opts - Confirmation options; defaults to `this.opts`.
1853
+ * @returns The transaction signature.
1854
+ */
524
1855
  sendSignedTx(tx: Transaction | VersionedTransaction, opts?: ConfirmOptions): Promise<TransactionSignature>;
1856
+ /**
1857
+ * Builds (without sending) the set of transactions needed to place a market order and,
1858
+ * for legacy (non-versioned) transactions, a companion transaction that fills it against
1859
+ * the AMM. Also builds optional companion transactions to cancel the market's existing
1860
+ * orders first and/or settle PnL after the fill. Used by `sendMarketOrderAndGetSignedFillTx`.
1861
+ * @param orderParams - Order to place; `orderParams.baseAssetAmount` is BASE_PRECISION (1e9)
1862
+ * for perp (token-mint precision for spot), `orderParams.price` is PRICE_PRECISION (1e6).
1863
+ * @param userAccountPublicKey - Public key of the placing user account (used for the
1864
+ * post-fill settle-PnL instruction).
1865
+ * @param userAccount - Decoded user account; supplies `subAccountId` and `nextOrderId`.
1866
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
1867
+ * @param txParams - Optional compute-unit/priority-fee overrides applied to all built transactions.
1868
+ * @param bracketOrdersParams - Additional orders (e.g. TP/SL) placed in the same transaction as the market order.
1869
+ * @param cancelExistingOrders - If `true` and `orderParams.marketType` is perp, also builds a
1870
+ * transaction cancelling all existing open orders in that market — intended for auto-cancelling
1871
+ * TP/SL orders when closing a position. Ignored for spot.
1872
+ * @param settlePnl - If `true` and `orderParams.marketType` is perp, also builds a
1873
+ * settle-PnL transaction for `orderParams.marketIndex`.
1874
+ * @param positionMaxLev - If set, prepends an instruction to set a custom max-leverage margin
1875
+ * ratio (`MARGIN_PRECISION`, 1e4, derived as `1 / positionMaxLev`) for the position before placing.
1876
+ * @param isolatedPositionDepositAmount - If set and the order increases the position, prepends a
1877
+ * transfer-into-isolated-position deposit instruction (token-mint precision) before placing.
1878
+ * @returns An object with `marketOrderTx` (always present) and optional `cancelExistingOrdersTx`,
1879
+ * `settlePnlTx`, `fillTx` (only built when `this.txVersion === 0`, i.e. legacy transactions).
1880
+ */
525
1881
  prepareMarketOrderTxs(orderParams: OptionalOrderParams, userAccountPublicKey: PublicKey, userAccount: UserAccount, makerInfo?: MakerInfo | MakerInfo[], txParams?: TxParams, bracketOrdersParams?: OptionalOrderParams[], cancelExistingOrders?: boolean, settlePnl?: boolean, positionMaxLev?: number, isolatedPositionDepositAmount?: BN): Promise<{
526
1882
  cancelExistingOrdersTx?: Transaction | VersionedTransaction;
527
1883
  settlePnlTx?: Transaction | VersionedTransaction;
@@ -529,15 +1885,24 @@ export declare class VelocityClient {
529
1885
  marketOrderTx: Transaction | VersionedTransaction;
530
1886
  }>;
531
1887
  /**
532
- * Sends a market order and returns a signed tx which can fill the order against the vamm, which the caller can use to fill their own order if required.
533
- * @param orderParams
534
- * @param userAccountPublicKey
535
- * @param userAccount
536
- * @param makerInfo
537
- * @param txParams
538
- * @param bracketOrdersParams
539
- * @param cancelExistingOrders - Builds and returns an extra transaciton to cancel the existing orders in the same perp market. Intended use is to auto-cancel TP/SL orders when closing a position. Ignored if orderParams.marketType is not MarketType.PERP
540
- * @returns
1888
+ * Sends a market order transaction and, for legacy (non-versioned) transactions, also returns
1889
+ * a co-signed fill transaction the caller can broadcast themselves to fill the order against
1890
+ * the AMM (useful when the caller wants to control fill timing/submission rather than relying
1891
+ * on a keeper). Internally builds transactions via `prepareMarketOrderTxs`, signs them all, then
1892
+ * sends only `marketOrderTx`.
1893
+ * @param orderParams - Order to place; `baseAssetAmount` is BASE_PRECISION (1e9) for perp
1894
+ * (token-mint precision for spot), `price` is PRICE_PRECISION (1e6).
1895
+ * @param userAccountPublicKey - Public key of the placing user account.
1896
+ * @param userAccount - Decoded user account; supplies `subAccountId` and `nextOrderId`.
1897
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
1898
+ * @param txParams - Optional compute-unit/priority-fee overrides.
1899
+ * @param bracketOrdersParams - Additional orders (e.g. TP/SL) placed alongside the market order.
1900
+ * @param cancelExistingOrders - Builds and returns an extra transaction to cancel the existing orders in the same perp market. Intended use is to auto-cancel TP/SL orders when closing a position. Ignored if orderParams.marketType is not MarketType.PERP.
1901
+ * @param settlePnl - If `true` and the order is a perp order, also builds and returns a signed settle-PnL transaction for the order's market.
1902
+ * @returns `txSig` for the sent market-order transaction, plus `signedFillTx` (only when
1903
+ * `this.txVersion === 0`), `signedCancelExistingOrdersTx`, and `signedSettlePnlTx` — each
1904
+ * `undefined` when not applicable/requested. None of the returned side transactions are sent;
1905
+ * the caller must broadcast them.
541
1906
  */
542
1907
  sendMarketOrderAndGetSignedFillTx(orderParams: OptionalOrderParams, userAccountPublicKey: PublicKey, userAccount: UserAccount, makerInfo?: MakerInfo | MakerInfo[], txParams?: TxParams, bracketOrdersParams?: OptionalOrderParams[], cancelExistingOrders?: boolean, settlePnl?: boolean): Promise<{
543
1908
  txSig: TransactionSignature;
@@ -545,6 +1910,20 @@ export declare class VelocityClient {
545
1910
  signedCancelExistingOrdersTx?: Transaction;
546
1911
  signedSettlePnlTx?: Transaction;
547
1912
  }>;
1913
+ /**
1914
+ * Places a single perp order without attempting to fill it in the same instruction — the
1915
+ * order rests until a keeper (or a `placeAndTake*`/signed-msg fill) matches it. Use
1916
+ * `placeAndTakePerpOrder` instead if the caller wants an immediate attempt to fill against
1917
+ * the AMM/makers.
1918
+ * @param orderParams - Order to place; `baseAssetAmount` is BASE_PRECISION (1e9), `price` /
1919
+ * `triggerPrice` / `oraclePriceOffset` (signed) / `auctionStartPrice` / `auctionEndPrice` are
1920
+ * PRICE_PRECISION (1e6).
1921
+ * @param txParams - Optional compute-unit/priority-fee overrides.
1922
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
1923
+ * @param isolatedPositionDepositAmount - If set and the order increases the position, a transfer
1924
+ * into an isolated-margin position (token-mint precision) is prepended in the same transaction.
1925
+ * @returns The transaction signature.
1926
+ */
548
1927
  placePerpOrder(orderParams: OptionalOrderParams, txParams?: TxParams, subAccountId?: number, isolatedPositionDepositAmount?: BN): Promise<TransactionSignature>;
549
1928
  /**
550
1929
  * Returns the RevenueShareEscrow account meta for the placing user when `orderParams`
@@ -564,15 +1943,58 @@ export declare class VelocityClient {
564
1943
  * Throws when `takerEscrow` does not belong to `takerAuthority`.
565
1944
  */
566
1945
  private getTakerEscrowAccountMeta;
1946
+ /**
1947
+ * Builds the `placePerpOrder` instruction. See `placePerpOrder` for semantics. Automatically
1948
+ * attaches the placing user's `RevenueShareEscrow` account when `orderParams` carries a
1949
+ * builder code (`builderIdx`/`builderFeeTenthBps`).
1950
+ * @param orderParams - Order to place; see `placePerpOrder` for field precisions.
1951
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
1952
+ * @param depositToTradeArgs - Pass when composing this instruction ahead of the user account
1953
+ * actually existing on-chain yet (e.g. deposit-to-trade in the same transaction as account
1954
+ * creation): `isMakingNewAccount` skips loading the (not-yet-existing) user account for
1955
+ * `remainingAccounts`, and `depositMarketIndex` marks the deposit's spot market as readable.
1956
+ * @returns The instruction.
1957
+ */
567
1958
  getPlacePerpOrderIx(orderParams: OptionalOrderParams, subAccountId?: number, depositToTradeArgs?: {
568
1959
  isMakingNewAccount: boolean;
569
1960
  depositMarketIndex: number;
570
1961
  }): Promise<TransactionInstruction>;
571
1962
  updateAMMs(marketIndexes: number[], txParams?: TxParams): Promise<TransactionSignature>;
572
1963
  getUpdateAMMsIx(marketIndexes: number[]): Promise<TransactionInstruction>;
1964
+ /**
1965
+ * Admin instruction: finalizes settlement pricing for a perp market that has already been put
1966
+ * into `Settlement` status (`market.status === MarketStatus.SETTLEMENT`), snapping the market's
1967
+ * settlement price/oracle-twap so every position can subsequently be closed at that fixed price
1968
+ * via `settlePNL`. Requires a warm- or cold-tier admin signer (`check_warm`).
1969
+ * @param marketIndex - Perp market index to settle.
1970
+ * @param txParams - Optional compute-unit/priority-fee overrides.
1971
+ * @returns The transaction signature.
1972
+ */
573
1973
  settleExpiredMarket(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
1974
+ /**
1975
+ * Builds the `settleExpiredMarket` instruction. See `settleExpiredMarket` for semantics. Signs
1976
+ * with `this.wallet.publicKey` when not subscribed, or the state's `coldAdmin` when subscribed —
1977
+ * the on-chain constraint accepts either a warm- or cold-tier admin, so passing `coldAdmin`
1978
+ * always satisfies it regardless of which tier the actual signer holds.
1979
+ * @param marketIndex - Perp market index to settle.
1980
+ * @returns The instruction.
1981
+ */
574
1982
  getSettleExpiredMarketIx(marketIndex: number): Promise<TransactionInstruction>;
1983
+ /**
1984
+ * Admin instruction: sweeps a settled (`MarketStatus.SETTLEMENT`) perp market's remaining fee
1985
+ * pool and PnL pool balances into the quote spot market's revenue pool, once all user positions
1986
+ * in the market have been settled out. Requires a warm- or cold-tier admin signer.
1987
+ * @param marketIndex - Perp market index to sweep.
1988
+ * @param txParams - Optional compute-unit/priority-fee overrides.
1989
+ * @returns The transaction signature.
1990
+ */
575
1991
  settleExpiredMarketPoolsToRevenuePool(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
1992
+ /**
1993
+ * Builds the `settleExpiredMarketPoolsToRevenuePool` instruction. See
1994
+ * `settleExpiredMarketPoolsToRevenuePool` for semantics.
1995
+ * @param perpMarketIndex - Perp market index to sweep.
1996
+ * @returns The instruction.
1997
+ */
576
1998
  getSettleExpiredMarketPoolsToRevenuePoolIx(perpMarketIndex: number): Promise<TransactionInstruction>;
577
1999
  /**
578
2000
  * Cancel an open order and broadcast the transaction.
@@ -586,7 +2008,15 @@ export declare class VelocityClient {
586
2008
  * is also provided, `getOrder` will return `undefined` (the ID is unknown client-side),
587
2009
  * causing the withdraw path to throw — supply an explicit `orderId` in that case.
588
2010
  *
589
- * @see {@link getCancelOrderIx} to obtain the instruction without sending.
2011
+ * @param orderId - Program-assigned order ID to cancel; omit to cancel the most recently
2012
+ * placed order (resolved on-chain via `get_last_order_id`).
2013
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2014
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
2015
+ * @param overrides.withdrawIsolatedDepositAmount - If set and > 0, appends an isolated-margin
2016
+ * withdrawal (token-mint precision) for the cancelled order's market in the same transaction;
2017
+ * requires an explicit `orderId` (see note above).
2018
+ * @returns The transaction signature.
2019
+ * @see `getCancelOrderIx` to obtain the instruction without sending.
590
2020
  */
591
2021
  cancelOrder(orderId?: number, txParams?: TxParams, subAccountId?: number, overrides?: {
592
2022
  withdrawIsolatedDepositAmount?: BN;
@@ -603,19 +2033,43 @@ export declare class VelocityClient {
603
2033
  *
604
2034
  * When `orderId` is supplied, only that specific order is cancelled.
605
2035
  *
606
- * @see {@link cancelOrder} to send the transaction directly.
607
- * @see {@link getCancelOrderByUserIdIx} to cancel by the caller-supplied `userOrderId`.
2036
+ * @param orderId - Program-assigned order ID to cancel; omit (or `undefined`) to cancel the
2037
+ * most recently placed order.
2038
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
2039
+ * @returns The instruction.
2040
+ * @see `cancelOrder` to send the transaction directly.
2041
+ * @see `getCancelOrderByUserIdIx` to cancel by the caller-supplied `userOrderId`.
608
2042
  */
609
2043
  getCancelOrderIx(orderId?: number, subAccountId?: number): Promise<TransactionInstruction>;
2044
+ /**
2045
+ * Cancel an open order identified by its caller-supplied `userOrderId` and broadcast the
2046
+ * transaction.
2047
+ * @param userOrderId - Caller-chosen order slot (set via `OrderParams.userOrderId` at placement).
2048
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2049
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
2050
+ * @returns The transaction signature.
2051
+ * @see `getCancelOrderByUserIdIx` to obtain the instruction without sending.
2052
+ */
610
2053
  cancelOrderByUserId(userOrderId: number, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
2054
+ /**
2055
+ * Builds the `cancelOrderByUserId` instruction. See `cancelOrderByUserId` for semantics.
2056
+ * @param userOrderId - Caller-chosen order slot (set via `OrderParams.userOrderId` at placement).
2057
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
2058
+ * @throws If no open order with `userOrderId` is found in the cached user account (looked up
2059
+ * client-side to resolve the order's market/oracle for `remainingAccounts`).
2060
+ * @returns The instruction.
2061
+ * @see `getCancelOrderIx` to cancel by the program-assigned order ID instead.
2062
+ */
611
2063
  getCancelOrderByUserIdIx(userOrderId: number, subAccountId?: number): Promise<TransactionInstruction>;
612
2064
  /**
613
2065
  * Sends a transaction to cancel the provided order ids.
614
2066
  *
615
- * @param orderIds - The order ids to cancel.
2067
+ * @param orderIds - Program-assigned order IDs to cancel; an order ID that no longer exists is
2068
+ * silently skipped. `undefined` sends an empty list on-chain, i.e. cancels nothing.
616
2069
  * @param txParams - The transaction parameters.
617
2070
  * @param subAccountId - The sub account id to cancel the orders for.
618
2071
  * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
2072
+ * @param overrides.authority - Signing authority to use instead of `this.wallet.publicKey`.
619
2073
  * @returns The transaction signature.
620
2074
  */
621
2075
  cancelOrdersByIds(orderIds?: number[], txParams?: TxParams, subAccountId?: number, user?: User, overrides?: {
@@ -624,67 +2078,254 @@ export declare class VelocityClient {
624
2078
  /**
625
2079
  * Returns the transaction instruction to cancel the provided order ids.
626
2080
  *
627
- * @param orderIds - The order ids to cancel.
2081
+ * @param orderIds - Program-assigned order IDs to cancel; an order ID that no longer exists is
2082
+ * silently skipped. `undefined` sends an empty list on-chain, i.e. cancels nothing.
628
2083
  * @param subAccountId - The sub account id to cancel the orders for.
629
2084
  * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
2085
+ * @param overrides.authority - Signing authority to use instead of `this.wallet.publicKey`.
630
2086
  * @returns The transaction instruction to cancel the orders.
631
2087
  */
632
2088
  getCancelOrdersByIdsIx(orderIds?: number[], subAccountId?: number, user?: User, overrides?: {
633
2089
  authority?: PublicKey;
634
2090
  }): Promise<TransactionInstruction>;
2091
+ /**
2092
+ * Cancel all of a user's open orders matching the given (optional) filters, and broadcast the
2093
+ * transaction. Any filter left `undefined` is not applied — calling with no filters cancels
2094
+ * every open order on the sub-account.
2095
+ * @param marketType - Only cancel orders of this market type (`PERP`/`SPOT`); combined with
2096
+ * `marketIndex` to scope to one perp or spot market.
2097
+ * @param marketIndex - Only cancel orders in this market index.
2098
+ * @param direction - Only cancel orders on this side (`LONG`/`SHORT`).
2099
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2100
+ * @param subAccountId - Sub-account to cancel orders for; defaults to the active sub-account.
2101
+ * @returns The transaction signature.
2102
+ * @see `getCancelOrdersIx` to obtain the instruction without sending.
2103
+ */
635
2104
  cancelOrders(marketType?: MarketType, marketIndex?: number, direction?: PositionDirection, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
2105
+ /**
2106
+ * Builds the `cancelOrders` instruction. See `cancelOrders` for filter semantics (`null`/`undefined`
2107
+ * on any of `marketType`/`marketIndex`/`direction` means "don't filter on that field").
2108
+ * @param marketType - Only cancel orders of this market type.
2109
+ * @param marketIndex - Only cancel orders in this market index.
2110
+ * @param direction - Only cancel orders on this side.
2111
+ * @param subAccountId - Sub-account to cancel orders for; defaults to the active sub-account.
2112
+ * @returns The instruction.
2113
+ */
636
2114
  getCancelOrdersIx(marketType: MarketType | null | undefined, marketIndex: number | null | undefined, direction: PositionDirection | null | undefined, subAccountId?: number): Promise<TransactionInstruction>;
2115
+ /**
2116
+ * Atomically cancels orders matching the given filters and places new orders in a single
2117
+ * transaction (cancel instruction first, then place). Useful for order replacement flows
2118
+ * (e.g. re-quoting) where the old orders must not be fillable in the gap before the new
2119
+ * ones land.
2120
+ * @param cancelOrderParams - Filters for which open orders to cancel; see `cancelOrders` for
2121
+ * semantics (`undefined` fields are not filtered on).
2122
+ * @param placeOrderParams - Orders to place after the cancel; `baseAssetAmount` is BASE_PRECISION
2123
+ * (1e9), `price`/`triggerPrice`/`oraclePriceOffset` are PRICE_PRECISION (1e6).
2124
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2125
+ * @param subAccountId - Sub-account to operate on; defaults to the active sub-account.
2126
+ * @returns The transaction signature.
2127
+ */
637
2128
  cancelAndPlaceOrders(cancelOrderParams: {
638
2129
  marketType?: MarketType;
639
2130
  marketIndex?: number;
640
2131
  direction?: PositionDirection;
641
2132
  }, placeOrderParams: OrderParams[], txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
2133
+ /**
2134
+ * Places a batch of orders (perp and/or spot) in a single instruction. None are filled
2135
+ * in-instruction — each rests until matched by a keeper or a subsequent fill/place-and-take.
2136
+ * @param params - Orders to place; `baseAssetAmount` is BASE_PRECISION (1e9) for perp
2137
+ * (token-mint precision for spot), `price`/`triggerPrice`/`oraclePriceOffset` are
2138
+ * PRICE_PRECISION (1e6).
2139
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2140
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2141
+ * @param optionalIxs - Extra instructions to prepend to the transaction.
2142
+ * @param isolatedPositionDepositAmount - If set and `params` has exactly one perp order that
2143
+ * increases the position, a transfer into an isolated-margin position (token-mint precision)
2144
+ * is prepended before placing. Ignored for batches of more than one order.
2145
+ * @returns The transaction signature.
2146
+ */
642
2147
  placeOrders(params: OrderParams[], txParams?: TxParams, subAccountId?: number, optionalIxs?: TransactionInstruction[], isolatedPositionDepositAmount?: BN): Promise<TransactionSignature>;
2148
+ /**
2149
+ * Builds (without sending) the `placeOrders` transaction. See `placeOrders` for semantics.
2150
+ * @param params - Orders to place; see `placeOrders` for field precisions.
2151
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2152
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2153
+ * @param optionalIxs - Extra instructions to prepend to the transaction.
2154
+ * @param isolatedPositionDepositAmount - See `placeOrders`; only applied when `params.length === 1`.
2155
+ * @returns An object with `placeOrdersTx`, the built (unsigned) transaction.
2156
+ */
643
2157
  preparePlaceOrdersTx(params: OrderParams[], txParams?: TxParams, subAccountId?: number, optionalIxs?: TransactionInstruction[], isolatedPositionDepositAmount?: BN): Promise<{
644
2158
  placeOrdersTx: Transaction | VersionedTransaction;
645
2159
  }>;
2160
+ /**
2161
+ * Builds the `placeOrders` instruction. See `placeOrders` for semantics. Attaches the placing
2162
+ * user's `RevenueShareEscrow` once (not per-order) when any order in the batch carries a
2163
+ * builder code — the on-chain handler expects a single escrow account for the whole batch.
2164
+ * @param params - Orders to place; every entry must set `marketType`. See `placeOrders` for
2165
+ * field precisions.
2166
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2167
+ * @param overrides - `authority` overrides the signing authority (defaults to `this.wallet.publicKey`).
2168
+ * @throws If any order in `params` omits `marketType`.
2169
+ * @returns The instruction.
2170
+ */
646
2171
  getPlaceOrdersIx(params: OptionalOrderParams[], subAccountId?: number, overrides?: {
647
2172
  authority?: PublicKey;
648
2173
  }): Promise<TransactionInstruction>;
2174
+ /**
2175
+ * Builds a `placeOrders` instruction followed by an instruction that sets a custom max-leverage
2176
+ * margin ratio on the position for `params[0]`'s market. Unlike `placeOrders`, this bypasses the
2177
+ * `RevenueShareEscrow` attachment for builder-coded orders (uses the raw `program.instruction`
2178
+ * call directly) — don't use it for batches containing a builder-coded order.
2179
+ * @param params - Orders to place; `baseAssetAmount` is BASE_PRECISION (1e9) for perp
2180
+ * (token-mint precision for spot), `price`/`triggerPrice`/`oraclePriceOffset` are PRICE_PRECISION (1e6).
2181
+ * @param positionMaxLev - Max leverage to apply to the position in `params[0].marketIndex`; converted
2182
+ * to a MARGIN_PRECISION (1e4) margin ratio as `1 / positionMaxLev`.
2183
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2184
+ * @returns A two-element array: `[placeOrdersIx, setPositionMaxLevIx]`.
2185
+ */
649
2186
  getPlaceOrdersAndSetPositionMaxLevIx(params: OptionalOrderParams[], positionMaxLev: number, subAccountId?: number): Promise<TransactionInstruction[]>;
650
2187
  /**
651
- * Place scale orders: multiple limit orders distributed across a price range
652
- * @param params Scale order parameters
653
- * @param txParams Optional transaction parameters
654
- * @param subAccountId Optional sub account ID
655
- * @returns Transaction signature
2188
+ * Places multiple limit orders (`params.orderCount`, 2-32) distributed across a price range
2189
+ * in a single instruction, none filled in-instruction — each rests until matched.
2190
+ * @param params - Scale order parameters: `totalBaseAssetAmount` is BASE_PRECISION (1e9),
2191
+ * `startPrice`/`endPrice` are PRICE_PRECISION (1e6); see `ScaleOrderParams` for the rest.
2192
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2193
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2194
+ * @returns The transaction signature.
656
2195
  */
657
2196
  placeScaleOrders(params: ScaleOrderParams, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
2197
+ /**
2198
+ * Builds (without sending) the `placeScaleOrders` transaction. See `placeScaleOrders` for semantics.
2199
+ * @param params - Scale order parameters; see `placeScaleOrders` for field precisions.
2200
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2201
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2202
+ * @returns An object with `placeScaleOrdersTx`, the built (unsigned) transaction.
2203
+ */
658
2204
  preparePlaceScaleOrdersTx(params: ScaleOrderParams, txParams?: TxParams, subAccountId?: number): Promise<{
659
2205
  placeScaleOrdersTx: Transaction | VersionedTransaction;
660
2206
  }>;
2207
+ /**
2208
+ * Builds the `placeScaleOrders` instruction. See `placeScaleOrders` for semantics.
2209
+ * @param params - Scale order parameters; see `placeScaleOrders` for field precisions.
2210
+ * @param subAccountId - Sub-account to place the orders for; defaults to the active sub-account.
2211
+ * @returns The instruction.
2212
+ */
661
2213
  getPlaceScaleOrdersIx(params: ScaleOrderParams, subAccountId?: number): Promise<TransactionInstruction>;
2214
+ /**
2215
+ * Keeper instruction that fills a resting DLOB perp order against one or more makers (or the
2216
+ * AMM/vAMM when no maker matches). Permissionless — any signer can act as filler and earns the
2217
+ * filler reward. Does not place or cancel orders itself; it only matches an order that is
2218
+ * already on the book.
2219
+ * @param userAccountPublicKey - Public key of the order owner's user account.
2220
+ * @param user - Decoded user account of the order owner.
2221
+ * @param order - The order to fill (`marketIndex`/`orderId`); defaults to the owner's most
2222
+ * recently placed order (`nextOrderId - 1`) when omitted.
2223
+ * @param makerInfo - Maker(s) to attempt to cross against; a single `MakerInfo` or an array.
2224
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2225
+ * @param fillerSubAccountId - Filler's sub-account to credit; defaults to the active sub-account.
2226
+ * @param fillerAuthority - Filler's authority, if different from this client's wallet (e.g.
2227
+ * filling on behalf of a delegated sub-account); the filler user/user-stats PDAs are derived
2228
+ * from this authority instead of `this.wallet.publicKey`.
2229
+ * @param hasBuilderFee - Force-attach the taker's `RevenueShareEscrow` account, bypassing the
2230
+ * automatic builder-code detection performed by `getFillPerpOrderIx`.
2231
+ * @param takerEscrow - The taker's decoded `RevenueShareEscrow`. Required whenever the order
2232
+ * carries a builder code or the taker is referred — the program rejects the fill if the escrow
2233
+ * is owed but not attached.
2234
+ * @returns The transaction signature.
2235
+ */
662
2236
  fillPerpOrder(userAccountPublicKey: PublicKey, user: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], txParams?: TxParams, fillerSubAccountId?: number, fillerAuthority?: PublicKey, hasBuilderFee?: boolean, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionSignature>;
663
- getFillPerpOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], fillerSubAccountId?: number, isSignedMsg?: boolean, fillerAuthority?: PublicKey, hasBuilderFee?: boolean, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionInstruction>;
2237
+ /**
2238
+ * Builds the `fillPerpOrder` instruction. See `fillPerpOrder` for semantics. Assembles maker
2239
+ * accounts and the taker's `RevenueShareEscrow` (when owed) into `remainingAccounts` in the
2240
+ * order the on-chain handler expects: user/maker market+oracle accounts first, then each
2241
+ * maker's `(maker, makerStats)` pair, then the taker escrow meta last.
2242
+ * @param userAccountPublicKey - Public key of the order owner's user account.
2243
+ * @param userAccount - Decoded user account of the order owner.
2244
+ * @param order - The order to fill (`marketIndex`/`orderId`); defaults to the owner's most
2245
+ * recently placed order when omitted and `isSignedMsg` is false.
2246
+ * @param makerInfo - Maker(s) to attempt to cross against.
2247
+ * @param fillerSubAccountId - Filler's sub-account to credit; defaults to the active sub-account.
2248
+ * @param isSignedMsg - Whether this fills a signed-msg (swift) order that has not yet been
2249
+ * placed on-chain; when true, `order` is not required and the builder-escrow attachment is
2250
+ * done optimistically (the order's builder flag cannot be inspected before it lands).
2251
+ * @param fillerAuthority - Filler's authority if different from this client's wallet; the
2252
+ * filler user/user-stats PDAs are derived from this authority.
2253
+ * @param hasBuilderFee - Force-attach the taker escrow regardless of the detected builder flag.
2254
+ * @param takerEscrow - The taker's decoded `RevenueShareEscrow`. Required to attach the escrow
2255
+ * when the order has a builder code or the taker is referred with an initialized escrow — the
2256
+ * on-chain handler rejects the fill if an owed escrow is missing from `remainingAccounts`.
2257
+ * @throws If no order can be resolved to fill, or (for a non-signed-msg fill) `order` is omitted.
2258
+ * @returns The instruction.
2259
+ */
2260
+ getFillPerpOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], fillerSubAccountId?: number, isSignedMsg?: boolean, fillerAuthority?: PublicKey, hasBuilderFee?: boolean, takerEscrow?: RevenueShareEscrowAccount, takerIsReferred?: boolean): Promise<TransactionInstruction>;
2261
+ /**
2262
+ * Builds the `revertFill` instruction. Used by keepers as a same-transaction fallback after a
2263
+ * simulated fill fails downstream (e.g. a subsequent instruction errors): it only asserts the
2264
+ * filler's `lastActiveSlot` equals the current slot and otherwise is a no-op, letting the
2265
+ * keeper's earlier fill CPI effects be discarded by the transaction failing cleanly rather than
2266
+ * with a confusing downstream error.
2267
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own
2268
+ * user account.
2269
+ * @returns The instruction.
2270
+ */
664
2271
  getRevertFillIx(fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2272
+ /**
2273
+ * Disabled. Spot DLOB trading (order placement/matching) is turned off in this deployment —
2274
+ * spot balances, deposits, withdrawals, and swaps remain available.
2275
+ * @throws Always throws with the spot-DLOB-disabled message.
2276
+ */
665
2277
  placeSpotOrder(_orderParams: OptionalOrderParams, _txParams?: TxParams, _subAccountId?: number): Promise<TransactionSignature>;
2278
+ /**
2279
+ * Disabled. See `placeSpotOrder`.
2280
+ * @throws Always throws with the spot-DLOB-disabled message.
2281
+ */
666
2282
  preparePlaceSpotOrderTx(_orderParams: OptionalOrderParams, _txParams?: TxParams, _subAccountId?: number): Promise<void>;
2283
+ /**
2284
+ * Disabled. See `placeSpotOrder`.
2285
+ * @throws Always throws with the spot-DLOB-disabled message.
2286
+ */
667
2287
  getPlaceSpotOrderIx(_orderParams: OptionalOrderParams, _subAccountId?: number, _overrides?: {
668
2288
  authority?: PublicKey;
669
2289
  }): Promise<TransactionInstruction>;
2290
+ /**
2291
+ * Disabled. See `placeSpotOrder`.
2292
+ * @throws Always throws with the spot-DLOB-disabled message.
2293
+ */
670
2294
  fillSpotOrder(_userAccountPublicKey: PublicKey, _user: UserAccount, _order?: Pick<Order, 'marketIndex' | 'orderId'>, _fulfillmentConfig?: unknown, _makerInfo?: MakerInfo | MakerInfo[], _txParams?: TxParams): Promise<TransactionSignature>;
2295
+ /**
2296
+ * Disabled. See `placeSpotOrder`.
2297
+ * @throws Always throws with the spot-DLOB-disabled message.
2298
+ */
671
2299
  getFillSpotOrderIx(_userAccountPublicKey: PublicKey, _userAccount: UserAccount, _order?: Pick<Order, 'marketIndex' | 'orderId'>, _fulfillmentConfig?: unknown, _makerInfo?: MakerInfo | MakerInfo[], _fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
672
2300
  /**
673
- * Swap tokens in velocity account using titan or jupiter
674
- * @param swapClient swap client to find routes and instructions (Titan or Jupiter)
675
- * @param jupiterClient @deprecated Use swapClient instead. Legacy parameter for backward compatibility
676
- * @param outMarketIndex the market index of the token you're buying
677
- * @param inMarketIndex the market index of the token you're selling
678
- * @param outAssociatedTokenAccount the token account to receive the token being sold on the swap provider
679
- * @param inAssociatedTokenAccount the token account to
680
- * @param amount the amount of TokenIn, regardless of swapMode
681
- * @param slippageBps the max slippage passed to the swap provider api
682
- * @param swapMode swap provider swapMode (ExactIn or ExactOut), default is ExactIn
683
- * @param route the swap provider route to use for the swap
684
- * @param reduceOnly specify if In or Out token on the velocity account must reduceOnly, checked at end of swap
685
- * @param v6 pass in the quote response from swap provider quote's API (deprecated, use quote instead)
686
- * @param quote pass in the quote response from swap provider quote's API
687
- * @param txParams
2301
+ * Swaps one spot-market token for another inside the user's velocity account: brackets the
2302
+ * external swap provider's instructions between the program's `beginSwap`/`endSwap`
2303
+ * instructions in a single transaction, so the swap is settled directly against the user's
2304
+ * deposits/vault balances rather than the wallet's own token accounts. Sends and confirms the
2305
+ * transaction.
2306
+ * @param swapClient - Swap client used to fetch routes/instructions (`UnifiedSwapClient` or a
2307
+ * `TitanClient`); dispatches to `getSwapIxV2` or `getTitanSwapIx` respectively.
2308
+ * @param jupiterClient - @deprecated Use `swapClient` instead. When passed (and `swapClient` is
2309
+ * not), dispatches to `getJupiterSwapIxV6`.
2310
+ * @param outMarketIndex - Spot market index of the token being bought.
2311
+ * @param inMarketIndex - Spot market index of the token being sold.
2312
+ * @param outAssociatedTokenAccount - Token account to receive the bought token; created
2313
+ * idempotently if omitted.
2314
+ * @param inAssociatedTokenAccount - Token account to source the sold token from; created
2315
+ * idempotently if omitted.
2316
+ * @param amount - Amount of the "in" token (or "out" token when `swapMode` is `ExactOut`, in
2317
+ * which case this is the desired output amount), in the token's own mint decimals — not a
2318
+ * fixed protocol precision.
2319
+ * @param slippageBps - Max slippage in basis points passed to the swap provider's routing API.
2320
+ * @param swapMode - `ExactIn` (default) or `ExactOut`.
2321
+ * @param reduceOnly - Whether the in/out token's position on the velocity account must reduce
2322
+ * (not flip sign); enforced by `endSwap` after the swap completes.
2323
+ * @param v6 - @deprecated Use `quote` instead. Pre-fetched Jupiter v6 quote response.
2324
+ * @param quote - Pre-fetched quote response (skips an extra round-trip to the swap provider).
2325
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2326
+ * @throws If neither `swapClient` nor `jupiterClient` is provided, or if `swapClient` is not a
2327
+ * recognized client type.
2328
+ * @returns The transaction signature.
688
2329
  */
689
2330
  swap({ swapClient, jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, reduceOnly, txParams, v6, quote, onlyDirectRoutes, }: {
690
2331
  swapClient?: UnifiedSwapClient | SwapClient;
@@ -705,6 +2346,15 @@ export declare class VelocityClient {
705
2346
  };
706
2347
  quote?: UnifiedQuoteResponse;
707
2348
  }): Promise<TransactionSignature>;
2349
+ /**
2350
+ * Builds the instruction list for a Titan-routed swap: creates any missing associated token
2351
+ * accounts, wraps Titan's routing instructions between `beginSwap`/`endSwap`. See `swap` for
2352
+ * parameter semantics; `amount` is in the "in" token's mint decimals.
2353
+ * @param userAccountPublicKey - Optional user account override (e.g. when the account is being
2354
+ * created in the same transaction and not yet resolvable via `getUserAccountPublicKey`).
2355
+ * @returns `ixs` — instruction list (ATA creation, `beginSwap`, Titan swap instructions,
2356
+ * `endSwap`, in order) and `lookupTables` needed to fit it in a versioned transaction.
2357
+ */
708
2358
  getTitanSwapIx({ titanClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, reduceOnly, userAccountPublicKey, }: {
709
2359
  titanClient: TitanClient;
710
2360
  outMarketIndex: number;
@@ -721,6 +2371,17 @@ export declare class VelocityClient {
721
2371
  ixs: TransactionInstruction[];
722
2372
  lookupTables: AddressLookupTableAccount[];
723
2373
  }>;
2374
+ /**
2375
+ * Builds the instruction list for a Jupiter v6-routed swap: fetches a quote if none is passed,
2376
+ * creates any missing associated token accounts, and wraps Jupiter's routing instructions
2377
+ * between `beginSwap`/`endSwap`. See `swap` for parameter semantics; `amount` is in the "in"
2378
+ * token's mint decimals.
2379
+ * @param userAccountPublicKey - Optional user account override (e.g. when the account is being
2380
+ * created in the same transaction).
2381
+ * @throws If no quote is passed and Jupiter's quote API returns none.
2382
+ * @returns `ixs` — instruction list (ATA creation, `beginSwap`, Jupiter swap instructions,
2383
+ * `endSwap`, in order) and `lookupTables` needed to fit it in a versioned transaction.
2384
+ */
724
2385
  getJupiterSwapIxV6({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, quote, reduceOnly, userAccountPublicKey, }: {
725
2386
  jupiterClient: JupiterClient;
726
2387
  outMarketIndex: number;
@@ -739,16 +2400,25 @@ export declare class VelocityClient {
739
2400
  lookupTables: AddressLookupTableAccount[];
740
2401
  }>;
741
2402
  /**
742
- * Get the velocity begin_swap and end_swap instructions
743
- *
744
- * @param outMarketIndex the market index of the token you're buying
745
- * @param inMarketIndex the market index of the token you're selling
746
- * @param amountIn the amount of the token to sell
747
- * @param inTokenAccount the token account to move the tokens being sold
748
- * @param outTokenAccount the token account to receive the tokens being bought
749
- * @param limitPrice the limit price of the swap
750
- * @param reduceOnly
751
- * @param userAccountPublicKey optional, specify a custom userAccountPublicKey to use instead of getting the current user account; can be helpful if the account is being created within the current tx
2403
+ * Builds the `beginSwap`/`endSwap` instruction pair that must bracket an external swap
2404
+ * provider's routing instructions in the same transaction. `beginSwap` snapshots the token
2405
+ * account balances and moves `amountIn` out of the in-market vault; `endSwap` reconciles the
2406
+ * post-swap token balances back into the user's velocity deposits, enforces `limitPrice` and
2407
+ * `reduceOnly`, and validates both spot markets' oracles are fresh/valid.
2408
+ * @param outMarketIndex - Spot market index of the token being bought.
2409
+ * @param inMarketIndex - Spot market index of the token being sold.
2410
+ * @param amountIn - Amount of the in-token released from the vault to the swap provider, in
2411
+ * the in-token's own mint decimals (not a fixed protocol precision).
2412
+ * @param inTokenAccount - Token account the sold tokens are moved through.
2413
+ * @param outTokenAccount - Token account the bought tokens are moved through.
2414
+ * @param limitPrice - Minimum acceptable `out/in` swap price, PRICE_PRECISION (1e6); `endSwap`
2415
+ * throws `SwapLimitPriceBreached` if the realized price is lower. Omit for no price check.
2416
+ * @param reduceOnly - Which side (`In`/`Out`) must not increase in magnitude after the swap;
2417
+ * enforced by `endSwap`.
2418
+ * @param userAccountPublicKey - Optional user account override; useful when the account is
2419
+ * being created within the same transaction and not yet resolvable via
2420
+ * `getUserAccountPublicKey`.
2421
+ * @returns `{ beginSwapIx, endSwapIx }` — insert the swap provider's instructions between them.
752
2422
  */
753
2423
  getSwapIx({ outMarketIndex, inMarketIndex, amountIn, inTokenAccount, outTokenAccount, limitPrice, reduceOnly, userAccountPublicKey, }: {
754
2424
  outMarketIndex: number;
@@ -763,6 +2433,17 @@ export declare class VelocityClient {
763
2433
  beginSwapIx: TransactionInstruction;
764
2434
  endSwapIx: TransactionInstruction;
765
2435
  }>;
2436
+ /**
2437
+ * Builds the instruction list for a swap routed through a `UnifiedSwapClient` (the current
2438
+ * preferred swap path). Creates any missing associated token accounts and wraps the client's
2439
+ * routing instructions between `beginSwap`/`endSwap`. See `swap` for parameter semantics;
2440
+ * `amount` is in the "in" token's mint decimals (or "out" token's decimals when `swapMode` is
2441
+ * `ExactOut`).
2442
+ * @param userAccountPublicKey - Optional user account override (e.g. when the account is being
2443
+ * created in the same transaction).
2444
+ * @returns `ixs` — instruction list (ATA creation, `beginSwap`, routed swap instructions,
2445
+ * `endSwap`, in order) and `lookupTables` needed to fit it in a versioned transaction.
2446
+ */
766
2447
  getSwapIxV2({ swapClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, reduceOnly, quote, v6, userAccountPublicKey, }: {
767
2448
  swapClient: UnifiedSwapClient;
768
2449
  outMarketIndex: number;
@@ -783,128 +2464,514 @@ export declare class VelocityClient {
783
2464
  ixs: TransactionInstruction[];
784
2465
  lookupTables: AddressLookupTableAccount[];
785
2466
  }>;
2467
+ /**
2468
+ * Converts a portion of the user's deposited wSOL (spot market index 1) into mSOL (spot market
2469
+ * index 2) by staking it with Marinade Finance, then swapping the resulting mSOL back into the
2470
+ * velocity deposit via `beginSwap`/`endSwap`. Sends and confirms the transaction.
2471
+ * @param amount - Amount of wSOL to stake, in lamports (wSOL mint decimals, 1e9).
2472
+ * @returns The transaction signature and confirmation slot.
2473
+ */
786
2474
  stakeForMSOL({ amount }: {
787
2475
  amount: BN;
788
2476
  }): Promise<TxSigAndSlot>;
2477
+ /**
2478
+ * Builds the instruction list for `stakeForMSOL`: wraps a Marinade `deposit` (wSOL to mSOL)
2479
+ * between the velocity `beginSwap`/`endSwap` pair so the mSOL lands back in the user's velocity
2480
+ * deposit for spot market index 2. Hardcodes wSOL as market index 1 and mSOL as market index 2.
2481
+ * @param amount - Amount of wSOL to stake, in lamports (wSOL mint decimals, 1e9).
2482
+ * @param userAccountPublicKey - Optional user account override; useful when the account is
2483
+ * being created within the same transaction.
2484
+ * @returns The ordered instruction list (WSOL ATA setup, `beginSwap`, close/recreate wSOL
2485
+ * account around the Marinade deposit, `endSwap`).
2486
+ */
789
2487
  getStakeForMSOLIx({ amount, userAccountPublicKey, }: {
790
2488
  amount: BN;
791
2489
  userAccountPublicKey?: PublicKey;
792
2490
  }): Promise<TransactionInstruction[]>;
2491
+ /**
2492
+ * Keeper instruction: activates a resting trigger order (stop/take-profit, perp or spot) once
2493
+ * its `triggerPrice`/`triggerCondition` has been met, turning it into a fillable market/limit
2494
+ * order. Permissionless — any signer can act as filler and earns a small keeper fee. Does not
2495
+ * fill the order itself; a separate fill instruction (or place-and-take) is still required.
2496
+ * @param userAccountPublicKey - Public key of the order owner's user account.
2497
+ * @param user - Decoded user account for the order owner.
2498
+ * @param order - The trigger order to activate (`order.orderId`, `order.marketType`, `order.marketIndex`).
2499
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2500
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2501
+ * @returns The transaction signature.
2502
+ */
793
2503
  triggerOrder(userAccountPublicKey: PublicKey, user: UserAccount, order: Order, txParams?: TxParams, fillerPublicKey?: PublicKey): Promise<TransactionSignature>;
2504
+ /**
2505
+ * Builds the `triggerOrder` instruction. See `triggerOrder` for semantics.
2506
+ * @param userAccountPublicKey - Public key of the order owner's user account.
2507
+ * @param userAccount - Decoded user account for the order owner.
2508
+ * @param order - The trigger order to activate.
2509
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2510
+ * @returns The instruction.
2511
+ */
794
2512
  getTriggerOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Order, fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2513
+ /**
2514
+ * Keeper instruction: cancels a user's open, non-position-reducing orders when the user fails
2515
+ * their initial margin requirement (reverts with `SufficientCollateral` if the user still
2516
+ * meets it, or with `UserIsBeingLiquidated`/`UserBankrupt` if either is set). Charges the user a
2517
+ * per-cancelled-order fee paid to the filler. Permissionless — any signer can act as filler.
2518
+ * @param userAccountPublicKey - Public key of the target user's user account.
2519
+ * @param user - Decoded user account of the target user.
2520
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2521
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2522
+ * @returns The transaction signature.
2523
+ */
795
2524
  forceCancelOrders(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams, fillerPublicKey?: PublicKey): Promise<TransactionSignature>;
2525
+ /**
2526
+ * Builds the `forceCancelOrders` instruction. See `forceCancelOrders` for semantics.
2527
+ * @param userAccountPublicKey - Public key of the target user's user account.
2528
+ * @param userAccount - Decoded user account of the target user.
2529
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2530
+ * @returns The instruction.
2531
+ */
796
2532
  getForceCancelOrdersIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2533
+ /**
2534
+ * Keeper instruction: trips the authority-wide equity floor breaker. Proves on-chain that the
2535
+ * given subaccount's cross-margin total collateral is below its `equityFloor` (reverts with
2536
+ * `SufficientCollateral` otherwise, or if no floor is set) and sets `equityBreakerTripped` on the
2537
+ * authority's `UserStats` — every subaccount of the authority then rejects risk-increasing fills,
2538
+ * withdrawals and transfers out until the warm admin calls `resetEquityFloorBreaker`.
2539
+ * Permissionless — any signer may trip it; the margin calculation is the proof.
2540
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
2541
+ * @param user - Decoded user account of the breached subaccount.
2542
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2543
+ * @returns The transaction signature.
2544
+ */
2545
+ tripEquityFloorBreaker(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams): Promise<TransactionSignature>;
2546
+ /**
2547
+ * Builds the `tripEquityFloorBreaker` instruction. See `tripEquityFloorBreaker` for semantics.
2548
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
2549
+ * @param userAccount - Decoded user account of the breached subaccount.
2550
+ * @returns The instruction.
2551
+ */
2552
+ getTripEquityFloorBreakerIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
2553
+ /**
2554
+ * Keeper instruction: marks a user account idle after confirming (via `validate_user_is_idle`)
2555
+ * it has been inactive long enough — the inactivity window is shorter (accelerated) when the
2556
+ * user's equity is below 1000 USDC (QUOTE_PRECISION, 1e6). Idle users are excluded from some
2557
+ * keeper crank workloads. Permissionless — any signer can act as filler.
2558
+ * @param userAccountPublicKey - Public key of the target user's user account.
2559
+ * @param user - Decoded user account of the target user.
2560
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2561
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2562
+ * @throws If the user does not yet qualify as idle.
2563
+ * @returns The transaction signature.
2564
+ */
797
2565
  updateUserIdle(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams, fillerPublicKey?: PublicKey): Promise<TransactionSignature>;
2566
+ /**
2567
+ * Builds the `updateUserIdle` instruction. See `updateUserIdle` for semantics.
2568
+ * @param userAccountPublicKey - Public key of the target user's user account.
2569
+ * @param userAccount - Decoded user account of the target user.
2570
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2571
+ * @returns The instruction.
2572
+ */
798
2573
  getUpdateUserIdleIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2574
+ /**
2575
+ * Debug/monitoring instruction: emits the user's equity, each non-zero spot position's signed
2576
+ * token amount (native mint decimals), and each open perp position's unrealized PnL
2577
+ * (QUOTE_PRECISION, 1e6) as program logs. Has no on-chain state effect. Exchange must not be
2578
+ * paused.
2579
+ * @param userAccountPublicKey - Public key of the user account to log.
2580
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2581
+ * @returns The transaction signature.
2582
+ */
799
2583
  logUserBalances(userAccountPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
2584
+ /**
2585
+ * Builds the `logUserBalances` instruction. See `logUserBalances` for semantics. Fetches the
2586
+ * user account fresh from the RPC (rather than relying on a cached/passed-in account) to build
2587
+ * `remainingAccounts`.
2588
+ * @param userAccountPublicKey - Public key of the user account to log.
2589
+ * @returns The instruction.
2590
+ */
800
2591
  getLogUserBalancesIx(userAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
2592
+ /**
2593
+ * Recomputes and updates the `isReferrer` flag on a `UserStats` account from its current
2594
+ * referrer-related fields. Permissionless — anyone can trigger the refresh for any authority.
2595
+ * @param userAuthority - Wallet authority whose `UserStats` PDA should be refreshed.
2596
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2597
+ * @returns The transaction signature.
2598
+ */
801
2599
  updateUserStatsReferrerStatus(userAuthority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
2600
+ /**
2601
+ * Builds the `updateUserStatsReferrerStatus` instruction. See `updateUserStatsReferrerStatus`
2602
+ * for semantics.
2603
+ * @param userAuthority - Wallet authority whose `UserStats` PDA should be refreshed.
2604
+ * @returns The instruction.
2605
+ */
802
2606
  getUpdateUserStatsReferrerStatusIx(userAuthority: PublicKey): Promise<TransactionInstruction>;
2607
+ /**
2608
+ * Keeper instruction: recounts `user.orders` and rewrites `openOrders`/`hasOpenOrder`/
2609
+ * `openAuctions`/`hasOpenAuction` to match the account's actual order state — a repair
2610
+ * instruction for when these cached counters have drifted. Permissionless — any signer can act
2611
+ * as filler.
2612
+ * @param userAccountPublicKey - Public key of the target user's user account.
2613
+ * @param user - Decoded user account of the target user.
2614
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2615
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2616
+ * @returns The transaction signature.
2617
+ */
803
2618
  updateUserOpenOrdersCount(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams, fillerPublicKey?: PublicKey): Promise<TransactionSignature>;
2619
+ /**
2620
+ * Builds the `updateUserOpenOrdersCount` instruction. See `updateUserOpenOrdersCount` for
2621
+ * semantics.
2622
+ * @param userAccountPublicKey - Public key of the target user's user account.
2623
+ * @param userAccount - Decoded user account of the target user.
2624
+ * @param fillerPublicKey - Filler's user account public key; defaults to this client's own user account.
2625
+ * @returns The instruction.
2626
+ */
804
2627
  getUpdateUserOpenOrdersCountIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2628
+ /**
2629
+ * Places a perp order and immediately attempts to fill it in the same instruction against the
2630
+ * AMM and/or the supplied `makerInfo`. `orderParams.postOnly` must be `PostOnlyParams.NONE` —
2631
+ * the on-chain handler rejects post-only orders here (use `placeAndMakePerpOrder` instead for a
2632
+ * post-only maker order). If the order is immediate-or-cancel (or `successCondition`/
2633
+ * `auctionDurationPercentage` is set) and still open after the fill attempt, it is cancelled
2634
+ * in the same instruction.
2635
+ * @param orderParams - Order to place; `baseAssetAmount` is BASE_PRECISION (1e9), `price`/
2636
+ * `triggerPrice`/`oraclePriceOffset` (signed) are PRICE_PRECISION (1e6).
2637
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
2638
+ * @param successCondition - Require the fill to be a `PartialFill` or `FullFill`; the
2639
+ * instruction reverts with `PlaceAndTakeOrderSuccessConditionFailed` if not met. Omit for no check.
2640
+ * @param auctionDurationPercentage - Percent (0-100, default 100) of the order's auction that
2641
+ * must have elapsed before this fill attempt is allowed to cross the AMM/makers at the current
2642
+ * auction price; packed on-chain into the same `u32` as `successCondition`.
2643
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2644
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
2645
+ * @param takerEscrow - The placing user's (taker's) decoded `RevenueShareEscrow`. Required to
2646
+ * attach the escrow account when the taker is referred but the order itself carries no builder
2647
+ * code — the builder case is detected automatically from `orderParams`.
2648
+ * @returns The transaction signature.
2649
+ */
805
2650
  placeAndTakePerpOrder(orderParams: OptionalOrderParams, makerInfo?: MakerInfo | MakerInfo[], successCondition?: PlaceAndTakeOrderSuccessCondition, auctionDurationPercentage?: number, txParams?: TxParams, subAccountId?: number, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionSignature>;
2651
+ /**
2652
+ * Builds (without sending) a `placeAndTakePerpOrder` transaction bundled with optional bracket
2653
+ * orders (e.g. TP/SL) in the same transaction, plus optional companion transactions to cancel
2654
+ * the market's existing orders first and/or settle PnL after. Reuses a single recent blockhash
2655
+ * across all built transactions to save RPC round trips.
2656
+ * @param orderParams - Order to place; see `placeAndTakePerpOrder` for field precisions.
2657
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
2658
+ * @param bracketOrdersParams - Additional orders placed in the same transaction as the place-and-take.
2659
+ * @param txParams - Compute-unit/priority-fee overrides. Required (throws otherwise) if
2660
+ * `txParams.useSimulatedComputeUnits` is set or `exitEarlyIfSimFails` is `true`.
2661
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
2662
+ * @param cancelExistingOrders - If `true` and the order is perp, also builds a transaction
2663
+ * cancelling all existing open orders in that market.
2664
+ * @param settlePnl - If `true` and the order is perp, also builds a settle-PnL transaction for the market.
2665
+ * @param exitEarlyIfSimFails - If `true`, simulates the place-and-take transaction first and
2666
+ * returns `null` without building the real transactions if the simulation fails.
2667
+ * @param auctionDurationPercentage - See `placeAndTakePerpOrder`.
2668
+ * @param optionalIxs - Extra instructions prepended to the place-and-take transaction (and to
2669
+ * the cancel/settle-PnL transactions).
2670
+ * @param isolatedPositionDepositAmount - If set and the order increases the position, a
2671
+ * transfer into an isolated-margin position (token-mint precision) is prepended before placing.
2672
+ * @returns `null` if `exitEarlyIfSimFails` triggered an early exit; otherwise an object with
2673
+ * `placeAndTakeTx` and optional `cancelExistingOrdersTx`/`settlePnlTx` (each `undefined` when
2674
+ * not applicable).
2675
+ */
806
2676
  preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams: OptionalOrderParams, makerInfo?: MakerInfo | MakerInfo[], bracketOrdersParams?: OptionalOrderParams[], txParams?: TxParams, subAccountId?: number, cancelExistingOrders?: boolean, settlePnl?: boolean, exitEarlyIfSimFails?: boolean, auctionDurationPercentage?: number, optionalIxs?: TransactionInstruction[], isolatedPositionDepositAmount?: BN): Promise<{
807
2677
  placeAndTakeTx: Transaction | VersionedTransaction | undefined;
808
2678
  cancelExistingOrdersTx: Transaction | VersionedTransaction | undefined;
809
2679
  settlePnlTx: Transaction | VersionedTransaction | undefined;
810
2680
  } | null>;
2681
+ /**
2682
+ * Builds, signs, and sends a `placeAndTakePerpOrder` transaction bundled with bracket orders via
2683
+ * `preparePlaceAndTakePerpOrderWithAdditionalOrders`, and returns the signed (but unsent)
2684
+ * companion cancel/settle-PnL transactions for the caller to broadcast separately.
2685
+ * @param orderParams - Order to place; see `placeAndTakePerpOrder` for field precisions.
2686
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
2687
+ * @param bracketOrdersParams - Additional orders placed in the same transaction as the place-and-take.
2688
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2689
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
2690
+ * @param cancelExistingOrders - See `preparePlaceAndTakePerpOrderWithAdditionalOrders`.
2691
+ * @param settlePnl - See `preparePlaceAndTakePerpOrderWithAdditionalOrders`.
2692
+ * @param exitEarlyIfSimFails - If `true`, returns `null` without sending when the pre-flight
2693
+ * simulation of the place-and-take transaction fails.
2694
+ * @returns `null` if the simulation failed and `exitEarlyIfSimFails` was set; otherwise `txSig`
2695
+ * for the sent place-and-take transaction plus the signed (unsent) `signedCancelExistingOrdersTx`
2696
+ * / `signedSettlePnlTx`, each `undefined` when not applicable.
2697
+ * @throws If `placeAndTakeTx` was not built (should not happen unless simulation-related options are misused).
2698
+ */
811
2699
  placeAndTakePerpWithAdditionalOrders(orderParams: OptionalOrderParams, makerInfo?: MakerInfo | MakerInfo[], bracketOrdersParams?: OptionalOrderParams[], txParams?: TxParams, subAccountId?: number, cancelExistingOrders?: boolean, settlePnl?: boolean, exitEarlyIfSimFails?: boolean): Promise<{
812
2700
  txSig: TransactionSignature;
813
2701
  signedCancelExistingOrdersTx?: Transaction;
814
2702
  signedSettlePnlTx?: Transaction;
815
2703
  } | null>;
2704
+ /**
2705
+ * Builds the `placeAndTakePerpOrder` instruction. See `placeAndTakePerpOrder` for semantics.
2706
+ * @param orderParams - Order to place; see `placeAndTakePerpOrder` for field precisions.
2707
+ * @param makerInfo - Maker account(s) to include as fill counterparties, if any.
2708
+ * @param successCondition - See `placeAndTakePerpOrder`.
2709
+ * @param auctionDurationPercentage - See `placeAndTakePerpOrder`.
2710
+ * @param subAccountId - Sub-account to place the order for; defaults to the active sub-account.
2711
+ * @param overrides - `authority` overrides the signing authority (defaults to `this.wallet.publicKey`).
2712
+ * @param takerEscrow - See `placeAndTakePerpOrder`.
2713
+ * @returns The instruction.
2714
+ */
816
2715
  getPlaceAndTakePerpOrderIx(orderParams: OptionalOrderParams, makerInfo?: MakerInfo | MakerInfo[], successCondition?: PlaceAndTakeOrderSuccessCondition, auctionDurationPercentage?: number, subAccountId?: number, overrides?: {
817
2716
  authority?: PublicKey;
818
2717
  }, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionInstruction>;
2718
+ /**
2719
+ * Places a resting maker order and, in the same instruction, fills a specific counterparty
2720
+ * taker order (`takerInfo.order`) against it. `orderParams` must be an immediate-or-cancel,
2721
+ * post-only (not `PostOnlyParams.NONE`) limit order — the on-chain handler rejects any other
2722
+ * shape with `InvalidOrderIOCPostOnly`.
2723
+ * @param orderParams - Maker order to place; `baseAssetAmount` is BASE_PRECISION (1e9), `price`
2724
+ * is PRICE_PRECISION (1e6). Must have `orderType: LIMIT`, `postOnly` set, and be IOC.
2725
+ * @param takerInfo - The taker account/order to fill against (`takerInfo.order.orderId` must be open).
2726
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2727
+ * @param subAccountId - Sub-account placing the maker order; defaults to the active sub-account.
2728
+ * @param takerEscrow - The taker's decoded `RevenueShareEscrow`. Required to attach the escrow
2729
+ * when the taker is referred but their order carries no builder code — the builder case is
2730
+ * detected automatically from `takerInfo.order`.
2731
+ * @returns The transaction signature.
2732
+ */
819
2733
  placeAndMakePerpOrder(orderParams: OptionalOrderParams, takerInfo: TakerInfo, txParams?: TxParams, subAccountId?: number, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionSignature>;
2734
+ /**
2735
+ * Builds the `placeAndMakePerpOrder` instruction. See `placeAndMakePerpOrder` for semantics.
2736
+ * @param orderParams - Maker order to place; see `placeAndMakePerpOrder` for field precisions
2737
+ * and required order shape.
2738
+ * @param takerInfo - The taker account/order to fill against.
2739
+ * @param subAccountId - Sub-account placing the maker order; defaults to the active sub-account.
2740
+ * @param takerEscrow - See `placeAndMakePerpOrder`.
2741
+ * @returns The instruction.
2742
+ */
820
2743
  getPlaceAndMakePerpOrderIx(orderParams: OptionalOrderParams, takerInfo: TakerInfo, subAccountId?: number, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionInstruction>;
2744
+ /**
2745
+ * Borsh-encodes a swift/signed-msg order message and signs the resulting hex-encoded buffer
2746
+ * with `signMessage` (this client's wallet keypair by default). The returned payload is what a
2747
+ * swift/signed-msg service or a taker-facing `placeSignedMsgTakerOrder` expects.
2748
+ * @param orderParamsMessage - The order message to sign; use `SignedMsgOrderParamsDelegateMessage`
2749
+ * when signing on behalf of a delegated authority (`delegateSigner: true`), otherwise
2750
+ * `SignedMsgOrderParamsMessage`.
2751
+ * @param delegateSigner - Whether `orderParamsMessage` is the delegate-signer variant; must match
2752
+ * the message's actual shape or encoding/decoding elsewhere will misinterpret the buffer.
2753
+ * @returns `{ orderParams, signature }` — `orderParams` is the hex-encoded borsh buffer as a
2754
+ * `Buffer`, `signature` is the detached ed25519 signature over it.
2755
+ */
821
2756
  signSignedMsgOrderParamsMessage(orderParamsMessage: SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage, delegateSigner?: boolean): SignedMsgOrderParams;
822
2757
  /**
823
- * Builds a deposit and place request for Swift service
824
- *
825
- * @param depositTx - The signed tx containing a velocity deposit (e.g. see `buildSwiftDepositTx`)
826
- * @param orderParamsMessage - The order parameters message to sign
827
- * @param delegateSigner - Whether this is a delegate signer
828
- *
829
- * @returns request object for Swift service
2758
+ * Bundles a pre-signed deposit transaction with a signed swift/signed-msg order message into
2759
+ * the request shape the Swift service expects for a "deposit and place" flow (e.g. depositing
2760
+ * new collateral and placing an order off-chain in one round trip before either lands on-chain).
2761
+ * @param depositTx - The signed tx containing a velocity deposit (e.g. see `buildSwiftDepositTx`).
2762
+ * @param orderParamsMessage - The order parameters message to sign.
2763
+ * @param delegateSigner - Whether `orderParamsMessage` is signed by a delegate; see `signSignedMsgOrderParamsMessage`.
2764
+ * @returns `{ deposit_tx, swift_order }` — the serialized deposit transaction and the signed order payload.
830
2765
  */
831
2766
  buildDepositAndPlaceSignedMsgOrderRequest(depositTx: VersionedTransaction, orderParamsMessage: SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage, delegateSigner?: boolean): {
832
2767
  deposit_tx: Buffer;
833
2768
  swift_order: SignedMsgOrderParams;
834
2769
  };
2770
+ /**
2771
+ * Borsh-encodes a swift/signed-msg order message using the program's IDL type coder. Used
2772
+ * internally by `signSignedMsgOrderParamsMessage`; call directly if you need the raw encoded
2773
+ * bytes without also signing them.
2774
+ * @param orderParamsMessage - The order message to encode.
2775
+ * @param delegateSigner - Whether `orderParamsMessage` is the delegate-signer variant
2776
+ * (`SignedMsgOrderParamsDelegateMessage`) rather than the regular one — selects which on-chain
2777
+ * type is used to encode.
2778
+ * @returns The borsh-encoded message bytes.
2779
+ */
835
2780
  encodeSignedMsgOrderParamsMessage(orderParamsMessage: SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage, delegateSigner?: boolean): Buffer;
2781
+ /**
2782
+ * Decodes a borsh-encoded swift/signed-msg order message. Zero-pads the input by 128 bytes
2783
+ * before decoding so messages encoded by an older IDL (missing newer, all-`Option` fields)
2784
+ * still decode instead of throwing on a too-short buffer. Note: this padding assumes any
2785
+ * newer fields added to the message type are `Option`s — a 128+ byte non-optional field
2786
+ * addition could still fail to decode older messages correctly.
2787
+ * @param encodedMessage - The borsh-encoded message bytes (as produced by `encodeSignedMsgOrderParamsMessage`).
2788
+ * @param delegateSigner - Whether to decode as the delegate-signer variant
2789
+ * (`SignedMsgOrderParamsDelegateMessage`) rather than the regular one.
2790
+ * @returns The decoded order message.
2791
+ */
836
2792
  decodeSignedMsgOrderParamsMessage(encodedMessage: Buffer, delegateSigner?: boolean): SignedMsgOrderParamsMessage | SignedMsgOrderParamsDelegateMessage;
2793
+ /**
2794
+ * Signs arbitrary bytes with a raw ed25519 detached signature (not a Solana transaction
2795
+ * signature) — the primitive used to sign swift/signed-msg order messages.
2796
+ * @param message - Bytes to sign.
2797
+ * @param keypair - Keypair to sign with; defaults to `this.wallet.payer`.
2798
+ * @throws If no keypair is available (e.g. the configured wallet has no local `payer`, such as
2799
+ * a browser-extension wallet — that case must sign the message externally instead).
2800
+ * @returns The detached ed25519 signature.
2801
+ */
837
2802
  signMessage(message: Uint8Array, keypair?: Keypair | undefined): Buffer;
2803
+ /**
2804
+ * Submits a previously off-chain-signed swift/signed-msg taker order on-chain: verifies the
2805
+ * ed25519 signature via the sysvar-instructions program and records the order in the taker's
2806
+ * `SignedMsgUserOrders` account (see `initializeSignedMsgUserOrders`, required beforehand).
2807
+ * This only registers the order — it does not place or fill it against the market; a keeper
2808
+ * (or `placeAndMakeSignedMsgPerpOrder`) still performs the actual place/fill.
2809
+ * @param signedSignedMsgOrderParams - The signed order payload from `signSignedMsgOrderParamsMessage`.
2810
+ * @param marketIndex - Perp market index the signed order targets.
2811
+ * @param takerInfo - Taker's account/authority info; `signingAuthority` is the delegate or
2812
+ * direct authority that produced the signature (compared against `takerUserAccount.delegate`
2813
+ * to determine whether the message decodes as the delegate-signer variant).
2814
+ * @param precedingIxs - Instructions that will precede the returned ones in the final
2815
+ * transaction; used only to compute the correct sysvar-instructions index for signature
2816
+ * verification (has no other effect — the caller is still responsible for including them).
2817
+ * @param overrideCustomIxIndex - Explicit index of the ed25519-verify instruction within the
2818
+ * final transaction; overrides the value derived from `precedingIxs.length`.
2819
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2820
+ * @returns The transaction signature.
2821
+ */
838
2822
  placeSignedMsgTakerOrder(signedSignedMsgOrderParams: SignedMsgOrderParams, marketIndex: number, takerInfo: {
839
2823
  taker: PublicKey;
840
2824
  takerStats: PublicKey;
841
2825
  takerUserAccount: UserAccount;
842
2826
  signingAuthority: PublicKey;
843
2827
  }, precedingIxs?: TransactionInstruction[], overrideCustomIxIndex?: number, txParams?: TxParams): Promise<TransactionSignature>;
2828
+ /**
2829
+ * Builds the two instructions for `placeSignedMsgTakerOrder`: an ed25519-signature-verify
2830
+ * instruction (must be placed at the sysvar-instructions index this function assumes — see
2831
+ * `precedingIxs`/`overrideCustomIxIndex`) followed by the `placeSignedMsgTakerOrder` program
2832
+ * instruction. See `placeSignedMsgTakerOrder` for semantics.
2833
+ * @param signedSignedMsgOrderParams - The signed order payload.
2834
+ * @param marketIndex - Perp market index the signed order targets.
2835
+ * @param takerInfo - Taker's account/authority info; see `placeSignedMsgTakerOrder`.
2836
+ * @param precedingIxs - Instructions preceding these two in the final transaction (used only
2837
+ * to compute the ed25519-verify instruction's sysvar index).
2838
+ * @param overrideCustomIxIndex - Explicit sysvar-instructions index override.
2839
+ * @returns `[ed25519VerifyIx, placeSignedMsgTakerOrderIx]`.
2840
+ */
844
2841
  getPlaceSignedMsgTakerPerpOrderIxs(signedSignedMsgOrderParams: SignedMsgOrderParams, marketIndex: number, takerInfo: {
845
2842
  taker: PublicKey;
846
2843
  takerStats: PublicKey;
847
2844
  takerUserAccount: UserAccount;
848
2845
  signingAuthority: PublicKey;
849
2846
  }, precedingIxs?: TransactionInstruction[], overrideCustomIxIndex?: number): Promise<TransactionInstruction[]>;
2847
+ /**
2848
+ * Verifies and registers a taker's off-chain signed swift/signed-msg order (same as
2849
+ * `placeSignedMsgTakerOrder`) and, in the same transaction, places a maker order and fills the
2850
+ * taker order against it in one shot — the signed-msg analog of `placeAndMakePerpOrder`.
2851
+ * `orderParams` (the maker order) is subject to the same IOC/post-only/limit requirement as
2852
+ * `placeAndMakePerpOrder`.
2853
+ * @param signedSignedMsgOrderParams - The taker's signed order payload.
2854
+ * @param signedMsgOrderUuid - UUID identifying the signed-msg order, used by the program to
2855
+ * dedupe/match it against the recorded `SignedMsgUserOrders` entry.
2856
+ * @param takerInfo - Taker's account/authority info; see `placeSignedMsgTakerOrder`.
2857
+ * @param orderParams - Maker order to place; `baseAssetAmount` is BASE_PRECISION (1e9), `price`
2858
+ * is PRICE_PRECISION (1e6). Must have `orderType: LIMIT`, `postOnly` set, and be IOC.
2859
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2860
+ * @param subAccountId - Sub-account placing the maker order; defaults to the active sub-account.
2861
+ * @param precedingIxs - Instructions preceding these in the final transaction (used only to
2862
+ * compute the ed25519-verify instruction's sysvar index).
2863
+ * @param overrideCustomIxIndex - Explicit sysvar-instructions index override.
2864
+ * @param takerEscrow - The taker's decoded `RevenueShareEscrow`. Required to attach the escrow
2865
+ * when the taker is referred but the signed order carries no builder code.
2866
+ * @returns The transaction signature.
2867
+ */
850
2868
  placeAndMakeSignedMsgPerpOrder(signedSignedMsgOrderParams: SignedMsgOrderParams, signedMsgOrderUuid: Uint8Array, takerInfo: {
851
2869
  taker: PublicKey;
852
2870
  takerStats: PublicKey;
853
2871
  takerUserAccount: UserAccount;
854
2872
  signingAuthority: PublicKey;
855
2873
  }, orderParams: OptionalOrderParams, txParams?: TxParams, subAccountId?: number, precedingIxs?: TransactionInstruction[], overrideCustomIxIndex?: number, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionSignature>;
2874
+ /**
2875
+ * Builds the instructions for `placeAndMakeSignedMsgPerpOrder`: the taker signature-verify +
2876
+ * registration instructions from `getPlaceSignedMsgTakerPerpOrderIxs`, followed by the
2877
+ * `placeAndMakeSignedMsgPerpOrder` program instruction. See `placeAndMakeSignedMsgPerpOrder`
2878
+ * for semantics.
2879
+ * @param signedSignedMsgOrderParams - The taker's signed order payload.
2880
+ * @param signedMsgOrderUuid - UUID identifying the signed-msg order.
2881
+ * @param takerInfo - Taker's account/authority info.
2882
+ * @param orderParams - Maker order to place; see `placeAndMakeSignedMsgPerpOrder` for field
2883
+ * precisions and required order shape.
2884
+ * @param subAccountId - Sub-account placing the maker order; defaults to the active sub-account.
2885
+ * @param precedingIxs - Instructions preceding these in the final transaction (used only to
2886
+ * compute the ed25519-verify instruction's sysvar index).
2887
+ * @param overrideCustomIxIndex - Explicit sysvar-instructions index override.
2888
+ * @param takerEscrow - See `placeAndMakeSignedMsgPerpOrder`.
2889
+ * @returns `[ed25519VerifyIx, placeSignedMsgTakerOrderIx, placeAndMakeSignedMsgPerpOrderIx]`.
2890
+ */
856
2891
  getPlaceAndMakeSignedMsgPerpOrderIxs(signedSignedMsgOrderParams: SignedMsgOrderParams, signedMsgOrderUuid: Uint8Array, takerInfo: {
857
2892
  taker: PublicKey;
858
2893
  takerStats: PublicKey;
859
2894
  takerUserAccount: UserAccount;
860
2895
  signingAuthority: PublicKey;
861
2896
  }, orderParams: OptionalOrderParams, subAccountId?: number, precedingIxs?: TransactionInstruction[], overrideCustomIxIndex?: number, takerEscrow?: RevenueShareEscrowAccount): Promise<TransactionInstruction[]>;
2897
+ /**
2898
+ * Disabled. See `placeSpotOrder`.
2899
+ * @throws Always throws with the spot-DLOB-disabled message.
2900
+ */
862
2901
  preparePlaceAndTakeSpotOrder(_orderParams: OptionalOrderParams, _fulfillmentConfig?: unknown, _makerInfo?: MakerInfo, _txParams?: TxParams, _subAccountId?: number): Promise<void>;
2902
+ /**
2903
+ * Disabled. See `placeSpotOrder`.
2904
+ * @throws Always throws with the spot-DLOB-disabled message.
2905
+ */
863
2906
  placeAndTakeSpotOrder(_orderParams: OptionalOrderParams, _fulfillmentConfig?: unknown, _makerInfo?: MakerInfo, _txParams?: TxParams, _subAccountId?: number): Promise<TransactionSignature>;
2907
+ /**
2908
+ * Disabled. See `placeSpotOrder`.
2909
+ * @throws Always throws with the spot-DLOB-disabled message.
2910
+ */
864
2911
  getPlaceAndTakeSpotOrderIx(_orderParams: OptionalOrderParams, _fulfillmentConfig?: unknown, _makerInfo?: MakerInfo, _subAccountId?: number): Promise<TransactionInstruction>;
2912
+ /**
2913
+ * Disabled. See `placeSpotOrder`.
2914
+ * @throws Always throws with the spot-DLOB-disabled message.
2915
+ */
865
2916
  placeAndMakeSpotOrder(_orderParams: OptionalOrderParams, _takerInfo: TakerInfo, _fulfillmentConfig?: unknown, _txParams?: TxParams, _subAccountId?: number): Promise<TransactionSignature>;
2917
+ /**
2918
+ * Disabled. See `placeSpotOrder`.
2919
+ * @throws Always throws with the spot-DLOB-disabled message.
2920
+ */
866
2921
  getPlaceAndMakeSpotOrderIx(_orderParams: OptionalOrderParams, _takerInfo: TakerInfo, _fulfillmentConfig?: unknown, _subAccountId?: number): Promise<TransactionInstruction>;
867
2922
  /**
868
- * @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
2923
+ * Closes (or reduces to zero) the caller's entire perp position in `marketIndex` with a
2924
+ * reduce-only market order (or limit order if `limitPrice` is given), filled immediately via
2925
+ * `placeAndTakePerpOrder`.
2926
+ * @deprecated use `placePerpOrder` or `placeAndTakePerpOrder` instead.
2927
+ * @param marketIndex - Perp market index of the position to close.
2928
+ * @param limitPrice - Optional limit price, PRICE_PRECISION (1e6); omit for a pure market order.
2929
+ * @param subAccountId - Sub-account holding the position; defaults to the active sub-account.
2930
+ * @throws If there is no open position in `marketIndex` for the sub-account.
2931
+ * @returns The transaction signature.
869
2932
  */
870
2933
  closePosition(marketIndex: number, limitPrice?: BN, subAccountId?: number): Promise<TransactionSignature>;
871
2934
  /**
872
2935
  * Modifies an open order by closing it and replacing it with a new order.
873
- * @deprecated use modifyOrder instead
874
- * @param orderId: The open order to modify
875
- * @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
876
- * @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
877
- * @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
878
- * @returns
2936
+ * @deprecated use `modifyOrder` instead.
2937
+ * @param orderId - The open order to modify (program-assigned order ID).
2938
+ * @param newBaseAmount - The new base amount for the order, BASE_PRECISION (1e9). One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2939
+ * @param newLimitPrice - The new limit price for the order, PRICE_PRECISION (1e6). One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2940
+ * @param newOraclePriceOffset - The new oracle price offset for the order, PRICE_PRECISION (1e6), signed. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2941
+ * @returns The transaction signature.
879
2942
  */
880
2943
  modifyPerpOrder(orderId: number, newBaseAmount?: BN, newLimitPrice?: BN, newOraclePriceOffset?: BN): Promise<TransactionSignature>;
881
2944
  /**
882
2945
  * Modifies an open order by closing it and replacing it with a new order.
883
- * @deprecated use modifyOrderByUserOrderId instead
884
- * @param userOrderId: The open order to modify
885
- * @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
886
- * @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
887
- * @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
888
- * @returns
2946
+ * @deprecated use `modifyOrderByUserOrderId` instead.
2947
+ * @param userOrderId - The open order to modify (caller-supplied `userOrderId`).
2948
+ * @param newBaseAmount - The new base amount for the order, BASE_PRECISION (1e9). One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2949
+ * @param newLimitPrice - The new limit price for the order, PRICE_PRECISION (1e6). One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2950
+ * @param newOraclePriceOffset - The new oracle price offset for the order, PRICE_PRECISION (1e6), signed. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
2951
+ * @returns The transaction signature.
889
2952
  */
890
2953
  modifyPerpOrderByUserOrderId(userOrderId: number, newBaseAmount?: BN, newLimitPrice?: BN, newOraclePriceOffset?: BN): Promise<TransactionSignature>;
891
2954
  /**
892
- * Modifies an open order (spot or perp) by closing it and replacing it with a new order.
893
- * @param orderParams.orderId: The open order to modify
894
- * @param orderParams.newDirection: The new direction for the order
895
- * @param orderParams.newBaseAmount: The new base amount for the order
896
- * @param orderParams.newLimitPice: The new limit price for the order
897
- * @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
898
- * @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
899
- * @param orderParams.auctionDuration:
900
- * @param orderParams.auctionStartPrice:
901
- * @param orderParams.auctionEndPrice:
902
- * @param orderParams.reduceOnly:
903
- * @param orderParams.postOnly:
904
- * @param orderParams.bitFlags:
905
- * @param orderParams.policy:
906
- * @param orderParams.maxTs:
907
- * @returns
2955
+ * Modifies an open order (spot or perp) by closing it and replacing it with a new order in one
2956
+ * instruction. Only fields present (non-`undefined`) in `orderParams` are changed; the rest of
2957
+ * the order is left as-is.
2958
+ * @param orderParams.orderId - The open order to modify (program-assigned order ID).
2959
+ * @param orderParams.newDirection - The new direction for the order.
2960
+ * @param orderParams.newBaseAmount - The new base amount for the order, BASE_PRECISION (1e9).
2961
+ * @param orderParams.newLimitPrice - The new limit price for the order, PRICE_PRECISION (1e6).
2962
+ * @param orderParams.newOraclePriceOffset - The new oracle price offset for the order, PRICE_PRECISION (1e6), signed.
2963
+ * @param orderParams.newTriggerPrice - Optional - the new trigger price for the order, PRICE_PRECISION (1e6).
2964
+ * @param orderParams.auctionDuration - Slots the auction lasts; only relevant for market/oracle orders.
2965
+ * @param orderParams.auctionStartPrice - PRICE_PRECISION (1e6), signed; only relevant for market/oracle orders.
2966
+ * @param orderParams.auctionEndPrice - PRICE_PRECISION (1e6), signed; only relevant for market/oracle orders.
2967
+ * @param orderParams.reduceOnly - Whether the modified order must only reduce the position.
2968
+ * @param orderParams.postOnly - Post-only behavior for the modified order.
2969
+ * @param orderParams.bitFlags - Bitmask, see `OrderParamsBitFlag`.
2970
+ * @param orderParams.policy - Bitmask of `ModifyOrderPolicy` (e.g. `MustModify`, `ExcludePreviousFill`).
2971
+ * @param orderParams.maxTs - Unix timestamp after which the order expires.
2972
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2973
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
2974
+ * @returns The transaction signature.
908
2975
  */
909
2976
  modifyOrder(orderParams: {
910
2977
  orderId: number;
@@ -924,10 +2991,12 @@ export declare class VelocityClient {
924
2991
  policy?: number;
925
2992
  }, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
926
2993
  /**
927
- * @param orderParams: The parameters for the order to modify.
928
- * @param subAccountId: Optional - The subaccount ID of the user to modify the order for.
929
- * @param userPublicKey: Optional - The public key of the user to modify the order for. This takes precedence over subAccountId.
930
- * @returns
2994
+ * Builds the `modifyOrder` instruction. See `modifyOrder` for field semantics/precisions.
2995
+ * @param orderParams - The parameters for the order to modify.
2996
+ * @param subAccountId - Optional - the sub-account ID of the user to modify the order for; ignored if `overrides.user` is set.
2997
+ * @param overrides - `user` supplies a fully-loaded `User` to modify on behalf of (takes precedence over `subAccountId`); `authority` overrides the signing authority (defaults to `overrides.user`'s authority, else `this.wallet.publicKey`).
2998
+ * @throws If `overrides.user` is provided but its `UserAccount` isn't loaded.
2999
+ * @returns The instruction.
931
3000
  */
932
3001
  getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }: {
933
3002
  orderId: number;
@@ -950,22 +3019,29 @@ export declare class VelocityClient {
950
3019
  authority?: PublicKey;
951
3020
  }): Promise<TransactionInstruction>;
952
3021
  /**
953
- * Modifies an open order by closing it and replacing it with a new order.
954
- * @param orderParams.userOrderId: The open order to modify
955
- * @param orderParams.newDirection: The new direction for the order
956
- * @param orderParams.newBaseAmount: The new base amount for the order
957
- * @param orderParams.newLimitPice: The new limit price for the order
958
- * @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
959
- * @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
960
- * @param orderParams.auctionDuration: Only required if order type changed to market from something else
961
- * @param orderParams.auctionStartPrice: Only required if order type changed to market from something else
962
- * @param orderParams.auctionEndPrice: Only required if order type changed to market from something else
963
- * @param orderParams.reduceOnly:
964
- * @param orderParams.postOnly:
965
- * @param orderParams.bitFlags:
966
- * @param orderParams.policy:
967
- * @param orderParams.maxTs:
968
- * @returns
3022
+ * Modifies an open order (identified by its caller-supplied `userOrderId`) by closing it and
3023
+ * replacing it with a new order in one instruction.
3024
+ *
3025
+ * Note: unlike `modifyOrder`, omitted `reduceOnly`/`bitFlags` are sent as `false`/`null`
3026
+ * respectively rather than "leave unchanged" passing this method's `orderParams` without
3027
+ * `reduceOnly` will explicitly clear an existing reduce-only flag on the order.
3028
+ * @param orderParams.userOrderId - The open order to modify (caller-supplied `userOrderId`).
3029
+ * @param orderParams.newDirection - The new direction for the order.
3030
+ * @param orderParams.newBaseAmount - The new base amount for the order, BASE_PRECISION (1e9).
3031
+ * @param orderParams.newLimitPrice - The new limit price for the order, PRICE_PRECISION (1e6).
3032
+ * @param orderParams.newOraclePriceOffset - The new oracle price offset for the order, PRICE_PRECISION (1e6), signed.
3033
+ * @param orderParams.newTriggerPrice - Optional - the new trigger price for the order, PRICE_PRECISION (1e6).
3034
+ * @param orderParams.auctionDuration - Only required if order type changed to market from something else; slots.
3035
+ * @param orderParams.auctionStartPrice - Only required if order type changed to market from something else; PRICE_PRECISION (1e6), signed.
3036
+ * @param orderParams.auctionEndPrice - Only required if order type changed to market from something else; PRICE_PRECISION (1e6), signed.
3037
+ * @param orderParams.reduceOnly - Whether the modified order must only reduce the position; defaults to `false` if omitted.
3038
+ * @param orderParams.postOnly - Post-only behavior for the modified order.
3039
+ * @param orderParams.bitFlags - Bitmask, see `OrderParamsBitFlag`; defaults to unset if omitted.
3040
+ * @param orderParams.policy - `ModifyOrderPolicy` bitmask (e.g. `MustModify`, `ExcludePreviousFill`).
3041
+ * @param orderParams.maxTs - Unix timestamp after which the order expires.
3042
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3043
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
3044
+ * @returns The transaction signature.
969
3045
  */
970
3046
  modifyOrderByUserOrderId(orderParams: {
971
3047
  userOrderId: number;
@@ -984,6 +3060,13 @@ export declare class VelocityClient {
984
3060
  policy?: ModifyOrderPolicy;
985
3061
  maxTs?: BN;
986
3062
  }, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
3063
+ /**
3064
+ * Builds the `modifyOrderByUserOrderId` instruction. See `modifyOrderByUserOrderId` for field
3065
+ * semantics/precisions, including the `reduceOnly`/`bitFlags` default-clearing note.
3066
+ * @param orderParams - The parameters for the order to modify.
3067
+ * @param subAccountId - Sub-account the order belongs to; defaults to the active sub-account.
3068
+ * @returns The instruction.
3069
+ */
987
3070
  getModifyOrderByUserIdIx({ userOrderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }: {
988
3071
  userOrderId: number;
989
3072
  newDirection?: PositionDirection;
@@ -1001,31 +3084,247 @@ export declare class VelocityClient {
1001
3084
  policy?: ModifyOrderPolicy;
1002
3085
  maxTs?: BN;
1003
3086
  }, subAccountId?: number): Promise<TransactionInstruction>;
3087
+ /**
3088
+ * Keeper instruction: settles unrealized perp PnL to/from each user's quote spot balance for
3089
+ * every `(user, marketIndex)` pair, one `settlePnl` instruction per pair in a single
3090
+ * transaction. Permissionless — any signer can act as the settling authority. Defaults to
3091
+ * `computeUnits: 1_400_000` if `txParams` is not supplied, since settling several users/markets
3092
+ * in one transaction is compute-heavy.
3093
+ * @param users - Users to settle, each with their user account public key and decoded account.
3094
+ * @param marketIndexes - Perp market indexes to settle for every user in `users`.
3095
+ * @param opts.filterInvalidMarkets - When true, drops any market index whose oracle currently
3096
+ * fails `isOracleValid` (per the on-chain oracle guard rails) before building instructions,
3097
+ * instead of letting the transaction fail on-chain for that market.
3098
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3099
+ * @returns The transaction signature.
3100
+ */
1004
3101
  settlePNLs(users: {
1005
3102
  settleeUserAccountPublicKey: PublicKey;
1006
3103
  settleeUserAccount: UserAccount;
1007
3104
  }[], marketIndexes: number[], opts?: {
1008
3105
  filterInvalidMarkets?: boolean;
1009
3106
  }, txParams?: TxParams): Promise<TransactionSignature>;
3107
+ /**
3108
+ * Builds one `settlePnl` instruction per `(user, marketIndex)` combination in `users` x
3109
+ * `marketIndexes`. See `settlePNL`/`settlePNLIx` for per-instruction semantics.
3110
+ * @param users - Users to settle, each with their user account public key and decoded account.
3111
+ * @param marketIndexes - Perp market indexes to settle for every user in `users`.
3112
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup; when a user's escrow
3113
+ * has completed builder or referral orders on a market being settled, its `RevenueShareEscrow`
3114
+ * and builder/referrer accounts are attached so the on-chain sweep can pay them out.
3115
+ * @returns The ordered instruction list.
3116
+ */
1010
3117
  getSettlePNLsIxs(users: {
1011
3118
  settleeUserAccountPublicKey: PublicKey;
1012
3119
  settleeUserAccount: UserAccount;
1013
3120
  }[], marketIndexes: number[], revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<Array<TransactionInstruction>>;
3121
+ /**
3122
+ * Keeper instruction: settles a single user's unrealized perp PnL on one market to/from their
3123
+ * quote spot balance. Reads the live oracle (falling back to the AMM's freshness check only if
3124
+ * the live oracle is degraded); requires the market not be in `Settlement` status (use
3125
+ * `settleExpiredMarket`/expired-position settlement for that) and the quote spot market vault
3126
+ * balance to reconcile afterward. Permissionless — any signer can act as the settling authority.
3127
+ * @param settleeUserAccountPublicKey - Public key of the user account to settle.
3128
+ * @param settleeUserAccount - Decoded user account to settle.
3129
+ * @param marketIndex - Perp market index to settle.
3130
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3131
+ * @param optionalIxs - Extra instructions prepended to the settle transaction.
3132
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup; see `settlePNLIx`.
3133
+ * @returns The transaction signature.
3134
+ */
1014
3135
  settlePNL(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number, txParams?: TxParams, optionalIxs?: TransactionInstruction[], revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionSignature>;
3136
+ /**
3137
+ * Builds the `settlePnl` instruction. See `settlePNL` for semantics. When
3138
+ * `revenueShareEscrowMap` is passed, inspects the settlee's `RevenueShareEscrow` for
3139
+ * completed, unpaid builder-fee or referral-reward orders on `marketIndex` and, if found,
3140
+ * appends the escrow PDA plus each relevant builder/referrer authority to
3141
+ * `remainingAccounts` so the on-chain sweep can pay them during settlement. Falls back to
3142
+ * attaching just the escrow PDA (for lazy cleanup) when the settlee has any builder order but
3143
+ * isn't present in the map (stale-cache case).
3144
+ * @param settleeUserAccountPublicKey - Public key of the user account to settle.
3145
+ * @param settleeUserAccount - Decoded user account to settle.
3146
+ * @param marketIndex - Perp market index to settle.
3147
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup keyed by authority.
3148
+ * @returns The instruction.
3149
+ */
1015
3150
  settlePNLIx(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number, revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionInstruction>;
3151
+ /**
3152
+ * Keeper instruction: settles one user's unrealized perp PnL across several markets in a
3153
+ * single `settleMultiplePnl` instruction/transaction. Fits at most ~4 markets per transaction
3154
+ * (see `settleMultiplePNLsMultipleTxs` for more). Permissionless — any signer can act as the
3155
+ * settling authority.
3156
+ * @param settleeUserAccountPublicKey - Public key of the user account to settle.
3157
+ * @param settleeUserAccount - Decoded user account to settle.
3158
+ * @param marketIndexes - Perp market indexes to settle (all in one transaction).
3159
+ * @param mode - `MustSettle` aborts the whole instruction if any per-market settlement fails;
3160
+ * `TrySettle` logs and skips failures so the remaining markets still settle.
3161
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup; see `settlePNLIx`.
3162
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3163
+ * @returns The transaction signature.
3164
+ */
1016
3165
  settleMultiplePNLs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, revenueShareEscrowMap?: RevenueShareEscrowMap, txParams?: TxParams): Promise<TransactionSignature>;
3166
+ /**
3167
+ * Settles one user's unrealized perp PnL across an arbitrary number of markets by splitting
3168
+ * `marketIndexes` into groups of 4 (more than ~4 markets' worth of accounts won't fit in a
3169
+ * single transaction) and sending one `settleMultiplePnl` transaction per group, sequentially.
3170
+ * Compute units scale with group size (`300_000` per market, capped at `1_400_000`).
3171
+ * @param settleeUserAccountPublicKey - Public key of the user account to settle.
3172
+ * @param settleeUserAccount - Decoded user account to settle.
3173
+ * @param marketIndexes - Perp market indexes to settle, in any quantity.
3174
+ * @param mode - `MustSettle` or `TrySettle`; see `settleMultiplePNLs`.
3175
+ * @param txParams - Optional compute-unit/priority-fee overrides (compute units are overridden
3176
+ * per group regardless of what is passed here).
3177
+ * @param optionalIxs - Extra instructions prepended to every group's transaction.
3178
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup; see `settlePNLIx`.
3179
+ * @returns One transaction signature per group of up to 4 markets, in group order.
3180
+ */
1017
3181
  settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, txParams?: TxParams, optionalIxs?: TransactionInstruction[], revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionSignature[]>;
3182
+ /**
3183
+ * Builds the `settleMultiplePnl` instruction. See `settleMultiplePNLs` for semantics. Attaches
3184
+ * the settlee's `RevenueShareEscrow` and any relevant builder/referrer accounts when
3185
+ * `revenueShareEscrowMap` shows completed builder/referral orders on any of `marketIndexes`
3186
+ * (same logic as `settlePNLIx`, generalized across markets).
3187
+ * @param settleeUserAccountPublicKey - Public key of the user account to settle.
3188
+ * @param settleeUserAccount - Decoded user account to settle.
3189
+ * @param marketIndexes - Perp market indexes to settle.
3190
+ * @param mode - `MustSettle` or `TrySettle`; see `settleMultiplePNLs`.
3191
+ * @param overrides.authority - Settling authority override, if different from this client's wallet.
3192
+ * @param revenueShareEscrowMap - Optional builder/referral escrow lookup keyed by authority.
3193
+ * @returns The instruction.
3194
+ */
1018
3195
  settleMultiplePNLsIx(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, overrides?: {
1019
3196
  authority?: PublicKey;
1020
3197
  }, revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionInstruction>;
3198
+ /**
3199
+ * Builds the `setUserStatusToBeingLiquidated` instruction. See `setUserStatusToBeingLiquidated`
3200
+ * for semantics.
3201
+ * @param userAccountPublicKey - Public key of the target user's user account.
3202
+ * @param userAccount - Decoded user account of the target user.
3203
+ * @returns The instruction.
3204
+ */
1021
3205
  getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
3206
+ /**
3207
+ * Keeper instruction: flags a user account as being liquidated (sets the `beingLiquidated`
3208
+ * status bit) without performing any liquidation itself. Used to "claim" a liquidation ahead of
3209
+ * the actual `liquidatePerp`/`liquidateSpot` call so a concurrent liquidator can't race it; the
3210
+ * on-chain handler re-checks the user is actually below maintenance margin before setting the
3211
+ * flag. Permissionless — any signer can act as liquidator.
3212
+ * @param userAccountPublicKey - Public key of the target user's user account.
3213
+ * @param userAccount - Decoded user account of the target user.
3214
+ * @returns The transaction signature.
3215
+ */
1022
3216
  setUserStatusToBeingLiquidated(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionSignature>;
3217
+ /**
3218
+ * Keeper instruction: liquidates part or all of a user's perp position in `marketIndex` when the
3219
+ * user is below maintenance margin (or already flagged `beingLiquidated`), transferring the
3220
+ * position to the calling liquidator's sub-account at the oracle price (subject to `limitPrice`
3221
+ * and the on-chain liquidation fee). Reverts if `userAccountPublicKey` equals the liquidator's
3222
+ * own user account. Permissionless — any signer can act as liquidator, taking on the position
3223
+ * and its PnL themselves.
3224
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3225
+ * @param userAccount - Decoded user account being liquidated.
3226
+ * @param marketIndex - Perp market index of the position to liquidate.
3227
+ * @param maxBaseAssetAmount - Maximum base amount the liquidator is willing to take on, BASE_PRECISION (1e9).
3228
+ * @param limitPrice - Optional worst acceptable price for the liquidator, PRICE_PRECISION (1e6).
3229
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3230
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3231
+ * @returns The transaction signature.
3232
+ */
1023
3233
  liquidatePerp(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, maxBaseAssetAmount: BN, limitPrice?: BN, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3234
+ /**
3235
+ * Builds the `liquidatePerp` instruction. See `liquidatePerp` for semantics.
3236
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3237
+ * @param userAccount - Decoded user account being liquidated.
3238
+ * @param marketIndex - Perp market index of the position to liquidate.
3239
+ * @param maxBaseAssetAmount - Maximum base amount the liquidator is willing to take on, BASE_PRECISION (1e9).
3240
+ * @param limitPrice - Optional worst acceptable price for the liquidator, PRICE_PRECISION (1e6).
3241
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3242
+ * @returns The instruction.
3243
+ */
1024
3244
  getLiquidatePerpIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, maxBaseAssetAmount: BN, limitPrice?: BN, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3245
+ /**
3246
+ * Keeper instruction: liquidates a user's perp position in `marketIndex` by filling it directly
3247
+ * against the supplied `makerInfos` (instead of transferring it to the liquidator's own
3248
+ * sub-account as `liquidatePerp` does). Reverts if `userAccountPublicKey` equals the liquidator's
3249
+ * own user account. Permissionless — any signer can act as liquidator/filler.
3250
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3251
+ * @param userAccount - Decoded user account being liquidated.
3252
+ * @param marketIndex - Perp market index of the position to liquidate.
3253
+ * @param makerInfos - Maker(s) to fill the liquidated position against.
3254
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3255
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3256
+ * @returns The transaction signature.
3257
+ */
1025
3258
  liquidatePerpWithFill(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, makerInfos: MakerInfo[], txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3259
+ /**
3260
+ * Builds the `liquidatePerpWithFill` instruction. See `liquidatePerpWithFill` for semantics.
3261
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3262
+ * @param userAccount - Decoded user account being liquidated.
3263
+ * @param marketIndex - Perp market index of the position to liquidate.
3264
+ * @param makerInfos - Maker(s) to fill the liquidated position against; each contributes a
3265
+ * `(maker, makerStats)` pair appended to `remainingAccounts`.
3266
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3267
+ * @returns The instruction.
3268
+ */
1026
3269
  getLiquidatePerpWithFillIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, makerInfos: MakerInfo[], liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3270
+ /**
3271
+ * Keeper instruction: liquidates a user's spot position by transferring `liabilityMarketIndex`
3272
+ * debt from the user to the liquidator's own sub-account in exchange for `assetMarketIndex`
3273
+ * collateral, when the user is below maintenance margin (or already flagged `beingLiquidated`).
3274
+ * Reverts if `userAccountPublicKey` equals the liquidator's own user account. Permissionless —
3275
+ * any signer can act as liquidator.
3276
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3277
+ * @param userAccount - Decoded user account being liquidated.
3278
+ * @param assetMarketIndex - Spot market index of the collateral the liquidator receives.
3279
+ * @param liabilityMarketIndex - Spot market index of the debt the liquidator repays/absorbs.
3280
+ * @param maxLiabilityTransfer - Maximum liability amount the liquidator is willing to take on, in
3281
+ * the liability spot market's token (mint) precision.
3282
+ * @param limitPrice - Optional worst acceptable asset/liability price ratio, PRICE_PRECISION (1e6).
3283
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3284
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3285
+ * @returns The transaction signature.
3286
+ */
1027
3287
  liquidateSpot(userAccountPublicKey: PublicKey, userAccount: UserAccount, assetMarketIndex: number, liabilityMarketIndex: number, maxLiabilityTransfer: BN, limitPrice?: BN, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3288
+ /**
3289
+ * Builds the `liquidateSpot` instruction. See `liquidateSpot` for semantics.
3290
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3291
+ * @param userAccount - Decoded user account being liquidated.
3292
+ * @param assetMarketIndex - Spot market index of the collateral the liquidator receives.
3293
+ * @param liabilityMarketIndex - Spot market index of the debt the liquidator repays/absorbs.
3294
+ * @param maxLiabilityTransfer - Maximum liability amount the liquidator is willing to take on, in
3295
+ * the liability spot market's token (mint) precision.
3296
+ * @param limitPrice - Optional worst acceptable asset/liability price ratio, PRICE_PRECISION (1e6).
3297
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3298
+ * @returns The instruction.
3299
+ */
1028
3300
  getLiquidateSpotIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, assetMarketIndex: number, liabilityMarketIndex: number, maxLiabilityTransfer: BN, limitPrice?: BN, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3301
+ /**
3302
+ * Builds a Jupiter-routed spot-liquidation-with-swap instruction set: swaps the liquidator's
3303
+ * `assetMarketIndex` proceeds into `liabilityMarketIndex` tokens via Jupiter inside a
3304
+ * `beginSwap`/`endSwap` flash-loan sandwich (see `getLiquidateSpotWithSwapIx`), letting the
3305
+ * liquidator repay the user's debt without needing to already hold the liability token. Fetches a
3306
+ * quote from `jupiterClient` when `quote` is not supplied, and idempotently creates any missing
3307
+ * associated token accounts.
3308
+ * @param jupiterClient - Jupiter client used to fetch the quote/swap transaction.
3309
+ * @param liabilityMarketIndex - Spot market index of the debt being repaid (swap output).
3310
+ * @param assetMarketIndex - Spot market index of the collateral being sold (swap input).
3311
+ * @param swapAmount - Amount of `assetMarketIndex` token to sell, in that market's mint precision.
3312
+ * @param assetTokenAccount - Token account to debit for the swap input; defaults to this client's
3313
+ * associated token account for `assetMarketIndex`, created if missing.
3314
+ * @param liabilityTokenAccount - Token account to credit with the swap output; defaults to this
3315
+ * client's associated token account for `liabilityMarketIndex`, created if missing.
3316
+ * @param slippageBps - Max slippage in basis points passed to Jupiter.
3317
+ * @param swapMode - Jupiter swap mode (`ExactIn`/`ExactOut`).
3318
+ * @param onlyDirectRoutes - Restrict Jupiter to single-hop routes.
3319
+ * @param quote - Pre-fetched Jupiter quote (skips an extra round-trip).
3320
+ * @param userAccount - Decoded user account being liquidated.
3321
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3322
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3323
+ * @param maxAccounts - Caps the number of accounts Jupiter's route may use.
3324
+ * @throws If no quote can be fetched and `quote` was not supplied.
3325
+ * @returns The ordered instructions (pre-instructions, `beginSwap`, Jupiter swap, `endSwap`) and
3326
+ * any address lookup tables the Jupiter route requires.
3327
+ */
1029
3328
  getJupiterLiquidateSpotWithSwapIxV6({ jupiterClient, liabilityMarketIndex, assetMarketIndex, swapAmount, assetTokenAccount, liabilityTokenAccount, slippageBps, swapMode, onlyDirectRoutes, quote, userAccount, userAccountPublicKey, liquidatorSubAccountId, maxAccounts, }: {
1030
3329
  jupiterClient: JupiterClient;
1031
3330
  liabilityMarketIndex: number;
@@ -1046,15 +3345,22 @@ export declare class VelocityClient {
1046
3345
  lookupTables: AddressLookupTableAccount[];
1047
3346
  }>;
1048
3347
  /**
1049
- * Get the velocity liquidate_spot_with_swap instructions
1050
- *
1051
- * @param liabilityMarketIndex the market index of the token you're buying
1052
- * @param assetMarketIndex the market index of the token you're selling
1053
- * @param amountIn the amount of the token to sell
1054
- * @param assetTokenAccount the token account to move the tokens being sold
1055
- * @param liabilityTokenAccount the token account to receive the tokens being bought
1056
- * @param userAccount
1057
- * @param userAccountPublicKey
3348
+ * Builds the `liquidateSpotWithSwapBegin`/`...End` instruction pair that sandwiches an
3349
+ * external swap (e.g. Jupiter) so a liquidator can repay a user's `liabilityMarketIndex` debt
3350
+ * using proceeds from selling `assetMarketIndex` collateral within the same transaction, without
3351
+ * pre-funding the liability token. The on-chain handler validates the liability spot market's
3352
+ * flash-loan balance is unwound by `endSwap`. See `getJupiterLiquidateSpotWithSwapIxV6` for the
3353
+ * Jupiter-specific wrapper that assembles the full instruction list around this pair.
3354
+ * @param liabilityMarketIndex - Spot market index of the debt being repaid (swap output/buy side).
3355
+ * @param assetMarketIndex - Spot market index of the collateral being sold (swap input/sell side).
3356
+ * @param swapAmount - Amount of `assetMarketIndex` token to sell, in that market's mint precision.
3357
+ * @param assetTokenAccount - Token account to debit for the swap input.
3358
+ * @param liabilityTokenAccount - Token account to credit with the swap output.
3359
+ * @param userAccount - Decoded user account being liquidated.
3360
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3361
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3362
+ * @returns `beginSwapIx`/`endSwapIx` — the caller must place the external swap instructions
3363
+ * between them.
1058
3364
  */
1059
3365
  getLiquidateSpotWithSwapIx({ liabilityMarketIndex, assetMarketIndex, swapAmount: swapAmount, assetTokenAccount, liabilityTokenAccount, userAccount, userAccountPublicKey, liquidatorSubAccountId, }: {
1060
3366
  liabilityMarketIndex: number;
@@ -1069,29 +3375,277 @@ export declare class VelocityClient {
1069
3375
  beginSwapIx: TransactionInstruction;
1070
3376
  endSwapIx: TransactionInstruction;
1071
3377
  }>;
3378
+ /**
3379
+ * Keeper instruction: liquidates a user by transferring `liabilityMarketIndex` spot debt from the
3380
+ * user to the liquidator in exchange for a matching amount of the user's positive unsettled perp
3381
+ * PnL in `perpMarketIndex`. Only usable once the user's position size in `perpMarketIndex` is
3382
+ * zero (the PnL must already be fully unrealized/settled-out, not backed by an open position).
3383
+ * Reverts if `userAccountPublicKey` equals the liquidator's own user account. Permissionless —
3384
+ * any signer can act as liquidator.
3385
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3386
+ * @param userAccount - Decoded user account being liquidated.
3387
+ * @param perpMarketIndex - Perp market index whose unsettled PnL backs the transfer, QUOTE_PRECISION (1e6).
3388
+ * @param liabilityMarketIndex - Spot market index of the debt being repaid.
3389
+ * @param maxLiabilityTransfer - Maximum liability amount the liquidator is willing to take on, in
3390
+ * the liability spot market's token (mint) precision.
3391
+ * @param limitPrice - Optional worst acceptable liability/PnL price ratio, PRICE_PRECISION (1e6).
3392
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3393
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3394
+ * @returns The transaction signature.
3395
+ */
1072
3396
  liquidateBorrowForPerpPnl(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: number, liabilityMarketIndex: number, maxLiabilityTransfer: BN, limitPrice?: BN, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3397
+ /**
3398
+ * Builds the `liquidateBorrowForPerpPnl` instruction. See `liquidateBorrowForPerpPnl` for semantics.
3399
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3400
+ * @param userAccount - Decoded user account being liquidated.
3401
+ * @param perpMarketIndex - Perp market index whose unsettled PnL backs the transfer.
3402
+ * @param liabilityMarketIndex - Spot market index of the debt being repaid.
3403
+ * @param maxLiabilityTransfer - Maximum liability amount the liquidator is willing to take on, in
3404
+ * the liability spot market's token (mint) precision.
3405
+ * @param limitPrice - Optional worst acceptable liability/PnL price ratio, PRICE_PRECISION (1e6).
3406
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3407
+ * @returns The instruction.
3408
+ */
1073
3409
  getLiquidateBorrowForPerpPnlIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: number, liabilityMarketIndex: number, maxLiabilityTransfer: BN, limitPrice?: BN, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3410
+ /**
3411
+ * Keeper instruction: liquidates a user by transferring negative unsettled perp PnL in
3412
+ * `perpMarketIndex` from the user to the liquidator in exchange for `assetMarketIndex` spot
3413
+ * collateral (the inverse of `liquidateBorrowForPerpPnl`). Only usable once the user's position
3414
+ * size in `perpMarketIndex` is zero. Reverts if `userAccountPublicKey` equals the liquidator's
3415
+ * own user account. Permissionless — any signer can act as liquidator.
3416
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3417
+ * @param userAccount - Decoded user account being liquidated.
3418
+ * @param perpMarketIndex - Perp market index of the negative unsettled PnL being absorbed.
3419
+ * @param assetMarketIndex - Spot market index of the collateral the liquidator receives.
3420
+ * @param maxPnlTransfer - Maximum PnL amount the liquidator is willing to absorb, QUOTE_PRECISION (1e6).
3421
+ * @param limitPrice - Optional worst acceptable PnL/asset price ratio, PRICE_PRECISION (1e6).
3422
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3423
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3424
+ * @returns The transaction signature.
3425
+ */
1074
3426
  liquidatePerpPnlForDeposit(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: number, assetMarketIndex: number, maxPnlTransfer: BN, limitPrice?: BN, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3427
+ /**
3428
+ * Builds the `liquidatePerpPnlForDeposit` instruction. See `liquidatePerpPnlForDeposit` for semantics.
3429
+ * @param userAccountPublicKey - Public key of the user account being liquidated.
3430
+ * @param userAccount - Decoded user account being liquidated.
3431
+ * @param perpMarketIndex - Perp market index of the negative unsettled PnL being absorbed.
3432
+ * @param assetMarketIndex - Spot market index of the collateral the liquidator receives.
3433
+ * @param maxPnlTransfer - Maximum PnL amount the liquidator is willing to absorb, QUOTE_PRECISION (1e6).
3434
+ * @param limitPrice - Optional worst acceptable PnL/asset price ratio, PRICE_PRECISION (1e6).
3435
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3436
+ * @returns The instruction.
3437
+ */
1075
3438
  getLiquidatePerpPnlForDepositIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: number, assetMarketIndex: number, maxPnlTransfer: BN, limitPrice?: BN, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3439
+ /**
3440
+ * Keeper instruction: resolves a user's perp bankruptcy in `marketIndex` (negative equity that
3441
+ * liquidation alone could not cover) by socializing the loss — first attempting to backstop it
3442
+ * from the quote spot market's insurance fund, then socializing any remainder across the market's
3443
+ * other position holders via the cumulative funding/PnL pool. Reverts if the resulting insurance
3444
+ * payout would fully drain the insurance fund vault, or if `userAccountPublicKey` equals the
3445
+ * liquidator's own user account. Permissionless — any signer can act as liquidator.
3446
+ * @param userAccountPublicKey - Public key of the bankrupt user's user account.
3447
+ * @param userAccount - Decoded user account of the bankrupt user.
3448
+ * @param marketIndex - Perp market index of the bankrupt position.
3449
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3450
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3451
+ * @returns The transaction signature.
3452
+ */
1076
3453
  resolvePerpBankruptcy(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3454
+ /**
3455
+ * Builds the `resolvePerpBankruptcy` instruction. See `resolvePerpBankruptcy` for semantics.
3456
+ * Always settles against the quote spot market (`QUOTE_SPOT_MARKET_INDEX`).
3457
+ * @param userAccountPublicKey - Public key of the bankrupt user's user account.
3458
+ * @param userAccount - Decoded user account of the bankrupt user.
3459
+ * @param marketIndex - Perp market index of the bankrupt position.
3460
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3461
+ * @returns The instruction.
3462
+ */
1077
3463
  getResolvePerpBankruptcyIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3464
+ /**
3465
+ * Keeper instruction: resolves a user's spot bankruptcy (negative balance in `marketIndex` that
3466
+ * liquidation alone could not cover) by backstopping the deficit from that spot market's
3467
+ * insurance fund. Reverts if `userAccountPublicKey` equals the liquidator's own user account.
3468
+ * Permissionless — any signer can act as liquidator.
3469
+ * @param userAccountPublicKey - Public key of the bankrupt user's user account.
3470
+ * @param userAccount - Decoded user account of the bankrupt user.
3471
+ * @param marketIndex - Spot market index of the bankrupt balance.
3472
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3473
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3474
+ * @returns The transaction signature.
3475
+ */
1078
3476
  resolveSpotBankruptcy(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
3477
+ /**
3478
+ * Builds the `resolveSpotBankruptcy` instruction. See `resolveSpotBankruptcy` for semantics.
3479
+ * Adds the spot market's mint (and transfer-hook extra account metas, if applicable) to
3480
+ * `remainingAccounts` for the token transfer from the insurance fund vault.
3481
+ * @param userAccountPublicKey - Public key of the bankrupt user's user account.
3482
+ * @param userAccount - Decoded user account of the bankrupt user.
3483
+ * @param marketIndex - Spot market index of the bankrupt balance.
3484
+ * @param liquidatorSubAccountId - Liquidator's sub-account to credit; defaults to the active sub-account.
3485
+ * @returns The instruction.
3486
+ */
1079
3487
  getResolveSpotBankruptcyIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, liquidatorSubAccountId?: number): Promise<TransactionInstruction>;
3488
+ /**
3489
+ * Keeper instruction: recomputes and applies `marketIndex`'s hourly-anchored funding rate
3490
+ * (`cumulativeFundingRateLong`/`Short`, FUNDING_RATE_PRECISION, 1e9) from the current oracle/AMM
3491
+ * mark-price spread, then updates the market's oracle-derived TWAP stats. No-ops (via
3492
+ * `FundingWasNotUpdated`, which the underlying call surfaces as a failed transaction) if it is
3493
+ * not yet time for the next update — `perp_market.market_stats.funding_period` seconds since the
3494
+ * last update, on-the-hour aligned. Reverts if the market's funding is paused or the market is
3495
+ * not `Active`/`ReduceOnly`. Permissionless — any signer can act as keeper.
3496
+ * @param perpMarketIndex - Perp market index to update funding for.
3497
+ * @param oracle - The market's oracle account (`perpMarket.oracle`).
3498
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3499
+ * @returns The transaction signature.
3500
+ */
1080
3501
  updateFundingRate(perpMarketIndex: number, oracle: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
3502
+ /**
3503
+ * Builds the `updateFundingRate` instruction. See `updateFundingRate` for semantics.
3504
+ * @param perpMarketIndex - Perp market index to update funding for.
3505
+ * @param oracle - The market's oracle account (`perpMarket.oracle`).
3506
+ * @returns The instruction.
3507
+ */
1081
3508
  getUpdateFundingRateIx(perpMarketIndex: number, oracle: PublicKey): Promise<TransactionInstruction>;
3509
+ /**
3510
+ * Keeper instruction: refreshes a `Prelaunch`-oracle-source perp market's synthetic oracle price
3511
+ * from its own recent trading activity (used for markets without a live external price feed,
3512
+ * e.g. pre-listing futures). Only valid when the market's `oracleSource` is `Prelaunch`.
3513
+ * Permissionless — any signer can act as keeper.
3514
+ * @param perpMarketIndex - Perp market index to update; must use the `Prelaunch` oracle source.
3515
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3516
+ * @throws If `perpMarketIndex`'s `oracleSource` is not `Prelaunch`.
3517
+ * @returns The transaction signature.
3518
+ */
1082
3519
  updatePrelaunchOracle(perpMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3520
+ /**
3521
+ * Builds the `updatePrelaunchOracle` instruction. See `updatePrelaunchOracle` for semantics.
3522
+ * @param perpMarketIndex - Perp market index to update; must use the `Prelaunch` oracle source.
3523
+ * @throws If `perpMarketIndex`'s `oracleSource` is not `Prelaunch`.
3524
+ * @returns The instruction.
3525
+ */
1083
3526
  getUpdatePrelaunchOracleIx(perpMarketIndex: number): Promise<TransactionInstruction>;
3527
+ /**
3528
+ * Keeper instruction: estimates the market's bid/ask price from the given makers' resting DLOB
3529
+ * orders (kept only within `±BID_ASK_TWAP_MAX_ORACLE_DIVERGENCE_PERCENT` of the oracle price on
3530
+ * both sides) and folds the estimate into `lastBidPriceTwap`/`lastAskPriceTwap`. This does NOT
3531
+ * update the funding rate, crank funding separately via `getUpdateFundingRateIx`. Restricted:
3532
+ * the calling wallet's `UserStats` (which must be the signer's own) must have
3533
+ * `canUpdateBidAskTwap` set and at least 1000 USDC (`QUOTE_PRECISION`, 1e6) staked in the
3534
+ * insurance fund (`ifStakedQuoteAssetAmount`), or the instruction reverts.
3535
+ * @param perpMarketIndex - Perp market index to update.
3536
+ * @param makers - `(maker, makerStats)` pairs whose resting orders are sampled for the estimate.
3537
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3538
+ * @returns The transaction signature.
3539
+ */
1084
3540
  updatePerpBidAskTwap(perpMarketIndex: number, makers: [PublicKey, PublicKey][], txParams?: TxParams): Promise<TransactionSignature>;
3541
+ /**
3542
+ * Builds the `updatePerpBidAskTwap` instruction. See `updatePerpBidAskTwap` for semantics.
3543
+ * @param perpMarketIndex - Perp market index to update.
3544
+ * @param makers - `(maker, makerStats)` pairs whose resting orders are sampled for the estimate.
3545
+ * @returns The instruction.
3546
+ */
1085
3547
  getUpdatePerpBidAskTwapIx(perpMarketIndex: number, makers: [PublicKey, PublicKey][]): Promise<TransactionInstruction>;
3548
+ /**
3549
+ * Keeper instruction: settles accrued funding payments into the quote balance of every perp
3550
+ * position the target user currently holds, using each market's latest
3551
+ * `cumulativeFundingRateLong`/`Short` (FUNDING_RATE_PRECISION, 1e9). Fetches the user account
3552
+ * fresh from the RPC (does not rely on this client's subscription cache) to determine which
3553
+ * markets to include. Permissionless — any signer can act as keeper.
3554
+ * @param userAccountPublicKey - Public key of the user account to settle funding for.
3555
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3556
+ * @returns The transaction signature.
3557
+ */
1086
3558
  settleFundingPayment(userAccountPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
3559
+ /**
3560
+ * Builds the `settleFundingPayment` instruction. See `settleFundingPayment` for semantics. Fetches
3561
+ * the user account directly via `program.account.user.fetch` and includes every market the user
3562
+ * has a non-empty position in as a writable remaining account.
3563
+ * @param userAccountPublicKey - Public key of the user account to settle funding for.
3564
+ * @returns The instruction.
3565
+ */
1087
3566
  getSettleFundingPaymentIx(userAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
3567
+ /**
3568
+ * Manually emits an event on this client's internal `eventEmitter`, as if it had come from the
3569
+ * account subscriber. Intended for tests/tooling that need to simulate account-update events;
3570
+ * not used by normal instruction-building code paths.
3571
+ * @param eventName - Name of the event to emit; see `VelocityClientAccountEvents`.
3572
+ * @param data - Optional event payload.
3573
+ */
1088
3574
  triggerEvent(eventName: keyof VelocityClientAccountEvents, data?: any): void;
3575
+ /**
3576
+ * Reads the last-known primary oracle price for a perp market from the account subscriber's
3577
+ * cache (no RPC call). This is the raw exchange oracle price, unadjusted by the market's MM
3578
+ * oracle — use `getMMOracleDataForPerpMarket` when you need the price the program actually uses
3579
+ * for fills/margin.
3580
+ * @param marketIndex - Perp market index.
3581
+ * @throws If subscribed oracle price data is not available for `marketIndex`.
3582
+ * @returns Oracle price data; `price`/`confidence` are PRICE_PRECISION (1e6).
3583
+ */
1089
3584
  getOracleDataForPerpMarket(marketIndex: number): OraclePriceData;
3585
+ /**
3586
+ * Resolves the effective oracle price the program uses for `marketIndex` — the market's MM
3587
+ * (market-maker-fed) oracle when it is fresher, valid, and not too divergent from the primary
3588
+ * exchange oracle; otherwise falls back to the primary oracle. Mirrors the on-chain
3589
+ * `get_mm_oracle_price_data` gating so client-side price reads (mark price, margin, liquidation
3590
+ * previews) match what a fill/settlement will actually see.
3591
+ *
3592
+ * Falls back to the primary oracle (`getOracleDataForPerpMarket`) when any of the following hold:
3593
+ * - the MM oracle price is zero (uninitialized) or its computed `OracleValidity` is
3594
+ * `NonPositive`/`TooVolatile` (per `state.oracleGuardRails`);
3595
+ * - the primary oracle is judged more recent than the MM oracle — by sequence-id ordering when
3596
+ * both oracles have a usable, closely-matched `sequenceId`, otherwise by slot comparison;
3597
+ * - the MM and primary oracle prices diverge by more than 1% (`PERCENTAGE_PRECISION`, 1e6 scale).
3598
+ *
3599
+ * Otherwise returns the MM oracle's price/slot/confidence.
3600
+ * @param marketIndex - Perp market index.
3601
+ * @throws If subscribed oracle price data is not available for `marketIndex`.
3602
+ * @returns Oracle price data (`price`/`confidence` at PRICE_PRECISION, 1e6) plus `isMMOracleActive`
3603
+ * indicating whether the market has an initialized MM oracle at all (independent of which price
3604
+ * was ultimately selected).
3605
+ */
1090
3606
  getMMOracleDataForPerpMarket(marketIndex: number): MMOraclePriceData;
3607
+ /**
3608
+ * Reads the last-known oracle price for a spot market from the account subscriber's cache (no
3609
+ * RPC call). Spot markets do not have an MM oracle — this is always the effective price used for
3610
+ * margin/borrow-lending calculations.
3611
+ * @param marketIndex - Spot market index.
3612
+ * @throws If subscribed oracle price data is not available for `marketIndex`.
3613
+ * @returns Oracle price data; `price`/`confidence` are PRICE_PRECISION (1e6).
3614
+ */
1091
3615
  getOracleDataForSpotMarket(marketIndex: number): OraclePriceData;
3616
+ /**
3617
+ * Creates this wallet's `InsuranceFundStake` PDA for `marketIndex`, required once before staking
3618
+ * into that market's insurance fund for the first time. A caller may only initialize their own
3619
+ * stake account. Reverts if insurance-fund init is paused for the market.
3620
+ * @param marketIndex - Spot market index whose insurance fund to stake into.
3621
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3622
+ * @returns The transaction signature.
3623
+ */
1092
3624
  initializeInsuranceFundStake(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
1093
- getInitializeInsuranceFundStakeIx(marketIndex: number): Promise<TransactionInstruction>;
1094
- getAddInsuranceFundStakeIx(marketIndex: number, amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
3625
+ /**
3626
+ * Builds the `initializeInsuranceFundStake` instruction. See `initializeInsuranceFundStake` for
3627
+ * semantics.
3628
+ * @param marketIndex - Spot market index whose insurance fund to stake into.
3629
+ * @returns The instruction.
3630
+ */
3631
+ getInitializeInsuranceFundStakeIx(marketIndex: number, overrides?: {
3632
+ authority?: PublicKey;
3633
+ }): Promise<TransactionInstruction>;
3634
+ /**
3635
+ * Builds the `addInsuranceFundStake` instruction, transferring `amount` of the market's token
3636
+ * from `collateralAccountPublicKey` into its insurance fund vault and minting the caller's
3637
+ * `InsuranceFundStake` the corresponding IF shares. Reverts if `amount` is zero, the spot market
3638
+ * is not active, insurance-fund add is paused, or a withdraw request is already in progress on
3639
+ * the stake account. See `addInsuranceFundStake`/`getAddInsuranceFundStakeIxs` for a wrapper that
3640
+ * also handles account creation and funding from a sub-account.
3641
+ * @param marketIndex - Spot market index whose insurance fund to stake into.
3642
+ * @param amount - Amount to stake, in the spot market's token (mint) precision.
3643
+ * @param collateralAccountPublicKey - Token account to debit for the stake.
3644
+ * @returns The instruction.
3645
+ */
3646
+ getAddInsuranceFundStakeIx(marketIndex: number, amount: BN, collateralAccountPublicKey: PublicKey, overrides?: {
3647
+ authority?: PublicKey;
3648
+ }): Promise<TransactionInstruction>;
1095
3649
  /**
1096
3650
  * Add to an insurance fund stake and optionally initialize the account
1097
3651
  */
@@ -1137,17 +3691,125 @@ export declare class VelocityClient {
1137
3691
  */
1138
3692
  fromSubaccount?: boolean;
1139
3693
  }): Promise<TransactionInstruction[]>;
3694
+ /**
3695
+ * Starts the unstaking cooldown for this wallet's insurance fund stake in `marketIndex`, locking
3696
+ * in the number of IF shares corresponding to `amount` at the current share price. The actual
3697
+ * withdrawal must be completed with `removeInsuranceFundStake` after
3698
+ * `spotMarket.insuranceFund.unstakingPeriod` seconds have elapsed; only one request may be
3699
+ * in-flight per stake account (`cancelRequestRemoveInsuranceFundStake` to reset). A caller may
3700
+ * only act on their own stake account.
3701
+ * @param marketIndex - Spot market index of the insurance fund stake.
3702
+ * @param amount - Amount to request removal of, in the spot market's token (mint) precision;
3703
+ * converted to IF shares at the current vault share price.
3704
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3705
+ * @returns The transaction signature.
3706
+ */
1140
3707
  requestRemoveInsuranceFundStake(marketIndex: number, amount: BN, txParams?: TxParams): Promise<TransactionSignature>;
3708
+ /**
3709
+ * Cancels this wallet's in-progress `requestRemoveInsuranceFundStake` for `marketIndex`, clearing
3710
+ * the pending withdraw request so the stake resumes earning normally. Reverts if no withdraw
3711
+ * request is currently in progress. A caller may only act on their own stake account.
3712
+ * @param marketIndex - Spot market index of the insurance fund stake.
3713
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3714
+ * @returns The transaction signature.
3715
+ */
1141
3716
  cancelRequestRemoveInsuranceFundStake(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3717
+ /**
3718
+ * Completes a previously-requested insurance fund unstake for `marketIndex`, transferring the
3719
+ * requested shares' worth of tokens from the insurance fund vault to `collateralAccountPublicKey`
3720
+ * (creating it, and a temporary wrapped-SOL account if the market is SOL, when needed). Reverts
3721
+ * if `spotMarket.insuranceFund.unstakingPeriod` has not yet elapsed since the matching
3722
+ * `requestRemoveInsuranceFundStake`, or if the spot market's utilization is above the healthy
3723
+ * threshold. A caller may only act on their own stake account.
3724
+ * @param marketIndex - Spot market index of the insurance fund stake.
3725
+ * @param collateralAccountPublicKey - Token account to receive the withdrawn tokens.
3726
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3727
+ * @returns The transaction signature.
3728
+ */
1142
3729
  removeInsuranceFundStake(marketIndex: number, collateralAccountPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
3730
+ /**
3731
+ * Keeper instruction: refreshes `authority`'s quote-market (`QUOTE_SPOT_MARKET_INDEX`) insurance
3732
+ * fund stake bookkeeping (applies any pending rebase to the stake's share count/value) without
3733
+ * adding or removing funds. `insuranceFundStake` and `userStats` must belong to the same
3734
+ * authority. Permissionless — any signer can trigger the refresh for any staker.
3735
+ * @param authority - Authority whose quote-market insurance fund stake to refresh.
3736
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3737
+ * @returns The transaction signature.
3738
+ */
1143
3739
  updateUserQuoteAssetInsuranceStake(authority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
3740
+ /**
3741
+ * Builds the `updateUserQuoteAssetInsuranceStake` instruction. See
3742
+ * `updateUserQuoteAssetInsuranceStake` for semantics. Always targets `QUOTE_SPOT_MARKET_INDEX`.
3743
+ * @param authority - Authority whose quote-market insurance fund stake to refresh.
3744
+ * @returns The instruction.
3745
+ */
1144
3746
  getUpdateUserQuoteAssetInsuranceStakeIx(authority: PublicKey): Promise<TransactionInstruction>;
3747
+ /**
3748
+ * Keeper instruction: sweeps the market's proportional share of accumulated protocol revenue from
3749
+ * its spot vault into its insurance fund vault. Only callable once per
3750
+ * `spotMarket.insuranceFund.revenueSettlePeriod` seconds (on-the-hour aligned from
3751
+ * `lastRevenueSettleTs`); reverts early with the remaining wait time otherwise. Reverts if the
3752
+ * market has `revenueSettlePeriod <= 0` (settling to IF disabled). Permissionless — any signer
3753
+ * can trigger the sweep.
3754
+ * @param spotMarketIndex - Spot market index to settle revenue for.
3755
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3756
+ * @returns The transaction signature.
3757
+ */
1145
3758
  settleRevenueToInsuranceFund(spotMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3759
+ /**
3760
+ * Builds the `settleRevenueToInsuranceFund` instruction. See `settleRevenueToInsuranceFund` for
3761
+ * semantics.
3762
+ * @param spotMarketIndex - Spot market index to settle revenue for.
3763
+ * @returns The instruction.
3764
+ */
1146
3765
  getSettleRevenueToInsuranceFundIx(spotMarketIndex: number): Promise<TransactionInstruction>;
3766
+ /**
3767
+ * Permissionless streaming-sweep keeper instruction: materializes a perp market's accrued pending
3768
+ * fee carveouts out of the PnL pool — `pendingProtocolFee` to the market's protocol fee pool
3769
+ * (runs first, buffer-exempt), then `pendingIfFee` to the quote spot market's revenue pool and
3770
+ * `pendingAmmProvision` into the AMM's fee pool (both leave `feePoolBufferTarget` behind). Every
3771
+ * drain reserves `max(netUserPnl, 0)` so user claims stay backed. This runs inline on every
3772
+ * `settlePNL` already — this instruction lets a keeper run it on demand without settling anyone's
3773
+ * PnL. Gates the oracle price used to value `netUserPnl` the same way `settlePNL` does (price-band
3774
+ * + validity/divergence checks when the market has curve updates enabled).
3775
+ * @param perpMarketIndex - Perp market index to sweep fees for.
3776
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3777
+ * @returns The transaction signature.
3778
+ */
1147
3779
  sweepPerpMarketFees(perpMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3780
+ /**
3781
+ * Builds the `sweepPerpMarketFees` instruction. See `sweepPerpMarketFees` for semantics.
3782
+ * @param perpMarketIndex - Perp market index to sweep fees for.
3783
+ * @returns The instruction.
3784
+ */
1148
3785
  getSweepPerpMarketFeesIx(perpMarketIndex: number): Promise<TransactionInstruction>;
3786
+ /**
3787
+ * Keeper instruction: backstops a perp market's negative PnL pool from the quote spot market's
3788
+ * insurance fund (first attempting a revenue-to-IF settlement so the vault balance is
3789
+ * up-to-date). `spotMarketIndex` must be `QUOTE_SPOT_MARKET_INDEX`. Permissionless — any signer
3790
+ * can trigger it.
3791
+ * @param spotMarketIndex - Spot market index backing the deficit; must be `QUOTE_SPOT_MARKET_INDEX`.
3792
+ * @param perpMarketIndex - Perp market index whose PnL pool deficit to resolve.
3793
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3794
+ * @throws (on-chain) if `spotMarketIndex` is not the quote spot market.
3795
+ * @returns The transaction signature.
3796
+ */
1149
3797
  resolvePerpPnlDeficit(spotMarketIndex: number, perpMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3798
+ /**
3799
+ * Builds the `resolvePerpPnlDeficit` instruction. See `resolvePerpPnlDeficit` for semantics.
3800
+ * @param spotMarketIndex - Spot market index backing the deficit; must be `QUOTE_SPOT_MARKET_INDEX`.
3801
+ * @param perpMarketIndex - Perp market index whose PnL pool deficit to resolve.
3802
+ * @returns The instruction.
3803
+ */
1150
3804
  getResolvePerpPnlDeficitIx(spotMarketIndex: number, perpMarketIndex: number): Promise<TransactionInstruction>;
3805
+ /**
3806
+ * Builds the `depositIntoSpotMarketRevenuePool` instruction. See `depositIntoSpotMarketRevenuePool`
3807
+ * for semantics.
3808
+ * @param marketIndex - Spot market index whose revenue pool to donate into.
3809
+ * @param amount - Amount to donate, in the spot market's token (mint) precision.
3810
+ * @param userTokenAccountPublicKey - Token account to debit for the donation.
3811
+ * @returns The instruction.
3812
+ */
1151
3813
  getDepositIntoSpotMarketRevenuePoolIx(marketIndex: number, amount: BN, userTokenAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
1152
3814
  /**
1153
3815
  * This ix will donate your funds to velocity revenue pool. It does not deposit into your user account
@@ -1157,14 +3819,24 @@ export declare class VelocityClient {
1157
3819
  * @returns
1158
3820
  */
1159
3821
  depositIntoSpotMarketRevenuePool(marketIndex: number, amount: BN, userTokenAccountPublicKey: PublicKey): Promise<TransactionSignature>;
3822
+ /**
3823
+ * Computes display/risk metadata for a perp market from currently-subscribed account state (no
3824
+ * RPC call): minimum order size, maintenance margin ratio, PnL pool value, contract tier, and the
3825
+ * maximum insurance available to the market.
3826
+ * @param marketIndex - Perp market index.
3827
+ * @returns `minOrderSize`/`marginMaintenance` in the market's native units; `pnlPoolValue` and
3828
+ * `availableInsurance` in QUOTE_PRECISION (1e6).
3829
+ */
1160
3830
  getPerpMarketExtendedInfo(marketIndex: number): PerpMarketExtendedInfo;
1161
3831
  /**
1162
3832
  * Calculates taker / maker fee (as a percentage, e.g. .001 = 10 basis points) for particular marketType
1163
3833
  * @param marketType
1164
3834
  * @param positionMarketIndex
3835
+ * @param user
3836
+ * @param orderParams When it carries a builder code, the builder fee (quoteAssetAmount * builderFeeTenthBps / 100_000) is added to takerFee.
1165
3837
  * @returns : {takerFee: number, makerFee: number} Precision None
1166
3838
  */
1167
- getMarketFees(marketType: MarketType, marketIndex?: number, user?: User): {
3839
+ getMarketFees(marketType: MarketType, marketIndex?: number, user?: User, orderParams?: Pick<OrderParams, 'builderIdx' | 'builderFeeTenthBps'>): {
1168
3840
  takerFee: number;
1169
3841
  makerFee: number;
1170
3842
  };
@@ -1178,31 +3850,282 @@ export declare class VelocityClient {
1178
3850
  marketIndex: number;
1179
3851
  marketType: MarketType;
1180
3852
  } | undefined;
3853
+ /**
3854
+ * Posts a signed Pyth Lazer price update on-chain for one or more feeds, prepended with the
3855
+ * Ed25519 signature-verification instruction the handler requires. Permissionless — any signer
3856
+ * can post a valid, correctly-signed update.
3857
+ * @param feedIds - Pyth Lazer feed IDs to update, in the same order as the encoded message.
3858
+ * @param pythMessageHex - Hex-encoded, Pyth-signed Lazer update message.
3859
+ * @returns The transaction signature.
3860
+ */
1181
3861
  postPythLazerOracleUpdate(feedIds: number[], pythMessageHex: string): Promise<string>;
3862
+ /**
3863
+ * Builds the `postPythLazerOracleUpdate` instruction pair. See `postPythLazerOracleUpdate` for
3864
+ * semantics.
3865
+ * @param feedIds - Pyth Lazer feed IDs to update, in the same order as the encoded message.
3866
+ * @param pythMessageHex - Hex-encoded, Pyth-signed Lazer update message.
3867
+ * @param precedingIxs - Instructions that will be placed before the returned pair in the final
3868
+ * transaction; only their count is used, to compute the Ed25519 verify instruction's index.
3869
+ * @param overrideCustomIxIndex - Explicit index of the verify instruction within the transaction,
3870
+ * overriding the `precedingIxs.length + 1` default.
3871
+ * @returns `[verifyIx, updateIx]` — the Ed25519 signature-verification instruction followed by the
3872
+ * oracle-update instruction; both must be included, in order, in the same transaction.
3873
+ */
1182
3874
  getPostPythLazerOracleUpdateIxs(feedIds: number[], pythMessageHex: string, precedingIxs?: TransactionInstruction[], overrideCustomIxIndex?: number): Promise<TransactionInstruction[]>;
3875
+ /**
3876
+ * Builds the `pauseSpotMarketDepositWithdraw` instruction. See `pauseSpotMarketDepositWithdraw`
3877
+ * for semantics.
3878
+ * @param spotMarketIndex - Spot market index to pause.
3879
+ * @returns The instruction.
3880
+ */
1183
3881
  getPauseSpotMarketDepositWithdrawIx(spotMarketIndex: number): Promise<TransactionInstruction>;
3882
+ /**
3883
+ * Emergency circuit-breaker instruction: pauses deposits and withdrawals for a spot market, but
3884
+ * only when the on-chain handler detects the spot market's vault invariant has already been
3885
+ * violated (actual vault balance diverges from the market's tracked deposit/borrow balances,
3886
+ * e.g. from an exploit) — it reverts with an error if the vault amount is still valid, so this
3887
+ * cannot be used to arbitrarily pause a healthy market. Permissionless — any signer can trigger
3888
+ * it once the invariant is broken.
3889
+ * @param spotMarketIndex - Spot market index to pause.
3890
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3891
+ * @throws (on-chain) if the spot market's vault amount is still valid (invariant not violated).
3892
+ * @returns The transaction signature.
3893
+ */
1184
3894
  pauseSpotMarketDepositWithdraw(spotMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
3895
+ /**
3896
+ * Updates a perp market's market-maker (MM) oracle price using the program's high-frequency
3897
+ * custom native entrypoint (bypasses Anchor's account deserialization overhead — see
3898
+ * `createNativeInstructionDiscriminatorBuffer`). Restricted to the state's configured
3899
+ * `hotMmOracleCrank` signer in production (unchecked under the `anchor-test` feature) and can be
3900
+ * disabled entirely via a state feature-bit-flag kill switch. See `getMMOracleDataForPerpMarket`
3901
+ * for how this price is subsequently gated against the primary oracle before use.
3902
+ * @param marketIndex - Perp market index whose MM oracle to update.
3903
+ * @param oraclePrice - New MM oracle price, PRICE_PRECISION (1e6). A value of `0` is a no-op.
3904
+ * @param oracleSequenceId - Monotonically increasing sequence id for this update, used for
3905
+ * recency comparisons against the primary oracle.
3906
+ * @returns The transaction signature.
3907
+ */
1185
3908
  updateMmOracleNative(marketIndex: number, oraclePrice: BN, oracleSequenceId: BN): Promise<TransactionSignature>;
3909
+ /**
3910
+ * Builds the `updateMmOracleNative` instruction. See `updateMmOracleNative` for semantics. Hand-
3911
+ * assembles the instruction (perp market, signer, clock sysvar, state) rather than going through
3912
+ * `this.program.instruction`, since this targets the native (non-Anchor) entrypoint.
3913
+ * @param marketIndex - Perp market index whose MM oracle to update.
3914
+ * @param oraclePrice - New MM oracle price, PRICE_PRECISION (1e6). A value of `0` is a no-op.
3915
+ * @param oracleSequenceId - Monotonically increasing sequence id for this update.
3916
+ * @returns The instruction.
3917
+ */
1186
3918
  getUpdateMmOracleNativeIx(marketIndex: number, oraclePrice: BN, oracleSequenceId: BN): Promise<TransactionInstruction>;
3919
+ /**
3920
+ * Updates a perp market's AMM spread adjustment using the program's high-frequency custom native
3921
+ * entrypoint. Restricted to the state's configured `hotAmmSpreadAdjust` signer in production
3922
+ * (unchecked under the `anchor-test` feature).
3923
+ * @param marketIndex - Perp market index whose AMM spread adjustment to update.
3924
+ * @param ammSpreadAdjustment - Percentage adjustment to the AMM's base long/short spread, as a
3925
+ * signed byte (-128 to 127): negative narrows the spread by that percent, positive widens it,
3926
+ * `0` is no adjustment.
3927
+ * @returns The transaction signature.
3928
+ */
1187
3929
  updateAmmSpreadAdjustmentNative(marketIndex: number, ammSpreadAdjustment: number): Promise<TransactionSignature>;
3930
+ /**
3931
+ * Builds the `updateAmmSpreadAdjustmentNative` instruction. See `updateAmmSpreadAdjustmentNative`
3932
+ * for semantics. Hand-assembles the instruction (perp market, signer, state) rather than going
3933
+ * through `this.program.instruction`, since this targets the native (non-Anchor) entrypoint.
3934
+ * @param marketIndex - Perp market index whose AMM spread adjustment to update.
3935
+ * @param ammSpreadAdjustment - Percentage adjustment to the AMM's base spread, signed byte (i8).
3936
+ * @returns The instruction.
3937
+ */
1188
3938
  getUpdateAmmSpreadAdjustmentNativeIx(marketIndex: number, ammSpreadAdjustment: number): Promise<TransactionInstruction>;
3939
+ /**
3940
+ * Fetches an LP pool account by ID directly from the RPC (not from this client's subscription
3941
+ * cache). An LP pool ("VLP") is a basket of spot-market "constituent" tokens that mints/redeems a
3942
+ * pool token against deposits/withdrawals and absorbs perp AMM PnL to hedge the protocol's
3943
+ * inventory risk (see `settlePerpToLpPool`).
3944
+ * @param lpPoolId - LP pool ID.
3945
+ * @returns The decoded LP pool account.
3946
+ */
1189
3947
  getLpPoolAccount(lpPoolId: number): Promise<LPPoolAccount>;
3948
+ /**
3949
+ * Fetches the target-base weights for an LP pool's constituents directly from the RPC. Target
3950
+ * base is each constituent's ideal share of the pool, derived from the AMMs it backs
3951
+ * (`updateLpConstituentTargetBase`); swap/add/remove-liquidity fees are priced off deviation from
3952
+ * these targets.
3953
+ * @param lpPoolId - LP pool ID.
3954
+ * @returns The decoded constituent target-base account.
3955
+ */
1190
3956
  getConstituentTargetBaseAccount(lpPoolId: number): Promise<ConstituentTargetBaseAccount>;
3957
+ /**
3958
+ * Fetches the program's single global AMM cache account directly from the RPC — a snapshot of
3959
+ * each hedge-enabled perp market's inventory/price/PnL used by LP pool AUM, target-base, and
3960
+ * settlement instructions without having to reload every perp market individually.
3961
+ * @returns The decoded AMM cache account.
3962
+ */
1191
3963
  getAmmCache(): Promise<AmmCache>;
3964
+ /**
3965
+ * Keeper instruction: recomputes each listed constituent's target-base weight from the current
3966
+ * AMM cache (each hedge-enabled perp market's inventory relative to its constituents), used to
3967
+ * price LP pool swap/add/remove-liquidity fees. Requires `updateAmmCache` to have run recently
3968
+ * for the relevant markets. Permissionless — any signer can act as keeper.
3969
+ * @param lpPoolId - LP pool ID.
3970
+ * @param constituents - Constituent account public keys to recompute target base for.
3971
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3972
+ * @returns The transaction signature.
3973
+ */
1192
3974
  updateLpConstituentTargetBase(lpPoolId: number, constituents: PublicKey[], txParams?: TxParams): Promise<TransactionSignature>;
3975
+ /**
3976
+ * Builds the `updateLpConstituentTargetBase` instruction. See `updateLpConstituentTargetBase` for
3977
+ * semantics.
3978
+ * @param lpPoolId - LP pool ID.
3979
+ * @param constituents - Constituent account public keys to recompute target base for, passed as
3980
+ * read-only remaining accounts.
3981
+ * @returns The instruction.
3982
+ */
1193
3983
  getUpdateLpConstituentTargetBaseIx(lpPoolId: number, constituents: PublicKey[]): Promise<TransactionInstruction>;
3984
+ /**
3985
+ * Keeper instruction: recomputes an LP pool's total AUM and per-constituent value from each
3986
+ * constituent's spot market and vault balance, refreshing `lastAumSlot`. Swaps and add/remove
3987
+ * liquidity revert with `LpPoolAumDelayed` if this has not run within `LP_POOL_SWAP_AUM_UPDATE_DELAY`
3988
+ * slots of the action, so it must typically precede those instructions in the same transaction
3989
+ * (see `getAllUpdateLpPoolAumIxs`). Permissionless — any signer can act as keeper.
3990
+ * @param lpPool - Decoded LP pool account to update.
3991
+ * @param spotMarketIndexOfConstituents - Spot market index of every constituent in the pool, in
3992
+ * the same order the pool's constituents were configured.
3993
+ * @param txParams - Optional compute-unit/priority-fee overrides.
3994
+ * @returns The transaction signature.
3995
+ */
1194
3996
  updateLpPoolAum(lpPool: LPPoolAccount, spotMarketIndexOfConstituents: number[], txParams?: TxParams): Promise<TransactionSignature>;
3997
+ /**
3998
+ * Builds the `updateLpPoolAum` instruction. See `updateLpPoolAum` for semantics.
3999
+ * @param lpPool - Decoded LP pool account to update.
4000
+ * @param spotMarketIndexOfConstituents - Spot market index of every constituent in the pool.
4001
+ * @returns The instruction.
4002
+ */
1195
4003
  getUpdateLpPoolAumIxs(lpPool: LPPoolAccount, spotMarketIndexOfConstituents: number[]): Promise<TransactionInstruction>;
4004
+ /**
4005
+ * Keeper instruction: refreshes the global AMM cache's per-market inventory/price/PnL snapshot
4006
+ * for the given hedge-enabled perp markets, feeding LP pool AUM, target-base, and settlement
4007
+ * math. Permissionless — any signer can act as keeper.
4008
+ * @param perpMarketIndexes - Perp market indexes to refresh; at most 50 per call.
4009
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4010
+ * @throws If more than 50 market indexes are supplied.
4011
+ * @returns The transaction signature.
4012
+ */
1196
4013
  updateAmmCache(perpMarketIndexes: number[], txParams?: TxParams): Promise<TransactionSignature>;
4014
+ /**
4015
+ * Builds the `updateAmmCache` instruction. See `updateAmmCache` for semantics.
4016
+ * @param perpMarketIndexes - Perp market indexes to refresh; at most 50.
4017
+ * @throws If more than 50 market indexes are supplied.
4018
+ * @returns The instruction.
4019
+ */
1197
4020
  getUpdateAmmCacheIx(perpMarketIndexes: number[]): Promise<TransactionInstruction>;
4021
+ /**
4022
+ * Keeper instruction: refreshes a single LP pool constituent's cached oracle price/slot from its
4023
+ * spot market's oracle. Called ahead of AUM/target-base updates that need a fresh price for that
4024
+ * constituent. Permissionless — any signer can act as keeper.
4025
+ * @param constituent - Decoded constituent account to refresh.
4026
+ * @returns The transaction signature.
4027
+ */
1198
4028
  updateConstituentOracleInfo(constituent: ConstituentAccount): Promise<TransactionSignature>;
4029
+ /**
4030
+ * Builds the `updateConstituentOracleInfo` instruction. See `updateConstituentOracleInfo` for
4031
+ * semantics.
4032
+ * @param constituent - Decoded constituent account to refresh.
4033
+ * @returns The instruction.
4034
+ */
1199
4035
  getUpdateConstituentOracleInfoIx(constituent: ConstituentAccount): Promise<TransactionInstruction>;
4036
+ /**
4037
+ * Swaps `inMarketIndex` tokens for `outMarketIndex` tokens directly against an LP pool's
4038
+ * constituent vaults (not the DLOB/AMM), paying a fee priced off each constituent's deviation
4039
+ * from its target-base weight. Reverts if pool swaps are disabled, `inMarketIndex` equals
4040
+ * `outMarketIndex`, or `updateLpPoolAum` has not run within `LP_POOL_SWAP_AUM_UPDATE_DELAY` slots
4041
+ * (see `getAllLpPoolSwapIxs` for a wrapper that prepends the required AUM refresh).
4042
+ * @param inMarketIndex - Spot market index of the token being sold.
4043
+ * @param outMarketIndex - Spot market index of the token being bought.
4044
+ * @param inAmount - Amount of `inMarketIndex` token to sell, in that market's mint precision.
4045
+ * @param minOutAmount - Minimum acceptable amount of `outMarketIndex` token to receive, in that
4046
+ * market's mint precision.
4047
+ * @param lpPool - LP pool public key.
4048
+ * @param userAuthority - Authority whose associated token accounts fund/receive the swap.
4049
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4050
+ * @returns The transaction signature.
4051
+ */
1200
4052
  lpPoolSwap(inMarketIndex: number, outMarketIndex: number, inAmount: BN, minOutAmount: BN, lpPool: PublicKey, userAuthority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
4053
+ /**
4054
+ * Builds the `lpPoolSwap` instruction. See `lpPoolSwap` for semantics.
4055
+ * @param inMarketIndex - Spot market index of the token being sold.
4056
+ * @param outMarketIndex - Spot market index of the token being bought.
4057
+ * @param inAmount - Amount of `inMarketIndex` token to sell, in that market's mint precision.
4058
+ * @param minOutAmount - Minimum acceptable amount of `outMarketIndex` token to receive, in that
4059
+ * market's mint precision.
4060
+ * @param lpPool - LP pool public key.
4061
+ * @param userAuthority - Authority whose associated token accounts fund/receive the swap.
4062
+ * @returns The instruction.
4063
+ */
1201
4064
  getLpPoolSwapIx(inMarketIndex: number, outMarketIndex: number, inAmount: BN, minOutAmount: BN, lpPool: PublicKey, userAuthority: PublicKey): Promise<TransactionInstruction>;
4065
+ /**
4066
+ * Simulation-only instruction: computes what `lpPoolSwap` would charge for the given swap without
4067
+ * moving any funds (intended to be run via `simulateTransaction`/a view call, not actually
4068
+ * confirmed on-chain). Useful for quoting a swap's fee before submitting it.
4069
+ * @param inMarketIndex - Spot market index of the token being sold.
4070
+ * @param outMarketIndex - Spot market index of the token being bought.
4071
+ * @param inAmount - Amount of `inMarketIndex` token to sell, in that market's mint precision.
4072
+ * @param inTargetWeight - Assumed target-base weight for the in-constituent (PERCENTAGE_PRECISION, 1e6).
4073
+ * @param outTargetWeight - Assumed target-base weight for the out-constituent (PERCENTAGE_PRECISION, 1e6).
4074
+ * @param lpPool - LP pool public key.
4075
+ * @param constituentTargetBase - The pool's constituent target-base account.
4076
+ * @param constituentInTokenAccount - In-constituent's vault token account.
4077
+ * @param constituentOutTokenAccount - Out-constituent's vault token account.
4078
+ * @param inConstituent - In-constituent account.
4079
+ * @param outConstituent - Out-constituent account.
4080
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4081
+ * @returns The transaction signature (intended for simulation, not confirmation).
4082
+ */
1202
4083
  viewLpPoolSwapFees(inMarketIndex: number, outMarketIndex: number, inAmount: BN, inTargetWeight: BN, outTargetWeight: BN, lpPool: PublicKey, constituentTargetBase: PublicKey, constituentInTokenAccount: PublicKey, constituentOutTokenAccount: PublicKey, inConstituent: PublicKey, outConstituent: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
4084
+ /**
4085
+ * Builds the `viewLpPoolSwapFees` instruction. See `viewLpPoolSwapFees` for semantics.
4086
+ * @param inMarketIndex - Spot market index of the token being sold.
4087
+ * @param outMarketIndex - Spot market index of the token being bought.
4088
+ * @param inAmount - Amount of `inMarketIndex` token to sell, in that market's mint precision.
4089
+ * @param inTargetWeight - Assumed target-base weight for the in-constituent (PERCENTAGE_PRECISION, 1e6).
4090
+ * @param outTargetWeight - Assumed target-base weight for the out-constituent (PERCENTAGE_PRECISION, 1e6).
4091
+ * @param lpPool - LP pool public key.
4092
+ * @param constituentTargetBase - The pool's constituent target-base account.
4093
+ * @param constituentInTokenAccount - In-constituent's vault token account.
4094
+ * @param constituentOutTokenAccount - Out-constituent's vault token account.
4095
+ * @param inConstituent - In-constituent account.
4096
+ * @param outConstituent - Out-constituent account.
4097
+ * @returns The instruction.
4098
+ */
1203
4099
  getViewLpPoolSwapFeesIx(inMarketIndex: number, outMarketIndex: number, inAmount: BN, inTargetWeight: BN, outTargetWeight: BN, lpPool: PublicKey, constituentTargetBase: PublicKey, constituentInTokenAccount: PublicKey, constituentOutTokenAccount: PublicKey, inConstituent: PublicKey, outConstituent: PublicKey): Promise<TransactionInstruction>;
4100
+ /**
4101
+ * Builds an idempotent instruction creating this wallet's associated token account for an LP
4102
+ * pool's mint, needed before receiving pool tokens from `lpPoolAddLiquidity`.
4103
+ * @param lpPool - Decoded LP pool account whose mint to create an account for.
4104
+ * @returns The instruction.
4105
+ */
1204
4106
  getCreateLpPoolTokenAccountIx(lpPool: LPPoolAccount): Promise<TransactionInstruction>;
4107
+ /**
4108
+ * Creates this wallet's associated token account for an LP pool's mint. See
4109
+ * `getCreateLpPoolTokenAccountIx`.
4110
+ * @param lpPool - Decoded LP pool account whose mint to create an account for.
4111
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4112
+ * @returns The transaction signature.
4113
+ */
1205
4114
  createLpPoolTokenAccount(lpPool: LPPoolAccount, txParams?: TxParams): Promise<TransactionSignature>;
4115
+ /**
4116
+ * Deposits `inMarketIndex` tokens into an LP pool's matching constituent and mints LP pool tokens
4117
+ * in return, priced at the pool's current AUM-derived share price. Reverts if mint/redeem is
4118
+ * disabled, the constituent doesn't allow deposits (or is reduce-only and this isn't a
4119
+ * reducing deposit), the pool is gated by a whitelist mint this wallet doesn't hold, or
4120
+ * `updateLpPoolAum` has not run within `LP_POOL_SWAP_AUM_UPDATE_DELAY` slots (see
4121
+ * `getAllLpPoolAddLiquidityIxs` for a wrapper that prepends the required AUM refresh).
4122
+ * @param inMarketIndex - Spot market index of the token being deposited.
4123
+ * @param inAmount - Amount to deposit, in `inMarketIndex`'s mint precision.
4124
+ * @param minMintAmount - Minimum acceptable LP pool tokens to receive, in the pool mint's precision.
4125
+ * @param lpPool - Decoded LP pool account to deposit into.
4126
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4127
+ * @returns The transaction signature.
4128
+ */
1206
4129
  lpPoolAddLiquidity({ inMarketIndex, inAmount, minMintAmount, lpPool, txParams, }: {
1207
4130
  inMarketIndex: number;
1208
4131
  inAmount: BN;
@@ -1210,23 +4133,62 @@ export declare class VelocityClient {
1210
4133
  lpPool: LPPoolAccount;
1211
4134
  txParams?: TxParams;
1212
4135
  }): Promise<TransactionSignature>;
4136
+ /**
4137
+ * Builds the `lpPoolAddLiquidity` instruction (plus any needed wrapped-SOL / associated-token-
4138
+ * account setup and teardown instructions). See `lpPoolAddLiquidity` for semantics.
4139
+ * @param inMarketIndex - Spot market index of the token being deposited.
4140
+ * @param inAmount - Amount to deposit, in `inMarketIndex`'s mint precision.
4141
+ * @param minMintAmount - Minimum acceptable LP pool tokens to receive, in the pool mint's precision.
4142
+ * @param lpPool - Decoded LP pool account to deposit into.
4143
+ * @returns The ordered instructions to include in the transaction.
4144
+ */
1213
4145
  getLpPoolAddLiquidityIx({ inMarketIndex, inAmount, minMintAmount, lpPool, }: {
1214
4146
  inMarketIndex: number;
1215
4147
  inAmount: BN;
1216
4148
  minMintAmount: BN;
1217
4149
  lpPool: LPPoolAccount;
1218
4150
  }): Promise<TransactionInstruction[]>;
4151
+ /**
4152
+ * Simulation-only instruction: computes what `lpPoolAddLiquidity` would mint/charge for the given
4153
+ * deposit without moving any funds (intended for `simulateTransaction`, not confirmation).
4154
+ * @param inMarketIndex - Spot market index of the token being deposited.
4155
+ * @param inAmount - Amount to deposit, in `inMarketIndex`'s mint precision.
4156
+ * @param lpPool - Decoded LP pool account to deposit into.
4157
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4158
+ * @returns The transaction signature (intended for simulation, not confirmation).
4159
+ */
1219
4160
  viewLpPoolAddLiquidityFees({ inMarketIndex, inAmount, lpPool, txParams, }: {
1220
4161
  inMarketIndex: number;
1221
4162
  inAmount: BN;
1222
4163
  lpPool: LPPoolAccount;
1223
4164
  txParams?: TxParams;
1224
4165
  }): Promise<TransactionSignature>;
4166
+ /**
4167
+ * Builds the `viewLpPoolAddLiquidityFees` instruction. See `viewLpPoolAddLiquidityFees` for semantics.
4168
+ * @param inMarketIndex - Spot market index of the token being deposited.
4169
+ * @param inAmount - Amount to deposit, in `inMarketIndex`'s mint precision.
4170
+ * @param lpPool - Decoded LP pool account to deposit into.
4171
+ * @returns The instruction.
4172
+ */
1225
4173
  getViewLpPoolAddLiquidityFeesIx({ inMarketIndex, inAmount, lpPool, }: {
1226
4174
  inMarketIndex: number;
1227
4175
  inAmount: BN;
1228
4176
  lpPool: LPPoolAccount;
1229
4177
  }): Promise<TransactionInstruction>;
4178
+ /**
4179
+ * Burns LP pool tokens and withdraws `outMarketIndex` tokens from the pool's matching constituent
4180
+ * in return, priced at the pool's current AUM-derived share price. Reverts if mint/redeem is
4181
+ * disabled, the constituent doesn't allow withdrawals, or `updateLpPoolAum` has not run within
4182
+ * `LP_POOL_SWAP_AUM_UPDATE_DELAY` slots (see `getAllLpPoolRemoveLiquidityIxs` for a wrapper that
4183
+ * prepends the required perp settlement and AUM refresh).
4184
+ * @param outMarketIndex - Spot market index of the token being withdrawn.
4185
+ * @param lpToBurn - Amount of LP pool tokens to burn, in the pool mint's precision.
4186
+ * @param minAmountOut - Minimum acceptable `outMarketIndex` tokens to receive, in that market's
4187
+ * mint precision.
4188
+ * @param lpPool - Decoded LP pool account to withdraw from.
4189
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4190
+ * @returns The transaction signature.
4191
+ */
1230
4192
  lpPoolRemoveLiquidity({ outMarketIndex, lpToBurn, minAmountOut, lpPool, txParams, }: {
1231
4193
  outMarketIndex: number;
1232
4194
  lpToBurn: BN;
@@ -1234,40 +4196,158 @@ export declare class VelocityClient {
1234
4196
  lpPool: LPPoolAccount;
1235
4197
  txParams?: TxParams;
1236
4198
  }): Promise<TransactionSignature>;
4199
+ /**
4200
+ * Builds the `lpPoolRemoveLiquidity` instruction (plus an idempotent associated-token-account
4201
+ * creation instruction for a wrapped-SOL output, if needed). See `lpPoolRemoveLiquidity` for
4202
+ * semantics.
4203
+ * @param outMarketIndex - Spot market index of the token being withdrawn.
4204
+ * @param lpToBurn - Amount of LP pool tokens to burn, in the pool mint's precision.
4205
+ * @param minAmountOut - Minimum acceptable `outMarketIndex` tokens to receive, in that market's
4206
+ * mint precision.
4207
+ * @param lpPool - Decoded LP pool account to withdraw from.
4208
+ * @returns The ordered instructions to include in the transaction.
4209
+ */
1237
4210
  getLpPoolRemoveLiquidityIx({ outMarketIndex, lpToBurn, minAmountOut, lpPool, }: {
1238
4211
  outMarketIndex: number;
1239
4212
  lpToBurn: BN;
1240
4213
  minAmountOut: BN;
1241
4214
  lpPool: LPPoolAccount;
1242
4215
  }): Promise<TransactionInstruction[]>;
4216
+ /**
4217
+ * Simulation-only instruction: computes what `lpPoolRemoveLiquidity` would return for the given
4218
+ * burn without moving any funds (intended for `simulateTransaction`, not confirmation).
4219
+ * @param outMarketIndex - Spot market index of the token being withdrawn.
4220
+ * @param lpToBurn - Amount of LP pool tokens to burn, in the pool mint's precision.
4221
+ * @param lpPool - Decoded LP pool account to withdraw from.
4222
+ * @param txParams - Optional compute-unit/priority-fee overrides.
4223
+ * @returns The transaction signature (intended for simulation, not confirmation).
4224
+ */
1243
4225
  viewLpPoolRemoveLiquidityFees({ outMarketIndex, lpToBurn, lpPool, txParams, }: {
1244
4226
  outMarketIndex: number;
1245
4227
  lpToBurn: BN;
1246
4228
  lpPool: LPPoolAccount;
1247
4229
  txParams?: TxParams;
1248
4230
  }): Promise<TransactionSignature>;
4231
+ /**
4232
+ * Builds the `viewLpPoolRemoveLiquidityFees` instruction. See `viewLpPoolRemoveLiquidityFees` for
4233
+ * semantics.
4234
+ * @param outMarketIndex - Spot market index of the token being withdrawn.
4235
+ * @param lpToBurn - Amount of LP pool tokens to burn, in the pool mint's precision.
4236
+ * @param lpPool - Decoded LP pool account to withdraw from.
4237
+ * @returns The instruction.
4238
+ */
1249
4239
  getViewLpPoolRemoveLiquidityFeesIx({ outMarketIndex, lpToBurn, lpPool, }: {
1250
4240
  outMarketIndex: number;
1251
4241
  lpToBurn: BN;
1252
4242
  lpPool: LPPoolAccount;
1253
4243
  }): Promise<TransactionInstruction>;
4244
+ /**
4245
+ * Convenience wrapper that prepends the AUM refresh `lpPoolAddLiquidity` requires (an
4246
+ * `updateConstituentOracleInfo` per constituent, then `updateLpPoolAum`) ahead of either the real
4247
+ * add-liquidity instruction or, when `view` is set, its fee-simulation counterpart.
4248
+ * @param inMarketIndex - Spot market index of the token being deposited.
4249
+ * @param inAmount - Amount to deposit, in `inMarketIndex`'s mint precision.
4250
+ * @param minMintAmount - Minimum acceptable LP pool tokens to receive, in the pool mint's precision.
4251
+ * @param lpPool - Decoded LP pool account to deposit into.
4252
+ * @param constituentMap - All of the pool's constituents, used to refresh oracle info and AUM.
4253
+ * @param includeUpdateConstituentOracleInfo - Whether to prepend an oracle-info refresh per
4254
+ * constituent; defaults to `true`.
4255
+ * @param view - When `true`, appends `getViewLpPoolAddLiquidityFeesIx` instead of the real deposit;
4256
+ * defaults to `false`.
4257
+ * @returns The ordered instructions to include in the transaction.
4258
+ */
1254
4259
  getAllLpPoolAddLiquidityIxs({ inMarketIndex, inAmount, minMintAmount, lpPool, }: {
1255
4260
  inMarketIndex: number;
1256
4261
  inAmount: BN;
1257
4262
  minMintAmount: BN;
1258
4263
  lpPool: LPPoolAccount;
1259
4264
  }, constituentMap: ConstituentMap, includeUpdateConstituentOracleInfo?: boolean, view?: boolean): Promise<TransactionInstruction[]>;
4265
+ /**
4266
+ * Convenience wrapper that prepends what `lpPoolRemoveLiquidity` requires: settling every hedge-
4267
+ * enabled perp market's PnL into the pool (`getAllSettlePerpToLpPoolIxs`) and refreshing AUM
4268
+ * (`getAllUpdateLpPoolAumIxs`), ahead of either the real remove-liquidity instruction or, when
4269
+ * `view` is set, its fee-simulation counterpart.
4270
+ * @param outMarketIndex - Spot market index of the token being withdrawn.
4271
+ * @param lpToBurn - Amount of LP pool tokens to burn, in the pool mint's precision.
4272
+ * @param minAmountOut - Minimum acceptable `outMarketIndex` tokens to receive, in that market's
4273
+ * mint precision.
4274
+ * @param lpPool - Decoded LP pool account to withdraw from.
4275
+ * @param constituentMap - All of the pool's constituents, used to refresh oracle info and AUM.
4276
+ * @param includeUpdateConstituentOracleInfo - Whether to prepend an oracle-info refresh per
4277
+ * constituent; defaults to `true`.
4278
+ * @param view - When `true`, appends `getViewLpPoolRemoveLiquidityFeesIx` instead of the real
4279
+ * withdrawal; defaults to `false`.
4280
+ * @returns The ordered instructions to include in the transaction.
4281
+ */
1260
4282
  getAllLpPoolRemoveLiquidityIxs({ outMarketIndex, lpToBurn, minAmountOut, lpPool, }: {
1261
4283
  outMarketIndex: number;
1262
4284
  lpToBurn: BN;
1263
4285
  minAmountOut: BN;
1264
4286
  lpPool: LPPoolAccount;
1265
4287
  }, constituentMap: ConstituentMap, includeUpdateConstituentOracleInfo?: boolean, view?: boolean): Promise<TransactionInstruction[]>;
4288
+ /**
4289
+ * Builds the full instruction set to refresh an LP pool's AUM: one `updateConstituentOracleInfo`
4290
+ * per constituent (optional) followed by `updateLpPoolAum` across all of them.
4291
+ * @param lpPool - Decoded LP pool account to update.
4292
+ * @param constituentMap - All of the pool's constituents.
4293
+ * @param includeUpdateConstituentOracleInfo - Whether to prepend an oracle-info refresh per
4294
+ * constituent; defaults to `true`. Pass `false` when a caller has already refreshed oracle info
4295
+ * earlier in the same transaction.
4296
+ * @returns The ordered instructions to include in the transaction.
4297
+ */
1266
4298
  getAllUpdateLpPoolAumIxs(lpPool: LPPoolAccount, constituentMap: ConstituentMap, includeUpdateConstituentOracleInfo?: boolean): Promise<TransactionInstruction[]>;
4299
+ /**
4300
+ * Builds the full instruction set to refresh an LP pool's constituent target-base weights:
4301
+ * `updateAmmCache` for the given markets, an optional `updateConstituentOracleInfo` per
4302
+ * constituent, `updateLpConstituentTargetBase`, then a full AUM refresh
4303
+ * (`getAllUpdateLpPoolAumIxs`, oracle info not repeated).
4304
+ * @param perpMarketIndexes - Hedge-enabled perp market indexes to refresh in the AMM cache.
4305
+ * @param lpPool - Decoded LP pool account to update.
4306
+ * @param constituentMap - All of the pool's constituents.
4307
+ * @param includeUpdateConstituentOracleInfo - Whether to include an oracle-info refresh per
4308
+ * constituent; defaults to `true`.
4309
+ * @returns The ordered instructions to include in the transaction.
4310
+ */
1267
4311
  getAllUpdateConstituentTargetBaseIxs(perpMarketIndexes: number[], lpPool: LPPoolAccount, constituentMap: ConstituentMap, includeUpdateConstituentOracleInfo?: boolean): Promise<TransactionInstruction[]>;
4312
+ /**
4313
+ * Convenience wrapper that prepends the AUM refresh `lpPoolSwap` requires ahead of the swap
4314
+ * instruction itself.
4315
+ * @param lpPool - Decoded LP pool account to swap against.
4316
+ * @param constituentMap - All of the pool's constituents, used to refresh AUM.
4317
+ * @param inMarketIndex - Spot market index of the token being sold.
4318
+ * @param outMarketIndex - Spot market index of the token being bought.
4319
+ * @param inAmount - Amount of `inMarketIndex` token to sell, in that market's mint precision.
4320
+ * @param minOutAmount - Minimum acceptable amount of `outMarketIndex` token to receive, in that
4321
+ * market's mint precision.
4322
+ * @param userAuthority - Authority whose associated token accounts fund/receive the swap.
4323
+ * @returns The ordered instructions to include in the transaction.
4324
+ */
1268
4325
  getAllLpPoolSwapIxs(lpPool: LPPoolAccount, constituentMap: ConstituentMap, inMarketIndex: number, outMarketIndex: number, inAmount: BN, minOutAmount: BN, userAuthority: PublicKey): Promise<TransactionInstruction[]>;
4326
+ /**
4327
+ * Keeper instruction: settles quote PnL owed between one or more hedge-enabled perp markets' fee
4328
+ * and PnL pools and the LP pool's quote constituent, bounded by the pool's settle cap. Requires
4329
+ * `updateAmmCache` to have run recently for the given markets. Permissionless — any signer can
4330
+ * act as keeper.
4331
+ * @param lpPoolId - LP pool ID.
4332
+ * @param perpMarketIndexes - Hedge-enabled perp market indexes to settle.
4333
+ * @returns The transaction signature.
4334
+ */
1269
4335
  settlePerpToLpPool(lpPoolId: number, perpMarketIndexes: number[]): Promise<TransactionSignature>;
4336
+ /**
4337
+ * Builds the `settlePerpToLpPool` instruction. See `settlePerpToLpPool` for semantics.
4338
+ * @param lpPoolId - LP pool ID.
4339
+ * @param perpMarketIndexes - Hedge-enabled perp market indexes to settle, passed as writable
4340
+ * remaining accounts.
4341
+ * @returns The instruction.
4342
+ */
1270
4343
  getSettlePerpToLpPoolIx(lpPoolId: number, perpMarketIndexes: number[]): Promise<TransactionInstruction>;
4344
+ /**
4345
+ * Builds the full instruction set to settle perp PnL into an LP pool: `updateAmmCache` for the
4346
+ * given markets followed by `settlePerpToLpPool`.
4347
+ * @param lpPoolId - LP pool ID.
4348
+ * @param marketIndexes - Hedge-enabled perp market indexes to settle.
4349
+ * @returns The ordered instructions to include in the transaction.
4350
+ */
1271
4351
  getAllSettlePerpToLpPoolIxs(lpPoolId: number, marketIndexes: number[]): Promise<TransactionInstruction[]>;
1272
4352
  /**
1273
4353
  * Below here are the transaction sending functions
@@ -1276,18 +4356,68 @@ export declare class VelocityClient {
1276
4356
  private handlePreSignedTransaction;
1277
4357
  private isVersionedTransaction;
1278
4358
  /**
1279
- * Send a transaction.
1280
- *
1281
- * @param tx
1282
- * @param additionalSigners
1283
- * @param opts :: Will fallback to VelocityClient's opts if not provided
1284
- * @param preSigned
1285
- * @returns
4359
+ * Signs (unless `preSigned`) and sends a transaction via this client's `txSender`, dispatching to
4360
+ * `sendVersionedTransaction` or `send` based on whether `tx` is a `VersionedTransaction`. The
4361
+ * shared low-level send path underlying nearly every instruction-building method on this class.
4362
+ * @param tx - Transaction to send; legacy `Transaction` or `VersionedTransaction`.
4363
+ * @param additionalSigners - Extra signers beyond this client's wallet (e.g. newly-created accounts).
4364
+ * @param opts - Confirmation options; falls back to `this.opts` if not provided.
4365
+ * @param preSigned - If `true`, `tx` is assumed already fully signed and is submitted as-is.
4366
+ * @returns The transaction signature and the slot it was confirmed at.
1286
4367
  */
1287
4368
  sendTransaction(tx: Transaction | VersionedTransaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
4369
+ /**
4370
+ * Assembles one or more instructions into a single unsigned transaction via `this.txHandler`,
4371
+ * applying compute-unit/priority-fee instructions from `txParams`, resolving address lookup
4372
+ * tables for versioned transactions, and fetching a recent blockhash if not supplied. Used by
4373
+ * nearly every instruction-building method on this class before sending.
4374
+ * @param instructions - Instruction(s) to include.
4375
+ * @param txParams - Optional compute-unit/priority-fee overrides; defaults to `this.txParams`.
4376
+ * @param txVersion - Legacy (`0`) vs versioned transaction; defaults to `this.txVersion`.
4377
+ * @param lookupTables - Additional address lookup tables to use, beyond the client's configured
4378
+ * market lookup tables.
4379
+ * @param forceVersionedTransaction - Force a `VersionedTransaction` even if `txVersion` implies legacy.
4380
+ * @param recentBlockhash - Pre-fetched blockhash to reuse instead of requesting a new one.
4381
+ * @param optionalIxs - Instructions to append opportunistically if space/compute budget allows
4382
+ * (dropped rather than causing failure if they don't fit).
4383
+ * @returns The assembled (unsigned) transaction.
4384
+ */
1288
4385
  buildTransaction(instructions: TransactionInstruction | TransactionInstruction[], txParams?: TxParams, txVersion?: TransactionVersion, lookupTables?: AddressLookupTableAccount[], forceVersionedTransaction?: boolean, recentBlockhash?: BlockhashWithExpiryBlockHeight, optionalIxs?: TransactionInstruction[]): Promise<Transaction | VersionedTransaction>;
4386
+ /**
4387
+ * Builds many independent transactions in one call — each entry in `instructions` becomes its own
4388
+ * transaction via the same path as `buildTransaction`. An entry may build to `undefined` if the
4389
+ * underlying `txHandler` implementation skips it (e.g. empty instruction list).
4390
+ * @param instructions - One instruction-list per transaction to build.
4391
+ * @param txParams - Optional compute-unit/priority-fee overrides applied to every transaction.
4392
+ * @param txVersion - Legacy (`0`) vs versioned transaction; defaults to `this.txVersion`.
4393
+ * @param lookupTables - Additional address lookup tables to use for every transaction.
4394
+ * @param forceVersionedTransaction - Force `VersionedTransaction`s even if `txVersion` implies legacy.
4395
+ * @returns The assembled (unsigned) transactions, in the same order as `instructions`.
4396
+ */
1289
4397
  buildBulkTransactions(instructions: (TransactionInstruction | TransactionInstruction[])[], txParams?: TxParams, txVersion?: TransactionVersion, lookupTables?: AddressLookupTableAccount[], forceVersionedTransaction?: boolean): Promise<(Transaction | VersionedTransaction | undefined)[]>;
4398
+ /**
4399
+ * Like `buildBulkTransactions`, but keyed by caller-chosen labels instead of array position — each
4400
+ * value in `instructionsMap` becomes its own transaction, returned under the same key.
4401
+ * @param instructionsMap - Instruction-list(s) to build, keyed by an arbitrary caller-defined label.
4402
+ * @param txParams - Optional compute-unit/priority-fee overrides applied to every transaction.
4403
+ * @param txVersion - Legacy (`0`) vs versioned transaction; defaults to `this.txVersion`.
4404
+ * @param lookupTables - Additional address lookup tables to use for every transaction.
4405
+ * @param forceVersionedTransaction - Force `VersionedTransaction`s even if `txVersion` implies legacy.
4406
+ * @returns A map from each input key to its assembled (unsigned) transaction.
4407
+ */
1290
4408
  buildTransactionsMap(instructionsMap: Record<string, TransactionInstruction | TransactionInstruction[]>, txParams?: TxParams, txVersion?: TransactionVersion, lookupTables?: AddressLookupTableAccount[], forceVersionedTransaction?: boolean): Promise<MappedRecord<Record<string, TransactionInstruction | TransactionInstruction[]>, Transaction | VersionedTransaction>>;
4409
+ /**
4410
+ * Like `buildTransactionsMap`, but additionally signs every built transaction with this client's
4411
+ * wallet before returning — useful for batching several independent, pre-signed transactions
4412
+ * (e.g. to submit separately or hand off to `sendSignedTx`).
4413
+ * @param instructionsMap - Instruction-list(s) to build and sign, keyed by an arbitrary
4414
+ * caller-defined label.
4415
+ * @param txParams - Optional compute-unit/priority-fee overrides applied to every transaction.
4416
+ * @param txVersion - Legacy (`0`) vs versioned transaction; defaults to `this.txVersion`.
4417
+ * @param lookupTables - Additional address lookup tables to use for every transaction.
4418
+ * @param forceVersionedTransaction - Force `VersionedTransaction`s even if `txVersion` implies legacy.
4419
+ * @returns A map from each input key to its signed transaction.
4420
+ */
1291
4421
  buildAndSignTransactionsMap(instructionsMap: Record<string, TransactionInstruction | TransactionInstruction[]>, txParams?: TxParams, txVersion?: TransactionVersion, lookupTables?: AddressLookupTableAccount[], forceVersionedTransaction?: boolean): Promise<{
1292
4422
  signedTxMap: Record<string, Transaction>;
1293
4423
  signedTxData: SignedTxData[];
@@ -1295,6 +4425,19 @@ export declare class VelocityClient {
1295
4425
  signedTxMap: MappedRecord<Record<string, TransactionInstruction | TransactionInstruction[]>, Transaction | VersionedTransaction>;
1296
4426
  signedTxData: SignedTxData[];
1297
4427
  }>;
4428
+ /**
4429
+ * Determines whether placing `orderParams` would increase the magnitude of the sub-account's
4430
+ * existing perp position in that market (same-direction add, or opening a new position) as
4431
+ * opposed to reducing/flattening/flipping it. Used by `placePerpOrder`/`placeOrders`/
4432
+ * `preparePlaceOrdersTx` to decide whether an `isolatedPositionDepositAmount` transfer should be
4433
+ * prepended — that transfer only makes sense when the order grows the position.
4434
+ * @param orderParams - Order to evaluate; `baseAssetAmount` is BASE_PRECISION (1e9).
4435
+ * @param subAccountId - Sub-account whose existing position to compare against; defaults to the
4436
+ * active sub-account.
4437
+ * @returns `true` if there is no existing position in the market, the existing position is flat
4438
+ * (zero), or the order's signed base amount increases the position's absolute size; `false` if it
4439
+ * reduces, flattens, or flips it.
4440
+ */
1298
4441
  isOrderIncreasingPosition(orderParams: OptionalOrderParams, subAccountId?: number): boolean;
1299
4442
  }
1300
4443
  export {};