@velocity-exchange/sdk 0.0.5 → 0.2.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 (815) hide show
  1. package/.prettierignore +1 -1
  2. package/CHANGELOG.md +35 -0
  3. package/README.md +30 -30
  4. package/bun.lock +24 -2
  5. package/lib/browser/accounts/basicUserAccountSubscriber.d.ts +5 -3
  6. package/lib/browser/accounts/basicUserAccountSubscriber.js +4 -3
  7. package/lib/browser/accounts/basicUserStatsAccountSubscriber.d.ts +5 -3
  8. package/lib/browser/accounts/basicUserStatsAccountSubscriber.js +4 -3
  9. package/lib/browser/accounts/bulkAccountLoader.d.ts +5 -5
  10. package/lib/browser/accounts/bulkAccountLoader.js +12 -1
  11. package/lib/browser/accounts/grpcAccountSubscriber.d.ts +2 -1
  12. package/lib/browser/accounts/grpcAccountSubscriber.js +8 -2
  13. package/lib/browser/accounts/grpcMultiAccountSubscriber.d.ts +3 -2
  14. package/lib/browser/accounts/grpcMultiAccountSubscriber.js +13 -5
  15. package/lib/browser/accounts/grpcMultiUserAccountSubscriber.d.ts +2 -1
  16. package/lib/browser/accounts/grpcMultiUserAccountSubscriber.js +12 -8
  17. package/lib/browser/accounts/grpcProgramAccountSubscriber.d.ts +2 -1
  18. package/lib/browser/accounts/grpcProgramAccountSubscriber.js +9 -3
  19. package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.d.ts +0 -4
  20. package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.js +19 -6
  21. package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +1 -5
  22. package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.js +44 -23
  23. package/lib/browser/accounts/laserProgramAccountSubscriber.js +4 -1
  24. package/lib/browser/accounts/oneShotUserAccountSubscriber.js +4 -3
  25. package/lib/browser/accounts/oneShotUserStatsAccountSubscriber.js +7 -3
  26. package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +4 -2
  27. package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.js +3 -3
  28. package/lib/browser/accounts/pollingOracleAccountSubscriber.d.ts +0 -2
  29. package/lib/browser/accounts/pollingOracleAccountSubscriber.js +16 -5
  30. package/lib/browser/accounts/pollingTokenAccountSubscriber.d.ts +0 -2
  31. package/lib/browser/accounts/pollingTokenAccountSubscriber.js +16 -5
  32. package/lib/browser/accounts/pollingUserAccountSubscriber.d.ts +8 -4
  33. package/lib/browser/accounts/pollingUserAccountSubscriber.js +17 -11
  34. package/lib/browser/accounts/pollingUserStatsAccountSubscriber.d.ts +4 -2
  35. package/lib/browser/accounts/pollingUserStatsAccountSubscriber.js +6 -6
  36. package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.d.ts +7 -5
  37. package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.js +69 -35
  38. package/lib/browser/accounts/types.d.ts +6 -12
  39. package/lib/browser/accounts/utils.d.ts +1 -0
  40. package/lib/browser/accounts/utils.js +10 -3
  41. package/lib/browser/accounts/webSocketAccountSubscriber.d.ts +4 -2
  42. package/lib/browser/accounts/webSocketAccountSubscriber.js +17 -5
  43. package/lib/browser/accounts/webSocketAccountSubscriberV2.d.ts +4 -2
  44. package/lib/browser/accounts/webSocketAccountSubscriberV2.js +17 -6
  45. package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +4 -2
  46. package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +9 -0
  47. package/lib/browser/accounts/webSocketProgramAccountSubscriber.d.ts +3 -1
  48. package/lib/browser/accounts/webSocketProgramAccountSubscriber.js +14 -3
  49. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.d.ts +3 -1
  50. package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.js +15 -3
  51. package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.d.ts +3 -1
  52. package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.js +14 -4
  53. package/lib/browser/accounts/webSocketUserAccountSubscriber.d.ts +4 -2
  54. package/lib/browser/accounts/webSocketUserAccountSubscriber.js +9 -0
  55. package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.d.ts +4 -2
  56. package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.js +9 -0
  57. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.d.ts +4 -8
  58. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.js +52 -26
  59. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +7 -7
  60. package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.js +49 -20
  61. package/lib/browser/accounts/websocketProgramUserAccountSubscriber.d.ts +1 -1
  62. package/lib/browser/accounts/websocketProgramUserAccountSubscriber.js +0 -3
  63. package/lib/browser/addresses/marketAddresses.js +3 -2
  64. package/lib/browser/addresses/pda.d.ts +1 -9
  65. package/lib/browser/addresses/pda.js +4 -23
  66. package/lib/browser/adminClient.d.ts +25 -29
  67. package/lib/browser/adminClient.js +168 -169
  68. package/lib/browser/auctionSubscriber/auctionSubscriber.d.ts +2 -4
  69. package/lib/browser/auctionSubscriber/auctionSubscriber.js +8 -10
  70. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.d.ts +2 -4
  71. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.js +11 -10
  72. package/lib/browser/auctionSubscriber/types.d.ts +3 -2
  73. package/lib/browser/bankrun/bankrunConnection.d.ts +6 -4
  74. package/lib/browser/bankrun/bankrunConnection.js +69 -31
  75. package/lib/browser/blockhashSubscriber/BlockhashSubscriber.d.ts +1 -1
  76. package/lib/browser/blockhashSubscriber/BlockhashSubscriber.js +3 -2
  77. package/lib/browser/clock/clockSubscriber.d.ts +6 -6
  78. package/lib/browser/clock/clockSubscriber.js +4 -3
  79. package/lib/browser/config.d.ts +11 -20
  80. package/lib/browser/config.js +13 -36
  81. package/lib/browser/constants/index.d.ts +1 -2
  82. package/lib/browser/constants/index.js +1 -2
  83. package/lib/browser/constants/numericConstants.d.ts +1 -3
  84. package/lib/browser/constants/numericConstants.js +3 -5
  85. package/lib/browser/constituentMap/constituentMap.d.ts +0 -2
  86. package/lib/browser/constituentMap/constituentMap.js +10 -6
  87. package/lib/browser/constituentMap/pollingConstituentAccountSubscriber.js +3 -2
  88. package/lib/browser/constituentMap/webSocketConstituentAccountSubscriber.d.ts +2 -3
  89. package/lib/browser/constituentMap/webSocketConstituentAccountSubscriber.js +10 -3
  90. package/lib/browser/core/VelocityCore.d.ts +9 -15
  91. package/lib/browser/core/VelocityCore.js +5 -7
  92. package/lib/browser/core/instructions/perpOrders.d.ts +14 -0
  93. package/lib/browser/core/instructions/perpOrders.js +14 -0
  94. package/lib/browser/core/instructions/withdraw.d.ts +1 -1
  95. package/lib/browser/core/instructions/withdraw.js +1 -1
  96. package/lib/browser/core/remainingAccounts.d.ts +2 -2
  97. package/lib/browser/core/remainingAccounts.js +5 -5
  98. package/lib/browser/decode/user.js +9 -1
  99. package/lib/browser/dlob/DLOB.d.ts +7 -2
  100. package/lib/browser/dlob/DLOB.js +205 -142
  101. package/lib/browser/dlob/DLOBNode.d.ts +5 -2
  102. package/lib/browser/dlob/DLOBNode.js +7 -0
  103. package/lib/browser/dlob/DLOBSubscriber.d.ts +0 -2
  104. package/lib/browser/dlob/DLOBSubscriber.js +39 -39
  105. package/lib/browser/dlob/NodeList.js +8 -7
  106. package/lib/browser/dlob/orderBookLevels.js +24 -17
  107. package/lib/browser/dlob/types.d.ts +0 -2
  108. package/lib/browser/events/eventList.js +4 -1
  109. package/lib/browser/events/eventSubscriber.d.ts +6 -3
  110. package/lib/browser/events/eventSubscriber.js +75 -26
  111. package/lib/browser/events/eventsServerLogProvider.d.ts +1 -1
  112. package/lib/browser/events/eventsServerLogProvider.js +17 -10
  113. package/lib/browser/events/fetchLogs.d.ts +1 -1
  114. package/lib/browser/events/fetchLogs.js +4 -2
  115. package/lib/browser/events/parse.js +14 -14
  116. package/lib/browser/events/pollingLogProvider.d.ts +1 -1
  117. package/lib/browser/events/pollingLogProvider.js +1 -0
  118. package/lib/browser/events/txEventCache.js +6 -2
  119. package/lib/browser/events/types.d.ts +3 -7
  120. package/lib/browser/events/types.js +1 -3
  121. package/lib/browser/events/webSocketLogProvider.d.ts +1 -1
  122. package/lib/browser/events/webSocketLogProvider.js +5 -2
  123. package/lib/browser/factory/bigNum.js +1 -1
  124. package/lib/{node/idl/drift.d.ts → browser/idl/velocity.d.ts} +2412 -2481
  125. package/lib/browser/idl/{drift.json → velocity.json} +2265 -2333
  126. package/lib/browser/index.d.ts +1 -3
  127. package/lib/browser/index.js +1 -4
  128. package/lib/browser/jupiter/jupiterClient.d.ts +1 -1
  129. package/lib/browser/jupiter/jupiterClient.js +18 -8
  130. package/lib/browser/marginCalculation.js +1 -0
  131. package/lib/browser/math/amm.d.ts +31 -13
  132. package/lib/browser/math/amm.js +87 -31
  133. package/lib/browser/math/auction.js +16 -12
  134. package/lib/browser/math/bankruptcy.js +1 -1
  135. package/lib/browser/math/builder.d.ts +18 -1
  136. package/lib/browser/math/builder.js +32 -1
  137. package/lib/browser/math/funding.js +30 -30
  138. package/lib/browser/math/insurance.d.ts +1 -1
  139. package/lib/browser/math/insurance.js +4 -5
  140. package/lib/browser/math/margin.d.ts +3 -11
  141. package/lib/browser/math/margin.js +10 -69
  142. package/lib/browser/math/market.d.ts +4 -12
  143. package/lib/browser/math/market.js +12 -46
  144. package/lib/browser/math/oracles.d.ts +4 -7
  145. package/lib/browser/math/oracles.js +24 -37
  146. package/lib/browser/math/orders.d.ts +2 -7
  147. package/lib/browser/math/orders.js +9 -81
  148. package/lib/browser/math/position.d.ts +0 -4
  149. package/lib/browser/math/position.js +6 -11
  150. package/lib/browser/math/repeg.d.ts +0 -1
  151. package/lib/browser/math/repeg.js +1 -23
  152. package/lib/browser/math/spotBalance.d.ts +4 -4
  153. package/lib/browser/math/spotBalance.js +6 -6
  154. package/lib/browser/math/spotMarket.d.ts +0 -6
  155. package/lib/browser/math/spotMarket.js +1 -16
  156. package/lib/browser/math/spotPosition.d.ts +4 -4
  157. package/lib/browser/math/state.d.ts +0 -2
  158. package/lib/browser/math/state.js +1 -9
  159. package/lib/browser/math/superStake.d.ts +11 -63
  160. package/lib/browser/math/superStake.js +29 -28
  161. package/lib/browser/math/trade.js +7 -7
  162. package/lib/browser/math/utils.d.ts +1 -1
  163. package/lib/browser/math/utils.js +1 -1
  164. package/lib/browser/memcmp.d.ts +0 -1
  165. package/lib/browser/memcmp.js +1 -10
  166. package/lib/browser/oracles/prelaunchOracleClient.js +3 -2
  167. package/lib/browser/oracles/pythClient.js +9 -3
  168. package/lib/browser/oracles/pythLazerClient.js +5 -4
  169. package/lib/browser/oracles/utils.d.ts +4 -0
  170. package/lib/browser/oracles/utils.js +9 -1
  171. package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +1 -3
  172. package/lib/browser/orderSubscriber/OrderSubscriber.js +16 -14
  173. package/lib/browser/orderSubscriber/WebsocketSubscription.js +1 -1
  174. package/lib/browser/orderSubscriber/grpcSubscription.js +2 -2
  175. package/lib/browser/orderSubscriber/types.d.ts +0 -2
  176. package/lib/browser/priorityFee/heliusPriorityFeeMethod.d.ts +1 -1
  177. package/lib/browser/priorityFee/priorityFeeSubscriber.d.ts +2 -6
  178. package/lib/browser/priorityFee/priorityFeeSubscriber.js +34 -18
  179. package/lib/browser/priorityFee/priorityFeeSubscriberMap.d.ts +0 -4
  180. package/lib/browser/priorityFee/priorityFeeSubscriberMap.js +3 -11
  181. package/lib/browser/priorityFee/solanaPriorityFeeMethod.d.ts +1 -1
  182. package/lib/browser/priorityFee/types.d.ts +3 -8
  183. package/lib/browser/priorityFee/velocityPriorityFeeMethod.d.ts +0 -8
  184. package/lib/browser/priorityFee/velocityPriorityFeeMethod.js +1 -3
  185. package/lib/browser/pyth/pythLazerSubscriber.d.ts +1 -1
  186. package/lib/browser/pyth/pythLazerSubscriber.js +1 -1
  187. package/lib/browser/pyth/types.d.ts +0 -1
  188. package/lib/browser/slot/SlotSubscriber.d.ts +1 -1
  189. package/lib/browser/slot/SlotSubscriber.js +2 -1
  190. package/lib/browser/slot/SlothashSubscriber.d.ts +3 -2
  191. package/lib/browser/slot/SlothashSubscriber.js +11 -4
  192. package/lib/browser/swap/UnifiedSwapClient.js +1 -1
  193. package/lib/browser/swift/grpcSignedMsgUserAccountSubscriber.d.ts +0 -3
  194. package/lib/browser/swift/grpcSignedMsgUserAccountSubscriber.js +5 -5
  195. package/lib/browser/swift/signedMsgUserAccountSubscriber.d.ts +7 -7
  196. package/lib/browser/swift/signedMsgUserAccountSubscriber.js +14 -10
  197. package/lib/browser/swift/swiftOrderSubscriber.d.ts +7 -6
  198. package/lib/browser/swift/swiftOrderSubscriber.js +15 -16
  199. package/lib/browser/testClient.js +3 -2
  200. package/lib/browser/tokenFaucet.js +16 -2
  201. package/lib/browser/tx/baseTxSender.d.ts +4 -4
  202. package/lib/browser/tx/baseTxSender.js +5 -4
  203. package/lib/browser/tx/fastSingleTxSender.d.ts +3 -3
  204. package/lib/browser/tx/fastSingleTxSender.js +9 -5
  205. package/lib/browser/tx/reportTransactionError.d.ts +2 -2
  206. package/lib/browser/tx/reportTransactionError.js +5 -1
  207. package/lib/browser/tx/retryTxSender.d.ts +1 -1
  208. package/lib/browser/tx/retryTxSender.js +4 -2
  209. package/lib/browser/tx/txHandler.d.ts +7 -1
  210. package/lib/browser/tx/txHandler.js +54 -40
  211. package/lib/browser/tx/txParamProcessor.d.ts +4 -1
  212. package/lib/browser/tx/txParamProcessor.js +6 -0
  213. package/lib/browser/tx/types.d.ts +1 -1
  214. package/lib/browser/tx/whileValidTxSender.d.ts +1 -6
  215. package/lib/browser/tx/whileValidTxSender.js +35 -13
  216. package/lib/browser/types.d.ts +102 -157
  217. package/lib/browser/types.js +6 -2
  218. package/lib/browser/user.d.ts +22 -10
  219. package/lib/browser/user.js +174 -154
  220. package/lib/browser/userConfig.d.ts +3 -2
  221. package/lib/browser/userMap/WebsocketSubscription.d.ts +1 -1
  222. package/lib/browser/userMap/WebsocketSubscription.js +1 -1
  223. package/lib/browser/userMap/grpcSubscription.d.ts +1 -1
  224. package/lib/browser/userMap/grpcSubscription.js +1 -1
  225. package/lib/browser/userMap/referrerMap.d.ts +0 -2
  226. package/lib/browser/userMap/referrerMap.js +10 -7
  227. package/lib/browser/userMap/revenueShareEscrowMap.d.ts +0 -2
  228. package/lib/browser/userMap/revenueShareEscrowMap.js +4 -4
  229. package/lib/browser/userMap/userMap.d.ts +3 -5
  230. package/lib/browser/userMap/userMap.js +39 -30
  231. package/lib/browser/userMap/userMapConfig.d.ts +3 -2
  232. package/lib/browser/userMap/userStatsMap.d.ts +1 -3
  233. package/lib/browser/userMap/userStatsMap.js +18 -17
  234. package/lib/browser/userStats.d.ts +7 -4
  235. package/lib/browser/userStats.js +28 -18
  236. package/lib/browser/userStatsConfig.d.ts +3 -2
  237. package/lib/browser/util/TransactionConfirmationManager.js +4 -2
  238. package/lib/browser/util/chainClock.d.ts +1 -1
  239. package/lib/browser/util/computeUnits.d.ts +1 -1
  240. package/lib/browser/util/computeUnits.js +6 -1
  241. package/lib/browser/util/ed25519Utils.d.ts +1 -1
  242. package/lib/browser/util/ed25519Utils.js +1 -1
  243. package/lib/browser/velocityClient.d.ts +144 -71
  244. package/lib/browser/velocityClient.js +653 -457
  245. package/lib/browser/velocityClientConfig.d.ts +0 -8
  246. package/lib/node/accounts/basicUserAccountSubscriber.d.ts +5 -3
  247. package/lib/node/accounts/basicUserAccountSubscriber.d.ts.map +1 -1
  248. package/lib/node/accounts/basicUserAccountSubscriber.js +4 -3
  249. package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts +5 -3
  250. package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts.map +1 -1
  251. package/lib/node/accounts/basicUserStatsAccountSubscriber.js +4 -3
  252. package/lib/node/accounts/bulkAccountLoader.d.ts +5 -5
  253. package/lib/node/accounts/bulkAccountLoader.d.ts.map +1 -1
  254. package/lib/node/accounts/bulkAccountLoader.js +12 -1
  255. package/lib/node/accounts/grpcAccountSubscriber.d.ts +2 -1
  256. package/lib/node/accounts/grpcAccountSubscriber.d.ts.map +1 -1
  257. package/lib/node/accounts/grpcAccountSubscriber.js +8 -2
  258. package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts +3 -2
  259. package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts.map +1 -1
  260. package/lib/node/accounts/grpcMultiAccountSubscriber.js +13 -5
  261. package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts +2 -1
  262. package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts.map +1 -1
  263. package/lib/node/accounts/grpcMultiUserAccountSubscriber.js +12 -8
  264. package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts +2 -1
  265. package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts.map +1 -1
  266. package/lib/node/accounts/grpcProgramAccountSubscriber.js +9 -3
  267. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts +0 -4
  268. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts.map +1 -1
  269. package/lib/node/accounts/grpcVelocityClientAccountSubscriber.js +19 -6
  270. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +1 -5
  271. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts.map +1 -1
  272. package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.js +44 -23
  273. package/lib/node/accounts/laserProgramAccountSubscriber.d.ts.map +1 -1
  274. package/lib/node/accounts/laserProgramAccountSubscriber.js +4 -1
  275. package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts.map +1 -1
  276. package/lib/node/accounts/oneShotUserAccountSubscriber.js +4 -3
  277. package/lib/node/accounts/oneShotUserStatsAccountSubscriber.d.ts.map +1 -1
  278. package/lib/node/accounts/oneShotUserStatsAccountSubscriber.js +7 -3
  279. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +4 -2
  280. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts.map +1 -1
  281. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.js +3 -3
  282. package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts +0 -2
  283. package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts.map +1 -1
  284. package/lib/node/accounts/pollingOracleAccountSubscriber.js +16 -5
  285. package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts +0 -2
  286. package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts.map +1 -1
  287. package/lib/node/accounts/pollingTokenAccountSubscriber.js +16 -5
  288. package/lib/node/accounts/pollingUserAccountSubscriber.d.ts +8 -4
  289. package/lib/node/accounts/pollingUserAccountSubscriber.d.ts.map +1 -1
  290. package/lib/node/accounts/pollingUserAccountSubscriber.js +17 -11
  291. package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts +4 -2
  292. package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts.map +1 -1
  293. package/lib/node/accounts/pollingUserStatsAccountSubscriber.js +6 -6
  294. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts +7 -5
  295. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts.map +1 -1
  296. package/lib/node/accounts/pollingVelocityClientAccountSubscriber.js +69 -35
  297. package/lib/node/accounts/types.d.ts +6 -12
  298. package/lib/node/accounts/types.d.ts.map +1 -1
  299. package/lib/node/accounts/utils.d.ts +1 -0
  300. package/lib/node/accounts/utils.d.ts.map +1 -1
  301. package/lib/node/accounts/utils.js +10 -3
  302. package/lib/node/accounts/webSocketAccountSubscriber.d.ts +4 -2
  303. package/lib/node/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  304. package/lib/node/accounts/webSocketAccountSubscriber.js +17 -5
  305. package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts +4 -2
  306. package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts.map +1 -1
  307. package/lib/node/accounts/webSocketAccountSubscriberV2.js +17 -6
  308. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +4 -2
  309. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts.map +1 -1
  310. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +9 -0
  311. package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts +3 -1
  312. package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts.map +1 -1
  313. package/lib/node/accounts/webSocketProgramAccountSubscriber.js +14 -3
  314. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts +3 -1
  315. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts.map +1 -1
  316. package/lib/node/accounts/webSocketProgramAccountSubscriberV2.js +15 -3
  317. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts +3 -1
  318. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts.map +1 -1
  319. package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.js +14 -4
  320. package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts +4 -2
  321. package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts.map +1 -1
  322. package/lib/node/accounts/webSocketUserAccountSubscriber.js +9 -0
  323. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts +4 -2
  324. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts.map +1 -1
  325. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.js +9 -0
  326. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts +4 -8
  327. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts.map +1 -1
  328. package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.js +52 -26
  329. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +7 -7
  330. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts.map +1 -1
  331. package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.js +49 -20
  332. package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts +1 -1
  333. package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts.map +1 -1
  334. package/lib/node/accounts/websocketProgramUserAccountSubscriber.js +0 -3
  335. package/lib/node/addresses/marketAddresses.d.ts.map +1 -1
  336. package/lib/node/addresses/marketAddresses.js +3 -2
  337. package/lib/node/addresses/pda.d.ts +1 -9
  338. package/lib/node/addresses/pda.d.ts.map +1 -1
  339. package/lib/node/addresses/pda.js +4 -23
  340. package/lib/node/adminClient.d.ts +25 -29
  341. package/lib/node/adminClient.d.ts.map +1 -1
  342. package/lib/node/adminClient.js +168 -169
  343. package/lib/node/auctionSubscriber/auctionSubscriber.d.ts +2 -4
  344. package/lib/node/auctionSubscriber/auctionSubscriber.d.ts.map +1 -1
  345. package/lib/node/auctionSubscriber/auctionSubscriber.js +8 -10
  346. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts +2 -4
  347. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts.map +1 -1
  348. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.js +11 -10
  349. package/lib/node/auctionSubscriber/types.d.ts +3 -2
  350. package/lib/node/auctionSubscriber/types.d.ts.map +1 -1
  351. package/lib/node/bankrun/bankrunConnection.d.ts +6 -4
  352. package/lib/node/bankrun/bankrunConnection.d.ts.map +1 -1
  353. package/lib/node/bankrun/bankrunConnection.js +69 -31
  354. package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts +1 -1
  355. package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts.map +1 -1
  356. package/lib/node/blockhashSubscriber/BlockhashSubscriber.js +3 -2
  357. package/lib/node/clock/clockSubscriber.d.ts +6 -6
  358. package/lib/node/clock/clockSubscriber.d.ts.map +1 -1
  359. package/lib/node/clock/clockSubscriber.js +4 -3
  360. package/lib/node/config.d.ts +11 -20
  361. package/lib/node/config.d.ts.map +1 -1
  362. package/lib/node/config.js +13 -36
  363. package/lib/node/constants/index.d.ts +1 -2
  364. package/lib/node/constants/index.d.ts.map +1 -1
  365. package/lib/node/constants/index.js +1 -2
  366. package/lib/node/constants/numericConstants.d.ts +1 -3
  367. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  368. package/lib/node/constants/numericConstants.js +3 -5
  369. package/lib/node/constituentMap/constituentMap.d.ts +0 -2
  370. package/lib/node/constituentMap/constituentMap.d.ts.map +1 -1
  371. package/lib/node/constituentMap/constituentMap.js +10 -6
  372. package/lib/node/constituentMap/pollingConstituentAccountSubscriber.d.ts.map +1 -1
  373. package/lib/node/constituentMap/pollingConstituentAccountSubscriber.js +3 -2
  374. package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.d.ts +2 -3
  375. package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.d.ts.map +1 -1
  376. package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.js +10 -3
  377. package/lib/node/core/VelocityCore.d.ts +9 -15
  378. package/lib/node/core/VelocityCore.d.ts.map +1 -1
  379. package/lib/node/core/VelocityCore.js +5 -7
  380. package/lib/node/core/instructions/perpOrders.d.ts +14 -0
  381. package/lib/node/core/instructions/perpOrders.d.ts.map +1 -1
  382. package/lib/node/core/instructions/perpOrders.js +14 -0
  383. package/lib/node/core/instructions/withdraw.d.ts +1 -1
  384. package/lib/node/core/instructions/withdraw.d.ts.map +1 -1
  385. package/lib/node/core/instructions/withdraw.js +1 -1
  386. package/lib/node/core/remainingAccounts.d.ts +2 -2
  387. package/lib/node/core/remainingAccounts.d.ts.map +1 -1
  388. package/lib/node/core/remainingAccounts.js +5 -5
  389. package/lib/node/decode/user.d.ts.map +1 -1
  390. package/lib/node/decode/user.js +9 -1
  391. package/lib/node/dlob/DLOB.d.ts +7 -2
  392. package/lib/node/dlob/DLOB.d.ts.map +1 -1
  393. package/lib/node/dlob/DLOB.js +205 -142
  394. package/lib/node/dlob/DLOBNode.d.ts +5 -2
  395. package/lib/node/dlob/DLOBNode.d.ts.map +1 -1
  396. package/lib/node/dlob/DLOBNode.js +7 -0
  397. package/lib/node/dlob/DLOBSubscriber.d.ts +0 -2
  398. package/lib/node/dlob/DLOBSubscriber.d.ts.map +1 -1
  399. package/lib/node/dlob/DLOBSubscriber.js +39 -39
  400. package/lib/node/dlob/NodeList.d.ts.map +1 -1
  401. package/lib/node/dlob/NodeList.js +8 -7
  402. package/lib/node/dlob/orderBookLevels.d.ts.map +1 -1
  403. package/lib/node/dlob/orderBookLevels.js +24 -17
  404. package/lib/node/dlob/types.d.ts +0 -2
  405. package/lib/node/dlob/types.d.ts.map +1 -1
  406. package/lib/node/events/eventList.d.ts +3 -3
  407. package/lib/node/events/eventList.d.ts.map +1 -1
  408. package/lib/node/events/eventList.js +4 -1
  409. package/lib/node/events/eventSubscriber.d.ts +6 -3
  410. package/lib/node/events/eventSubscriber.d.ts.map +1 -1
  411. package/lib/node/events/eventSubscriber.js +75 -26
  412. package/lib/node/events/eventsServerLogProvider.d.ts +2 -2
  413. package/lib/node/events/eventsServerLogProvider.d.ts.map +1 -1
  414. package/lib/node/events/eventsServerLogProvider.js +17 -10
  415. package/lib/node/events/fetchLogs.d.ts +1 -1
  416. package/lib/node/events/fetchLogs.d.ts.map +1 -1
  417. package/lib/node/events/fetchLogs.js +4 -2
  418. package/lib/node/events/parse.d.ts.map +1 -1
  419. package/lib/node/events/parse.js +14 -14
  420. package/lib/node/events/pollingLogProvider.d.ts +2 -2
  421. package/lib/node/events/pollingLogProvider.d.ts.map +1 -1
  422. package/lib/node/events/pollingLogProvider.js +1 -0
  423. package/lib/node/events/txEventCache.d.ts +3 -3
  424. package/lib/node/events/txEventCache.d.ts.map +1 -1
  425. package/lib/node/events/txEventCache.js +6 -2
  426. package/lib/node/events/types.d.ts +3 -7
  427. package/lib/node/events/types.d.ts.map +1 -1
  428. package/lib/node/events/types.js +1 -3
  429. package/lib/node/events/webSocketLogProvider.d.ts +2 -2
  430. package/lib/node/events/webSocketLogProvider.d.ts.map +1 -1
  431. package/lib/node/events/webSocketLogProvider.js +5 -2
  432. package/lib/node/factory/bigNum.js +1 -1
  433. package/lib/{browser/idl/drift.d.ts → node/idl/velocity.d.ts} +2413 -2480
  434. package/lib/node/idl/velocity.d.ts.map +1 -0
  435. package/lib/node/idl/{drift.json → velocity.json} +2265 -2333
  436. package/lib/node/index.d.ts +1 -3
  437. package/lib/node/index.d.ts.map +1 -1
  438. package/lib/node/index.js +1 -4
  439. package/lib/node/jupiter/jupiterClient.d.ts +1 -1
  440. package/lib/node/jupiter/jupiterClient.d.ts.map +1 -1
  441. package/lib/node/jupiter/jupiterClient.js +18 -8
  442. package/lib/node/marginCalculation.d.ts.map +1 -1
  443. package/lib/node/marginCalculation.js +1 -0
  444. package/lib/node/math/amm.d.ts +31 -13
  445. package/lib/node/math/amm.d.ts.map +1 -1
  446. package/lib/node/math/amm.js +87 -31
  447. package/lib/node/math/auction.d.ts.map +1 -1
  448. package/lib/node/math/auction.js +16 -12
  449. package/lib/node/math/bankruptcy.js +1 -1
  450. package/lib/node/math/builder.d.ts +18 -1
  451. package/lib/node/math/builder.d.ts.map +1 -1
  452. package/lib/node/math/builder.js +32 -1
  453. package/lib/node/math/funding.d.ts.map +1 -1
  454. package/lib/node/math/funding.js +30 -30
  455. package/lib/node/math/insurance.d.ts +1 -1
  456. package/lib/node/math/insurance.d.ts.map +1 -1
  457. package/lib/node/math/insurance.js +4 -5
  458. package/lib/node/math/margin.d.ts +3 -11
  459. package/lib/node/math/margin.d.ts.map +1 -1
  460. package/lib/node/math/margin.js +10 -69
  461. package/lib/node/math/market.d.ts +4 -12
  462. package/lib/node/math/market.d.ts.map +1 -1
  463. package/lib/node/math/market.js +12 -46
  464. package/lib/node/math/oracles.d.ts +4 -7
  465. package/lib/node/math/oracles.d.ts.map +1 -1
  466. package/lib/node/math/oracles.js +24 -37
  467. package/lib/node/math/orders.d.ts +2 -7
  468. package/lib/node/math/orders.d.ts.map +1 -1
  469. package/lib/node/math/orders.js +9 -81
  470. package/lib/node/math/position.d.ts +1 -5
  471. package/lib/node/math/position.d.ts.map +1 -1
  472. package/lib/node/math/position.js +6 -11
  473. package/lib/node/math/repeg.d.ts +0 -1
  474. package/lib/node/math/repeg.d.ts.map +1 -1
  475. package/lib/node/math/repeg.js +1 -23
  476. package/lib/node/math/spotBalance.d.ts +4 -4
  477. package/lib/node/math/spotBalance.d.ts.map +1 -1
  478. package/lib/node/math/spotBalance.js +6 -6
  479. package/lib/node/math/spotMarket.d.ts +0 -6
  480. package/lib/node/math/spotMarket.d.ts.map +1 -1
  481. package/lib/node/math/spotMarket.js +1 -16
  482. package/lib/node/math/spotPosition.d.ts +4 -4
  483. package/lib/node/math/spotPosition.d.ts.map +1 -1
  484. package/lib/node/math/state.d.ts +0 -2
  485. package/lib/node/math/state.d.ts.map +1 -1
  486. package/lib/node/math/state.js +1 -9
  487. package/lib/node/math/superStake.d.ts +11 -63
  488. package/lib/node/math/superStake.d.ts.map +1 -1
  489. package/lib/node/math/superStake.js +29 -28
  490. package/lib/node/math/trade.d.ts +2 -2
  491. package/lib/node/math/trade.d.ts.map +1 -1
  492. package/lib/node/math/trade.js +7 -7
  493. package/lib/node/math/utils.d.ts +1 -1
  494. package/lib/node/math/utils.js +1 -1
  495. package/lib/node/memcmp.d.ts +0 -1
  496. package/lib/node/memcmp.d.ts.map +1 -1
  497. package/lib/node/memcmp.js +1 -10
  498. package/lib/node/oracles/oracleClientCache.d.ts +1 -1
  499. package/lib/node/oracles/prelaunchOracleClient.d.ts.map +1 -1
  500. package/lib/node/oracles/prelaunchOracleClient.js +3 -2
  501. package/lib/node/oracles/pythClient.d.ts.map +1 -1
  502. package/lib/node/oracles/pythClient.js +9 -3
  503. package/lib/node/oracles/pythLazerClient.d.ts.map +1 -1
  504. package/lib/node/oracles/pythLazerClient.js +5 -4
  505. package/lib/node/oracles/utils.d.ts +4 -0
  506. package/lib/node/oracles/utils.d.ts.map +1 -1
  507. package/lib/node/oracles/utils.js +9 -1
  508. package/lib/node/orderSubscriber/OrderSubscriber.d.ts +1 -3
  509. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  510. package/lib/node/orderSubscriber/OrderSubscriber.js +16 -14
  511. package/lib/node/orderSubscriber/WebsocketSubscription.js +1 -1
  512. package/lib/node/orderSubscriber/grpcSubscription.js +2 -2
  513. package/lib/node/orderSubscriber/types.d.ts +0 -2
  514. package/lib/node/orderSubscriber/types.d.ts.map +1 -1
  515. package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts +1 -1
  516. package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts.map +1 -1
  517. package/lib/node/priorityFee/priorityFeeSubscriber.d.ts +2 -6
  518. package/lib/node/priorityFee/priorityFeeSubscriber.d.ts.map +1 -1
  519. package/lib/node/priorityFee/priorityFeeSubscriber.js +34 -18
  520. package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts +0 -4
  521. package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts.map +1 -1
  522. package/lib/node/priorityFee/priorityFeeSubscriberMap.js +3 -11
  523. package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts +1 -1
  524. package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts.map +1 -1
  525. package/lib/node/priorityFee/types.d.ts +3 -8
  526. package/lib/node/priorityFee/types.d.ts.map +1 -1
  527. package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts +0 -8
  528. package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts.map +1 -1
  529. package/lib/node/priorityFee/velocityPriorityFeeMethod.js +1 -3
  530. package/lib/node/pyth/pythLazerSubscriber.d.ts +1 -1
  531. package/lib/node/pyth/pythLazerSubscriber.js +1 -1
  532. package/lib/node/pyth/types.d.ts +0 -1
  533. package/lib/node/pyth/types.d.ts.map +1 -1
  534. package/lib/node/slot/SlotSubscriber.d.ts +1 -1
  535. package/lib/node/slot/SlotSubscriber.d.ts.map +1 -1
  536. package/lib/node/slot/SlotSubscriber.js +2 -1
  537. package/lib/node/slot/SlothashSubscriber.d.ts +3 -2
  538. package/lib/node/slot/SlothashSubscriber.d.ts.map +1 -1
  539. package/lib/node/slot/SlothashSubscriber.js +11 -4
  540. package/lib/node/swap/UnifiedSwapClient.js +1 -1
  541. package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.d.ts +0 -3
  542. package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.d.ts.map +1 -1
  543. package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.js +5 -5
  544. package/lib/node/swift/signedMsgUserAccountSubscriber.d.ts +7 -7
  545. package/lib/node/swift/signedMsgUserAccountSubscriber.d.ts.map +1 -1
  546. package/lib/node/swift/signedMsgUserAccountSubscriber.js +14 -10
  547. package/lib/node/swift/swiftOrderSubscriber.d.ts +7 -6
  548. package/lib/node/swift/swiftOrderSubscriber.d.ts.map +1 -1
  549. package/lib/node/swift/swiftOrderSubscriber.js +15 -16
  550. package/lib/node/testClient.js +3 -2
  551. package/lib/node/tokenFaucet.d.ts.map +1 -1
  552. package/lib/node/tokenFaucet.js +16 -2
  553. package/lib/node/tx/baseTxSender.d.ts +4 -4
  554. package/lib/node/tx/baseTxSender.d.ts.map +1 -1
  555. package/lib/node/tx/baseTxSender.js +5 -4
  556. package/lib/node/tx/fastSingleTxSender.d.ts +3 -3
  557. package/lib/node/tx/fastSingleTxSender.d.ts.map +1 -1
  558. package/lib/node/tx/fastSingleTxSender.js +9 -5
  559. package/lib/node/tx/reportTransactionError.d.ts +2 -2
  560. package/lib/node/tx/reportTransactionError.d.ts.map +1 -1
  561. package/lib/node/tx/reportTransactionError.js +5 -1
  562. package/lib/node/tx/retryTxSender.d.ts +1 -1
  563. package/lib/node/tx/retryTxSender.d.ts.map +1 -1
  564. package/lib/node/tx/retryTxSender.js +4 -2
  565. package/lib/node/tx/txHandler.d.ts +9 -3
  566. package/lib/node/tx/txHandler.d.ts.map +1 -1
  567. package/lib/node/tx/txHandler.js +54 -40
  568. package/lib/node/tx/txParamProcessor.d.ts +4 -1
  569. package/lib/node/tx/txParamProcessor.d.ts.map +1 -1
  570. package/lib/node/tx/txParamProcessor.js +6 -0
  571. package/lib/node/tx/types.d.ts +1 -1
  572. package/lib/node/tx/types.d.ts.map +1 -1
  573. package/lib/node/tx/whileValidTxSender.d.ts +1 -6
  574. package/lib/node/tx/whileValidTxSender.d.ts.map +1 -1
  575. package/lib/node/tx/whileValidTxSender.js +35 -13
  576. package/lib/node/types.d.ts +100 -155
  577. package/lib/node/types.d.ts.map +1 -1
  578. package/lib/node/types.js +6 -2
  579. package/lib/node/user.d.ts +22 -10
  580. package/lib/node/user.d.ts.map +1 -1
  581. package/lib/node/user.js +174 -154
  582. package/lib/node/userConfig.d.ts +3 -2
  583. package/lib/node/userConfig.d.ts.map +1 -1
  584. package/lib/node/userMap/WebsocketSubscription.d.ts +1 -1
  585. package/lib/node/userMap/WebsocketSubscription.d.ts.map +1 -1
  586. package/lib/node/userMap/WebsocketSubscription.js +1 -1
  587. package/lib/node/userMap/grpcSubscription.d.ts +1 -1
  588. package/lib/node/userMap/grpcSubscription.d.ts.map +1 -1
  589. package/lib/node/userMap/grpcSubscription.js +1 -1
  590. package/lib/node/userMap/referrerMap.d.ts +0 -2
  591. package/lib/node/userMap/referrerMap.d.ts.map +1 -1
  592. package/lib/node/userMap/referrerMap.js +10 -7
  593. package/lib/node/userMap/revenueShareEscrowMap.d.ts +0 -2
  594. package/lib/node/userMap/revenueShareEscrowMap.d.ts.map +1 -1
  595. package/lib/node/userMap/revenueShareEscrowMap.js +4 -4
  596. package/lib/node/userMap/userMap.d.ts +3 -5
  597. package/lib/node/userMap/userMap.d.ts.map +1 -1
  598. package/lib/node/userMap/userMap.js +39 -30
  599. package/lib/node/userMap/userMapConfig.d.ts +3 -2
  600. package/lib/node/userMap/userMapConfig.d.ts.map +1 -1
  601. package/lib/node/userMap/userStatsMap.d.ts +1 -3
  602. package/lib/node/userMap/userStatsMap.d.ts.map +1 -1
  603. package/lib/node/userMap/userStatsMap.js +18 -17
  604. package/lib/node/userStats.d.ts +7 -4
  605. package/lib/node/userStats.d.ts.map +1 -1
  606. package/lib/node/userStats.js +28 -18
  607. package/lib/node/userStatsConfig.d.ts +3 -2
  608. package/lib/node/userStatsConfig.d.ts.map +1 -1
  609. package/lib/node/util/TransactionConfirmationManager.d.ts.map +1 -1
  610. package/lib/node/util/TransactionConfirmationManager.js +4 -2
  611. package/lib/node/util/chainClock.d.ts +1 -1
  612. package/lib/node/util/chainClock.d.ts.map +1 -1
  613. package/lib/node/util/computeUnits.d.ts +1 -1
  614. package/lib/node/util/computeUnits.d.ts.map +1 -1
  615. package/lib/node/util/computeUnits.js +6 -1
  616. package/lib/node/util/ed25519Utils.d.ts +1 -1
  617. package/lib/node/util/ed25519Utils.js +1 -1
  618. package/lib/node/velocityClient.d.ts +145 -72
  619. package/lib/node/velocityClient.d.ts.map +1 -1
  620. package/lib/node/velocityClient.js +653 -457
  621. package/lib/node/velocityClientConfig.d.ts +0 -8
  622. package/lib/node/velocityClientConfig.d.ts.map +1 -1
  623. package/package.json +10 -9
  624. package/scripts/deposit-isolated-positions.ts +2 -2
  625. package/scripts/find-flagged-users.ts +1 -1
  626. package/scripts/grpc-client-test-comparison.ts +4 -4
  627. package/scripts/grpc-multiuser-client-test-comparison.ts +2 -2
  628. package/scripts/single-grpc-client-test.ts +3 -3
  629. package/scripts/updateVersion.js +4 -4
  630. package/scripts/withdraw-isolated-positions.ts +2 -2
  631. package/src/accounts/basicUserAccountSubscriber.ts +7 -5
  632. package/src/accounts/basicUserStatsAccountSubscriber.ts +9 -5
  633. package/src/accounts/bulkAccountLoader.ts +20 -7
  634. package/src/accounts/grpcAccountSubscriber.ts +11 -3
  635. package/src/accounts/grpcMultiAccountSubscriber.ts +24 -9
  636. package/src/accounts/grpcMultiUserAccountSubscriber.ts +16 -12
  637. package/src/accounts/grpcProgramAccountSubscriber.ts +12 -4
  638. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +17 -14
  639. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +69 -49
  640. package/src/accounts/laserProgramAccountSubscriber.ts +4 -1
  641. package/src/accounts/oneShotUserAccountSubscriber.ts +5 -3
  642. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +8 -3
  643. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +11 -5
  644. package/src/accounts/pollingOracleAccountSubscriber.ts +17 -10
  645. package/src/accounts/pollingTokenAccountSubscriber.ts +17 -10
  646. package/src/accounts/pollingUserAccountSubscriber.ts +26 -20
  647. package/src/accounts/pollingUserStatsAccountSubscriber.ts +12 -10
  648. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +80 -41
  649. package/src/accounts/types.ts +8 -13
  650. package/src/accounts/utils.ts +12 -2
  651. package/src/accounts/webSocketAccountSubscriber.ts +23 -10
  652. package/src/accounts/webSocketAccountSubscriberV2.ts +23 -8
  653. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +17 -2
  654. package/src/accounts/webSocketProgramAccountSubscriber.ts +29 -4
  655. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +30 -4
  656. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +29 -4
  657. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -2
  658. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +15 -2
  659. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +79 -58
  660. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +77 -45
  661. package/src/accounts/websocketProgramUserAccountSubscriber.ts +1 -6
  662. package/src/addresses/marketAddresses.ts +3 -2
  663. package/src/addresses/pda.ts +3 -38
  664. package/src/adminClient.ts +285 -315
  665. package/src/auctionSubscriber/auctionSubscriber.ts +8 -11
  666. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +13 -11
  667. package/src/auctionSubscriber/types.ts +3 -3
  668. package/src/bankrun/bankrunConnection.ts +83 -39
  669. package/src/blockhashSubscriber/BlockhashSubscriber.ts +5 -4
  670. package/src/clock/clockSubscriber.ts +10 -9
  671. package/src/config.ts +16 -70
  672. package/src/constants/index.ts +1 -2
  673. package/src/constants/numericConstants.ts +3 -3
  674. package/src/constituentMap/constituentMap.ts +10 -7
  675. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +4 -2
  676. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +13 -4
  677. package/src/core/VelocityCore.ts +11 -20
  678. package/src/core/instructions/perpOrders.ts +14 -0
  679. package/src/core/instructions/withdraw.ts +2 -2
  680. package/src/core/remainingAccounts.ts +7 -7
  681. package/src/decode/user.ts +8 -1
  682. package/src/dlob/DLOB.ts +300 -176
  683. package/src/dlob/DLOBNode.ts +23 -3
  684. package/src/dlob/DLOBSubscriber.ts +53 -42
  685. package/src/dlob/NodeList.ts +8 -7
  686. package/src/dlob/orderBookLevels.ts +51 -25
  687. package/src/dlob/types.ts +0 -2
  688. package/src/events/eventList.ts +4 -1
  689. package/src/events/eventSubscriber.ts +108 -50
  690. package/src/events/eventsServerLogProvider.ts +24 -15
  691. package/src/events/fetchLogs.ts +3 -3
  692. package/src/events/parse.ts +14 -14
  693. package/src/events/pollingLogProvider.ts +2 -2
  694. package/src/events/txEventCache.ts +8 -2
  695. package/src/events/types.ts +4 -15
  696. package/src/events/webSocketLogProvider.ts +5 -3
  697. package/src/factory/bigNum.ts +2 -2
  698. package/src/idl/{drift.json → velocity.json} +2265 -2333
  699. package/src/idl/{drift.ts → velocity.ts} +2267 -2335
  700. package/src/index.ts +1 -6
  701. package/src/jupiter/jupiterClient.ts +30 -10
  702. package/src/margin/README.md +2 -2
  703. package/src/marginCalculation.ts +1 -0
  704. package/src/math/amm.ts +217 -40
  705. package/src/math/auction.ts +16 -12
  706. package/src/math/bankruptcy.ts +1 -1
  707. package/src/math/builder.ts +45 -1
  708. package/src/math/funding.ts +51 -47
  709. package/src/math/insurance.ts +6 -8
  710. package/src/math/margin.ts +12 -119
  711. package/src/math/market.ts +16 -98
  712. package/src/math/oracles.ts +29 -43
  713. package/src/math/orders.ts +13 -109
  714. package/src/math/position.ts +6 -12
  715. package/src/math/repeg.ts +0 -29
  716. package/src/math/spotBalance.ts +14 -10
  717. package/src/math/spotMarket.ts +2 -28
  718. package/src/math/spotPosition.ts +4 -4
  719. package/src/math/state.ts +0 -8
  720. package/src/math/superStake.ts +36 -85
  721. package/src/math/trade.ts +7 -3
  722. package/src/math/utils.ts +1 -1
  723. package/src/memcmp.ts +0 -9
  724. package/src/oracles/prelaunchOracleClient.ts +7 -2
  725. package/src/oracles/pythClient.ts +12 -3
  726. package/src/oracles/pythLazerClient.ts +10 -5
  727. package/src/oracles/utils.ts +15 -0
  728. package/src/orderSubscriber/OrderSubscriber.ts +12 -12
  729. package/src/orderSubscriber/WebsocketSubscription.ts +1 -1
  730. package/src/orderSubscriber/grpcSubscription.ts +2 -2
  731. package/src/orderSubscriber/types.ts +0 -2
  732. package/src/priorityFee/heliusPriorityFeeMethod.ts +1 -1
  733. package/src/priorityFee/priorityFeeSubscriber.ts +50 -21
  734. package/src/priorityFee/priorityFeeSubscriberMap.ts +2 -10
  735. package/src/priorityFee/solanaPriorityFeeMethod.ts +1 -1
  736. package/src/priorityFee/types.ts +3 -13
  737. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -12
  738. package/src/pyth/pythLazerSubscriber.ts +1 -1
  739. package/src/pyth/types.ts +0 -2
  740. package/src/slot/SlotSubscriber.ts +3 -3
  741. package/src/slot/SlothashSubscriber.ts +17 -6
  742. package/src/swap/UnifiedSwapClient.ts +1 -1
  743. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +5 -6
  744. package/src/swift/signedMsgUserAccountSubscriber.ts +18 -16
  745. package/src/swift/swiftOrderSubscriber.ts +17 -21
  746. package/src/testClient.ts +2 -2
  747. package/src/tokenFaucet.ts +22 -3
  748. package/src/tx/baseTxSender.ts +10 -10
  749. package/src/tx/fastSingleTxSender.ts +12 -8
  750. package/src/tx/reportTransactionError.ts +12 -7
  751. package/src/tx/retryTxSender.ts +6 -4
  752. package/src/tx/txHandler.ts +88 -43
  753. package/src/tx/txParamProcessor.ts +18 -3
  754. package/src/tx/types.ts +1 -1
  755. package/src/tx/whileValidTxSender.ts +51 -22
  756. package/src/types.ts +119 -173
  757. package/src/user.ts +208 -165
  758. package/src/userConfig.ts +1 -3
  759. package/src/userMap/WebsocketSubscription.ts +2 -2
  760. package/src/userMap/grpcSubscription.ts +2 -2
  761. package/src/userMap/referrerMap.ts +13 -13
  762. package/src/userMap/revenueShareEscrowMap.ts +6 -5
  763. package/src/userMap/userMap.ts +46 -32
  764. package/src/userMap/userMapConfig.ts +3 -3
  765. package/src/userMap/userStatsMap.ts +32 -23
  766. package/src/userStats.ts +22 -13
  767. package/src/userStatsConfig.ts +3 -3
  768. package/src/util/TransactionConfirmationManager.ts +10 -2
  769. package/src/util/chainClock.ts +1 -1
  770. package/src/util/computeUnits.ts +7 -3
  771. package/src/util/ed25519Utils.ts +1 -1
  772. package/src/velocityClient.ts +867 -600
  773. package/src/velocityClientConfig.ts +0 -10
  774. package/tests/{DriftCore → VelocityCore}/decode.test.ts +1 -1
  775. package/tests/{DriftCore → VelocityCore}/fill_trigger.test.ts +1 -1
  776. package/tests/{DriftCore → VelocityCore}/instructions.test.ts +1 -1
  777. package/tests/{DriftCore → VelocityCore}/pdas.test.ts +4 -2
  778. package/tests/amm/test.ts +138 -0
  779. package/tests/ci/verifyConstants.ts +24 -27
  780. package/tests/decode/test.ts +2 -2
  781. package/tests/dlob/helpers.ts +11 -10
  782. package/tests/events/parseLogsForCuUsage.ts +15 -15
  783. package/tests/user/helpers.ts +9 -9
  784. package/tests/user/test.ts +13 -10
  785. package/tsconfig.json +1 -0
  786. package/lib/browser/constants/insuranceFund.d.ts +0 -5
  787. package/lib/browser/constants/insuranceFund.js +0 -9
  788. package/lib/browser/tx/forwardOnlyTxSender.d.ts +0 -37
  789. package/lib/browser/tx/forwardOnlyTxSender.js +0 -92
  790. package/lib/browser/util/deprecatedAlias.d.ts +0 -26
  791. package/lib/browser/util/deprecatedAlias.js +0 -10
  792. package/lib/browser/util/tps.d.ts +0 -2
  793. package/lib/browser/util/tps.js +0 -16
  794. package/lib/node/constants/insuranceFund.d.ts +0 -6
  795. package/lib/node/constants/insuranceFund.d.ts.map +0 -1
  796. package/lib/node/constants/insuranceFund.js +0 -9
  797. package/lib/node/idl/drift.d.ts.map +0 -1
  798. package/lib/node/tx/forwardOnlyTxSender.d.ts +0 -38
  799. package/lib/node/tx/forwardOnlyTxSender.d.ts.map +0 -1
  800. package/lib/node/tx/forwardOnlyTxSender.js +0 -92
  801. package/lib/node/util/deprecatedAlias.d.ts +0 -27
  802. package/lib/node/util/deprecatedAlias.d.ts.map +0 -1
  803. package/lib/node/util/deprecatedAlias.js +0 -10
  804. package/lib/node/util/tps.d.ts +0 -3
  805. package/lib/node/util/tps.d.ts.map +0 -1
  806. package/lib/node/util/tps.js +0 -16
  807. package/src/constants/insuranceFund.ts +0 -8
  808. package/src/tx/forwardOnlyTxSender.ts +0 -145
  809. package/src/util/deprecatedAlias.ts +0 -21
  810. package/src/util/tps.ts +0 -27
  811. /package/lib/browser/idl/{drift.js → velocity.js} +0 -0
  812. /package/lib/node/idl/{drift.js → velocity.js} +0 -0
  813. /package/tests/{DriftCore → VelocityCore}/perp_orders.test.ts +0 -0
  814. /package/tests/{DriftCore → VelocityCore}/remainingAccounts.test.ts +0 -0
  815. /package/tests/{DriftCore → VelocityCore}/settlement_liquidation.test.ts +0 -0
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DriftClient = exports.VelocityClient = void 0;
6
+ exports.VelocityClient = void 0;
7
7
  /**
8
8
  * VelocityClient — main SDK entry point for all trading and keeper operations.
9
9
  *
@@ -90,7 +90,7 @@ class VelocityClient {
90
90
  this._isSubscribed = val;
91
91
  }
92
92
  constructor(config) {
93
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29;
93
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26;
94
94
  this.users = new Map();
95
95
  this._isSubscribed = false;
96
96
  this.perpMarketLastSlotCache = new Map();
@@ -197,34 +197,28 @@ class VelocityClient {
197
197
  accountSubscription: this.userAccountSubscriptionConfig,
198
198
  });
199
199
  }
200
- this.marketLookupTable = config.marketLookupTable;
201
- if (!this.marketLookupTable) {
202
- this.marketLookupTable = new web3_js_1.PublicKey(config_1.configs[this.env].MARKET_LOOKUP_TABLE);
203
- }
204
- this.marketLookupTables = config.marketLookupTables;
205
- if (!this.marketLookupTables) {
206
- this.marketLookupTables = config_1.configs[this.env].MARKET_LOOKUP_TABLES.map((tableAddr) => new web3_js_1.PublicKey(tableAddr));
207
- }
200
+ this.marketLookupTables =
201
+ (_5 = config.marketLookupTables) !== null && _5 !== void 0 ? _5 : config_1.configs[this.env].MARKET_LOOKUP_TABLES.map((tableAddr) => new web3_js_1.PublicKey(tableAddr));
208
202
  const delistedMarketSetting = config.delistedMarketSetting || types_2.DelistedMarketSetting.Unsubscribe;
209
203
  const noMarketsAndOraclesSpecified = config.perpMarketIndexes === undefined &&
210
204
  config.spotMarketIndexes === undefined &&
211
205
  config.oracleInfos === undefined;
212
- if (((_5 = config.accountSubscription) === null || _5 === void 0 ? void 0 : _5.type) === 'polling') {
213
- this.accountSubscriber = new pollingVelocityClientAccountSubscriber_1.PollingVelocityClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_6 = config.perpMarketIndexes) !== null && _6 !== void 0 ? _6 : [], (_7 = config.spotMarketIndexes) !== null && _7 !== void 0 ? _7 : [], (_8 = config.oracleInfos) !== null && _8 !== void 0 ? _8 : [], noMarketsAndOraclesSpecified, delistedMarketSetting);
214
- }
215
- else if (((_9 = config.accountSubscription) === null || _9 === void 0 ? void 0 : _9.type) === 'grpc') {
216
- const accountSubscriberClass = (_13 = (_11 = (_10 = config.accountSubscription) === null || _10 === void 0 ? void 0 : _10.velocityClientAccountSubscriber) !== null && _11 !== void 0 ? _11 : (_12 = config.accountSubscription) === null || _12 === void 0 ? void 0 : _12.driftClientAccountSubscriber) !== null && _13 !== void 0 ? _13 : grpcVelocityClientAccountSubscriber_1.grpcVelocityClientAccountSubscriber;
217
- this.accountSubscriber = new accountSubscriberClass(config.accountSubscription.grpcConfigs, this.program, (_14 = config.perpMarketIndexes) !== null && _14 !== void 0 ? _14 : [], (_15 = config.spotMarketIndexes) !== null && _15 !== void 0 ? _15 : [], (_16 = config.oracleInfos) !== null && _16 !== void 0 ? _16 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
218
- resubTimeoutMs: (_17 = config.accountSubscription) === null || _17 === void 0 ? void 0 : _17.resubTimeoutMs,
219
- logResubMessages: (_18 = config.accountSubscription) === null || _18 === void 0 ? void 0 : _18.logResubMessages,
206
+ if (((_6 = config.accountSubscription) === null || _6 === void 0 ? void 0 : _6.type) === 'polling') {
207
+ this.accountSubscriber = new pollingVelocityClientAccountSubscriber_1.PollingVelocityClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_7 = config.perpMarketIndexes) !== null && _7 !== void 0 ? _7 : [], (_8 = config.spotMarketIndexes) !== null && _8 !== void 0 ? _8 : [], (_9 = config.oracleInfos) !== null && _9 !== void 0 ? _9 : [], noMarketsAndOraclesSpecified, delistedMarketSetting);
208
+ }
209
+ else if (((_10 = config.accountSubscription) === null || _10 === void 0 ? void 0 : _10.type) === 'grpc') {
210
+ const accountSubscriberClass = (_12 = (_11 = config.accountSubscription) === null || _11 === void 0 ? void 0 : _11.velocityClientAccountSubscriber) !== null && _12 !== void 0 ? _12 : grpcVelocityClientAccountSubscriber_1.grpcVelocityClientAccountSubscriber;
211
+ this.accountSubscriber = new accountSubscriberClass(config.accountSubscription.grpcConfigs, this.program, (_13 = config.perpMarketIndexes) !== null && _13 !== void 0 ? _13 : [], (_14 = config.spotMarketIndexes) !== null && _14 !== void 0 ? _14 : [], (_15 = config.oracleInfos) !== null && _15 !== void 0 ? _15 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
212
+ resubTimeoutMs: (_16 = config.accountSubscription) === null || _16 === void 0 ? void 0 : _16.resubTimeoutMs,
213
+ logResubMessages: (_17 = config.accountSubscription) === null || _17 === void 0 ? void 0 : _17.logResubMessages,
220
214
  });
221
215
  }
222
216
  else {
223
- const accountSubscriberClass = (_22 = (_20 = (_19 = config.accountSubscription) === null || _19 === void 0 ? void 0 : _19.velocityClientAccountSubscriber) !== null && _20 !== void 0 ? _20 : (_21 = config.accountSubscription) === null || _21 === void 0 ? void 0 : _21.driftClientAccountSubscriber) !== null && _22 !== void 0 ? _22 : webSocketVelocityClientAccountSubscriber_1.WebSocketVelocityClientAccountSubscriber;
224
- this.accountSubscriber = new accountSubscriberClass(this.program, (_23 = config.perpMarketIndexes) !== null && _23 !== void 0 ? _23 : [], (_24 = config.spotMarketIndexes) !== null && _24 !== void 0 ? _24 : [], (_25 = config.oracleInfos) !== null && _25 !== void 0 ? _25 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
225
- resubTimeoutMs: (_26 = config.accountSubscription) === null || _26 === void 0 ? void 0 : _26.resubTimeoutMs,
226
- logResubMessages: (_27 = config.accountSubscription) === null || _27 === void 0 ? void 0 : _27.logResubMessages,
227
- }, (_28 = config.accountSubscription) === null || _28 === void 0 ? void 0 : _28.commitment);
217
+ const accountSubscriberClass = (_19 = (_18 = config.accountSubscription) === null || _18 === void 0 ? void 0 : _18.velocityClientAccountSubscriber) !== null && _19 !== void 0 ? _19 : webSocketVelocityClientAccountSubscriber_1.WebSocketVelocityClientAccountSubscriber;
218
+ this.accountSubscriber = new accountSubscriberClass(this.program, (_20 = config.perpMarketIndexes) !== null && _20 !== void 0 ? _20 : [], (_21 = config.spotMarketIndexes) !== null && _21 !== void 0 ? _21 : [], (_22 = config.oracleInfos) !== null && _22 !== void 0 ? _22 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
219
+ resubTimeoutMs: (_23 = config.accountSubscription) === null || _23 === void 0 ? void 0 : _23.resubTimeoutMs,
220
+ logResubMessages: (_24 = config.accountSubscription) === null || _24 === void 0 ? void 0 : _24.logResubMessages,
221
+ }, (_25 = config.accountSubscription) === null || _25 === void 0 ? void 0 : _25.commitment);
228
222
  }
229
223
  this.eventEmitter = this.accountSubscriber.eventEmitter;
230
224
  this.metricsEventEmitter = new events_1.EventEmitter();
@@ -232,7 +226,7 @@ class VelocityClient {
232
226
  this.enableMetricsEvents = true;
233
227
  }
234
228
  this.txSender =
235
- (_29 = config.txSender) !== null && _29 !== void 0 ? _29 : new retryTxSender_1.RetryTxSender({
229
+ (_26 = config.txSender) !== null && _26 !== void 0 ? _26 : new retryTxSender_1.RetryTxSender({
236
230
  connection: this.connection,
237
231
  wallet: this.wallet,
238
232
  opts: this.opts,
@@ -312,6 +306,17 @@ class VelocityClient {
312
306
  var _a;
313
307
  return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
314
308
  }
309
+ /**
310
+ * Like {@link getPerpMarketAccount} but throws if the market is not loaded,
311
+ * for call sites that require a guaranteed account.
312
+ */
313
+ getPerpMarketAccountOrThrow(marketIndex) {
314
+ const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
315
+ if (!perpMarketAccount) {
316
+ throw new Error(`Perp market ${marketIndex} not found`);
317
+ }
318
+ return perpMarketAccount;
319
+ }
315
320
  /**
316
321
  * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
317
322
  * @param marketIndex
@@ -335,15 +340,28 @@ class VelocityClient {
335
340
  .map((value) => value.data);
336
341
  }
337
342
  getSpotMarketAccount(marketIndex) {
338
- return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
343
+ var _a;
344
+ return (_a = this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
345
+ }
346
+ /**
347
+ * Like {@link getSpotMarketAccount} but throws if the market is not loaded,
348
+ * for call sites that require a guaranteed account.
349
+ */
350
+ getSpotMarketAccountOrThrow(marketIndex) {
351
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
352
+ if (!spotMarketAccount) {
353
+ throw new Error(`Spot market ${marketIndex} not found`);
354
+ }
355
+ return spotMarketAccount;
339
356
  }
