@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
@@ -52,6 +52,7 @@ import {
52
52
  PositionDirection,
53
53
  ReferrerInfo,
54
54
  ReferrerNameAccount,
55
+ RevenueShareEscrowAccount,
55
56
  ScaleOrderParams,
56
57
  SettlePnlMode,
57
58
  SignedTxData,
@@ -115,7 +116,6 @@ import {
115
116
  getUserAccountPublicKeySync,
116
117
  getUserStatsAccountPublicKey,
117
118
  getSignedMsgWsDelegatesAccountPublicKey,
118
- getIfRebalanceConfigPublicKey,
119
119
  getRevenueShareAccountPublicKey,
120
120
  getRevenueShareEscrowAccountPublicKey,
121
121
  getConstituentTargetBasePublicKey,
@@ -137,7 +137,6 @@ import {
137
137
  import { TxSender, TxSigAndSlot } from './tx/types';
138
138
  import {
139
139
  BASE_PRECISION,
140
- GOV_SPOT_MARKET_INDEX,
141
140
  MARGIN_PRECISION,
142
141
  MIN_I64,
143
142
  ONE,
@@ -167,7 +166,7 @@ import {
167
166
  VelocityProgram,
168
167
  PYTH_LAZER_STORAGE_ACCOUNT_KEY,
169
168
  } from './config';
170
- import { Drift } from './idl/drift';
169
+ import { Velocity } from './idl/velocity';
171
170
  import { WRAPPED_SOL_MINT } from './constants/spotMarkets';
172
171
  import { UserStats } from './userStats';
173
172
  import { isSpotPositionAvailable } from './math/spotPosition';
@@ -202,6 +201,8 @@ import { RevenueShareEscrowMap } from './userMap/revenueShareEscrowMap';
202
201
  import {
203
202
  isBuilderOrderReferral,
204
203
  isBuilderOrderCompleted,
204
+ escrowHasReferrer,
205
+ hasBuilderParams,
205
206
  } from './math/builder';
206
207
  import { TitanClient, SwapMode as TitanSwapMode } from './titan/titanClient';
207
208
  import { UnifiedSwapClient } from './swap/UnifiedSwapClient';
@@ -224,11 +225,12 @@ export class VelocityClient {
224
225
  public program: VelocityProgram;
225
226
  provider: AnchorProvider;
226
227
  env: VelocityEnv;
227
- opts?: ConfirmOptions;
228
+ opts: ConfirmOptions;
228
229
  useHotWalletAdmin?: boolean;
229
230
  users = new Map<string, User>();
230
231
  userStats?: UserStats;
231
- activeSubAccountId: number;
232
+ userStatsAccountPublicKey?: PublicKey;
233
+ activeSubAccountId: number | undefined;
232
234
  userAccountSubscriptionConfig: UserSubscriptionConfig;
233
235
  userStatsAccountSubscriptionConfig: UserStatsSubscriptionConfig;
234
236
  accountSubscriber: VelocityClientAccountSubscriber;
@@ -245,13 +247,8 @@ export class VelocityClient {
245
247
  mustIncludeSpotMarketIndexes = new Set<number>();
246
248
  authority: PublicKey;
247
249
 
248
- /** @deprecated use marketLookupTables */
249
- marketLookupTable: PublicKey;
250
- /** @deprecated use lookupTableAccounts */
251
- lookupTableAccount: AddressLookupTableAccount;
252
-
253
250
  marketLookupTables: PublicKey[];
254
- lookupTableAccounts: AddressLookupTableAccount[];
251
+ lookupTableAccounts?: AddressLookupTableAccount[];
255
252
 
256
253
  includeDelegates?: boolean;
257
254
  authoritySubAccountMap?: Map<string, number[]>;
@@ -329,8 +326,8 @@ export class VelocityClient {
329
326
  config.wallet,
330
327
  this.opts
331
328
  );
332
- this.program = new Program<Drift>(
333
- VelocityCore.defaultIdl() as unknown as Drift,
329
+ this.program = new Program<Velocity>(
330
+ VelocityCore.defaultIdl() as unknown as Velocity,
334
331
  this.provider,
335
332
  config.coder
336
333
  );
@@ -438,19 +435,11 @@ export class VelocityClient {
438
435
  });
439
436
  }
440
437
 
441
- this.marketLookupTable = config.marketLookupTable;
442
- if (!this.marketLookupTable) {
443
- this.marketLookupTable = new PublicKey(
444
- configs[this.env].MARKET_LOOKUP_TABLE
445
- );
446
- }
447
-
448
- this.marketLookupTables = config.marketLookupTables;
449
- if (!this.marketLookupTables) {
450
- this.marketLookupTables = configs[this.env].MARKET_LOOKUP_TABLES.map(
438
+ this.marketLookupTables =
439
+ config.marketLookupTables ??
440
+ configs[this.env].MARKET_LOOKUP_TABLES.map(
451
441
  (tableAddr) => new PublicKey(tableAddr)
452
442
  );
453
- }
454
443
 
455
444
  const delistedMarketSetting =
456
445
  config.delistedMarketSetting || DelistedMarketSetting.Unsubscribe;
@@ -471,7 +460,6 @@ export class VelocityClient {
471
460
  } else if (config.accountSubscription?.type === 'grpc') {
472
461
  const accountSubscriberClass: any =
473
462
  config.accountSubscription?.velocityClientAccountSubscriber ??
474
- config.accountSubscription?.driftClientAccountSubscriber ??
475
463
  grpcVelocityClientAccountSubscriber;
476
464
  this.accountSubscriber = new accountSubscriberClass(
477
465
  config.accountSubscription.grpcConfigs,
@@ -489,7 +477,6 @@ export class VelocityClient {
489
477
  } else {
490
478
  const accountSubscriberClass: any =
491
479
  config.accountSubscription?.velocityClientAccountSubscriber ??
492
- config.accountSubscription?.driftClientAccountSubscriber ??
493
480
  WebSocketVelocityClientAccountSubscriber;
494
481
  this.accountSubscriber = new accountSubscriberClass(
495
482
  this.program as any,
@@ -632,6 +619,18 @@ export class VelocityClient {
632
619
  return this.accountSubscriber.getMarketAccountAndSlot(marketIndex)?.data;
633
620
  }
634
621
 
622
+ /**
623
+ * Like {@link getPerpMarketAccount} but throws if the market is not loaded,
624
+ * for call sites that require a guaranteed account.
625
+ */
626
+ public getPerpMarketAccountOrThrow(marketIndex: number): PerpMarketAccount {
627
+ const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
628
+ if (!perpMarketAccount) {
629
+ throw new Error(`Perp market ${marketIndex} not found`);
630
+ }
631
+ return perpMarketAccount;
632
+ }
633
+
635
634
  /**
636
635
  * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
637
636
  * @param marketIndex
@@ -661,7 +660,20 @@ export class VelocityClient {
661
660
  public getSpotMarketAccount(
662
661
  marketIndex: number
663
662
  ): SpotMarketAccount | undefined {
664
- return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
663
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex)
664
+ ?.data;
665
+ }
666
+
667
+ /**
668
+ * Like {@link getSpotMarketAccount} but throws if the market is not loaded,
669
+ * for call sites that require a guaranteed account.
670
+ */
671
+ public getSpotMarketAccountOrThrow(marketIndex: number): SpotMarketAccount {
672
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
673
+ if (!spotMarketAccount) {
674
+ throw new Error(`Spot market ${marketIndex} not found`);
675
+ }
676
+ return spotMarketAccount;
665
677
  }
666
678
 
667
679
  /**
@@ -672,7 +684,8 @@ export class VelocityClient {
672
684
  marketIndex: number
673
685
  ): Promise<SpotMarketAccount | undefined> {
674
686
  await this.accountSubscriber.fetch();
675
- return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
687
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex)
688
+ ?.data;
676
689
  }
677
690
 
678
691
  public getSpotMarketAccounts(): SpotMarketAccount[] {
@@ -683,9 +696,7 @@ export class VelocityClient {
683
696
  }
684
697
 
685
698
  public getQuoteSpotMarketAccount(): SpotMarketAccount {
686
- return this.accountSubscriber.getSpotMarketAccountAndSlot(
687
- QUOTE_SPOT_MARKET_INDEX
688
- ).data;
699
+ return this.getSpotMarketAccountOrThrow(QUOTE_SPOT_MARKET_INDEX);
689
700
  }
690
701
 
691
702
  public getOraclePriceDataAndSlot(
@@ -697,22 +708,6 @@ export class VelocityClient {
697
708
  );
698
709
  }
699
710
 
700
- /** @deprecated use fetchAllLookupTableAccounts() */
701
- public async fetchMarketLookupTableAccount(): Promise<AddressLookupTableAccount> {
702
- if (this.lookupTableAccount) return this.lookupTableAccount;
703
-
704
- if (!this.marketLookupTable) {
705
- console.log('Market lookup table address not set');
706
- return;
707
- }
708
-
709
- const lookupTableAccount = (
710
- await this.connection.getAddressLookupTable(this.marketLookupTable)
711
- ).value;
712
- this.lookupTableAccount = lookupTableAccount;
713
-
714
- return lookupTableAccount;
715
- }
716
711
  public async fetchAllLookupTableAccounts(): Promise<
717
712
  AddressLookupTableAccount[]
718
713
  > {
@@ -751,7 +746,7 @@ export class VelocityClient {
751
746
  }
752
747
 
753
748
  /**
754
- * Update the wallet to use for drift transactions and linked user account
749
+ * Update the wallet to use for velocity transactions and linked user account
755
750
  * @param newWallet
756
751
  * @param subAccountIds
757
752
  * @param activeSubAccountId
@@ -770,8 +765,8 @@ export class VelocityClient {
770
765
  newWallet,
771
766
  this.opts
772
767
  );
773
- const newProgram = new Program<Drift>(
774
- VelocityCore.defaultIdl() as unknown as Drift,
768
+ const newProgram = new Program<Velocity>(
769
+ VelocityCore.defaultIdl() as unknown as Velocity,
775
770
  newProvider
776
771
  );
777
772
 
@@ -891,10 +886,11 @@ export class VelocityClient {
891
886
 
892
887
  this.activeSubAccountId = subAccountId;
893
888
  this.authority = authority ?? this.authority;
894
- this.userStatsAccountPublicKey = getUserStatsAccountPublicKey(
889
+ const userStatsAccountPublicKey = getUserStatsAccountPublicKey(
895
890
  this.program.programId,
896
891
  this.authority
897
892
  );
893
+ this.userStatsAccountPublicKey = userStatsAccountPublicKey;
898
894
 
899
895
  /* If changing the user authority ie switching from delegate to non-delegate account, need to re-subscribe to the user stats account */
900
896
  if (authorityChanged && this.userStats) {
@@ -904,7 +900,7 @@ export class VelocityClient {
904
900
 
905
901
  this.userStats = new UserStats({
906
902
  velocityClient: this,
907
- userStatsAccountPublicKey: this.userStatsAccountPublicKey,
903
+ userStatsAccountPublicKey: userStatsAccountPublicKey,
908
904
  accountSubscription: this.userStatsAccountSubscriptionConfig,
909
905
  });
910
906
 
@@ -920,7 +916,7 @@ export class VelocityClient {
920
916
  authority = authority ?? this.authority;
921
917
  const userKey = this.getUserMapKey(subAccountId, authority);
922
918
 
923
- if (this.users.has(userKey) && this.users.get(userKey).isSubscribed) {
919
+ if (this.users.has(userKey) && this.users.get(userKey)?.isSubscribed) {
924
920
  return true;
925
921
  }
926
922
 
@@ -944,7 +940,7 @@ export class VelocityClient {
944
940
  * Adds and subscribes to users based on params set by the constructor or by updateWallet.
945
941
  */
946
942
  public async addAndSubscribeToUsers(authority?: PublicKey): Promise<boolean> {
947
- // save the rpc calls if driftclient is initialized without a real wallet
943
+ // save the rpc calls if velocityclient is initialized without a real wallet
948
944
  if (this.skipLoadUsers) return true;
949
945
 
950
946
  let result = true;
@@ -967,8 +963,8 @@ export class VelocityClient {
967
963
  );
968
964
  }
969
965
  } else {
970
- let userAccounts = [];
971
- let delegatedAccounts = [];
966
+ let userAccounts: UserAccount[] = [];
967
+ let delegatedAccounts: UserAccount[] = [];
972
968
 
973
969
  const userAccountsPromise = this.getUserAccountsForAuthority(
974
970
  authority ?? this.wallet.publicKey
@@ -1569,7 +1565,7 @@ export class VelocityClient {
1569
1565
 
1570
1566
  async getNextSubAccountId(): Promise<number> {
1571
1567
  const userStats = this.getUserStats();
1572
- let userStatsAccount: UserStatsAccount;
1568
+ let userStatsAccount: UserStatsAccount | undefined;
1573
1569
  if (!userStats) {
1574
1570
  userStatsAccount = await fetchUserStatsAccount(
1575
1571
  this.connection,
@@ -1577,7 +1573,19 @@ export class VelocityClient {
1577
1573
  this.wallet.publicKey
1578
1574
  );
1579
1575
  } else {
1580
- userStatsAccount = userStats.getAccount();
1576
+ const account = userStats.getAccount();
1577
+ if (!account) {
1578
+ userStatsAccount = await fetchUserStatsAccount(
1579
+ this.connection,
1580
+ this.program,
1581
+ this.wallet.publicKey
1582
+ );
1583
+ } else {
1584
+ userStatsAccount = account;
1585
+ }
1586
+ }
1587
+ if (!userStatsAccount) {
1588
+ throw new Error('UserStats account does not exist');
1581
1589
  }
1582
1590
  return userStatsAccount.numberOfSubAccountsCreated;
1583
1591
  }
@@ -1754,10 +1762,10 @@ export class VelocityClient {
1754
1762
 
1755
1763
  await this.addUser(subAccountId, this.wallet.publicKey);
1756
1764
 
1757
- let remainingAccounts;
1765
+ let remainingAccounts: AccountMeta[];
1758
1766
  try {
1759
1767
  remainingAccounts = this.getRemainingAccounts({
1760
- userAccounts: [this.getUserAccount(subAccountId)],
1768
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
1761
1769
  });
1762
1770
  } catch (err) {
1763
1771
  remainingAccounts = [];
@@ -1838,6 +1846,32 @@ export class VelocityClient {
1838
1846
  return txSig;
1839
1847
  }
1840
1848
 
1849
+ public async getUpdateUserAllowDelegateTransferIx(
1850
+ allowDelegateTransfer: boolean
1851
+ ): Promise<TransactionInstruction> {
1852
+ return await this.program.instruction.updateUserAllowDelegateTransfer(
1853
+ allowDelegateTransfer,
1854
+ {
1855
+ accounts: {
1856
+ userStats: this.getUserStatsAccountPublicKey(),
1857
+ authority: this.wallet.publicKey,
1858
+ },
1859
+ }
1860
+ );
1861
+ }
1862
+
1863
+ public async updateUserAllowDelegateTransfer(
1864
+ allowDelegateTransfer: boolean
1865
+ ): Promise<TransactionSignature> {
1866
+ const tx = await this.buildTransaction(
1867
+ await this.getUpdateUserAllowDelegateTransferIx(allowDelegateTransfer),
1868
+ this.txParams
1869
+ );
1870
+
1871
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
1872
+ return txSig;
1873
+ }
1874
+
1841
1875
  public async updateUserAdvancedLp(
1842
1876
  updates: { advancedLp: boolean; subAccountId: number }[]
1843
1877
  ): Promise<TransactionSignature> {
@@ -1961,7 +1995,9 @@ export class VelocityClient {
1961
1995
  public async getUserAccountsForDelegate(
1962
1996
  delegate: PublicKey
1963
1997
  ): Promise<UserAccount[]> {
1964
- const programAccounts = await (this.program.account as any).user.all([
1998
+ const programAccounts: ProgramAccount<UserAccount>[] = await (
1999
+ this.program.account as any
2000
+ ).user.all([
1965
2001
  {
1966
2002
  memcmp: {
1967
2003
  offset: 40,
@@ -1979,7 +2015,9 @@ export class VelocityClient {
1979
2015
  public async getUserAccountsAndAddressesForAuthority(
1980
2016
  authority: PublicKey
1981
2017
  ): Promise<ProgramAccount<UserAccount>[]> {
1982
- const programAccounts = await (this.program.account as any).user.all([
2018
+ const programAccounts: ProgramAccount<UserAccount>[] = await (
2019
+ this.program.account as any
2020
+ ).user.all([
1983
2021
  {
1984
2022
  memcmp: {
1985
2023
  offset: 8,
@@ -1997,7 +2035,9 @@ export class VelocityClient {
1997
2035
  public async getUserAccountsForAuthority(
1998
2036
  authority: PublicKey
1999
2037
  ): Promise<UserAccount[]> {
2000
- const programAccounts = await (this.program.account as any).user.all([
2038
+ const programAccounts: ProgramAccount<UserAccount>[] = await (
2039
+ this.program.account as any
2040
+ ).user.all([
2001
2041
  {
2002
2042
  memcmp: {
2003
2043
  offset: 8,
@@ -2015,7 +2055,9 @@ export class VelocityClient {
2015
2055
  public async getReferredUserStatsAccountsByReferrer(
2016
2056
  referrer: PublicKey
2017
2057
  ): Promise<UserStatsAccount[]> {
2018
- const programAccounts = await (this.program.account as any).userStats.all([
2058
+ const programAccounts: ProgramAccount<UserStatsAccount>[] = await (
2059
+ this.program.account as any
2060
+ ).userStats.all([
2019
2061
  {
2020
2062
  memcmp: {
2021
2063
  offset: 40,
@@ -2033,7 +2075,7 @@ export class VelocityClient {
2033
2075
  public async getReferrerNameAccountsForAuthority(
2034
2076
  authority: PublicKey
2035
2077
  ): Promise<ReferrerNameAccount[]> {
2036
- const programAccounts = await (
2078
+ const programAccounts: ProgramAccount<ReferrerNameAccount>[] = await (
2037
2079
  this.program.account as any
2038
2080
  ).referrerName.all([
2039
2081
  {
@@ -2137,7 +2179,9 @@ export class VelocityClient {
2137
2179
  if (isSpotPositionAvailable(spotPosition)) {
2138
2180
  continue;
2139
2181
  }
2140
- const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
2182
+ const spotMarket = this.getSpotMarketAccountOrThrow(
2183
+ spotPosition.marketIndex
2184
+ );
2141
2185
  remainingAccounts.push({
2142
2186
  isSigner: false,
2143
2187
  isWritable: true,
@@ -2178,7 +2222,7 @@ export class VelocityClient {
2178
2222
  userStats,
2179
2223
  authority,
2180
2224
  state: await this.getStatePublicKey(),
2181
- driftSigner: this.getSignerPublicKey(),
2225
+ velocitySigner: this.getSignerPublicKey(),
2182
2226
  keeper: this.wallet.publicKey,
2183
2227
  },
2184
2228
  remainingAccounts,
@@ -2273,17 +2317,26 @@ export class VelocityClient {
2273
2317
  public getUser(subAccountId?: number, authority?: PublicKey): User {
2274
2318
  subAccountId = subAccountId ?? this.activeSubAccountId;
2275
2319
  authority = authority ?? this.authority;
2320
+
2321
+ if (subAccountId === undefined || authority === undefined) {
2322
+ throw new Error('Subaccount ID and authority are required');
2323
+ }
2324
+
2276
2325
  const userMapKey = this.getUserMapKey(subAccountId, authority);
2277
2326
 
2278
- if (!this.users.has(userMapKey)) {
2327
+ const user = this.users.get(userMapKey);
2328
+ if (!user) {
2279
2329
  throw new Error(`VelocityClient has no user for user id ${userMapKey}`);
2280
2330
  }
2281
- return this.users.get(userMapKey);
2331
+ return user;
2282
2332
  }
2283
2333
 
2284
2334
  public hasUser(subAccountId?: number, authority?: PublicKey): boolean {
2285
2335
  subAccountId = subAccountId ?? this.activeSubAccountId;
2286
2336
  authority = authority ?? this.authority;
2337
+ if (subAccountId === undefined || authority === undefined) {
2338
+ throw new Error('Subaccount ID and authority are required');
2339
+ }
2287
2340
  const userMapKey = this.getUserMapKey(subAccountId, authority);
2288
2341
 
2289
2342
  return this.users.has(userMapKey);
@@ -2292,18 +2345,29 @@ export class VelocityClient {
2292
2345
  public getUsers(): User[] {
2293
2346
  // delegate users get added to the end
2294
2347
  return [...this.users.values()]
2295
- .filter((acct) =>
2296
- acct.getUserAccount().authority.equals(this.wallet.publicKey)
2348
+ .filter(
2349
+ (acct) => acct.getUserAccount()?.authority.equals(this.wallet.publicKey)
2297
2350
  )
2298
2351
  .concat(
2299
2352
  [...this.users.values()].filter(
2300
2353
  (acct) =>
2301
- !acct.getUserAccount().authority.equals(this.wallet.publicKey)
2354
+ !acct.getUserAccount()?.authority.equals(this.wallet.publicKey)
2302
2355
  )
2303
2356
  );
2304
2357
  }
2305
2358
 
2306
- public getUserStats(): UserStats {
2359
+ public getUserStats(): UserStats | undefined {
2360
+ return this.userStats;
2361
+ }
2362
+
2363
+ /**
2364
+ * Like {@link getUserStats} but throws if there is no UserStats
2365
+ * subscription, for call sites that require a guaranteed account.
2366
+ */
2367
+ public getUserStatsOrThrow(): UserStats {
2368
+ if (!this.userStats) {
2369
+ throw new Error('VelocityClient has no UserStats subscription');
2370
+ }
2307
2371
  return this.userStats;
2308
2372
  }
2309
2373
 
@@ -2320,7 +2384,6 @@ export class VelocityClient {
2320
2384
  )) as ReferrerNameAccount;
2321
2385
  }
2322
2386
 
2323
- userStatsAccountPublicKey: PublicKey;
2324
2387
  public getUserStatsAccountPublicKey(): PublicKey {
2325
2388
  if (this.userStatsAccountPublicKey) {
2326
2389
  return this.userStatsAccountPublicKey;
@@ -2347,6 +2410,18 @@ export class VelocityClient {
2347
2410
  return this.getUser(subAccountId, authority).getUserAccount();
2348
2411
  }
2349
2412
 
2413
+ /**
2414
+ * Like {@link getUserAccount} but throws a named error instead of returning
2415
+ * `undefined` when the account has not been loaded yet. Use at call sites
2416
+ * that structurally require a loaded account.
2417
+ */
2418
+ public getUserAccountOrThrow(
2419
+ subAccountId?: number,
2420
+ authority?: PublicKey
2421
+ ): UserAccount {
2422
+ return this.getUser(subAccountId, authority).getUserAccountOrThrow();
2423
+ }
2424
+
2350
2425
  /**
2351
2426
  * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
2352
2427
  * @param subAccountId
@@ -2370,7 +2445,7 @@ export class VelocityClient {
2370
2445
  marketIndex: number,
2371
2446
  subAccountId?: number
2372
2447
  ): SpotPosition | undefined {
2373
- return this.getUserAccount(subAccountId).spotPositions.find(
2448
+ return this.getUserAccountOrThrow(subAccountId).spotPositions.find(
2374
2449
  (spotPosition) => spotPosition.marketIndex === marketIndex
2375
2450
  );
2376
2451
  }
@@ -2398,7 +2473,7 @@ export class VelocityClient {
2398
2473
  if (spotPosition === undefined) {
2399
2474
  return ZERO;
2400
2475
  }
2401
- const spotMarket = this.getSpotMarketAccount(marketIndex);
2476
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
2402
2477
  return getSignedTokenAmount(
2403
2478
  getTokenAmount(
2404
2479
  spotPosition.scaledBalance,
@@ -2415,7 +2490,7 @@ export class VelocityClient {
2415
2490
  * @param amount
2416
2491
  */
2417
2492
  public convertToSpotPrecision(marketIndex: number, amount: BN | number): BN {
2418
- const spotMarket = this.getSpotMarketAccount(marketIndex);
2493
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
2419
2494
  return castNumberToSpotPrecision(amount, spotMarket);
2420
2495
  }
2421
2496
 
@@ -2444,7 +2519,7 @@ export class VelocityClient {
2444
2519
  }
2445
2520
 
2446
2521
  /**
2447
- * Each drift instruction must include perp and sport market accounts in the ix remaining accounts.
2522
+ * Each velocity instruction must include perp and sport market accounts in the ix remaining accounts.
2448
2523
  * Use this function to force a subset of markets to be included in the remaining accounts for every ix
2449
2524
  *
2450
2525
  * @param perpMarketIndexes
@@ -2465,8 +2540,52 @@ export class VelocityClient {
2465
2540
  this.mustIncludeSpotMarketIndexes.add(spotMarketIndex);
2466
2541
  });
2467
2542
  }
2543
+ private cachePerpMarketSlot(
2544
+ slot: number | undefined,
2545
+ ...marketIndexes: number[]
2546
+ ): void {
2547
+ for (const marketIndex of marketIndexes) {
2548
+ if (slot !== undefined) {
2549
+ this.perpMarketLastSlotCache.set(marketIndex, slot);
2550
+ } else {
2551
+ this.perpMarketLastSlotCache.delete(marketIndex);
2552
+ }
2553
+ }
2554
+ }
2555
+
2556
+ private cacheSpotMarketSlot(
2557
+ slot: number | undefined,
2558
+ ...marketIndexes: number[]
2559
+ ): void {
2560
+ for (const marketIndex of marketIndexes) {
2561
+ if (slot !== undefined) {
2562
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
2563
+ } else {
2564
+ this.spotMarketLastSlotCache.delete(marketIndex);
2565
+ }
2566
+ }
2567
+ }
2568
+
2468
2569
  getRemainingAccounts(params: RemainingAccountParams): AccountMeta[] {
2469
- return VelocityCore.remainingAccounts.getRemainingAccounts(this, params);
2570
+ return VelocityCore.remainingAccounts.getRemainingAccounts(
2571
+ {
2572
+ getPerpMarketAccount: (marketIndex: number) =>
2573
+ this.getPerpMarketAccountOrThrow(marketIndex),
2574
+ getSpotMarketAccount: (marketIndex: number) =>
2575
+ this.getSpotMarketAccountOrThrow(marketIndex),
2576
+ getUserAccountAndSlot: (
2577
+ subAccountId: number | undefined,
2578
+ authority: PublicKey
2579
+ ) => this.getUserAccountAndSlot(subAccountId, authority),
2580
+ activeSubAccountId: this.activeSubAccountId,
2581
+ authority: this.authority,
2582
+ perpMarketLastSlotCache: this.perpMarketLastSlotCache,
2583
+ spotMarketLastSlotCache: this.spotMarketLastSlotCache,
2584
+ mustIncludePerpMarketIndexes: this.mustIncludePerpMarketIndexes,
2585
+ mustIncludeSpotMarketIndexes: this.mustIncludeSpotMarketIndexes,
2586
+ },
2587
+ params
2588
+ );
2470
2589
  }
2471
2590
 
2472
2591
  addPerpMarketToRemainingAccountMaps(
@@ -2476,16 +2595,16 @@ export class VelocityClient {
2476
2595
  spotMarketAccountMap: Map<number, AccountMeta>,
2477
2596
  perpMarketAccountMap: Map<number, AccountMeta>
2478
2597
  ): void {
2479
- const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
2598
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
2480
2599
  perpMarketAccountMap.set(marketIndex, {
2481
2600
  pubkey: perpMarketAccount.pubkey,
2482
2601
  isSigner: false,
2483
2602
  isWritable: writable,
2484
2603
  });
2485
2604
  const oracleWritable =
2486
- writable && isVariant(perpMarketAccount.amm.oracleSource, 'prelaunch');
2487
- oracleAccountMap.set(perpMarketAccount.amm.oracle.toString(), {
2488
- pubkey: perpMarketAccount.amm.oracle,
2605
+ writable && isVariant(perpMarketAccount.oracleSource, 'prelaunch');
2606
+ oracleAccountMap.set(perpMarketAccount.oracle.toString(), {
2607
+ pubkey: perpMarketAccount.oracle,
2489
2608
  isSigner: false,
2490
2609
  isWritable: oracleWritable,
2491
2610
  });
@@ -2503,7 +2622,7 @@ export class VelocityClient {
2503
2622
  oracleAccountMap: Map<string, AccountMeta>,
2504
2623
  spotMarketAccountMap: Map<number, AccountMeta>
2505
2624
  ): void {
2506
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2625
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
2507
2626
  spotMarketAccountMap.set(spotMarketAccount.marketIndex, {
2508
2627
  pubkey: spotMarketAccount.pubkey,
2509
2628
  isSigner: false,
@@ -2523,27 +2642,34 @@ export class VelocityClient {
2523
2642
  remainingAccounts: AccountMeta[]
2524
2643
  ): void {
2525
2644
  for (const builder of builders) {
2526
- // Add User account for the builder
2645
+ // Add User account for the builder. Dedupe by pubkey: an authority may be
2646
+ // both a builder and the referrer, in which case its User + RevenueShare
2647
+ // accounts would otherwise be pushed twice. On-chain `load_revenue_share_map`
2648
+ // rejects duplicates, which would silently abort the entire sweep.
2527
2649
  const builderUserAccount = getUserAccountPublicKeySync(
2528
2650
  this.program.programId,
2529
2651
  builder,
2530
2652
  0 // subAccountId 0 for builder user account
2531
2653
  );
2532
- remainingAccounts.push({
2533
- pubkey: builderUserAccount,
2534
- isSigner: false,
2535
- isWritable: true,
2536
- });
2654
+ if (!remainingAccounts.find((a) => a.pubkey.equals(builderUserAccount))) {
2655
+ remainingAccounts.push({
2656
+ pubkey: builderUserAccount,
2657
+ isSigner: false,
2658
+ isWritable: true,
2659
+ });
2660
+ }
2537
2661
 
2538
2662
  const builderAccount = getRevenueShareAccountPublicKey(
2539
2663
  this.program.programId,
2540
2664
  builder
2541
2665
  );
2542
- remainingAccounts.push({
2543
- pubkey: builderAccount,
2544
- isSigner: false,
2545
- isWritable: true,
2546
- });
2666
+ if (!remainingAccounts.find((a) => a.pubkey.equals(builderAccount))) {
2667
+ remainingAccounts.push({
2668
+ pubkey: builderAccount,
2669
+ isSigner: false,
2670
+ isWritable: true,
2671
+ });
2672
+ }
2547
2673
  }
2548
2674
  }
2549
2675
 
@@ -2599,12 +2725,37 @@ export class VelocityClient {
2599
2725
  };
2600
2726
  }
2601
2727
 
2602
- public getOrder(orderId: number, subAccountId?: number): Order | undefined {
2728
+ /**
2729
+ * Look up an open order by its program-assigned order ID from the cached user account.
2730
+ *
2731
+ * `orderId` is the monotonically incrementing u32 counter that the program assigns at
2732
+ * placement time — it is not known until the place instruction executes on-chain. Use
2733
+ * {@link getOrderByUserId} when you need to look up an order by the caller-supplied
2734
+ * `userOrderId` instead.
2735
+ *
2736
+ * Returns `undefined` when the order is not found (already filled, cancelled, or the
2737
+ * account cache is stale).
2738
+ */
2739
+ public getOrder(
2740
+ orderId: number | undefined,
2741
+ subAccountId?: number
2742
+ ): Order | undefined {
2603
2743
  return this.getUserAccount(subAccountId)?.orders.find(
2604
2744
  (order) => order.orderId === orderId
2605
2745
  );
2606
2746
  }
2607
2747
 
2748
+ /**
2749
+ * Look up an open order by the caller-supplied `userOrderId` from the cached user account.
2750
+ *
2751
+ * `userOrderId` is a 1-255 slot chosen by the caller in {@link OrderParams} and is stable
2752
+ * across the life of the order — useful when you need to reference an order before the
2753
+ * program-assigned {@link Order.orderId} is known (e.g. immediately after placing without
2754
+ * waiting for confirmation). Use {@link getOrder} when you have the program-assigned ID.
2755
+ *
2756
+ * Returns `undefined` when the order is not found (already filled, cancelled, or the
2757
+ * account cache is stale).
2758
+ */
2608
2759
  public getOrderByUserId(
2609
2760
  userOrderId: number,
2610
2761
  subAccountId?: number
@@ -2627,7 +2778,7 @@ export class VelocityClient {
2627
2778
  authority = this.wallet.publicKey,
2628
2779
  allowOwnerOffCurve = false
2629
2780
  ): Promise<PublicKey> {
2630
- const spotMarket = this.getSpotMarketAccount(marketIndex);
2781
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
2631
2782
  if (useNative && spotMarket.mint.equals(WRAPPED_SOL_MINT)) {
2632
2783
  return authority;
2633
2784
  }
@@ -2675,7 +2826,7 @@ export class VelocityClient {
2675
2826
  authority?: PublicKey;
2676
2827
  }
2677
2828
  ): Promise<TransactionInstruction[]> {
2678
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2829
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
2679
2830
 
2680
2831
  const isSolMarket = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);
2681
2832
 
@@ -2859,7 +3010,7 @@ export class VelocityClient {
2859
3010
  );
2860
3011
 
2861
3012
  const { txSig, slot } = await this.sendTransaction(tx, [], this.opts);
2862
- this.spotMarketLastSlotCache.set(marketIndex, slot);
3013
+ this.cacheSpotMarketSlot(slot, marketIndex);
2863
3014
  return txSig;
2864
3015
  }
2865
3016
 
@@ -2882,8 +3033,12 @@ export class VelocityClient {
2882
3033
 
2883
3034
  let remainingAccounts = [];
2884
3035
  if (userInitialized) {
3036
+ const userAccount = await this.forceGetUserAccount(subAccountId);
3037
+ if (!userAccount) {
3038
+ throw new Error('User account not loaded after force fetch');
3039
+ }
2885
3040
  remainingAccounts = this.getRemainingAccounts({
2886
- userAccounts: [await this.forceGetUserAccount(subAccountId)],
3041
+ userAccounts: [userAccount],
2887
3042
  useMarketLastSlotCache: true,
2888
3043
  writableSpotMarketIndexes: [marketIndex],
2889
3044
  });
@@ -2894,7 +3049,7 @@ export class VelocityClient {
2894
3049
  });
2895
3050
  }
2896
3051
 
2897
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3052
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
2898
3053
 
2899
3054
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
2900
3055
  if (this.isTransferHook(spotMarketAccount)) {
@@ -2957,7 +3112,11 @@ export class VelocityClient {
2957
3112
  TOKEN_PROGRAM_ID
2958
3113
  );
2959
3114
 
2960
- const result = {
3115
+ const result: {
3116
+ ixs: TransactionInstruction[];
3117
+ signers: Signer[];
3118
+ pubkey: PublicKey;
3119
+ } = {
2961
3120
  ixs: [],
2962
3121
  signers: [],
2963
3122
  pubkey: wrappedSolAccount,
@@ -3044,9 +3203,15 @@ export class VelocityClient {
3044
3203
  mint,
3045
3204
  hookAccount!.programId
3046
3205
  );
3047
- const extraAccountMetas = getExtraAccountMetas(
3048
- await this.connection.getAccountInfo(extraAccountMetasAddress)!
3206
+ const extraAccountMetasAccount = await this.connection.getAccountInfo(
3207
+ extraAccountMetasAddress
3049
3208
  );
3209
+ if (!extraAccountMetasAccount) {
3210
+ throw new Error(
3211
+ 'Extra account metas account not found for transfer hook'
3212
+ );
3213
+ }
3214
+ const extraAccountMetas = getExtraAccountMetas(extraAccountMetasAccount);
3050
3215
 
3051
3216
  for (const acc of extraAccountMetas) {
3052
3217
  // assuming it's an extra account meta that does not rely on ix data
@@ -3132,7 +3297,7 @@ export class VelocityClient {
3132
3297
  ixs.push(initializeSignedMsgUserOrdersAccountIx);
3133
3298
  }
3134
3299
 
3135
- const spotMarket = this.getSpotMarketAccount(marketIndex);
3300
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
3136
3301
 
3137
3302
  const isSolMarket = spotMarket.mint.equals(WRAPPED_SOL_MINT);
3138
3303
 
@@ -3154,7 +3319,7 @@ export class VelocityClient {
3154
3319
 
3155
3320
  const wSolAmount = isSolMarket ? amount.add(donateAmount) : donateAmount;
3156
3321
 
3157
- let wsolTokenAccount: PublicKey;
3322
+ let wsolTokenAccount: PublicKey | undefined;
3158
3323
  if (createWSOLTokenAccount) {
3159
3324
  const { ixs: startIxs, pubkey } =
3160
3325
  await this.getWrappedSolAccountCreationIxs(
@@ -3228,6 +3393,9 @@ export class VelocityClient {
3228
3393
  ixs.push(depositCollateralIx);
3229
3394
 
3230
3395
  if (!donateAmount.eq(ZERO)) {
3396
+ if (!wsolTokenAccount) {
3397
+ throw new Error('wsolTokenAccount is required to donate to rev pool');
3398
+ }
3231
3399
  const donateIx = await this.getDepositIntoSpotMarketRevenuePoolIx(
3232
3400
  1,
3233
3401
  donateAmount,
@@ -3249,6 +3417,9 @@ export class VelocityClient {
3249
3417
  // Close the wrapped sol account at the end of the transaction
3250
3418
  // Return funds to the deposit source (external wallet if provided)
3251
3419
  if (createWSOLTokenAccount) {
3420
+ if (!wsolTokenAccount) {
3421
+ throw new Error('wsolTokenAccount was not created');
3422
+ }
3252
3423
  ixs.push(
3253
3424
  createCloseAccountInstruction(
3254
3425
  wsolTokenAccount,
@@ -3354,7 +3525,7 @@ export class VelocityClient {
3354
3525
  additionalSigners,
3355
3526
  this.opts
3356
3527
  );
3357
- this.spotMarketLastSlotCache.set(marketIndex, slot);
3528
+ this.cacheSpotMarketSlot(slot, marketIndex);
3358
3529
 
3359
3530
  await this.addUser(subAccountId);
3360
3531
 
@@ -3423,7 +3594,7 @@ export class VelocityClient {
3423
3594
  ): Promise<TransactionInstruction[]> {
3424
3595
  const withdrawIxs: TransactionInstruction[] = [];
3425
3596
 
3426
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3597
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
3427
3598
 
3428
3599
  const isSolMarket = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);
3429
3600
 
@@ -3518,7 +3689,7 @@ export class VelocityClient {
3518
3689
  additionalSigners,
3519
3690
  this.opts
3520
3691
  );
3521
- this.spotMarketLastSlotCache.set(marketIndex, slot);
3692
+ this.cacheSpotMarketSlot(slot, marketIndex);
3522
3693
  return txSig;
3523
3694
  }
3524
3695
 
@@ -3585,13 +3756,13 @@ export class VelocityClient {
3585
3756
  const user = await this.getUserAccountPublicKey(subAccountId);
3586
3757
 
3587
3758
  const remainingAccounts = this.getRemainingAccounts({
3588
- userAccounts: [this.getUserAccount(subAccountId)],
3759
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
3589
3760
  useMarketLastSlotCache: true,
3590
3761
  writableSpotMarketIndexes: [marketIndex],
3591
3762
  readableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
3592
3763
  });
3593
3764
 
3594
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3765
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
3595
3766
 
3596
3767
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
3597
3768
  if (this.isTransferHook(spotMarketAccount)) {
@@ -3611,7 +3782,7 @@ export class VelocityClient {
3611
3782
  state: await this.getStatePublicKey(),
3612
3783
  spotMarket: spotMarketAccount.pubkey,
3613
3784
  spotMarketVault: spotMarketAccount.vault,
3614
- driftSigner: this.getSignerPublicKey(),
3785
+ velocitySigner: this.getSignerPublicKey(),
3615
3786
  user,
3616
3787
  userStats: this.getUserStatsAccountPublicKey(),
3617
3788
  userTokenAccount,
@@ -3653,7 +3824,7 @@ export class VelocityClient {
3653
3824
  fromSubAccountId === this.activeSubAccountId ||
3654
3825
  toSubAccountId === this.activeSubAccountId
3655
3826
  ) {
3656
- this.spotMarketLastSlotCache.set(marketIndex, slot);
3827
+ this.cacheSpotMarketSlot(slot, marketIndex);
3657
3828
  }
3658
3829
  return txSig;
3659
3830
  }
@@ -3681,9 +3852,10 @@ export class VelocityClient {
3681
3852
  fromSubAccountId,
3682
3853
  this.wallet.publicKey
3683
3854
  );
3684
- if (this.users.has(userMapKey)) {
3855
+ const mapUser = this.users.get(userMapKey);
3856
+ if (mapUser) {
3685
3857
  remainingAccounts = this.getRemainingAccounts({
3686
- userAccounts: [this.users.get(userMapKey).getUserAccount()],
3858
+ userAccounts: [mapUser.getUserAccountOrThrow()],
3687
3859
  useMarketLastSlotCache: true,
3688
3860
  writableSpotMarketIndexes: [marketIndex],
3689
3861
  });
@@ -3711,12 +3883,96 @@ export class VelocityClient {
3711
3883
  toUser,
3712
3884
  userStats: this.getUserStatsAccountPublicKey(),
3713
3885
  state: await this.getStatePublicKey(),
3714
- spotMarketVault: this.getSpotMarketAccount(marketIndex).vault,
3886
+ spotMarketVault: this.getSpotMarketAccountOrThrow(marketIndex).vault,
3715
3887
  },
3716
3888
  remainingAccounts,
3717
3889
  });
3718
3890
  }
3719
3891
 
3892
+ public async transferDepositByDelegate(
3893
+ amount: BN,
3894
+ marketIndex: number,
3895
+ fromSubAccountId: number,
3896
+ toSubAccountId: number,
3897
+ txParams?: TxParams
3898
+ ): Promise<TransactionSignature> {
3899
+ const { txSig, slot } = await this.sendTransaction(
3900
+ await this.buildTransaction(
3901
+ await this.getTransferDepositByDelegateIx(
3902
+ amount,
3903
+ marketIndex,
3904
+ fromSubAccountId,
3905
+ toSubAccountId
3906
+ ),
3907
+ txParams
3908
+ ),
3909
+ [],
3910
+ this.opts
3911
+ );
3912
+ if (
3913
+ fromSubAccountId === this.activeSubAccountId ||
3914
+ toSubAccountId === this.activeSubAccountId
3915
+ ) {
3916
+ this.cacheSpotMarketSlot(slot, marketIndex);
3917
+ }
3918
+ return txSig;
3919
+ }
3920
+
3921
+ public async getTransferDepositByDelegateIx(
3922
+ amount: BN,
3923
+ marketIndex: number,
3924
+ fromSubAccountId: number,
3925
+ toSubAccountId: number
3926
+ ): Promise<TransactionInstruction> {
3927
+ const fromUser = await getUserAccountPublicKey(
3928
+ this.program.programId,
3929
+ this.authority,
3930
+ fromSubAccountId
3931
+ );
3932
+ const toUser = await getUserAccountPublicKey(
3933
+ this.program.programId,
3934
+ this.authority,
3935
+ toSubAccountId
3936
+ );
3937
+
3938
+ let remainingAccounts;
3939
+
3940
+ const userMapKey = this.getUserMapKey(fromSubAccountId, this.authority);
3941
+ const mapUser = this.users.get(userMapKey);
3942
+ if (mapUser) {
3943
+ remainingAccounts = this.getRemainingAccounts({
3944
+ userAccounts: [mapUser.getUserAccountOrThrow()],
3945
+ useMarketLastSlotCache: true,
3946
+ writableSpotMarketIndexes: [marketIndex],
3947
+ });
3948
+ } else {
3949
+ const fromUserAccount = (await (this.program.account as any).user.fetch(
3950
+ fromUser
3951
+ )) as UserAccount;
3952
+ remainingAccounts = this.getRemainingAccounts({
3953
+ userAccounts: [fromUserAccount],
3954
+ useMarketLastSlotCache: true,
3955
+ writableSpotMarketIndexes: [marketIndex],
3956
+ });
3957
+ }
3958
+
3959
+ return await this.program.instruction.transferDepositByDelegate(
3960
+ marketIndex,
3961
+ amount,
3962
+ {
3963
+ accounts: {
3964
+ delegate: this.wallet.publicKey,
3965
+ fromUser,
3966
+ toUser,
3967
+ userStats: this.getUserStatsAccountPublicKey(),
3968
+ state: await this.getStatePublicKey(),
3969
+ spotMarketVault: this.getSpotMarketAccountOrThrow(marketIndex).vault,
3970
+ },
3971
+ remainingAccounts,
3972
+ }
3973
+ );
3974
+ }
3975
+
3720
3976
  public async transferPools(
3721
3977
  depositFromMarketIndex: number,
3722
3978
  depositToMarketIndex: number,
@@ -3750,10 +4006,13 @@ export class VelocityClient {
3750
4006
  fromSubAccountId === this.activeSubAccountId ||
3751
4007
  toSubAccountId === this.activeSubAccountId
3752
4008
  ) {
3753
- this.spotMarketLastSlotCache.set(depositFromMarketIndex, slot);
3754
- this.spotMarketLastSlotCache.set(depositToMarketIndex, slot);
3755
- this.spotMarketLastSlotCache.set(borrowFromMarketIndex, slot);
3756
- this.spotMarketLastSlotCache.set(borrowToMarketIndex, slot);
4009
+ this.cacheSpotMarketSlot(
4010
+ slot,
4011
+ depositFromMarketIndex,
4012
+ depositToMarketIndex,
4013
+ borrowFromMarketIndex,
4014
+ borrowToMarketIndex
4015
+ );
3757
4016
  }
3758
4017
  return txSig;
3759
4018
  }
@@ -3780,10 +4039,10 @@ export class VelocityClient {
3780
4039
  toSubAccountId
3781
4040
  );
3782
4041
 
3783
- const userAccounts = [this.getUserAccount(fromSubAccountId)];
4042
+ const userAccounts = [this.getUserAccountOrThrow(fromSubAccountId)];
3784
4043
 
3785
4044
  if (!isToNewSubAccount) {
3786
- userAccounts.push(this.getUserAccount(toSubAccountId));
4045
+ userAccounts.push(this.getUserAccountOrThrow(toSubAccountId));
3787
4046
  }
3788
4047
 
3789
4048
  const remainingAccounts = this.getRemainingAccounts({
@@ -3798,10 +4057,10 @@ export class VelocityClient {
3798
4057
  });
3799
4058
 
3800
4059
  const tokenPrograms = new Set<string>();
3801
- const depositFromSpotMarket = this.getSpotMarketAccount(
4060
+ const depositFromSpotMarket = this.getSpotMarketAccountOrThrow(
3802
4061
  depositFromMarketIndex
3803
4062
  );
3804
- const borrowFromSpotMarket = this.getSpotMarketAccount(
4063
+ const borrowFromSpotMarket = this.getSpotMarketAccountOrThrow(
3805
4064
  borrowFromMarketIndex
3806
4065
  );
3807
4066
 
@@ -3834,17 +4093,17 @@ export class VelocityClient {
3834
4093
  toUser,
3835
4094
  userStats: this.getUserStatsAccountPublicKey(),
3836
4095
  state: await this.getStatePublicKey(),
3837
- depositFromSpotMarketVault: this.getSpotMarketAccount(
4096
+ depositFromSpotMarketVault: this.getSpotMarketAccountOrThrow(
3838
4097
  depositFromMarketIndex
3839
4098
  ).vault,
3840
4099
  depositToSpotMarketVault:
3841
- this.getSpotMarketAccount(depositToMarketIndex).vault,
3842
- borrowFromSpotMarketVault: this.getSpotMarketAccount(
4100
+ this.getSpotMarketAccountOrThrow(depositToMarketIndex).vault,
4101
+ borrowFromSpotMarketVault: this.getSpotMarketAccountOrThrow(
3843
4102
  borrowFromMarketIndex
3844
4103
  ).vault,
3845
4104
  borrowToSpotMarketVault:
3846
- this.getSpotMarketAccount(borrowToMarketIndex).vault,
3847
- driftSigner: this.getSignerPublicKey(),
4105
+ this.getSpotMarketAccountOrThrow(borrowToMarketIndex).vault,
4106
+ velocitySigner: this.getSignerPublicKey(),
3848
4107
  },
3849
4108
  remainingAccounts,
3850
4109
  }
@@ -3893,8 +4152,8 @@ export class VelocityClient {
3893
4152
 
3894
4153
  const remainingAccounts = this.getRemainingAccounts({
3895
4154
  userAccounts: [
3896
- this.getUserAccount(fromSubAccountId),
3897
- this.getUserAccount(toSubAccountId),
4155
+ this.getUserAccountOrThrow(fromSubAccountId),
4156
+ this.getUserAccountOrThrow(toSubAccountId),
3898
4157
  ],
3899
4158
  useMarketLastSlotCache: true,
3900
4159
  writablePerpMarketIndexes: [marketIndex],
@@ -3991,9 +4250,9 @@ export class VelocityClient {
3991
4250
  subAccountId ?? this.activeSubAccountId
3992
4251
  );
3993
4252
 
3994
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
4253
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
3995
4254
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
3996
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
4255
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
3997
4256
 
3998
4257
  const remainingAccounts = this.getRemainingAccounts({
3999
4258
  userAccounts: [],
@@ -4048,7 +4307,7 @@ export class VelocityClient {
4048
4307
  this.authority,
4049
4308
  subAccountId ?? this.activeSubAccountId
4050
4309
  ),
4051
- this.getUserAccount(subAccountId),
4310
+ this.getUserAccountOrThrow(subAccountId),
4052
4311
  [perpMarketIndex],
4053
4312
  SettlePnlMode.TRY_SETTLE
4054
4313
  );
@@ -4078,10 +4337,10 @@ export class VelocityClient {
4078
4337
  subAccountId ?? this.activeSubAccountId
4079
4338
  );
4080
4339
 
4081
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
4340
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
4082
4341
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
4083
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
4084
- const user = await this.getUserAccount(subAccountId);
4342
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
4343
+ const user = await this.getUserAccountOrThrow(subAccountId);
4085
4344
  const remainingAccounts = this.getRemainingAccounts({
4086
4345
  userAccounts: [user],
4087
4346
  writableSpotMarketIndexes: [spotMarketIndex],
@@ -4141,18 +4400,26 @@ export class VelocityClient {
4141
4400
  this.authority,
4142
4401
  subAccountId ?? this.activeSubAccountId
4143
4402
  );
4144
- const userAccount = this.getUserAccount(subAccountId);
4403
+ const userAccount = this.getUserAccountOrThrow(subAccountId);
4145
4404
 
4146
4405
  const tokenAmountDeposited =
4147
4406
  this.getIsolatedPerpPositionTokenAmount(perpMarketIndex);
4407
+ const isolatedPerpPosition = userAccount.perpPositions.find(
4408
+ (p) => p.marketIndex === perpMarketIndex
4409
+ );
4410
+ if (!isolatedPerpPosition) {
4411
+ throw new Error(
4412
+ `No perp position found for market index ${perpMarketIndex}`
4413
+ );
4414
+ }
4148
4415
  const isolatedPositionUnrealizedPnl = calculateClaimablePnl(
4149
- this.getPerpMarketAccount(perpMarketIndex),
4150
- this.getSpotMarketAccount(
4151
- this.getPerpMarketAccount(perpMarketIndex).quoteSpotMarketIndex
4416
+ this.getPerpMarketAccountOrThrow(perpMarketIndex),
4417
+ this.getSpotMarketAccountOrThrow(
4418
+ this.getPerpMarketAccountOrThrow(perpMarketIndex).quoteSpotMarketIndex
4152
4419
  ),
4153
- userAccount.perpPositions.find((p) => p.marketIndex === perpMarketIndex),
4420
+ isolatedPerpPosition,
4154
4421
  this.getOracleDataForSpotMarket(
4155
- this.getPerpMarketAccount(perpMarketIndex).quoteSpotMarketIndex
4422
+ this.getPerpMarketAccountOrThrow(perpMarketIndex).quoteSpotMarketIndex
4156
4423
  )
4157
4424
  );
4158
4425
 
@@ -4165,7 +4432,8 @@ export class VelocityClient {
4165
4432
  : amount;
4166
4433
  let associatedTokenAccount = userTokenAccount;
4167
4434
  if (!associatedTokenAccount) {
4168
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
4435
+ const perpMarketAccount =
4436
+ this.getPerpMarketAccountOrThrow(perpMarketIndex);
4169
4437
  const quoteSpotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
4170
4438
  associatedTokenAccount = await this.getAssociatedTokenAccount(
4171
4439
  quoteSpotMarketIndex
@@ -4206,11 +4474,11 @@ export class VelocityClient {
4206
4474
  this.authority,
4207
4475
  subAccountId ?? this.activeSubAccountId
4208
4476
  );
4209
- const perpMarketAccount = this.getPerpMarketAccount(perpMarketIndex);
4477
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
4210
4478
  const spotMarketIndex = perpMarketAccount.quoteSpotMarketIndex;
4211
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
4479
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
4212
4480
  const remainingAccounts = this.getRemainingAccounts({
4213
- userAccounts: [this.getUserAccount(subAccountId)],
4481
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
4214
4482
  writableSpotMarketIndexes: [spotMarketIndex],
4215
4483
  readablePerpMarketIndex: [perpMarketIndex],
4216
4484
  });
@@ -4228,7 +4496,7 @@ export class VelocityClient {
4228
4496
  authority: this.wallet.publicKey,
4229
4497
  userTokenAccount: userTokenAccount,
4230
4498
  tokenProgram: this.getTokenProgramForSpotMarket(spotMarketAccount),
4231
- driftSigner: this.getSignerPublicKey(),
4499
+ velocitySigner: this.getSignerPublicKey(),
4232
4500
  },
4233
4501
  remainingAccounts,
4234
4502
  }
@@ -4253,7 +4521,7 @@ export class VelocityClient {
4253
4521
  public async updateSpotMarketCumulativeInterestIx(
4254
4522
  marketIndex: number
4255
4523
  ): Promise<TransactionInstruction> {
4256
- const spotMarket = this.getSpotMarketAccount(marketIndex);
4524
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
4257
4525
  return await this.program.instruction.updateSpotMarketCumulativeInterest({
4258
4526
  accounts: {
4259
4527
  state: await this.getStatePublicKey(),
@@ -4286,7 +4554,6 @@ export class VelocityClient {
4286
4554
  undefined,
4287
4555
  undefined,
4288
4556
  undefined,
4289
- undefined,
4290
4557
  subAccountId
4291
4558
  );
4292
4559
  }
@@ -4312,7 +4579,6 @@ export class VelocityClient {
4312
4579
  makerInfo?: MakerInfo | MakerInfo[],
4313
4580
  txParams?: TxParams,
4314
4581
  bracketOrdersParams = new Array<OptionalOrderParams>(),
4315
- referrerInfo?: ReferrerInfo,
4316
4582
  cancelExistingOrders?: boolean,
4317
4583
  settlePnl?: boolean,
4318
4584
  positionMaxLev?: number,
@@ -4334,7 +4600,7 @@ export class VelocityClient {
4334
4600
 
4335
4601
  const ixPromisesForTxs: Record<
4336
4602
  TxKeys,
4337
- Promise<TransactionInstruction | TransactionInstruction[]>
4603
+ Promise<TransactionInstruction | TransactionInstruction[]> | undefined
4338
4604
  > = {
4339
4605
  cancelExistingOrdersTx: undefined,
4340
4606
  settlePnlTx: undefined,
@@ -4393,14 +4659,18 @@ export class VelocityClient {
4393
4659
  marketIndex,
4394
4660
  },
4395
4661
  makerInfo,
4396
- referrerInfo,
4397
4662
  userAccount.subAccountId
4398
4663
  );
4399
4664
  }
4400
4665
 
4401
4666
  const ixs = await Promise.all(Object.values(ixPromisesForTxs));
4402
4667
 
4403
- const ixsMap = ixs.reduce((acc, ix, i) => {
4668
+ const ixsMap = ixs.reduce<
4669
+ Record<
4670
+ string,
4671
+ TransactionInstruction | TransactionInstruction[] | undefined
4672
+ >
4673
+ >((acc, ix, i) => {
4404
4674
  acc[txKeys[i]] = ix;
4405
4675
  return acc;
4406
4676
  }, {}) as MappedRecord<
@@ -4434,7 +4704,6 @@ export class VelocityClient {
4434
4704
  makerInfo?: MakerInfo | MakerInfo[],
4435
4705
  txParams?: TxParams,
4436
4706
  bracketOrdersParams = new Array<OptionalOrderParams>(),
4437
- referrerInfo?: ReferrerInfo,
4438
4707
  cancelExistingOrders?: boolean,
4439
4708
  settlePnl?: boolean
4440
4709
  ): Promise<{
@@ -4450,7 +4719,6 @@ export class VelocityClient {
4450
4719
  makerInfo,
4451
4720
  txParams,
4452
4721
  bracketOrdersParams,
4453
- referrerInfo,
4454
4722
  cancelExistingOrders,
4455
4723
  settlePnl
4456
4724
  );
@@ -4466,7 +4734,7 @@ export class VelocityClient {
4466
4734
  true
4467
4735
  );
4468
4736
 
4469
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
4737
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
4470
4738
 
4471
4739
  return {
4472
4740
  txSig,
@@ -4510,10 +4778,69 @@ export class VelocityClient {
4510
4778
  [],
4511
4779
  this.opts
4512
4780
  );
4513
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
4781
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
4514
4782
  return txSig;
4515
4783
  }
4516
4784
 
4785
+ /**
4786
+ * Returns the RevenueShareEscrow account meta for the placing user when `orderParams`
4787
+ * carries a builder code (`builderIdx` + `builderFeeTenthBps`), otherwise `undefined`.
4788
+ * The on-chain handlers peek for this account last in `remaining_accounts`, so callers
4789
+ * must push it after the market/oracle/maker accounts.
4790
+ */
4791
+ private getBuilderEscrowAccountMeta(
4792
+ orderParams: Pick<OrderParams, 'builderIdx' | 'builderFeeTenthBps'>,
4793
+ subAccountId?: number
4794
+ ): AccountMeta | undefined {
4795
+ if (!hasBuilderParams(orderParams)) {
4796
+ return undefined;
4797
+ }
4798
+ const authority =
4799
+ this.getUserAccount(subAccountId)?.authority ?? this.authority;
4800
+ return {
4801
+ pubkey: getRevenueShareEscrowAccountPublicKey(
4802
+ this.program.programId,
4803
+ authority
4804
+ ),
4805
+ isWritable: true,
4806
+ isSigner: false,
4807
+ };
4808
+ }
4809
+
4810
+ /**
4811
+ * Returns the AccountMeta for the taker's RevenueShareEscrow when a fill of the
4812
+ * taker's order must include it: the order carries a builder code, or the taker
4813
+ * is referred (their escrow was initialized with a referrer). Returns `undefined`
4814
+ * when neither applies so no account meta is added to the transaction. The
4815
+ * on-chain handlers peek for this account last in `remaining_accounts`, so
4816
+ * callers must push it after the market/oracle/maker accounts.
4817
+ *
4818
+ * Throws when `takerEscrow` does not belong to `takerAuthority`.
4819
+ */
4820
+ private getTakerEscrowAccountMeta(
4821
+ takerAuthority: PublicKey,
4822
+ orderHasBuilder: boolean,
4823
+ takerEscrow?: RevenueShareEscrowAccount
4824
+ ): AccountMeta | undefined {
4825
+ if (takerEscrow && !takerEscrow.authority.equals(takerAuthority)) {
4826
+ throw new Error(
4827
+ 'takerEscrow.authority does not match the taker user account authority'
4828
+ );
4829
+ }
4830
+ const takerIsReferred = takerEscrow && escrowHasReferrer(takerEscrow);
4831
+ if (!orderHasBuilder && !takerIsReferred) {
4832
+ return undefined;
4833
+ }
4834
+ return {
4835
+ pubkey: getRevenueShareEscrowAccountPublicKey(
4836
+ this.program.programId,
4837
+ takerAuthority
4838
+ ),
4839
+ isWritable: true,
4840
+ isSigner: false,
4841
+ };
4842
+ }
4843
+
4517
4844
  public async getPlacePerpOrderIx(
4518
4845
  orderParams: OptionalOrderParams,
4519
4846
  subAccountId?: number,
@@ -4537,7 +4864,7 @@ export class VelocityClient {
4537
4864
  const remainingAccounts = this.getRemainingAccounts({
4538
4865
  userAccounts: depositToTradeArgs?.isMakingNewAccount
4539
4866
  ? []
4540
- : [this.getUserAccount(subAccountId)],
4867
+ : [this.getUserAccountOrThrow(subAccountId)],
4541
4868
  useMarketLastSlotCache: false,
4542
4869
  readablePerpMarketIndex: orderParams.marketIndex,
4543
4870
  readableSpotMarketIndexes: isDepositToTradeTx
@@ -4545,6 +4872,14 @@ export class VelocityClient {
4545
4872
  : undefined,
4546
4873
  });
4547
4874
 
4875
+ const builderEscrow = this.getBuilderEscrowAccountMeta(
4876
+ orderParams,
4877
+ subAccountId
4878
+ );
4879
+ if (builderEscrow) {
4880
+ remainingAccounts.push(builderEscrow);
4881
+ }
4882
+
4548
4883
  return await VelocityCore.buildPlacePerpOrderInstruction({
4549
4884
  program: this.program,
4550
4885
  orderParams,
@@ -4577,14 +4912,14 @@ export class VelocityClient {
4577
4912
  const marketAccountInfos = [];
4578
4913
  const oracleAccountInfos = [];
4579
4914
  for (const marketIndex of marketIndexes) {
4580
- const market = this.getPerpMarketAccount(marketIndex);
4915
+ const market = this.getPerpMarketAccountOrThrow(marketIndex);
4581
4916
  marketAccountInfos.push({
4582
4917
  pubkey: market.pubkey,
4583
4918
  isWritable: true,
4584
4919
  isSigner: false,
4585
4920
  });
4586
4921
  oracleAccountInfos.push({
4587
- pubkey: market.amm.oracle,
4922
+ pubkey: market.oracle,
4588
4923
  isWritable: false,
4589
4924
  isSigner: false,
4590
4925
  });
@@ -4682,6 +5017,20 @@ export class VelocityClient {
4682
5017
  );
4683
5018
  }
4684
5019
 
5020
+ /**
5021
+ * Cancel an open order and broadcast the transaction.
5022
+ *
5023
+ * When `orderId` is `undefined` (omitted or passed explicitly), the instruction is
5024
+ * sent with a `null` order ID and the program cancels the most recently placed order
5025
+ * on-chain via `get_last_order_id`. This is safe to use in a composed transaction
5026
+ * where a place instruction runs first and the assigned order ID is not yet known.
5027
+ *
5028
+ * Note: when `orderId` is `undefined` and `overrides.withdrawIsolatedDepositAmount`
5029
+ * is also provided, `getOrder` will return `undefined` (the ID is unknown client-side),
5030
+ * causing the withdraw path to throw — supply an explicit `orderId` in that case.
5031
+ *
5032
+ * @see {@link getCancelOrderIx} to obtain the instruction without sending.
5033
+ */
4685
5034
  public async cancelOrder(
4686
5035
  orderId?: number,
4687
5036
  txParams?: TxParams,
@@ -4698,6 +5047,11 @@ export class VelocityClient {
4698
5047
  const withdrawAmount = overrides.withdrawIsolatedDepositAmount;
4699
5048
 
4700
5049
  if (withdrawAmount.gt(ZERO)) {
5050
+ if (perpMarketIndex === undefined) {
5051
+ throw new Error(
5052
+ `Order ${orderId} not found when withdrawing isolated deposit`
5053
+ );
5054
+ }
4701
5055
  const withdrawIxs =
4702
5056
  await this.getWithdrawFromIsolatedPerpPositionIxsBundle(
4703
5057
  withdrawAmount,
@@ -4716,6 +5070,21 @@ export class VelocityClient {
4716
5070
  return txSig;
4717
5071
  }
4718
5072
 
5073
+ /**
5074
+ * Build a `cancelOrder` instruction for the given order.
5075
+ *
5076
+ * When `orderId` is `undefined` (omitted or passed explicitly), the instruction is
5077
+ * built with a `null` order ID (`orderId ?? null`). The program interprets a `null`
5078
+ * ID as "cancel the user's most recently placed order" (via `get_last_order_id`
5079
+ * on-chain). This is useful when composing a multi-instruction transaction where a
5080
+ * place instruction precedes the cancel and the program-assigned order ID is not yet
5081
+ * known at build time.
5082
+ *
5083
+ * When `orderId` is supplied, only that specific order is cancelled.
5084
+ *
5085
+ * @see {@link cancelOrder} to send the transaction directly.
5086
+ * @see {@link getCancelOrderByUserIdIx} to cancel by the caller-supplied `userOrderId`.
5087
+ */
4719
5088
  public async getCancelOrderIx(
4720
5089
  orderId?: number,
4721
5090
  subAccountId?: number
@@ -4723,7 +5092,7 @@ export class VelocityClient {
4723
5092
  const user = await this.getUserAccountPublicKey(subAccountId);
4724
5093
 
4725
5094
  const remainingAccounts = this.getRemainingAccounts({
4726
- userAccounts: [this.getUserAccount(subAccountId)],
5095
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
4727
5096
  useMarketLastSlotCache: true,
4728
5097
  });
4729
5098
 
@@ -4759,11 +5128,14 @@ export class VelocityClient {
4759
5128
  ): Promise<TransactionInstruction> {
4760
5129
  const user = await this.getUserAccountPublicKey(subAccountId);
4761
5130
 
4762
- const order = this.getOrderByUserId(userOrderId);
4763
- const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
5131
+ const order = this.getOrderByUserId(userOrderId, subAccountId);
5132
+ if (!order) {
5133
+ throw new Error(`Order with user order id ${userOrderId} not found`);
5134
+ }
5135
+ const oracle = this.getPerpMarketAccountOrThrow(order.marketIndex).oracle;
4764
5136
 
4765
5137
  const remainingAccounts = this.getRemainingAccounts({
4766
- userAccounts: [this.getUserAccount(subAccountId)],
5138
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
4767
5139
  useMarketLastSlotCache: true,
4768
5140
  });
4769
5141
 
@@ -4832,7 +5204,7 @@ export class VelocityClient {
4832
5204
  user?.userAccountPublicKey ??
4833
5205
  (await this.getUserAccountPublicKey(subAccountId));
4834
5206
  const userAccount =
4835
- user?.getUserAccount() ?? this.getUserAccount(subAccountId);
5207
+ user?.getUserAccount() ?? this.getUserAccountOrThrow(subAccountId);
4836
5208
 
4837
5209
  const remainingAccounts = this.getRemainingAccounts({
4838
5210
  userAccounts: [userAccount],
@@ -4875,9 +5247,9 @@ export class VelocityClient {
4875
5247
  }
4876
5248
 
4877
5249
  public async getCancelOrdersIx(
4878
- marketType: MarketType | null,
4879
- marketIndex: number | null,
4880
- direction: PositionDirection | null,
5250
+ marketType: MarketType | null | undefined,
5251
+ marketIndex: number | null | undefined,
5252
+ direction: PositionDirection | null | undefined,
4881
5253
  subAccountId?: number
4882
5254
  ): Promise<TransactionInstruction> {
4883
5255
  const user = await this.getUserAccountPublicKey(subAccountId);
@@ -4894,7 +5266,7 @@ export class VelocityClient {
4894
5266
  }
4895
5267
 
4896
5268
  const remainingAccounts = this.getRemainingAccounts({
4897
- userAccounts: [this.getUserAccount(subAccountId)],
5269
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
4898
5270
  readablePerpMarketIndex,
4899
5271
  readableSpotMarketIndexes,
4900
5272
  useMarketLastSlotCache: true,
@@ -5025,7 +5397,7 @@ export class VelocityClient {
5025
5397
  }
5026
5398
 
5027
5399
  const remainingAccounts = this.getRemainingAccounts({
5028
- userAccounts: [this.getUserAccount(subAccountId)],
5400
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
5029
5401
  readablePerpMarketIndex,
5030
5402
  readableSpotMarketIndexes,
5031
5403
  useMarketLastSlotCache: true,
@@ -5034,6 +5406,19 @@ export class VelocityClient {
5034
5406
  const formattedParams = params.map((item) => getOrderParams(item));
5035
5407
  const authority = overrides?.authority ?? this.wallet.publicKey;
5036
5408
 
5409
+ // The handler loads a single RevenueShareEscrow for the placing user, so push it once
5410
+ // if any order in the batch carries a builder code.
5411
+ const builderParam = formattedParams.find((p) => hasBuilderParams(p));
5412
+ if (builderParam) {
5413
+ const builderEscrow = this.getBuilderEscrowAccountMeta(
5414
+ builderParam,
5415
+ subAccountId
5416
+ );
5417
+ if (builderEscrow) {
5418
+ remainingAccounts.push(builderEscrow);
5419
+ }
5420
+ }
5421
+
5037
5422
  return await VelocityCore.buildPlaceOrdersInstruction({
5038
5423
  program: this.program,
5039
5424
  formattedParams,
@@ -5066,7 +5451,7 @@ export class VelocityClient {
5066
5451
  }
5067
5452
 
5068
5453
  const remainingAccounts = this.getRemainingAccounts({
5069
- userAccounts: [this.getUserAccount(subAccountId)],
5454
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
5070
5455
  readablePerpMarketIndex,
5071
5456
  readableSpotMarketIndexes,
5072
5457
  useMarketLastSlotCache: true,
@@ -5151,7 +5536,7 @@ export class VelocityClient {
5151
5536
  const isPerp = isVariant(params.marketType, 'perp');
5152
5537
 
5153
5538
  const remainingAccounts = this.getRemainingAccounts({
5154
- userAccounts: [this.getUserAccount(subAccountId)],
5539
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
5155
5540
  readablePerpMarketIndex: isPerp ? [params.marketIndex] : [],
5156
5541
  readableSpotMarketIndexes: isPerp ? [] : [params.marketIndex],
5157
5542
  useMarketLastSlotCache: true,
@@ -5191,11 +5576,11 @@ export class VelocityClient {
5191
5576
  user: UserAccount,
5192
5577
  order?: Pick<Order, 'marketIndex' | 'orderId'>,
5193
5578
  makerInfo?: MakerInfo | MakerInfo[],
5194
- referrerInfo?: ReferrerInfo,
5195
5579
  txParams?: TxParams,
5196
5580
  fillerSubAccountId?: number,
5197
5581
  fillerAuthority?: PublicKey,
5198
- hasBuilderFee?: boolean
5582
+ hasBuilderFee?: boolean,
5583
+ takerEscrow?: RevenueShareEscrowAccount
5199
5584
  ): Promise<TransactionSignature> {
5200
5585
  const { txSig } = await this.sendTransaction(
5201
5586
  await this.buildTransaction(
@@ -5204,11 +5589,11 @@ export class VelocityClient {
5204
5589
  user,
5205
5590
  order,
5206
5591
  makerInfo,
5207
- referrerInfo,
5208
5592
  fillerSubAccountId,
5209
5593
  undefined,
5210
5594
  fillerAuthority,
5211
- hasBuilderFee
5595
+ hasBuilderFee,
5596
+ takerEscrow
5212
5597
  ),
5213
5598
  txParams
5214
5599
  ),
@@ -5221,13 +5606,17 @@ export class VelocityClient {
5221
5606
  public async getFillPerpOrderIx(
5222
5607
  userAccountPublicKey: PublicKey,
5223
5608
  userAccount: UserAccount,
5224
- order: Pick<Order, 'marketIndex' | 'orderId'>,
5609
+ order?: Pick<Order, 'marketIndex' | 'orderId'>,
5225
5610
  makerInfo?: MakerInfo | MakerInfo[],
5226
- referrerInfo?: ReferrerInfo,
5227
5611
  fillerSubAccountId?: number,
5228
5612
  isSignedMsg?: boolean,
5229
5613
  fillerAuthority?: PublicKey,
5230
- hasBuilderFee?: boolean
5614
+ hasBuilderFee?: boolean,
5615
+ // The program rejects fills that omit the taker's RevenueShareEscrow when the
5616
+ // order has a builder OR the taker is referred with an escrow. The builder case
5617
+ // is detected from the order bitflags; pass the taker's decoded escrow (e.g.
5618
+ // from a RevenueShareEscrowMap) so referred takers also get it attached.
5619
+ takerEscrow?: RevenueShareEscrowAccount
5231
5620
  ): Promise<TransactionInstruction> {
5232
5621
  const userStatsPublicKey = getUserStatsAccountPublicKey(
5233
5622
  this.program.programId,
@@ -5261,7 +5650,10 @@ export class VelocityClient {
5261
5650
  ? order.marketIndex
5262
5651
  : userAccount.orders.find(
5263
5652
  (order) => order.orderId === userAccount.nextOrderId - 1
5264
- ).marketIndex;
5653
+ )?.marketIndex;
5654
+ if (marketIndex === undefined) {
5655
+ throw new Error('No order found to fill');
5656
+ }
5265
5657
 
5266
5658
  makerInfo = Array.isArray(makerInfo)
5267
5659
  ? makerInfo
@@ -5291,24 +5683,6 @@ export class VelocityClient {
5291
5683
  });
5292
5684
  }
5293
5685
 
5294
- if (referrerInfo) {
5295
- const referrerIsMaker =
5296
- makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
5297
- undefined;
5298
- if (!referrerIsMaker) {
5299
- remainingAccounts.push({
5300
- pubkey: referrerInfo.referrer,
5301
- isWritable: true,
5302
- isSigner: false,
5303
- });
5304
- remainingAccounts.push({
5305
- pubkey: referrerInfo.referrerStats,
5306
- isWritable: true,
5307
- isSigner: false,
5308
- });
5309
- }
5310
- }
5311
-
5312
5686
  let withBuilder = false;
5313
5687
  if (hasBuilderFee) {
5314
5688
  withBuilder = true;
@@ -5328,18 +5702,22 @@ export class VelocityClient {
5328
5702
  }
5329
5703
  }
5330
5704
 
5331
- if (withBuilder) {
5332
- remainingAccounts.push({
5333
- pubkey: getRevenueShareEscrowAccountPublicKey(
5334
- this.program.programId,
5335
- userAccount.authority
5336
- ),
5337
- isWritable: true,
5338
- isSigner: false,
5339
- });
5705
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(
5706
+ userAccount.authority,
5707
+ withBuilder,
5708
+ takerEscrow
5709
+ );
5710
+ if (takerEscrowMeta) {
5711
+ remainingAccounts.push(takerEscrowMeta);
5340
5712
  }
5341
5713
 
5342
- const orderId = isSignedMsg ? null : order.orderId;
5714
+ let orderId: number | null = null;
5715
+ if (!isSignedMsg) {
5716
+ if (!order) {
5717
+ throw new Error('order is required to fill a non-signedMsg order');
5718
+ }
5719
+ orderId = order.orderId;
5720
+ }
5343
5721
  return await VelocityCore.buildFillPerpOrderInstruction({
5344
5722
  program: this.program,
5345
5723
  orderId,
@@ -5401,7 +5779,6 @@ export class VelocityClient {
5401
5779
  _order?: Pick<Order, 'marketIndex' | 'orderId'>,
5402
5780
  _fulfillmentConfig?: unknown,
5403
5781
  _makerInfo?: MakerInfo | MakerInfo[],
5404
- _referrerInfo?: ReferrerInfo,
5405
5782
  _txParams?: TxParams
5406
5783
  ): Promise<TransactionSignature> {
5407
5784
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
@@ -5413,14 +5790,13 @@ export class VelocityClient {
5413
5790
  _order?: Pick<Order, 'marketIndex' | 'orderId'>,
5414
5791
  _fulfillmentConfig?: unknown,
5415
5792
  _makerInfo?: MakerInfo | MakerInfo[],
5416
- _referrerInfo?: ReferrerInfo,
5417
5793
  _fillerPublicKey?: PublicKey
5418
5794
  ): Promise<TransactionInstruction> {
5419
5795
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
5420
5796
  }
5421
5797
 
5422
5798
  /**
5423
- * Swap tokens in drift account using titan or jupiter
5799
+ * Swap tokens in velocity account using titan or jupiter
5424
5800
  * @param swapClient swap client to find routes and instructions (Titan or Jupiter)
5425
5801
  * @param jupiterClient @deprecated Use swapClient instead. Legacy parameter for backward compatibility
5426
5802
  * @param outMarketIndex the market index of the token you're buying
@@ -5431,7 +5807,7 @@ export class VelocityClient {
5431
5807
  * @param slippageBps the max slippage passed to the swap provider api
5432
5808
  * @param swapMode swap provider swapMode (ExactIn or ExactOut), default is ExactIn
5433
5809
  * @param route the swap provider route to use for the swap
5434
- * @param reduceOnly specify if In or Out token on the drift account must reduceOnly, checked at end of swap
5810
+ * @param reduceOnly specify if In or Out token on the velocity account must reduceOnly, checked at end of swap
5435
5811
  * @param v6 pass in the quote response from swap provider quote's API (deprecated, use quote instead)
5436
5812
  * @param quote pass in the quote response from swap provider quote's API
5437
5813
  * @param txParams
@@ -5543,8 +5919,7 @@ export class VelocityClient {
5543
5919
  )) as VersionedTransaction;
5544
5920
 
5545
5921
  const { txSig, slot } = await this.sendTransaction(tx);
5546
- this.spotMarketLastSlotCache.set(outMarketIndex, slot);
5547
- this.spotMarketLastSlotCache.set(inMarketIndex, slot);
5922
+ this.cacheSpotMarketSlot(slot, outMarketIndex, inMarketIndex);
5548
5923
 
5549
5924
  return txSig;
5550
5925
  }
@@ -5577,8 +5952,8 @@ export class VelocityClient {
5577
5952
  ixs: TransactionInstruction[];
5578
5953
  lookupTables: AddressLookupTableAccount[];
5579
5954
  }> {
5580
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
5581
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
5955
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
5956
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5582
5957
 
5583
5958
  const isExactOut = swapMode === 'ExactOut';
5584
5959
  const exactOutBufferedAmountIn = amount.muln(1001).divn(1000); // Add 10bp buffer
@@ -5650,7 +6025,7 @@ export class VelocityClient {
5650
6025
  slippageBps,
5651
6026
  swapMode: isExactOut ? TitanSwapMode.ExactOut : TitanSwapMode.ExactIn,
5652
6027
  onlyDirectRoutes,
5653
- sizeConstraint: MAX_TX_BYTE_SIZE - 375, // buffer for drift instructions
6028
+ sizeConstraint: MAX_TX_BYTE_SIZE - 375, // buffer for velocity instructions
5654
6029
  });
5655
6030
 
5656
6031
  const titanInstructions = titanClient.getTitanInstructions({
@@ -5699,8 +6074,8 @@ export class VelocityClient {
5699
6074
  ixs: TransactionInstruction[];
5700
6075
  lookupTables: AddressLookupTableAccount[];
5701
6076
  }> {
5702
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
5703
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
6077
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
6078
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5704
6079
 
5705
6080
  if (!quote) {
5706
6081
  const fetchedQuote = await jupiterClient.getQuote({
@@ -5810,7 +6185,7 @@ export class VelocityClient {
5810
6185
  }
5811
6186
 
5812
6187
  /**
5813
- * Get the drift begin_swap and end_swap instructions
6188
+ * Get the velocity begin_swap and end_swap instructions
5814
6189
  *
5815
6190
  * @param outMarketIndex the market index of the token you're buying
5816
6191
  * @param inMarketIndex the market index of the token you're selling
@@ -5848,8 +6223,11 @@ export class VelocityClient {
5848
6223
 
5849
6224
  const userAccounts = [];
5850
6225
  try {
5851
- if (this.hasUser() && this.getUser().getUserAccountAndSlot()) {
5852
- userAccounts.push(this.getUser().getUserAccountAndSlot()!.data);
6226
+ const userAccount = this.hasUser()
6227
+ ? this.getUser().getUserAccount()
6228
+ : undefined;
6229
+ if (userAccount) {
6230
+ userAccounts.push(userAccount);
5853
6231
  }
5854
6232
  } catch (err) {
5855
6233
  // ignore
@@ -5861,8 +6239,8 @@ export class VelocityClient {
5861
6239
  readableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
5862
6240
  });
5863
6241
 
5864
- const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
5865
- const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
6242
+ const outSpotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
6243
+ const inSpotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5866
6244
 
5867
6245
  const outTokenProgram = this.getTokenProgramForSpotMarket(outSpotMarket);
5868
6246
  const inTokenProgram = this.getTokenProgramForSpotMarket(inSpotMarket);
@@ -5915,7 +6293,7 @@ export class VelocityClient {
5915
6293
  inTokenAccount,
5916
6294
  outTokenAccount,
5917
6295
  tokenProgram: inTokenProgram,
5918
- driftSigner: this.getStateAccount().signer,
6296
+ velocitySigner: this.getStateAccount().signer,
5919
6297
  instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
5920
6298
  },
5921
6299
  remainingAccounts,
@@ -5938,7 +6316,7 @@ export class VelocityClient {
5938
6316
  inTokenAccount,
5939
6317
  outTokenAccount,
5940
6318
  tokenProgram: inTokenProgram,
5941
- driftSigner: this.getStateAccount().signer,
6319
+ velocitySigner: this.getStateAccount().signer,
5942
6320
  instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
5943
6321
  },
5944
6322
  remainingAccounts,
@@ -5983,8 +6361,8 @@ export class VelocityClient {
5983
6361
  lookupTables: AddressLookupTableAccount[];
5984
6362
  }> {
5985
6363
  // Get market accounts to determine mints
5986
- const outMarket = this.getSpotMarketAccount(outMarketIndex);
5987
- const inMarket = this.getSpotMarketAccount(inMarketIndex);
6364
+ const outMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
6365
+ const inMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
5988
6366
 
5989
6367
  const isExactOut = swapMode === 'ExactOut';
5990
6368
 
@@ -6055,7 +6433,7 @@ export class VelocityClient {
6055
6433
  amountInForBeginSwap = amount;
6056
6434
  }
6057
6435
 
6058
- // Get drift swap instructions for begin and end
6436
+ // Get velocity swap instructions for begin and end
6059
6437
  const { beginSwapIx, endSwapIx } = await this.getSwapIx({
6060
6438
  outMarketIndex,
6061
6439
  inMarketIndex,
@@ -6104,7 +6482,7 @@ export class VelocityClient {
6104
6482
  amount: BN;
6105
6483
  userAccountPublicKey?: PublicKey;
6106
6484
  }): Promise<TransactionInstruction[]> {
6107
- const wSOLMint = this.getSpotMarketAccount(1).mint;
6485
+ const wSOLMint = this.getSpotMarketAccountOrThrow(1).mint;
6108
6486
  const mSOLAccount = await this.getAssociatedTokenAccount(2);
6109
6487
  const wSOLAccount = await this.getAssociatedTokenAccount(1, false);
6110
6488
 
@@ -6411,34 +6789,34 @@ export class VelocityClient {
6411
6789
  public async placeAndTakePerpOrder(
6412
6790
  orderParams: OptionalOrderParams,
6413
6791
  makerInfo?: MakerInfo | MakerInfo[],
6414
- referrerInfo?: ReferrerInfo,
6415
6792
  successCondition?: PlaceAndTakeOrderSuccessCondition,
6416
6793
  auctionDurationPercentage?: number,
6417
6794
  txParams?: TxParams,
6418
- subAccountId?: number
6795
+ subAccountId?: number,
6796
+ takerEscrow?: RevenueShareEscrowAccount
6419
6797
  ): Promise<TransactionSignature> {
6420
6798
  const { txSig, slot } = await this.sendTransaction(
6421
6799
  await this.buildTransaction(
6422
6800
  await this.getPlaceAndTakePerpOrderIx(
6423
6801
  orderParams,
6424
6802
  makerInfo,
6425
- referrerInfo,
6426
6803
  successCondition,
6427
6804
  auctionDurationPercentage,
6428
- subAccountId
6805
+ subAccountId,
6806
+ undefined,
6807
+ takerEscrow
6429
6808
  ),
6430
6809
  txParams
6431
6810
  ),
6432
6811
  [],
6433
6812
  this.opts
6434
6813
  );
6435
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
6814
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
6436
6815
  return txSig;
6437
6816
  }
6438
6817
  public async preparePlaceAndTakePerpOrderWithAdditionalOrders(
6439
6818
  orderParams: OptionalOrderParams,
6440
6819
  makerInfo?: MakerInfo | MakerInfo[],
6441
- referrerInfo?: ReferrerInfo,
6442
6820
  bracketOrdersParams = new Array<OptionalOrderParams>(),
6443
6821
  txParams?: TxParams,
6444
6822
  subAccountId?: number,
@@ -6449,15 +6827,18 @@ export class VelocityClient {
6449
6827
  optionalIxs?: TransactionInstruction[],
6450
6828
  isolatedPositionDepositAmount?: BN
6451
6829
  ): Promise<{
6452
- placeAndTakeTx: Transaction | VersionedTransaction;
6453
- cancelExistingOrdersTx: Transaction | VersionedTransaction;
6454
- settlePnlTx: Transaction | VersionedTransaction;
6455
- }> {
6830
+ placeAndTakeTx: Transaction | VersionedTransaction | undefined;
6831
+ cancelExistingOrdersTx: Transaction | VersionedTransaction | undefined;
6832
+ settlePnlTx: Transaction | VersionedTransaction | undefined;
6833
+ } | null> {
6456
6834
  const placeAndTakeIxs: TransactionInstruction[] = [];
6457
6835
 
6458
6836
  type TxKeys = 'placeAndTakeTx' | 'cancelExistingOrdersTx' | 'settlePnlTx';
6459
6837
 
6460
- const txsToSign: Record<TxKeys, Transaction | VersionedTransaction> = {
6838
+ const txsToSign: Record<
6839
+ TxKeys,
6840
+ Transaction | VersionedTransaction | undefined
6841
+ > = {
6461
6842
  placeAndTakeTx: undefined,
6462
6843
  cancelExistingOrdersTx: undefined,
6463
6844
  settlePnlTx: undefined,
@@ -6475,7 +6856,6 @@ export class VelocityClient {
6475
6856
  const placeAndTakeIx = await this.getPlaceAndTakePerpOrderIx(
6476
6857
  orderParams,
6477
6858
  makerInfo,
6478
- referrerInfo,
6479
6859
  undefined,
6480
6860
  auctionDurationPercentage,
6481
6861
  subAccountId
@@ -6520,6 +6900,11 @@ export class VelocityClient {
6520
6900
  };
6521
6901
 
6522
6902
  if (shouldUseSimulationComputeUnits || shouldExitIfSimulationFails) {
6903
+ if (!txParams) {
6904
+ throw new Error(
6905
+ 'txParams is required when simulating compute units or exiting early on failed simulation'
6906
+ );
6907
+ }
6523
6908
  const placeAndTakeTxToSim = (await this.buildTransaction(
6524
6909
  placeAndTakeIxs,
6525
6910
  txParams,
@@ -6601,7 +6986,7 @@ export class VelocityClient {
6601
6986
 
6602
6987
  const settlePnlIx = await this.settlePNLIx(
6603
6988
  userAccountPublicKey,
6604
- this.getUserAccount(subAccountId),
6989
+ this.getUserAccountOrThrow(subAccountId),
6605
6990
  orderParams.marketIndex
6606
6991
  );
6607
6992
 
@@ -6634,7 +7019,6 @@ export class VelocityClient {
6634
7019
  public async placeAndTakePerpWithAdditionalOrders(
6635
7020
  orderParams: OptionalOrderParams,
6636
7021
  makerInfo?: MakerInfo | MakerInfo[],
6637
- referrerInfo?: ReferrerInfo,
6638
7022
  bracketOrdersParams = new Array<OptionalOrderParams>(),
6639
7023
  txParams?: TxParams,
6640
7024
  subAccountId?: number,
@@ -6645,12 +7029,11 @@ export class VelocityClient {
6645
7029
  txSig: TransactionSignature;
6646
7030
  signedCancelExistingOrdersTx?: Transaction;
6647
7031
  signedSettlePnlTx?: Transaction;
6648
- }> {
7032
+ } | null> {
6649
7033
  const txsToSign =
6650
7034
  await this.preparePlaceAndTakePerpOrderWithAdditionalOrders(
6651
7035
  orderParams,
6652
7036
  makerInfo,
6653
- referrerInfo,
6654
7037
  bracketOrdersParams,
6655
7038
  txParams,
6656
7039
  subAccountId,
@@ -6671,6 +7054,10 @@ export class VelocityClient {
6671
7054
  )
6672
7055
  ).signedTxMap;
6673
7056
 
7057
+ if (!signedTxs.placeAndTakeTx) {
7058
+ throw new Error('placeAndTakeTx was not built');
7059
+ }
7060
+
6674
7061
  const { txSig, slot } = await this.sendTransaction(
6675
7062
  signedTxs.placeAndTakeTx,
6676
7063
  [],
@@ -6678,7 +7065,7 @@ export class VelocityClient {
6678
7065
  true
6679
7066
  );
6680
7067
 
6681
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
7068
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
6682
7069
 
6683
7070
  return {
6684
7071
  txSig,
@@ -6691,13 +7078,17 @@ export class VelocityClient {
6691
7078
  public async getPlaceAndTakePerpOrderIx(
6692
7079
  orderParams: OptionalOrderParams,
6693
7080
  makerInfo?: MakerInfo | MakerInfo[],
6694
- referrerInfo?: ReferrerInfo,
6695
7081
  successCondition?: PlaceAndTakeOrderSuccessCondition,
6696
7082
  auctionDurationPercentage?: number,
6697
7083
  subAccountId?: number,
6698
7084
  overrides?: {
6699
7085
  authority?: PublicKey;
6700
- }
7086
+ },
7087
+ // place_and_take fills the placing user's (the taker's) order in-instruction, so
7088
+ // their RevenueShareEscrow must be attached for BOTH builder fees and referrer
7089
+ // revenue share. The builder case is detected from orderParams; pass the user's
7090
+ // decoded escrow (e.g. from a RevenueShareEscrowMap) to cover the referred case.
7091
+ takerEscrow?: RevenueShareEscrowAccount
6701
7092
  ): Promise<TransactionInstruction> {
6702
7093
  orderParams = getOrderParams(orderParams, { marketType: MarketType.PERP });
6703
7094
  const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
@@ -6709,7 +7100,7 @@ export class VelocityClient {
6709
7100
  ? [makerInfo]
6710
7101
  : [];
6711
7102
 
6712
- const userAccounts = [this.getUserAccount(subAccountId)];
7103
+ const userAccounts = [this.getUserAccountOrThrow(subAccountId)];
6713
7104
  for (const maker of makerInfo) {
6714
7105
  userAccounts.push(maker.makerUserAccount);
6715
7106
  }
@@ -6733,22 +7124,13 @@ export class VelocityClient {
6733
7124
  });
6734
7125
  }
6735
7126
 
6736
- if (referrerInfo) {
6737
- const referrerIsMaker =
6738
- makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
6739
- undefined;
6740
- if (!referrerIsMaker) {
6741
- remainingAccounts.push({
6742
- pubkey: referrerInfo.referrer,
6743
- isWritable: true,
6744
- isSigner: false,
6745
- });
6746
- remainingAccounts.push({
6747
- pubkey: referrerInfo.referrerStats,
6748
- isWritable: true,
6749
- isSigner: false,
6750
- });
6751
- }
7127
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(
7128
+ this.getUserAccount(subAccountId)?.authority ?? this.authority,
7129
+ hasBuilderParams(orderParams),
7130
+ takerEscrow
7131
+ );
7132
+ if (takerEscrowMeta) {
7133
+ remainingAccounts.push(takerEscrowMeta);
6752
7134
  }
6753
7135
 
6754
7136
  let optionalParams = null;
@@ -6774,17 +7156,17 @@ export class VelocityClient {
6774
7156
  public async placeAndMakePerpOrder(
6775
7157
  orderParams: OptionalOrderParams,
6776
7158
  takerInfo: TakerInfo,
6777
- referrerInfo?: ReferrerInfo,
6778
7159
  txParams?: TxParams,
6779
- subAccountId?: number
7160
+ subAccountId?: number,
7161
+ takerEscrow?: RevenueShareEscrowAccount
6780
7162
  ): Promise<TransactionSignature> {
6781
7163
  const { txSig, slot } = await this.sendTransaction(
6782
7164
  await this.buildTransaction(
6783
7165
  await this.getPlaceAndMakePerpOrderIx(
6784
7166
  orderParams,
6785
7167
  takerInfo,
6786
- referrerInfo,
6787
- subAccountId
7168
+ subAccountId,
7169
+ takerEscrow
6788
7170
  ),
6789
7171
  txParams
6790
7172
  ),
@@ -6792,7 +7174,7 @@ export class VelocityClient {
6792
7174
  this.opts
6793
7175
  );
6794
7176
 
6795
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
7177
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
6796
7178
 
6797
7179
  return txSig;
6798
7180
  }
@@ -6800,8 +7182,12 @@ export class VelocityClient {
6800
7182
  public async getPlaceAndMakePerpOrderIx(
6801
7183
  orderParams: OptionalOrderParams,
6802
7184
  takerInfo: TakerInfo,
6803
- referrerInfo?: ReferrerInfo,
6804
- subAccountId?: number
7185
+ subAccountId?: number,
7186
+ // place_and_make fills the taker's order in-instruction, so the TAKER's
7187
+ // RevenueShareEscrow must be attached when their order has a builder or they
7188
+ // are referred with an escrow. The builder case is detected from the taker
7189
+ // order bitflags; pass the taker's decoded escrow to cover the referred case.
7190
+ takerEscrow?: RevenueShareEscrowAccount
6805
7191
  ): Promise<TransactionInstruction> {
6806
7192
  orderParams = getOrderParams(orderParams, { marketType: MarketType.PERP });
6807
7193
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
@@ -6809,36 +7195,21 @@ export class VelocityClient {
6809
7195
 
6810
7196
  const remainingAccounts = this.getRemainingAccounts({
6811
7197
  userAccounts: [
6812
- this.getUserAccount(subAccountId),
7198
+ this.getUserAccountOrThrow(subAccountId),
6813
7199
  takerInfo.takerUserAccount,
6814
7200
  ],
6815
7201
  useMarketLastSlotCache: true,
6816
7202
  writablePerpMarketIndexes: [orderParams.marketIndex],
6817
7203
  });
6818
7204
 
6819
- if (referrerInfo) {
6820
- remainingAccounts.push({
6821
- pubkey: referrerInfo.referrer,
6822
- isWritable: true,
6823
- isSigner: false,
6824
- });
6825
- remainingAccounts.push({
6826
- pubkey: referrerInfo.referrerStats,
6827
- isWritable: true,
6828
- isSigner: false,
6829
- });
6830
- }
6831
-
6832
7205
  const takerOrderId = takerInfo.order.orderId;
6833
- if (hasBuilder(takerInfo.order)) {
6834
- remainingAccounts.push({
6835
- pubkey: getRevenueShareEscrowAccountPublicKey(
6836
- this.program.programId,
6837
- takerInfo.takerUserAccount.authority
6838
- ),
6839
- isWritable: true,
6840
- isSigner: false,
6841
- });
7206
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(
7207
+ takerInfo.takerUserAccount.authority,
7208
+ hasBuilder(takerInfo.order),
7209
+ takerEscrow
7210
+ );
7211
+ if (takerEscrowMeta) {
7212
+ remainingAccounts.push(takerEscrowMeta);
6842
7213
  }
6843
7214
  return await VelocityCore.buildPlaceAndMakePerpOrderInstruction({
6844
7215
  program: this.program,
@@ -6874,7 +7245,7 @@ export class VelocityClient {
6874
7245
  /**
6875
7246
  * Builds a deposit and place request for Swift service
6876
7247
  *
6877
- * @param depositTx - The signed tx containing a drift deposit (e.g. see `buildSwiftDepositTx`)
7248
+ * @param depositTx - The signed tx containing a velocity deposit (e.g. see `buildSwiftDepositTx`)
6878
7249
  * @param orderParamsMessage - The order parameters message to sign
6879
7250
  * @param delegateSigner - Whether this is a delegate signer
6880
7251
  *
@@ -6940,8 +7311,11 @@ export class VelocityClient {
6940
7311
 
6941
7312
  public signMessage(
6942
7313
  message: Uint8Array,
6943
- keypair: Keypair = this.wallet.payer
7314
+ keypair: Keypair | undefined = this.wallet.payer
6944
7315
  ): Buffer {
7316
+ if (!keypair) {
7317
+ throw new Error('No keypair available to sign message');
7318
+ }
6945
7319
  return Buffer.from(nacl.sign.detached(message, keypair.secretKey));
6946
7320
  }
6947
7321
 
@@ -7012,10 +7386,7 @@ export class VelocityClient {
7012
7386
  writableSpotMarketIndexes,
7013
7387
  });
7014
7388
 
7015
- if (
7016
- signedMessage.builderFeeTenthBps !== null &&
7017
- signedMessage.builderIdx !== null
7018
- ) {
7389
+ if (hasBuilderParams(signedMessage)) {
7019
7390
  remainingAccounts.push({
7020
7391
  pubkey: getRevenueShareEscrowAccountPublicKey(
7021
7392
  this.program.programId,
@@ -7078,21 +7449,21 @@ export class VelocityClient {
7078
7449
  signingAuthority: PublicKey;
7079
7450
  },
7080
7451
  orderParams: OptionalOrderParams,
7081
- referrerInfo?: ReferrerInfo,
7082
7452
  txParams?: TxParams,
7083
7453
  subAccountId?: number,
7084
7454
  precedingIxs: TransactionInstruction[] = [],
7085
- overrideCustomIxIndex?: number
7455
+ overrideCustomIxIndex?: number,
7456
+ takerEscrow?: RevenueShareEscrowAccount
7086
7457
  ): Promise<TransactionSignature> {
7087
7458
  const ixs = await this.getPlaceAndMakeSignedMsgPerpOrderIxs(
7088
7459
  signedSignedMsgOrderParams,
7089
7460
  signedMsgOrderUuid,
7090
7461
  takerInfo,
7091
7462
  orderParams,
7092
- referrerInfo,
7093
7463
  subAccountId,
7094
7464
  precedingIxs,
7095
- overrideCustomIxIndex
7465
+ overrideCustomIxIndex,
7466
+ takerEscrow
7096
7467
  );
7097
7468
  const { txSig, slot } = await this.sendTransaction(
7098
7469
  await this.buildTransaction(ixs, txParams),
@@ -7100,7 +7471,7 @@ export class VelocityClient {
7100
7471
  this.opts
7101
7472
  );
7102
7473
 
7103
- this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
7474
+ this.cachePerpMarketSlot(slot, orderParams.marketIndex);
7104
7475
  return txSig;
7105
7476
  }
7106
7477
 
@@ -7114,10 +7485,13 @@ export class VelocityClient {
7114
7485
  signingAuthority: PublicKey;
7115
7486
  },
7116
7487
  orderParams: OptionalOrderParams,
7117
- referrerInfo?: ReferrerInfo,
7118
7488
  subAccountId?: number,
7119
7489
  precedingIxs: TransactionInstruction[] = [],
7120
- overrideCustomIxIndex?: number
7490
+ overrideCustomIxIndex?: number,
7491
+ // fills the taker's order in-instruction; pass the taker's decoded escrow so a
7492
+ // referred taker's escrow is attached even when the signed order carries no
7493
+ // builder fee
7494
+ takerEscrow?: RevenueShareEscrowAccount
7121
7495
  ): Promise<TransactionInstruction[]> {
7122
7496
  const [signedMsgOrderSignatureIx, placeTakerSignedMsgPerpOrderIx] =
7123
7497
  await this.getPlaceSignedMsgTakerPerpOrderIxs(
@@ -7134,26 +7508,13 @@ export class VelocityClient {
7134
7508
 
7135
7509
  const remainingAccounts = this.getRemainingAccounts({
7136
7510
  userAccounts: [
7137
- this.getUserAccount(subAccountId),
7511
+ this.getUserAccountOrThrow(subAccountId),
7138
7512
  takerInfo.takerUserAccount,
7139
7513
  ],
7140
7514
  useMarketLastSlotCache: false,
7141
7515
  writablePerpMarketIndexes: [orderParams.marketIndex],
7142
7516
  });
7143
7517
 
7144
- if (referrerInfo) {
7145
- remainingAccounts.push({
7146
- pubkey: referrerInfo.referrer,
7147
- isWritable: true,
7148
- isSigner: false,
7149
- });
7150
- remainingAccounts.push({
7151
- pubkey: referrerInfo.referrerStats,
7152
- isWritable: true,
7153
- isSigner: false,
7154
- });
7155
- }
7156
-
7157
7518
  const isDelegateSigner = takerInfo.signingAuthority.equals(
7158
7519
  takerInfo.takerUserAccount.delegate
7159
7520
  );
@@ -7166,18 +7527,13 @@ export class VelocityClient {
7166
7527
  borshBuf,
7167
7528
  isDelegateSigner
7168
7529
  );
7169
- if (
7170
- signedMessage.builderFeeTenthBps !== null &&
7171
- signedMessage.builderIdx !== null
7172
- ) {
7173
- remainingAccounts.push({
7174
- pubkey: getRevenueShareEscrowAccountPublicKey(
7175
- this.program.programId,
7176
- takerInfo.takerUserAccount.authority
7177
- ),
7178
- isWritable: true,
7179
- isSigner: false,
7180
- });
7530
+ const takerEscrowMeta = this.getTakerEscrowAccountMeta(
7531
+ takerInfo.takerUserAccount.authority,
7532
+ hasBuilderParams(signedMessage),
7533
+ takerEscrow
7534
+ );
7535
+ if (takerEscrowMeta) {
7536
+ remainingAccounts.push(takerEscrowMeta);
7181
7537
  }
7182
7538
 
7183
7539
  const placeAndMakeIx =
@@ -7212,7 +7568,6 @@ export class VelocityClient {
7212
7568
  _orderParams: OptionalOrderParams,
7213
7569
  _fulfillmentConfig?: unknown,
7214
7570
  _makerInfo?: MakerInfo,
7215
- _referrerInfo?: ReferrerInfo,
7216
7571
  _txParams?: TxParams,
7217
7572
  _subAccountId?: number
7218
7573
  ) {
@@ -7223,7 +7578,6 @@ export class VelocityClient {
7223
7578
  _orderParams: OptionalOrderParams,
7224
7579
  _fulfillmentConfig?: unknown,
7225
7580
  _makerInfo?: MakerInfo,
7226
- _referrerInfo?: ReferrerInfo,
7227
7581
  _txParams?: TxParams,
7228
7582
  _subAccountId?: number
7229
7583
  ): Promise<TransactionSignature> {
@@ -7233,7 +7587,6 @@ export class VelocityClient {
7233
7587
  _orderParams: OptionalOrderParams,
7234
7588
  _fulfillmentConfig?: unknown,
7235
7589
  _makerInfo?: MakerInfo,
7236
- _referrerInfo?: ReferrerInfo,
7237
7590
  _subAccountId?: number
7238
7591
  ): Promise<TransactionInstruction> {
7239
7592
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
@@ -7243,7 +7596,6 @@ export class VelocityClient {
7243
7596
  _orderParams: OptionalOrderParams,
7244
7597
  _takerInfo: TakerInfo,
7245
7598
  _fulfillmentConfig?: unknown,
7246
- _referrerInfo?: ReferrerInfo,
7247
7599
  _txParams?: TxParams,
7248
7600
  _subAccountId?: number
7249
7601
  ): Promise<TransactionSignature> {
@@ -7254,7 +7606,6 @@ export class VelocityClient {
7254
7606
  _orderParams: OptionalOrderParams,
7255
7607
  _takerInfo: TakerInfo,
7256
7608
  _fulfillmentConfig?: unknown,
7257
- _referrerInfo?: ReferrerInfo,
7258
7609
  _subAccountId?: number
7259
7610
  ): Promise<TransactionInstruction> {
7260
7611
  throw new Error(SPOT_DLOB_TRADING_DISABLED_MSG);
@@ -7287,7 +7638,6 @@ export class VelocityClient {
7287
7638
  undefined,
7288
7639
  undefined,
7289
7640
  undefined,
7290
- undefined,
7291
7641
  subAccountId
7292
7642
  );
7293
7643
  }
@@ -7437,8 +7787,12 @@ export class VelocityClient {
7437
7787
  const userPubKey =
7438
7788
  overrides?.user?.getUserAccountPublicKey() ??
7439
7789
  (await this.getUserAccountPublicKey(subAccountId));
7790
+ const overrideUserAccount = overrides?.user?.getUserAccount();
7791
+ if (overrides?.user && !overrideUserAccount) {
7792
+ throw new Error('modifyOrder: override user account is not loaded');
7793
+ }
7440
7794
  const userAccount =
7441
- overrides?.user?.getUserAccount() ?? this.getUserAccount(subAccountId);
7795
+ overrideUserAccount ?? this.getUserAccountOrThrow(subAccountId);
7442
7796
 
7443
7797
  const remainingAccounts = this.getRemainingAccounts({
7444
7798
  userAccounts: [userAccount],
@@ -7464,7 +7818,7 @@ export class VelocityClient {
7464
7818
 
7465
7819
  const authority =
7466
7820
  overrides?.authority ??
7467
- overrides?.user?.getUserAccount().authority ??
7821
+ overrideUserAccount?.authority ??
7468
7822
  this.wallet.publicKey;
7469
7823
  return await VelocityCore.buildModifyOrderInstruction({
7470
7824
  program: this.program,
@@ -7567,7 +7921,7 @@ export class VelocityClient {
7567
7921
  const user = await this.getUserAccountPublicKey(subAccountId);
7568
7922
 
7569
7923
  const remainingAccounts = this.getRemainingAccounts({
7570
- userAccounts: [this.getUserAccount(subAccountId)],
7924
+ userAccounts: [this.getUserAccountOrThrow(subAccountId)],
7571
7925
  useMarketLastSlotCache: true,
7572
7926
  });
7573
7927
 
@@ -7620,7 +7974,7 @@ export class VelocityClient {
7620
7974
 
7621
7975
  if (filterInvalidMarkets) {
7622
7976
  for (const marketIndex of marketIndexes) {
7623
- const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
7977
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
7624
7978
  const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
7625
7979
  const stateAccountAndSlot =
7626
7980
  this.accountSubscriber.getStateAccountAndSlot();
@@ -7775,7 +8129,7 @@ export class VelocityClient {
7775
8129
  isWritable: true,
7776
8130
  });
7777
8131
  }
7778
- if (!escrow.referrer.equals(PublicKey.default)) {
8132
+ if (escrowHasReferrer(escrow)) {
7779
8133
  this.addBuilderToRemainingAccounts(
7780
8134
  [escrow.referrer],
7781
8135
  remainingAccounts
@@ -7978,7 +8332,7 @@ export class VelocityClient {
7978
8332
  }
7979
8333
 
7980
8334
  // Add referrer's User and RevenueShare accounts
7981
- if (!escrow.referrer.equals(PublicKey.default)) {
8335
+ if (escrowHasReferrer(escrow)) {
7982
8336
  this.addBuilderToRemainingAccounts(
7983
8337
  [escrow.referrer],
7984
8338
  remainingAccounts
@@ -8080,7 +8434,7 @@ export class VelocityClient {
8080
8434
  [],
8081
8435
  this.opts
8082
8436
  );
8083
- this.perpMarketLastSlotCache.set(marketIndex, slot);
8437
+ this.cachePerpMarketSlot(slot, marketIndex);
8084
8438
  return txSig;
8085
8439
  }
8086
8440
  public async getLiquidatePerpIx(
@@ -8102,7 +8456,10 @@ export class VelocityClient {
8102
8456
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8103
8457
 
8104
8458
  const remainingAccounts = this.getRemainingAccounts({
8105
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
8459
+ userAccounts: [
8460
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
8461
+ userAccount,
8462
+ ],
8106
8463
  useMarketLastSlotCache: true,
8107
8464
  writablePerpMarketIndexes: [marketIndex],
8108
8465
  });
@@ -8144,7 +8501,7 @@ export class VelocityClient {
8144
8501
  [],
8145
8502
  this.opts
8146
8503
  );
8147
- this.perpMarketLastSlotCache.set(marketIndex, slot);
8504
+ this.cachePerpMarketSlot(slot, marketIndex);
8148
8505
  return txSig;
8149
8506
  }
8150
8507
 
@@ -8225,8 +8582,7 @@ export class VelocityClient {
8225
8582
  [],
8226
8583
  this.opts
8227
8584
  );
8228
- this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
8229
- this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
8585
+ this.cacheSpotMarketSlot(slot, assetMarketIndex, liabilityMarketIndex);
8230
8586
  return txSig;
8231
8587
  }
8232
8588
 
@@ -8250,7 +8606,10 @@ export class VelocityClient {
8250
8606
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8251
8607
 
8252
8608
  const remainingAccounts = this.getRemainingAccounts({
8253
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
8609
+ userAccounts: [
8610
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
8611
+ userAccount,
8612
+ ],
8254
8613
  useMarketLastSlotCache: true,
8255
8614
  writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
8256
8615
  });
@@ -8287,7 +8646,6 @@ export class VelocityClient {
8287
8646
  quote,
8288
8647
  userAccount,
8289
8648
  userAccountPublicKey,
8290
- userStatsAccountPublicKey,
8291
8649
  liquidatorSubAccountId,
8292
8650
  maxAccounts,
8293
8651
  }: {
@@ -8303,15 +8661,15 @@ export class VelocityClient {
8303
8661
  quote?: QuoteResponse;
8304
8662
  userAccount: UserAccount;
8305
8663
  userAccountPublicKey: PublicKey;
8306
- userStatsAccountPublicKey: PublicKey;
8307
8664
  liquidatorSubAccountId?: number;
8308
8665
  maxAccounts?: number;
8309
8666
  }): Promise<{
8310
8667
  ixs: TransactionInstruction[];
8311
8668
  lookupTables: AddressLookupTableAccount[];
8312
8669
  }> {
8313
- const liabilityMarket = this.getSpotMarketAccount(liabilityMarketIndex);
8314
- const assetMarket = this.getSpotMarketAccount(assetMarketIndex);
8670
+ const liabilityMarket =
8671
+ this.getSpotMarketAccountOrThrow(liabilityMarketIndex);
8672
+ const assetMarket = this.getSpotMarketAccountOrThrow(assetMarketIndex);
8315
8673
 
8316
8674
  if (!quote) {
8317
8675
  const fetchedQuote = await jupiterClient.getQuote({
@@ -8397,7 +8755,6 @@ export class VelocityClient {
8397
8755
  liabilityTokenAccount,
8398
8756
  userAccount,
8399
8757
  userAccountPublicKey,
8400
- userStatsAccountPublicKey,
8401
8758
  liquidatorSubAccountId,
8402
8759
  });
8403
8760
 
@@ -8412,7 +8769,7 @@ export class VelocityClient {
8412
8769
  }
8413
8770
 
8414
8771
  /**
8415
- * Get the drift liquidate_spot_with_swap instructions
8772
+ * Get the velocity liquidate_spot_with_swap instructions
8416
8773
  *
8417
8774
  * @param liabilityMarketIndex the market index of the token you're buying
8418
8775
  * @param assetMarketIndex the market index of the token you're selling
@@ -8421,7 +8778,6 @@ export class VelocityClient {
8421
8778
  * @param liabilityTokenAccount the token account to receive the tokens being bought
8422
8779
  * @param userAccount
8423
8780
  * @param userAccountPublicKey
8424
- * @param userStatsAccountPublicKey
8425
8781
  */
8426
8782
  public async getLiquidateSpotWithSwapIx({
8427
8783
  liabilityMarketIndex,
@@ -8431,7 +8787,6 @@ export class VelocityClient {
8431
8787
  liabilityTokenAccount,
8432
8788
  userAccount,
8433
8789
  userAccountPublicKey,
8434
- userStatsAccountPublicKey,
8435
8790
  liquidatorSubAccountId,
8436
8791
  }: {
8437
8792
  liabilityMarketIndex: number;
@@ -8441,7 +8796,6 @@ export class VelocityClient {
8441
8796
  liabilityTokenAccount: PublicKey;
8442
8797
  userAccount: UserAccount;
8443
8798
  userAccountPublicKey: PublicKey;
8444
- userStatsAccountPublicKey: PublicKey;
8445
8799
  liquidatorSubAccountId?: number;
8446
8800
  }): Promise<{
8447
8801
  beginSwapIx: TransactionInstruction;
@@ -8450,7 +8804,6 @@ export class VelocityClient {
8450
8804
  const liquidatorAccountPublicKey = await this.getUserAccountPublicKey(
8451
8805
  liquidatorSubAccountId
8452
8806
  );
8453
- const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8454
8807
 
8455
8808
  const userAccounts = [userAccount];
8456
8809
  const remainingAccounts = this.getRemainingAccounts({
@@ -8459,8 +8812,9 @@ export class VelocityClient {
8459
8812
  readableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
8460
8813
  });
8461
8814
 
8462
- const liabilitySpotMarket = this.getSpotMarketAccount(liabilityMarketIndex);
8463
- const assetSpotMarket = this.getSpotMarketAccount(assetMarketIndex);
8815
+ const liabilitySpotMarket =
8816
+ this.getSpotMarketAccountOrThrow(liabilityMarketIndex);
8817
+ const assetSpotMarket = this.getSpotMarketAccountOrThrow(assetMarketIndex);
8464
8818
 
8465
8819
  const liabilityTokenProgram =
8466
8820
  this.getTokenProgramForSpotMarket(liabilitySpotMarket);
@@ -8512,16 +8866,14 @@ export class VelocityClient {
8512
8866
  accounts: {
8513
8867
  state: await this.getStatePublicKey(),
8514
8868
  user: userAccountPublicKey,
8515
- userStats: userStatsAccountPublicKey,
8516
8869
  liquidator: liquidatorAccountPublicKey,
8517
- liquidatorStats: liquidatorStatsPublicKey,
8518
8870
  authority: this.wallet.publicKey,
8519
8871
  liabilitySpotMarketVault: liabilitySpotMarket.vault,
8520
8872
  assetSpotMarketVault: assetSpotMarket.vault,
8521
8873
  assetTokenAccount: assetTokenAccount,
8522
8874
  liabilityTokenAccount: liabilityTokenAccount,
8523
8875
  tokenProgram: assetTokenProgram,
8524
- driftSigner: this.getStateAccount().signer,
8876
+ velocitySigner: this.getStateAccount().signer,
8525
8877
  instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
8526
8878
  },
8527
8879
  remainingAccounts,
@@ -8535,115 +8887,14 @@ export class VelocityClient {
8535
8887
  accounts: {
8536
8888
  state: await this.getStatePublicKey(),
8537
8889
  user: userAccountPublicKey,
8538
- userStats: userStatsAccountPublicKey,
8539
8890
  liquidator: liquidatorAccountPublicKey,
8540
- liquidatorStats: liquidatorStatsPublicKey,
8541
8891
  authority: this.wallet.publicKey,
8542
8892
  liabilitySpotMarketVault: liabilitySpotMarket.vault,
8543
8893
  assetSpotMarketVault: assetSpotMarket.vault,
8544
8894
  assetTokenAccount: assetTokenAccount,
8545
8895
  liabilityTokenAccount: liabilityTokenAccount,
8546
8896
  tokenProgram: assetTokenProgram,
8547
- driftSigner: this.getStateAccount().signer,
8548
- instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
8549
- },
8550
- remainingAccounts,
8551
- }
8552
- );
8553
-
8554
- return { beginSwapIx, endSwapIx };
8555
- }
8556
-
8557
- public async getInsuranceFundSwapIx({
8558
- inMarketIndex,
8559
- outMarketIndex,
8560
- amountIn,
8561
- inTokenAccount,
8562
- outTokenAccount,
8563
- }: {
8564
- inMarketIndex: number;
8565
- outMarketIndex: number;
8566
- amountIn: BN;
8567
- inTokenAccount: PublicKey;
8568
- outTokenAccount: PublicKey;
8569
- }): Promise<{
8570
- beginSwapIx: TransactionInstruction;
8571
- endSwapIx: TransactionInstruction;
8572
- }> {
8573
- const remainingAccounts = await this.getRemainingAccounts({
8574
- userAccounts: [],
8575
- writableSpotMarketIndexes: [inMarketIndex, outMarketIndex],
8576
- });
8577
-
8578
- const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
8579
- const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
8580
-
8581
- if (this.isToken2022(inSpotMarket) || this.isToken2022(outSpotMarket)) {
8582
- remainingAccounts.push({
8583
- pubkey: inSpotMarket.mint,
8584
- isWritable: false,
8585
- isSigner: false,
8586
- });
8587
- remainingAccounts.push({
8588
- pubkey: outSpotMarket.mint,
8589
- isWritable: false,
8590
- isSigner: false,
8591
- });
8592
- if (this.isTransferHook(inSpotMarket)) {
8593
- this.addExtraAccountMetasToRemainingAccounts(
8594
- inSpotMarket.mint,
8595
- remainingAccounts
8596
- );
8597
- }
8598
- if (this.isTransferHook(outSpotMarket)) {
8599
- this.addExtraAccountMetasToRemainingAccounts(
8600
- outSpotMarket.mint,
8601
- remainingAccounts
8602
- );
8603
- }
8604
- }
8605
-
8606
- const ifRebalanceConfig = getIfRebalanceConfigPublicKey(
8607
- this.program.programId,
8608
- inMarketIndex,
8609
- outMarketIndex
8610
- );
8611
-
8612
- const beginSwapIx = await this.program.instruction.beginInsuranceFundSwap(
8613
- inMarketIndex,
8614
- outMarketIndex,
8615
- amountIn,
8616
- {
8617
- accounts: {
8618
- state: await this.getStatePublicKey(),
8619
- authority: this.wallet.publicKey,
8620
- outInsuranceFundVault: outSpotMarket.insuranceFund.vault,
8621
- inInsuranceFundVault: inSpotMarket.insuranceFund.vault,
8622
- outTokenAccount,
8623
- inTokenAccount,
8624
- ifRebalanceConfig: ifRebalanceConfig,
8625
- tokenProgram: TOKEN_PROGRAM_ID,
8626
- driftSigner: this.getStateAccount().signer,
8627
- instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
8628
- },
8629
- remainingAccounts,
8630
- }
8631
- );
8632
-
8633
- const endSwapIx = await this.program.instruction.endInsuranceFundSwap(
8634
- inMarketIndex,
8635
- outMarketIndex,
8636
- {
8637
- accounts: {
8638
- state: await this.getStatePublicKey(),
8639
- authority: this.wallet.publicKey,
8640
- outInsuranceFundVault: outSpotMarket.insuranceFund.vault,
8641
- inInsuranceFundVault: inSpotMarket.insuranceFund.vault,
8642
- outTokenAccount,
8643
- inTokenAccount,
8644
- ifRebalanceConfig: ifRebalanceConfig,
8645
- tokenProgram: TOKEN_PROGRAM_ID,
8646
- driftSigner: this.getStateAccount().signer,
8897
+ velocitySigner: this.getStateAccount().signer,
8647
8898
  instructions: SYSVAR_INSTRUCTIONS_PUBKEY,
8648
8899
  },
8649
8900
  remainingAccounts,
@@ -8679,8 +8930,8 @@ export class VelocityClient {
8679
8930
  [],
8680
8931
  this.opts
8681
8932
  );
8682
- this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
8683
- this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
8933
+ this.cachePerpMarketSlot(slot, perpMarketIndex);
8934
+ this.cacheSpotMarketSlot(slot, liabilityMarketIndex);
8684
8935
  return txSig;
8685
8936
  }
8686
8937
 
@@ -8704,7 +8955,10 @@ export class VelocityClient {
8704
8955
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8705
8956
 
8706
8957
  const remainingAccounts = this.getRemainingAccounts({
8707
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
8958
+ userAccounts: [
8959
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
8960
+ userAccount,
8961
+ ],
8708
8962
  writablePerpMarketIndexes: [perpMarketIndex],
8709
8963
  writableSpotMarketIndexes: [liabilityMarketIndex],
8710
8964
  });
@@ -8754,8 +9008,8 @@ export class VelocityClient {
8754
9008
  [],
8755
9009
  this.opts
8756
9010
  );
8757
- this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
8758
- this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
9011
+ this.cachePerpMarketSlot(slot, perpMarketIndex);
9012
+ this.cacheSpotMarketSlot(slot, assetMarketIndex);
8759
9013
  return txSig;
8760
9014
  }
8761
9015
 
@@ -8779,7 +9033,10 @@ export class VelocityClient {
8779
9033
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8780
9034
 
8781
9035
  const remainingAccounts = this.getRemainingAccounts({
8782
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
9036
+ userAccounts: [
9037
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
9038
+ userAccount,
9039
+ ],
8783
9040
  writablePerpMarketIndexes: [perpMarketIndex],
8784
9041
  writableSpotMarketIndexes: [assetMarketIndex],
8785
9042
  });
@@ -8843,7 +9100,10 @@ export class VelocityClient {
8843
9100
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8844
9101
 
8845
9102
  const remainingAccounts = this.getRemainingAccounts({
8846
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
9103
+ userAccounts: [
9104
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
9105
+ userAccount,
9106
+ ],
8847
9107
  writablePerpMarketIndexes: [marketIndex],
8848
9108
  writableSpotMarketIndexes: [QUOTE_SPOT_MARKET_INDEX],
8849
9109
  });
@@ -8863,7 +9123,7 @@ export class VelocityClient {
8863
9123
  liquidatorStats: liquidatorStatsPublicKey,
8864
9124
  spotMarketVault: spotMarket.vault,
8865
9125
  insuranceFundVault: spotMarket.insuranceFund.vault,
8866
- driftSigner: this.getSignerPublicKey(),
9126
+ velocitySigner: this.getSignerPublicKey(),
8867
9127
  tokenProgram: TOKEN_PROGRAM_ID,
8868
9128
  },
8869
9129
  remainingAccounts: remainingAccounts,
@@ -8910,11 +9170,14 @@ export class VelocityClient {
8910
9170
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
8911
9171
 
8912
9172
  const remainingAccounts = this.getRemainingAccounts({
8913
- userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
9173
+ userAccounts: [
9174
+ this.getUserAccountOrThrow(liquidatorSubAccountId),
9175
+ userAccount,
9176
+ ],
8914
9177
  writableSpotMarketIndexes: [marketIndex],
8915
9178
  });
8916
9179
 
8917
- const spotMarket = this.getSpotMarketAccount(marketIndex);
9180
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
8918
9181
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
8919
9182
 
8920
9183
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
@@ -8935,7 +9198,7 @@ export class VelocityClient {
8935
9198
  liquidator,
8936
9199
  spotMarketVault: spotMarket.vault,
8937
9200
  insuranceFundVault: spotMarket.insuranceFund.vault,
8938
- driftSigner: this.getSignerPublicKey(),
9201
+ velocitySigner: this.getSignerPublicKey(),
8939
9202
  tokenProgram: tokenProgramId,
8940
9203
  },
8941
9204
  remainingAccounts: remainingAccounts,
@@ -8993,17 +9256,17 @@ export class VelocityClient {
8993
9256
  public async getUpdatePrelaunchOracleIx(
8994
9257
  perpMarketIndex: number
8995
9258
  ): Promise<TransactionInstruction> {
8996
- const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
9259
+ const perpMarket = this.getPerpMarketAccountOrThrow(perpMarketIndex);
8997
9260
 
8998
- if (!isVariant(perpMarket.amm.oracleSource, 'prelaunch')) {
8999
- throw new Error(`Wrong oracle source ${perpMarket.amm.oracleSource}`);
9261
+ if (!isVariant(perpMarket.oracleSource, 'prelaunch')) {
9262
+ throw new Error(`Wrong oracle source ${perpMarket.oracleSource}`);
9000
9263
  }
9001
9264
 
9002
9265
  return await this.program.instruction.updatePrelaunchOracle({
9003
9266
  accounts: {
9004
9267
  state: await this.getStatePublicKey(),
9005
9268
  perpMarket: perpMarket.pubkey,
9006
- oracle: perpMarket.amm.oracle,
9269
+ oracle: perpMarket.oracle,
9007
9270
  },
9008
9271
  });
9009
9272
  }
@@ -9028,7 +9291,7 @@ export class VelocityClient {
9028
9291
  perpMarketIndex: number,
9029
9292
  makers: [PublicKey, PublicKey][]
9030
9293
  ): Promise<TransactionInstruction> {
9031
- const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
9294
+ const perpMarket = this.getPerpMarketAccountOrThrow(perpMarketIndex);
9032
9295
 
9033
9296
  const remainingAccounts = [];
9034
9297
  for (const [maker, makerStats] of makers) {
@@ -9048,7 +9311,7 @@ export class VelocityClient {
9048
9311
  accounts: {
9049
9312
  state: await this.getStatePublicKey(),
9050
9313
  perpMarket: perpMarket.pubkey,
9051
- oracle: perpMarket.amm.oracle,
9314
+ oracle: perpMarket.oracle,
9052
9315
  authority: this.wallet.publicKey,
9053
9316
  keeperStats: this.getUserStatsAccountPublicKey(),
9054
9317
  },
@@ -9107,23 +9370,28 @@ export class VelocityClient {
9107
9370
  }
9108
9371
 
9109
9372
  public getOracleDataForPerpMarket(marketIndex: number): OraclePriceData {
9110
- return this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(
9111
- marketIndex
9112
- ).data;
9373
+ const oraclePriceDataAndSlot =
9374
+ this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(
9375
+ marketIndex
9376
+ );
9377
+ if (!oraclePriceDataAndSlot) {
9378
+ throw new Error(`No oracle price data for perp market ${marketIndex}`);
9379
+ }
9380
+ return oraclePriceDataAndSlot.data;
9113
9381
  }
9114
9382
 
9115
9383
  public getMMOracleDataForPerpMarket(marketIndex: number): MMOraclePriceData {
9116
- const perpMarket = this.getPerpMarketAccount(marketIndex);
9384
+ const perpMarket = this.getPerpMarketAccountOrThrow(marketIndex);
9117
9385
  const oracleData = this.getOracleDataForPerpMarket(marketIndex);
9118
9386
  const stateAccountAndSlot = this.accountSubscriber.getStateAccountAndSlot();
9119
- const isMMOracleActive = !perpMarket.amm.mmOracleSlot.eq(ZERO);
9120
- const pctDiff = perpMarket.amm.mmOraclePrice
9387
+ const isMMOracleActive = !perpMarket.marketStats.mmOracleSlot.eq(ZERO);
9388
+ const pctDiff = perpMarket.marketStats.mmOraclePrice
9121
9389
  .sub(oracleData.price)
9122
9390
  .abs()
9123
9391
  .mul(PERCENTAGE_PRECISION)
9124
9392
  .div(BN.max(oracleData.price, ONE));
9125
9393
 
9126
- const mmOracleSequenceId = perpMarket.amm.mmOracleSequenceId;
9394
+ const mmOracleSequenceId = perpMarket.marketStats.mmOracleSequenceId;
9127
9395
 
9128
9396
  // Do slot check for recency if sequence ids are zero or they're too divergent
9129
9397
  const doSlotCheckForRecency =
@@ -9131,48 +9399,49 @@ export class VelocityClient {
9131
9399
  oracleData.sequenceId.eq(ZERO) ||
9132
9400
  mmOracleSequenceId.eq(ZERO) ||
9133
9401
  oracleData.sequenceId
9134
- .sub(perpMarket.amm.mmOracleSequenceId)
9402
+ .sub(perpMarket.marketStats.mmOracleSequenceId)
9135
9403
  .abs()
9136
9404
  .gt(oracleData.sequenceId.div(new BN(10_000)));
9137
9405
 
9138
9406
  let isExchangeOracleMoreRecent = true;
9139
9407
  if (
9140
9408
  doSlotCheckForRecency &&
9141
- oracleData.slot <= perpMarket.amm.mmOracleSlot
9409
+ oracleData.slot.lte(perpMarket.marketStats.mmOracleSlot)
9142
9410
  ) {
9143
9411
  isExchangeOracleMoreRecent = false;
9144
9412
  } else if (
9145
9413
  !doSlotCheckForRecency &&
9146
- oracleData.sequenceId < mmOracleSequenceId
9414
+ oracleData.sequenceId != null &&
9415
+ oracleData.sequenceId.lt(mmOracleSequenceId)
9147
9416
  ) {
9148
9417
  isExchangeOracleMoreRecent = false;
9149
9418
  }
9150
9419
 
9151
9420
  const conf = getOracleConfidenceFromMMOracleData(
9152
- perpMarket.amm.mmOraclePrice,
9421
+ perpMarket.marketStats.mmOraclePrice,
9153
9422
  oracleData
9154
9423
  );
9155
9424
 
9156
9425
  if (
9157
9426
  isOracleTooDivergent(
9158
- perpMarket.amm,
9427
+ perpMarket.marketStats,
9159
9428
  {
9160
- price: perpMarket.amm.mmOraclePrice,
9161
- slot: perpMarket.amm.mmOracleSlot,
9429
+ price: perpMarket.marketStats.mmOraclePrice,
9430
+ slot: perpMarket.marketStats.mmOracleSlot,
9162
9431
  confidence: conf,
9163
9432
  hasSufficientNumberOfDataPoints: true,
9164
9433
  },
9165
9434
  stateAccountAndSlot.data.oracleGuardRails
9166
9435
  ) ||
9167
- perpMarket.amm.mmOraclePrice.eq(ZERO) ||
9436
+ perpMarket.marketStats.mmOraclePrice.eq(ZERO) ||
9168
9437
  isExchangeOracleMoreRecent ||
9169
9438
  pctDiff.gt(PERCENTAGE_PRECISION.divn(100)) // 1% threshold
9170
9439
  ) {
9171
9440
  return { ...oracleData, isMMOracleActive };
9172
9441
  } else {
9173
9442
  return {
9174
- price: perpMarket.amm.mmOraclePrice,
9175
- slot: perpMarket.amm.mmOracleSlot,
9443
+ price: perpMarket.marketStats.mmOraclePrice,
9444
+ slot: perpMarket.marketStats.mmOracleSlot,
9176
9445
  confidence: conf,
9177
9446
  hasSufficientNumberOfDataPoints: true,
9178
9447
  isMMOracleActive,
@@ -9181,9 +9450,14 @@ export class VelocityClient {
9181
9450
  }
9182
9451
 
9183
9452
  public getOracleDataForSpotMarket(marketIndex: number): OraclePriceData {
9184
- return this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(
9185
- marketIndex
9186
- ).data;
9453
+ const oraclePriceDataAndSlot =
9454
+ this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(
9455
+ marketIndex
9456
+ );
9457
+ if (!oraclePriceDataAndSlot) {
9458
+ throw new Error(`No oracle price data for spot market ${marketIndex}`);
9459
+ }
9460
+ return oraclePriceDataAndSlot.data;
9187
9461
  }
9188
9462
 
9189
9463
  public async initializeInsuranceFundStake(
@@ -9212,7 +9486,7 @@ export class VelocityClient {
9212
9486
 
9213
9487
  const accounts = {
9214
9488
  insuranceFundStake: ifStakeAccountPublicKey,
9215
- spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
9489
+ spotMarket: this.getSpotMarketAccountOrThrow(marketIndex).pubkey,
9216
9490
  userStats: getUserStatsAccountPublicKey(
9217
9491
  this.program.programId,
9218
9492
  this.wallet.publicKey // only allow payer to initialize own insurance fund stake account
@@ -9237,14 +9511,14 @@ export class VelocityClient {
9237
9511
  amount: BN,
9238
9512
  collateralAccountPublicKey: PublicKey
9239
9513
  ): Promise<TransactionInstruction> {
9240
- const spotMarket = this.getSpotMarketAccount(marketIndex);
9514
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
9241
9515
  const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9242
9516
  this.program.programId,
9243
9517
  this.wallet.publicKey,
9244
9518
  marketIndex
9245
9519
  );
9246
9520
 
9247
- const remainingAccounts = [];
9521
+ const remainingAccounts: AccountMeta[] = [];
9248
9522
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
9249
9523
  if (this.isTransferHook(spotMarket)) {
9250
9524
  await this.addExtraAccountMetasToRemainingAccounts(
@@ -9269,7 +9543,7 @@ export class VelocityClient {
9269
9543
  authority: this.wallet.publicKey,
9270
9544
  spotMarketVault: spotMarket.vault,
9271
9545
  insuranceFundVault: spotMarket.insuranceFund.vault,
9272
- driftSigner: this.getSignerPublicKey(),
9546
+ velocitySigner: this.getSignerPublicKey(),
9273
9547
  userTokenAccount: collateralAccountPublicKey,
9274
9548
  tokenProgram,
9275
9549
  },
@@ -9360,7 +9634,7 @@ export class VelocityClient {
9360
9634
  }): Promise<TransactionInstruction[]> {
9361
9635
  const addIfStakeIxs = [];
9362
9636
 
9363
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
9637
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
9364
9638
  const isSolMarket = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);
9365
9639
  const createWSOLTokenAccount =
9366
9640
  isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
@@ -9453,7 +9727,7 @@ export class VelocityClient {
9453
9727
  amount: BN,
9454
9728
  txParams?: TxParams
9455
9729
  ): Promise<TransactionSignature> {
9456
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
9730
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
9457
9731
  const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9458
9732
  this.program.programId,
9459
9733
  this.wallet.publicKey,
@@ -9486,7 +9760,7 @@ export class VelocityClient {
9486
9760
  marketIndex: number,
9487
9761
  txParams?: TxParams
9488
9762
  ): Promise<TransactionSignature> {
9489
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
9763
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
9490
9764
  const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9491
9765
  this.program.programId,
9492
9766
  this.wallet.publicKey,
@@ -9521,7 +9795,7 @@ export class VelocityClient {
9521
9795
  txParams?: TxParams
9522
9796
  ): Promise<TransactionSignature> {
9523
9797
  const removeIfStakeIxs = [];
9524
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
9798
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
9525
9799
  const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9526
9800
  this.program.programId,
9527
9801
  this.wallet.publicKey,
@@ -9561,7 +9835,7 @@ export class VelocityClient {
9561
9835
  }
9562
9836
  }
9563
9837
 
9564
- const remainingAccounts = [];
9838
+ const remainingAccounts: AccountMeta[] = [];
9565
9839
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
9566
9840
  if (this.isTransferHook(spotMarketAccount)) {
9567
9841
  await this.addExtraAccountMetasToRemainingAccounts(
@@ -9583,7 +9857,7 @@ export class VelocityClient {
9583
9857
  ),
9584
9858
  authority: this.wallet.publicKey,
9585
9859
  insuranceFundVault: spotMarketAccount.insuranceFund.vault,
9586
- driftSigner: this.getSignerPublicKey(),
9860
+ velocitySigner: this.getSignerPublicKey(),
9587
9861
  userTokenAccount: tokenAccount,
9588
9862
  tokenProgram,
9589
9863
  },
@@ -9630,7 +9904,7 @@ export class VelocityClient {
9630
9904
  authority: PublicKey
9631
9905
  ): Promise<TransactionInstruction> {
9632
9906
  const marketIndex = QUOTE_SPOT_MARKET_INDEX;
9633
- const spotMarket = this.getSpotMarketAccount(marketIndex);
9907
+ const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
9634
9908
  const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9635
9909
  this.program.programId,
9636
9910
  authority,
@@ -9655,45 +9929,6 @@ export class VelocityClient {
9655
9929
  return ix;
9656
9930
  }
9657
9931
 
9658
- public async updateUserGovTokenInsuranceStake(
9659
- authority: PublicKey,
9660
- txParams?: TxParams
9661
- ): Promise<TransactionSignature> {
9662
- const ix = await this.getUpdateUserGovTokenInsuranceStakeIx(authority);
9663
- const tx = await this.buildTransaction(ix, txParams);
9664
- const { txSig } = await this.sendTransaction(tx, [], this.opts);
9665
- return txSig;
9666
- }
9667
-
9668
- public async getUpdateUserGovTokenInsuranceStakeIx(
9669
- authority: PublicKey
9670
- ): Promise<TransactionInstruction> {
9671
- const marketIndex = GOV_SPOT_MARKET_INDEX;
9672
- const spotMarket = this.getSpotMarketAccount(marketIndex);
9673
- const ifStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey(
9674
- this.program.programId,
9675
- authority,
9676
- marketIndex
9677
- );
9678
- const userStatsPublicKey = getUserStatsAccountPublicKey(
9679
- this.program.programId,
9680
- authority
9681
- );
9682
-
9683
- const ix = this.program.instruction.updateUserGovTokenInsuranceStake({
9684
- accounts: {
9685
- state: await this.getStatePublicKey(),
9686
- spotMarket: spotMarket.pubkey,
9687
- insuranceFundStake: ifStakeAccountPublicKey,
9688
- userStats: userStatsPublicKey,
9689
- signer: this.wallet.publicKey,
9690
- insuranceFundVault: spotMarket.insuranceFund.vault,
9691
- },
9692
- });
9693
-
9694
- return ix;
9695
- }
9696
-
9697
9932
  public async settleRevenueToInsuranceFund(
9698
9933
  spotMarketIndex: number,
9699
9934
  txParams?: TxParams
@@ -9708,10 +9943,10 @@ export class VelocityClient {
9708
9943
  public async getSettleRevenueToInsuranceFundIx(
9709
9944
  spotMarketIndex: number
9710
9945
  ): Promise<TransactionInstruction> {
9711
- const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
9946
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(spotMarketIndex);
9712
9947
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
9713
9948
 
9714
- const remainingAccounts = [];
9949
+ const remainingAccounts: AccountMeta[] = [];
9715
9950
  this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
9716
9951
  if (this.isTransferHook(spotMarketAccount)) {
9717
9952
  await this.addExtraAccountMetasToRemainingAccounts(
@@ -9727,7 +9962,7 @@ export class VelocityClient {
9727
9962
  state: await this.getStatePublicKey(),
9728
9963
  spotMarket: spotMarketAccount.pubkey,
9729
9964
  spotMarketVault: spotMarketAccount.vault,
9730
- driftSigner: this.getSignerPublicKey(),
9965
+ velocitySigner: this.getSignerPublicKey(),
9731
9966
  insuranceFundVault: spotMarketAccount.insuranceFund.vault,
9732
9967
  tokenProgram: tokenProgramId,
9733
9968
  },
@@ -9737,6 +9972,40 @@ export class VelocityClient {
9737
9972
  return ix;
9738
9973
  }
9739
9974
 
9975
+ public async sweepPerpMarketFees(
9976
+ perpMarketIndex: number,
9977
+ txParams?: TxParams
9978
+ ): Promise<TransactionSignature> {
9979
+ const tx = await this.buildTransaction(
9980
+ await this.getSweepPerpMarketFeesIx(perpMarketIndex),
9981
+ txParams
9982
+ );
9983
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
9984
+ return txSig;
9985
+ }
9986
+
9987
+ public async getSweepPerpMarketFeesIx(
9988
+ perpMarketIndex: number
9989
+ ): Promise<TransactionInstruction> {
9990
+ const perpMarketAccount = this.getPerpMarketAccountOrThrow(perpMarketIndex);
9991
+ const spotMarketAccount = this.getSpotMarketAccountOrThrow(
9992
+ perpMarketAccount.quoteSpotMarketIndex
9993
+ );
9994
+
9995
+ const ix = await this.program.instruction.sweepPerpMarketFees(
9996
+ perpMarketIndex,
9997
+ {
9998
+ accounts: {
9999
+ state: await this.getStatePublicKey(),
10000
+ perpMarket: perpMarketAccount.pubkey,
10001
+ spotMarket: spotMarketAccount.pubkey,
10002
+ oracle: perpMarketAccount.oracle,
10003
+ },
10004
+ }
10005
+ );
10006
+ return ix;
10007
+ }
10008
+
9740
10009
  public async resolvePerpPnlDeficit(
9741
10010
  spotMarketIndex: number,
9742
10011
  perpMarketIndex: number,
@@ -9758,12 +10027,12 @@ export class VelocityClient {
9758
10027
  perpMarketIndex: number
9759
10028
  ): Promise<TransactionInstruction> {
9760
10029
  const remainingAccounts = this.getRemainingAccounts({
9761
- userAccounts: [this.getUserAccount()],
10030
+ userAccounts: [],
9762
10031
  writablePerpMarketIndexes: [perpMarketIndex],
9763
10032
  writableSpotMarketIndexes: [spotMarketIndex],
9764
10033
  });
9765
10034
 
9766
- const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
10035
+ const spotMarket = this.getSpotMarketAccountOrThrow(spotMarketIndex);
9767
10036
  const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
9768
10037
 
9769
10038
  return await this.program.instruction.resolvePerpPnlDeficit(
@@ -9775,7 +10044,7 @@ export class VelocityClient {
9775
10044
  authority: this.wallet.publicKey,
9776
10045
  spotMarketVault: spotMarket.vault,
9777
10046
  insuranceFundVault: spotMarket.insuranceFund.vault,
9778
- driftSigner: this.getSignerPublicKey(),
10047
+ velocitySigner: this.getSignerPublicKey(),
9779
10048
  tokenProgram: tokenProgramId,
9780
10049
  },
9781
10050
  remainingAccounts: remainingAccounts,
@@ -9788,9 +10057,9 @@ export class VelocityClient {
9788
10057
  amount: BN,
9789
10058
  userTokenAccountPublicKey: PublicKey
9790
10059
  ): Promise<TransactionInstruction> {
9791
- const spotMarket = await this.getSpotMarketAccount(marketIndex);
10060
+ const spotMarket = await this.getSpotMarketAccountOrThrow(marketIndex);
9792
10061
 
9793
- const remainingAccounts = [];
10062
+ const remainingAccounts: AccountMeta[] = [];
9794
10063
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
9795
10064
  if (this.isTransferHook(spotMarket)) {
9796
10065
  await this.addExtraAccountMetasToRemainingAccounts(
@@ -9818,7 +10087,7 @@ export class VelocityClient {
9818
10087
  }
9819
10088
 
9820
10089
  /**
9821
- * This ix will donate your funds to drift revenue pool. It does not deposit into your user account
10090
+ * This ix will donate your funds to velocity revenue pool. It does not deposit into your user account
9822
10091
  * @param marketIndex
9823
10092
  * @param amount
9824
10093
  * @param userTokenAccountPublicKey
@@ -9843,12 +10112,14 @@ export class VelocityClient {
9843
10112
  public getPerpMarketExtendedInfo(
9844
10113
  marketIndex: number
9845
10114
  ): PerpMarketExtendedInfo {
9846
- const marketAccount = this.getPerpMarketAccount(marketIndex);
9847
- const quoteAccount = this.getSpotMarketAccount(QUOTE_SPOT_MARKET_INDEX);
10115
+ const marketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
10116
+ const quoteAccount = this.getSpotMarketAccountOrThrow(
10117
+ QUOTE_SPOT_MARKET_INDEX
10118
+ );
9848
10119
 
9849
10120
  const extendedInfo: PerpMarketExtendedInfo = {
9850
10121
  marketIndex,
9851
- minOrderSize: marketAccount.amm?.minOrderSize,
10122
+ minOrderSize: marketAccount.marketStats?.minOrderSize,
9852
10123
  marginMaintenance: marketAccount.marginRatioMaintenance,
9853
10124
  pnlPoolValue: getTokenAmount(
9854
10125
  marketAccount.pnlPool?.scaledBalance,
@@ -9891,11 +10162,11 @@ export class VelocityClient {
9891
10162
  feeTier.makerRebateNumerator / feeTier.makerRebateDenominator;
9892
10163
 
9893
10164
  if (marketIndex !== undefined) {
9894
- let marketAccount = null;
10165
+ let marketAccount: PerpMarketAccount | SpotMarketAccount;
9895
10166
  if (isVariant(marketType, 'perp')) {
9896
- marketAccount = this.getPerpMarketAccount(marketIndex);
10167
+ marketAccount = this.getPerpMarketAccountOrThrow(marketIndex);
9897
10168
  } else {
9898
- marketAccount = this.getSpotMarketAccount(marketIndex);
10169
+ marketAccount = this.getSpotMarketAccountOrThrow(marketIndex);
9899
10170
  }
9900
10171
 
9901
10172
  takerFee += (takerFee * marketAccount.feeAdjustment) / 100;
@@ -9993,7 +10264,7 @@ export class VelocityClient {
9993
10264
  public async getPauseSpotMarketDepositWithdrawIx(
9994
10265
  spotMarketIndex: number
9995
10266
  ): Promise<TransactionInstruction> {
9996
- const spotMarket = await this.getSpotMarketAccount(spotMarketIndex);
10267
+ const spotMarket = await this.getSpotMarketAccountOrThrow(spotMarketIndex);
9997
10268
  return this.program.instruction.pauseSpotMarketDepositWithdraw({
9998
10269
  accounts: {
9999
10270
  state: await this.getStatePublicKey(),
@@ -10055,7 +10326,7 @@ export class VelocityClient {
10055
10326
  programId: this.program.programId,
10056
10327
  keys: [
10057
10328
  {
10058
- pubkey: this.getPerpMarketAccount(marketIndex).pubkey,
10329
+ pubkey: this.getPerpMarketAccountOrThrow(marketIndex).pubkey,
10059
10330
  isWritable: true,
10060
10331
  isSigner: false,
10061
10332
  },
@@ -10111,7 +10382,7 @@ export class VelocityClient {
10111
10382
  programId: this.program.programId,
10112
10383
  keys: [
10113
10384
  {
10114
- pubkey: this.getPerpMarketAccount(marketIndex).pubkey,
10385
+ pubkey: this.getPerpMarketAccountOrThrow(marketIndex).pubkey,
10115
10386
  isWritable: true,
10116
10387
  isSigner: false,
10117
10388
  },
@@ -10285,7 +10556,7 @@ export class VelocityClient {
10285
10556
  state: await this.getStatePublicKey(),
10286
10557
  keeper: this.wallet.publicKey,
10287
10558
  ammCache: getAmmCachePublicKey(this.program.programId),
10288
- quoteMarket: this.getSpotMarketAccount(0).pubkey,
10559
+ quoteMarket: this.getSpotMarketAccountOrThrow(0).pubkey,
10289
10560
  },
10290
10561
  remainingAccounts,
10291
10562
  });
@@ -10308,7 +10579,9 @@ export class VelocityClient {
10308
10579
  public async getUpdateConstituentOracleInfoIx(
10309
10580
  constituent: ConstituentAccount
10310
10581
  ): Promise<TransactionInstruction> {
10311
- const spotMarket = this.getSpotMarketAccount(constituent.spotMarketIndex);
10582
+ const spotMarket = this.getSpotMarketAccountOrThrow(
10583
+ constituent.spotMarketIndex
10584
+ );
10312
10585
  return this.program.instruction.updateConstituentOracleInfo({
10313
10586
  accounts: {
10314
10587
  keeper: this.wallet.publicKey,
@@ -10371,11 +10644,11 @@ export class VelocityClient {
10371
10644
  outMarketIndex
10372
10645
  );
10373
10646
  const userInTokenAccount = await getAssociatedTokenAddress(
10374
- this.getSpotMarketAccount(inMarketIndex).mint,
10647
+ this.getSpotMarketAccountOrThrow(inMarketIndex).mint,
10375
10648
  userAuthority
10376
10649
  );
10377
10650
  const userOutTokenAccount = await getAssociatedTokenAddress(
10378
- this.getSpotMarketAccount(outMarketIndex).mint,
10651
+ this.getSpotMarketAccountOrThrow(outMarketIndex).mint,
10379
10652
  userAuthority
10380
10653
  );
10381
10654
  const inConstituent = getConstituentPublicKey(
@@ -10388,8 +10661,8 @@ export class VelocityClient {
10388
10661
  lpPool,
10389
10662
  outMarketIndex
10390
10663
  );
10391
- const inMarketMint = this.getSpotMarketAccount(inMarketIndex).mint;
10392
- const outMarketMint = this.getSpotMarketAccount(outMarketIndex).mint;
10664
+ const inMarketMint = this.getSpotMarketAccountOrThrow(inMarketIndex).mint;
10665
+ const outMarketMint = this.getSpotMarketAccountOrThrow(outMarketIndex).mint;
10393
10666
 
10394
10667
  const constituentTargetBase = getConstituentTargetBasePublicKey(
10395
10668
  this.program.programId,
@@ -10490,7 +10763,7 @@ export class VelocityClient {
10490
10763
  {
10491
10764
  remainingAccounts,
10492
10765
  accounts: {
10493
- driftSigner: this.getSignerPublicKey(),
10766
+ velocitySigner: this.getSignerPublicKey(),
10494
10767
  state: await this.getStatePublicKey(),
10495
10768
  lpPool,
10496
10769
  constituentTargetBase,
@@ -10587,7 +10860,7 @@ export class VelocityClient {
10587
10860
  writableSpotMarketIndexes: [inMarketIndex],
10588
10861
  });
10589
10862
 
10590
- const spotMarket = this.getSpotMarketAccount(inMarketIndex);
10863
+ const spotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
10591
10864
  const inMarketMint = spotMarket.mint;
10592
10865
  const isSolMarket = inMarketMint.equals(WRAPPED_SOL_MINT);
10593
10866
 
@@ -10724,7 +10997,7 @@ export class VelocityClient {
10724
10997
  readableSpotMarketIndexes: [inMarketIndex],
10725
10998
  });
10726
10999
 
10727
- const spotMarket = this.getSpotMarketAccount(inMarketIndex);
11000
+ const spotMarket = this.getSpotMarketAccountOrThrow(inMarketIndex);
10728
11001
  const inMarketMint = spotMarket.mint;
10729
11002
  const inConstituent = getConstituentPublicKey(
10730
11003
  this.program.programId,
@@ -10802,7 +11075,7 @@ export class VelocityClient {
10802
11075
  writableSpotMarketIndexes: [outMarketIndex],
10803
11076
  });
10804
11077
 
10805
- const spotMarket = this.getSpotMarketAccount(outMarketIndex);
11078
+ const spotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
10806
11079
  const outMarketMint = spotMarket.mint;
10807
11080
  const outConstituent = getConstituentPublicKey(
10808
11081
  this.program.programId,
@@ -10848,7 +11121,7 @@ export class VelocityClient {
10848
11121
  {
10849
11122
  remainingAccounts,
10850
11123
  accounts: {
10851
- driftSigner: this.getSignerPublicKey(),
11124
+ velocitySigner: this.getSignerPublicKey(),
10852
11125
  state: await this.getStatePublicKey(),
10853
11126
  lpPool: lpPool.pubkey,
10854
11127
  authority: this.wallet.publicKey,
@@ -10913,7 +11186,7 @@ export class VelocityClient {
10913
11186
  writableSpotMarketIndexes: [outMarketIndex],
10914
11187
  });
10915
11188
 
10916
- const spotMarket = this.getSpotMarketAccount(outMarketIndex);
11189
+ const spotMarket = this.getSpotMarketAccountOrThrow(outMarketIndex);
10917
11190
  const outMarketMint = spotMarket.mint;
10918
11191
  const outConstituent = getConstituentPublicKey(
10919
11192
  this.program.programId,
@@ -11013,7 +11286,7 @@ export class VelocityClient {
11013
11286
  ...(await this.getAllSettlePerpToLpPoolIxs(
11014
11287
  lpPool.lpPoolId,
11015
11288
  this.getPerpMarketAccounts()
11016
- .filter((marketAccount) => marketAccount.lpStatus > 0)
11289
+ .filter((marketAccount) => marketAccount.hedgeConfig.status > 0)
11017
11290
  .map((marketAccount) => marketAccount.marketIndex)
11018
11291
  ))
11019
11292
  );
@@ -11152,7 +11425,7 @@ export class VelocityClient {
11152
11425
  remainingAccounts.push(
11153
11426
  ...perpMarketIndexes.map((index) => {
11154
11427
  return {
11155
- pubkey: this.getPerpMarketAccount(index).pubkey,
11428
+ pubkey: this.getPerpMarketAccountOrThrow(index).pubkey,
11156
11429
  isSigner: false,
11157
11430
  isWritable: true,
11158
11431
  };
@@ -11162,7 +11435,7 @@ export class VelocityClient {
11162
11435
  const lpPool = getLpPoolPublicKey(this.program.programId, lpPoolId);
11163
11436
  return this.program.instruction.settlePerpToLpPool({
11164
11437
  accounts: {
11165
- driftSigner: this.getSignerPublicKey(),
11438
+ velocitySigner: this.getSignerPublicKey(),
11166
11439
  state: await this.getStatePublicKey(),
11167
11440
  keeper: this.wallet.publicKey,
11168
11441
  ammCache: getAmmCachePublicKey(this.program.programId),
@@ -11276,7 +11549,7 @@ export class VelocityClient {
11276
11549
  txVersion?: TransactionVersion,
11277
11550
  lookupTables?: AddressLookupTableAccount[],
11278
11551
  forceVersionedTransaction?: boolean
11279
- ): Promise<(Transaction | VersionedTransaction)[]> {
11552
+ ): Promise<(Transaction | VersionedTransaction | undefined)[]> {
11280
11553
  return this.txHandler.buildBulkTransactions({
11281
11554
  instructions,
11282
11555
  txVersion: txVersion ?? this.txVersion,
@@ -11338,9 +11611,9 @@ export class VelocityClient {
11338
11611
 
11339
11612
  isOrderIncreasingPosition(
11340
11613
  orderParams: OptionalOrderParams,
11341
- subAccountId: number
11614
+ subAccountId?: number
11342
11615
  ): boolean {
11343
- const userAccount = this.getUserAccount(subAccountId);
11616
+ const userAccount = this.getUserAccountOrThrow(subAccountId);
11344
11617
  const perpPosition = userAccount.perpPositions.find(
11345
11618
  (p) => p.marketIndex === orderParams.marketIndex
11346
11619
  );
@@ -11356,9 +11629,3 @@ export class VelocityClient {
11356
11629
  return currentBase.add(orderBaseAmount).abs().gt(currentBase.abs());
11357
11630
  }
11358
11631
  }
11359
-
11360
- /** @deprecated Use `VelocityClient` instead. `DriftClient` will be removed in a future major. */
11361
- export const DriftClient = VelocityClient;
11362
-
11363
- /** @deprecated Use `VelocityClient` instead. `DriftClient` will be removed in a future major. */
11364
- export type DriftClient = VelocityClient;