340
357
  /**
341
358
  * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
342
359
  * @param marketIndex
343
360
  */
344
361
  async forceGetSpotMarketAccount(marketIndex) {
362
+ var _a;
345
363
  await this.accountSubscriber.fetch();
346
- return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
364
+ return (_a = this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
347
365
  }
348
366
  getSpotMarketAccounts() {
349
367
  return this.accountSubscriber
@@ -352,23 +370,11 @@ class VelocityClient {
352
370
  .map((value) => value.data);
353
371
  }
354
372
  getQuoteSpotMarketAccount() {
355
- return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
373
+ return this.getSpotMarketAccountOrThrow(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
356
374
  }
357
375
  getOraclePriceDataAndSlot(oraclePublicKey, oracleSource) {
358
376
  return this.accountSubscriber.getOraclePriceDataAndSlot((0, oracleId_1.getOracleId)(oraclePublicKey, oracleSource));
359
377
  }
360
- /** @deprecated use fetchAllLookupTableAccounts() */
361
- async fetchMarketLookupTableAccount() {
362
- if (this.lookupTableAccount)
363
- return this.lookupTableAccount;
364
- if (!this.marketLookupTable) {
365
- console.log('Market lookup table address not set');
366
- return;
367
- }
368
- const lookupTableAccount = (await this.connection.getAddressLookupTable(this.marketLookupTable)).value;
369
- this.lookupTableAccount = lookupTableAccount;
370
- return lookupTableAccount;
371
- }
372
378
  async fetchAllLookupTableAccounts() {
373
379
  if (this.lookupTableAccounts)
374
380
  return this.lookupTableAccounts;
@@ -393,7 +399,7 @@ class VelocityClient {
393
399
  return walletSupportsVersionedTxns ? 0 : 'legacy';
394
400
  }
395
401
  /**
396
- * Update the wallet to use for drift transactions and linked user account
402
+ * Update the wallet to use for velocity transactions and linked user account
397
403
  * @param newWallet
398
404
  * @param subAccountIds
399
405
  * @param activeSubAccountId
@@ -493,7 +499,8 @@ class VelocityClient {
493
499
  const authorityChanged = authority && !((_a = this.authority) === null || _a === void 0 ? void 0 : _a.equals(authority));
494
500
  this.activeSubAccountId = subAccountId;
495
501
  this.authority = authority !== null && authority !== void 0 ? authority : this.authority;
496
- this.userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
502
+ const userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
503
+ this.userStatsAccountPublicKey = userStatsAccountPublicKey;
497
504
  /* If changing the user authority ie switching from delegate to non-delegate account, need to re-subscribe to the user stats account */
498
505
  if (authorityChanged && this.userStats) {
499
506
  if (this.userStats.isSubscribed) {
@@ -501,16 +508,17 @@ class VelocityClient {
501
508
  }
502
509
  this.userStats = new userStats_1.UserStats({
503
510
  velocityClient: this,
504
- userStatsAccountPublicKey: this.userStatsAccountPublicKey,
511
+ userStatsAccountPublicKey: userStatsAccountPublicKey,
505
512
  accountSubscription: this.userStatsAccountSubscriptionConfig,
506
513
  });
507
514
  this.userStats.subscribe();
508
515
  }
509
516
  }
510
517
  async addUser(subAccountId, authority, userAccount) {
518
+ var _a;
511
519
  authority = authority !== null && authority !== void 0 ? authority : this.authority;
512
520
  const userKey = this.getUserMapKey(subAccountId, authority);
513
- if (this.users.has(userKey) && this.users.get(userKey).isSubscribed) {
521
+ if (this.users.has(userKey) && ((_a = this.users.get(userKey)) === null || _a === void 0 ? void 0 : _a.isSubscribed)) {
514
522
  return true;
515
523
  }
516
524
  const user = this.createUser(subAccountId, this.userAccountSubscriptionConfig, authority);
@@ -528,7 +536,7 @@ class VelocityClient {
528
536
  */
529
537
  async addAndSubscribeToUsers(authority) {
530
538
  var _a, _b, _c, _d, _e, _f, _g;
531
- // save the rpc calls if driftclient is initialized without a real wallet
539
+ // save the rpc calls if velocityclient is initialized without a real wallet
532
540
  if (this.skipLoadUsers)
533
541
  return true;
534
542
  let result = true;
@@ -887,7 +895,16 @@ class VelocityClient {
887
895
  userStatsAccount = await (0, fetch_1.fetchUserStatsAccount)(this.connection, this.program, this.wallet.publicKey);
888
896
  }
889
897
  else {
890
- userStatsAccount = userStats.getAccount();
898
+ const account = userStats.getAccount();
899
+ if (!account) {
900
+ userStatsAccount = await (0, fetch_1.fetchUserStatsAccount)(this.connection, this.program, this.wallet.publicKey);
901
+ }
902
+ else {
903
+ userStatsAccount = account;
904
+ }
905
+ }
906
+ if (!userStatsAccount) {
907
+ throw new Error('UserStats account does not exist');
891
908
  }
892
909
  return userStatsAccount.numberOfSubAccountsCreated;
893
910
  }
@@ -969,7 +986,7 @@ class VelocityClient {
969
986
  let remainingAccounts;
970
987
  try {
971
988
  remainingAccounts = this.getRemainingAccounts({
972
- userAccounts: [this.getUserAccount(subAccountId)],
989
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
973
990
  });
974
991
  }
975
992
  catch (err) {
@@ -1013,6 +1030,19 @@ class VelocityClient {
1013
1030
  const { txSig } = await this.sendTransaction(tx, [], this.opts);
1014
1031
  return txSig;
1015
1032
  }
1033
+ async getUpdateUserAllowDelegateTransferIx(allowDelegateTransfer) {
1034
+ return await this.program.instruction.updateUserAllowDelegateTransfer(allowDelegateTransfer, {
1035
+ accounts: {
1036
+ userStats: this.getUserStatsAccountPublicKey(),
1037
+ authority: this.wallet.publicKey,
1038
+ },
1039
+ });
1040
+ }
1041
+ async updateUserAllowDelegateTransfer(allowDelegateTransfer) {
1042
+ const tx = await this.buildTransaction(await this.getUpdateUserAllowDelegateTransferIx(allowDelegateTransfer), this.txParams);
1043
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
1044
+ return txSig;
1045
+ }
1016
1046
  async updateUserAdvancedLp(updates) {
1017
1047
  const ixs = await Promise.all(updates.map(async ({ advancedLp, subAccountId }) => {
1018
1048
  return await this.getUpdateAdvancedDlpIx(advancedLp, subAccountId);
@@ -1188,7 +1218,7 @@ class VelocityClient {
1188
1218
  if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1189
1219
  continue;
1190
1220
  }
1191
- const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1221
+ const spotMarket = this.getSpotMarketAccountOrThrow(spotPosition.marketIndex);
1192
1222
  remainingAccounts.push({
1193
1223
  isSigner: false,
1194
1224
  isWritable: true,
@@ -1219,7 +1249,7 @@ class VelocityClient {
1219
1249
  userStats,
1220
1250
  authority,
1221
1251
  state: await this.getStatePublicKey(),
1222
- driftSigner: this.getSignerPublicKey(),
1252
+ velocitySigner: this.getSignerPublicKey(),
1223
1253
  keeper: this.wallet.publicKey,
1224
1254
  },
1225
1255
  remainingAccounts,
@@ -1274,27 +1304,44 @@ class VelocityClient {
1274
1304
  getUser(subAccountId, authority) {
1275
1305
  subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
1276
1306
  authority = authority !== null && authority !== void 0 ? authority : this.authority;
1307
+ if (subAccountId === undefined || authority === undefined) {
1308
+ throw new Error('Subaccount ID and authority are required');
1309
+ }
1277
1310
  const userMapKey = this.getUserMapKey(subAccountId, authority);
1278
- if (!this.users.has(userMapKey)) {
1311
+ const user = this.users.get(userMapKey);
1312
+ if (!user) {
1279
1313
  throw new Error(`VelocityClient has no user for user id ${userMapKey}`);
1280
1314
  }
1281
- return this.users.get(userMapKey);
1315
+ return user;
1282
1316
  }
1283
1317
  hasUser(subAccountId, authority) {
1284
1318
  subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
1285
1319
  authority = authority !== null && authority !== void 0 ? authority : this.authority;
1320
+ if (subAccountId === undefined || authority === undefined) {
1321
+ throw new Error('Subaccount ID and authority are required');
1322
+ }
1286
1323
  const userMapKey = this.getUserMapKey(subAccountId, authority);
1287
1324
  return this.users.has(userMapKey);
1288
1325
  }
1289
1326
  getUsers() {
1290
1327
  // delegate users get added to the end
1291
1328
  return [...this.users.values()]
1292
- .filter((acct) => acct.getUserAccount().authority.equals(this.wallet.publicKey))
1293
- .concat([...this.users.values()].filter((acct) => !acct.getUserAccount().authority.equals(this.wallet.publicKey)));
1329
+ .filter((acct) => { var _a; return (_a = acct.getUserAccount()) === null || _a === void 0 ? void 0 : _a.authority.equals(this.wallet.publicKey); })
1330
+ .concat([...this.users.values()].filter((acct) => { var _a; return !((_a = acct.getUserAccount()) === null || _a === void 0 ? void 0 : _a.authority.equals(this.wallet.publicKey)); }));
1294
1331
  }
1295
1332
  getUserStats() {
1296
1333
  return this.userStats;
1297
1334
  }
1335
+ /**
1336
+ * Like {@link getUserStats} but throws if there is no UserStats
1337
+ * subscription, for call sites that require a guaranteed account.
1338
+ */
1339
+ getUserStatsOrThrow() {
1340
+ if (!this.userStats) {
1341
+ throw new Error('VelocityClient has no UserStats subscription');
1342
+ }
1343
+ return this.userStats;
1344
+ }
1298
1345
  async fetchReferrerNameAccount(name) {
1299
1346
  const nameBuffer = (0, userName_1.encodeName)(name);
1300
1347
  const referrerNameAccountPublicKey = (0, pda_1.getReferrerNamePublicKeySync)(this.program.programId, nameBuffer);
@@ -1313,6 +1360,14 @@ class VelocityClient {
1313
1360
  getUserAccount(subAccountId, authority) {
1314
1361
  return this.getUser(subAccountId, authority).getUserAccount();
1315
1362
  }
1363
+ /**
1364
+ * Like {@link getUserAccount} but throws a named error instead of returning
1365
+ * `undefined` when the account has not been loaded yet. Use at call sites
1366
+ * that structurally require a loaded account.
1367
+ */
1368
+ getUserAccountOrThrow(subAccountId, authority) {
1369
+ return this.getUser(subAccountId, authority).getUserAccountOrThrow();
1370
+ }
1316
1371
  /**
1317
1372
  * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
1318
1373
  * @param subAccountId
@@ -1325,7 +1380,7 @@ class VelocityClient {
1325
1380
  return this.getUser(subAccountId, authority).getUserAccountAndSlot();
1326
1381
  }
1327
1382
  getSpotPosition(marketIndex, subAccountId) {
1328
- return this.getUserAccount(subAccountId).spotPositions.find((spotPosition) => spotPosition.marketIndex === marketIndex);
1383
+ return this.getUserAccountOrThrow(subAccountId).spotPositions.find((spotPosition) => spotPosition.marketIndex === marketIndex);
1329
1384
  }
1330
1385
  getQuoteAssetTokenAmount() {
1331
1386
  return this.getTokenAmount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
@@ -1343,7 +1398,7 @@ class VelocityClient {
1343
1398
  if (spotPosition === undefined) {
1344
1399
  return numericConstants_1.ZERO;
1345
1400
  }
1346
- const spotMarket = this.getSpotMarketAccount(marketIndex);
1401
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
1347
1402
  return (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_1.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
1348
1403
  }
1349
1404
  /**
@@ -1352,7 +1407,7 @@ class VelocityClient {
1352
1407
  * @param amount
1353
1408
  */
1354
1409
  convertToSpotPrecision(marketIndex, amount) {
1355
- const spotMarket = this.getSpotMarketAccount(marketIndex);
1410
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
1356
1411
  return (0, spotMarket_1.castNumberToSpotPrecision)(amount, spotMarket);
1357
1412
  }
1358
1413
  /**
@@ -1380,7 +1435,7 @@ class VelocityClient {
1380
1435
  }
1381
1436
  }
1382
1437
  /**
1383
- * Each drift instruction must include perp and sport market accounts in the ix remaining accounts.
1438
+ * Each velocity instruction must include perp and sport market accounts in the ix remaining accounts.
1384
1439
  * Use this function to force a subset of markets to be included in the remaining accounts for every ix
1385
1440
  *
1386
1441
  * @param perpMarketIndexes
@@ -1394,26 +1449,56 @@ class VelocityClient {
1394
1449
  this.mustIncludeSpotMarketIndexes.add(spotMarketIndex);
1395
1450
  });
1396
1451
  }
1452
+ cachePerpMarketSlot(slot, ...marketIndexes) {
1453
+ for (const marketIndex of marketIndexes) {
1454
+ if (slot !== undefined) {
1455
+ this.perpMarketLastSlotCache.set(marketIndex, slot);
1456
+ }
1457
+ else {
1458
+ this.perpMarketLastSlotCache.delete(marketIndex);
1459
+ }
1460
+ }
1461
+ }
1462
+ cacheSpotMarketSlot(slot, ...marketIndexes) {
1463
+ for (const marketIndex of marketIndexes) {
1464
+ if (slot !== undefined) {
1465
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
1466
+ }
1467
+ else {
1468
+ this.spotMarketLastSlotCache.delete(marketIndex);
1469
+ }
1470
+ }
1471
+ }
1397
1472
  getRemainingAccounts(params) {
1398
- return VelocityCore_1.VelocityCore.remainingAccounts.getRemainingAccounts(this, params);
1473
+ return VelocityCore_1.VelocityCore.remainingAccounts.getRemainingAccounts({
1474
+ getPerpMarketAccount: (marketIndex) => this.getPerpMarketAccountOrThrow(marketIndex),
1475
+ getSpotMarketAccount: (marketIndex) => this.getSpotMarketAccountOrThrow(marketIndex),
1476
+ getUserAccountAndSlot: (subAccountId, authority) => this.getUserAccountAndSlot(subAccountId, authority),
1477
+ activeSubAccountId: this.activeSubAccountId,
1478
+ authority: this.authority,
1479
+ perpMarketLastSlotCache: this.perpMarketLastSlotCache,
1480
+ spotMarketLastSlotCache: this.spotMarketLastSlotCache,
1481
+ mustIncludePerpMarketIndexes: this.mustIncludePerpMarketIndexes,
1482
+ mustIncludeSpotMarketIndexes: this.mustIncludeSpotMarketIndexes,
1483
+ }, params);
1399
1484
  }
1400
1485
  addPerpMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap) {
1401
- const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
1486
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
1402
1487
  perpMarketAccountMap.set(marketIndex, {
1403
1488
  pubkey: perpMarketAccount.pubkey,
1404
1489
  isSigner: false,
1405
1490
  isWritable: writable,
1406
1491
  });
1407
- const oracleWritable = writable && (0, types_1.isVariant)(perpMarketAccount.amm.oracleSource, 'prelaunch');
1408
- oracleAccountMap.set(perpMarketAccount.amm.oracle.toString(), {
1409
- pubkey: perpMarketAccount.amm.oracle,
1492
+ const oracleWritable = writable && (0, types_1.isVariant)(perpMarketAccount.oracleSource, 'prelaunch');
1493
+ oracleAccountMap.set(perpMarketAccount.oracle.toString(), {
1494
+ pubkey: perpMarketAccount.oracle,
1410
1495
  isSigner: false,
1411
1496
  isWritable: oracleWritable,
1412
1497
  });
1413
1498
  this.addSpotMarketToRemainingAccountMaps(perpMarketAccount.quoteSpotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
1414
1499
  }
1415
1500
  addSpotMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap) {
1416
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1501
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
1417
1502
  spotMarketAccountMap.set(spotMarketAccount.marketIndex, {
1418
1503
  pubkey: spotMarketAccount.pubkey,
1419
1504
  isSigner: false,
@@ -1429,20 +1514,27 @@ class VelocityClient {
1429
1514
  }
1430
1515
  addBuilderToRemainingAccounts(builders, remainingAccounts) {
1431
1516
  for (const builder of builders) {
1432
- // Add User account for the builder
1517
+ // Add User account for the builder. Dedupe by pubkey: an authority may be
1518
+ // both a builder and the referrer, in which case its User + RevenueShare
1519
+ // accounts would otherwise be pushed twice. On-chain `load_revenue_share_map`
1520
+ // rejects duplicates, which would silently abort the entire sweep.
1433
1521
  const builderUserAccount = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, builder, 0 // subAccountId 0 for builder user account
1434
1522
  );
1435
- remainingAccounts.push({
1436
- pubkey: builderUserAccount,
1437
- isSigner: false,
1438
- isWritable: true,
1439
- });
1523
+ if (!remainingAccounts.find((a) => a.pubkey.equals(builderUserAccount))) {
1524
+ remainingAccounts.push({
1525
+ pubkey: builderUserAccount,
1526
+ isSigner: false,
1527
+ isWritable: true,
1528
+ });
1529
+ }
1440
1530
  const builderAccount = (0, pda_1.getRevenueShareAccountPublicKey)(this.program.programId, builder);
1441
- remainingAccounts.push({
1442
- pubkey: builderAccount,
1443
- isSigner: false,
1444
- isWritable: true,
1445
- });
1531
+ if (!remainingAccounts.find((a) => a.pubkey.equals(builderAccount))) {
1532
+ remainingAccounts.push({
1533
+ pubkey: builderAccount,
1534
+ isSigner: false,
1535
+ isWritable: true,
1536
+ });
1537
+ }
1446
1538
  }
1447
1539
  }
1448
1540
  getRemainingAccountMapsForUsers(userAccounts) {
@@ -1471,10 +1563,32 @@ class VelocityClient {
1471
1563
  perpMarketAccountMap,
1472
1564
  };
1473
1565
  }
1566
+ /**
1567
+ * Look up an open order by its program-assigned order ID from the cached user account.
1568
+ *
1569
+ * `orderId` is the monotonically incrementing u32 counter that the program assigns at
1570
+ * placement time — it is not known until the place instruction executes on-chain. Use
1571
+ * {@link getOrderByUserId} when you need to look up an order by the caller-supplied
1572
+ * `userOrderId` instead.
1573
+ *
1574
+ * Returns `undefined` when the order is not found (already filled, cancelled, or the
1575
+ * account cache is stale).
1576
+ */
1474
1577
  getOrder(orderId, subAccountId) {
1475
1578
  var _a;
1476
1579
  return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.orderId === orderId);
1477
1580
  }
1581
+ /**
1582
+ * Look up an open order by the caller-supplied `userOrderId` from the cached user account.
1583
+ *
1584
+ * `userOrderId` is a 1-255 slot chosen by the caller in {@link OrderParams} and is stable
1585
+ * across the life of the order — useful when you need to reference an order before the
1586
+ * program-assigned {@link Order.orderId} is known (e.g. immediately after placing without
1587
+ * waiting for confirmation). Use {@link getOrder} when you have the program-assigned ID.
1588
+ *
1589
+ * Returns `undefined` when the order is not found (already filled, cancelled, or the
1590
+ * account cache is stale).
1591
+ */
1478
1592
  getOrderByUserId(userOrderId, subAccountId) {
1479
1593
  var _a;
1480
1594
  return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
@@ -1486,7 +1600,7 @@ class VelocityClient {
1486
1600
  * @param tokenProgram
1487
1601
  */
1488
1602
  async getAssociatedTokenAccount(marketIndex, useNative = true, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID, authority = this.wallet.publicKey, allowOwnerOffCurve = false) {
1489
- const spotMarket = this.getSpotMarketAccount(marketIndex);
1603
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
1490
1604
  if (useNative && spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT)) {
1491
1605
  return authority;
1492
1606
  }
@@ -1513,7 +1627,7 @@ class VelocityClient {
1513
1627
  }
1514
1628
  async getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, overrides) {
1515
1629
  var _a;
1516
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1630
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
1517
1631
  const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1518
1632
  const signer = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
1519
1633
  const createWSOLTokenAccount = isSolMarket && associatedTokenAccount.equals(signer);
@@ -1574,7 +1688,7 @@ class VelocityClient {
1574
1688
  async deposit(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams, initSwiftAccount = false, overrides) {
1575
1689
  const tx = await this.createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly, txParams, initSwiftAccount, overrides);
1576
1690
  const { txSig, slot } = await this.sendTransaction(tx, [], this.opts);
1577
- this.spotMarketLastSlotCache.set(marketIndex, slot);
1691
+ this.cacheSpotMarketSlot(slot, marketIndex);
1578
1692
  return txSig;
1579
1693
  }
1580
1694
  async getDepositInstruction(amount, marketIndex, userTokenAccount, subAccountId, reduceOnly = false, userInitialized = true, overrides) {
@@ -1582,8 +1696,12 @@ class VelocityClient {
1582
1696
  const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
1583
1697
  let remainingAccounts = [];
1584
1698
  if (userInitialized) {
1699
+ const userAccount = await this.forceGetUserAccount(subAccountId);
1700
+ if (!userAccount) {
1701
+ throw new Error('User account not loaded after force fetch');
1702
+ }
1585
1703
  remainingAccounts = this.getRemainingAccounts({
1586
- userAccounts: [await this.forceGetUserAccount(subAccountId)],
1704
+ userAccounts: [userAccount],
1587
1705
  useMarketLastSlotCache: true,
1588
1706
  writableSpotMarketIndexes: [marketIndex],
1589
1707
  });
@@ -1594,7 +1712,7 @@ class VelocityClient {
1594
1712
  writableSpotMarketIndexes: [marketIndex],
1595
1713
  });
1596
1714
  }
1597
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1715
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
1598
1716
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
1599
1717
  if (this.isTransferHook(spotMarketAccount)) {
1600
1718
  await this.addExtraAccountMetasToRemainingAccounts(spotMarketAccount.mint, remainingAccounts);
@@ -1683,7 +1801,11 @@ class VelocityClient {
1683
1801
  return;
1684
1802
  }
1685
1803
  const extraAccountMetasAddress = (0, spl_token_1.getExtraAccountMetaAddress)(mint, hookAccount.programId);
1686
- const extraAccountMetas = (0, spl_token_1.getExtraAccountMetas)(await this.connection.getAccountInfo(extraAccountMetasAddress));
1804
+ const extraAccountMetasAccount = await this.connection.getAccountInfo(extraAccountMetasAddress);
1805
+ if (!extraAccountMetasAccount) {
1806
+ throw new Error('Extra account metas account not found for transfer hook');
1807
+ }
1808
+ const extraAccountMetas = (0, spl_token_1.getExtraAccountMetas)(extraAccountMetasAccount);
1687
1809
  for (const acc of extraAccountMetas) {
1688
1810
  // assuming it's an extra account meta that does not rely on ix data
1689
1811
  const resolvedAcc = await (0, spl_token_1.resolveExtraAccountMeta)(this.connection, acc, remainingAccounts, Buffer.from([]), hookAccount.programId);
@@ -1713,7 +1835,7 @@ class VelocityClient {
1713
1835
  const [, initializeSignedMsgUserOrdersAccountIx] = await this.getInitializeSignedMsgUserOrdersAccountIx(this.authority, 8, overrides);
1714
1836
  ixs.push(initializeSignedMsgUserOrdersAccountIx);
1715
1837
  }
1716
- const spotMarket = this.getSpotMarketAccount(marketIndex);
1838
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
1717
1839
  const isSolMarket = spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1718
1840
  // Use external wallet for deposit source if provided, otherwise use the wallet
1719
1841
  const depositSource = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.externalWallet) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
@@ -1764,6 +1886,9 @@ class VelocityClient {
1764
1886
  }
1765
1887
  ixs.push(depositCollateralIx);
1766
1888
  if (!donateAmount.eq(numericConstants_1.ZERO)) {
1889
+ if (!wsolTokenAccount) {
1890
+ throw new Error('wsolTokenAccount is required to donate to rev pool');
1891
+ }
1767
1892
  const donateIx = await this.getDepositIntoSpotMarketRevenuePoolIx(1, donateAmount, wsolTokenAccount);
1768
1893
  ixs.push(donateIx);
1769
1894
  }
@@ -1775,6 +1900,9 @@ class VelocityClient {
1775
1900
  // Close the wrapped sol account at the end of the transaction
1776
1901
  // Return funds to the deposit source (external wallet if provided)
1777
1902
  if (createWSOLTokenAccount) {
1903
+ if (!wsolTokenAccount) {
1904
+ throw new Error('wsolTokenAccount was not created');
1905
+ }
1778
1906
  ixs.push((0, spl_token_1.createCloseAccountInstruction)(wsolTokenAccount, depositSource, depositSource, []));
1779
1907
  }
1780
1908
  return {
@@ -1807,7 +1935,7 @@ class VelocityClient {
1807
1935
  const [tx, userAccountPublicKey] = await this.createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio, poolId, overrides);
1808
1936
  const additionalSigners = [];
1809
1937
  const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
1810
- this.spotMarketLastSlotCache.set(marketIndex, slot);
1938
+ this.cacheSpotMarketSlot(slot, marketIndex);
1811
1939
  await this.addUser(subAccountId);
1812
1940
  return [txSig, userAccountPublicKey];
1813
1941
  }
@@ -1830,7 +1958,7 @@ class VelocityClient {
1830
1958
  }
1831
1959
  async getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly = false, subAccountId) {
1832
1960
  const withdrawIxs = [];
1833
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1961
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
1834
1962
  const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1835
1963
  const authority = this.wallet.publicKey;
1836
1964
  const createWSOLTokenAccount = isSolMarket && associatedTokenAddress.equals(authority);
@@ -1866,7 +1994,7 @@ class VelocityClient {
1866
1994
  const withdrawIxs = await this.getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly, subAccountId);
1867
1995
  const tx = await this.buildTransaction(withdrawIxs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
1868
1996
  const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
1869
- this.spotMarketLastSlotCache.set(marketIndex, slot);
1997
+ this.cacheSpotMarketSlot(slot, marketIndex);
1870
1998
  return txSig;
1871
1999
  }
1872
2000
  async withdrawAllDustPositions(subAccountId, txParams, opts) {
@@ -1895,12 +2023,12 @@ class VelocityClient {
1895
2023
  async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false, subAccountId) {
1896
2024
  const user = await this.getUserAccountPublicKey(subAccountId);
1897
2025
  const remainingAccounts = this.getRemainingAccounts({
1898
- userAccounts: [this.getUserAccount(subAccountId)],
2026
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
1899
2027
  useMarketLastSlotCache: true,
1900
2028
  writableSpotMarketIndexes: [marketIndex],
1901
2029
  readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1902
2030
  });
1903
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2031
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
1904
2032
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
1905
2033
  if (this.isTransferHook(spotMarketAccount)) {
1906
2034
  await this.addExtraAccountMetasToRemainingAccounts(spotMarketAccount.mint, remainingAccounts);
@@ -1914,7 +2042,7 @@ class VelocityClient {
1914
2042
  state: await this.getStatePublicKey(),
1915
2043
  spotMarket: spotMarketAccount.pubkey,
1916
2044
  spotMarketVault: spotMarketAccount.vault,
1917
- driftSigner: this.getSignerPublicKey(),
2045
+ velocitySigner: this.getSignerPublicKey(),
1918
2046
  user,
1919
2047
  userStats: this.getUserStatsAccountPublicKey(),
1920
2048
  userTokenAccount,
@@ -1935,7 +2063,7 @@ class VelocityClient {
1935
2063
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositIx(amount, marketIndex, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
1936
2064
  if (fromSubAccountId === this.activeSubAccountId ||
1937
2065
  toSubAccountId === this.activeSubAccountId) {
1938
- this.spotMarketLastSlotCache.set(marketIndex, slot);
2066
+ this.cacheSpotMarketSlot(slot, marketIndex);
1939
2067
  }
1940
2068
  return txSig;
1941
2069
  }
@@ -1944,9 +2072,10 @@ class VelocityClient {
1944
2072
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toSubAccountId);
1945
2073
  let remainingAccounts;
1946
2074
  const userMapKey = this.getUserMapKey(fromSubAccountId, this.wallet.publicKey);
1947
- if (this.users.has(userMapKey)) {
2075
+ const mapUser = this.users.get(userMapKey);
2076
+ if (mapUser) {
1948
2077
  remainingAccounts = this.getRemainingAccounts({
1949
- userAccounts: [this.users.get(userMapKey).getUserAccount()],
2078
+ userAccounts: [mapUser.getUserAccountOrThrow()],
1950
2079
  useMarketLastSlotCache: true,
1951
2080
  writableSpotMarketIndexes: [marketIndex],
1952
2081
  });
@@ -1967,7 +2096,48 @@ class VelocityClient {
1967
2096
  toUser,
1968
2097
  userStats: this.getUserStatsAccountPublicKey(),
1969
2098
  state: await this.getStatePublicKey(),
1970
- spotMarketVault: this.getSpotMarketAccount(marketIndex).vault,
2099
+ spotMarketVault: this.getSpotMarketAccountOrThrow(marketIndex).vault,
2100
+ },
2101
+ remainingAccounts,
2102
+ });
2103
+ }
2104
+ async transferDepositByDelegate(amount, marketIndex, fromSubAccountId, toSubAccountId, txParams) {
2105
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
2106
+ if (fromSubAccountId === this.activeSubAccountId ||
2107
+ toSubAccountId === this.activeSubAccountId) {
2108
+ this.cacheSpotMarketSlot(slot, marketIndex);
2109
+ }
2110
+ return txSig;
2111
+ }
2112
+ async getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId) {
2113
+ const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, fromSubAccountId);
2114
+ const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, toSubAccountId);
2115
+ let remainingAccounts;
2116
+ const userMapKey = this.getUserMapKey(fromSubAccountId, this.authority);
2117
+ const mapUser = this.users.get(userMapKey);
2118
+ if (mapUser) {
2119
+ remainingAccounts = this.getRemainingAccounts({
2120
+ userAccounts: [mapUser.getUserAccountOrThrow()],
2121
+ useMarketLastSlotCache: true,
2122
+ writableSpotMarketIndexes: [marketIndex],
2123
+ });
2124
+ }
2125
+ else {
2126
+ const fromUserAccount = (await this.program.account.user.fetch(fromUser));
2127
+ remainingAccounts = this.getRemainingAccounts({
2128
+ userAccounts: [fromUserAccount],
2129
+ useMarketLastSlotCache: true,
2130
+ writableSpotMarketIndexes: [marketIndex],
2131
+ });
2132
+ }
2133
+ return await this.program.instruction.transferDepositByDelegate(marketIndex, amount, {
2134
+ accounts: {
2135
+ delegate: this.wallet.publicKey,
2136
+ fromUser,
2137
+ toUser,
2138
+ userStats: this.getUserStatsAccountPublicKey(),
2139
+ state: await this.getStatePublicKey(),
2140
+ spotMarketVault: this.getSpotMarketAccountOrThrow(marketIndex).vault,
1971
2141
  },
1972
2142
  remainingAccounts,
1973
2143
  });
@@ -1976,19 +2146,16 @@ class VelocityClient {
1976
2146
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferPoolsIx(depositFromMarketIndex, depositToMarketIndex, borrowFromMarketIndex, borrowToMarketIndex, depositAmount, borrowAmount, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
1977
2147
  if (fromSubAccountId === this.activeSubAccountId ||
1978
2148
  toSubAccountId === this.activeSubAccountId) {
1979
- this.spotMarketLastSlotCache.set(depositFromMarketIndex, slot);
1980
- this.spotMarketLastSlotCache.set(depositToMarketIndex, slot);
1981
- this.spotMarketLastSlotCache.set(borrowFromMarketIndex, slot);
1982
- this.spotMarketLastSlotCache.set(borrowToMarketIndex, slot);
2149
+ this.cacheSpotMarketSlot(slot, depositFromMarketIndex, depositToMarketIndex, borrowFromMarketIndex, borrowToMarketIndex);
1983
2150
  }
1984
2151
  return txSig;
1985
2152
  }
1986
2153
  async getTransferPoolsIx(depositFromMarketIndex, depositToMarketIndex, borrowFromMarketIndex, borrowToMarketIndex, depositAmount, borrowAmount, fromSubAccountId, toSubAccountId, isToNewSubAccount) {
1987
2154
  const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromSubAccountId);
1988
2155
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toSubAccountId);
1989
- const userAccounts = [this.getUserAccount(fromSubAccountId)];
2156
+ const userAccounts = [this.getUserAccountOrThrow(fromSubAccountId)];
1990
2157
  if (!isToNewSubAccount) {
1991
- userAccounts.push(this.getUserAccount(toSubAccountId));
2158
+ userAccounts.push(this.getUserAccountOrThrow(toSubAccountId));
1992
2159
  }
1993
2160
  const remainingAccounts = this.getRemainingAccounts({
1994
2161
  userAccounts,
@@ -2001,8 +2168,8 @@ class VelocityClient {
2001
2168
  ],
2002
2169
  });
2003
2170
  const tokenPrograms = new Set();
2004
- const depositFromSpotMarket = this.getSpotMarketAccount(depositFromMarketIndex);
2005
- const borrowFromSpotMarket = this.getSpotMarketAccount(borrowFromMarketIndex);
2171
+ const depositFromSpotMarket = this.getSpotMarketAccountOrThrow(depositFromMarketIndex);
2172
+ const borrowFromSpotMarket = this.getSpotMarketAccountOrThrow(borrowFromMarketIndex);
2006
2173
  tokenPrograms.add(this.getTokenProgramForSpotMarket(depositFromSpotMarket).toBase58());
2007
2174
  tokenPrograms.add(this.getTokenProgramForSpotMarket(borrowFromSpotMarket).toBase58());
2008
2175
  for (const tokenProgram of tokenPrograms) {
@@ -2019,11 +2186,11 @@ class VelocityClient {
2019
2186
  toUser,
2020
2187
  userStats: this.getUserStatsAccountPublicKey(),
2021
2188
  state: await this.getStatePublicKey(),
2022
- depositFromSpotMarketVault: this.getSpotMarketAccount(depositFromMarketIndex).vault,
2023
- depositToSpotMarketVault: this.getSpotMarketAccount(depositToMarketIndex).vault,
2024
- borrowFromSpotMarketVault: this.getSpotMarketAccount(borrowFromMarketIndex).vault,
2025
- borrowToSpotMarketVault: this.getSpotMarketAccount(borrowToMarketIndex).vault,
2026
- driftSigner: this.getSignerPublicKey(),
2189
+ depositFromSpotMarketVault: this.getSpotMarketAccountOrThrow(depositFromMarketIndex).vault,
2190
+ depositToSpotMarketVault: this.getSpotMarketAccountOrThrow(depositToMarketIndex).vault,
2191
+ borrowFromSpotMarketVault: this.getSpotMarketAccountOrThrow(borrowFromMarketIndex).vault,
2192
+ borrowToSpotMarketVault: this.getSpotMarketAccountOrThrow(borrowToMarketIndex).vault,
2193
+ velocitySigner: this.getSignerPublicKey(),
2027
2194
  },
2028
2195
  remainingAccounts,
2029
2196
  });
@@ -2037,8 +2204,8 @@ class VelocityClient {
2037
2204
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, toSubAccountId);
2038
2205
  const remainingAccounts = this.getRemainingAccounts({
2039
2206
  userAccounts: [
2040
- this.getUserAccount(fromSubAccountId),
2041
- this.getUserAccount(toSubAccountId),
2207
+ this.getUserAccountOrThrow(fromSubAccountId),
2208
+ this.getUserAccountOrThrow(toSubAccountId),
2042
2209
  ],
2043
2210
  useMarketLastSlotCache: true,
2044
2211
  writablePerpMarketIndexes: [marketIndex],
@@ -2080,9 +2247,9 @@ class VelocityClient {
2080
2247
  }
2081
2248
  async getDepositIntoIsolatedPerpPositionIx(amount, perpMarketIndex, userTokenAccount, subAccountId) {
2082
2249
  const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
2083
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
2250
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
2084
2251
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
2085
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
2252
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
2086
2253
  const remainingAccounts = this.getRemainingAccounts({
2087
2254
  userAccounts: [],
2088
2255
  writableSpotMarketIndexes: [spotMarketIndex],
@@ -2108,7 +2275,7 @@ class VelocityClient {
2108
2275
  const transferIx = await this.getTransferIsolatedPerpPositionDepositIx(amount, perpMarketIndex, subAccountId, noBuffer);
2109
2276
  const needsToSettle = amount.lt(tokenAmountDeposited.neg()) || amount.eq(numericConstants_1.MIN_I64) || trySettle;
2110
2277
  if (needsToSettle) {
2111
- const settleIx = await this.settleMultiplePNLsIx(await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId), this.getUserAccount(subAccountId), [perpMarketIndex], types_1.SettlePnlMode.TRY_SETTLE);
2278
+ const settleIx = await this.settleMultiplePNLsIx(await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId), this.getUserAccountOrThrow(subAccountId), [perpMarketIndex], types_1.SettlePnlMode.TRY_SETTLE);
2112
2279
  ixs.push(settleIx);
2113
2280
  }
2114
2281
  ixs.push(transferIx);
@@ -2121,10 +2288,10 @@ class VelocityClient {
2121
2288
  }
2122
2289
  async getTransferIsolatedPerpPositionDepositIx(amount, perpMarketIndex, subAccountId, noAmountBuffer, signingAuthority) {
2123
2290
  const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
2124
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
2291
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
2125
2292
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
2126
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
2127
- const user = await this.getUserAccount(subAccountId);
2293
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
2294
+ const user = await this.getUserAccountOrThrow(subAccountId);
2128
2295
  const remainingAccounts = this.getRemainingAccounts({
2129
2296
  userAccounts: [user],
2130
2297
  writableSpotMarketIndexes: [spotMarketIndex],
@@ -2151,16 +2318,20 @@ class VelocityClient {
2151
2318
  }
2152
2319
  async getWithdrawFromIsolatedPerpPositionIxsBundle(amount, perpMarketIndex, subAccountId, userTokenAccount) {
2153
2320
  const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
2154
- const userAccount = this.getUserAccount(subAccountId);
2321
+ const userAccount = this.getUserAccountOrThrow(subAccountId);
2155
2322
  const tokenAmountDeposited = this.getIsolatedPerpPositionTokenAmount(perpMarketIndex);
2156
- const isolatedPositionUnrealizedPnl = (0, position_1.calculateClaimablePnl)(this.getPerpMarketAccount(perpMarketIndex), this.getSpotMarketAccount(this.getPerpMarketAccount(perpMarketIndex).quoteSpotMarketIndex), userAccount.perpPositions.find((p) => p.marketIndex === perpMarketIndex), this.getOracleDataForSpotMarket(this.getPerpMarketAccount(perpMarketIndex).quoteSpotMarketIndex));
2323
+ const isolatedPerpPosition = userAccount.perpPositions.find((p) => p.marketIndex === perpMarketIndex);
2324
+ if (!isolatedPerpPosition) {
2325
+ throw new Error(`No perp position found for market index ${perpMarketIndex}`);
2326
+ }
2327
+ const isolatedPositionUnrealizedPnl = (0, position_1.calculateClaimablePnl)(this.getPerpMarketAccountOrThrow(perpMarketIndex), this.getSpotMarketAccountOrThrow(this.getPerpMarketAccountOrThrow(perpMarketIndex).quoteSpotMarketIndex), isolatedPerpPosition, this.getOracleDataForSpotMarket(this.getPerpMarketAccountOrThrow(perpMarketIndex).quoteSpotMarketIndex));
2157
2328
  const depositAmountPlusUnrealizedPnl = tokenAmountDeposited.add(isolatedPositionUnrealizedPnl);
2158
2329
  const amountToWithdraw = amount.gt(depositAmountPlusUnrealizedPnl)
2159
2330
  ? numericConstants_1.MIN_I64 // min i64
2160
2331
  : amount;
2161
2332
  let associatedTokenAccount = userTokenAccount;
2162
2333
  if (!associatedTokenAccount) {
2163
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
2334
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
2164
2335
  const quoteSpotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
2165
2336
  associatedTokenAccount = await this.getAssociatedTokenAccount(quoteSpotMarketIndex);
2166
2337
  }
@@ -2176,11 +2347,11 @@ class VelocityClient {
2176
2347
  }
2177
2348
  async getWithdrawFromIsolatedPerpPositionIx(amount, perpMarketIndex, userTokenAccount, subAccountId) {
2178
2349
  const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
2179
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
2350
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
2180
2351
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
2181
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
2352
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
2182
2353
  const remainingAccounts = this.getRemainingAccounts({
2183
- userAccounts: [this.getUserAccount(subAccountId)],
2354
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2184
2355
  writableSpotMarketIndexes: [spotMarketIndex],
2185
2356
  readablePerpMarketIndex: [perpMarketIndex],
2186
2357
  });
@@ -2193,7 +2364,7 @@ class VelocityClient {
2193
2364
  authority: this.wallet.publicKey,
2194
2365
  userTokenAccount: userTokenAccount,
2195
2366
  tokenProgram: this.getTokenProgramForSpotMarket(spotMarketAccount),
2196
- driftSigner: this.getSignerPublicKey(),
2367
+ velocitySigner: this.getSignerPublicKey(),
2197
2368
  },
2198
2369
  remainingAccounts,
2199
2370
  });
@@ -2203,7 +2374,7 @@ class VelocityClient {
2203
2374
  return txSig;
2204
2375
  }
2205
2376
  async updateSpotMarketCumulativeInterestIx(marketIndex) {
2206
- const spotMarket = this.getSpotMarketAccount(marketIndex);
2377
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
2207
2378
  return await this.program.instruction.updateSpotMarketCumulativeInterest({
2208
2379
  accounts: {
2209
2380
  state: await this.getStatePublicKey(),
@@ -2223,13 +2394,13 @@ class VelocityClient {
2223
2394
  direction,
2224
2395
  baseAssetAmount: amount,
2225
2396
  price: limitPrice,
2226
- }, undefined, undefined, undefined, undefined, undefined, subAccountId);
2397
+ }, undefined, undefined, undefined, undefined, subAccountId);
2227
2398
  }
2228
2399
  async sendSignedTx(tx, opts) {
2229
2400
  const { txSig } = await this.sendTransaction(tx, undefined, opts !== null && opts !== void 0 ? opts : this.opts, true);
2230
2401
  return txSig;
2231
2402
  }
2232
- async prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl, positionMaxLev, isolatedPositionDepositAmount) {
2403
+ async prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), cancelExistingOrders, settlePnl, positionMaxLev, isolatedPositionDepositAmount) {
2233
2404
  const marketIndex = orderParams.marketIndex;
2234
2405
  const orderId = userAccount.nextOrderId;
2235
2406
  const ixPromisesForTxs = {
@@ -2263,7 +2434,7 @@ class VelocityClient {
2263
2434
  ixPromisesForTxs.fillTx = this.getFillPerpOrderIx(userAccountPublicKey, userAccount, {
2264
2435
  orderId,
2265
2436
  marketIndex,
2266
- }, makerInfo, referrerInfo, userAccount.subAccountId);
2437
+ }, makerInfo, userAccount.subAccountId);
2267
2438
  }
2268
2439
  const ixs = await Promise.all(Object.values(ixPromisesForTxs));
2269
2440
  const ixsMap = ixs.reduce((acc, ix, i) => {
@@ -2284,11 +2455,11 @@ class VelocityClient {
2284
2455
  * @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
2285
2456
  * @returns
2286
2457
  */
2287
- async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl) {
2288
- const preppedTxs = await this.prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams, referrerInfo, cancelExistingOrders, settlePnl);
2458
+ async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), cancelExistingOrders, settlePnl) {
2459
+ const preppedTxs = await this.prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams, cancelExistingOrders, settlePnl);
2289
2460
  const signedTxs = (await this.txHandler.getSignedTransactionMap(preppedTxs, this.wallet)).signedTxMap;
2290
2461
  const { txSig, slot } = await this.sendTransaction(signedTxs.marketOrderTx, [], this.opts, true);
2291
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2462
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
2292
2463
  return {
2293
2464
  txSig,
2294
2465
  signedFillTx: signedTxs.fillTx,
@@ -2304,9 +2475,51 @@ class VelocityClient {
2304
2475
  preIxs.push(await this.getTransferIsolatedPerpPositionDepositIx(isolatedPositionDepositAmount, orderParams.marketIndex, subAccountId));
2305
2476
  }
2306
2477
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlacePerpOrderIx(orderParams, subAccountId), txParams, undefined, undefined, undefined, undefined, preIxs), [], this.opts);
2307
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2478
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
2308
2479
  return txSig;
2309
2480
  }
2481
+ /**
2482
+ * Returns the RevenueShareEscrow account meta for the placing user when `orderParams`
2483
+ * carries a builder code (`builderIdx` + `builderFeeTenthBps`), otherwise `undefined`.
2484
+ * The on-chain handlers peek for this account last in `remaining_accounts`, so callers
2485
+ * must push it after the market/oracle/maker accounts.
2486
+ */
2487
+ getBuilderEscrowAccountMeta(orderParams, subAccountId) {
2488
+ var _a, _b;
2489
+ if (!(0, builder_1.hasBuilderParams)(orderParams)) {
2490
+ return undefined;
2491
+ }
2492
+ const authority = (_b = (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.authority) !== null && _b !== void 0 ? _b : this.authority;
2493
+ return {
2494
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, authority),
2495
+ isWritable: true,
2496
+ isSigner: false,
2497
+ };
2498
+ }
2499
+ /**
2500
+ * Returns the AccountMeta for the taker's RevenueShareEscrow when a fill of the
2501
+ * taker's order must include it: the order carries a builder code, or the taker
2502
+ * is referred (their escrow was initialized with a referrer). Returns `undefined`
2503
+ * when neither applies so no account meta is added to the transaction. The
2504
+ * on-chain handlers peek for this account last in `remaining_accounts`, so
2505
+ * callers must push it after the market/oracle/maker accounts.
2506
+ *
2507
+ * Throws when `takerEscrow` does not belong to `takerAuthority`.
2508
+ */
2509
+ getTakerEscrowAccountMeta(takerAuthority, orderHasBuilder, takerEscrow) {
2510
+ if (takerEscrow && !takerEscrow.authority.equals(takerAuthority)) {
2511
+ throw new Error('takerEscrow.authority does not match the taker user account authority');
2512
+ }
2513
+ const takerIsReferred = takerEscrow && (0, builder_1.escrowHasReferrer)(takerEscrow);
2514
+ if (!orderHasBuilder && !takerIsReferred) {
2515
+ return undefined;
2516
+ }
2517
+ return {
2518
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerAuthority),
2519
+ isWritable: true,
2520
+ isSigner: false,
2521
+ };
2522
+ }
2310
2523
  async getPlacePerpOrderIx(orderParams, subAccountId, depositToTradeArgs) {
2311
2524
  orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
2312
2525
  const isDepositToTradeTx = depositToTradeArgs !== undefined;
@@ -2316,13 +2529,17 @@ class VelocityClient {
2316
2529
  const remainingAccounts = this.getRemainingAccounts({
2317
2530
  userAccounts: (depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.isMakingNewAccount)
2318
2531
  ? []
2319
- : [this.getUserAccount(subAccountId)],
2532
+ : [this.getUserAccountOrThrow(subAccountId)],
2320
2533
  useMarketLastSlotCache: false,
2321
2534
  readablePerpMarketIndex: orderParams.marketIndex,
2322
2535
  readableSpotMarketIndexes: isDepositToTradeTx
2323
2536
  ? [depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.depositMarketIndex]
2324
2537
  : undefined,
2325
2538
  });
2539
+ const builderEscrow = this.getBuilderEscrowAccountMeta(orderParams, subAccountId);
2540
+ if (builderEscrow) {
2541
+ remainingAccounts.push(builderEscrow);
2542
+ }
2326
2543
  return await VelocityCore_1.VelocityCore.buildPlacePerpOrderInstruction({
2327
2544
  program: this.program,
2328
2545
  orderParams,
@@ -2341,14 +2558,14 @@ class VelocityClient {
2341
2558
  const marketAccountInfos = [];
2342
2559
  const oracleAccountInfos = [];
2343
2560
  for (const marketIndex of marketIndexes) {
2344
- const market = this.getPerpMarketAccount(marketIndex);
2561
+ const market = this.getPerpMarketAccountOrThrow(marketIndex);
2345
2562
  marketAccountInfos.push({
2346
2563
  pubkey: market.pubkey,
2347
2564
  isWritable: true,
2348
2565
  isSigner: false,
2349
2566
  });
2350
2567
  oracleAccountInfos.push({
2351
- pubkey: market.amm.oracle,
2568
+ pubkey: market.oracle,
2352
2569
  isWritable: false,
2353
2570
  isSigner: false,
2354
2571
  });
@@ -2402,6 +2619,20 @@ class VelocityClient {
2402
2619
  },
2403
2620
  });
2404
2621
  }
2622
+ /**
2623
+ * Cancel an open order and broadcast the transaction.
2624
+ *
2625
+ * When `orderId` is `undefined` (omitted or passed explicitly), the instruction is
2626
+ * sent with a `null` order ID and the program cancels the most recently placed order
2627
+ * on-chain via `get_last_order_id`. This is safe to use in a composed transaction
2628
+ * where a place instruction runs first and the assigned order ID is not yet known.
2629
+ *
2630
+ * Note: when `orderId` is `undefined` and `overrides.withdrawIsolatedDepositAmount`
2631
+ * is also provided, `getOrder` will return `undefined` (the ID is unknown client-side),
2632
+ * causing the withdraw path to throw — supply an explicit `orderId` in that case.
2633
+ *
2634
+ * @see {@link getCancelOrderIx} to obtain the instruction without sending.
2635
+ */
2405
2636
  async cancelOrder(orderId, txParams, subAccountId, overrides) {
2406
2637
  const cancelIx = await this.getCancelOrderIx(orderId, subAccountId);
2407
2638
  const instructions = [cancelIx];
@@ -2410,6 +2641,9 @@ class VelocityClient {
2410
2641
  const perpMarketIndex = order === null || order === void 0 ? void 0 : order.marketIndex;
2411
2642
  const withdrawAmount = overrides.withdrawIsolatedDepositAmount;
2412
2643
  if (withdrawAmount.gt(numericConstants_1.ZERO)) {
2644
+ if (perpMarketIndex === undefined) {
2645
+ throw new Error(`Order ${orderId} not found when withdrawing isolated deposit`);
2646
+ }
2413
2647
  const withdrawIxs = await this.getWithdrawFromIsolatedPerpPositionIxsBundle(withdrawAmount, perpMarketIndex, subAccountId);
2414
2648
  instructions.push(...withdrawIxs);
2415
2649
  }
@@ -2417,10 +2651,25 @@ class VelocityClient {
2417
2651
  const { txSig } = await this.sendTransaction(await this.buildTransaction(instructions, txParams), [], this.opts);
2418
2652
  return txSig;
2419
2653
  }
2654
+ /**
2655
+ * Build a `cancelOrder` instruction for the given order.
2656
+ *
2657
+ * When `orderId` is `undefined` (omitted or passed explicitly), the instruction is
2658
+ * built with a `null` order ID (`orderId ?? null`). The program interprets a `null`
2659
+ * ID as "cancel the user's most recently placed order" (via `get_last_order_id`
2660
+ * on-chain). This is useful when composing a multi-instruction transaction where a
2661
+ * place instruction precedes the cancel and the program-assigned order ID is not yet
2662
+ * known at build time.
2663
+ *
2664
+ * When `orderId` is supplied, only that specific order is cancelled.
2665
+ *
2666
+ * @see {@link cancelOrder} to send the transaction directly.
2667
+ * @see {@link getCancelOrderByUserIdIx} to cancel by the caller-supplied `userOrderId`.
2668
+ */
2420
2669
  async getCancelOrderIx(orderId, subAccountId) {
2421
2670
  const user = await this.getUserAccountPublicKey(subAccountId);
2422
2671
  const remainingAccounts = this.getRemainingAccounts({
2423
- userAccounts: [this.getUserAccount(subAccountId)],
2672
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2424
2673
  useMarketLastSlotCache: true,
2425
2674
  });
2426
2675
  return await VelocityCore_1.VelocityCore.buildCancelOrderInstruction({
@@ -2438,10 +2687,13 @@ class VelocityClient {
2438
2687
  }
2439
2688
  async getCancelOrderByUserIdIx(userOrderId, subAccountId) {
2440
2689
  const user = await this.getUserAccountPublicKey(subAccountId);
2441
- const order = this.getOrderByUserId(userOrderId);
2442
- const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
2690
+ const order = this.getOrderByUserId(userOrderId, subAccountId);
2691
+ if (!order) {
2692
+ throw new Error(`Order with user order id ${userOrderId} not found`);
2693
+ }
2694
+ const oracle = this.getPerpMarketAccountOrThrow(order.marketIndex).oracle;
2443
2695
  const remainingAccounts = this.getRemainingAccounts({
2444
- userAccounts: [this.getUserAccount(subAccountId)],
2696
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2445
2697
  useMarketLastSlotCache: true,
2446
2698
  });
2447
2699
  return await VelocityCore_1.VelocityCore.buildCancelOrderByUserIdInstruction({
@@ -2478,7 +2730,7 @@ class VelocityClient {
2478
2730
  async getCancelOrdersByIdsIx(orderIds, subAccountId, user, overrides) {
2479
2731
  var _a, _b, _c;
2480
2732
  const userAccountPubKey = (_a = user === null || user === void 0 ? void 0 : user.userAccountPublicKey) !== null && _a !== void 0 ? _a : (await this.getUserAccountPublicKey(subAccountId));
2481
- const userAccount = (_b = user === null || user === void 0 ? void 0 : user.getUserAccount()) !== null && _b !== void 0 ? _b : this.getUserAccount(subAccountId);
2733
+ const userAccount = (_b = user === null || user === void 0 ? void 0 : user.getUserAccount()) !== null && _b !== void 0 ? _b : this.getUserAccountOrThrow(subAccountId);
2482
2734
  const remainingAccounts = this.getRemainingAccounts({
2483
2735
  userAccounts: [userAccount],
2484
2736
  useMarketLastSlotCache: true,
@@ -2510,7 +2762,7 @@ class VelocityClient {
2510
2762
  }
2511
2763
  }
2512
2764
  const remainingAccounts = this.getRemainingAccounts({
2513
- userAccounts: [this.getUserAccount(subAccountId)],
2765
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2514
2766
  readablePerpMarketIndex,
2515
2767
  readableSpotMarketIndexes,
2516
2768
  useMarketLastSlotCache: true,
@@ -2574,13 +2826,22 @@ class VelocityClient {
2574
2826
  }
2575
2827
  }
2576
2828
  const remainingAccounts = this.getRemainingAccounts({
2577
- userAccounts: [this.getUserAccount(subAccountId)],
2829
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2578
2830
  readablePerpMarketIndex,
2579
2831
  readableSpotMarketIndexes,
2580
2832
  useMarketLastSlotCache: true,
2581
2833
  });
2582
2834
  const formattedParams = params.map((item) => (0, orderParams_1.getOrderParams)(item));
2583
2835
  const authority = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
2836
+ // The handler loads a single RevenueShareEscrow for the placing user, so push it once
2837
+ // if any order in the batch carries a builder code.
2838
+ const builderParam = formattedParams.find((p) => (0, builder_1.hasBuilderParams)(p));
2839
+ if (builderParam) {
2840
+ const builderEscrow = this.getBuilderEscrowAccountMeta(builderParam, subAccountId);
2841
+ if (builderEscrow) {
2842
+ remainingAccounts.push(builderEscrow);
2843
+ }
2844
+ }
2584
2845
  return await VelocityCore_1.VelocityCore.buildPlaceOrdersInstruction({
2585
2846
  program: this.program,
2586
2847
  formattedParams,
@@ -2607,7 +2868,7 @@ class VelocityClient {
2607
2868
  }
2608
2869
  }
2609
2870
  const remainingAccounts = this.getRemainingAccounts({
2610
- userAccounts: [this.getUserAccount(subAccountId)],
2871
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2611
2872
  readablePerpMarketIndex,
2612
2873
  readableSpotMarketIndexes,
2613
2874
  useMarketLastSlotCache: true,
@@ -2650,7 +2911,7 @@ class VelocityClient {
2650
2911
  const user = await this.getUserAccountPublicKey(subAccountId);
2651
2912
  const isPerp = (0, types_1.isVariant)(params.marketType, 'perp');
2652
2913
  const remainingAccounts = this.getRemainingAccounts({
2653
- userAccounts: [this.getUserAccount(subAccountId)],
2914
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
2654
2915
  readablePerpMarketIndex: isPerp ? [params.marketIndex] : [],
2655
2916
  readableSpotMarketIndexes: isPerp ? [] : [params.marketIndex],
2656
2917
  useMarketLastSlotCache: true,
@@ -2679,11 +2940,17 @@ class VelocityClient {
2679
2940
  remainingAccounts,
2680
2941
  });
2681
2942
  }
2682
- async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, referrerInfo, txParams, fillerSubAccountId, fillerAuthority, hasBuilderFee) {
2683
- const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, referrerInfo, fillerSubAccountId, undefined, fillerAuthority, hasBuilderFee), txParams), [], this.opts);
2943
+ async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, txParams, fillerSubAccountId, fillerAuthority, hasBuilderFee, takerEscrow) {
2944
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, fillerSubAccountId, undefined, fillerAuthority, hasBuilderFee, takerEscrow), txParams), [], this.opts);
2684
2945
  return txSig;
2685
2946
  }
2686
- async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, referrerInfo, fillerSubAccountId, isSignedMsg, fillerAuthority, hasBuilderFee) {
2947
+ async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, fillerSubAccountId, isSignedMsg, fillerAuthority, hasBuilderFee,
2948
+ // The program rejects fills that omit the taker's RevenueShareEscrow when the
2949
+ // order has a builder OR the taker is referred with an escrow. The builder case
2950
+ // is detected from the order bitflags; pass the taker's decoded escrow (e.g.
2951
+ // from a RevenueShareEscrowMap) so referred takers also get it attached.
2952
+ takerEscrow) {
2953
+ var _a;
2687
2954
  const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
2688
2955
  let filler;
2689
2956
  if (fillerAuthority) {
@@ -2701,7 +2968,10 @@ class VelocityClient {
2701
2968
  }
2702
2969
  const marketIndex = order
2703
2970
  ? order.marketIndex
2704
- : userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1).marketIndex;
2971
+ : (_a = userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1)) === null || _a === void 0 ? void 0 : _a.marketIndex;
2972
+ if (marketIndex === undefined) {
2973
+ throw new Error('No order found to fill');
2974
+ }
2705
2975
  makerInfo = Array.isArray(makerInfo)
2706
2976
  ? makerInfo
2707
2977
  : makerInfo
@@ -2727,22 +2997,6 @@ class VelocityClient {
2727
2997
  isSigner: false,
2728
2998
  });
2729
2999
  }
2730
- if (referrerInfo) {
2731
- const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
2732
- undefined;
2733
- if (!referrerIsMaker) {
2734
- remainingAccounts.push({
2735
- pubkey: referrerInfo.referrer,
2736
- isWritable: true,
2737
- isSigner: false,
2738
- });
2739
- remainingAccounts.push({
2740
- pubkey: referrerInfo.referrerStats,
2741
- isWritable: true,
2742
- isSigner: false,
2743
- });
2744
- }
2745
- }
2746
3000
  let withBuilder = false;
2747
3001
  if (hasBuilderFee) {
2748
3002
  withBuilder = true;
@@ -2761,14 +3015,17 @@ class VelocityClient {
2761
3015
  withBuilder = true;
2762
3016
  }
2763
3017
  }
2764
- if (withBuilder) {
2765
- remainingAccounts.push({
2766
- pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, userAccount.authority),
2767
- isWritable: true,
2768
- isSigner: false,
2769
- });
3018
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(userAccount.authority, withBuilder, takerEscrow);
3019
+ if (takerEscrowMeta) {
3020
+ remainingAccounts.push(takerEscrowMeta);
3021
+ }
3022
+ let orderId = null;
3023
+ if (!isSignedMsg) {
3024
+ if (!order) {
3025
+ throw new Error('order is required to fill a non-signedMsg order');
3026
+ }
3027
+ orderId = order.orderId;
2770
3028
  }
2771
- const orderId = isSignedMsg ? null : order.orderId;
2772
3029
  return await VelocityCore_1.VelocityCore.buildFillPerpOrderInstruction({
2773
3030
  program: this.program,
2774
3031
  orderId,
@@ -2802,14 +3059,14 @@ class VelocityClient {
2802
3059
  async getPlaceSpotOrderIx(_orderParams, _subAccountId, _overrides) {
2803
3060
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
2804
3061
  }
2805
- async fillSpotOrder(_userAccountPublicKey, _user, _order, _fulfillmentConfig, _makerInfo, _referrerInfo, _txParams) {
3062
+ async fillSpotOrder(_userAccountPublicKey, _user, _order, _fulfillmentConfig, _makerInfo, _txParams) {
2806
3063
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
2807
3064
  }
2808
- async getFillSpotOrderIx(_userAccountPublicKey, _userAccount, _order, _fulfillmentConfig, _makerInfo, _referrerInfo, _fillerPublicKey) {
3065
+ async getFillSpotOrderIx(_userAccountPublicKey, _userAccount, _order, _fulfillmentConfig, _makerInfo, _fillerPublicKey) {
2809
3066
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
2810
3067
  }
2811
3068
  /**
2812
- * Swap tokens in drift account using titan or jupiter
3069
+ * Swap tokens in velocity account using titan or jupiter
2813
3070
  * @param swapClient swap client to find routes and instructions (Titan or Jupiter)
2814
3071
  * @param jupiterClient @deprecated Use swapClient instead. Legacy parameter for backward compatibility
2815
3072
  * @param outMarketIndex the market index of the token you're buying
@@ -2820,7 +3077,7 @@ class VelocityClient {
2820
3077
  * @param slippageBps the max slippage passed to the swap provider api
2821
3078
  * @param swapMode swap provider swapMode (ExactIn or ExactOut), default is ExactIn
2822
3079
  * @param route the swap provider route to use for the swap
2823
- * @param reduceOnly specify if In or Out token on the drift account must reduceOnly, checked at end of swap
3080
+ * @param reduceOnly specify if In or Out token on the velocity account must reduceOnly, checked at end of swap
2824
3081
  * @param v6 pass in the quote response from swap provider quote's API (deprecated, use quote instead)
2825
3082
  * @param quote pass in the quote response from swap provider quote's API
2826
3083
  * @param txParams
@@ -2886,13 +3143,12 @@ class VelocityClient {
2886
3143
  const lookupTables = res.lookupTables;
2887
3144
  const tx = (await this.buildTransaction(ixs, txParams, 0, lookupTables));
2888
3145
  const { txSig, slot } = await this.sendTransaction(tx);
2889
- this.spotMarketLastSlotCache.set(outMarketIndex, slot);
2890
- this.spotMarketLastSlotCache.set(inMarketIndex, slot);
3146
+ this.cacheSpotMarketSlot(slot, outMarketIndex, inMarketIndex);
2891
3147
  return txSig;
2892
3148
  }
2893
3149
  async getTitanSwapIx({ titanClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, reduceOnly, userAccountPublicKey, }) {
2894
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
2895
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
3150
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
3151
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
2896
3152
  const isExactOut = swapMode === 'ExactOut';
2897
3153
  const exactOutBufferedAmountIn = amount.muln(1001).divn(1000); // Add 10bp buffer
2898
3154
  const preInstructions = [];
@@ -2929,7 +3185,7 @@ class VelocityClient {
2929
3185
  slippageBps,
2930
3186
  swapMode: isExactOut ? titanClient_1.SwapMode.ExactOut : titanClient_1.SwapMode.ExactIn,
2931
3187
  onlyDirectRoutes,
2932
- sizeConstraint: utils_2.MAX_TX_BYTE_SIZE - 375, // buffer for drift instructions
3188
+ sizeConstraint: utils_2.MAX_TX_BYTE_SIZE - 375, // buffer for velocity instructions
2933
3189
  });
2934
3190
  const titanInstructions = titanClient.getTitanInstructions({
2935
3191
  transactionMessage,
@@ -2945,8 +3201,8 @@ class VelocityClient {
2945
3201
  return { ixs, lookupTables };
2946
3202
  }
2947
3203
  async getJupiterSwapIxV6({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, quote, reduceOnly, userAccountPublicKey, }) {
2948
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
2949
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
3204
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
3205
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
2950
3206
  if (!quote) {
2951
3207
  const fetchedQuote = await jupiterClient.getQuote({
2952
3208
  inputMint: inMarket.mint,
@@ -3012,7 +3268,7 @@ class VelocityClient {
3012
3268
  return { ixs, lookupTables };
3013
3269
  }
3014
3270
  /**
3015
- * Get the drift begin_swap and end_swap instructions
3271
+ * Get the velocity begin_swap and end_swap instructions
3016
3272
  *
3017
3273
  * @param outMarketIndex the market index of the token you're buying
3018
3274
  * @param inMarketIndex the market index of the token you're selling
@@ -3027,8 +3283,11 @@ class VelocityClient {
3027
3283
  const userAccountPublicKeyToUse = userAccountPublicKey || (await this.getUserAccountPublicKey());
3028
3284
  const userAccounts = [];
3029
3285
  try {
3030
- if (this.hasUser() && this.getUser().getUserAccountAndSlot()) {
3031
- userAccounts.push(this.getUser().getUserAccountAndSlot().data);
3286
+ const userAccount = this.hasUser()
3287
+ ? this.getUser().getUserAccount()
3288
+ : undefined;
3289
+ if (userAccount) {
3290
+ userAccounts.push(userAccount);
3032
3291
  }
3033
3292
  }
3034
3293
  catch (err) {
@@ -3039,8 +3298,8 @@ class VelocityClient {
3039
3298
  writableSpotMarketIndexes: [outMarketIndex, inMarketIndex],
3040
3299
  readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3041
3300
  });
3042
- const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
3043
- const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
3301
+ const outSpotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
3302
+ const inSpotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
3044
3303
  const outTokenProgram = this.getTokenProgramForSpotMarket(outSpotMarket);
3045
3304
  const inTokenProgram = this.getTokenProgramForSpotMarket(inSpotMarket);
3046
3305
  if (!outTokenProgram.equals(inTokenProgram)) {
@@ -3079,7 +3338,7 @@ class VelocityClient {
3079
3338
  inTokenAccount,
3080
3339
  outTokenAccount,
3081
3340
  tokenProgram: inTokenProgram,
3082
- driftSigner: this.getStateAccount().signer,
3341
+ velocitySigner: this.getStateAccount().signer,
3083
3342
  instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3084
3343
  },
3085
3344
  remainingAccounts,
@@ -3095,7 +3354,7 @@ class VelocityClient {
3095
3354
  inTokenAccount,
3096
3355
  outTokenAccount,
3097
3356
  tokenProgram: inTokenProgram,
3098
- driftSigner: this.getStateAccount().signer,
3357
+ velocitySigner: this.getStateAccount().signer,
3099
3358
  instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3100
3359
  },
3101
3360
  remainingAccounts,
@@ -3104,8 +3363,8 @@ class VelocityClient {
3104
3363
  }
3105
3364
  async getSwapIxV2({ swapClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, reduceOnly, quote, v6, userAccountPublicKey, }) {
3106
3365
  // Get market accounts to determine mints
3107
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
3108
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
3366
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
3367
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
3109
3368
  const isExactOut = swapMode === 'ExactOut';
3110
3369
  const preInstructions = [];
3111
3370
  // Handle token accounts if not provided
@@ -3141,7 +3400,7 @@ class VelocityClient {
3141
3400
  else {
3142
3401
  amountInForBeginSwap = amount;
3143
3402
  }
3144
- // Get drift swap instructions for begin and end
3403
+ // Get velocity swap instructions for begin and end
3145
3404
  const { beginSwapIx, endSwapIx } = await this.getSwapIx({
3146
3405
  outMarketIndex,
3147
3406
  inMarketIndex,
@@ -3179,7 +3438,7 @@ class VelocityClient {
3179
3438
  return this.sendTransaction(tx);
3180
3439
  }
3181
3440
  async getStakeForMSOLIx({ amount, userAccountPublicKey, }) {
3182
- const wSOLMint = this.getSpotMarketAccount(1).mint;
3441
+ const wSOLMint = this.getSpotMarketAccountOrThrow(1).mint;
3183
3442
  const mSOLAccount = await this.getAssociatedTokenAccount(2);
3184
3443
  const wSOLAccount = await this.getAssociatedTokenAccount(1, false);
3185
3444
  const wSOLAccountExists = await this.checkIfAccountExists(wSOLAccount);
@@ -3328,12 +3587,12 @@ class VelocityClient {
3328
3587
  remainingAccounts,
3329
3588
  });
3330
3589
  }
3331
- async placeAndTakePerpOrder(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, txParams, subAccountId) {
3332
- const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, subAccountId), txParams), [], this.opts);
3333
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
3590
+ async placeAndTakePerpOrder(orderParams, makerInfo, successCondition, auctionDurationPercentage, txParams, subAccountId, takerEscrow) {
3591
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, successCondition, auctionDurationPercentage, subAccountId, undefined, takerEscrow), txParams), [], this.opts);
3592
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
3334
3593
  return txSig;
3335
3594
  }
3336
- async preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails, auctionDurationPercentage, optionalIxs, isolatedPositionDepositAmount) {
3595
+ async preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails, auctionDurationPercentage, optionalIxs, isolatedPositionDepositAmount) {
3337
3596
  const placeAndTakeIxs = [];
3338
3597
  const txsToSign = {
3339
3598
  placeAndTakeTx: undefined,
@@ -3346,7 +3605,7 @@ class VelocityClient {
3346
3605
  let earlyExitFailedPlaceAndTakeSim = false;
3347
3606
  const prepPlaceAndTakeTx = async () => {
3348
3607
  var _a, _b;
3349
- const placeAndTakeIx = await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, undefined, auctionDurationPercentage, subAccountId);
3608
+ const placeAndTakeIx = await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, undefined, auctionDurationPercentage, subAccountId);
3350
3609
  if ((0, types_1.isVariant)(orderParams.marketType, 'perp') &&
3351
3610
  ((_a = isolatedPositionDepositAmount === null || isolatedPositionDepositAmount === void 0 ? void 0 : isolatedPositionDepositAmount.gt) === null || _a === void 0 ? void 0 : _a.call(isolatedPositionDepositAmount, numericConstants_1.ZERO)) &&
3352
3611
  this.isOrderIncreasingPosition(orderParams, subAccountId)) {
@@ -3368,6 +3627,9 @@ class VelocityClient {
3368
3627
  useSimulatedComputeUnits: false,
3369
3628
  };
3370
3629
  if (shouldUseSimulationComputeUnits || shouldExitIfSimulationFails) {
3630
+ if (!txParams) {
3631
+ throw new Error('txParams is required when simulating compute units or exiting early on failed simulation');
3632
+ }
3371
3633
  const placeAndTakeTxToSim = (await this.buildTransaction(placeAndTakeIxs, txParams, undefined, lookupTableAccounts, true, recentBlockHash, optionalIxs));
3372
3634
  const simulationResult = await txParamProcessor_1.TransactionParamProcessor.getTxSimComputeUnits(placeAndTakeTxToSim, this.connection, (_b = txParams.computeUnitsBufferMultiplier) !== null && _b !== void 0 ? _b : 1.2, txParams.lowerBoundCu);
3373
3635
  if (shouldExitIfSimulationFails && !simulationResult.success) {
@@ -3394,7 +3656,7 @@ class VelocityClient {
3394
3656
  const prepSettlePnlTx = async () => {
3395
3657
  if (settlePnl && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
3396
3658
  const userAccountPublicKey = await this.getUserAccountPublicKey(subAccountId);
3397
- const settlePnlIx = await this.settlePNLIx(userAccountPublicKey, this.getUserAccount(subAccountId), orderParams.marketIndex);
3659
+ const settlePnlIx = await this.settlePNLIx(userAccountPublicKey, this.getUserAccountOrThrow(subAccountId), orderParams.marketIndex);
3398
3660
  txsToSign.settlePnlTx = await this.buildTransaction([settlePnlIx], txParams, this.txVersion, lookupTableAccounts, undefined, recentBlockHash, optionalIxs);
3399
3661
  }
3400
3662
  return;
@@ -3409,24 +3671,32 @@ class VelocityClient {
3409
3671
  }
3410
3672
  return txsToSign;
3411
3673
  }
3412
- async placeAndTakePerpWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails) {
3413
- const txsToSign = await this.preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams, txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails);
3674
+ async placeAndTakePerpWithAdditionalOrders(orderParams, makerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails) {
3675
+ const txsToSign = await this.preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, bracketOrdersParams, txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails);
3414
3676
  if (!txsToSign) {
3415
3677
  return null;
3416
3678
  }
3417
3679
  const signedTxs = (await this.txHandler.getSignedTransactionMap(txsToSign,
3418
3680
  // @ts-ignore
3419
3681
  this.provider.wallet)).signedTxMap;
3682
+ if (!signedTxs.placeAndTakeTx) {
3683
+ throw new Error('placeAndTakeTx was not built');
3684
+ }
3420
3685
  const { txSig, slot } = await this.sendTransaction(signedTxs.placeAndTakeTx, [], this.opts, true);
3421
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
3686
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
3422
3687
  return {
3423
3688
  txSig,
3424
3689
  signedCancelExistingOrdersTx: signedTxs.cancelExistingOrdersTx,
3425
3690
  signedSettlePnlTx: signedTxs.settlePnlTx,
3426
3691
  };
3427
3692
  }
3428
- async getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, subAccountId, overrides) {
3429
- var _a;
3693
+ async getPlaceAndTakePerpOrderIx(orderParams, makerInfo, successCondition, auctionDurationPercentage, subAccountId, overrides,
3694
+ // place_and_take fills the placing user's (the taker's) order in-instruction, so
3695
+ // their RevenueShareEscrow must be attached for BOTH builder fees and referrer
3696
+ // revenue share. The builder case is detected from orderParams; pass the user's
3697
+ // decoded escrow (e.g. from a RevenueShareEscrowMap) to cover the referred case.
3698
+ takerEscrow) {
3699
+ var _a, _b, _c;
3430
3700
  orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
3431
3701
  const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
3432
3702
  const user = await this.getUserAccountPublicKey(subAccountId);
@@ -3435,7 +3705,7 @@ class VelocityClient {
3435
3705
  : makerInfo
3436
3706
  ? [makerInfo]
3437
3707
  : [];
3438
- const userAccounts = [this.getUserAccount(subAccountId)];
3708
+ const userAccounts = [this.getUserAccountOrThrow(subAccountId)];
3439
3709
  for (const maker of makerInfo) {
3440
3710
  userAccounts.push(maker.makerUserAccount);
3441
3711
  }
@@ -3456,28 +3726,16 @@ class VelocityClient {
3456
3726
  isSigner: false,
3457
3727
  });
3458
3728
  }
3459
- if (referrerInfo) {
3460
- const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
3461
- undefined;
3462
- if (!referrerIsMaker) {
3463
- remainingAccounts.push({
3464
- pubkey: referrerInfo.referrer,
3465
- isWritable: true,
3466
- isSigner: false,
3467
- });
3468
- remainingAccounts.push({
3469
- pubkey: referrerInfo.referrerStats,
3470
- isWritable: true,
3471
- isSigner: false,
3472
- });
3473
- }
3729
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta((_b = (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.authority) !== null && _b !== void 0 ? _b : this.authority, (0, builder_1.hasBuilderParams)(orderParams), takerEscrow);
3730
+ if (takerEscrowMeta) {
3731
+ remainingAccounts.push(takerEscrowMeta);
3474
3732
  }
3475
3733
  let optionalParams = null;
3476
3734
  if (auctionDurationPercentage || successCondition) {
3477
3735
  optionalParams =
3478
3736
  ((auctionDurationPercentage !== null && auctionDurationPercentage !== void 0 ? auctionDurationPercentage : 100) << 8) | (successCondition !== null && successCondition !== void 0 ? successCondition : 0);
3479
3737
  }
3480
- const authority = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
3738
+ const authority = (_c = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _c !== void 0 ? _c : this.wallet.publicKey;
3481
3739
  return await VelocityCore_1.VelocityCore.buildPlaceAndTakePerpOrderInstruction({
3482
3740
  program: this.program,
3483
3741
  orderParams,
@@ -3489,42 +3747,32 @@ class VelocityClient {
3489
3747
  remainingAccounts,
3490
3748
  });
3491
3749
  }
3492
- async placeAndMakePerpOrder(orderParams, takerInfo, referrerInfo, txParams, subAccountId) {
3493
- const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId), txParams), [], this.opts);
3494
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
3750
+ async placeAndMakePerpOrder(orderParams, takerInfo, txParams, subAccountId, takerEscrow) {
3751
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakePerpOrderIx(orderParams, takerInfo, subAccountId, takerEscrow), txParams), [], this.opts);
3752
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
3495
3753
  return txSig;
3496
3754
  }
3497
- async getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId) {
3755
+ async getPlaceAndMakePerpOrderIx(orderParams, takerInfo, subAccountId,
3756
+ // place_and_make fills the taker's order in-instruction, so the TAKER's
3757
+ // RevenueShareEscrow must be attached when their order has a builder or they
3758
+ // are referred with an escrow. The builder case is detected from the taker
3759
+ // order bitflags; pass the taker's decoded escrow to cover the referred case.
3760
+ takerEscrow) {
3498
3761
  orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
3499
3762
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3500
3763
  const user = await this.getUserAccountPublicKey(subAccountId);
3501
3764
  const remainingAccounts = this.getRemainingAccounts({
3502
3765
  userAccounts: [
3503
- this.getUserAccount(subAccountId),
3766
+ this.getUserAccountOrThrow(subAccountId),
3504
3767
  takerInfo.takerUserAccount,
3505
3768
  ],
3506
3769
  useMarketLastSlotCache: true,
3507
3770
  writablePerpMarketIndexes: [orderParams.marketIndex],
3508
3771
  });
3509
- if (referrerInfo) {
3510
- remainingAccounts.push({
3511
- pubkey: referrerInfo.referrer,
3512
- isWritable: true,
3513
- isSigner: false,
3514
- });
3515
- remainingAccounts.push({
3516
- pubkey: referrerInfo.referrerStats,
3517
- isWritable: true,
3518
- isSigner: false,
3519
- });
3520
- }
3521
3772
  const takerOrderId = takerInfo.order.orderId;
3522
- if ((0, orders_1.hasBuilder)(takerInfo.order)) {
3523
- remainingAccounts.push({
3524
- pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3525
- isWritable: true,
3526
- isSigner: false,
3527
- });
3773
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(takerInfo.takerUserAccount.authority, (0, orders_1.hasBuilder)(takerInfo.order), takerEscrow);
3774
+ if (takerEscrowMeta) {
3775
+ remainingAccounts.push(takerEscrowMeta);
3528
3776
  }
3529
3777
  return await VelocityCore_1.VelocityCore.buildPlaceAndMakePerpOrderInstruction({
3530
3778
  program: this.program,
@@ -3550,7 +3798,7 @@ class VelocityClient {
3550
3798
  /**
3551
3799
  * Builds a deposit and place request for Swift service
3552
3800
  *
3553
- * @param depositTx - The signed tx containing a drift deposit (e.g. see `buildSwiftDepositTx`)
3801
+ * @param depositTx - The signed tx containing a velocity deposit (e.g. see `buildSwiftDepositTx`)
3554
3802
  * @param orderParamsMessage - The order parameters message to sign
3555
3803
  * @param delegateSigner - Whether this is a delegate signer
3556
3804
  *
@@ -3590,6 +3838,9 @@ class VelocityClient {
3590
3838
  });
3591
3839
  }
3592
3840
  signMessage(message, keypair = this.wallet.payer) {
3841
+ if (!keypair) {
3842
+ throw new Error('No keypair available to sign message');
3843
+ }
3593
3844
  return Buffer.from(tweetnacl_1.default.sign.detached(message, keypair.secretKey));
3594
3845
  }
3595
3846
  async placeSignedMsgTakerOrder(signedSignedMsgOrderParams, marketIndex, takerInfo, precedingIxs = [], overrideCustomIxIndex, txParams) {
@@ -3611,8 +3862,7 @@ class VelocityClient {
3611
3862
  readablePerpMarketIndex: marketIndex,
3612
3863
  writableSpotMarketIndexes,
3613
3864
  });
3614
- if (signedMessage.builderFeeTenthBps !== null &&
3615
- signedMessage.builderIdx !== null) {
3865
+ if ((0, builder_1.hasBuilderParams)(signedMessage)) {
3616
3866
  remainingAccounts.push({
3617
3867
  pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3618
3868
  isWritable: true,
@@ -3641,47 +3891,35 @@ class VelocityClient {
3641
3891
  });
3642
3892
  return [signedMsgOrderParamsSignatureIx, placeTakerSignedMsgPerpOrderIx];
3643
3893
  }
3644
- async placeAndMakeSignedMsgPerpOrder(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, referrerInfo, txParams, subAccountId, precedingIxs = [], overrideCustomIxIndex) {
3645
- const ixs = await this.getPlaceAndMakeSignedMsgPerpOrderIxs(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, referrerInfo, subAccountId, precedingIxs, overrideCustomIxIndex);
3894
+ async placeAndMakeSignedMsgPerpOrder(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, txParams, subAccountId, precedingIxs = [], overrideCustomIxIndex, takerEscrow) {
3895
+ const ixs = await this.getPlaceAndMakeSignedMsgPerpOrderIxs(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, subAccountId, precedingIxs, overrideCustomIxIndex, takerEscrow);
3646
3896
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
3647
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
3897
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
3648
3898
  return txSig;
3649
3899
  }
3650
- async getPlaceAndMakeSignedMsgPerpOrderIxs(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, referrerInfo, subAccountId, precedingIxs = [], overrideCustomIxIndex) {
3900
+ async getPlaceAndMakeSignedMsgPerpOrderIxs(signedSignedMsgOrderParams, signedMsgOrderUuid, takerInfo, orderParams, subAccountId, precedingIxs = [], overrideCustomIxIndex,
3901
+ // fills the taker's order in-instruction; pass the taker's decoded escrow so a
3902
+ // referred taker's escrow is attached even when the signed order carries no
3903
+ // builder fee
3904
+ takerEscrow) {
3651
3905
  const [signedMsgOrderSignatureIx, placeTakerSignedMsgPerpOrderIx] = await this.getPlaceSignedMsgTakerPerpOrderIxs(signedSignedMsgOrderParams, orderParams.marketIndex, takerInfo, precedingIxs, overrideCustomIxIndex);
3652
3906
  orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
3653
3907
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3654
3908
  const user = await this.getUserAccountPublicKey(subAccountId);
3655
3909
  const remainingAccounts = this.getRemainingAccounts({
3656
3910
  userAccounts: [
3657
- this.getUserAccount(subAccountId),
3911
+ this.getUserAccountOrThrow(subAccountId),
3658
3912
  takerInfo.takerUserAccount,
3659
3913
  ],
3660
3914
  useMarketLastSlotCache: false,
3661
3915
  writablePerpMarketIndexes: [orderParams.marketIndex],
3662
3916
  });
3663
- if (referrerInfo) {
3664
- remainingAccounts.push({
3665
- pubkey: referrerInfo.referrer,
3666
- isWritable: true,
3667
- isSigner: false,
3668
- });
3669
- remainingAccounts.push({
3670
- pubkey: referrerInfo.referrerStats,
3671
- isWritable: true,
3672
- isSigner: false,
3673
- });
3674
- }
3675
3917
  const isDelegateSigner = takerInfo.signingAuthority.equals(takerInfo.takerUserAccount.delegate);
3676
3918
  const borshBuf = Buffer.from(signedSignedMsgOrderParams.orderParams.toString(), 'hex');
3677
3919
  const signedMessage = this.decodeSignedMsgOrderParamsMessage(borshBuf, isDelegateSigner);
3678
- if (signedMessage.builderFeeTenthBps !== null &&
3679
- signedMessage.builderIdx !== null) {
3680
- remainingAccounts.push({
3681
- pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3682
- isWritable: true,
3683
- isSigner: false,
3684
- });
3920
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(takerInfo.takerUserAccount.authority, (0, builder_1.hasBuilderParams)(signedMessage), takerEscrow);
3921
+ if (takerEscrowMeta) {
3922
+ remainingAccounts.push(takerEscrowMeta);
3685
3923
  }
3686
3924
  const placeAndMakeIx = await this.program.instruction.placeAndMakeSignedMsgPerpOrder(orderParams, signedMsgOrderUuid, {
3687
3925
  accounts: {
@@ -3701,19 +3939,19 @@ class VelocityClient {
3701
3939
  placeAndMakeIx,
3702
3940
  ];
3703
3941
  }
3704
- async preparePlaceAndTakeSpotOrder(_orderParams, _fulfillmentConfig, _makerInfo, _referrerInfo, _txParams, _subAccountId) {
3942
+ async preparePlaceAndTakeSpotOrder(_orderParams, _fulfillmentConfig, _makerInfo, _txParams, _subAccountId) {
3705
3943
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
3706
3944
  }
3707
- async placeAndTakeSpotOrder(_orderParams, _fulfillmentConfig, _makerInfo, _referrerInfo, _txParams, _subAccountId) {
3945
+ async placeAndTakeSpotOrder(_orderParams, _fulfillmentConfig, _makerInfo, _txParams, _subAccountId) {
3708
3946
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
3709
3947
  }
3710
- async getPlaceAndTakeSpotOrderIx(_orderParams, _fulfillmentConfig, _makerInfo, _referrerInfo, _subAccountId) {
3948
+ async getPlaceAndTakeSpotOrderIx(_orderParams, _fulfillmentConfig, _makerInfo, _subAccountId) {
3711
3949
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
3712
3950
  }
3713
- async placeAndMakeSpotOrder(_orderParams, _takerInfo, _fulfillmentConfig, _referrerInfo, _txParams, _subAccountId) {
3951
+ async placeAndMakeSpotOrder(_orderParams, _takerInfo, _fulfillmentConfig, _txParams, _subAccountId) {
3714
3952
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
3715
3953
  }
3716
- async getPlaceAndMakeSpotOrderIx(_orderParams, _takerInfo, _fulfillmentConfig, _referrerInfo, _subAccountId) {
3954
+ async getPlaceAndMakeSpotOrderIx(_orderParams, _takerInfo, _fulfillmentConfig, _subAccountId) {
3717
3955
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
3718
3956
  }
3719
3957
  /**
@@ -3731,7 +3969,7 @@ class VelocityClient {
3731
3969
  baseAssetAmount: userPosition.baseAssetAmount.abs(),
3732
3970
  reduceOnly: true,
3733
3971
  price: limitPrice,
3734
- }, undefined, undefined, undefined, undefined, undefined, subAccountId);
3972
+ }, undefined, undefined, undefined, undefined, subAccountId);
3735
3973
  }
3736
3974
  /**
3737
3975
  * Modifies an open order by closing it and replacing it with a new order.
@@ -3796,9 +4034,13 @@ class VelocityClient {
3796
4034
  * @returns
3797
4035
  */
3798
4036
  async getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }, subAccountId, overrides) {
3799
- var _a, _b, _c, _d, _e, _f, _g;
4037
+ var _a, _b, _c, _d, _e;
3800
4038
  const userPubKey = (_b = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.user) === null || _a === void 0 ? void 0 : _a.getUserAccountPublicKey()) !== null && _b !== void 0 ? _b : (await this.getUserAccountPublicKey(subAccountId));
3801
- const userAccount = (_d = (_c = overrides === null || overrides === void 0 ? void 0 : overrides.user) === null || _c === void 0 ? void 0 : _c.getUserAccount()) !== null && _d !== void 0 ? _d : this.getUserAccount(subAccountId);
4039
+ const overrideUserAccount = (_c = overrides === null || overrides === void 0 ? void 0 : overrides.user) === null || _c === void 0 ? void 0 : _c.getUserAccount();
4040
+ if ((overrides === null || overrides === void 0 ? void 0 : overrides.user) && !overrideUserAccount) {
4041
+ throw new Error('modifyOrder: override user account is not loaded');
4042
+ }
4043
+ const userAccount = overrideUserAccount !== null && overrideUserAccount !== void 0 ? overrideUserAccount : this.getUserAccountOrThrow(subAccountId);
3802
4044
  const remainingAccounts = this.getRemainingAccounts({
3803
4045
  userAccounts: [userAccount],
3804
4046
  useMarketLastSlotCache: true,
@@ -3819,7 +4061,7 @@ class VelocityClient {
3819
4061
  policy: policy || null,
3820
4062
  maxTs: maxTs || null,
3821
4063
  };
3822
- const authority = (_g = (_e = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _e !== void 0 ? _e : (_f = overrides === null || overrides === void 0 ? void 0 : overrides.user) === null || _f === void 0 ? void 0 : _f.getUserAccount().authority) !== null && _g !== void 0 ? _g : this.wallet.publicKey;
4064
+ const authority = (_e = (_d = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _d !== void 0 ? _d : overrideUserAccount === null || overrideUserAccount === void 0 ? void 0 : overrideUserAccount.authority) !== null && _e !== void 0 ? _e : this.wallet.publicKey;
3823
4065
  return await VelocityCore_1.VelocityCore.buildModifyOrderInstruction({
3824
4066
  program: this.program,
3825
4067
  orderId,
@@ -3856,7 +4098,7 @@ class VelocityClient {
3856
4098
  async getModifyOrderByUserIdIx({ userOrderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }, subAccountId) {
3857
4099
  const user = await this.getUserAccountPublicKey(subAccountId);
3858
4100
  const remainingAccounts = this.getRemainingAccounts({
3859
- userAccounts: [this.getUserAccount(subAccountId)],
4101
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
3860
4102
  useMarketLastSlotCache: true,
3861
4103
  });
3862
4104
  const orderParams = {
@@ -3894,7 +4136,7 @@ class VelocityClient {
3894
4136
  : marketIndexes;
3895
4137
  if (filterInvalidMarkets) {
3896
4138
  for (const marketIndex of marketIndexes) {
3897
- const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
4139
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
3898
4140
  const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
3899
4141
  const stateAccountAndSlot = this.accountSubscriber.getStateAccountAndSlot();
3900
4142
  const oracleGuardRails = stateAccountAndSlot.data.oracleGuardRails;
@@ -3968,7 +4210,7 @@ class VelocityClient {
3968
4210
  isWritable: true,
3969
4211
  });
3970
4212
  }
3971
- if (!escrow.referrer.equals(web3_js_1.PublicKey.default)) {
4213
+ if ((0, builder_1.escrowHasReferrer)(escrow)) {
3972
4214
  this.addBuilderToRemainingAccounts([escrow.referrer], remainingAccounts);
3973
4215
  }
3974
4216
  }
@@ -4082,7 +4324,7 @@ class VelocityClient {
4082
4324
  });
4083
4325
  }
4084
4326
  // Add referrer's User and RevenueShare accounts
4085
- if (!escrow.referrer.equals(web3_js_1.PublicKey.default)) {
4327
+ if ((0, builder_1.escrowHasReferrer)(escrow)) {
4086
4328
  this.addBuilderToRemainingAccounts([escrow.referrer], remainingAccounts);
4087
4329
  }
4088
4330
  }
@@ -4134,7 +4376,7 @@ class VelocityClient {
4134
4376
  }
4135
4377
  async liquidatePerp(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, txParams, liquidatorSubAccountId) {
4136
4378
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
4137
- this.perpMarketLastSlotCache.set(marketIndex, slot);
4379
+ this.cachePerpMarketSlot(slot, marketIndex);
4138
4380
  return txSig;
4139
4381
  }
4140
4382
  async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId) {
@@ -4142,7 +4384,10 @@ class VelocityClient {
4142
4384
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4143
4385
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4144
4386
  const remainingAccounts = this.getRemainingAccounts({
4145
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4387
+ userAccounts: [
4388
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4389
+ userAccount,
4390
+ ],
4146
4391
  useMarketLastSlotCache: true,
4147
4392
  writablePerpMarketIndexes: [marketIndex],
4148
4393
  });
@@ -4162,7 +4407,7 @@ class VelocityClient {
4162
4407
  }
4163
4408
  async liquidatePerpWithFill(userAccountPublicKey, userAccount, marketIndex, makerInfos, txParams, liquidatorSubAccountId) {
4164
4409
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId), txParams), [], this.opts);
4165
- this.perpMarketLastSlotCache.set(marketIndex, slot);
4410
+ this.cachePerpMarketSlot(slot, marketIndex);
4166
4411
  return txSig;
4167
4412
  }
4168
4413
  async getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId) {
@@ -4202,8 +4447,7 @@ class VelocityClient {
4202
4447
  }
4203
4448
  async liquidateSpot(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
4204
4449
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
4205
- this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
4206
- this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
4450
+ this.cacheSpotMarketSlot(slot, assetMarketIndex, liabilityMarketIndex);
4207
4451
  return txSig;
4208
4452
  }
4209
4453
  async getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
@@ -4211,7 +4455,10 @@ class VelocityClient {
4211
4455
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4212
4456
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4213
4457
  const remainingAccounts = this.getRemainingAccounts({
4214
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4458
+ userAccounts: [
4459
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4460
+ userAccount,
4461
+ ],
4215
4462
  useMarketLastSlotCache: true,
4216
4463
  writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
4217
4464
  });
@@ -4227,9 +4474,9 @@ class VelocityClient {
4227
4474
  remainingAccounts,
4228
4475
  });
4229
4476
  }
4230
- async getJupiterLiquidateSpotWithSwapIxV6({ jupiterClient, liabilityMarketIndex, assetMarketIndex, swapAmount, assetTokenAccount, liabilityTokenAccount, slippageBps, swapMode, onlyDirectRoutes, quote, userAccount, userAccountPublicKey, userStatsAccountPublicKey, liquidatorSubAccountId, maxAccounts, }) {
4231
- const liabilityMarket = this.getSpotMarketAccount(liabilityMarketIndex);
4232
- const assetMarket = this.getSpotMarketAccount(assetMarketIndex);
4477
+ async getJupiterLiquidateSpotWithSwapIxV6({ jupiterClient, liabilityMarketIndex, assetMarketIndex, swapAmount, assetTokenAccount, liabilityTokenAccount, slippageBps, swapMode, onlyDirectRoutes, quote, userAccount, userAccountPublicKey, liquidatorSubAccountId, maxAccounts, }) {
4478
+ const liabilityMarket = this.getSpotMarketAccountOrThrow(liabilityMarketIndex);
4479
+ const assetMarket = this.getSpotMarketAccountOrThrow(assetMarketIndex);
4233
4480
  if (!quote) {
4234
4481
  const fetchedQuote = await jupiterClient.getQuote({
4235
4482
  inputMint: assetMarket.mint,
@@ -4278,7 +4525,6 @@ class VelocityClient {
4278
4525
  liabilityTokenAccount,
4279
4526
  userAccount,
4280
4527
  userAccountPublicKey,
4281
- userStatsAccountPublicKey,
4282
4528
  liquidatorSubAccountId,
4283
4529
  });
4284
4530
  const ixs = [
@@ -4290,7 +4536,7 @@ class VelocityClient {
4290
4536
  return { ixs, lookupTables };
4291
4537
  }
4292
4538
  /**
4293
- * Get the drift liquidate_spot_with_swap instructions
4539
+ * Get the velocity liquidate_spot_with_swap instructions
4294
4540
  *
4295
4541
  * @param liabilityMarketIndex the market index of the token you're buying
4296
4542
  * @param assetMarketIndex the market index of the token you're selling
@@ -4299,19 +4545,17 @@ class VelocityClient {
4299
4545
  * @param liabilityTokenAccount the token account to receive the tokens being bought
4300
4546
  * @param userAccount
4301
4547
  * @param userAccountPublicKey
4302
- * @param userStatsAccountPublicKey
4303
4548
  */
4304
- async getLiquidateSpotWithSwapIx({ liabilityMarketIndex, assetMarketIndex, swapAmount: swapAmount, assetTokenAccount, liabilityTokenAccount, userAccount, userAccountPublicKey, userStatsAccountPublicKey, liquidatorSubAccountId, }) {
4549
+ async getLiquidateSpotWithSwapIx({ liabilityMarketIndex, assetMarketIndex, swapAmount: swapAmount, assetTokenAccount, liabilityTokenAccount, userAccount, userAccountPublicKey, liquidatorSubAccountId, }) {
4305
4550
  const liquidatorAccountPublicKey = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4306
- const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4307
4551
  const userAccounts = [userAccount];
4308
4552
  const remainingAccounts = this.getRemainingAccounts({
4309
4553
  userAccounts,
4310
4554
  writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
4311
4555
  readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
4312
4556
  });
4313
- const liabilitySpotMarket = this.getSpotMarketAccount(liabilityMarketIndex);
4314
- const assetSpotMarket = this.getSpotMarketAccount(assetMarketIndex);
4557
+ const liabilitySpotMarket = this.getSpotMarketAccountOrThrow(liabilityMarketIndex);
4558
+ const assetSpotMarket = this.getSpotMarketAccountOrThrow(assetMarketIndex);
4315
4559
  const liabilityTokenProgram = this.getTokenProgramForSpotMarket(liabilitySpotMarket);
4316
4560
  const assetTokenProgram = this.getTokenProgramForSpotMarket(assetSpotMarket);
4317
4561
  if (!liabilityTokenProgram.equals(assetTokenProgram)) {
@@ -4344,16 +4588,14 @@ class VelocityClient {
4344
4588
  accounts: {
4345
4589
  state: await this.getStatePublicKey(),
4346
4590
  user: userAccountPublicKey,
4347
- userStats: userStatsAccountPublicKey,
4348
4591
  liquidator: liquidatorAccountPublicKey,
4349
- liquidatorStats: liquidatorStatsPublicKey,
4350
4592
  authority: this.wallet.publicKey,
4351
4593
  liabilitySpotMarketVault: liabilitySpotMarket.vault,
4352
4594
  assetSpotMarketVault: assetSpotMarket.vault,
4353
4595
  assetTokenAccount: assetTokenAccount,
4354
4596
  liabilityTokenAccount: liabilityTokenAccount,
4355
4597
  tokenProgram: assetTokenProgram,
4356
- driftSigner: this.getStateAccount().signer,
4598
+ velocitySigner: this.getStateAccount().signer,
4357
4599
  instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
4358
4600
  },
4359
4601
  remainingAccounts,
@@ -4362,74 +4604,14 @@ class VelocityClient {
4362
4604
  accounts: {
4363
4605
  state: await this.getStatePublicKey(),
4364
4606
  user: userAccountPublicKey,
4365
- userStats: userStatsAccountPublicKey,
4366
4607
  liquidator: liquidatorAccountPublicKey,
4367
- liquidatorStats: liquidatorStatsPublicKey,
4368
4608
  authority: this.wallet.publicKey,
4369
4609
  liabilitySpotMarketVault: liabilitySpotMarket.vault,
4370
4610
  assetSpotMarketVault: assetSpotMarket.vault,
4371
4611
  assetTokenAccount: assetTokenAccount,
4372
4612
  liabilityTokenAccount: liabilityTokenAccount,
4373
4613
  tokenProgram: assetTokenProgram,
4374
- driftSigner: this.getStateAccount().signer,
4375
- instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
4376
- },
4377
- remainingAccounts,
4378
- });
4379
- return { beginSwapIx, endSwapIx };
4380
- }
4381
- async getInsuranceFundSwapIx({ inMarketIndex, outMarketIndex, amountIn, inTokenAccount, outTokenAccount, }) {
4382
- const remainingAccounts = await this.getRemainingAccounts({
4383
- userAccounts: [],
4384
- writableSpotMarketIndexes: [inMarketIndex, outMarketIndex],
4385
- });
4386
- const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
4387
- const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
4388
- if (this.isToken2022(inSpotMarket) || this.isToken2022(outSpotMarket)) {
4389
- remainingAccounts.push({
4390
- pubkey: inSpotMarket.mint,
4391
- isWritable: false,
4392
- isSigner: false,
4393
- });
4394
- remainingAccounts.push({
4395
- pubkey: outSpotMarket.mint,
4396
- isWritable: false,
4397
- isSigner: false,
4398
- });
4399
- if (this.isTransferHook(inSpotMarket)) {
4400
- this.addExtraAccountMetasToRemainingAccounts(inSpotMarket.mint, remainingAccounts);
4401
- }
4402
- if (this.isTransferHook(outSpotMarket)) {
4403
- this.addExtraAccountMetasToRemainingAccounts(outSpotMarket.mint, remainingAccounts);
4404
- }
4405
- }
4406
- const ifRebalanceConfig = (0, pda_1.getIfRebalanceConfigPublicKey)(this.program.programId, inMarketIndex, outMarketIndex);
4407
- const beginSwapIx = await this.program.instruction.beginInsuranceFundSwap(inMarketIndex, outMarketIndex, amountIn, {
4408
- accounts: {
4409
- state: await this.getStatePublicKey(),
4410
- authority: this.wallet.publicKey,
4411
- outInsuranceFundVault: outSpotMarket.insuranceFund.vault,
4412
- inInsuranceFundVault: inSpotMarket.insuranceFund.vault,
4413
- outTokenAccount,
4414
- inTokenAccount,
4415
- ifRebalanceConfig: ifRebalanceConfig,
4416
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
4417
- driftSigner: this.getStateAccount().signer,
4418
- instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
4419
- },
4420
- remainingAccounts,
4421
- });
4422
- const endSwapIx = await this.program.instruction.endInsuranceFundSwap(inMarketIndex, outMarketIndex, {
4423
- accounts: {
4424
- state: await this.getStatePublicKey(),
4425
- authority: this.wallet.publicKey,
4426
- outInsuranceFundVault: outSpotMarket.insuranceFund.vault,
4427
- inInsuranceFundVault: inSpotMarket.insuranceFund.vault,
4428
- outTokenAccount,
4429
- inTokenAccount,
4430
- ifRebalanceConfig: ifRebalanceConfig,
4431
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
4432
- driftSigner: this.getStateAccount().signer,
4614
+ velocitySigner: this.getStateAccount().signer,
4433
4615
  instructions: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
4434
4616
  },
4435
4617
  remainingAccounts,
@@ -4438,8 +4620,8 @@ class VelocityClient {
4438
4620
  }
4439
4621
  async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
4440
4622
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
4441
- this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
4442
- this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
4623
+ this.cachePerpMarketSlot(slot, perpMarketIndex);
4624
+ this.cacheSpotMarketSlot(slot, liabilityMarketIndex);
4443
4625
  return txSig;
4444
4626
  }
4445
4627
  async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
@@ -4447,7 +4629,10 @@ class VelocityClient {
4447
4629
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4448
4630
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4449
4631
  const remainingAccounts = this.getRemainingAccounts({
4450
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4632
+ userAccounts: [
4633
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4634
+ userAccount,
4635
+ ],
4451
4636
  writablePerpMarketIndexes: [perpMarketIndex],
4452
4637
  writableSpotMarketIndexes: [liabilityMarketIndex],
4453
4638
  });
@@ -4465,8 +4650,8 @@ class VelocityClient {
4465
4650
  }
4466
4651
  async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, txParams, liquidatorSubAccountId) {
4467
4652
  const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
4468
- this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
4469
- this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
4653
+ this.cachePerpMarketSlot(slot, perpMarketIndex);
4654
+ this.cacheSpotMarketSlot(slot, assetMarketIndex);
4470
4655
  return txSig;
4471
4656
  }
4472
4657
  async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId) {
@@ -4474,7 +4659,10 @@ class VelocityClient {
4474
4659
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4475
4660
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4476
4661
  const remainingAccounts = this.getRemainingAccounts({
4477
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4662
+ userAccounts: [
4663
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4664
+ userAccount,
4665
+ ],
4478
4666
  writablePerpMarketIndexes: [perpMarketIndex],
4479
4667
  writableSpotMarketIndexes: [assetMarketIndex],
4480
4668
  });
@@ -4499,7 +4687,10 @@ class VelocityClient {
4499
4687
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4500
4688
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4501
4689
  const remainingAccounts = this.getRemainingAccounts({
4502
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4690
+ userAccounts: [
4691
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4692
+ userAccount,
4693
+ ],
4503
4694
  writablePerpMarketIndexes: [marketIndex],
4504
4695
  writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
4505
4696
  });
@@ -4514,7 +4705,7 @@ class VelocityClient {
4514
4705
  liquidatorStats: liquidatorStatsPublicKey,
4515
4706
  spotMarketVault: spotMarket.vault,
4516
4707
  insuranceFundVault: spotMarket.insuranceFund.vault,
4517
- driftSigner: this.getSignerPublicKey(),
4708
+ velocitySigner: this.getSignerPublicKey(),
4518
4709
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
4519
4710
  },
4520
4711
  remainingAccounts: remainingAccounts,
@@ -4529,10 +4720,13 @@ class VelocityClient {
4529
4720
  const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
4530
4721
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
4531
4722
  const remainingAccounts = this.getRemainingAccounts({
4532
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
4723
+ userAccounts: [
4724
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
4725
+ userAccount,
4726
+ ],
4533
4727
  writableSpotMarketIndexes: [marketIndex],
4534
4728
  });
4535
- const spotMarket = this.getSpotMarketAccount(marketIndex);
4729
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
4536
4730
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
4537
4731
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
4538
4732
  if (this.isTransferHook(spotMarket)) {
@@ -4548,7 +4742,7 @@ class VelocityClient {
4548
4742
  liquidator,
4549
4743
  spotMarketVault: spotMarket.vault,
4550
4744
  insuranceFundVault: spotMarket.insuranceFund.vault,
4551
- driftSigner: this.getSignerPublicKey(),
4745
+ velocitySigner: this.getSignerPublicKey(),
4552
4746
  tokenProgram: tokenProgramId,
4553
4747
  },
4554
4748
  remainingAccounts: remainingAccounts,
@@ -4573,15 +4767,15 @@ class VelocityClient {
4573
4767
  return txSig;
4574
4768
  }
4575
4769
  async getUpdatePrelaunchOracleIx(perpMarketIndex) {
4576
- const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
4577
- if (!(0, types_1.isVariant)(perpMarket.amm.oracleSource, 'prelaunch')) {
4578
- throw new Error(`Wrong oracle source ${perpMarket.amm.oracleSource}`);
4770
+ const perpMarket = this.getPerpMarketAccountOrThrow(perpMarketIndex);
4771
+ if (!(0, types_1.isVariant)(perpMarket.oracleSource, 'prelaunch')) {
4772
+ throw new Error(`Wrong oracle source ${perpMarket.oracleSource}`);
4579
4773
  }
4580
4774
  return await this.program.instruction.updatePrelaunchOracle({
4581
4775
  accounts: {
4582
4776
  state: await this.getStatePublicKey(),
4583
4777
  perpMarket: perpMarket.pubkey,
4584
- oracle: perpMarket.amm.oracle,
4778
+ oracle: perpMarket.oracle,
4585
4779
  },
4586
4780
  });
4587
4781
  }
@@ -4590,7 +4784,7 @@ class VelocityClient {
4590
4784
  return txSig;
4591
4785
  }
4592
4786
  async getUpdatePerpBidAskTwapIx(perpMarketIndex, makers) {
4593
- const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
4787
+ const perpMarket = this.getPerpMarketAccountOrThrow(perpMarketIndex);
4594
4788
  const remainingAccounts = [];
4595
4789
  for (const [maker, makerStats] of makers) {
4596
4790
  remainingAccounts.push({
@@ -4608,7 +4802,7 @@ class VelocityClient {
4608
4802
  accounts: {
4609
4803
  state: await this.getStatePublicKey(),
4610
4804
  perpMarket: perpMarket.pubkey,
4611
- oracle: perpMarket.amm.oracle,
4805
+ oracle: perpMarket.oracle,
4612
4806
  authority: this.wallet.publicKey,
4613
4807
  keeperStats: this.getUserStatsAccountPublicKey(),
4614
4808
  },
@@ -4643,44 +4837,49 @@ class VelocityClient {
4643
4837
  this.eventEmitter.emit(eventName, data);
4644
4838
  }
4645
4839
  getOracleDataForPerpMarket(marketIndex) {
4646
- return this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(marketIndex).data;
4840
+ const oraclePriceDataAndSlot = this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(marketIndex);
4841
+ if (!oraclePriceDataAndSlot) {
4842
+ throw new Error(`No oracle price data for perp market ${marketIndex}`);
4843
+ }
4844
+ return oraclePriceDataAndSlot.data;
4647
4845
  }
4648
4846
  getMMOracleDataForPerpMarket(marketIndex) {
4649
- const perpMarket = this.getPerpMarketAccount(marketIndex);
4847
+ const perpMarket = this.getPerpMarketAccountOrThrow(marketIndex);
4650
4848
  const oracleData = this.getOracleDataForPerpMarket(marketIndex);
4651
4849
  const stateAccountAndSlot = this.accountSubscriber.getStateAccountAndSlot();
4652
- const isMMOracleActive = !perpMarket.amm.mmOracleSlot.eq(numericConstants_1.ZERO);
4653
- const pctDiff = perpMarket.amm.mmOraclePrice
4850
+ const isMMOracleActive = !perpMarket.marketStats.mmOracleSlot.eq(numericConstants_1.ZERO);
4851
+ const pctDiff = perpMarket.marketStats.mmOraclePrice
4654
4852
  .sub(oracleData.price)
4655
4853
  .abs()
4656
4854
  .mul(numericConstants_1.PERCENTAGE_PRECISION)
4657
4855
  .div(anchor_1.BN.max(oracleData.price, numericConstants_1.ONE));
4658
- const mmOracleSequenceId = perpMarket.amm.mmOracleSequenceId;
4856
+ const mmOracleSequenceId = perpMarket.marketStats.mmOracleSequenceId;
4659
4857
  // Do slot check for recency if sequence ids are zero or they're too divergent
4660
4858
  const doSlotCheckForRecency = oracleData.sequenceId == null ||
4661
4859
  oracleData.sequenceId.eq(numericConstants_1.ZERO) ||
4662
4860
  mmOracleSequenceId.eq(numericConstants_1.ZERO) ||
4663
4861
  oracleData.sequenceId
4664
- .sub(perpMarket.amm.mmOracleSequenceId)
4862
+ .sub(perpMarket.marketStats.mmOracleSequenceId)
4665
4863
  .abs()
4666
4864
  .gt(oracleData.sequenceId.div(new anchor_1.BN(10000)));
4667
4865
  let isExchangeOracleMoreRecent = true;
4668
4866
  if (doSlotCheckForRecency &&
4669
- oracleData.slot <= perpMarket.amm.mmOracleSlot) {
4867
+ oracleData.slot.lte(perpMarket.marketStats.mmOracleSlot)) {
4670
4868
  isExchangeOracleMoreRecent = false;
4671
4869
  }
4672
4870
  else if (!doSlotCheckForRecency &&
4673
- oracleData.sequenceId < mmOracleSequenceId) {
4871
+ oracleData.sequenceId != null &&
4872
+ oracleData.sequenceId.lt(mmOracleSequenceId)) {
4674
4873
  isExchangeOracleMoreRecent = false;
4675
4874
  }
4676
- const conf = (0, utils_3.getOracleConfidenceFromMMOracleData)(perpMarket.amm.mmOraclePrice, oracleData);
4677
- if ((0, oracles_1.isOracleTooDivergent)(perpMarket.amm, {
4678
- price: perpMarket.amm.mmOraclePrice,
4679
- slot: perpMarket.amm.mmOracleSlot,
4875
+ const conf = (0, utils_3.getOracleConfidenceFromMMOracleData)(perpMarket.marketStats.mmOraclePrice, oracleData);
4876
+ if ((0, oracles_1.isOracleTooDivergent)(perpMarket.marketStats, {
4877
+ price: perpMarket.marketStats.mmOraclePrice,
4878
+ slot: perpMarket.marketStats.mmOracleSlot,
4680
4879
  confidence: conf,
4681
4880
  hasSufficientNumberOfDataPoints: true,
4682
4881
  }, stateAccountAndSlot.data.oracleGuardRails) ||
4683
- perpMarket.amm.mmOraclePrice.eq(numericConstants_1.ZERO) ||
4882
+ perpMarket.marketStats.mmOraclePrice.eq(numericConstants_1.ZERO) ||
4684
4883
  isExchangeOracleMoreRecent ||
4685
4884
  pctDiff.gt(numericConstants_1.PERCENTAGE_PRECISION.divn(100)) // 1% threshold
4686
4885
  ) {
@@ -4688,8 +4887,8 @@ class VelocityClient {
4688
4887
  }
4689
4888
  else {
4690
4889
  return {
4691
- price: perpMarket.amm.mmOraclePrice,
4692
- slot: perpMarket.amm.mmOracleSlot,
4890
+ price: perpMarket.marketStats.mmOraclePrice,
4891
+ slot: perpMarket.marketStats.mmOracleSlot,
4693
4892
  confidence: conf,
4694
4893
  hasSufficientNumberOfDataPoints: true,
4695
4894
  isMMOracleActive,
@@ -4697,7 +4896,11 @@ class VelocityClient {
4697
4896
  }
4698
4897
  }
4699
4898
  getOracleDataForSpotMarket(marketIndex) {
4700
- return this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(marketIndex).data;
4899
+ const oraclePriceDataAndSlot = this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(marketIndex);
4900
+ if (!oraclePriceDataAndSlot) {
4901
+ throw new Error(`No oracle price data for spot market ${marketIndex}`);
4902
+ }
4903
+ return oraclePriceDataAndSlot.data;
4701
4904
  }
4702
4905
  async initializeInsuranceFundStake(marketIndex, txParams) {
4703
4906
  const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getInitializeInsuranceFundStakeIx(marketIndex), txParams), [], this.opts);
@@ -4707,7 +4910,7 @@ class VelocityClient {
4707
4910
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
4708
4911
  const accounts = {
4709
4912
  insuranceFundStake: ifStakeAccountPublicKey,
4710
- spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
4913
+ spotMarket: this.getSpotMarketAccountOrThrow(marketIndex).pubkey,
4711
4914
  userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.wallet.publicKey // only allow payer to initialize own insurance fund stake account
4712
4915
  ),
4713
4916
  authority: this.wallet.publicKey,
@@ -4721,7 +4924,7 @@ class VelocityClient {
4721
4924
  });
4722
4925
  }
4723
4926
  async getAddInsuranceFundStakeIx(marketIndex, amount, collateralAccountPublicKey) {
4724
- const spotMarket = this.getSpotMarketAccount(marketIndex);
4927
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
4725
4928
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
4726
4929
  const remainingAccounts = [];
4727
4930
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
@@ -4739,7 +4942,7 @@ class VelocityClient {
4739
4942
  authority: this.wallet.publicKey,
4740
4943
  spotMarketVault: spotMarket.vault,
4741
4944
  insuranceFundVault: spotMarket.insuranceFund.vault,
4742
- driftSigner: this.getSignerPublicKey(),
4945
+ velocitySigner: this.getSignerPublicKey(),
4743
4946
  userTokenAccount: collateralAccountPublicKey,
4744
4947
  tokenProgram,
4745
4948
  },
@@ -4768,7 +4971,7 @@ class VelocityClient {
4768
4971
  */
4769
4972
  async getAddInsuranceFundStakeIxs({ marketIndex, amount, collateralAccountPublicKey, initializeStakeAccount, fromSubaccount, }) {
4770
4973
  const addIfStakeIxs = [];
4771
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
4974
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
4772
4975
  const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
4773
4976
  const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
4774
4977
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
@@ -4806,7 +5009,7 @@ class VelocityClient {
4806
5009
  return addIfStakeIxs;
4807
5010
  }
4808
5011
  async requestRemoveInsuranceFundStake(marketIndex, amount, txParams) {
4809
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
5012
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
4810
5013
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
4811
5014
  const ix = await this.program.instruction.requestRemoveInsuranceFundStake(marketIndex, amount, {
4812
5015
  accounts: {
@@ -4824,7 +5027,7 @@ class VelocityClient {
4824
5027
  return txSig;
4825
5028
  }
4826
5029
  async cancelRequestRemoveInsuranceFundStake(marketIndex, txParams) {
4827
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
5030
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
4828
5031
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
4829
5032
  const ix = await this.program.instruction.cancelRequestRemoveInsuranceFundStake(marketIndex, {
4830
5033
  accounts: {
@@ -4843,7 +5046,7 @@ class VelocityClient {
4843
5046
  }
4844
5047
  async removeInsuranceFundStake(marketIndex, collateralAccountPublicKey, txParams) {
4845
5048
  const removeIfStakeIxs = [];
4846
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
5049
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
4847
5050
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
4848
5051
  const additionalSigners = [];
4849
5052
  const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
@@ -4880,7 +5083,7 @@ class VelocityClient {
4880
5083
  ),
4881
5084
  authority: this.wallet.publicKey,
4882
5085
  insuranceFundVault: spotMarketAccount.insuranceFund.vault,
4883
- driftSigner: this.getSignerPublicKey(),
5086
+ velocitySigner: this.getSignerPublicKey(),
4884
5087
  userTokenAccount: tokenAccount,
4885
5088
  tokenProgram,
4886
5089
  },
@@ -4902,7 +5105,7 @@ class VelocityClient {
4902
5105
  }
4903
5106
  async getUpdateUserQuoteAssetInsuranceStakeIx(authority) {
4904
5107
  const marketIndex = numericConstants_1.QUOTE_SPOT_MARKET_INDEX;
4905
- const spotMarket = this.getSpotMarketAccount(marketIndex);
5108
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
4906
5109
  const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
4907
5110
  const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
4908
5111
  const ix = this.program.instruction.updateUserQuoteAssetInsuranceStake({
@@ -4917,36 +5120,13 @@ class VelocityClient {
4917
5120
  });
4918
5121
  return ix;
4919
5122
  }
4920
- async updateUserGovTokenInsuranceStake(authority, txParams) {
4921
- const ix = await this.getUpdateUserGovTokenInsuranceStakeIx(authority);
4922
- const tx = await this.buildTransaction(ix, txParams);
4923
- const { txSig } = await this.sendTransaction(tx, [], this.opts);
4924
- return txSig;
4925
- }
4926
- async getUpdateUserGovTokenInsuranceStakeIx(authority) {
4927
- const marketIndex = numericConstants_1.GOV_SPOT_MARKET_INDEX;
4928
- const spotMarket = this.getSpotMarketAccount(marketIndex);
4929
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
4930
- const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
4931
- const ix = this.program.instruction.updateUserGovTokenInsuranceStake({
4932
- accounts: {
4933
- state: await this.getStatePublicKey(),
4934
- spotMarket: spotMarket.pubkey,
4935
- insuranceFundStake: ifStakeAccountPublicKey,
4936
- userStats: userStatsPublicKey,
4937
- signer: this.wallet.publicKey,
4938
- insuranceFundVault: spotMarket.insuranceFund.vault,
4939
- },
4940
- });
4941
- return ix;
4942
- }
4943
5123
  async settleRevenueToInsuranceFund(spotMarketIndex, txParams) {
4944
5124
  const tx = await this.buildTransaction(await this.getSettleRevenueToInsuranceFundIx(spotMarketIndex), txParams);
4945
5125
  const { txSig } = await this.sendTransaction(tx, [], this.opts);
4946
5126
  return txSig;
4947
5127
  }
4948
5128
  async getSettleRevenueToInsuranceFundIx(spotMarketIndex) {
4949
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
5129
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
4950
5130
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
4951
5131
  const remainingAccounts = [];
4952
5132
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
@@ -4958,7 +5138,7 @@ class VelocityClient {
4958
5138
  state: await this.getStatePublicKey(),
4959
5139
  spotMarket: spotMarketAccount.pubkey,
4960
5140
  spotMarketVault: spotMarketAccount.vault,
4961
- driftSigner: this.getSignerPublicKey(),
5141
+ velocitySigner: this.getSignerPublicKey(),
4962
5142
  insuranceFundVault: spotMarketAccount.insuranceFund.vault,
4963
5143
  tokenProgram: tokenProgramId,
4964
5144
  },
@@ -4966,17 +5146,35 @@ class VelocityClient {
4966
5146
  });
4967
5147
  return ix;
4968
5148
  }
5149
+ async sweepPerpMarketFees(perpMarketIndex, txParams) {
5150
+ const tx = await this.buildTransaction(await this.getSweepPerpMarketFeesIx(perpMarketIndex), txParams);
5151
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
5152
+ return txSig;
5153
+ }
5154
+ async getSweepPerpMarketFeesIx(perpMarketIndex) {
5155
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
5156
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(perpMarketAccount.quoteSpotMarketIndex);
5157
+ const ix = await this.program.instruction.sweepPerpMarketFees(perpMarketIndex, {
5158
+ accounts: {
5159
+ state: await this.getStatePublicKey(),
5160
+ perpMarket: perpMarketAccount.pubkey,
5161
+ spotMarket: spotMarketAccount.pubkey,
5162
+ oracle: perpMarketAccount.oracle,
5163
+ },
5164
+ });
5165
+ return ix;
5166
+ }
4969
5167
  async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, txParams) {
4970
5168
  const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex), txParams), [], this.opts);
4971
5169
  return txSig;
4972
5170
  }
4973
5171
  async getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex) {
4974
5172
  const remainingAccounts = this.getRemainingAccounts({
4975
- userAccounts: [this.getUserAccount()],
5173
+ userAccounts: [],
4976
5174
  writablePerpMarketIndexes: [perpMarketIndex],
4977
5175
  writableSpotMarketIndexes: [spotMarketIndex],
4978
5176
  });
4979
- const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
5177
+ const spotMarket = this.getSpotMarketAccountOrThrow(spotMarketIndex);
4980
5178
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
4981
5179
  return await this.program.instruction.resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, {
4982
5180
  accounts: {
@@ -4984,14 +5182,14 @@ class VelocityClient {
4984
5182
  authority: this.wallet.publicKey,
4985
5183
  spotMarketVault: spotMarket.vault,
4986
5184
  insuranceFundVault: spotMarket.insuranceFund.vault,
4987
- driftSigner: this.getSignerPublicKey(),
5185
+ velocitySigner: this.getSignerPublicKey(),
4988
5186
  tokenProgram: tokenProgramId,
4989
5187
  },
4990
5188
  remainingAccounts: remainingAccounts,
4991
5189
  });
4992
5190
  }
4993
5191
  async getDepositIntoSpotMarketRevenuePoolIx(marketIndex, amount, userTokenAccountPublicKey) {
4994
- const spotMarket = await this.getSpotMarketAccount(marketIndex);
5192
+ const spotMarket = await this.getSpotMarketAccountOrThrow(marketIndex);
4995
5193
  const remainingAccounts = [];
4996
5194
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
4997
5195
  if (this.isTransferHook(spotMarket)) {
@@ -5011,7 +5209,7 @@ class VelocityClient {
5011
5209
  return ix;
5012
5210
  }
5013
5211
  /**
5014
- * This ix will donate your funds to drift revenue pool. It does not deposit into your user account
5212
+ * This ix will donate your funds to velocity revenue pool. It does not deposit into your user account
5015
5213
  * @param marketIndex
5016
5214
  * @param amount
5017
5215
  * @param userTokenAccountPublicKey
@@ -5025,11 +5223,11 @@ class VelocityClient {
5025
5223
  }
5026
5224
  getPerpMarketExtendedInfo(marketIndex) {
5027
5225
  var _a, _b;
5028
- const marketAccount = this.getPerpMarketAccount(marketIndex);
5029
- const quoteAccount = this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
5226
+ const marketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
5227
+ const quoteAccount = this.getSpotMarketAccountOrThrow(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
5030
5228
  const extendedInfo = {
5031
5229
  marketIndex,
5032
- minOrderSize: (_a = marketAccount.amm) === null || _a === void 0 ? void 0 : _a.minOrderSize,
5230
+ minOrderSize: (_a = marketAccount.marketStats) === null || _a === void 0 ? void 0 : _a.minOrderSize,
5033
5231
  marginMaintenance: marketAccount.marginRatioMaintenance,
5034
5232
  pnlPoolValue: (0, spotBalance_1.getTokenAmount)((_b = marketAccount.pnlPool) === null || _b === void 0 ? void 0 : _b.scaledBalance, quoteAccount, types_1.SpotBalanceType.DEPOSIT),
5035
5233
  contractTier: marketAccount.contractTier,
@@ -5057,12 +5255,12 @@ class VelocityClient {
5057
5255
  let takerFee = feeTier.feeNumerator / feeTier.feeDenominator;
5058
5256
  let makerFee = feeTier.makerRebateNumerator / feeTier.makerRebateDenominator;
5059
5257
  if (marketIndex !== undefined) {
5060
- let marketAccount = null;
5258
+ let marketAccount;
5061
5259
  if ((0, types_1.isVariant)(marketType, 'perp')) {
5062
- marketAccount = this.getPerpMarketAccount(marketIndex);
5260
+ marketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
5063
5261
  }
5064
5262
  else {
5065
- marketAccount = this.getSpotMarketAccount(marketIndex);
5263
+ marketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
5066
5264
  }
5067
5265
  takerFee += (takerFee * marketAccount.feeAdjustment) / 100;
5068
5266
  makerFee += (makerFee * marketAccount.feeAdjustment) / 100;
@@ -5125,7 +5323,7 @@ class VelocityClient {
5125
5323
  return [verifyIx, ix];
5126
5324
  }
5127
5325
  async getPauseSpotMarketDepositWithdrawIx(spotMarketIndex) {
5128
- const spotMarket = await this.getSpotMarketAccount(spotMarketIndex);
5326
+ const spotMarket = await this.getSpotMarketAccountOrThrow(spotMarketIndex);
5129
5327
  return this.program.instruction.pauseSpotMarketDepositWithdraw({
5130
5328
  accounts: {
5131
5329
  state: await this.getStatePublicKey(),
@@ -5159,7 +5357,7 @@ class VelocityClient {
5159
5357
  programId: this.program.programId,
5160
5358
  keys: [
5161
5359
  {
5162
- pubkey: this.getPerpMarketAccount(marketIndex).pubkey,
5360
+ pubkey: this.getPerpMarketAccountOrThrow(marketIndex).pubkey,
5163
5361
  isWritable: true,
5164
5362
  isSigner: false,
5165
5363
  },
@@ -5202,7 +5400,7 @@ class VelocityClient {
5202
5400
  programId: this.program.programId,
5203
5401
  keys: [
5204
5402
  {
5205
- pubkey: this.getPerpMarketAccount(marketIndex).pubkey,
5403
+ pubkey: this.getPerpMarketAccountOrThrow(marketIndex).pubkey,
5206
5404
  isWritable: true,
5207
5405
  isSigner: false,
5208
5406
  },
@@ -5296,7 +5494,7 @@ class VelocityClient {
5296
5494
  state: await this.getStatePublicKey(),
5297
5495
  keeper: this.wallet.publicKey,
5298
5496
  ammCache: (0, pda_1.getAmmCachePublicKey)(this.program.programId),
5299
- quoteMarket: this.getSpotMarketAccount(0).pubkey,
5497
+ quoteMarket: this.getSpotMarketAccountOrThrow(0).pubkey,
5300
5498
  },
5301
5499
  remainingAccounts,
5302
5500
  });
@@ -5306,7 +5504,7 @@ class VelocityClient {
5306
5504
  return txSig;
5307
5505
  }
5308
5506
  async getUpdateConstituentOracleInfoIx(constituent) {
5309
- const spotMarket = this.getSpotMarketAccount(constituent.spotMarketIndex);
5507
+ const spotMarket = this.getSpotMarketAccountOrThrow(constituent.spotMarketIndex);
5310
5508
  return this.program.instruction.updateConstituentOracleInfo({
5311
5509
  accounts: {
5312
5510
  keeper: this.wallet.publicKey,
@@ -5328,12 +5526,12 @@ class VelocityClient {
5328
5526
  });
5329
5527
  const constituentInTokenAccount = (0, pda_1.getConstituentVaultPublicKey)(this.program.programId, lpPool, inMarketIndex);
5330
5528
  const constituentOutTokenAccount = (0, pda_1.getConstituentVaultPublicKey)(this.program.programId, lpPool, outMarketIndex);
5331
- const userInTokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(this.getSpotMarketAccount(inMarketIndex).mint, userAuthority);
5332
- const userOutTokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(this.getSpotMarketAccount(outMarketIndex).mint, userAuthority);
5529
+ const userInTokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(this.getSpotMarketAccountOrThrow(inMarketIndex).mint, userAuthority);
5530
+ const userOutTokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(this.getSpotMarketAccountOrThrow(outMarketIndex).mint, userAuthority);
5333
5531
  const inConstituent = (0, pda_1.getConstituentPublicKey)(this.program.programId, lpPool, inMarketIndex);
5334
5532
  const outConstituent = (0, pda_1.getConstituentPublicKey)(this.program.programId, lpPool, outMarketIndex);
5335
- const inMarketMint = this.getSpotMarketAccount(inMarketIndex).mint;
5336
- const outMarketMint = this.getSpotMarketAccount(outMarketIndex).mint;
5533
+ const inMarketMint = this.getSpotMarketAccountOrThrow(inMarketIndex).mint;
5534
+ const outMarketMint = this.getSpotMarketAccountOrThrow(outMarketIndex).mint;
5337
5535
  const constituentTargetBase = (0, pda_1.getConstituentTargetBasePublicKey)(this.program.programId, lpPool);
5338
5536
  return this.program.instruction.lpPoolSwap(inMarketIndex, outMarketIndex, inAmount, minOutAmount, {
5339
5537
  remainingAccounts,
@@ -5367,7 +5565,7 @@ class VelocityClient {
5367
5565
  return this.program.instruction.viewLpPoolSwapFees(inMarketIndex, outMarketIndex, inAmount, inTargetWeight, outTargetWeight, {
5368
5566
  remainingAccounts,
5369
5567
  accounts: {
5370
- driftSigner: this.getSignerPublicKey(),
5568
+ velocitySigner: this.getSignerPublicKey(),
5371
5569
  state: await this.getStatePublicKey(),
5372
5570
  lpPool,
5373
5571
  constituentTargetBase,
@@ -5405,7 +5603,7 @@ class VelocityClient {
5405
5603
  userAccounts: [],
5406
5604
  writableSpotMarketIndexes: [inMarketIndex],
5407
5605
  });
5408
- const spotMarket = this.getSpotMarketAccount(inMarketIndex);
5606
+ const spotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5409
5607
  const inMarketMint = spotMarket.mint;
5410
5608
  const isSolMarket = inMarketMint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
5411
5609
  let wSolTokenAccount;
@@ -5467,7 +5665,7 @@ class VelocityClient {
5467
5665
  userAccounts: [],
5468
5666
  readableSpotMarketIndexes: [inMarketIndex],
5469
5667
  });
5470
- const spotMarket = this.getSpotMarketAccount(inMarketIndex);
5668
+ const spotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5471
5669
  const inMarketMint = spotMarket.mint;
5472
5670
  const inConstituent = (0, pda_1.getConstituentPublicKey)(this.program.programId, lpPool.pubkey, inMarketIndex);
5473
5671
  const lpMint = lpPool.mint;
@@ -5500,7 +5698,7 @@ class VelocityClient {
5500
5698
  userAccounts: [],
5501
5699
  writableSpotMarketIndexes: [outMarketIndex],
5502
5700
  });
5503
- const spotMarket = this.getSpotMarketAccount(outMarketIndex);
5701
+ const spotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
5504
5702
  const outMarketMint = spotMarket.mint;
5505
5703
  const outConstituent = (0, pda_1.getConstituentPublicKey)(this.program.programId, lpPool.pubkey, outMarketIndex);
5506
5704
  if (outMarketMint.equals(spotMarkets_1.WRAPPED_SOL_MINT)) {
@@ -5514,7 +5712,7 @@ class VelocityClient {
5514
5712
  ixs.push(this.program.instruction.lpPoolRemoveLiquidity(outMarketIndex, lpToBurn, minAmountOut, {
5515
5713
  remainingAccounts,
5516
5714
  accounts: {
5517
- driftSigner: this.getSignerPublicKey(),
5715
+ velocitySigner: this.getSignerPublicKey(),
5518
5716
  state: await this.getStatePublicKey(),
5519
5717
  lpPool: lpPool.pubkey,
5520
5718
  authority: this.wallet.publicKey,
@@ -5546,7 +5744,7 @@ class VelocityClient {
5546
5744
  userAccounts: [],
5547
5745
  writableSpotMarketIndexes: [outMarketIndex],
5548
5746
  });
5549
- const spotMarket = this.getSpotMarketAccount(outMarketIndex);
5747
+ const spotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
5550
5748
  const outMarketMint = spotMarket.mint;
5551
5749
  const outConstituent = (0, pda_1.getConstituentPublicKey)(this.program.programId, lpPool.pubkey, outMarketIndex);
5552
5750
  const lpMint = lpPool.mint;
@@ -5587,7 +5785,7 @@ class VelocityClient {
5587
5785
  async getAllLpPoolRemoveLiquidityIxs({ outMarketIndex, lpToBurn, minAmountOut, lpPool, }, constituentMap, includeUpdateConstituentOracleInfo = true, view = false) {
5588
5786
  const ixs = [];
5589
5787
  ixs.push(...(await this.getAllSettlePerpToLpPoolIxs(lpPool.lpPoolId, this.getPerpMarketAccounts()
5590
- .filter((marketAccount) => marketAccount.lpStatus > 0)
5788
+ .filter((marketAccount) => marketAccount.hedgeConfig.status > 0)
5591
5789
  .map((marketAccount) => marketAccount.marketIndex))));
5592
5790
  ixs.push(...(await this.getAllUpdateLpPoolAumIxs(lpPool, constituentMap, includeUpdateConstituentOracleInfo)));
5593
5791
  if (view) {
@@ -5646,7 +5844,7 @@ class VelocityClient {
5646
5844
  const remainingAccounts = [];
5647
5845
  remainingAccounts.push(...perpMarketIndexes.map((index) => {
5648
5846
  return {
5649
- pubkey: this.getPerpMarketAccount(index).pubkey,
5847
+ pubkey: this.getPerpMarketAccountOrThrow(index).pubkey,
5650
5848
  isSigner: false,
5651
5849
  isWritable: true,
5652
5850
  };
@@ -5655,7 +5853,7 @@ class VelocityClient {
5655
5853
  const lpPool = (0, pda_1.getLpPoolPublicKey)(this.program.programId, lpPoolId);
5656
5854
  return this.program.instruction.settlePerpToLpPool({
5657
5855
  accounts: {
5658
- driftSigner: this.getSignerPublicKey(),
5856
+ velocitySigner: this.getSignerPublicKey(),
5659
5857
  state: await this.getStatePublicKey(),
5660
5858
  keeper: this.wallet.publicKey,
5661
5859
  ammCache: (0, pda_1.getAmmCachePublicKey)(this.program.programId),
@@ -5760,7 +5958,7 @@ class VelocityClient {
5760
5958
  });
5761
5959
  }
5762
5960
  isOrderIncreasingPosition(orderParams, subAccountId) {
5763
- const userAccount = this.getUserAccount(subAccountId);
5961
+ const userAccount = this.getUserAccountOrThrow(subAccountId);
5764
5962
  const perpPosition = userAccount.perpPositions.find((p) => p.marketIndex === orderParams.marketIndex);
5765
5963
  if (!perpPosition)
5766
5964
  return true;
@@ -5774,5 +5972,3 @@ class VelocityClient {
5774
5972
  }
5775
5973
  }
5776
5974
  exports.VelocityClient = VelocityClient;
5777
- /** @deprecated Use `VelocityClient` instead. `DriftClient` will be removed in a future major. */
5778
- exports.DriftClient = VelocityClient;