@drift-labs/sdk 2.97.0-beta.9 → 2.98.0-beta.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 (754) hide show
  1. package/README.md +11 -4
  2. package/VERSION +1 -1
  3. package/bun.lockb +0 -0
  4. package/lib/{accounts → browser/accounts}/bulkAccountLoader.d.ts +1 -0
  5. package/lib/browser/accounts/grpcAccountSubscriber.d.ts +16 -0
  6. package/lib/browser/accounts/grpcAccountSubscriber.js +154 -0
  7. package/lib/browser/accounts/grpcDriftClientAccountSubscriber.d.ts +12 -0
  8. package/lib/browser/accounts/grpcDriftClientAccountSubscriber.js +97 -0
  9. package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +10 -0
  10. package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.js +30 -0
  11. package/lib/browser/accounts/grpcProgramAccountSubscriber.d.ts +18 -0
  12. package/lib/browser/accounts/grpcProgramAccountSubscriber.js +171 -0
  13. package/lib/browser/accounts/grpcUserAccountSubscriber.d.ts +10 -0
  14. package/lib/browser/accounts/grpcUserAccountSubscriber.js +28 -0
  15. package/lib/browser/accounts/grpcUserStatsAccountSubscriber.d.ts +10 -0
  16. package/lib/browser/accounts/grpcUserStatsAccountSubscriber.js +28 -0
  17. package/lib/{accounts → browser/accounts}/types.d.ts +8 -0
  18. package/lib/{accounts → browser/accounts}/webSocketAccountSubscriber.d.ts +2 -1
  19. package/lib/{accounts → browser/accounts}/webSocketDriftClientAccountSubscriber.d.ts +3 -3
  20. package/lib/{accounts → browser/accounts}/webSocketProgramAccountSubscriber.d.ts +2 -1
  21. package/lib/{addresses → browser/addresses}/pda.d.ts +1 -0
  22. package/lib/{addresses → browser/addresses}/pda.js +8 -1
  23. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.d.ts +15 -0
  24. package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.js +32 -0
  25. package/lib/{auctionSubscriber → browser/auctionSubscriber}/index.d.ts +1 -0
  26. package/lib/browser/auctionSubscriber/index.js +19 -0
  27. package/lib/{auctionSubscriber → browser/auctionSubscriber}/types.d.ts +2 -0
  28. package/lib/{bankrun → browser/bankrun}/bankrunConnection.d.ts +1 -0
  29. package/lib/{config.js → browser/config.js} +1 -1
  30. package/lib/{constants → browser/constants}/perpMarkets.js +25 -4
  31. package/lib/{constants → browser/constants}/spotMarkets.js +6 -6
  32. package/lib/{decode → browser/decode}/phoenix.d.ts +1 -0
  33. package/lib/{decode → browser/decode}/user.d.ts +1 -0
  34. package/lib/{decode → browser/decode}/user.js +10 -0
  35. package/lib/{dlob → browser/dlob}/DLOBOrders.d.ts +1 -0
  36. package/lib/{driftClient.d.ts → browser/driftClient.d.ts} +25 -7
  37. package/lib/{driftClient.js → browser/driftClient.js} +177 -40
  38. package/lib/{driftClientConfig.d.ts → browser/driftClientConfig.d.ts} +6 -1
  39. package/lib/{idl → browser/idl}/drift.json +281 -4
  40. package/lib/{idl → browser/idl}/switchboard_on_demand_30.json +195 -37
  41. package/lib/{index.d.ts → browser/index.d.ts} +8 -0
  42. package/lib/{index.js → browser/index.js} +8 -0
  43. package/lib/browser/isomorphic/grpc.browser.d.ts +1 -0
  44. package/lib/browser/isomorphic/grpc.browser.js +8 -0
  45. package/lib/browser/isomorphic/grpc.d.ts +1 -0
  46. package/lib/browser/isomorphic/grpc.js +8 -0
  47. package/lib/browser/isomorphic/grpc.node.d.ts +5 -0
  48. package/lib/{math → browser/math}/auction.js +9 -6
  49. package/lib/{math → browser/math}/margin.d.ts +3 -3
  50. package/lib/{math → browser/math}/margin.js +9 -9
  51. package/lib/{math → browser/math}/oracles.d.ts +1 -0
  52. package/lib/{math → browser/math}/position.d.ts +16 -0
  53. package/lib/{math → browser/math}/position.js +30 -3
  54. package/lib/{oracles → browser/oracles}/prelaunchOracleClient.d.ts +1 -0
  55. package/lib/{oracles → browser/oracles}/pythClient.d.ts +1 -1
  56. package/lib/{oracles → browser/oracles}/pythClient.js +1 -2
  57. package/lib/{oracles → browser/oracles}/pythPullClient.d.ts +1 -0
  58. package/lib/{oracles → browser/oracles}/quoteAssetOracleClient.d.ts +1 -0
  59. package/lib/{oracles → browser/oracles}/switchboardClient.d.ts +1 -0
  60. package/lib/{oracles → browser/oracles}/switchboardOnDemandClient.d.ts +1 -0
  61. package/lib/{oracles → browser/oracles}/types.d.ts +1 -0
  62. package/lib/{orderSubscriber → browser/orderSubscriber}/OrderSubscriber.d.ts +3 -1
  63. package/lib/{orderSubscriber → browser/orderSubscriber}/OrderSubscriber.js +18 -13
  64. package/lib/browser/orderSubscriber/grpcSubscription.d.ts +22 -0
  65. package/lib/browser/orderSubscriber/grpcSubscription.js +66 -0
  66. package/lib/{orderSubscriber → browser/orderSubscriber}/types.d.ts +9 -0
  67. package/lib/{token → browser/token}/index.d.ts +1 -0
  68. package/lib/{tx → browser/tx}/baseTxSender.d.ts +4 -1
  69. package/lib/{tx → browser/tx}/baseTxSender.js +9 -4
  70. package/lib/{tx → browser/tx}/fastSingleTxSender.d.ts +3 -1
  71. package/lib/{tx → browser/tx}/fastSingleTxSender.js +6 -5
  72. package/lib/{tx → browser/tx}/forwardOnlyTxSender.d.ts +3 -1
  73. package/lib/{tx → browser/tx}/forwardOnlyTxSender.js +5 -4
  74. package/lib/{tx → browser/tx}/retryTxSender.d.ts +3 -1
  75. package/lib/{tx → browser/tx}/retryTxSender.js +5 -4
  76. package/lib/{tx → browser/tx}/types.d.ts +1 -0
  77. package/lib/{tx → browser/tx}/whileValidTxSender.d.ts +3 -1
  78. package/lib/{tx → browser/tx}/whileValidTxSender.js +5 -4
  79. package/lib/{types.d.ts → browser/types.d.ts} +30 -1
  80. package/lib/{types.js → browser/types.js} +6 -1
  81. package/lib/{user.d.ts → browser/user.d.ts} +1 -1
  82. package/lib/{user.js → browser/user.js} +16 -9
  83. package/lib/{userConfig.d.ts → browser/userConfig.d.ts} +6 -1
  84. package/lib/{userMap → browser/userMap}/WebsocketSubscription.d.ts +1 -0
  85. package/lib/browser/userMap/grpcSubscription.d.ts +24 -0
  86. package/lib/browser/userMap/grpcSubscription.js +40 -0
  87. package/lib/{userMap → browser/userMap}/userMap.js +17 -1
  88. package/lib/{userMap → browser/userMap}/userMapConfig.d.ts +6 -0
  89. package/lib/{userStats.js → browser/userStats.js} +11 -4
  90. package/lib/{userStatsConfig.d.ts → browser/userStatsConfig.d.ts} +6 -0
  91. package/lib/node/accounts/basicUserAccountSubscriber.d.ts +27 -0
  92. package/lib/node/accounts/basicUserAccountSubscriber.js +38 -0
  93. package/lib/node/accounts/bulkAccountLoader.d.ts +37 -0
  94. package/lib/node/accounts/bulkAccountLoader.js +222 -0
  95. package/lib/node/accounts/bulkUserStatsSubscription.d.ts +7 -0
  96. package/lib/node/accounts/bulkUserStatsSubscription.js +21 -0
  97. package/lib/node/accounts/bulkUserSubscription.d.ts +7 -0
  98. package/lib/node/accounts/bulkUserSubscription.js +21 -0
  99. package/lib/node/accounts/fetch.d.ts +6 -0
  100. package/lib/node/accounts/fetch.js +30 -0
  101. package/lib/node/accounts/grpcAccountSubscriber.d.ts +16 -0
  102. package/lib/node/accounts/grpcAccountSubscriber.js +154 -0
  103. package/lib/node/accounts/grpcDriftClientAccountSubscriber.d.ts +12 -0
  104. package/lib/node/accounts/grpcDriftClientAccountSubscriber.js +97 -0
  105. package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +10 -0
  106. package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.js +30 -0
  107. package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts +18 -0
  108. package/lib/node/accounts/grpcProgramAccountSubscriber.js +171 -0
  109. package/lib/node/accounts/grpcUserAccountSubscriber.d.ts +10 -0
  110. package/lib/node/accounts/grpcUserAccountSubscriber.js +28 -0
  111. package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts +10 -0
  112. package/lib/node/accounts/grpcUserStatsAccountSubscriber.js +28 -0
  113. package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts +18 -0
  114. package/lib/node/accounts/oneShotUserAccountSubscriber.js +48 -0
  115. package/lib/node/accounts/pollingDriftClientAccountSubscriber.d.ts +69 -0
  116. package/lib/node/accounts/pollingDriftClientAccountSubscriber.js +415 -0
  117. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +29 -0
  118. package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.js +110 -0
  119. package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts +27 -0
  120. package/lib/node/accounts/pollingOracleAccountSubscriber.js +78 -0
  121. package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts +26 -0
  122. package/lib/node/accounts/pollingTokenAccountSubscriber.js +78 -0
  123. package/lib/node/accounts/pollingUserAccountSubscriber.d.ts +29 -0
  124. package/lib/node/accounts/pollingUserAccountSubscriber.js +102 -0
  125. package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  126. package/lib/node/accounts/pollingUserStatsAccountSubscriber.js +94 -0
  127. package/lib/node/accounts/testBulkAccountLoader.d.ts +4 -0
  128. package/lib/node/accounts/testBulkAccountLoader.js +45 -0
  129. package/lib/node/accounts/types.d.ts +155 -0
  130. package/lib/node/accounts/types.js +16 -0
  131. package/lib/node/accounts/utils.d.ts +8 -0
  132. package/lib/node/accounts/utils.js +39 -0
  133. package/lib/node/accounts/webSocketAccountSubscriber.d.ts +29 -0
  134. package/lib/node/accounts/webSocketAccountSubscriber.js +149 -0
  135. package/lib/node/accounts/webSocketDriftClientAccountSubscriber.d.ts +66 -0
  136. package/lib/node/accounts/webSocketDriftClientAccountSubscriber.js +352 -0
  137. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +23 -0
  138. package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +67 -0
  139. package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts +34 -0
  140. package/lib/node/accounts/webSocketProgramAccountSubscriber.js +127 -0
  141. package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts +23 -0
  142. package/lib/node/accounts/webSocketUserAccountSubscriber.js +61 -0
  143. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts +22 -0
  144. package/lib/node/accounts/webSocketUserStatsAccountSubsriber.js +52 -0
  145. package/lib/node/addresses/marketAddresses.d.ts +2 -0
  146. package/lib/node/addresses/marketAddresses.js +15 -0
  147. package/lib/node/addresses/pda.d.ts +30 -0
  148. package/lib/node/addresses/pda.js +193 -0
  149. package/lib/node/adminClient.d.ts +202 -0
  150. package/lib/node/adminClient.js +1826 -0
  151. package/lib/node/assert/assert.d.ts +1 -0
  152. package/lib/node/assert/assert.js +9 -0
  153. package/lib/node/auctionSubscriber/auctionSubscriber.d.ts +14 -0
  154. package/lib/node/auctionSubscriber/auctionSubscriber.js +32 -0
  155. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts +15 -0
  156. package/lib/node/auctionSubscriber/auctionSubscriberGrpc.js +32 -0
  157. package/lib/node/auctionSubscriber/index.d.ts +3 -0
  158. package/lib/node/auctionSubscriber/index.js +19 -0
  159. package/lib/node/auctionSubscriber/types.d.ts +14 -0
  160. package/lib/node/auctionSubscriber/types.js +2 -0
  161. package/lib/node/bankrun/bankrunConnection.d.ts +74 -0
  162. package/lib/node/bankrun/bankrunConnection.js +318 -0
  163. package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts +27 -0
  164. package/lib/node/blockhashSubscriber/BlockhashSubscriber.js +89 -0
  165. package/lib/node/blockhashSubscriber/index.d.ts +1 -0
  166. package/lib/node/blockhashSubscriber/index.js +17 -0
  167. package/lib/node/blockhashSubscriber/types.d.ts +7 -0
  168. package/lib/node/blockhashSubscriber/types.js +2 -0
  169. package/lib/node/clock/clockSubscriber.d.ts +31 -0
  170. package/lib/node/clock/clockSubscriber.js +80 -0
  171. package/lib/node/config.d.ts +58 -0
  172. package/lib/node/config.js +126 -0
  173. package/lib/node/constants/numericConstants.d.ts +71 -0
  174. package/lib/node/constants/numericConstants.js +75 -0
  175. package/lib/node/constants/perpMarkets.d.ts +19 -0
  176. package/lib/node/constants/perpMarkets.js +868 -0
  177. package/lib/node/constants/spotMarkets.d.ts +23 -0
  178. package/lib/node/constants/spotMarkets.js +361 -0
  179. package/lib/node/constants/txConstants.d.ts +1 -0
  180. package/lib/node/constants/txConstants.js +4 -0
  181. package/lib/node/decode/phoenix.d.ts +7 -0
  182. package/lib/node/decode/phoenix.js +159 -0
  183. package/lib/node/decode/user.d.ts +4 -0
  184. package/lib/node/decode/user.js +339 -0
  185. package/lib/node/dlob/DLOB.d.ts +166 -0
  186. package/lib/node/dlob/DLOB.js +1142 -0
  187. package/lib/node/dlob/DLOBApiClient.d.ts +14 -0
  188. package/lib/node/dlob/DLOBApiClient.js +34 -0
  189. package/lib/node/dlob/DLOBNode.d.ts +57 -0
  190. package/lib/node/dlob/DLOBNode.js +86 -0
  191. package/lib/node/dlob/DLOBOrders.d.ts +17 -0
  192. package/lib/node/dlob/DLOBOrders.js +40 -0
  193. package/lib/node/dlob/DLOBSubscriber.d.ts +54 -0
  194. package/lib/node/dlob/DLOBSubscriber.js +139 -0
  195. package/lib/node/dlob/NodeList.d.ts +27 -0
  196. package/lib/node/dlob/NodeList.js +141 -0
  197. package/lib/node/dlob/dlobIdl.json +248 -0
  198. package/lib/node/dlob/orderBookLevels.d.ts +72 -0
  199. package/lib/node/dlob/orderBookLevels.js +438 -0
  200. package/lib/node/dlob/types.d.ts +18 -0
  201. package/lib/node/dlob/types.js +2 -0
  202. package/lib/node/driftClient.d.ts +829 -0
  203. package/lib/node/driftClient.js +4496 -0
  204. package/lib/node/driftClientConfig.d.ts +49 -0
  205. package/lib/node/driftClientConfig.js +2 -0
  206. package/lib/node/events/eventList.d.ts +22 -0
  207. package/lib/node/events/eventList.js +80 -0
  208. package/lib/node/events/eventSubscriber.d.ts +46 -0
  209. package/lib/node/events/eventSubscriber.js +223 -0
  210. package/lib/node/events/eventsServerLogProvider.d.ts +21 -0
  211. package/lib/node/events/eventsServerLogProvider.js +121 -0
  212. package/lib/node/events/fetchLogs.d.ts +25 -0
  213. package/lib/node/events/fetchLogs.js +99 -0
  214. package/lib/node/events/parse.d.ts +6 -0
  215. package/lib/node/events/parse.js +106 -0
  216. package/lib/node/events/pollingLogProvider.d.ts +17 -0
  217. package/lib/node/events/pollingLogProvider.js +58 -0
  218. package/lib/node/events/sort.d.ts +2 -0
  219. package/lib/node/events/sort.js +24 -0
  220. package/lib/node/events/txEventCache.d.ts +24 -0
  221. package/lib/node/events/txEventCache.js +71 -0
  222. package/lib/node/events/types.d.ts +77 -0
  223. package/lib/node/events/types.js +30 -0
  224. package/lib/node/events/webSocketLogProvider.d.ts +24 -0
  225. package/lib/node/events/webSocketLogProvider.js +96 -0
  226. package/lib/node/factory/bigNum.d.ts +122 -0
  227. package/lib/node/factory/bigNum.js +457 -0
  228. package/lib/node/factory/oracleClient.d.ts +5 -0
  229. package/lib/node/factory/oracleClient.js +52 -0
  230. package/lib/node/idl/drift.json +13656 -0
  231. package/lib/node/idl/openbook.json +3854 -0
  232. package/lib/node/idl/pyth_solana_receiver.json +628 -0
  233. package/lib/node/idl/switchboard.json +8354 -0
  234. package/lib/node/idl/switchboard_on_demand_30.json +4541 -0
  235. package/lib/node/idl/token_faucet.json +142 -0
  236. package/lib/node/index.d.ts +120 -0
  237. package/lib/node/index.js +142 -0
  238. package/lib/node/isomorphic/grpc.browser.d.ts +1 -0
  239. package/lib/node/isomorphic/grpc.d.ts +1 -0
  240. package/lib/node/isomorphic/grpc.js +17 -0
  241. package/lib/node/isomorphic/grpc.node.d.ts +5 -0
  242. package/lib/node/isomorphic/grpc.node.js +17 -0
  243. package/lib/node/jupiter/jupiterClient.d.ts +296 -0
  244. package/lib/node/jupiter/jupiterClient.js +178 -0
  245. package/lib/node/keypair.d.ts +2 -0
  246. package/lib/node/keypair.js +28 -0
  247. package/lib/node/marinade/index.d.ts +12 -0
  248. package/lib/node/marinade/index.js +36 -0
  249. package/lib/node/marinade/types.d.ts +1963 -0
  250. package/lib/node/marinade/types.js +1965 -0
  251. package/lib/node/math/amm.d.ts +98 -0
  252. package/lib/node/math/amm.js +626 -0
  253. package/lib/node/math/auction.d.ts +23 -0
  254. package/lib/node/math/auction.js +130 -0
  255. package/lib/node/math/bankruptcy.d.ts +2 -0
  256. package/lib/node/math/bankruptcy.js +31 -0
  257. package/lib/node/math/conversion.d.ts +2 -0
  258. package/lib/node/math/conversion.js +11 -0
  259. package/lib/node/math/exchangeStatus.d.ts +6 -0
  260. package/lib/node/math/exchangeStatus.js +77 -0
  261. package/lib/node/math/fuel.d.ts +6 -0
  262. package/lib/node/math/fuel.js +55 -0
  263. package/lib/node/math/funding.d.ts +34 -0
  264. package/lib/node/math/funding.js +209 -0
  265. package/lib/node/math/insurance.d.ts +7 -0
  266. package/lib/node/math/insurance.js +73 -0
  267. package/lib/node/math/margin.d.ts +39 -0
  268. package/lib/node/math/margin.js +184 -0
  269. package/lib/node/math/market.d.ts +39 -0
  270. package/lib/node/math/market.js +163 -0
  271. package/lib/node/math/oracles.d.ts +14 -0
  272. package/lib/node/math/oracles.js +134 -0
  273. package/lib/node/math/orders.d.ts +23 -0
  274. package/lib/node/math/orders.js +216 -0
  275. package/lib/node/math/position.d.ts +70 -0
  276. package/lib/node/math/position.js +225 -0
  277. package/lib/node/math/repeg.d.ts +22 -0
  278. package/lib/node/math/repeg.js +164 -0
  279. package/lib/node/math/spotBalance.d.ts +83 -0
  280. package/lib/node/math/spotBalance.js +373 -0
  281. package/lib/node/math/spotMarket.d.ts +11 -0
  282. package/lib/node/math/spotMarket.js +49 -0
  283. package/lib/node/math/spotPosition.d.ts +19 -0
  284. package/lib/node/math/spotPosition.js +78 -0
  285. package/lib/node/math/state.d.ts +5 -0
  286. package/lib/node/math/state.js +30 -0
  287. package/lib/node/math/superStake.d.ts +167 -0
  288. package/lib/node/math/superStake.js +306 -0
  289. package/lib/node/math/tiers.d.ts +4 -0
  290. package/lib/node/math/tiers.js +52 -0
  291. package/lib/node/math/trade.d.ts +117 -0
  292. package/lib/node/math/trade.js +637 -0
  293. package/lib/node/math/utils.d.ts +23 -0
  294. package/lib/node/math/utils.js +112 -0
  295. package/lib/node/memcmp.d.ts +7 -0
  296. package/lib/node/memcmp.js +63 -0
  297. package/lib/node/openbook/openbookV2FulfillmentConfigMap.d.ts +10 -0
  298. package/lib/node/openbook/openbookV2FulfillmentConfigMap.js +17 -0
  299. package/lib/node/openbook/openbookV2Subscriber.d.ts +36 -0
  300. package/lib/node/openbook/openbookV2Subscriber.js +104 -0
  301. package/lib/node/oracles/oracleClientCache.d.ts +9 -0
  302. package/lib/node/oracles/oracleClientCache.js +19 -0
  303. package/lib/node/oracles/prelaunchOracleClient.d.ts +12 -0
  304. package/lib/node/oracles/prelaunchOracleClient.js +24 -0
  305. package/lib/node/oracles/pythClient.d.ts +14 -0
  306. package/lib/node/oracles/pythClient.js +51 -0
  307. package/lib/node/oracles/pythPullClient.d.ts +19 -0
  308. package/lib/node/oracles/pythPullClient.js +60 -0
  309. package/lib/node/oracles/quoteAssetOracleClient.d.ts +10 -0
  310. package/lib/node/oracles/quoteAssetOracleClient.js +21 -0
  311. package/lib/node/oracles/strictOraclePrice.d.ts +9 -0
  312. package/lib/node/oracles/strictOraclePrice.js +17 -0
  313. package/lib/node/oracles/switchboardClient.d.ts +12 -0
  314. package/lib/node/oracles/switchboardClient.js +40 -0
  315. package/lib/node/oracles/switchboardOnDemandClient.d.ts +12 -0
  316. package/lib/node/oracles/switchboardOnDemandClient.js +32 -0
  317. package/lib/node/oracles/types.d.ts +23 -0
  318. package/lib/node/oracles/types.js +2 -0
  319. package/lib/node/orderParams.d.ts +29 -0
  320. package/lib/node/orderParams.js +44 -0
  321. package/lib/node/orderSubscriber/OrderSubscriber.d.ts +42 -0
  322. package/lib/node/orderSubscriber/OrderSubscriber.js +170 -0
  323. package/lib/node/orderSubscriber/PollingSubscription.d.ts +12 -0
  324. package/lib/node/orderSubscriber/PollingSubscription.js +23 -0
  325. package/lib/node/orderSubscriber/WebsocketSubscription.d.ts +23 -0
  326. package/lib/node/orderSubscriber/WebsocketSubscription.js +67 -0
  327. package/lib/node/orderSubscriber/grpcSubscription.d.ts +22 -0
  328. package/lib/node/orderSubscriber/grpcSubscription.js +66 -0
  329. package/lib/node/orderSubscriber/index.d.ts +2 -0
  330. package/lib/{auctionSubscriber → node/orderSubscriber}/index.js +1 -1
  331. package/lib/node/orderSubscriber/types.d.ts +34 -0
  332. package/lib/node/orderSubscriber/types.js +2 -0
  333. package/lib/node/phoenix/phoenixFulfillmentConfigMap.d.ts +10 -0
  334. package/lib/node/phoenix/phoenixFulfillmentConfigMap.js +17 -0
  335. package/lib/node/phoenix/phoenixSubscriber.d.ts +41 -0
  336. package/lib/node/phoenix/phoenixSubscriber.js +152 -0
  337. package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts +5 -0
  338. package/lib/node/priorityFee/averageOverSlotsStrategy.js +16 -0
  339. package/lib/node/priorityFee/averageStrategy.d.ts +5 -0
  340. package/lib/node/priorityFee/averageStrategy.js +11 -0
  341. package/lib/node/priorityFee/driftPriorityFeeMethod.d.ts +13 -0
  342. package/lib/node/priorityFee/driftPriorityFeeMethod.js +26 -0
  343. package/lib/node/priorityFee/ewmaStrategy.d.ts +11 -0
  344. package/lib/node/priorityFee/ewmaStrategy.js +33 -0
  345. package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts +20 -0
  346. package/lib/node/priorityFee/heliusPriorityFeeMethod.js +46 -0
  347. package/lib/node/priorityFee/index.d.ts +11 -0
  348. package/lib/node/priorityFee/index.js +27 -0
  349. package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts +5 -0
  350. package/lib/node/priorityFee/maxOverSlotsStrategy.js +17 -0
  351. package/lib/node/priorityFee/maxStrategy.d.ts +7 -0
  352. package/lib/node/priorityFee/maxStrategy.js +9 -0
  353. package/lib/node/priorityFee/priorityFeeSubscriber.d.ts +46 -0
  354. package/lib/node/priorityFee/priorityFeeSubscriber.js +188 -0
  355. package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts +48 -0
  356. package/lib/node/priorityFee/priorityFeeSubscriberMap.js +88 -0
  357. package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts +6 -0
  358. package/lib/node/priorityFee/solanaPriorityFeeMethod.js +21 -0
  359. package/lib/node/priorityFee/types.d.ts +31 -0
  360. package/lib/node/priorityFee/types.js +10 -0
  361. package/lib/node/serum/serumFulfillmentConfigMap.d.ts +10 -0
  362. package/lib/node/serum/serumFulfillmentConfigMap.js +17 -0
  363. package/lib/node/serum/serumSubscriber.d.ts +32 -0
  364. package/lib/node/serum/serumSubscriber.js +107 -0
  365. package/lib/node/serum/types.d.ts +13 -0
  366. package/lib/node/serum/types.js +2 -0
  367. package/lib/node/slot/SlotSubscriber.d.ts +27 -0
  368. package/lib/node/slot/SlotSubscriber.js +71 -0
  369. package/lib/node/testClient.d.ts +8 -0
  370. package/lib/node/testClient.js +23 -0
  371. package/lib/node/token/index.d.ts +5 -0
  372. package/lib/node/token/index.js +15 -0
  373. package/lib/node/tokenFaucet.d.ts +41 -0
  374. package/lib/node/tokenFaucet.js +188 -0
  375. package/lib/node/tx/baseTxSender.d.ts +57 -0
  376. package/lib/node/tx/baseTxSender.js +293 -0
  377. package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +8 -0
  378. package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.js +13 -0
  379. package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +28 -0
  380. package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.js +73 -0
  381. package/lib/node/tx/blockhashFetcher/types.d.ts +4 -0
  382. package/lib/node/tx/blockhashFetcher/types.js +2 -0
  383. package/lib/node/tx/fastSingleTxSender.d.ts +41 -0
  384. package/lib/node/tx/fastSingleTxSender.js +86 -0
  385. package/lib/node/tx/forwardOnlyTxSender.d.ts +37 -0
  386. package/lib/node/tx/forwardOnlyTxSender.js +92 -0
  387. package/lib/node/tx/priorityFeeCalculator.d.ts +44 -0
  388. package/lib/node/tx/priorityFeeCalculator.js +85 -0
  389. package/lib/node/tx/reportTransactionError.d.ts +20 -0
  390. package/lib/node/tx/reportTransactionError.js +103 -0
  391. package/lib/node/tx/retryTxSender.d.ts +37 -0
  392. package/lib/node/tx/retryTxSender.js +86 -0
  393. package/lib/node/tx/txHandler.d.ts +154 -0
  394. package/lib/node/tx/txHandler.js +453 -0
  395. package/lib/node/tx/txParamProcessor.d.ts +25 -0
  396. package/lib/node/tx/txParamProcessor.js +88 -0
  397. package/lib/node/tx/types.d.ts +29 -0
  398. package/lib/node/tx/types.js +20 -0
  399. package/lib/node/tx/utils.d.ts +2 -0
  400. package/lib/node/tx/utils.js +10 -0
  401. package/lib/node/tx/whileValidTxSender.d.ts +44 -0
  402. package/lib/node/tx/whileValidTxSender.js +166 -0
  403. package/lib/node/types.d.ts +1351 -0
  404. package/lib/node/types.js +347 -0
  405. package/lib/node/user.d.ts +411 -0
  406. package/lib/node/user.js +2161 -0
  407. package/lib/node/userConfig.d.ts +26 -0
  408. package/lib/node/userConfig.js +2 -0
  409. package/lib/node/userMap/PollingSubscription.d.ts +16 -0
  410. package/lib/node/userMap/PollingSubscription.js +30 -0
  411. package/lib/node/userMap/WebsocketSubscription.d.ts +25 -0
  412. package/lib/node/userMap/WebsocketSubscription.js +41 -0
  413. package/lib/node/userMap/grpcSubscription.d.ts +24 -0
  414. package/lib/node/userMap/grpcSubscription.js +40 -0
  415. package/lib/node/userMap/userMap.d.ts +88 -0
  416. package/lib/node/userMap/userMap.js +455 -0
  417. package/lib/node/userMap/userMapConfig.d.ts +37 -0
  418. package/lib/node/userMap/userMapConfig.js +2 -0
  419. package/lib/node/userMap/userStatsMap.d.ts +46 -0
  420. package/lib/node/userMap/userStatsMap.js +165 -0
  421. package/lib/node/userName.d.ts +5 -0
  422. package/lib/node/userName.js +21 -0
  423. package/lib/node/userStats.d.ts +19 -0
  424. package/lib/node/userStats.js +65 -0
  425. package/lib/node/userStatsConfig.d.ts +25 -0
  426. package/lib/node/userStatsConfig.js +2 -0
  427. package/lib/node/util/TransactionConfirmationManager.d.ts +16 -0
  428. package/lib/node/util/TransactionConfirmationManager.js +174 -0
  429. package/lib/node/util/chainClock.d.ts +17 -0
  430. package/lib/node/util/chainClock.js +29 -0
  431. package/lib/node/util/computeUnits.d.ts +8 -0
  432. package/lib/node/util/computeUnits.js +46 -0
  433. package/lib/node/util/promiseTimeout.d.ts +1 -0
  434. package/lib/node/util/promiseTimeout.js +14 -0
  435. package/lib/node/util/pythPullOracleUtils.d.ts +2 -0
  436. package/lib/node/util/pythPullOracleUtils.js +15 -0
  437. package/lib/node/util/tps.d.ts +2 -0
  438. package/lib/node/util/tps.js +16 -0
  439. package/lib/node/wallet.d.ts +11 -0
  440. package/lib/node/wallet.js +32 -0
  441. package/package.json +8 -4
  442. package/scripts/postbuild.js +61 -0
  443. package/src/accounts/grpcAccountSubscriber.ts +160 -0
  444. package/src/accounts/grpcDriftClientAccountSubscriber.ts +197 -0
  445. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +56 -0
  446. package/src/accounts/grpcProgramAccountSubscriber.ts +190 -0
  447. package/src/accounts/grpcUserAccountSubscriber.ts +48 -0
  448. package/src/accounts/grpcUserStatsAccountSubscriber.ts +50 -0
  449. package/src/accounts/types.ts +8 -0
  450. package/src/accounts/webSocketAccountSubscriber.ts +1 -1
  451. package/src/accounts/webSocketDriftClientAccountSubscriber.ts +3 -3
  452. package/src/accounts/webSocketProgramAccountSubscriber.ts +1 -1
  453. package/src/addresses/pda.ts +13 -0
  454. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +70 -0
  455. package/src/auctionSubscriber/index.ts +1 -0
  456. package/src/auctionSubscriber/types.ts +2 -0
  457. package/src/config.ts +1 -1
  458. package/src/constants/perpMarkets.ts +26 -4
  459. package/src/constants/spotMarkets.ts +6 -6
  460. package/src/decode/user.ts +11 -1
  461. package/src/driftClient.ts +243 -29
  462. package/src/driftClientConfig.ts +7 -1
  463. package/src/idl/drift.json +281 -4
  464. package/src/idl/switchboard_on_demand_30.json +195 -37
  465. package/src/index.ts +8 -0
  466. package/src/isomorphic/README.md +19 -0
  467. package/src/isomorphic/grpc.browser.ts +4 -0
  468. package/src/isomorphic/grpc.node.ts +23 -0
  469. package/src/isomorphic/grpc.ts +1 -0
  470. package/src/math/auction.ts +7 -6
  471. package/src/math/margin.ts +15 -11
  472. package/src/math/position.ts +44 -2
  473. package/src/oracles/pythClient.ts +1 -5
  474. package/src/orderSubscriber/OrderSubscriber.ts +14 -11
  475. package/src/orderSubscriber/grpcSubscription.ts +121 -0
  476. package/src/orderSubscriber/types.ts +10 -0
  477. package/src/tx/baseTxSender.ts +21 -13
  478. package/src/tx/fastSingleTxSender.ts +6 -3
  479. package/src/tx/forwardOnlyTxSender.ts +4 -1
  480. package/src/tx/retryTxSender.ts +5 -2
  481. package/src/tx/whileValidTxSender.ts +5 -2
  482. package/src/types.ts +35 -1
  483. package/src/user.ts +24 -7
  484. package/src/userConfig.ts +7 -1
  485. package/src/userMap/grpcSubscription.ts +78 -0
  486. package/src/userMap/userMap.ts +21 -2
  487. package/src/userMap/userMapConfig.ts +7 -0
  488. package/src/userStats.ts +11 -0
  489. package/src/userStatsConfig.ts +7 -0
  490. package/tsconfig.browser.json +13 -0
  491. package/tsconfig.json +1 -1
  492. /package/lib/{accounts → browser/accounts}/basicUserAccountSubscriber.d.ts +0 -0
  493. /package/lib/{accounts → browser/accounts}/basicUserAccountSubscriber.js +0 -0
  494. /package/lib/{accounts → browser/accounts}/bulkAccountLoader.js +0 -0
  495. /package/lib/{accounts → browser/accounts}/bulkUserStatsSubscription.d.ts +0 -0
  496. /package/lib/{accounts → browser/accounts}/bulkUserStatsSubscription.js +0 -0
  497. /package/lib/{accounts → browser/accounts}/bulkUserSubscription.d.ts +0 -0
  498. /package/lib/{accounts → browser/accounts}/bulkUserSubscription.js +0 -0
  499. /package/lib/{accounts → browser/accounts}/fetch.d.ts +0 -0
  500. /package/lib/{accounts → browser/accounts}/fetch.js +0 -0
  501. /package/lib/{accounts → browser/accounts}/oneShotUserAccountSubscriber.d.ts +0 -0
  502. /package/lib/{accounts → browser/accounts}/oneShotUserAccountSubscriber.js +0 -0
  503. /package/lib/{accounts → browser/accounts}/pollingDriftClientAccountSubscriber.d.ts +0 -0
  504. /package/lib/{accounts → browser/accounts}/pollingDriftClientAccountSubscriber.js +0 -0
  505. /package/lib/{accounts → browser/accounts}/pollingInsuranceFundStakeAccountSubscriber.d.ts +0 -0
  506. /package/lib/{accounts → browser/accounts}/pollingInsuranceFundStakeAccountSubscriber.js +0 -0
  507. /package/lib/{accounts → browser/accounts}/pollingOracleAccountSubscriber.d.ts +0 -0
  508. /package/lib/{accounts → browser/accounts}/pollingOracleAccountSubscriber.js +0 -0
  509. /package/lib/{accounts → browser/accounts}/pollingTokenAccountSubscriber.d.ts +0 -0
  510. /package/lib/{accounts → browser/accounts}/pollingTokenAccountSubscriber.js +0 -0
  511. /package/lib/{accounts → browser/accounts}/pollingUserAccountSubscriber.d.ts +0 -0
  512. /package/lib/{accounts → browser/accounts}/pollingUserAccountSubscriber.js +0 -0
  513. /package/lib/{accounts → browser/accounts}/pollingUserStatsAccountSubscriber.d.ts +0 -0
  514. /package/lib/{accounts → browser/accounts}/pollingUserStatsAccountSubscriber.js +0 -0
  515. /package/lib/{accounts → browser/accounts}/testBulkAccountLoader.d.ts +0 -0
  516. /package/lib/{accounts → browser/accounts}/testBulkAccountLoader.js +0 -0
  517. /package/lib/{accounts → browser/accounts}/types.js +0 -0
  518. /package/lib/{accounts → browser/accounts}/utils.d.ts +0 -0
  519. /package/lib/{accounts → browser/accounts}/utils.js +0 -0
  520. /package/lib/{accounts → browser/accounts}/webSocketAccountSubscriber.js +0 -0
  521. /package/lib/{accounts → browser/accounts}/webSocketDriftClientAccountSubscriber.js +0 -0
  522. /package/lib/{accounts → browser/accounts}/webSocketInsuranceFundStakeAccountSubscriber.d.ts +0 -0
  523. /package/lib/{accounts → browser/accounts}/webSocketInsuranceFundStakeAccountSubscriber.js +0 -0
  524. /package/lib/{accounts → browser/accounts}/webSocketProgramAccountSubscriber.js +0 -0
  525. /package/lib/{accounts → browser/accounts}/webSocketUserAccountSubscriber.d.ts +0 -0
  526. /package/lib/{accounts → browser/accounts}/webSocketUserAccountSubscriber.js +0 -0
  527. /package/lib/{accounts → browser/accounts}/webSocketUserStatsAccountSubsriber.d.ts +0 -0
  528. /package/lib/{accounts → browser/accounts}/webSocketUserStatsAccountSubsriber.js +0 -0
  529. /package/lib/{addresses → browser/addresses}/marketAddresses.d.ts +0 -0
  530. /package/lib/{addresses → browser/addresses}/marketAddresses.js +0 -0
  531. /package/lib/{adminClient.d.ts → browser/adminClient.d.ts} +0 -0
  532. /package/lib/{adminClient.js → browser/adminClient.js} +0 -0
  533. /package/lib/{assert → browser/assert}/assert.d.ts +0 -0
  534. /package/lib/{assert → browser/assert}/assert.js +0 -0
  535. /package/lib/{auctionSubscriber → browser/auctionSubscriber}/auctionSubscriber.d.ts +0 -0
  536. /package/lib/{auctionSubscriber → browser/auctionSubscriber}/auctionSubscriber.js +0 -0
  537. /package/lib/{auctionSubscriber → browser/auctionSubscriber}/types.js +0 -0
  538. /package/lib/{bankrun → browser/bankrun}/bankrunConnection.js +0 -0
  539. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/BlockhashSubscriber.d.ts +0 -0
  540. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/BlockhashSubscriber.js +0 -0
  541. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/index.d.ts +0 -0
  542. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/index.js +0 -0
  543. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/types.d.ts +0 -0
  544. /package/lib/{blockhashSubscriber → browser/blockhashSubscriber}/types.js +0 -0
  545. /package/lib/{clock → browser/clock}/clockSubscriber.d.ts +0 -0
  546. /package/lib/{clock → browser/clock}/clockSubscriber.js +0 -0
  547. /package/lib/{config.d.ts → browser/config.d.ts} +0 -0
  548. /package/lib/{constants → browser/constants}/numericConstants.d.ts +0 -0
  549. /package/lib/{constants → browser/constants}/numericConstants.js +0 -0
  550. /package/lib/{constants → browser/constants}/perpMarkets.d.ts +0 -0
  551. /package/lib/{constants → browser/constants}/spotMarkets.d.ts +0 -0
  552. /package/lib/{constants → browser/constants}/txConstants.d.ts +0 -0
  553. /package/lib/{constants → browser/constants}/txConstants.js +0 -0
  554. /package/lib/{decode → browser/decode}/phoenix.js +0 -0
  555. /package/lib/{dlob → browser/dlob}/DLOB.d.ts +0 -0
  556. /package/lib/{dlob → browser/dlob}/DLOB.js +0 -0
  557. /package/lib/{dlob → browser/dlob}/DLOBApiClient.d.ts +0 -0
  558. /package/lib/{dlob → browser/dlob}/DLOBApiClient.js +0 -0
  559. /package/lib/{dlob → browser/dlob}/DLOBNode.d.ts +0 -0
  560. /package/lib/{dlob → browser/dlob}/DLOBNode.js +0 -0
  561. /package/lib/{dlob → browser/dlob}/DLOBOrders.js +0 -0
  562. /package/lib/{dlob → browser/dlob}/DLOBSubscriber.d.ts +0 -0
  563. /package/lib/{dlob → browser/dlob}/DLOBSubscriber.js +0 -0
  564. /package/lib/{dlob → browser/dlob}/NodeList.d.ts +0 -0
  565. /package/lib/{dlob → browser/dlob}/NodeList.js +0 -0
  566. /package/lib/{dlob → browser/dlob}/dlobIdl.json +0 -0
  567. /package/lib/{dlob → browser/dlob}/orderBookLevels.d.ts +0 -0
  568. /package/lib/{dlob → browser/dlob}/orderBookLevels.js +0 -0
  569. /package/lib/{dlob → browser/dlob}/types.d.ts +0 -0
  570. /package/lib/{dlob → browser/dlob}/types.js +0 -0
  571. /package/lib/{driftClientConfig.js → browser/driftClientConfig.js} +0 -0
  572. /package/lib/{events → browser/events}/eventList.d.ts +0 -0
  573. /package/lib/{events → browser/events}/eventList.js +0 -0
  574. /package/lib/{events → browser/events}/eventSubscriber.d.ts +0 -0
  575. /package/lib/{events → browser/events}/eventSubscriber.js +0 -0
  576. /package/lib/{events → browser/events}/eventsServerLogProvider.d.ts +0 -0
  577. /package/lib/{events → browser/events}/eventsServerLogProvider.js +0 -0
  578. /package/lib/{events → browser/events}/fetchLogs.d.ts +0 -0
  579. /package/lib/{events → browser/events}/fetchLogs.js +0 -0
  580. /package/lib/{events → browser/events}/parse.d.ts +0 -0
  581. /package/lib/{events → browser/events}/parse.js +0 -0
  582. /package/lib/{events → browser/events}/pollingLogProvider.d.ts +0 -0
  583. /package/lib/{events → browser/events}/pollingLogProvider.js +0 -0
  584. /package/lib/{events → browser/events}/sort.d.ts +0 -0
  585. /package/lib/{events → browser/events}/sort.js +0 -0
  586. /package/lib/{events → browser/events}/txEventCache.d.ts +0 -0
  587. /package/lib/{events → browser/events}/txEventCache.js +0 -0
  588. /package/lib/{events → browser/events}/types.d.ts +0 -0
  589. /package/lib/{events → browser/events}/types.js +0 -0
  590. /package/lib/{events → browser/events}/webSocketLogProvider.d.ts +0 -0
  591. /package/lib/{events → browser/events}/webSocketLogProvider.js +0 -0
  592. /package/lib/{factory → browser/factory}/bigNum.d.ts +0 -0
  593. /package/lib/{factory → browser/factory}/bigNum.js +0 -0
  594. /package/lib/{factory → browser/factory}/oracleClient.d.ts +0 -0
  595. /package/lib/{factory → browser/factory}/oracleClient.js +0 -0
  596. /package/lib/{idl → browser/idl}/openbook.json +0 -0
  597. /package/lib/{idl → browser/idl}/pyth_solana_receiver.json +0 -0
  598. /package/lib/{idl → browser/idl}/switchboard.json +0 -0
  599. /package/lib/{idl → browser/idl}/token_faucet.json +0 -0
  600. /package/lib/{jupiter → browser/jupiter}/jupiterClient.d.ts +0 -0
  601. /package/lib/{jupiter → browser/jupiter}/jupiterClient.js +0 -0
  602. /package/lib/{keypair.d.ts → browser/keypair.d.ts} +0 -0
  603. /package/lib/{keypair.js → browser/keypair.js} +0 -0
  604. /package/lib/{marinade → browser/marinade}/index.d.ts +0 -0
  605. /package/lib/{marinade → browser/marinade}/index.js +0 -0
  606. /package/lib/{marinade → browser/marinade}/types.d.ts +0 -0
  607. /package/lib/{marinade → browser/marinade}/types.js +0 -0
  608. /package/lib/{math → browser/math}/amm.d.ts +0 -0
  609. /package/lib/{math → browser/math}/amm.js +0 -0
  610. /package/lib/{math → browser/math}/auction.d.ts +0 -0
  611. /package/lib/{math → browser/math}/bankruptcy.d.ts +0 -0
  612. /package/lib/{math → browser/math}/bankruptcy.js +0 -0
  613. /package/lib/{math → browser/math}/conversion.d.ts +0 -0
  614. /package/lib/{math → browser/math}/conversion.js +0 -0
  615. /package/lib/{math → browser/math}/exchangeStatus.d.ts +0 -0
  616. /package/lib/{math → browser/math}/exchangeStatus.js +0 -0
  617. /package/lib/{math → browser/math}/fuel.d.ts +0 -0
  618. /package/lib/{math → browser/math}/fuel.js +0 -0
  619. /package/lib/{math → browser/math}/funding.d.ts +0 -0
  620. /package/lib/{math → browser/math}/funding.js +0 -0
  621. /package/lib/{math → browser/math}/insurance.d.ts +0 -0
  622. /package/lib/{math → browser/math}/insurance.js +0 -0
  623. /package/lib/{math → browser/math}/market.d.ts +0 -0
  624. /package/lib/{math → browser/math}/market.js +0 -0
  625. /package/lib/{math → browser/math}/oracles.js +0 -0
  626. /package/lib/{math → browser/math}/orders.d.ts +0 -0
  627. /package/lib/{math → browser/math}/orders.js +0 -0
  628. /package/lib/{math → browser/math}/repeg.d.ts +0 -0
  629. /package/lib/{math → browser/math}/repeg.js +0 -0
  630. /package/lib/{math → browser/math}/spotBalance.d.ts +0 -0
  631. /package/lib/{math → browser/math}/spotBalance.js +0 -0
  632. /package/lib/{math → browser/math}/spotMarket.d.ts +0 -0
  633. /package/lib/{math → browser/math}/spotMarket.js +0 -0
  634. /package/lib/{math → browser/math}/spotPosition.d.ts +0 -0
  635. /package/lib/{math → browser/math}/spotPosition.js +0 -0
  636. /package/lib/{math → browser/math}/state.d.ts +0 -0
  637. /package/lib/{math → browser/math}/state.js +0 -0
  638. /package/lib/{math → browser/math}/superStake.d.ts +0 -0
  639. /package/lib/{math → browser/math}/superStake.js +0 -0
  640. /package/lib/{math → browser/math}/tiers.d.ts +0 -0
  641. /package/lib/{math → browser/math}/tiers.js +0 -0
  642. /package/lib/{math → browser/math}/trade.d.ts +0 -0
  643. /package/lib/{math → browser/math}/trade.js +0 -0
  644. /package/lib/{math → browser/math}/utils.d.ts +0 -0
  645. /package/lib/{math → browser/math}/utils.js +0 -0
  646. /package/lib/{memcmp.d.ts → browser/memcmp.d.ts} +0 -0
  647. /package/lib/{memcmp.js → browser/memcmp.js} +0 -0
  648. /package/lib/{openbook → browser/openbook}/openbookV2FulfillmentConfigMap.d.ts +0 -0
  649. /package/lib/{openbook → browser/openbook}/openbookV2FulfillmentConfigMap.js +0 -0
  650. /package/lib/{openbook → browser/openbook}/openbookV2Subscriber.d.ts +0 -0
  651. /package/lib/{openbook → browser/openbook}/openbookV2Subscriber.js +0 -0
  652. /package/lib/{oracles → browser/oracles}/oracleClientCache.d.ts +0 -0
  653. /package/lib/{oracles → browser/oracles}/oracleClientCache.js +0 -0
  654. /package/lib/{oracles → browser/oracles}/prelaunchOracleClient.js +0 -0
  655. /package/lib/{oracles → browser/oracles}/pythPullClient.js +0 -0
  656. /package/lib/{oracles → browser/oracles}/quoteAssetOracleClient.js +0 -0
  657. /package/lib/{oracles → browser/oracles}/strictOraclePrice.d.ts +0 -0
  658. /package/lib/{oracles → browser/oracles}/strictOraclePrice.js +0 -0
  659. /package/lib/{oracles → browser/oracles}/switchboardClient.js +0 -0
  660. /package/lib/{oracles → browser/oracles}/switchboardOnDemandClient.js +0 -0
  661. /package/lib/{oracles → browser/oracles}/types.js +0 -0
  662. /package/lib/{orderParams.d.ts → browser/orderParams.d.ts} +0 -0
  663. /package/lib/{orderParams.js → browser/orderParams.js} +0 -0
  664. /package/lib/{orderSubscriber → browser/orderSubscriber}/PollingSubscription.d.ts +0 -0
  665. /package/lib/{orderSubscriber → browser/orderSubscriber}/PollingSubscription.js +0 -0
  666. /package/lib/{orderSubscriber → browser/orderSubscriber}/WebsocketSubscription.d.ts +0 -0
  667. /package/lib/{orderSubscriber → browser/orderSubscriber}/WebsocketSubscription.js +0 -0
  668. /package/lib/{orderSubscriber → browser/orderSubscriber}/index.d.ts +0 -0
  669. /package/lib/{orderSubscriber → browser/orderSubscriber}/index.js +0 -0
  670. /package/lib/{orderSubscriber → browser/orderSubscriber}/types.js +0 -0
  671. /package/lib/{phoenix → browser/phoenix}/phoenixFulfillmentConfigMap.d.ts +0 -0
  672. /package/lib/{phoenix → browser/phoenix}/phoenixFulfillmentConfigMap.js +0 -0
  673. /package/lib/{phoenix → browser/phoenix}/phoenixSubscriber.d.ts +0 -0
  674. /package/lib/{phoenix → browser/phoenix}/phoenixSubscriber.js +0 -0
  675. /package/lib/{priorityFee → browser/priorityFee}/averageOverSlotsStrategy.d.ts +0 -0
  676. /package/lib/{priorityFee → browser/priorityFee}/averageOverSlotsStrategy.js +0 -0
  677. /package/lib/{priorityFee → browser/priorityFee}/averageStrategy.d.ts +0 -0
  678. /package/lib/{priorityFee → browser/priorityFee}/averageStrategy.js +0 -0
  679. /package/lib/{priorityFee → browser/priorityFee}/driftPriorityFeeMethod.d.ts +0 -0
  680. /package/lib/{priorityFee → browser/priorityFee}/driftPriorityFeeMethod.js +0 -0
  681. /package/lib/{priorityFee → browser/priorityFee}/ewmaStrategy.d.ts +0 -0
  682. /package/lib/{priorityFee → browser/priorityFee}/ewmaStrategy.js +0 -0
  683. /package/lib/{priorityFee → browser/priorityFee}/heliusPriorityFeeMethod.d.ts +0 -0
  684. /package/lib/{priorityFee → browser/priorityFee}/heliusPriorityFeeMethod.js +0 -0
  685. /package/lib/{priorityFee → browser/priorityFee}/index.d.ts +0 -0
  686. /package/lib/{priorityFee → browser/priorityFee}/index.js +0 -0
  687. /package/lib/{priorityFee → browser/priorityFee}/maxOverSlotsStrategy.d.ts +0 -0
  688. /package/lib/{priorityFee → browser/priorityFee}/maxOverSlotsStrategy.js +0 -0
  689. /package/lib/{priorityFee → browser/priorityFee}/maxStrategy.d.ts +0 -0
  690. /package/lib/{priorityFee → browser/priorityFee}/maxStrategy.js +0 -0
  691. /package/lib/{priorityFee → browser/priorityFee}/priorityFeeSubscriber.d.ts +0 -0
  692. /package/lib/{priorityFee → browser/priorityFee}/priorityFeeSubscriber.js +0 -0
  693. /package/lib/{priorityFee → browser/priorityFee}/priorityFeeSubscriberMap.d.ts +0 -0
  694. /package/lib/{priorityFee → browser/priorityFee}/priorityFeeSubscriberMap.js +0 -0
  695. /package/lib/{priorityFee → browser/priorityFee}/solanaPriorityFeeMethod.d.ts +0 -0
  696. /package/lib/{priorityFee → browser/priorityFee}/solanaPriorityFeeMethod.js +0 -0
  697. /package/lib/{priorityFee → browser/priorityFee}/types.d.ts +0 -0
  698. /package/lib/{priorityFee → browser/priorityFee}/types.js +0 -0
  699. /package/lib/{serum → browser/serum}/serumFulfillmentConfigMap.d.ts +0 -0
  700. /package/lib/{serum → browser/serum}/serumFulfillmentConfigMap.js +0 -0
  701. /package/lib/{serum → browser/serum}/serumSubscriber.d.ts +0 -0
  702. /package/lib/{serum → browser/serum}/serumSubscriber.js +0 -0
  703. /package/lib/{serum → browser/serum}/types.d.ts +0 -0
  704. /package/lib/{serum → browser/serum}/types.js +0 -0
  705. /package/lib/{slot → browser/slot}/SlotSubscriber.d.ts +0 -0
  706. /package/lib/{slot → browser/slot}/SlotSubscriber.js +0 -0
  707. /package/lib/{testClient.d.ts → browser/testClient.d.ts} +0 -0
  708. /package/lib/{testClient.js → browser/testClient.js} +0 -0
  709. /package/lib/{token → browser/token}/index.js +0 -0
  710. /package/lib/{tokenFaucet.d.ts → browser/tokenFaucet.d.ts} +0 -0
  711. /package/lib/{tokenFaucet.js → browser/tokenFaucet.js} +0 -0
  712. /package/lib/{tx → browser/tx}/blockhashFetcher/baseBlockhashFetcher.d.ts +0 -0
  713. /package/lib/{tx → browser/tx}/blockhashFetcher/baseBlockhashFetcher.js +0 -0
  714. /package/lib/{tx → browser/tx}/blockhashFetcher/cachedBlockhashFetcher.d.ts +0 -0
  715. /package/lib/{tx → browser/tx}/blockhashFetcher/cachedBlockhashFetcher.js +0 -0
  716. /package/lib/{tx → browser/tx}/blockhashFetcher/types.d.ts +0 -0
  717. /package/lib/{tx → browser/tx}/blockhashFetcher/types.js +0 -0
  718. /package/lib/{tx → browser/tx}/priorityFeeCalculator.d.ts +0 -0
  719. /package/lib/{tx → browser/tx}/priorityFeeCalculator.js +0 -0
  720. /package/lib/{tx → browser/tx}/reportTransactionError.d.ts +0 -0
  721. /package/lib/{tx → browser/tx}/reportTransactionError.js +0 -0
  722. /package/lib/{tx → browser/tx}/txHandler.d.ts +0 -0
  723. /package/lib/{tx → browser/tx}/txHandler.js +0 -0
  724. /package/lib/{tx → browser/tx}/txParamProcessor.d.ts +0 -0
  725. /package/lib/{tx → browser/tx}/txParamProcessor.js +0 -0
  726. /package/lib/{tx → browser/tx}/types.js +0 -0
  727. /package/lib/{tx → browser/tx}/utils.d.ts +0 -0
  728. /package/lib/{tx → browser/tx}/utils.js +0 -0
  729. /package/lib/{userConfig.js → browser/userConfig.js} +0 -0
  730. /package/lib/{userMap → browser/userMap}/PollingSubscription.d.ts +0 -0
  731. /package/lib/{userMap → browser/userMap}/PollingSubscription.js +0 -0
  732. /package/lib/{userMap → browser/userMap}/WebsocketSubscription.js +0 -0
  733. /package/lib/{userMap → browser/userMap}/userMap.d.ts +0 -0
  734. /package/lib/{userMap → browser/userMap}/userMapConfig.js +0 -0
  735. /package/lib/{userMap → browser/userMap}/userStatsMap.d.ts +0 -0
  736. /package/lib/{userMap → browser/userMap}/userStatsMap.js +0 -0
  737. /package/lib/{userName.d.ts → browser/userName.d.ts} +0 -0
  738. /package/lib/{userName.js → browser/userName.js} +0 -0
  739. /package/lib/{userStats.d.ts → browser/userStats.d.ts} +0 -0
  740. /package/lib/{userStatsConfig.js → browser/userStatsConfig.js} +0 -0
  741. /package/lib/{util → browser/util}/TransactionConfirmationManager.d.ts +0 -0
  742. /package/lib/{util → browser/util}/TransactionConfirmationManager.js +0 -0
  743. /package/lib/{util → browser/util}/chainClock.d.ts +0 -0
  744. /package/lib/{util → browser/util}/chainClock.js +0 -0
  745. /package/lib/{util → browser/util}/computeUnits.d.ts +0 -0
  746. /package/lib/{util → browser/util}/computeUnits.js +0 -0
  747. /package/lib/{util → browser/util}/promiseTimeout.d.ts +0 -0
  748. /package/lib/{util → browser/util}/promiseTimeout.js +0 -0
  749. /package/lib/{util → browser/util}/pythPullOracleUtils.d.ts +0 -0
  750. /package/lib/{util → browser/util}/pythPullOracleUtils.js +0 -0
  751. /package/lib/{util → browser/util}/tps.d.ts +0 -0
  752. /package/lib/{util → browser/util}/tps.js +0 -0
  753. /package/lib/{wallet.d.ts → browser/wallet.d.ts} +0 -0
  754. /package/lib/{wallet.js → browser/wallet.js} +0 -0
@@ -0,0 +1,4496 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.DriftClient = void 0;
30
+ const anchor = __importStar(require("@coral-xyz/anchor"));
31
+ const anchor_1 = require("@coral-xyz/anchor");
32
+ const anchor_30_1 = require("@coral-xyz/anchor-30");
33
+ const bs58_1 = __importDefault(require("bs58"));
34
+ const spl_token_1 = require("@solana/spl-token");
35
+ const types_1 = require("./types");
36
+ const drift_json_1 = __importDefault(require("./idl/drift.json"));
37
+ const web3_js_1 = require("@solana/web3.js");
38
+ const events_1 = require("events");
39
+ const pda_1 = require("./addresses/pda");
40
+ const types_2 = require("./accounts/types");
41
+ const numericConstants_1 = require("./constants/numericConstants");
42
+ const position_1 = require("./math/position");
43
+ const spotBalance_1 = require("./math/spotBalance");
44
+ const userName_1 = require("./userName");
45
+ const pollingDriftClientAccountSubscriber_1 = require("./accounts/pollingDriftClientAccountSubscriber");
46
+ const webSocketDriftClientAccountSubscriber_1 = require("./accounts/webSocketDriftClientAccountSubscriber");
47
+ const retryTxSender_1 = require("./tx/retryTxSender");
48
+ const user_1 = require("./user");
49
+ const config_1 = require("./config");
50
+ const spotMarkets_1 = require("./constants/spotMarkets");
51
+ const userStats_1 = require("./userStats");
52
+ const spotPosition_1 = require("./math/spotPosition");
53
+ const market_1 = require("./math/market");
54
+ const fetch_1 = require("./accounts/fetch");
55
+ const spotMarket_1 = require("./math/spotMarket");
56
+ const memcmp_1 = require("./memcmp");
57
+ const marinade_1 = require("./marinade");
58
+ const orderParams_1 = require("./orderParams");
59
+ const utils_1 = require("./math/utils");
60
+ const txParamProcessor_1 = require("./tx/txParamProcessor");
61
+ const oracles_1 = require("./math/oracles");
62
+ const txHandler_1 = require("./tx/txHandler");
63
+ const pyth_solana_receiver_1 = require("@pythnetwork/pyth-solana-receiver");
64
+ const price_service_sdk_1 = require("@pythnetwork/price-service-sdk");
65
+ const address_1 = require("@pythnetwork/pyth-solana-receiver/lib/address");
66
+ const pythPullOracleUtils_1 = require("./util/pythPullOracleUtils");
67
+ const utils_2 = require("./tx/utils");
68
+ const pyth_solana_receiver_json_1 = __importDefault(require("./idl/pyth_solana_receiver.json"));
69
+ const on_demand_1 = require("@switchboard-xyz/on-demand");
70
+ const grpcDriftClientAccountSubscriber_1 = require("./accounts/grpcDriftClientAccountSubscriber");
71
+ const tweetnacl_1 = __importDefault(require("tweetnacl"));
72
+ /**
73
+ * # DriftClient
74
+ * This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
75
+ */
76
+ class DriftClient {
77
+ get isSubscribed() {
78
+ return this._isSubscribed && this.accountSubscriber.isSubscribed;
79
+ }
80
+ set isSubscribed(val) {
81
+ this._isSubscribed = val;
82
+ }
83
+ constructor(config) {
84
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21;
85
+ this.users = new Map();
86
+ this._isSubscribed = false;
87
+ this.perpMarketLastSlotCache = new Map();
88
+ this.spotMarketLastSlotCache = new Map();
89
+ this.mustIncludePerpMarketIndexes = new Set();
90
+ this.mustIncludeSpotMarketIndexes = new Set();
91
+ this.connection = config.connection;
92
+ this.wallet = config.wallet;
93
+ this.opts = config.opts || {
94
+ ...config_1.DEFAULT_CONFIRMATION_OPTS,
95
+ commitment: (_a = config === null || config === void 0 ? void 0 : config.connection) === null || _a === void 0 ? void 0 : _a.commitment,
96
+ preflightCommitment: (_b = config === null || config === void 0 ? void 0 : config.connection) === null || _b === void 0 ? void 0 : _b.commitment, // At the moment this ensures that our transaction simulations (which use Connection object) will use the same commitment level as our Transaction blockhashes (which use these opts)
97
+ };
98
+ this.provider = new anchor_1.AnchorProvider(config.connection,
99
+ // @ts-ignore
100
+ config.wallet, this.opts);
101
+ this.program = new anchor_1.Program(drift_json_1.default, (_c = config.programID) !== null && _c !== void 0 ? _c : new web3_js_1.PublicKey(config_1.DRIFT_PROGRAM_ID), this.provider);
102
+ this.swiftID = (_d = config.swiftID) !== null && _d !== void 0 ? _d : new web3_js_1.PublicKey(config_1.SWIFT_ID);
103
+ this.authority = (_e = config.authority) !== null && _e !== void 0 ? _e : this.wallet.publicKey;
104
+ this.activeSubAccountId = (_f = config.activeSubAccountId) !== null && _f !== void 0 ? _f : 0;
105
+ this.skipLoadUsers = (_g = config.skipLoadUsers) !== null && _g !== void 0 ? _g : false;
106
+ this.txVersion = (_h = config.txVersion) !== null && _h !== void 0 ? _h : 'legacy';
107
+ this.txParams = {
108
+ computeUnits: (_k = (_j = config.txParams) === null || _j === void 0 ? void 0 : _j.computeUnits) !== null && _k !== void 0 ? _k : 600000,
109
+ computeUnitsPrice: (_m = (_l = config.txParams) === null || _l === void 0 ? void 0 : _l.computeUnitsPrice) !== null && _m !== void 0 ? _m : 0,
110
+ };
111
+ this.txHandler =
112
+ (_o = config === null || config === void 0 ? void 0 : config.txHandler) !== null && _o !== void 0 ? _o : new txHandler_1.TxHandler({
113
+ connection: this.connection,
114
+ // @ts-ignore
115
+ wallet: this.provider.wallet,
116
+ confirmationOptions: this.opts,
117
+ opts: {
118
+ returnBlockHeightsWithSignedTxCallbackData: config.enableMetricsEvents,
119
+ onSignedCb: this.handleSignedTransaction.bind(this),
120
+ preSignedCb: this.handlePreSignedTransaction.bind(this),
121
+ },
122
+ config: config.txHandlerConfig,
123
+ });
124
+ if (config.includeDelegates && config.subAccountIds) {
125
+ throw new Error('Can only pass one of includeDelegates or subAccountIds. If you want to specify subaccount ids for multiple authorities, pass authoritySubaccountMap instead');
126
+ }
127
+ if (config.authoritySubAccountMap && config.subAccountIds) {
128
+ throw new Error('Can only pass one of authoritySubaccountMap or subAccountIds');
129
+ }
130
+ if (config.authoritySubAccountMap && config.includeDelegates) {
131
+ throw new Error('Can only pass one of authoritySubaccountMap or includeDelegates');
132
+ }
133
+ this.authoritySubAccountMap = config.authoritySubAccountMap
134
+ ? config.authoritySubAccountMap
135
+ : config.subAccountIds
136
+ ? new Map([[this.authority.toString(), config.subAccountIds]])
137
+ : new Map();
138
+ this.includeDelegates = (_p = config.includeDelegates) !== null && _p !== void 0 ? _p : false;
139
+ if (((_q = config.accountSubscription) === null || _q === void 0 ? void 0 : _q.type) === 'polling') {
140
+ this.userAccountSubscriptionConfig = {
141
+ type: 'polling',
142
+ accountLoader: config.accountSubscription.accountLoader,
143
+ };
144
+ this.userStatsAccountSubscriptionConfig = {
145
+ type: 'polling',
146
+ accountLoader: config.accountSubscription.accountLoader,
147
+ };
148
+ }
149
+ else if (((_r = config.accountSubscription) === null || _r === void 0 ? void 0 : _r.type) === 'grpc') {
150
+ this.userAccountSubscriptionConfig = {
151
+ type: 'grpc',
152
+ resubTimeoutMs: (_s = config.accountSubscription) === null || _s === void 0 ? void 0 : _s.resubTimeoutMs,
153
+ logResubMessages: (_t = config.accountSubscription) === null || _t === void 0 ? void 0 : _t.logResubMessages,
154
+ grpcConfigs: (_u = config.accountSubscription) === null || _u === void 0 ? void 0 : _u.grpcConfigs,
155
+ };
156
+ this.userStatsAccountSubscriptionConfig = {
157
+ type: 'grpc',
158
+ grpcConfigs: (_v = config.accountSubscription) === null || _v === void 0 ? void 0 : _v.grpcConfigs,
159
+ resubTimeoutMs: (_w = config.accountSubscription) === null || _w === void 0 ? void 0 : _w.resubTimeoutMs,
160
+ logResubMessages: (_x = config.accountSubscription) === null || _x === void 0 ? void 0 : _x.logResubMessages,
161
+ };
162
+ }
163
+ else {
164
+ this.userAccountSubscriptionConfig = {
165
+ type: 'websocket',
166
+ resubTimeoutMs: (_y = config.accountSubscription) === null || _y === void 0 ? void 0 : _y.resubTimeoutMs,
167
+ logResubMessages: (_z = config.accountSubscription) === null || _z === void 0 ? void 0 : _z.logResubMessages,
168
+ commitment: (_0 = config.accountSubscription) === null || _0 === void 0 ? void 0 : _0.commitment,
169
+ };
170
+ this.userStatsAccountSubscriptionConfig = {
171
+ type: 'websocket',
172
+ resubTimeoutMs: (_1 = config.accountSubscription) === null || _1 === void 0 ? void 0 : _1.resubTimeoutMs,
173
+ logResubMessages: (_2 = config.accountSubscription) === null || _2 === void 0 ? void 0 : _2.logResubMessages,
174
+ commitment: (_3 = config.accountSubscription) === null || _3 === void 0 ? void 0 : _3.commitment,
175
+ };
176
+ }
177
+ if (config.userStats) {
178
+ this.userStats = new userStats_1.UserStats({
179
+ driftClient: this,
180
+ userStatsAccountPublicKey: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority),
181
+ accountSubscription: this.userAccountSubscriptionConfig,
182
+ });
183
+ }
184
+ this.marketLookupTable = config.marketLookupTable;
185
+ if (config.env && !this.marketLookupTable) {
186
+ this.marketLookupTable = new web3_js_1.PublicKey(config_1.configs[config.env].MARKET_LOOKUP_TABLE);
187
+ }
188
+ const delistedMarketSetting = config.delistedMarketSetting || types_2.DelistedMarketSetting.Subscribe;
189
+ const noMarketsAndOraclesSpecified = config.perpMarketIndexes === undefined &&
190
+ config.spotMarketIndexes === undefined &&
191
+ config.oracleInfos === undefined;
192
+ if (((_4 = config.accountSubscription) === null || _4 === void 0 ? void 0 : _4.type) === 'polling') {
193
+ this.accountSubscriber = new pollingDriftClientAccountSubscriber_1.PollingDriftClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_5 = config.perpMarketIndexes) !== null && _5 !== void 0 ? _5 : [], (_6 = config.spotMarketIndexes) !== null && _6 !== void 0 ? _6 : [], (_7 = config.oracleInfos) !== null && _7 !== void 0 ? _7 : [], noMarketsAndOraclesSpecified, delistedMarketSetting);
194
+ }
195
+ else if (((_8 = config.accountSubscription) === null || _8 === void 0 ? void 0 : _8.type) === 'grpc') {
196
+ this.accountSubscriber = new grpcDriftClientAccountSubscriber_1.gprcDriftClientAccountSubscriber(config.accountSubscription.grpcConfigs, this.program, (_9 = config.perpMarketIndexes) !== null && _9 !== void 0 ? _9 : [], (_10 = config.spotMarketIndexes) !== null && _10 !== void 0 ? _10 : [], (_11 = config.oracleInfos) !== null && _11 !== void 0 ? _11 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
197
+ resubTimeoutMs: (_12 = config.accountSubscription) === null || _12 === void 0 ? void 0 : _12.resubTimeoutMs,
198
+ logResubMessages: (_13 = config.accountSubscription) === null || _13 === void 0 ? void 0 : _13.logResubMessages,
199
+ });
200
+ }
201
+ else {
202
+ this.accountSubscriber = new webSocketDriftClientAccountSubscriber_1.WebSocketDriftClientAccountSubscriber(this.program, (_14 = config.perpMarketIndexes) !== null && _14 !== void 0 ? _14 : [], (_15 = config.spotMarketIndexes) !== null && _15 !== void 0 ? _15 : [], (_16 = config.oracleInfos) !== null && _16 !== void 0 ? _16 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
203
+ resubTimeoutMs: (_17 = config.accountSubscription) === null || _17 === void 0 ? void 0 : _17.resubTimeoutMs,
204
+ logResubMessages: (_18 = config.accountSubscription) === null || _18 === void 0 ? void 0 : _18.logResubMessages,
205
+ }, (_19 = config.accountSubscription) === null || _19 === void 0 ? void 0 : _19.commitment);
206
+ }
207
+ this.eventEmitter = this.accountSubscriber.eventEmitter;
208
+ this.metricsEventEmitter = new events_1.EventEmitter();
209
+ if (config.enableMetricsEvents) {
210
+ this.enableMetricsEvents = true;
211
+ }
212
+ this.txSender =
213
+ (_20 = config.txSender) !== null && _20 !== void 0 ? _20 : new retryTxSender_1.RetryTxSender({
214
+ connection: this.connection,
215
+ wallet: this.wallet,
216
+ opts: this.opts,
217
+ txHandler: this.txHandler,
218
+ });
219
+ this.sbOnDemandProgramdId =
220
+ config_1.configs[(_21 = config.env) !== null && _21 !== void 0 ? _21 : 'mainnet-beta'].SB_ON_DEMAND_PID;
221
+ }
222
+ getUserMapKey(subAccountId, authority) {
223
+ return `${subAccountId}_${authority.toString()}`;
224
+ }
225
+ createUser(subAccountId, accountSubscriptionConfig, authority) {
226
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, authority !== null && authority !== void 0 ? authority : this.authority, subAccountId);
227
+ return new user_1.User({
228
+ driftClient: this,
229
+ userAccountPublicKey,
230
+ accountSubscription: accountSubscriptionConfig,
231
+ });
232
+ }
233
+ async subscribe() {
234
+ let subscribePromises = [this.addAndSubscribeToUsers()].concat(this.accountSubscriber.subscribe());
235
+ if (this.userStats !== undefined) {
236
+ subscribePromises = subscribePromises.concat(this.userStats.subscribe());
237
+ }
238
+ this.isSubscribed = (await Promise.all(subscribePromises)).reduce((success, prevSuccess) => success && prevSuccess);
239
+ return this.isSubscribed;
240
+ }
241
+ subscribeUsers() {
242
+ return [...this.users.values()].map((user) => user.subscribe());
243
+ }
244
+ /**
245
+ * Forces the accountSubscriber to fetch account updates from rpc
246
+ */
247
+ async fetchAccounts() {
248
+ let promises = [...this.users.values()]
249
+ .map((user) => user.fetchAccounts())
250
+ .concat(this.accountSubscriber.fetch());
251
+ if (this.userStats) {
252
+ promises = promises.concat(this.userStats.fetchAccounts());
253
+ }
254
+ await Promise.all(promises);
255
+ }
256
+ async unsubscribe() {
257
+ let unsubscribePromises = this.unsubscribeUsers().concat(this.accountSubscriber.unsubscribe());
258
+ if (this.userStats !== undefined) {
259
+ unsubscribePromises = unsubscribePromises.concat(this.userStats.unsubscribe());
260
+ }
261
+ await Promise.all(unsubscribePromises);
262
+ this.isSubscribed = false;
263
+ }
264
+ unsubscribeUsers() {
265
+ return [...this.users.values()].map((user) => user.unsubscribe());
266
+ }
267
+ async getStatePublicKey() {
268
+ if (this.statePublicKey) {
269
+ return this.statePublicKey;
270
+ }
271
+ this.statePublicKey = await (0, pda_1.getDriftStateAccountPublicKey)(this.program.programId);
272
+ return this.statePublicKey;
273
+ }
274
+ getSignerPublicKey() {
275
+ if (this.signerPublicKey) {
276
+ return this.signerPublicKey;
277
+ }
278
+ this.signerPublicKey = (0, pda_1.getDriftSignerPublicKey)(this.program.programId);
279
+ return this.signerPublicKey;
280
+ }
281
+ getStateAccount() {
282
+ return this.accountSubscriber.getStateAccountAndSlot().data;
283
+ }
284
+ /**
285
+ * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
286
+ */
287
+ async forceGetStateAccount() {
288
+ await this.accountSubscriber.fetch();
289
+ return this.accountSubscriber.getStateAccountAndSlot().data;
290
+ }
291
+ getPerpMarketAccount(marketIndex) {
292
+ var _a;
293
+ return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
294
+ }
295
+ /**
296
+ * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
297
+ * @param marketIndex
298
+ */
299
+ async forceGetPerpMarketAccount(marketIndex) {
300
+ var _a, _b;
301
+ await this.accountSubscriber.fetch();
302
+ let data = (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
303
+ let i = 0;
304
+ while (data === undefined && i < 10) {
305
+ await this.accountSubscriber.fetch();
306
+ data = (_b = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _b === void 0 ? void 0 : _b.data;
307
+ i++;
308
+ }
309
+ return data;
310
+ }
311
+ getPerpMarketAccounts() {
312
+ return this.accountSubscriber
313
+ .getMarketAccountsAndSlots()
314
+ .filter((value) => value !== undefined)
315
+ .map((value) => value.data);
316
+ }
317
+ getSpotMarketAccount(marketIndex) {
318
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
319
+ }
320
+ /**
321
+ * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
322
+ * @param marketIndex
323
+ */
324
+ async forceGetSpotMarketAccount(marketIndex) {
325
+ await this.accountSubscriber.fetch();
326
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
327
+ }
328
+ getSpotMarketAccounts() {
329
+ return this.accountSubscriber
330
+ .getSpotMarketAccountsAndSlots()
331
+ .filter((value) => value !== undefined)
332
+ .map((value) => value.data);
333
+ }
334
+ getQuoteSpotMarketAccount() {
335
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
336
+ }
337
+ getOraclePriceDataAndSlot(oraclePublicKey) {
338
+ return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey.toBase58());
339
+ }
340
+ async getSerumV3FulfillmentConfig(serumMarket) {
341
+ const address = await (0, pda_1.getSerumFulfillmentConfigPublicKey)(this.program.programId, serumMarket);
342
+ return (await this.program.account.serumV3FulfillmentConfig.fetch(address));
343
+ }
344
+ async getSerumV3FulfillmentConfigs() {
345
+ const accounts = await this.program.account.serumV3FulfillmentConfig.all();
346
+ return accounts.map((account) => account.account);
347
+ }
348
+ async getPhoenixV1FulfillmentConfig(phoenixMarket) {
349
+ const address = await (0, pda_1.getPhoenixFulfillmentConfigPublicKey)(this.program.programId, phoenixMarket);
350
+ return (await this.program.account.phoenixV1FulfillmentConfig.fetch(address));
351
+ }
352
+ async getPhoenixV1FulfillmentConfigs() {
353
+ const accounts = await this.program.account.phoenixV1FulfillmentConfig.all();
354
+ return accounts.map((account) => account.account);
355
+ }
356
+ async getOpenbookV2FulfillmentConfig(openbookMarket) {
357
+ const address = (0, pda_1.getOpenbookV2FulfillmentConfigPublicKey)(this.program.programId, openbookMarket);
358
+ return (await this.program.account.openbookV2FulfillmentConfig.fetch(address));
359
+ }
360
+ async getOpenbookV2FulfillmentConfigs() {
361
+ const accounts = await this.program.account.openbookV2FulfillmentConfig.all();
362
+ return accounts.map((account) => account.account);
363
+ }
364
+ async fetchMarketLookupTableAccount() {
365
+ if (this.lookupTableAccount)
366
+ return this.lookupTableAccount;
367
+ if (!this.marketLookupTable) {
368
+ console.log('Market lookup table address not set');
369
+ return;
370
+ }
371
+ const lookupTableAccount = (await this.connection.getAddressLookupTable(this.marketLookupTable)).value;
372
+ this.lookupTableAccount = lookupTableAccount;
373
+ return lookupTableAccount;
374
+ }
375
+ /**
376
+ * Update the wallet to use for drift transactions and linked user account
377
+ * @param newWallet
378
+ * @param subAccountIds
379
+ * @param activeSubAccountId
380
+ * @param includeDelegates
381
+ */
382
+ async updateWallet(newWallet, subAccountIds, activeSubAccountId, includeDelegates, authoritySubaccountMap) {
383
+ var _a, _b, _c;
384
+ const newProvider = new anchor_1.AnchorProvider(this.connection,
385
+ // @ts-ignore
386
+ newWallet, this.opts);
387
+ const newProgram = new anchor_1.Program(drift_json_1.default, this.program.programId, newProvider);
388
+ this.skipLoadUsers = false;
389
+ // Update provider for txSender with new wallet details
390
+ this.txSender.wallet = newWallet;
391
+ this.wallet = newWallet;
392
+ this.txHandler.updateWallet(newWallet);
393
+ this.provider = newProvider;
394
+ this.program = newProgram;
395
+ this.authority = newWallet.publicKey;
396
+ this.activeSubAccountId = activeSubAccountId;
397
+ this.userStatsAccountPublicKey = undefined;
398
+ this.includeDelegates = includeDelegates !== null && includeDelegates !== void 0 ? includeDelegates : false;
399
+ const walletSupportsVersionedTxns =
400
+ //@ts-ignore
401
+ (_b = (_a = this.wallet.supportedTransactionVersions) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0 > 1;
402
+ this.txVersion = walletSupportsVersionedTxns ? 0 : 'legacy';
403
+ if (includeDelegates && subAccountIds) {
404
+ throw new Error('Can only pass one of includeDelegates or subAccountIds. If you want to specify subaccount ids for multiple authorities, pass authoritySubaccountMap instead');
405
+ }
406
+ if (authoritySubaccountMap && subAccountIds) {
407
+ throw new Error('Can only pass one of authoritySubaccountMap or subAccountIds');
408
+ }
409
+ if (authoritySubaccountMap && includeDelegates) {
410
+ throw new Error('Can only pass one of authoritySubaccountMap or includeDelegates');
411
+ }
412
+ this.authoritySubAccountMap = authoritySubaccountMap
413
+ ? authoritySubaccountMap
414
+ : subAccountIds
415
+ ? new Map([[this.authority.toString(), subAccountIds]])
416
+ : new Map();
417
+ /* Reset user stats account */
418
+ if ((_c = this.userStats) === null || _c === void 0 ? void 0 : _c.isSubscribed) {
419
+ await this.userStats.unsubscribe();
420
+ }
421
+ this.userStats = undefined;
422
+ this.userStats = new userStats_1.UserStats({
423
+ driftClient: this,
424
+ userStatsAccountPublicKey: this.getUserStatsAccountPublicKey(),
425
+ accountSubscription: this.userStatsAccountSubscriptionConfig,
426
+ });
427
+ await this.userStats.subscribe();
428
+ let success = true;
429
+ if (this.isSubscribed) {
430
+ await Promise.all(this.unsubscribeUsers());
431
+ this.users.clear();
432
+ success = await this.addAndSubscribeToUsers();
433
+ }
434
+ return success;
435
+ }
436
+ /**
437
+ * Update the subscribed accounts to a given authority, while leaving the
438
+ * connected wallet intact. This allows a user to emulate another user's
439
+ * account on the UI and sign permissionless transactions with their own wallet.
440
+ * @param emulateAuthority
441
+ */
442
+ async emulateAccount(emulateAuthority) {
443
+ var _a, _b, _c;
444
+ this.skipLoadUsers = false;
445
+ // Update provider for txSender with new wallet details
446
+ this.authority = emulateAuthority;
447
+ this.userStatsAccountPublicKey = undefined;
448
+ this.includeDelegates = true;
449
+ const walletSupportsVersionedTxns =
450
+ //@ts-ignore
451
+ (_b = (_a = this.wallet.supportedTransactionVersions) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0 > 1;
452
+ this.txVersion = walletSupportsVersionedTxns ? 0 : 'legacy';
453
+ this.authoritySubAccountMap = new Map();
454
+ /* Reset user stats account */
455
+ if ((_c = this.userStats) === null || _c === void 0 ? void 0 : _c.isSubscribed) {
456
+ await this.userStats.unsubscribe();
457
+ }
458
+ this.userStats = undefined;
459
+ this.userStats = new userStats_1.UserStats({
460
+ driftClient: this,
461
+ userStatsAccountPublicKey: this.getUserStatsAccountPublicKey(),
462
+ accountSubscription: this.userStatsAccountSubscriptionConfig,
463
+ });
464
+ await this.userStats.subscribe();
465
+ let success = true;
466
+ if (this.isSubscribed) {
467
+ await Promise.all(this.unsubscribeUsers());
468
+ this.users.clear();
469
+ success = await this.addAndSubscribeToUsers(emulateAuthority);
470
+ }
471
+ return success;
472
+ }
473
+ async switchActiveUser(subAccountId, authority) {
474
+ var _a;
475
+ const authorityChanged = authority && !((_a = this.authority) === null || _a === void 0 ? void 0 : _a.equals(authority));
476
+ this.activeSubAccountId = subAccountId;
477
+ this.authority = authority !== null && authority !== void 0 ? authority : this.authority;
478
+ this.userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
479
+ /* If changing the user authority ie switching from delegate to non-delegate account, need to re-subscribe to the user stats account */
480
+ if (authorityChanged) {
481
+ if (this.userStats && this.userStats.isSubscribed) {
482
+ await this.userStats.unsubscribe();
483
+ }
484
+ this.userStats = new userStats_1.UserStats({
485
+ driftClient: this,
486
+ userStatsAccountPublicKey: this.userStatsAccountPublicKey,
487
+ accountSubscription: this.userAccountSubscriptionConfig,
488
+ });
489
+ this.userStats.subscribe();
490
+ }
491
+ }
492
+ async addUser(subAccountId, authority, userAccount) {
493
+ authority = authority !== null && authority !== void 0 ? authority : this.authority;
494
+ const userKey = this.getUserMapKey(subAccountId, authority);
495
+ if (this.users.has(userKey) && this.users.get(userKey).isSubscribed) {
496
+ return true;
497
+ }
498
+ const user = this.createUser(subAccountId, this.userAccountSubscriptionConfig, authority);
499
+ const result = await user.subscribe(userAccount);
500
+ if (result) {
501
+ this.users.set(userKey, user);
502
+ return true;
503
+ }
504
+ else {
505
+ return false;
506
+ }
507
+ }
508
+ /**
509
+ * Adds and subscribes to users based on params set by the constructor or by updateWallet.
510
+ */
511
+ async addAndSubscribeToUsers(authority) {
512
+ var _a, _b, _c, _d, _e, _f, _g;
513
+ // save the rpc calls if driftclient is initialized without a real wallet
514
+ if (this.skipLoadUsers)
515
+ return true;
516
+ let result = true;
517
+ if (this.authoritySubAccountMap && this.authoritySubAccountMap.size > 0) {
518
+ this.authoritySubAccountMap.forEach(async (value, key) => {
519
+ for (const subAccountId of value) {
520
+ result =
521
+ result && (await this.addUser(subAccountId, new web3_js_1.PublicKey(key)));
522
+ }
523
+ });
524
+ if (this.activeSubAccountId == undefined) {
525
+ this.switchActiveUser((_a = [...this.authoritySubAccountMap.values()][0][0]) !== null && _a !== void 0 ? _a : 0, new web3_js_1.PublicKey((_b = [...this.authoritySubAccountMap.keys()][0]) !== null && _b !== void 0 ? _b : this.authority.toString()));
526
+ }
527
+ }
528
+ else {
529
+ let userAccounts = [];
530
+ let delegatedAccounts = [];
531
+ const userAccountsPromise = this.getUserAccountsForAuthority(authority !== null && authority !== void 0 ? authority : this.wallet.publicKey);
532
+ if (this.includeDelegates) {
533
+ const delegatedAccountsPromise = this.getUserAccountsForDelegate(authority !== null && authority !== void 0 ? authority : this.wallet.publicKey);
534
+ [userAccounts, delegatedAccounts] = await Promise.all([
535
+ userAccountsPromise,
536
+ delegatedAccountsPromise,
537
+ ]);
538
+ !userAccounts && (userAccounts = []);
539
+ !delegatedAccounts && (delegatedAccounts = []);
540
+ }
541
+ else {
542
+ userAccounts = (_c = (await userAccountsPromise)) !== null && _c !== void 0 ? _c : [];
543
+ }
544
+ const allAccounts = userAccounts.concat(delegatedAccounts);
545
+ const addAllAccountsPromise = allAccounts.map((acc) => this.addUser(acc.subAccountId, acc.authority, acc));
546
+ const addAllAccountsResults = await Promise.all(addAllAccountsPromise);
547
+ result = addAllAccountsResults.every((res) => !!res);
548
+ if (this.activeSubAccountId == undefined) {
549
+ this.switchActiveUser((_e = (_d = userAccounts.concat(delegatedAccounts)[0]) === null || _d === void 0 ? void 0 : _d.subAccountId) !== null && _e !== void 0 ? _e : 0, (_g = (_f = userAccounts.concat(delegatedAccounts)[0]) === null || _f === void 0 ? void 0 : _f.authority) !== null && _g !== void 0 ? _g : this.authority);
550
+ }
551
+ }
552
+ return result;
553
+ }
554
+ async initializeUserAccount(subAccountId = 0, name, referrerInfo, txParams) {
555
+ const initializeIxs = [];
556
+ const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
557
+ if (subAccountId === 0) {
558
+ if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
559
+ initializeIxs.push(await this.getInitializeUserStatsIx());
560
+ }
561
+ }
562
+ initializeIxs.push(initializeUserAccountIx);
563
+ const tx = await this.buildTransaction(initializeIxs, txParams);
564
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
565
+ await this.addUser(subAccountId);
566
+ return [txSig, userAccountPublicKey];
567
+ }
568
+ async getInitializeUserStatsIx() {
569
+ return await this.program.instruction.initializeUserStats({
570
+ accounts: {
571
+ userStats: this.getUserStatsAccountPublicKey(),
572
+ authority: this.wallet.publicKey,
573
+ payer: this.wallet.publicKey,
574
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
575
+ systemProgram: anchor.web3.SystemProgram.programId,
576
+ state: await this.getStatePublicKey(),
577
+ },
578
+ });
579
+ }
580
+ async initializeRFQUser(userAccountPublicKey, txParams) {
581
+ const initializeIxs = [];
582
+ const [rfqUserAccountPublicKey, initializeUserAccountIx] = await this.getInitializeRFQUserInstruction(userAccountPublicKey);
583
+ initializeIxs.push(initializeUserAccountIx);
584
+ const tx = await this.buildTransaction(initializeIxs, txParams);
585
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
586
+ return [txSig, rfqUserAccountPublicKey];
587
+ }
588
+ async getInitializeRFQUserInstruction(userAccountPublicKey) {
589
+ const rfqUserAccountPublicKey = (0, pda_1.getRFQUserAccountPublicKey)(this.program.programId, userAccountPublicKey);
590
+ const initializeUserAccountIx = await this.program.instruction.initializeRfqUser({
591
+ accounts: {
592
+ rfqUser: rfqUserAccountPublicKey,
593
+ authority: this.wallet.publicKey,
594
+ user: userAccountPublicKey,
595
+ payer: this.wallet.publicKey,
596
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
597
+ systemProgram: anchor.web3.SystemProgram.programId,
598
+ },
599
+ });
600
+ return [rfqUserAccountPublicKey, initializeUserAccountIx];
601
+ }
602
+ async getInitializeUserInstructions(subAccountId = 0, name, referrerInfo) {
603
+ const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, subAccountId);
604
+ const remainingAccounts = new Array();
605
+ if (referrerInfo !== undefined) {
606
+ remainingAccounts.push({
607
+ pubkey: referrerInfo.referrer,
608
+ isWritable: true,
609
+ isSigner: false,
610
+ });
611
+ remainingAccounts.push({
612
+ pubkey: referrerInfo.referrerStats,
613
+ isWritable: true,
614
+ isSigner: false,
615
+ });
616
+ }
617
+ const state = this.getStateAccount();
618
+ if (!state.whitelistMint.equals(web3_js_1.PublicKey.default)) {
619
+ const associatedTokenPublicKey = await (0, spl_token_1.getAssociatedTokenAddress)(state.whitelistMint, this.wallet.publicKey);
620
+ remainingAccounts.push({
621
+ pubkey: associatedTokenPublicKey,
622
+ isWritable: false,
623
+ isSigner: false,
624
+ });
625
+ }
626
+ if (name === undefined) {
627
+ if (subAccountId === 0) {
628
+ name = userName_1.DEFAULT_USER_NAME;
629
+ }
630
+ else {
631
+ name = `Subaccount ${subAccountId + 1}`;
632
+ }
633
+ }
634
+ const nameBuffer = (0, userName_1.encodeName)(name);
635
+ const initializeUserAccountIx = await this.program.instruction.initializeUser(subAccountId, nameBuffer, {
636
+ accounts: {
637
+ user: userAccountPublicKey,
638
+ userStats: this.getUserStatsAccountPublicKey(),
639
+ authority: this.wallet.publicKey,
640
+ payer: this.wallet.publicKey,
641
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
642
+ systemProgram: anchor.web3.SystemProgram.programId,
643
+ state: await this.getStatePublicKey(),
644
+ },
645
+ remainingAccounts,
646
+ });
647
+ return [userAccountPublicKey, initializeUserAccountIx];
648
+ }
649
+ async getNextSubAccountId() {
650
+ const userStats = this.getUserStats();
651
+ let userStatsAccount;
652
+ if (!userStats) {
653
+ userStatsAccount = await (0, fetch_1.fetchUserStatsAccount)(this.connection, this.program, this.wallet.publicKey);
654
+ }
655
+ else {
656
+ userStatsAccount = userStats.getAccount();
657
+ }
658
+ return userStatsAccount.numberOfSubAccountsCreated;
659
+ }
660
+ async initializeReferrerName(name) {
661
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, 0);
662
+ const nameBuffer = (0, userName_1.encodeName)(name);
663
+ const referrerNameAccountPublicKey = (0, pda_1.getReferrerNamePublicKeySync)(this.program.programId, nameBuffer);
664
+ const tx = await this.program.transaction.initializeReferrerName(nameBuffer, {
665
+ accounts: {
666
+ referrerName: referrerNameAccountPublicKey,
667
+ user: userAccountPublicKey,
668
+ authority: this.wallet.publicKey,
669
+ userStats: this.getUserStatsAccountPublicKey(),
670
+ payer: this.wallet.publicKey,
671
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
672
+ systemProgram: anchor.web3.SystemProgram.programId,
673
+ },
674
+ });
675
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
676
+ return txSig;
677
+ }
678
+ async updateUserName(name, subAccountId = 0) {
679
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
680
+ const nameBuffer = (0, userName_1.encodeName)(name);
681
+ const tx = await this.program.transaction.updateUserName(subAccountId, nameBuffer, {
682
+ accounts: {
683
+ user: userAccountPublicKey,
684
+ authority: this.wallet.publicKey,
685
+ },
686
+ });
687
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
688
+ return txSig;
689
+ }
690
+ async updateUserCustomMarginRatio(updates, txParams) {
691
+ const ixs = await Promise.all(updates.map(async ({ marginRatio, subAccountId }) => {
692
+ const ix = await this.getUpdateUserCustomMarginRatioIx(marginRatio, subAccountId);
693
+ return ix;
694
+ }));
695
+ const tx = await this.buildTransaction(ixs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
696
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
697
+ return txSig;
698
+ }
699
+ async getUpdateUserCustomMarginRatioIx(marginRatio, subAccountId = 0) {
700
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
701
+ await this.addUser(subAccountId, this.wallet.publicKey);
702
+ const ix = this.program.instruction.updateUserCustomMarginRatio(subAccountId, marginRatio, {
703
+ accounts: {
704
+ user: userAccountPublicKey,
705
+ authority: this.wallet.publicKey,
706
+ },
707
+ });
708
+ return ix;
709
+ }
710
+ async getUpdateUserMarginTradingEnabledIx(marginTradingEnabled, subAccountId = 0, userAccountPublicKey) {
711
+ const userAccountPublicKeyToUse = userAccountPublicKey ||
712
+ (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
713
+ await this.addUser(subAccountId, this.wallet.publicKey);
714
+ let remainingAccounts;
715
+ try {
716
+ remainingAccounts = this.getRemainingAccounts({
717
+ userAccounts: [this.getUserAccount(subAccountId)],
718
+ });
719
+ }
720
+ catch (err) {
721
+ remainingAccounts = [];
722
+ }
723
+ return await this.program.instruction.updateUserMarginTradingEnabled(subAccountId, marginTradingEnabled, {
724
+ accounts: {
725
+ user: userAccountPublicKeyToUse,
726
+ authority: this.wallet.publicKey,
727
+ },
728
+ remainingAccounts,
729
+ });
730
+ }
731
+ async updateUserMarginTradingEnabled(updates) {
732
+ const ixs = await Promise.all(updates.map(async ({ marginTradingEnabled, subAccountId }) => {
733
+ return await this.getUpdateUserMarginTradingEnabledIx(marginTradingEnabled, subAccountId);
734
+ }));
735
+ const tx = await this.buildTransaction(ixs, this.txParams);
736
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
737
+ return txSig;
738
+ }
739
+ async updateUserDelegate(delegate, subAccountId = 0) {
740
+ const tx = await this.program.transaction.updateUserDelegate(subAccountId, delegate, {
741
+ accounts: {
742
+ user: await this.getUserAccountPublicKey(),
743
+ authority: this.wallet.publicKey,
744
+ },
745
+ });
746
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
747
+ return txSig;
748
+ }
749
+ async updateUserAdvancedLp(updates) {
750
+ const ixs = await Promise.all(updates.map(async ({ advancedLp, subAccountId }) => {
751
+ return await this.getUpdateAdvancedDlpIx(advancedLp, subAccountId);
752
+ }));
753
+ const tx = await this.buildTransaction(ixs, this.txParams);
754
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
755
+ return txSig;
756
+ }
757
+ async getUpdateAdvancedDlpIx(advancedLp, subAccountId) {
758
+ const ix = await this.program.instruction.updateUserAdvancedLp(subAccountId, advancedLp, {
759
+ accounts: {
760
+ user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
761
+ authority: this.wallet.publicKey,
762
+ },
763
+ });
764
+ return ix;
765
+ }
766
+ async updateUserReduceOnly(updates) {
767
+ const ixs = await Promise.all(updates.map(async ({ reduceOnly, subAccountId }) => {
768
+ return await this.getUpdateUserReduceOnlyIx(reduceOnly, subAccountId);
769
+ }));
770
+ const tx = await this.buildTransaction(ixs, this.txParams);
771
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
772
+ return txSig;
773
+ }
774
+ async getUpdateUserReduceOnlyIx(reduceOnly, subAccountId) {
775
+ const ix = await this.program.instruction.updateUserReduceOnly(subAccountId, reduceOnly, {
776
+ accounts: {
777
+ user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
778
+ authority: this.wallet.publicKey,
779
+ },
780
+ });
781
+ return ix;
782
+ }
783
+ async fetchAllUserAccounts(includeIdle = true) {
784
+ let filters = undefined;
785
+ if (!includeIdle) {
786
+ filters = [(0, memcmp_1.getNonIdleUserFilter)()];
787
+ }
788
+ return (await this.program.account.user.all(filters));
789
+ }
790
+ async getUserAccountsForDelegate(delegate) {
791
+ const programAccounts = await this.program.account.user.all([
792
+ {
793
+ memcmp: {
794
+ offset: 40,
795
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
796
+ bytes: bs58_1.default.encode(delegate.toBuffer()),
797
+ },
798
+ },
799
+ ]);
800
+ return programAccounts
801
+ .map((programAccount) => programAccount.account)
802
+ .sort((a, b) => a.subAccountId - b.subAccountId);
803
+ }
804
+ async getUserAccountsAndAddressesForAuthority(authority) {
805
+ const programAccounts = await this.program.account.user.all([
806
+ {
807
+ memcmp: {
808
+ offset: 8,
809
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
810
+ bytes: bs58_1.default.encode(authority.toBuffer()),
811
+ },
812
+ },
813
+ ]);
814
+ return programAccounts.map((programAccount) => programAccount);
815
+ }
816
+ async getUserAccountsForAuthority(authority) {
817
+ const programAccounts = await this.program.account.user.all([
818
+ {
819
+ memcmp: {
820
+ offset: 8,
821
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
822
+ bytes: bs58_1.default.encode(authority.toBuffer()),
823
+ },
824
+ },
825
+ ]);
826
+ return programAccounts
827
+ .map((programAccount) => programAccount.account)
828
+ .sort((a, b) => a.subAccountId - b.subAccountId);
829
+ }
830
+ async getReferredUserStatsAccountsByReferrer(referrer) {
831
+ const programAccounts = await this.program.account.userStats.all([
832
+ {
833
+ memcmp: {
834
+ offset: 40,
835
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
836
+ bytes: bs58_1.default.encode(referrer.toBuffer()),
837
+ },
838
+ },
839
+ ]);
840
+ return programAccounts.map((programAccount) => programAccount.account);
841
+ }
842
+ async getReferrerNameAccountsForAuthority(authority) {
843
+ const programAccounts = await this.program.account.referrerName.all([
844
+ {
845
+ memcmp: {
846
+ offset: 8,
847
+ /** data to match, as base-58 encoded string and limited to less than 129 bytes */
848
+ bytes: bs58_1.default.encode(authority.toBuffer()),
849
+ },
850
+ },
851
+ ]);
852
+ return programAccounts.map((programAccount) => programAccount.account);
853
+ }
854
+ async deleteUser(subAccountId = 0, txParams) {
855
+ var _a;
856
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
857
+ const ix = await this.getUserDeletionIx(userAccountPublicKey);
858
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(ix, txParams), [], this.opts);
859
+ const userMapKey = this.getUserMapKey(subAccountId, this.wallet.publicKey);
860
+ await ((_a = this.users.get(userMapKey)) === null || _a === void 0 ? void 0 : _a.unsubscribe());
861
+ this.users.delete(userMapKey);
862
+ return txSig;
863
+ }
864
+ async getUserDeletionIx(userAccountPublicKey) {
865
+ const ix = await this.program.instruction.deleteUser({
866
+ accounts: {
867
+ user: userAccountPublicKey,
868
+ userStats: this.getUserStatsAccountPublicKey(),
869
+ authority: this.wallet.publicKey,
870
+ state: await this.getStatePublicKey(),
871
+ },
872
+ });
873
+ return ix;
874
+ }
875
+ async reclaimRent(subAccountId = 0, txParams) {
876
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
877
+ const ix = await this.getReclaimRentIx(userAccountPublicKey);
878
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(ix, txParams), [], this.opts);
879
+ return txSig;
880
+ }
881
+ async getReclaimRentIx(userAccountPublicKey) {
882
+ return await this.program.instruction.reclaimRent({
883
+ accounts: {
884
+ user: userAccountPublicKey,
885
+ userStats: this.getUserStatsAccountPublicKey(),
886
+ authority: this.wallet.publicKey,
887
+ state: await this.getStatePublicKey(),
888
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
889
+ },
890
+ });
891
+ }
892
+ getUser(subAccountId, authority) {
893
+ subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
894
+ authority = authority !== null && authority !== void 0 ? authority : this.authority;
895
+ const userMapKey = this.getUserMapKey(subAccountId, authority);
896
+ if (!this.users.has(userMapKey)) {
897
+ throw new Error(`DriftClient has no user for user id ${userMapKey}`);
898
+ }
899
+ return this.users.get(userMapKey);
900
+ }
901
+ hasUser(subAccountId, authority) {
902
+ subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
903
+ authority = authority !== null && authority !== void 0 ? authority : this.authority;
904
+ const userMapKey = this.getUserMapKey(subAccountId, authority);
905
+ return this.users.has(userMapKey);
906
+ }
907
+ getUsers() {
908
+ // delegate users get added to the end
909
+ return [...this.users.values()]
910
+ .filter((acct) => acct.getUserAccount().authority.equals(this.wallet.publicKey))
911
+ .concat([...this.users.values()].filter((acct) => !acct.getUserAccount().authority.equals(this.wallet.publicKey)));
912
+ }
913
+ getUserStats() {
914
+ return this.userStats;
915
+ }
916
+ async fetchReferrerNameAccount(name) {
917
+ const nameBuffer = (0, userName_1.encodeName)(name);
918
+ const referrerNameAccountPublicKey = (0, pda_1.getReferrerNamePublicKeySync)(this.program.programId, nameBuffer);
919
+ return (await this.program.account.referrerName.fetch(referrerNameAccountPublicKey));
920
+ }
921
+ getUserStatsAccountPublicKey() {
922
+ if (this.userStatsAccountPublicKey) {
923
+ return this.userStatsAccountPublicKey;
924
+ }
925
+ this.userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
926
+ return this.userStatsAccountPublicKey;
927
+ }
928
+ async getUserAccountPublicKey(subAccountId, authority) {
929
+ return this.getUser(subAccountId, authority).userAccountPublicKey;
930
+ }
931
+ getUserAccount(subAccountId, authority) {
932
+ return this.getUser(subAccountId, authority).getUserAccount();
933
+ }
934
+ /**
935
+ * Forces a fetch to rpc before returning accounts. Useful for anchor tests.
936
+ * @param subAccountId
937
+ */
938
+ async forceGetUserAccount(subAccountId) {
939
+ await this.getUser(subAccountId).fetchAccounts();
940
+ return this.getUser(subAccountId).getUserAccount();
941
+ }
942
+ getUserAccountAndSlot(subAccountId) {
943
+ return this.getUser(subAccountId).getUserAccountAndSlot();
944
+ }
945
+ getSpotPosition(marketIndex, subAccountId) {
946
+ return this.getUserAccount(subAccountId).spotPositions.find((spotPosition) => spotPosition.marketIndex === marketIndex);
947
+ }
948
+ getQuoteAssetTokenAmount() {
949
+ return this.getTokenAmount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
950
+ }
951
+ /**
952
+ * Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
953
+ * Positive if it is a deposit, negative if it is a borrow.
954
+ * @param marketIndex
955
+ */
956
+ getTokenAmount(marketIndex) {
957
+ const spotPosition = this.getSpotPosition(marketIndex);
958
+ if (spotPosition === undefined) {
959
+ return numericConstants_1.ZERO;
960
+ }
961
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
962
+ return (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_1.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
963
+ }
964
+ /**
965
+ * Converts an amount to the spot precision for a given market. The spot market precision is based on the token mint decimals.
966
+ * @param marketIndex
967
+ * @param amount
968
+ */
969
+ convertToSpotPrecision(marketIndex, amount) {
970
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
971
+ return (0, spotMarket_1.castNumberToSpotPrecision)(amount, spotMarket);
972
+ }
973
+ /**
974
+ * Converts an amount to the perp precision. The perp market precision is {@link BASE_PRECISION} (1e9).
975
+ * @param amount
976
+ */
977
+ convertToPerpPrecision(amount) {
978
+ if (typeof amount === 'number') {
979
+ return (0, utils_1.numberToSafeBN)(amount, numericConstants_1.BASE_PRECISION);
980
+ }
981
+ else {
982
+ return amount.mul(numericConstants_1.BASE_PRECISION);
983
+ }
984
+ }
985
+ /**
986
+ * Converts an amount to the price precision. The perp market precision is {@link PRICE_PRECISION} (1e6).
987
+ * @param amount
988
+ */
989
+ convertToPricePrecision(amount) {
990
+ if (typeof amount === 'number') {
991
+ return (0, utils_1.numberToSafeBN)(amount, numericConstants_1.PRICE_PRECISION);
992
+ }
993
+ else {
994
+ return amount.mul(numericConstants_1.BASE_PRECISION);
995
+ }
996
+ }
997
+ /**
998
+ * Each drift instruction must include perp and sport market accounts in the ix remaining accounts.
999
+ * Use this function to force a subset of markets to be included in the remaining accounts for every ix
1000
+ *
1001
+ * @param perpMarketIndexes
1002
+ * @param spotMarketIndexes
1003
+ */
1004
+ mustIncludeMarketsInIx({ perpMarketIndexes, spotMarketIndexes, }) {
1005
+ perpMarketIndexes.forEach((perpMarketIndex) => {
1006
+ this.mustIncludePerpMarketIndexes.add(perpMarketIndex);
1007
+ });
1008
+ spotMarketIndexes.forEach((spotMarketIndex) => {
1009
+ this.mustIncludeSpotMarketIndexes.add(spotMarketIndex);
1010
+ });
1011
+ }
1012
+ getRemainingAccounts(params) {
1013
+ var _a;
1014
+ const { oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap } = this.getRemainingAccountMapsForUsers(params.userAccounts);
1015
+ if (params.useMarketLastSlotCache) {
1016
+ const lastUserSlot = (_a = this.getUserAccountAndSlot()) === null || _a === void 0 ? void 0 : _a.slot;
1017
+ for (const [marketIndex, slot,] of this.perpMarketLastSlotCache.entries()) {
1018
+ // if cache has more recent slot than user positions account slot, add market to remaining accounts
1019
+ // otherwise remove from slot
1020
+ if (slot > lastUserSlot) {
1021
+ this.addPerpMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
1022
+ }
1023
+ else {
1024
+ this.perpMarketLastSlotCache.delete(marketIndex);
1025
+ }
1026
+ }
1027
+ for (const [marketIndex, slot,] of this.spotMarketLastSlotCache.entries()) {
1028
+ // if cache has more recent slot than user positions account slot, add market to remaining accounts
1029
+ // otherwise remove from slot
1030
+ if (slot > lastUserSlot) {
1031
+ this.addSpotMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap);
1032
+ }
1033
+ else {
1034
+ this.spotMarketLastSlotCache.delete(marketIndex);
1035
+ }
1036
+ }
1037
+ }
1038
+ if (params.readablePerpMarketIndex !== undefined) {
1039
+ const readablePerpMarketIndexes = Array.isArray(params.readablePerpMarketIndex)
1040
+ ? params.readablePerpMarketIndex
1041
+ : [params.readablePerpMarketIndex];
1042
+ for (const marketIndex of readablePerpMarketIndexes) {
1043
+ this.addPerpMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
1044
+ }
1045
+ }
1046
+ for (const perpMarketIndex of this.mustIncludePerpMarketIndexes.values()) {
1047
+ this.addPerpMarketToRemainingAccountMaps(perpMarketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
1048
+ }
1049
+ if (params.readableSpotMarketIndexes !== undefined) {
1050
+ for (const readableSpotMarketIndex of params.readableSpotMarketIndexes) {
1051
+ this.addSpotMarketToRemainingAccountMaps(readableSpotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
1052
+ }
1053
+ }
1054
+ for (const spotMarketIndex of this.mustIncludeSpotMarketIndexes.values()) {
1055
+ this.addSpotMarketToRemainingAccountMaps(spotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
1056
+ }
1057
+ if (params.writablePerpMarketIndexes !== undefined) {
1058
+ for (const writablePerpMarketIndex of params.writablePerpMarketIndexes) {
1059
+ this.addPerpMarketToRemainingAccountMaps(writablePerpMarketIndex, true, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
1060
+ }
1061
+ }
1062
+ if (params.writableSpotMarketIndexes !== undefined) {
1063
+ for (const writableSpotMarketIndex of params.writableSpotMarketIndexes) {
1064
+ this.addSpotMarketToRemainingAccountMaps(writableSpotMarketIndex, true, oracleAccountMap, spotMarketAccountMap);
1065
+ }
1066
+ }
1067
+ return [
1068
+ ...oracleAccountMap.values(),
1069
+ ...spotMarketAccountMap.values(),
1070
+ ...perpMarketAccountMap.values(),
1071
+ ];
1072
+ }
1073
+ addPerpMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap) {
1074
+ const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
1075
+ perpMarketAccountMap.set(marketIndex, {
1076
+ pubkey: perpMarketAccount.pubkey,
1077
+ isSigner: false,
1078
+ isWritable: writable,
1079
+ });
1080
+ const oracleWritable = writable && (0, types_1.isVariant)(perpMarketAccount.amm.oracleSource, 'prelaunch');
1081
+ oracleAccountMap.set(perpMarketAccount.amm.oracle.toString(), {
1082
+ pubkey: perpMarketAccount.amm.oracle,
1083
+ isSigner: false,
1084
+ isWritable: oracleWritable,
1085
+ });
1086
+ this.addSpotMarketToRemainingAccountMaps(perpMarketAccount.quoteSpotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
1087
+ }
1088
+ addSpotMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap) {
1089
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1090
+ spotMarketAccountMap.set(spotMarketAccount.marketIndex, {
1091
+ pubkey: spotMarketAccount.pubkey,
1092
+ isSigner: false,
1093
+ isWritable: writable,
1094
+ });
1095
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1096
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1097
+ pubkey: spotMarketAccount.oracle,
1098
+ isSigner: false,
1099
+ isWritable: false,
1100
+ });
1101
+ }
1102
+ }
1103
+ getRemainingAccountMapsForUsers(userAccounts) {
1104
+ const oracleAccountMap = new Map();
1105
+ const spotMarketAccountMap = new Map();
1106
+ const perpMarketAccountMap = new Map();
1107
+ for (const userAccount of userAccounts) {
1108
+ for (const spotPosition of userAccount.spotPositions) {
1109
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1110
+ this.addSpotMarketToRemainingAccountMaps(spotPosition.marketIndex, false, oracleAccountMap, spotMarketAccountMap);
1111
+ if (!spotPosition.openAsks.eq(numericConstants_1.ZERO) ||
1112
+ !spotPosition.openBids.eq(numericConstants_1.ZERO)) {
1113
+ this.addSpotMarketToRemainingAccountMaps(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, false, oracleAccountMap, spotMarketAccountMap);
1114
+ }
1115
+ }
1116
+ }
1117
+ for (const position of userAccount.perpPositions) {
1118
+ if (!(0, position_1.positionIsAvailable)(position)) {
1119
+ this.addPerpMarketToRemainingAccountMaps(position.marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
1120
+ }
1121
+ }
1122
+ }
1123
+ return {
1124
+ oracleAccountMap,
1125
+ spotMarketAccountMap,
1126
+ perpMarketAccountMap,
1127
+ };
1128
+ }
1129
+ getOrder(orderId, subAccountId) {
1130
+ var _a;
1131
+ return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.orderId === orderId);
1132
+ }
1133
+ getOrderByUserId(userOrderId, subAccountId) {
1134
+ var _a;
1135
+ return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
1136
+ }
1137
+ /**
1138
+ * Get the associated token address for the given spot market
1139
+ * @param marketIndex
1140
+ * @param useNative
1141
+ * @param tokenProgram
1142
+ */
1143
+ async getAssociatedTokenAccount(marketIndex, useNative = true, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID) {
1144
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1145
+ if (useNative && spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT)) {
1146
+ return this.wallet.publicKey;
1147
+ }
1148
+ const mint = spotMarket.mint;
1149
+ return await (0, spl_token_1.getAssociatedTokenAddress)(mint, this.wallet.publicKey, undefined, tokenProgram);
1150
+ }
1151
+ createAssociatedTokenAccountIdempotentInstruction(account, payer, owner, mint, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID) {
1152
+ return new web3_js_1.TransactionInstruction({
1153
+ keys: [
1154
+ { pubkey: payer, isSigner: true, isWritable: true },
1155
+ { pubkey: account, isSigner: false, isWritable: true },
1156
+ { pubkey: owner, isSigner: false, isWritable: false },
1157
+ { pubkey: mint, isSigner: false, isWritable: false },
1158
+ {
1159
+ pubkey: anchor.web3.SystemProgram.programId,
1160
+ isSigner: false,
1161
+ isWritable: false,
1162
+ },
1163
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
1164
+ ],
1165
+ programId: spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
1166
+ data: Buffer.from([0x1]),
1167
+ });
1168
+ }
1169
+ async getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false) {
1170
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1171
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1172
+ const signerAuthority = this.wallet.publicKey;
1173
+ const createWSOLTokenAccount = isSolMarket && associatedTokenAccount.equals(signerAuthority);
1174
+ const instructions = [];
1175
+ if (createWSOLTokenAccount) {
1176
+ const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, true);
1177
+ associatedTokenAccount = pubkey;
1178
+ instructions.push(...ixs);
1179
+ }
1180
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly, true);
1181
+ instructions.push(depositCollateralIx);
1182
+ // Close the wrapped sol account at the end of the transaction
1183
+ if (createWSOLTokenAccount) {
1184
+ instructions.push((0, spl_token_1.createCloseAccountInstruction)(associatedTokenAccount, signerAuthority, signerAuthority, []));
1185
+ }
1186
+ return instructions;
1187
+ }
1188
+ async createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
1189
+ const instructions = await this.getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly);
1190
+ txParams = { ...(txParams !== null && txParams !== void 0 ? txParams : this.txParams), computeUnits: 600000 };
1191
+ const tx = await this.buildTransaction(instructions, txParams);
1192
+ return tx;
1193
+ }
1194
+ /**
1195
+ * Deposit funds into the given spot market
1196
+ *
1197
+ * @param amount to deposit
1198
+ * @param marketIndex spot market index to deposit into
1199
+ * @param associatedTokenAccount can be the wallet public key if using native sol
1200
+ * @param subAccountId subaccountId to deposit
1201
+ * @param reduceOnly if true, deposit must not increase account risk
1202
+ */
1203
+ async deposit(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
1204
+ const tx = await this.createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly, txParams);
1205
+ const { txSig, slot } = await this.sendTransaction(tx, [], this.opts);
1206
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
1207
+ return txSig;
1208
+ }
1209
+ async getDepositInstruction(amount, marketIndex, userTokenAccount, subAccountId, reduceOnly = false, userInitialized = true) {
1210
+ const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
1211
+ let remainingAccounts = [];
1212
+ if (userInitialized) {
1213
+ remainingAccounts = this.getRemainingAccounts({
1214
+ userAccounts: [await this.forceGetUserAccount()],
1215
+ useMarketLastSlotCache: true,
1216
+ writableSpotMarketIndexes: [marketIndex],
1217
+ });
1218
+ }
1219
+ else {
1220
+ remainingAccounts = this.getRemainingAccounts({
1221
+ userAccounts: [],
1222
+ writableSpotMarketIndexes: [marketIndex],
1223
+ });
1224
+ }
1225
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1226
+ this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
1227
+ const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
1228
+ return await this.program.instruction.deposit(marketIndex, amount, reduceOnly, {
1229
+ accounts: {
1230
+ state: await this.getStatePublicKey(),
1231
+ spotMarket: spotMarketAccount.pubkey,
1232
+ spotMarketVault: spotMarketAccount.vault,
1233
+ user: userAccountPublicKey,
1234
+ userStats: this.getUserStatsAccountPublicKey(),
1235
+ userTokenAccount: userTokenAccount,
1236
+ authority: this.wallet.publicKey,
1237
+ tokenProgram,
1238
+ },
1239
+ remainingAccounts,
1240
+ });
1241
+ }
1242
+ async checkIfAccountExists(account) {
1243
+ try {
1244
+ const accountInfo = await this.connection.getAccountInfo(account);
1245
+ return accountInfo != null;
1246
+ }
1247
+ catch (e) {
1248
+ // Doesn't already exist
1249
+ return false;
1250
+ }
1251
+ }
1252
+ async getWrappedSolAccountCreationIxs(amount, includeRent) {
1253
+ const authority = this.wallet.publicKey;
1254
+ // Generate a random seed for wrappedSolAccount.
1255
+ const seed = web3_js_1.Keypair.generate().publicKey.toBase58().slice(0, 32);
1256
+ // Calculate a publicKey that will be controlled by the authority.
1257
+ const wrappedSolAccount = await web3_js_1.PublicKey.createWithSeed(authority, seed, spl_token_1.TOKEN_PROGRAM_ID);
1258
+ const result = {
1259
+ ixs: [],
1260
+ signers: [],
1261
+ pubkey: wrappedSolAccount,
1262
+ };
1263
+ const rentSpaceLamports = new anchor_1.BN(web3_js_1.LAMPORTS_PER_SOL / 100);
1264
+ const lamports = includeRent
1265
+ ? amount.add(rentSpaceLamports)
1266
+ : rentSpaceLamports;
1267
+ result.ixs.push(web3_js_1.SystemProgram.createAccountWithSeed({
1268
+ fromPubkey: authority,
1269
+ basePubkey: authority,
1270
+ seed,
1271
+ newAccountPubkey: wrappedSolAccount,
1272
+ lamports: lamports.toNumber(),
1273
+ space: 165,
1274
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
1275
+ }));
1276
+ result.ixs.push((0, spl_token_1.createInitializeAccountInstruction)(wrappedSolAccount, spotMarkets_1.WRAPPED_SOL_MINT, authority));
1277
+ return result;
1278
+ }
1279
+ getTokenProgramForSpotMarket(spotMarketAccount) {
1280
+ if (spotMarketAccount.tokenProgram === 1) {
1281
+ return spl_token_1.TOKEN_2022_PROGRAM_ID;
1282
+ }
1283
+ return spl_token_1.TOKEN_PROGRAM_ID;
1284
+ }
1285
+ addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts) {
1286
+ if (spotMarketAccount.tokenProgram === 1) {
1287
+ remainingAccounts.push({
1288
+ pubkey: spotMarketAccount.mint,
1289
+ isSigner: false,
1290
+ isWritable: false,
1291
+ });
1292
+ }
1293
+ }
1294
+ getAssociatedTokenAccountCreationIx(tokenMintAddress, associatedTokenAddress, tokenProgram) {
1295
+ return (0, spl_token_1.createAssociatedTokenAccountInstruction)(this.wallet.publicKey, associatedTokenAddress, this.wallet.publicKey, tokenMintAddress, tokenProgram);
1296
+ }
1297
+ async createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio) {
1298
+ const ixs = [];
1299
+ const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
1300
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1301
+ const isSolMarket = spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1302
+ const authority = this.wallet.publicKey;
1303
+ const isFromSubaccount = fromSubAccountId !== null &&
1304
+ fromSubAccountId !== undefined &&
1305
+ !isNaN(fromSubAccountId);
1306
+ donateAmount = donateAmount ? donateAmount : numericConstants_1.ZERO;
1307
+ const createWSOLTokenAccount = (isSolMarket &&
1308
+ userTokenAccount.equals(authority) &&
1309
+ !isFromSubaccount) ||
1310
+ !donateAmount.eq(numericConstants_1.ZERO);
1311
+ const wSolAmount = isSolMarket ? amount.add(donateAmount) : donateAmount;
1312
+ let wsolTokenAccount;
1313
+ if (createWSOLTokenAccount) {
1314
+ const { ixs: startIxs, pubkey } = await this.getWrappedSolAccountCreationIxs(wSolAmount, true);
1315
+ wsolTokenAccount = pubkey;
1316
+ if (isSolMarket) {
1317
+ userTokenAccount = pubkey;
1318
+ }
1319
+ ixs.push(...startIxs);
1320
+ }
1321
+ const depositCollateralIx = isFromSubaccount
1322
+ ? await this.getTransferDepositIx(amount, marketIndex, fromSubAccountId, subAccountId)
1323
+ : await this.getDepositInstruction(amount, marketIndex, userTokenAccount, subAccountId, false, false);
1324
+ if (subAccountId === 0) {
1325
+ if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
1326
+ ixs.push(await this.getInitializeUserStatsIx());
1327
+ }
1328
+ }
1329
+ ixs.push(initializeUserAccountIx, depositCollateralIx);
1330
+ if (!donateAmount.eq(numericConstants_1.ZERO)) {
1331
+ const donateIx = await this.getDepositIntoSpotMarketRevenuePoolIx(1, donateAmount, wsolTokenAccount);
1332
+ ixs.push(donateIx);
1333
+ }
1334
+ // Set the max margin ratio to initialize account with if passed
1335
+ if (customMaxMarginRatio) {
1336
+ const customMarginRatioIx = await this.getUpdateUserCustomMarginRatioIx(customMaxMarginRatio, subAccountId);
1337
+ ixs.push(customMarginRatioIx);
1338
+ }
1339
+ // Close the wrapped sol account at the end of the transaction
1340
+ if (createWSOLTokenAccount) {
1341
+ ixs.push((0, spl_token_1.createCloseAccountInstruction)(wsolTokenAccount, authority, authority, []));
1342
+ }
1343
+ return {
1344
+ ixs,
1345
+ userAccountPublicKey,
1346
+ };
1347
+ }
1348
+ async createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
1349
+ const { ixs, userAccountPublicKey } = await this.createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio);
1350
+ const tx = await this.buildTransaction(ixs, txParams);
1351
+ return [tx, userAccountPublicKey];
1352
+ }
1353
+ /**
1354
+ * Creates the User account for a user, and deposits some initial collateral
1355
+ * @param amount
1356
+ * @param userTokenAccount
1357
+ * @param marketIndex
1358
+ * @param subAccountId
1359
+ * @param name
1360
+ * @param fromSubAccountId
1361
+ * @param referrerInfo
1362
+ * @param donateAmount
1363
+ * @param txParams
1364
+ * @returns
1365
+ */
1366
+ async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
1367
+ const [tx, userAccountPublicKey] = await this.createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio);
1368
+ const additionalSigners = [];
1369
+ const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
1370
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
1371
+ await this.addUser(subAccountId);
1372
+ return [txSig, userAccountPublicKey];
1373
+ }
1374
+ async initializeUserAccountForDevnet(subAccountId = 0, name = userName_1.DEFAULT_USER_NAME, marketIndex, tokenFaucet, amount, referrerInfo, txParams) {
1375
+ const ixs = [];
1376
+ const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await tokenFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
1377
+ const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
1378
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associateTokenPublicKey, subAccountId, false, false);
1379
+ ixs.push(createAssociatedAccountIx, mintToIx);
1380
+ if (subAccountId === 0) {
1381
+ if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
1382
+ ixs.push(await this.getInitializeUserStatsIx());
1383
+ }
1384
+ }
1385
+ ixs.push(initializeUserAccountIx, depositCollateralIx);
1386
+ const tx = await this.buildTransaction(ixs, txParams);
1387
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
1388
+ await this.addUser(subAccountId);
1389
+ return [txSig, userAccountPublicKey];
1390
+ }
1391
+ async getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly = false, subAccountId) {
1392
+ const withdrawIxs = [];
1393
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1394
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
1395
+ const authority = this.wallet.publicKey;
1396
+ const createWSOLTokenAccount = isSolMarket && associatedTokenAddress.equals(authority);
1397
+ if (createWSOLTokenAccount) {
1398
+ const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, false);
1399
+ associatedTokenAddress = pubkey;
1400
+ withdrawIxs.push(...ixs);
1401
+ }
1402
+ else {
1403
+ const accountExists = await this.checkIfAccountExists(associatedTokenAddress);
1404
+ if (!accountExists) {
1405
+ const createAssociatedTokenAccountIx = this.getAssociatedTokenAccountCreationIx(spotMarketAccount.mint, associatedTokenAddress, this.getTokenProgramForSpotMarket(spotMarketAccount));
1406
+ withdrawIxs.push(createAssociatedTokenAccountIx);
1407
+ }
1408
+ }
1409
+ const withdrawCollateralIx = await this.getWithdrawIx(amount, spotMarketAccount.marketIndex, associatedTokenAddress, reduceOnly, subAccountId);
1410
+ withdrawIxs.push(withdrawCollateralIx);
1411
+ // Close the wrapped sol account at the end of the transaction
1412
+ if (createWSOLTokenAccount) {
1413
+ withdrawIxs.push((0, spl_token_1.createCloseAccountInstruction)(associatedTokenAddress, authority, authority, []));
1414
+ }
1415
+ return withdrawIxs;
1416
+ }
1417
+ /**
1418
+ * Withdraws from a user account. If deposit doesn't already exist, creates a borrow
1419
+ * @param amount
1420
+ * @param marketIndex
1421
+ * @param associatedTokenAddress - the token account to withdraw to. can be the wallet public key if using native sol
1422
+ * @param reduceOnly
1423
+ */
1424
+ async withdraw(amount, marketIndex, associatedTokenAddress, reduceOnly = false, subAccountId, txParams) {
1425
+ const additionalSigners = [];
1426
+ const withdrawIxs = await this.getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly, subAccountId);
1427
+ const tx = await this.buildTransaction(withdrawIxs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
1428
+ const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
1429
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
1430
+ return txSig;
1431
+ }
1432
+ async withdrawAllDustPositions(subAccountId, txParams, opts) {
1433
+ var _a, _b;
1434
+ const user = this.getUser(subAccountId);
1435
+ const dustPositionSpotMarketAccounts = user.getSpotMarketAccountsWithDustPosition();
1436
+ if (!dustPositionSpotMarketAccounts ||
1437
+ dustPositionSpotMarketAccounts.length === 0) {
1438
+ (_a = opts === null || opts === void 0 ? void 0 : opts.dustPositionCountCallback) === null || _a === void 0 ? void 0 : _a.call(opts, 0);
1439
+ return undefined;
1440
+ }
1441
+ (_b = opts === null || opts === void 0 ? void 0 : opts.dustPositionCountCallback) === null || _b === void 0 ? void 0 : _b.call(opts, dustPositionSpotMarketAccounts.length);
1442
+ let allWithdrawIxs = [];
1443
+ for (const position of dustPositionSpotMarketAccounts) {
1444
+ const tokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(position.mint, this.wallet.publicKey);
1445
+ const tokenAmount = await user.getTokenAmount(position.marketIndex);
1446
+ const withdrawIxs = await this.getWithdrawalIxs(tokenAmount.muln(2), // 2x to ensure all dust is withdrawn
1447
+ position.marketIndex, tokenAccount, true, // reduce-only true to ensure all dust is withdrawn
1448
+ subAccountId);
1449
+ allWithdrawIxs = allWithdrawIxs.concat(withdrawIxs);
1450
+ }
1451
+ const tx = await this.buildTransaction(allWithdrawIxs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
1452
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
1453
+ return txSig;
1454
+ }
1455
+ async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false, subAccountId) {
1456
+ const user = await this.getUserAccountPublicKey(subAccountId);
1457
+ const remainingAccounts = this.getRemainingAccounts({
1458
+ userAccounts: [this.getUserAccount(subAccountId)],
1459
+ useMarketLastSlotCache: true,
1460
+ writableSpotMarketIndexes: [marketIndex],
1461
+ readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1462
+ });
1463
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1464
+ this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
1465
+ const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
1466
+ return await this.program.instruction.withdraw(marketIndex, amount, reduceOnly, {
1467
+ accounts: {
1468
+ state: await this.getStatePublicKey(),
1469
+ spotMarket: spotMarketAccount.pubkey,
1470
+ spotMarketVault: spotMarketAccount.vault,
1471
+ driftSigner: this.getSignerPublicKey(),
1472
+ user,
1473
+ userStats: this.getUserStatsAccountPublicKey(),
1474
+ userTokenAccount: userTokenAccount,
1475
+ authority: this.wallet.publicKey,
1476
+ tokenProgram,
1477
+ },
1478
+ remainingAccounts,
1479
+ });
1480
+ }
1481
+ /**
1482
+ * Withdraws from the fromSubAccount and deposits into the toSubAccount
1483
+ * @param amount
1484
+ * @param marketIndex
1485
+ * @param fromSubAccountId
1486
+ * @param toSubAccountId
1487
+ * @param txParams
1488
+ */
1489
+ async transferDeposit(amount, marketIndex, fromSubAccountId, toSubAccountId, txParams) {
1490
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositIx(amount, marketIndex, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
1491
+ if (fromSubAccountId === this.activeSubAccountId ||
1492
+ toSubAccountId === this.activeSubAccountId) {
1493
+ this.spotMarketLastSlotCache.set(marketIndex, slot);
1494
+ }
1495
+ return txSig;
1496
+ }
1497
+ async getTransferDepositIx(amount, marketIndex, fromSubAccountId, toSubAccountId) {
1498
+ const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromSubAccountId);
1499
+ const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toSubAccountId);
1500
+ let remainingAccounts;
1501
+ const userMapKey = this.getUserMapKey(fromSubAccountId, this.wallet.publicKey);
1502
+ if (this.users.has(userMapKey)) {
1503
+ remainingAccounts = this.getRemainingAccounts({
1504
+ userAccounts: [this.users.get(userMapKey).getUserAccount()],
1505
+ useMarketLastSlotCache: true,
1506
+ writableSpotMarketIndexes: [marketIndex],
1507
+ });
1508
+ }
1509
+ else {
1510
+ const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.authority, fromSubAccountId);
1511
+ const fromUserAccount = (await this.program.account.user.fetch(userAccountPublicKey));
1512
+ remainingAccounts = this.getRemainingAccounts({
1513
+ userAccounts: [fromUserAccount],
1514
+ useMarketLastSlotCache: true,
1515
+ writableSpotMarketIndexes: [marketIndex],
1516
+ });
1517
+ }
1518
+ return await this.program.instruction.transferDeposit(marketIndex, amount, {
1519
+ accounts: {
1520
+ authority: this.wallet.publicKey,
1521
+ fromUser,
1522
+ toUser,
1523
+ userStats: this.getUserStatsAccountPublicKey(),
1524
+ state: await this.getStatePublicKey(),
1525
+ spotMarketVault: this.getSpotMarketAccount(marketIndex).vault,
1526
+ },
1527
+ remainingAccounts,
1528
+ });
1529
+ }
1530
+ async updateSpotMarketCumulativeInterest(marketIndex, txParams) {
1531
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.updateSpotMarketCumulativeInterestIx(marketIndex), txParams), [], this.opts);
1532
+ return txSig;
1533
+ }
1534
+ async updateSpotMarketCumulativeInterestIx(marketIndex) {
1535
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1536
+ return await this.program.instruction.updateSpotMarketCumulativeInterest({
1537
+ accounts: {
1538
+ state: await this.getStatePublicKey(),
1539
+ spotMarket: spotMarket.pubkey,
1540
+ spotMarketVault: spotMarket.vault,
1541
+ oracle: spotMarket.oracle,
1542
+ },
1543
+ });
1544
+ }
1545
+ async settleLP(settleeUserAccountPublicKey, marketIndex, txParams) {
1546
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleLPIx(settleeUserAccountPublicKey, marketIndex), txParams), [], this.opts);
1547
+ return txSig;
1548
+ }
1549
+ async settleLPIx(settleeUserAccountPublicKey, marketIndex) {
1550
+ const settleeUserAccount = (await this.program.account.user.fetch(settleeUserAccountPublicKey));
1551
+ const remainingAccounts = this.getRemainingAccounts({
1552
+ userAccounts: [settleeUserAccount],
1553
+ writablePerpMarketIndexes: [marketIndex],
1554
+ });
1555
+ return this.program.instruction.settleLp(marketIndex, {
1556
+ accounts: {
1557
+ state: await this.getStatePublicKey(),
1558
+ user: settleeUserAccountPublicKey,
1559
+ },
1560
+ remainingAccounts: remainingAccounts,
1561
+ });
1562
+ }
1563
+ async removePerpLpShares(marketIndex, sharesToBurn, txParams, subAccountId) {
1564
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getRemovePerpLpSharesIx(marketIndex, sharesToBurn, subAccountId), txParams), [], this.opts);
1565
+ return txSig;
1566
+ }
1567
+ async removePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn, txParams) {
1568
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getRemovePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn), txParams), [], this.opts);
1569
+ return txSig;
1570
+ }
1571
+ async getRemovePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn) {
1572
+ const userAccount = (await this.program.account.user.fetch(userAccountPublicKey));
1573
+ const remainingAccounts = this.getRemainingAccounts({
1574
+ userAccounts: [userAccount],
1575
+ useMarketLastSlotCache: true,
1576
+ writablePerpMarketIndexes: [marketIndex],
1577
+ });
1578
+ if (sharesToBurn == undefined) {
1579
+ const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex === marketIndex)[0];
1580
+ sharesToBurn = perpPosition.lpShares;
1581
+ console.log('burning lp shares:', sharesToBurn.toString());
1582
+ }
1583
+ return this.program.instruction.removePerpLpSharesInExpiringMarket(sharesToBurn, marketIndex, {
1584
+ accounts: {
1585
+ state: await this.getStatePublicKey(),
1586
+ user: userAccountPublicKey,
1587
+ },
1588
+ remainingAccounts: remainingAccounts,
1589
+ });
1590
+ }
1591
+ async getRemovePerpLpSharesIx(marketIndex, sharesToBurn, subAccountId) {
1592
+ const user = await this.getUserAccountPublicKey(subAccountId);
1593
+ const remainingAccounts = this.getRemainingAccounts({
1594
+ userAccounts: [this.getUserAccount(subAccountId)],
1595
+ useMarketLastSlotCache: true,
1596
+ writablePerpMarketIndexes: [marketIndex],
1597
+ });
1598
+ if (sharesToBurn == undefined) {
1599
+ const userAccount = this.getUserAccount(subAccountId);
1600
+ const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex === marketIndex)[0];
1601
+ sharesToBurn = perpPosition.lpShares;
1602
+ console.log('burning lp shares:', sharesToBurn.toString());
1603
+ }
1604
+ return this.program.instruction.removePerpLpShares(sharesToBurn, marketIndex, {
1605
+ accounts: {
1606
+ state: await this.getStatePublicKey(),
1607
+ user,
1608
+ authority: this.wallet.publicKey,
1609
+ },
1610
+ remainingAccounts: remainingAccounts,
1611
+ });
1612
+ }
1613
+ async addPerpLpShares(amount, marketIndex, txParams, subAccountId) {
1614
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getAddPerpLpSharesIx(amount, marketIndex, subAccountId), txParams), [], this.opts);
1615
+ this.perpMarketLastSlotCache.set(marketIndex, slot);
1616
+ return txSig;
1617
+ }
1618
+ async getAddPerpLpSharesIx(amount, marketIndex, subAccountId) {
1619
+ const user = await this.getUserAccountPublicKey(subAccountId);
1620
+ const remainingAccounts = this.getRemainingAccounts({
1621
+ userAccounts: [this.getUserAccount(subAccountId)],
1622
+ useMarketLastSlotCache: true,
1623
+ writablePerpMarketIndexes: [marketIndex],
1624
+ });
1625
+ return this.program.instruction.addPerpLpShares(amount, marketIndex, {
1626
+ accounts: {
1627
+ state: await this.getStatePublicKey(),
1628
+ user,
1629
+ authority: this.wallet.publicKey,
1630
+ },
1631
+ remainingAccounts: remainingAccounts,
1632
+ });
1633
+ }
1634
+ getQuoteValuePerLpShare(marketIndex) {
1635
+ const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
1636
+ const openBids = anchor_1.BN.max(perpMarketAccount.amm.baseAssetReserve.sub(perpMarketAccount.amm.minBaseAssetReserve), numericConstants_1.ZERO);
1637
+ const openAsks = anchor_1.BN.max(perpMarketAccount.amm.maxBaseAssetReserve.sub(perpMarketAccount.amm.baseAssetReserve), numericConstants_1.ZERO);
1638
+ const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
1639
+ const maxOpenBidsAsks = anchor_1.BN.max(openBids, openAsks);
1640
+ const quoteValuePerLpShare = maxOpenBidsAsks
1641
+ .mul(oraclePriceData.price)
1642
+ .mul(numericConstants_1.QUOTE_PRECISION)
1643
+ .div(numericConstants_1.PRICE_PRECISION)
1644
+ .div(perpMarketAccount.amm.sqrtK);
1645
+ return quoteValuePerLpShare;
1646
+ }
1647
+ /**
1648
+ * @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
1649
+ */
1650
+ async openPosition(direction, amount, marketIndex, limitPrice, subAccountId) {
1651
+ return await this.placeAndTakePerpOrder({
1652
+ orderType: types_1.OrderType.MARKET,
1653
+ marketIndex,
1654
+ direction,
1655
+ baseAssetAmount: amount,
1656
+ price: limitPrice,
1657
+ }, undefined, undefined, undefined, undefined, subAccountId);
1658
+ }
1659
+ async sendSignedTx(tx, opts) {
1660
+ const { txSig } = await this.sendTransaction(tx, undefined, opts !== null && opts !== void 0 ? opts : this.opts, true);
1661
+ return txSig;
1662
+ }
1663
+ async prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl) {
1664
+ const marketIndex = orderParams.marketIndex;
1665
+ const orderId = userAccount.nextOrderId;
1666
+ const ixPromisesForTxs = {
1667
+ cancelExistingOrdersTx: undefined,
1668
+ settlePnlTx: undefined,
1669
+ fillTx: undefined,
1670
+ marketOrderTx: undefined,
1671
+ };
1672
+ const txKeys = Object.keys(ixPromisesForTxs);
1673
+ ixPromisesForTxs.marketOrderTx = this.getPlaceOrdersIx([orderParams, ...bracketOrdersParams], userAccount.subAccountId);
1674
+ /* Cancel open orders in market if requested */
1675
+ if (cancelExistingOrders && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
1676
+ ixPromisesForTxs.cancelExistingOrdersTx = this.getCancelOrdersIx(orderParams.marketType, orderParams.marketIndex, null, userAccount.subAccountId);
1677
+ }
1678
+ /* Settle PnL after fill if requested */
1679
+ if (settlePnl && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
1680
+ ixPromisesForTxs.settlePnlTx = this.settlePNLIx(userAccountPublicKey, userAccount, marketIndex);
1681
+ }
1682
+ // use versioned transactions if there is a lookup table account and wallet is compatible
1683
+ if (this.txVersion === 0) {
1684
+ ixPromisesForTxs.fillTx = this.getFillPerpOrderIx(userAccountPublicKey, userAccount, {
1685
+ orderId,
1686
+ marketIndex,
1687
+ }, makerInfo, referrerInfo, userAccount.subAccountId);
1688
+ }
1689
+ const ixs = await Promise.all(Object.values(ixPromisesForTxs));
1690
+ const ixsMap = ixs.reduce((acc, ix, i) => {
1691
+ acc[txKeys[i]] = ix;
1692
+ return acc;
1693
+ }, {});
1694
+ const txsMap = (await this.buildTransactionsMap(ixsMap, txParams));
1695
+ return txsMap;
1696
+ }
1697
+ /**
1698
+ * Sends a market order and returns a signed tx which can fill the order against the vamm, which the caller can use to fill their own order if required.
1699
+ * @param orderParams
1700
+ * @param userAccountPublicKey
1701
+ * @param userAccount
1702
+ * @param makerInfo
1703
+ * @param txParams
1704
+ * @param bracketOrdersParams
1705
+ * @param cancelExistingOrders - Builds and returns an extra transaciton to cancel the existing orders in the same perp market. Intended use is to auto-cancel TP/SL orders when closing a position. Ignored if orderParams.marketType is not MarketType.PERP
1706
+ * @returns
1707
+ */
1708
+ async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl) {
1709
+ const preppedTxs = await this.prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams, referrerInfo, cancelExistingOrders, settlePnl);
1710
+ const signedTxs = (await this.txHandler.getSignedTransactionMap(preppedTxs, this.wallet)).signedTxMap;
1711
+ const { txSig, slot } = await this.sendTransaction(signedTxs.marketOrderTx, [], this.opts, true);
1712
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
1713
+ return {
1714
+ txSig,
1715
+ signedFillTx: signedTxs.fillTx,
1716
+ signedCancelExistingOrdersTx: signedTxs.cancelExistingOrdersTx,
1717
+ signedSettlePnlTx: signedTxs.settlePnlTx,
1718
+ };
1719
+ }
1720
+ async placePerpOrder(orderParams, txParams, subAccountId) {
1721
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlacePerpOrderIx(orderParams, subAccountId), txParams), [], this.opts);
1722
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
1723
+ return txSig;
1724
+ }
1725
+ async getPlacePerpOrderIx(orderParams, subAccountId, depositToTradeArgs) {
1726
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
1727
+ const isDepositToTradeTx = depositToTradeArgs !== undefined;
1728
+ const user = isDepositToTradeTx
1729
+ ? (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.authority, subAccountId)
1730
+ : await this.getUserAccountPublicKey(subAccountId);
1731
+ const remainingAccounts = this.getRemainingAccounts({
1732
+ userAccounts: (depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.isMakingNewAccount)
1733
+ ? []
1734
+ : [this.getUserAccount(subAccountId)],
1735
+ useMarketLastSlotCache: false,
1736
+ readablePerpMarketIndex: orderParams.marketIndex,
1737
+ readableSpotMarketIndexes: isDepositToTradeTx
1738
+ ? [depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.depositMarketIndex]
1739
+ : undefined,
1740
+ });
1741
+ return await this.program.instruction.placePerpOrder(orderParams, {
1742
+ accounts: {
1743
+ state: await this.getStatePublicKey(),
1744
+ user,
1745
+ userStats: this.getUserStatsAccountPublicKey(),
1746
+ authority: this.wallet.publicKey,
1747
+ },
1748
+ remainingAccounts,
1749
+ });
1750
+ }
1751
+ async updateAMMs(marketIndexes, txParams) {
1752
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateAMMsIx(marketIndexes), txParams), [], this.opts);
1753
+ return txSig;
1754
+ }
1755
+ async getUpdateAMMsIx(marketIndexes) {
1756
+ for (let i = marketIndexes.length; i < 5; i++) {
1757
+ marketIndexes.push(100);
1758
+ }
1759
+ const marketAccountInfos = [];
1760
+ const oracleAccountInfos = [];
1761
+ for (const marketIndex of marketIndexes) {
1762
+ if (marketIndex !== 100) {
1763
+ const market = this.getPerpMarketAccount(marketIndex);
1764
+ marketAccountInfos.push({
1765
+ pubkey: market.pubkey,
1766
+ isWritable: true,
1767
+ isSigner: false,
1768
+ });
1769
+ oracleAccountInfos.push({
1770
+ pubkey: market.amm.oracle,
1771
+ isWritable: false,
1772
+ isSigner: false,
1773
+ });
1774
+ }
1775
+ }
1776
+ const remainingAccounts = oracleAccountInfos.concat(marketAccountInfos);
1777
+ return await this.program.instruction.updateAmms(marketIndexes, {
1778
+ accounts: {
1779
+ state: await this.getStatePublicKey(),
1780
+ authority: this.wallet.publicKey,
1781
+ },
1782
+ remainingAccounts,
1783
+ });
1784
+ }
1785
+ async settleExpiredMarket(marketIndex, txParams) {
1786
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleExpiredMarketIx(marketIndex), txParams), [], this.opts);
1787
+ return txSig;
1788
+ }
1789
+ async getSettleExpiredMarketIx(marketIndex) {
1790
+ const remainingAccounts = this.getRemainingAccounts({
1791
+ userAccounts: [],
1792
+ writablePerpMarketIndexes: [marketIndex],
1793
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1794
+ });
1795
+ const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, marketIndex);
1796
+ return await this.program.instruction.settleExpiredMarket(marketIndex, {
1797
+ accounts: {
1798
+ state: await this.getStatePublicKey(),
1799
+ admin: this.isSubscribed
1800
+ ? this.getStateAccount().admin
1801
+ : this.wallet.publicKey,
1802
+ perpMarket: perpMarketPublicKey,
1803
+ },
1804
+ remainingAccounts,
1805
+ });
1806
+ }
1807
+ async settleExpiredMarketPoolsToRevenuePool(marketIndex, txParams) {
1808
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleExpiredMarketPoolsToRevenuePoolIx(marketIndex), txParams), [], this.opts);
1809
+ return txSig;
1810
+ }
1811
+ async getSettleExpiredMarketPoolsToRevenuePoolIx(perpMarketIndex) {
1812
+ const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, perpMarketIndex);
1813
+ const spotMarketPublicKey = await (0, pda_1.getSpotMarketPublicKey)(this.program.programId, numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
1814
+ return await this.program.instruction.settleExpiredMarketPoolsToRevenuePool({
1815
+ accounts: {
1816
+ state: await this.getStatePublicKey(),
1817
+ admin: this.isSubscribed
1818
+ ? this.getStateAccount().admin
1819
+ : this.wallet.publicKey,
1820
+ spotMarket: spotMarketPublicKey,
1821
+ perpMarket: perpMarketPublicKey,
1822
+ },
1823
+ });
1824
+ }
1825
+ async cancelOrder(orderId, txParams, subAccountId) {
1826
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrderIx(orderId, subAccountId), txParams), [], this.opts);
1827
+ return txSig;
1828
+ }
1829
+ async getCancelOrderIx(orderId, subAccountId) {
1830
+ const user = await this.getUserAccountPublicKey(subAccountId);
1831
+ const remainingAccounts = this.getRemainingAccounts({
1832
+ userAccounts: [this.getUserAccount(subAccountId)],
1833
+ useMarketLastSlotCache: true,
1834
+ });
1835
+ return await this.program.instruction.cancelOrder(orderId !== null && orderId !== void 0 ? orderId : null, {
1836
+ accounts: {
1837
+ state: await this.getStatePublicKey(),
1838
+ user,
1839
+ authority: this.wallet.publicKey,
1840
+ },
1841
+ remainingAccounts,
1842
+ });
1843
+ }
1844
+ async cancelOrderByUserId(userOrderId, txParams, subAccountId) {
1845
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrderByUserIdIx(userOrderId, subAccountId), txParams), [], this.opts);
1846
+ return txSig;
1847
+ }
1848
+ async getCancelOrderByUserIdIx(userOrderId, subAccountId) {
1849
+ const user = await this.getUserAccountPublicKey(subAccountId);
1850
+ const order = this.getOrderByUserId(userOrderId);
1851
+ const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
1852
+ const remainingAccounts = this.getRemainingAccounts({
1853
+ userAccounts: [this.getUserAccount(subAccountId)],
1854
+ useMarketLastSlotCache: true,
1855
+ });
1856
+ return await this.program.instruction.cancelOrderByUserId(userOrderId, {
1857
+ accounts: {
1858
+ state: await this.getStatePublicKey(),
1859
+ user,
1860
+ authority: this.wallet.publicKey,
1861
+ oracle,
1862
+ },
1863
+ remainingAccounts,
1864
+ });
1865
+ }
1866
+ async cancelOrdersByIds(orderIds, txParams, subAccountId) {
1867
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersByIdsIx(orderIds, subAccountId), txParams), [], this.opts);
1868
+ return txSig;
1869
+ }
1870
+ async getCancelOrdersByIdsIx(orderIds, subAccountId) {
1871
+ const user = await this.getUserAccountPublicKey(subAccountId);
1872
+ const remainingAccounts = this.getRemainingAccounts({
1873
+ userAccounts: [this.getUserAccount(subAccountId)],
1874
+ useMarketLastSlotCache: true,
1875
+ });
1876
+ return await this.program.instruction.cancelOrdersByIds(orderIds, {
1877
+ accounts: {
1878
+ state: await this.getStatePublicKey(),
1879
+ user,
1880
+ authority: this.wallet.publicKey,
1881
+ },
1882
+ remainingAccounts,
1883
+ });
1884
+ }
1885
+ async cancelOrders(marketType, marketIndex, direction, txParams, subAccountId) {
1886
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersIx(marketType, marketIndex, direction, subAccountId), txParams), [], this.opts);
1887
+ return txSig;
1888
+ }
1889
+ async getCancelOrdersIx(marketType, marketIndex, direction, subAccountId) {
1890
+ const user = await this.getUserAccountPublicKey(subAccountId);
1891
+ let readablePerpMarketIndex = undefined;
1892
+ let readableSpotMarketIndexes = undefined;
1893
+ if (typeof marketIndex === 'number') {
1894
+ if (marketType && (0, types_1.isVariant)(marketType, 'perp')) {
1895
+ readablePerpMarketIndex = marketIndex;
1896
+ }
1897
+ else if (marketType && (0, types_1.isVariant)(marketType, 'spot')) {
1898
+ readableSpotMarketIndexes = [marketIndex];
1899
+ }
1900
+ }
1901
+ const remainingAccounts = this.getRemainingAccounts({
1902
+ userAccounts: [this.getUserAccount(subAccountId)],
1903
+ readablePerpMarketIndex,
1904
+ readableSpotMarketIndexes,
1905
+ useMarketLastSlotCache: true,
1906
+ });
1907
+ return await this.program.instruction.cancelOrders(marketType !== null && marketType !== void 0 ? marketType : null, marketIndex !== null && marketIndex !== void 0 ? marketIndex : null, direction !== null && direction !== void 0 ? direction : null, {
1908
+ accounts: {
1909
+ state: await this.getStatePublicKey(),
1910
+ user,
1911
+ authority: this.wallet.publicKey,
1912
+ },
1913
+ remainingAccounts,
1914
+ });
1915
+ }
1916
+ async cancelAndPlaceOrders(cancelOrderParams, placeOrderParams, txParams, subAccountId) {
1917
+ const ixs = [
1918
+ await this.getCancelOrdersIx(cancelOrderParams.marketType, cancelOrderParams.marketIndex, cancelOrderParams.direction, subAccountId),
1919
+ await this.getPlaceOrdersIx(placeOrderParams, subAccountId),
1920
+ ];
1921
+ const tx = await this.buildTransaction(ixs, txParams);
1922
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
1923
+ return txSig;
1924
+ }
1925
+ async placeOrders(params, txParams, subAccountId) {
1926
+ const { txSig } = await this.sendTransaction((await this.preparePlaceOrdersTx(params, txParams, subAccountId))
1927
+ .placeOrdersTx, [], this.opts, false);
1928
+ return txSig;
1929
+ }
1930
+ async preparePlaceOrdersTx(params, txParams, subAccountId) {
1931
+ const tx = await this.buildTransaction(await this.getPlaceOrdersIx(params, subAccountId), txParams);
1932
+ return {
1933
+ placeOrdersTx: tx,
1934
+ };
1935
+ }
1936
+ async getPlaceOrdersIx(params, subAccountId) {
1937
+ const user = await this.getUserAccountPublicKey(subAccountId);
1938
+ const readablePerpMarketIndex = [];
1939
+ const readableSpotMarketIndexes = [];
1940
+ for (const param of params) {
1941
+ if (!param.marketType) {
1942
+ throw new Error('must set param.marketType');
1943
+ }
1944
+ if ((0, types_1.isVariant)(param.marketType, 'perp')) {
1945
+ readablePerpMarketIndex.push(param.marketIndex);
1946
+ }
1947
+ else {
1948
+ readableSpotMarketIndexes.push(param.marketIndex);
1949
+ }
1950
+ }
1951
+ const remainingAccounts = this.getRemainingAccounts({
1952
+ userAccounts: [this.getUserAccount(subAccountId)],
1953
+ readablePerpMarketIndex,
1954
+ readableSpotMarketIndexes,
1955
+ useMarketLastSlotCache: true,
1956
+ });
1957
+ const formattedParams = params.map((item) => (0, orderParams_1.getOrderParams)(item));
1958
+ return await this.program.instruction.placeOrders(formattedParams, {
1959
+ accounts: {
1960
+ state: await this.getStatePublicKey(),
1961
+ user,
1962
+ userStats: this.getUserStatsAccountPublicKey(),
1963
+ authority: this.wallet.publicKey,
1964
+ },
1965
+ remainingAccounts,
1966
+ });
1967
+ }
1968
+ async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, referrerInfo, txParams, fillerPublicKey) {
1969
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, referrerInfo, fillerPublicKey), txParams), [], this.opts);
1970
+ return txSig;
1971
+ }
1972
+ async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, referrerInfo, fillerSubAccountId) {
1973
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
1974
+ const filler = await this.getUserAccountPublicKey(fillerSubAccountId);
1975
+ const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
1976
+ const marketIndex = order
1977
+ ? order.marketIndex
1978
+ : userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1).marketIndex;
1979
+ makerInfo = Array.isArray(makerInfo)
1980
+ ? makerInfo
1981
+ : makerInfo
1982
+ ? [makerInfo]
1983
+ : [];
1984
+ const userAccounts = [userAccount];
1985
+ for (const maker of makerInfo) {
1986
+ userAccounts.push(maker.makerUserAccount);
1987
+ }
1988
+ const remainingAccounts = this.getRemainingAccounts({
1989
+ userAccounts,
1990
+ writablePerpMarketIndexes: [marketIndex],
1991
+ });
1992
+ for (const maker of makerInfo) {
1993
+ remainingAccounts.push({
1994
+ pubkey: maker.maker,
1995
+ isWritable: true,
1996
+ isSigner: false,
1997
+ });
1998
+ remainingAccounts.push({
1999
+ pubkey: maker.makerStats,
2000
+ isWritable: true,
2001
+ isSigner: false,
2002
+ });
2003
+ }
2004
+ if (referrerInfo) {
2005
+ const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
2006
+ undefined;
2007
+ if (!referrerIsMaker) {
2008
+ remainingAccounts.push({
2009
+ pubkey: referrerInfo.referrer,
2010
+ isWritable: true,
2011
+ isSigner: false,
2012
+ });
2013
+ remainingAccounts.push({
2014
+ pubkey: referrerInfo.referrerStats,
2015
+ isWritable: true,
2016
+ isSigner: false,
2017
+ });
2018
+ }
2019
+ }
2020
+ const orderId = order.orderId;
2021
+ return await this.program.instruction.fillPerpOrder(orderId, null, {
2022
+ accounts: {
2023
+ state: await this.getStatePublicKey(),
2024
+ filler,
2025
+ fillerStats: fillerStatsPublicKey,
2026
+ user: userAccountPublicKey,
2027
+ userStats: userStatsPublicKey,
2028
+ authority: this.wallet.publicKey,
2029
+ },
2030
+ remainingAccounts,
2031
+ });
2032
+ }
2033
+ async getRevertFillIx(fillerPublicKey) {
2034
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2035
+ const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
2036
+ return this.program.instruction.revertFill({
2037
+ accounts: {
2038
+ state: await this.getStatePublicKey(),
2039
+ filler,
2040
+ fillerStats: fillerStatsPublicKey,
2041
+ authority: this.wallet.publicKey,
2042
+ },
2043
+ });
2044
+ }
2045
+ async placeSpotOrder(orderParams, txParams, subAccountId) {
2046
+ const { txSig, slot } = await this.sendTransaction((await this.preparePlaceSpotOrderTx(orderParams, txParams, subAccountId))
2047
+ .placeSpotOrderTx, [], this.opts, false);
2048
+ this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
2049
+ this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
2050
+ return txSig;
2051
+ }
2052
+ async preparePlaceSpotOrderTx(orderParams, txParams, subAccountId) {
2053
+ const tx = await this.buildTransaction(await this.getPlaceSpotOrderIx(orderParams, subAccountId), txParams);
2054
+ return {
2055
+ placeSpotOrderTx: tx,
2056
+ };
2057
+ }
2058
+ async getPlaceSpotOrderIx(orderParams, subAccountId) {
2059
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
2060
+ const userAccountPublicKey = await this.getUserAccountPublicKey(subAccountId);
2061
+ const remainingAccounts = this.getRemainingAccounts({
2062
+ userAccounts: [this.getUserAccount(subAccountId)],
2063
+ useMarketLastSlotCache: true,
2064
+ readableSpotMarketIndexes: [
2065
+ orderParams.marketIndex,
2066
+ numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
2067
+ ],
2068
+ });
2069
+ return await this.program.instruction.placeSpotOrder(orderParams, {
2070
+ accounts: {
2071
+ state: await this.getStatePublicKey(),
2072
+ user: userAccountPublicKey,
2073
+ userStats: this.getUserStatsAccountPublicKey(),
2074
+ authority: this.wallet.publicKey,
2075
+ },
2076
+ remainingAccounts,
2077
+ });
2078
+ }
2079
+ async fillSpotOrder(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo, txParams) {
2080
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillSpotOrderIx(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo), txParams), [], this.opts);
2081
+ return txSig;
2082
+ }
2083
+ async getFillSpotOrderIx(userAccountPublicKey, userAccount, order, fulfillmentConfig, makerInfo, referrerInfo, fillerPublicKey) {
2084
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
2085
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2086
+ const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
2087
+ const marketIndex = order
2088
+ ? order.marketIndex
2089
+ : userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1).marketIndex;
2090
+ makerInfo = Array.isArray(makerInfo)
2091
+ ? makerInfo
2092
+ : makerInfo
2093
+ ? [makerInfo]
2094
+ : [];
2095
+ const userAccounts = [userAccount];
2096
+ for (const maker of makerInfo) {
2097
+ userAccounts.push(maker.makerUserAccount);
2098
+ }
2099
+ const remainingAccounts = this.getRemainingAccounts({
2100
+ userAccounts,
2101
+ writableSpotMarketIndexes: [marketIndex, numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
2102
+ });
2103
+ for (const maker of makerInfo) {
2104
+ remainingAccounts.push({
2105
+ pubkey: maker.maker,
2106
+ isWritable: true,
2107
+ isSigner: false,
2108
+ });
2109
+ remainingAccounts.push({
2110
+ pubkey: maker.makerStats,
2111
+ isWritable: true,
2112
+ isSigner: false,
2113
+ });
2114
+ }
2115
+ const orderId = order.orderId;
2116
+ this.addSpotFulfillmentAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
2117
+ return await this.program.instruction.fillSpotOrder(orderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, null, {
2118
+ accounts: {
2119
+ state: await this.getStatePublicKey(),
2120
+ filler,
2121
+ fillerStats: fillerStatsPublicKey,
2122
+ user: userAccountPublicKey,
2123
+ userStats: userStatsPublicKey,
2124
+ authority: this.wallet.publicKey,
2125
+ },
2126
+ remainingAccounts,
2127
+ });
2128
+ }
2129
+ addSpotFulfillmentAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
2130
+ if (fulfillmentConfig) {
2131
+ if ('serumProgramId' in fulfillmentConfig) {
2132
+ this.addSerumRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
2133
+ }
2134
+ else if ('phoenixProgramId' in fulfillmentConfig) {
2135
+ this.addPhoenixRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
2136
+ }
2137
+ else if ('openbookV2ProgramId' in fulfillmentConfig) {
2138
+ this.addOpenbookRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
2139
+ }
2140
+ else {
2141
+ throw Error('Invalid fulfillment config type');
2142
+ }
2143
+ }
2144
+ else {
2145
+ remainingAccounts.push({
2146
+ pubkey: this.getSpotMarketAccount(marketIndex).vault,
2147
+ isWritable: false,
2148
+ isSigner: false,
2149
+ });
2150
+ remainingAccounts.push({
2151
+ pubkey: this.getQuoteSpotMarketAccount().vault,
2152
+ isWritable: false,
2153
+ isSigner: false,
2154
+ });
2155
+ }
2156
+ }
2157
+ addSerumRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
2158
+ remainingAccounts.push({
2159
+ pubkey: fulfillmentConfig.pubkey,
2160
+ isWritable: false,
2161
+ isSigner: false,
2162
+ });
2163
+ remainingAccounts.push({
2164
+ pubkey: fulfillmentConfig.serumProgramId,
2165
+ isWritable: false,
2166
+ isSigner: false,
2167
+ });
2168
+ remainingAccounts.push({
2169
+ pubkey: fulfillmentConfig.serumMarket,
2170
+ isWritable: true,
2171
+ isSigner: false,
2172
+ });
2173
+ remainingAccounts.push({
2174
+ pubkey: fulfillmentConfig.serumRequestQueue,
2175
+ isWritable: true,
2176
+ isSigner: false,
2177
+ });
2178
+ remainingAccounts.push({
2179
+ pubkey: fulfillmentConfig.serumEventQueue,
2180
+ isWritable: true,
2181
+ isSigner: false,
2182
+ });
2183
+ remainingAccounts.push({
2184
+ pubkey: fulfillmentConfig.serumBids,
2185
+ isWritable: true,
2186
+ isSigner: false,
2187
+ });
2188
+ remainingAccounts.push({
2189
+ pubkey: fulfillmentConfig.serumAsks,
2190
+ isWritable: true,
2191
+ isSigner: false,
2192
+ });
2193
+ remainingAccounts.push({
2194
+ pubkey: fulfillmentConfig.serumBaseVault,
2195
+ isWritable: true,
2196
+ isSigner: false,
2197
+ });
2198
+ remainingAccounts.push({
2199
+ pubkey: fulfillmentConfig.serumQuoteVault,
2200
+ isWritable: true,
2201
+ isSigner: false,
2202
+ });
2203
+ remainingAccounts.push({
2204
+ pubkey: fulfillmentConfig.serumOpenOrders,
2205
+ isWritable: true,
2206
+ isSigner: false,
2207
+ });
2208
+ remainingAccounts.push({
2209
+ pubkey: (0, pda_1.getSerumSignerPublicKey)(fulfillmentConfig.serumProgramId, fulfillmentConfig.serumMarket, fulfillmentConfig.serumSignerNonce),
2210
+ isWritable: false,
2211
+ isSigner: false,
2212
+ });
2213
+ remainingAccounts.push({
2214
+ pubkey: this.getSignerPublicKey(),
2215
+ isWritable: false,
2216
+ isSigner: false,
2217
+ });
2218
+ remainingAccounts.push({
2219
+ pubkey: spl_token_1.TOKEN_PROGRAM_ID,
2220
+ isWritable: false,
2221
+ isSigner: false,
2222
+ });
2223
+ remainingAccounts.push({
2224
+ pubkey: this.getSpotMarketAccount(marketIndex).vault,
2225
+ isWritable: true,
2226
+ isSigner: false,
2227
+ });
2228
+ remainingAccounts.push({
2229
+ pubkey: this.getQuoteSpotMarketAccount().vault,
2230
+ isWritable: true,
2231
+ isSigner: false,
2232
+ });
2233
+ remainingAccounts.push({
2234
+ pubkey: this.getStateAccount().srmVault,
2235
+ isWritable: false,
2236
+ isSigner: false,
2237
+ });
2238
+ }
2239
+ addPhoenixRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
2240
+ remainingAccounts.push({
2241
+ pubkey: fulfillmentConfig.pubkey,
2242
+ isWritable: false,
2243
+ isSigner: false,
2244
+ });
2245
+ remainingAccounts.push({
2246
+ pubkey: fulfillmentConfig.phoenixProgramId,
2247
+ isWritable: false,
2248
+ isSigner: false,
2249
+ });
2250
+ remainingAccounts.push({
2251
+ pubkey: fulfillmentConfig.phoenixLogAuthority,
2252
+ isWritable: false,
2253
+ isSigner: false,
2254
+ });
2255
+ remainingAccounts.push({
2256
+ pubkey: fulfillmentConfig.phoenixMarket,
2257
+ isWritable: true,
2258
+ isSigner: false,
2259
+ });
2260
+ remainingAccounts.push({
2261
+ pubkey: this.getSignerPublicKey(),
2262
+ isWritable: false,
2263
+ isSigner: false,
2264
+ });
2265
+ remainingAccounts.push({
2266
+ pubkey: fulfillmentConfig.phoenixBaseVault,
2267
+ isWritable: true,
2268
+ isSigner: false,
2269
+ });
2270
+ remainingAccounts.push({
2271
+ pubkey: fulfillmentConfig.phoenixQuoteVault,
2272
+ isWritable: true,
2273
+ isSigner: false,
2274
+ });
2275
+ remainingAccounts.push({
2276
+ pubkey: this.getSpotMarketAccount(marketIndex).vault,
2277
+ isWritable: true,
2278
+ isSigner: false,
2279
+ });
2280
+ remainingAccounts.push({
2281
+ pubkey: this.getQuoteSpotMarketAccount().vault,
2282
+ isWritable: true,
2283
+ isSigner: false,
2284
+ });
2285
+ remainingAccounts.push({
2286
+ pubkey: spl_token_1.TOKEN_PROGRAM_ID,
2287
+ isWritable: false,
2288
+ isSigner: false,
2289
+ });
2290
+ }
2291
+ addOpenbookRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
2292
+ remainingAccounts.push({
2293
+ pubkey: fulfillmentConfig.pubkey,
2294
+ isWritable: false,
2295
+ isSigner: false,
2296
+ });
2297
+ remainingAccounts.push({
2298
+ pubkey: this.getSignerPublicKey(),
2299
+ isWritable: true,
2300
+ isSigner: false,
2301
+ });
2302
+ remainingAccounts.push({
2303
+ pubkey: fulfillmentConfig.openbookV2ProgramId,
2304
+ isWritable: false,
2305
+ isSigner: false,
2306
+ });
2307
+ remainingAccounts.push({
2308
+ pubkey: fulfillmentConfig.openbookV2Market,
2309
+ isWritable: true,
2310
+ isSigner: false,
2311
+ });
2312
+ remainingAccounts.push({
2313
+ pubkey: fulfillmentConfig.openbookV2MarketAuthority,
2314
+ isWritable: false,
2315
+ isSigner: false,
2316
+ });
2317
+ remainingAccounts.push({
2318
+ pubkey: fulfillmentConfig.openbookV2EventHeap,
2319
+ isWritable: true,
2320
+ isSigner: false,
2321
+ });
2322
+ remainingAccounts.push({
2323
+ pubkey: fulfillmentConfig.openbookV2Bids,
2324
+ isWritable: true,
2325
+ isSigner: false,
2326
+ });
2327
+ remainingAccounts.push({
2328
+ pubkey: fulfillmentConfig.openbookV2Asks,
2329
+ isWritable: true,
2330
+ isSigner: false,
2331
+ });
2332
+ remainingAccounts.push({
2333
+ pubkey: fulfillmentConfig.openbookV2BaseVault,
2334
+ isWritable: true,
2335
+ isSigner: false,
2336
+ });
2337
+ remainingAccounts.push({
2338
+ pubkey: fulfillmentConfig.openbookV2QuoteVault,
2339
+ isWritable: true,
2340
+ isSigner: false,
2341
+ });
2342
+ remainingAccounts.push({
2343
+ pubkey: this.getSpotMarketAccount(marketIndex).vault,
2344
+ isWritable: true,
2345
+ isSigner: false,
2346
+ });
2347
+ remainingAccounts.push({
2348
+ pubkey: this.getQuoteSpotMarketAccount().vault,
2349
+ isWritable: true,
2350
+ isSigner: false,
2351
+ });
2352
+ remainingAccounts.push({
2353
+ pubkey: spl_token_1.TOKEN_PROGRAM_ID,
2354
+ isWritable: false,
2355
+ isSigner: false,
2356
+ });
2357
+ remainingAccounts.push({
2358
+ pubkey: web3_js_1.SystemProgram.programId,
2359
+ isWritable: false,
2360
+ isSigner: false,
2361
+ });
2362
+ remainingAccounts.push({
2363
+ pubkey: this.getSpotMarketAccount(marketIndex).pubkey,
2364
+ isWritable: true,
2365
+ isSigner: false,
2366
+ });
2367
+ remainingAccounts.push({
2368
+ pubkey: this.getQuoteSpotMarketAccount().pubkey,
2369
+ isWritable: true,
2370
+ isSigner: false,
2371
+ });
2372
+ if (fulfillmentConfig.remainingAccounts) {
2373
+ for (const remainingAccount of fulfillmentConfig.remainingAccounts) {
2374
+ remainingAccounts.push({
2375
+ pubkey: remainingAccount,
2376
+ isWritable: true,
2377
+ isSigner: false,
2378
+ });
2379
+ }
2380
+ }
2381
+ }
2382
+ /**
2383
+ * Swap tokens in drift account using jupiter
2384
+ * @param jupiterClient jupiter client to find routes and jupiter instructions
2385
+ * @param outMarketIndex the market index of the token you're buying
2386
+ * @param inMarketIndex the market index of the token you're selling
2387
+ * @param outAssociatedTokenAccount the token account to receive the token being sold on jupiter
2388
+ * @param inAssociatedTokenAccount the token account to
2389
+ * @param amount the amount of TokenIn, regardless of swapMode
2390
+ * @param slippageBps the max slippage passed to jupiter api
2391
+ * @param swapMode jupiter swapMode (ExactIn or ExactOut), default is ExactIn
2392
+ * @param route the jupiter route to use for the swap
2393
+ * @param reduceOnly specify if In or Out token on the drift account must reduceOnly, checked at end of swap
2394
+ * @param txParams
2395
+ */
2396
+ async swap({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, route, reduceOnly, txParams, v6, onlyDirectRoutes = false, }) {
2397
+ let ixs;
2398
+ let lookupTables;
2399
+ if (v6) {
2400
+ const res = await this.getJupiterSwapIxV6({
2401
+ jupiterClient,
2402
+ outMarketIndex,
2403
+ inMarketIndex,
2404
+ outAssociatedTokenAccount,
2405
+ inAssociatedTokenAccount,
2406
+ amount,
2407
+ slippageBps,
2408
+ swapMode,
2409
+ quote: v6.quote,
2410
+ reduceOnly,
2411
+ onlyDirectRoutes,
2412
+ });
2413
+ ixs = res.ixs;
2414
+ lookupTables = res.lookupTables;
2415
+ }
2416
+ else {
2417
+ const res = await this.getJupiterSwapIx({
2418
+ jupiterClient,
2419
+ outMarketIndex,
2420
+ inMarketIndex,
2421
+ outAssociatedTokenAccount,
2422
+ inAssociatedTokenAccount,
2423
+ amount,
2424
+ slippageBps,
2425
+ swapMode,
2426
+ route,
2427
+ reduceOnly,
2428
+ });
2429
+ ixs = res.ixs;
2430
+ lookupTables = res.lookupTables;
2431
+ }
2432
+ const tx = (await this.buildTransaction(ixs, txParams, 0, lookupTables));
2433
+ const { txSig, slot } = await this.sendTransaction(tx);
2434
+ this.spotMarketLastSlotCache.set(outMarketIndex, slot);
2435
+ this.spotMarketLastSlotCache.set(inMarketIndex, slot);
2436
+ return txSig;
2437
+ }
2438
+ async getJupiterSwapIx({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, route, reduceOnly, userAccountPublicKey, }) {
2439
+ const outMarket = this.getSpotMarketAccount(outMarketIndex);
2440
+ const inMarket = this.getSpotMarketAccount(inMarketIndex);
2441
+ if (!route) {
2442
+ const routes = await jupiterClient.getRoutes({
2443
+ inputMint: inMarket.mint,
2444
+ outputMint: outMarket.mint,
2445
+ amount,
2446
+ slippageBps,
2447
+ swapMode,
2448
+ onlyDirectRoutes,
2449
+ });
2450
+ if (!routes || routes.length === 0) {
2451
+ throw new Error('No jupiter routes found');
2452
+ }
2453
+ route = routes[0];
2454
+ }
2455
+ const transaction = await jupiterClient.getSwapTransaction({
2456
+ route,
2457
+ userPublicKey: this.provider.wallet.publicKey,
2458
+ slippageBps,
2459
+ });
2460
+ const { transactionMessage, lookupTables } = await jupiterClient.getTransactionMessageAndLookupTables({
2461
+ transaction,
2462
+ });
2463
+ const jupiterInstructions = jupiterClient.getJupiterInstructions({
2464
+ transactionMessage,
2465
+ inputMint: inMarket.mint,
2466
+ outputMint: outMarket.mint,
2467
+ });
2468
+ const preInstructions = [];
2469
+ if (!outAssociatedTokenAccount) {
2470
+ const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
2471
+ outAssociatedTokenAccount = await this.getAssociatedTokenAccount(outMarket.marketIndex, false, tokenProgram);
2472
+ const accountInfo = await this.connection.getAccountInfo(outAssociatedTokenAccount);
2473
+ if (!accountInfo) {
2474
+ preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(outAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, outMarket.mint, tokenProgram));
2475
+ }
2476
+ }
2477
+ if (!inAssociatedTokenAccount) {
2478
+ const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
2479
+ inAssociatedTokenAccount = await this.getAssociatedTokenAccount(inMarket.marketIndex, false, tokenProgram);
2480
+ const accountInfo = await this.connection.getAccountInfo(inAssociatedTokenAccount);
2481
+ if (!accountInfo) {
2482
+ preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(inAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, inMarket.mint, tokenProgram));
2483
+ }
2484
+ }
2485
+ const { beginSwapIx, endSwapIx } = await this.getSwapIx({
2486
+ outMarketIndex,
2487
+ inMarketIndex,
2488
+ amountIn: new anchor_1.BN(route.inAmount),
2489
+ inTokenAccount: inAssociatedTokenAccount,
2490
+ outTokenAccount: outAssociatedTokenAccount,
2491
+ reduceOnly,
2492
+ userAccountPublicKey,
2493
+ });
2494
+ const ixs = [
2495
+ ...preInstructions,
2496
+ beginSwapIx,
2497
+ ...jupiterInstructions,
2498
+ endSwapIx,
2499
+ ];
2500
+ return { ixs, lookupTables };
2501
+ }
2502
+ async getJupiterSwapIxV6({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, quote, reduceOnly, userAccountPublicKey, }) {
2503
+ const outMarket = this.getSpotMarketAccount(outMarketIndex);
2504
+ const inMarket = this.getSpotMarketAccount(inMarketIndex);
2505
+ if (!quote) {
2506
+ const fetchedQuote = await jupiterClient.getQuote({
2507
+ inputMint: inMarket.mint,
2508
+ outputMint: outMarket.mint,
2509
+ amount,
2510
+ slippageBps,
2511
+ swapMode,
2512
+ onlyDirectRoutes,
2513
+ });
2514
+ quote = fetchedQuote;
2515
+ }
2516
+ if (!quote) {
2517
+ throw new Error("Could not fetch Jupiter's quote. Please try again.");
2518
+ }
2519
+ const isExactOut = swapMode === 'ExactOut' || quote.swapMode === 'ExactOut';
2520
+ const amountIn = new anchor_1.BN(quote.inAmount);
2521
+ const exactOutBufferedAmountIn = amountIn.muln(1001).divn(1000); // Add 10bp buffer
2522
+ const transaction = await jupiterClient.getSwap({
2523
+ quote,
2524
+ userPublicKey: this.provider.wallet.publicKey,
2525
+ slippageBps,
2526
+ });
2527
+ const { transactionMessage, lookupTables } = await jupiterClient.getTransactionMessageAndLookupTables({
2528
+ transaction,
2529
+ });
2530
+ const jupiterInstructions = jupiterClient.getJupiterInstructions({
2531
+ transactionMessage,
2532
+ inputMint: inMarket.mint,
2533
+ outputMint: outMarket.mint,
2534
+ });
2535
+ const preInstructions = [];
2536
+ if (!outAssociatedTokenAccount) {
2537
+ const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
2538
+ outAssociatedTokenAccount = await this.getAssociatedTokenAccount(outMarket.marketIndex, false, tokenProgram);
2539
+ const accountInfo = await this.connection.getAccountInfo(outAssociatedTokenAccount);
2540
+ if (!accountInfo) {
2541
+ preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(outAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, outMarket.mint, tokenProgram));
2542
+ }
2543
+ }
2544
+ if (!inAssociatedTokenAccount) {
2545
+ const tokenProgram = this.getTokenProgramForSpotMarket(inMarket);
2546
+ inAssociatedTokenAccount = await this.getAssociatedTokenAccount(inMarket.marketIndex, false, tokenProgram);
2547
+ const accountInfo = await this.connection.getAccountInfo(inAssociatedTokenAccount);
2548
+ if (!accountInfo) {
2549
+ preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(inAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, inMarket.mint, tokenProgram));
2550
+ }
2551
+ }
2552
+ const { beginSwapIx, endSwapIx } = await this.getSwapIx({
2553
+ outMarketIndex,
2554
+ inMarketIndex,
2555
+ amountIn: isExactOut ? exactOutBufferedAmountIn : amountIn,
2556
+ inTokenAccount: inAssociatedTokenAccount,
2557
+ outTokenAccount: outAssociatedTokenAccount,
2558
+ reduceOnly,
2559
+ userAccountPublicKey,
2560
+ });
2561
+ const ixs = [
2562
+ ...preInstructions,
2563
+ beginSwapIx,
2564
+ ...jupiterInstructions,
2565
+ endSwapIx,
2566
+ ];
2567
+ return { ixs, lookupTables };
2568
+ }
2569
+ /**
2570
+ * Get the drift begin_swap and end_swap instructions
2571
+ *
2572
+ * @param outMarketIndex the market index of the token you're buying
2573
+ * @param inMarketIndex the market index of the token you're selling
2574
+ * @param amountIn the amount of the token to sell
2575
+ * @param inTokenAccount the token account to move the tokens being sold
2576
+ * @param outTokenAccount the token account to receive the tokens being bought
2577
+ * @param limitPrice the limit price of the swap
2578
+ * @param reduceOnly
2579
+ * @param userAccountPublicKey optional, specify a custom userAccountPublicKey to use instead of getting the current user account; can be helpful if the account is being created within the current tx
2580
+ */
2581
+ async getSwapIx({ outMarketIndex, inMarketIndex, amountIn, inTokenAccount, outTokenAccount, limitPrice, reduceOnly, userAccountPublicKey, }) {
2582
+ const userAccountPublicKeyToUse = userAccountPublicKey || (await this.getUserAccountPublicKey());
2583
+ const userAccounts = [];
2584
+ try {
2585
+ if (this.hasUser() && this.getUser().getUserAccountAndSlot()) {
2586
+ userAccounts.push(this.getUser().getUserAccountAndSlot().data);
2587
+ }
2588
+ }
2589
+ catch (err) {
2590
+ // ignore
2591
+ }
2592
+ const remainingAccounts = this.getRemainingAccounts({
2593
+ userAccounts,
2594
+ writableSpotMarketIndexes: [outMarketIndex, inMarketIndex],
2595
+ readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
2596
+ });
2597
+ const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
2598
+ const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
2599
+ const outTokenProgram = this.getTokenProgramForSpotMarket(outSpotMarket);
2600
+ const inTokenProgram = this.getTokenProgramForSpotMarket(inSpotMarket);
2601
+ if (!outTokenProgram.equals(inTokenProgram)) {
2602
+ remainingAccounts.push({
2603
+ pubkey: outTokenProgram,
2604
+ isWritable: false,
2605
+ isSigner: false,
2606
+ });
2607
+ }
2608
+ if (outSpotMarket.tokenProgram === 1 || inSpotMarket.tokenProgram === 1) {
2609
+ remainingAccounts.push({
2610
+ pubkey: inSpotMarket.mint,
2611
+ isWritable: false,
2612
+ isSigner: false,
2613
+ });
2614
+ remainingAccounts.push({
2615
+ pubkey: outSpotMarket.mint,
2616
+ isWritable: false,
2617
+ isSigner: false,
2618
+ });
2619
+ }
2620
+ const beginSwapIx = await this.program.instruction.beginSwap(inMarketIndex, outMarketIndex, amountIn, {
2621
+ accounts: {
2622
+ state: await this.getStatePublicKey(),
2623
+ user: userAccountPublicKeyToUse,
2624
+ userStats: this.getUserStatsAccountPublicKey(),
2625
+ authority: this.wallet.publicKey,
2626
+ outSpotMarketVault: outSpotMarket.vault,
2627
+ inSpotMarketVault: inSpotMarket.vault,
2628
+ inTokenAccount,
2629
+ outTokenAccount,
2630
+ tokenProgram: inTokenProgram,
2631
+ driftSigner: this.getStateAccount().signer,
2632
+ instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
2633
+ },
2634
+ remainingAccounts,
2635
+ });
2636
+ const endSwapIx = await this.program.instruction.endSwap(inMarketIndex, outMarketIndex, limitPrice !== null && limitPrice !== void 0 ? limitPrice : null, reduceOnly !== null && reduceOnly !== void 0 ? reduceOnly : null, {
2637
+ accounts: {
2638
+ state: await this.getStatePublicKey(),
2639
+ user: userAccountPublicKeyToUse,
2640
+ userStats: this.getUserStatsAccountPublicKey(),
2641
+ authority: this.wallet.publicKey,
2642
+ outSpotMarketVault: outSpotMarket.vault,
2643
+ inSpotMarketVault: inSpotMarket.vault,
2644
+ inTokenAccount,
2645
+ outTokenAccount,
2646
+ tokenProgram: inTokenProgram,
2647
+ driftSigner: this.getStateAccount().signer,
2648
+ instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
2649
+ },
2650
+ remainingAccounts,
2651
+ });
2652
+ return { beginSwapIx, endSwapIx };
2653
+ }
2654
+ async stakeForMSOL({ amount }) {
2655
+ const ixs = await this.getStakeForMSOLIx({ amount });
2656
+ const tx = await this.buildTransaction(ixs);
2657
+ return this.sendTransaction(tx);
2658
+ }
2659
+ async getStakeForMSOLIx({ amount, userAccountPublicKey, }) {
2660
+ const wSOLMint = this.getSpotMarketAccount(1).mint;
2661
+ const mSOLAccount = await this.getAssociatedTokenAccount(2);
2662
+ const wSOLAccount = await this.getAssociatedTokenAccount(1, false);
2663
+ const wSOLAccountExists = await this.checkIfAccountExists(wSOLAccount);
2664
+ const closeWSOLIx = (0, spl_token_1.createCloseAccountInstruction)(wSOLAccount, this.wallet.publicKey, this.wallet.publicKey);
2665
+ const createWSOLIx = await this.createAssociatedTokenAccountIdempotentInstruction(wSOLAccount, this.wallet.publicKey, this.wallet.publicKey, wSOLMint);
2666
+ const { beginSwapIx, endSwapIx } = await this.getSwapIx({
2667
+ inMarketIndex: 1,
2668
+ outMarketIndex: 2,
2669
+ amountIn: amount,
2670
+ inTokenAccount: wSOLAccount,
2671
+ outTokenAccount: mSOLAccount,
2672
+ userAccountPublicKey,
2673
+ });
2674
+ const program = (0, marinade_1.getMarinadeFinanceProgram)(this.provider);
2675
+ const depositIx = await (0, marinade_1.getMarinadeDepositIx)({
2676
+ program,
2677
+ mSOLAccount: mSOLAccount,
2678
+ transferFrom: this.wallet.publicKey,
2679
+ amount,
2680
+ });
2681
+ const ixs = [];
2682
+ if (!wSOLAccountExists) {
2683
+ ixs.push(createWSOLIx);
2684
+ }
2685
+ ixs.push(beginSwapIx, closeWSOLIx, depositIx, createWSOLIx, endSwapIx);
2686
+ return ixs;
2687
+ }
2688
+ async triggerOrder(userAccountPublicKey, user, order, txParams, fillerPublicKey) {
2689
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getTriggerOrderIx(userAccountPublicKey, user, order, fillerPublicKey), txParams), [], this.opts);
2690
+ return txSig;
2691
+ }
2692
+ async getTriggerOrderIx(userAccountPublicKey, userAccount, order, fillerPublicKey) {
2693
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2694
+ let remainingAccountsParams;
2695
+ if ((0, types_1.isVariant)(order.marketType, 'perp')) {
2696
+ remainingAccountsParams = {
2697
+ userAccounts: [userAccount],
2698
+ writablePerpMarketIndexes: [order.marketIndex],
2699
+ };
2700
+ }
2701
+ else {
2702
+ remainingAccountsParams = {
2703
+ userAccounts: [userAccount],
2704
+ writableSpotMarketIndexes: [order.marketIndex, numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
2705
+ };
2706
+ }
2707
+ const remainingAccounts = this.getRemainingAccounts(remainingAccountsParams);
2708
+ const orderId = order.orderId;
2709
+ return await this.program.instruction.triggerOrder(orderId, {
2710
+ accounts: {
2711
+ state: await this.getStatePublicKey(),
2712
+ filler,
2713
+ user: userAccountPublicKey,
2714
+ authority: this.wallet.publicKey,
2715
+ },
2716
+ remainingAccounts,
2717
+ });
2718
+ }
2719
+ async forceCancelOrders(userAccountPublicKey, user, txParams, fillerPublicKey) {
2720
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getForceCancelOrdersIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
2721
+ return txSig;
2722
+ }
2723
+ async getForceCancelOrdersIx(userAccountPublicKey, userAccount, fillerPublicKey) {
2724
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2725
+ const remainingAccounts = this.getRemainingAccounts({
2726
+ userAccounts: [userAccount],
2727
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
2728
+ });
2729
+ return await this.program.instruction.forceCancelOrders({
2730
+ accounts: {
2731
+ state: await this.getStatePublicKey(),
2732
+ filler,
2733
+ user: userAccountPublicKey,
2734
+ authority: this.wallet.publicKey,
2735
+ },
2736
+ remainingAccounts,
2737
+ });
2738
+ }
2739
+ async updateUserIdle(userAccountPublicKey, user, txParams, fillerPublicKey) {
2740
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserIdleIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
2741
+ return txSig;
2742
+ }
2743
+ async getUpdateUserIdleIx(userAccountPublicKey, userAccount, fillerPublicKey) {
2744
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2745
+ const remainingAccounts = this.getRemainingAccounts({
2746
+ userAccounts: [userAccount],
2747
+ });
2748
+ return await this.program.instruction.updateUserIdle({
2749
+ accounts: {
2750
+ state: await this.getStatePublicKey(),
2751
+ filler,
2752
+ user: userAccountPublicKey,
2753
+ authority: this.wallet.publicKey,
2754
+ },
2755
+ remainingAccounts,
2756
+ });
2757
+ }
2758
+ async updateUserFuelBonus(userAccountPublicKey, user, userAuthority, txParams) {
2759
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserFuelBonusIx(userAccountPublicKey, user, userAuthority), txParams), [], this.opts);
2760
+ return txSig;
2761
+ }
2762
+ async getUpdateUserFuelBonusIx(userAccountPublicKey, userAccount, userAuthority) {
2763
+ const userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAuthority);
2764
+ const remainingAccounts = this.getRemainingAccounts({
2765
+ userAccounts: [userAccount],
2766
+ });
2767
+ return await this.program.instruction.updateUserFuelBonus({
2768
+ accounts: {
2769
+ state: await this.getStatePublicKey(),
2770
+ user: userAccountPublicKey,
2771
+ userStats: userStatsAccountPublicKey,
2772
+ authority: this.wallet.publicKey,
2773
+ },
2774
+ remainingAccounts,
2775
+ });
2776
+ }
2777
+ async updateUserStatsReferrerInfo(userStatsAccountPublicKey, txParams) {
2778
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserStatsReferrerInfoIx(userStatsAccountPublicKey), txParams), [], this.opts);
2779
+ return txSig;
2780
+ }
2781
+ async getUpdateUserStatsReferrerInfoIx(userStatsAccountPublicKey) {
2782
+ return await this.program.instruction.updateUserStatsReferrerInfo({
2783
+ accounts: {
2784
+ state: await this.getStatePublicKey(),
2785
+ userStats: userStatsAccountPublicKey,
2786
+ authority: this.wallet.publicKey,
2787
+ },
2788
+ });
2789
+ }
2790
+ async updateUserOpenOrdersCount(userAccountPublicKey, user, txParams, fillerPublicKey) {
2791
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserOpenOrdersCountIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
2792
+ return txSig;
2793
+ }
2794
+ async getUpdateUserOpenOrdersCountIx(userAccountPublicKey, userAccount, fillerPublicKey) {
2795
+ const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
2796
+ const remainingAccounts = this.getRemainingAccounts({
2797
+ userAccounts: [userAccount],
2798
+ });
2799
+ return await this.program.instruction.updateUserOpenOrdersCount({
2800
+ accounts: {
2801
+ state: await this.getStatePublicKey(),
2802
+ filler,
2803
+ user: userAccountPublicKey,
2804
+ authority: this.wallet.publicKey,
2805
+ },
2806
+ remainingAccounts,
2807
+ });
2808
+ }
2809
+ async placeAndTakePerpOrder(orderParams, makerInfo, referrerInfo, successCondition, txParams, subAccountId) {
2810
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, subAccountId), txParams), [], this.opts);
2811
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2812
+ return txSig;
2813
+ }
2814
+ async preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails) {
2815
+ const placeAndTakeIxs = [];
2816
+ const txsToSign = {
2817
+ placeAndTakeTx: undefined,
2818
+ cancelExistingOrdersTx: undefined,
2819
+ settlePnlTx: undefined,
2820
+ };
2821
+ // Get recent block hash so that we can re-use it for all transactions. Makes this logic run faster with fewer RPC requests
2822
+ const recentBlockHash = await this.txHandler.getLatestBlockhashForTransaction();
2823
+ let earlyExitFailedPlaceAndTakeSim = false;
2824
+ const prepPlaceAndTakeTx = async () => {
2825
+ var _a;
2826
+ const placeAndTakeIx = await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, undefined, subAccountId);
2827
+ placeAndTakeIxs.push(placeAndTakeIx);
2828
+ if (bracketOrdersParams.length > 0) {
2829
+ const bracketOrdersIx = await this.getPlaceOrdersIx(bracketOrdersParams, subAccountId);
2830
+ placeAndTakeIxs.push(bracketOrdersIx);
2831
+ }
2832
+ const shouldUseSimulationComputeUnits = txParams === null || txParams === void 0 ? void 0 : txParams.useSimulatedComputeUnits;
2833
+ const shouldExitIfSimulationFails = exitEarlyIfSimFails;
2834
+ const txParamsWithoutImplicitSimulation = {
2835
+ ...txParams,
2836
+ useSimulatedComputeUnits: false,
2837
+ };
2838
+ if (shouldUseSimulationComputeUnits || shouldExitIfSimulationFails) {
2839
+ const placeAndTakeTxToSim = (await this.buildTransaction(placeAndTakeIxs, txParams, undefined, undefined, true, recentBlockHash));
2840
+ const simulationResult = await txParamProcessor_1.TransactionParamProcessor.getTxSimComputeUnits(placeAndTakeTxToSim, this.connection, (_a = txParams.computeUnitsBufferMultiplier) !== null && _a !== void 0 ? _a : 1.2, txParams.lowerBoundCu);
2841
+ if (shouldExitIfSimulationFails && !simulationResult.success) {
2842
+ earlyExitFailedPlaceAndTakeSim = true;
2843
+ return;
2844
+ }
2845
+ txsToSign.placeAndTakeTx = await this.buildTransaction(placeAndTakeIxs, {
2846
+ ...txParamsWithoutImplicitSimulation,
2847
+ computeUnits: simulationResult.computeUnits,
2848
+ }, undefined, undefined, undefined, recentBlockHash);
2849
+ }
2850
+ else {
2851
+ txsToSign.placeAndTakeTx = await this.buildTransaction(placeAndTakeIxs, txParams, undefined, undefined, undefined, recentBlockHash);
2852
+ }
2853
+ return;
2854
+ };
2855
+ const prepCancelOrderTx = async () => {
2856
+ if (cancelExistingOrders && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
2857
+ const cancelOrdersIx = await this.getCancelOrdersIx(orderParams.marketType, orderParams.marketIndex, null, subAccountId);
2858
+ txsToSign.cancelExistingOrdersTx = await this.buildTransaction([cancelOrdersIx], txParams, this.txVersion, undefined, undefined, recentBlockHash);
2859
+ }
2860
+ return;
2861
+ };
2862
+ const prepSettlePnlTx = async () => {
2863
+ if (settlePnl && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
2864
+ const userAccountPublicKey = await this.getUserAccountPublicKey(subAccountId);
2865
+ const settlePnlIx = await this.settlePNLIx(userAccountPublicKey, this.getUserAccount(subAccountId), orderParams.marketIndex);
2866
+ txsToSign.settlePnlTx = await this.buildTransaction([settlePnlIx], txParams, this.txVersion, undefined, undefined, recentBlockHash);
2867
+ }
2868
+ return;
2869
+ };
2870
+ await Promise.all([
2871
+ prepPlaceAndTakeTx(),
2872
+ prepCancelOrderTx(),
2873
+ prepSettlePnlTx(),
2874
+ ]);
2875
+ if (earlyExitFailedPlaceAndTakeSim) {
2876
+ return null;
2877
+ }
2878
+ return txsToSign;
2879
+ }
2880
+ async placeAndTakePerpWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails) {
2881
+ const txsToSign = await this.preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams, txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails);
2882
+ if (!txsToSign) {
2883
+ return null;
2884
+ }
2885
+ const signedTxs = (await this.txHandler.getSignedTransactionMap(txsToSign,
2886
+ // @ts-ignore
2887
+ this.provider.wallet)).signedTxMap;
2888
+ const { txSig, slot } = await this.sendTransaction(signedTxs.placeAndTakeTx, [], this.opts, true);
2889
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2890
+ return {
2891
+ txSig,
2892
+ signedCancelExistingOrdersTx: signedTxs.cancelExistingOrdersTx,
2893
+ signedSettlePnlTx: signedTxs.settlePnlTx,
2894
+ };
2895
+ }
2896
+ async getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, subAccountId) {
2897
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
2898
+ const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
2899
+ const user = await this.getUserAccountPublicKey(subAccountId);
2900
+ makerInfo = Array.isArray(makerInfo)
2901
+ ? makerInfo
2902
+ : makerInfo
2903
+ ? [makerInfo]
2904
+ : [];
2905
+ const userAccounts = [this.getUserAccount(subAccountId)];
2906
+ for (const maker of makerInfo) {
2907
+ userAccounts.push(maker.makerUserAccount);
2908
+ }
2909
+ const remainingAccounts = this.getRemainingAccounts({
2910
+ userAccounts,
2911
+ useMarketLastSlotCache: true,
2912
+ writablePerpMarketIndexes: [orderParams.marketIndex],
2913
+ });
2914
+ for (const maker of makerInfo) {
2915
+ remainingAccounts.push({
2916
+ pubkey: maker.maker,
2917
+ isWritable: true,
2918
+ isSigner: false,
2919
+ });
2920
+ remainingAccounts.push({
2921
+ pubkey: maker.makerStats,
2922
+ isWritable: true,
2923
+ isSigner: false,
2924
+ });
2925
+ }
2926
+ if (referrerInfo) {
2927
+ const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
2928
+ undefined;
2929
+ if (!referrerIsMaker) {
2930
+ remainingAccounts.push({
2931
+ pubkey: referrerInfo.referrer,
2932
+ isWritable: true,
2933
+ isSigner: false,
2934
+ });
2935
+ remainingAccounts.push({
2936
+ pubkey: referrerInfo.referrerStats,
2937
+ isWritable: true,
2938
+ isSigner: false,
2939
+ });
2940
+ }
2941
+ }
2942
+ return await this.program.instruction.placeAndTakePerpOrder(orderParams, successCondition !== null && successCondition !== void 0 ? successCondition : null, {
2943
+ accounts: {
2944
+ state: await this.getStatePublicKey(),
2945
+ user,
2946
+ userStats: userStatsPublicKey,
2947
+ authority: this.wallet.publicKey,
2948
+ },
2949
+ remainingAccounts,
2950
+ });
2951
+ }
2952
+ async placeAndMakePerpOrder(orderParams, takerInfo, referrerInfo, txParams, subAccountId) {
2953
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId), txParams), [], this.opts);
2954
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2955
+ return txSig;
2956
+ }
2957
+ async getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId) {
2958
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
2959
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
2960
+ const user = await this.getUserAccountPublicKey(subAccountId);
2961
+ const remainingAccounts = this.getRemainingAccounts({
2962
+ userAccounts: [
2963
+ this.getUserAccount(subAccountId),
2964
+ takerInfo.takerUserAccount,
2965
+ ],
2966
+ useMarketLastSlotCache: true,
2967
+ writablePerpMarketIndexes: [orderParams.marketIndex],
2968
+ });
2969
+ if (referrerInfo) {
2970
+ remainingAccounts.push({
2971
+ pubkey: referrerInfo.referrer,
2972
+ isWritable: true,
2973
+ isSigner: false,
2974
+ });
2975
+ remainingAccounts.push({
2976
+ pubkey: referrerInfo.referrerStats,
2977
+ isWritable: true,
2978
+ isSigner: false,
2979
+ });
2980
+ }
2981
+ const takerOrderId = takerInfo.order.orderId;
2982
+ return await this.program.instruction.placeAndMakePerpOrder(orderParams, takerOrderId, {
2983
+ accounts: {
2984
+ state: await this.getStatePublicKey(),
2985
+ user,
2986
+ userStats: userStatsPublicKey,
2987
+ taker: takerInfo.taker,
2988
+ takerStats: takerInfo.takerStats,
2989
+ authority: this.wallet.publicKey,
2990
+ },
2991
+ remainingAccounts,
2992
+ });
2993
+ }
2994
+ encodeSwiftServerMessage(message) {
2995
+ const messageWithBuffer = {
2996
+ slot: message.slot,
2997
+ swiftOrderSignature: message.swiftOrderSignature,
2998
+ };
2999
+ return this.program.coder.types.encode('SwiftServerMessage', messageWithBuffer);
3000
+ }
3001
+ decodeSwiftServerMessage(encodedMessage) {
3002
+ const decodedSwiftMessage = this.program.coder.types.decode('SwiftServerMessage', encodedMessage);
3003
+ return {
3004
+ slot: decodedSwiftMessage.slot,
3005
+ swiftOrderSignature: decodedSwiftMessage.swiftSignature,
3006
+ };
3007
+ }
3008
+ signSwiftServerMessage(message) {
3009
+ const swiftServerMessage = Uint8Array.from(this.encodeSwiftServerMessage(message));
3010
+ return this.signMessage(swiftServerMessage);
3011
+ }
3012
+ signSwiftOrderParamsMessage(orderParamsMessage) {
3013
+ const takerOrderParamsMessage = Uint8Array.from(this.encodeSwiftOrderParamsMessage(orderParamsMessage));
3014
+ return this.signMessage(takerOrderParamsMessage);
3015
+ }
3016
+ encodeSwiftOrderParamsMessage(orderParamsMessage) {
3017
+ return this.program.coder.types.encode('SwiftOrderParamsMessage', orderParamsMessage);
3018
+ }
3019
+ decodeSwiftOrderParamsMessage(encodedMessage) {
3020
+ return this.program.coder.types.decode('SwiftOrderParamsMessage', encodedMessage);
3021
+ }
3022
+ signMessage(message, keypair = this.wallet.payer) {
3023
+ return Buffer.from(tweetnacl_1.default.sign.detached(message, keypair.secretKey));
3024
+ }
3025
+ async placeSwiftTakerOrder(swiftServerMessage, swiftSignature, swiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo, txParams) {
3026
+ const ixs = await this.getPlaceSwiftTakerPerpOrderIxs(swiftServerMessage, swiftSignature, swiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo);
3027
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
3028
+ return txSig;
3029
+ }
3030
+ async getPlaceSwiftTakerPerpOrderIxs(encodedSwiftServerMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo) {
3031
+ const remainingAccounts = this.getRemainingAccounts({
3032
+ userAccounts: [takerInfo.takerUserAccount],
3033
+ useMarketLastSlotCache: true,
3034
+ readablePerpMarketIndex: marketIndex,
3035
+ });
3036
+ const swiftServerSignatureIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
3037
+ publicKey: new web3_js_1.PublicKey(this.swiftID).toBytes(),
3038
+ signature: Uint8Array.from(swiftSignature),
3039
+ message: Uint8Array.from(encodedSwiftServerMessage),
3040
+ });
3041
+ const swiftOrderParamsSignatureIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
3042
+ publicKey: takerInfo.takerUserAccount.authority.toBytes(),
3043
+ signature: Uint8Array.from(swiftOrderParamsSignature),
3044
+ message: Uint8Array.from(encodedSwiftOrderParamsMessage),
3045
+ });
3046
+ const placeTakerSwiftPerpOrderIx = await this.program.instruction.placeSwiftTakerOrder(encodedSwiftServerMessage, encodedSwiftOrderParamsMessage, swiftSignature, {
3047
+ accounts: {
3048
+ state: await this.getStatePublicKey(),
3049
+ user: takerInfo.taker,
3050
+ userStats: takerInfo.takerStats,
3051
+ authority: this.wallet.publicKey,
3052
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3053
+ },
3054
+ remainingAccounts,
3055
+ });
3056
+ return [
3057
+ swiftServerSignatureIx,
3058
+ swiftOrderParamsSignatureIx,
3059
+ placeTakerSwiftPerpOrderIx,
3060
+ ];
3061
+ }
3062
+ async placeAndMakeSwiftPerpOrder(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, txParams, subAccountId) {
3063
+ const ixs = await this.getPlaceAndMakeSwiftPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, subAccountId);
3064
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
3065
+ this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
3066
+ return txSig;
3067
+ }
3068
+ async getPlaceAndMakeSwiftPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, takerExpectedOrderId, takerInfo, orderParams, referrerInfo, subAccountId) {
3069
+ const [swiftServerSignatureIx, swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx,] = await this.getPlaceSwiftTakerPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, orderParams.marketIndex, takerInfo);
3070
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
3071
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3072
+ const user = await this.getUserAccountPublicKey(subAccountId);
3073
+ const remainingAccounts = this.getRemainingAccounts({
3074
+ userAccounts: [
3075
+ this.getUserAccount(subAccountId),
3076
+ takerInfo.takerUserAccount,
3077
+ ],
3078
+ useMarketLastSlotCache: true,
3079
+ writablePerpMarketIndexes: [orderParams.marketIndex],
3080
+ });
3081
+ if (referrerInfo) {
3082
+ remainingAccounts.push({
3083
+ pubkey: referrerInfo.referrer,
3084
+ isWritable: true,
3085
+ isSigner: false,
3086
+ });
3087
+ remainingAccounts.push({
3088
+ pubkey: referrerInfo.referrerStats,
3089
+ isWritable: true,
3090
+ isSigner: false,
3091
+ });
3092
+ }
3093
+ const placeAndMakeIx = await this.program.instruction.placeAndMakePerpOrder(orderParams, takerExpectedOrderId, {
3094
+ accounts: {
3095
+ state: await this.getStatePublicKey(),
3096
+ user,
3097
+ userStats: userStatsPublicKey,
3098
+ taker: takerInfo.taker,
3099
+ takerStats: takerInfo.takerStats,
3100
+ authority: this.wallet.publicKey,
3101
+ },
3102
+ remainingAccounts,
3103
+ });
3104
+ return [
3105
+ swiftServerSignatureIx,
3106
+ swiftOrderSignatureIx,
3107
+ placeTakerSwiftPerpOrderIx,
3108
+ placeAndMakeIx,
3109
+ ];
3110
+ }
3111
+ encodeRFQMakerOrderParams(message) {
3112
+ return this.program.coder.types.encode('RFQMakerOrderParams', message);
3113
+ }
3114
+ async placeAndMatchRFQOrders(rfqMatches, txParams) {
3115
+ const ixs = await this.getPlaceAndMatchRFQOrdersIxs(rfqMatches);
3116
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
3117
+ return txSig;
3118
+ }
3119
+ async getPlaceAndMatchRFQOrdersIxs(rfqMatches) {
3120
+ const remainingAccounts = this.getRemainingAccounts({
3121
+ userAccounts: [this.getUserAccount()],
3122
+ useMarketLastSlotCache: true,
3123
+ writablePerpMarketIndexes: [rfqMatches[0].makerOrderParams.marketIndex],
3124
+ });
3125
+ const makerAccountMetas = [];
3126
+ const verifyIxs = [];
3127
+ for (const match of rfqMatches) {
3128
+ const verifyIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
3129
+ publicKey: match.makerOrderParams.authority.toBytes(),
3130
+ signature: match.makerSignature,
3131
+ message: Uint8Array.from(this.encodeRFQMakerOrderParams(match.makerOrderParams)),
3132
+ });
3133
+ verifyIxs.push(verifyIx);
3134
+ const userAccountPubkey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, match.makerOrderParams.authority, match.makerOrderParams.subAccountId);
3135
+ makerAccountMetas.push({
3136
+ pubkey: userAccountPubkey,
3137
+ isWritable: true,
3138
+ isSigner: false,
3139
+ });
3140
+ makerAccountMetas.push({
3141
+ pubkey: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, match.makerOrderParams.authority),
3142
+ isWritable: true,
3143
+ isSigner: false,
3144
+ });
3145
+ makerAccountMetas.push({
3146
+ pubkey: (0, pda_1.getRFQUserAccountPublicKey)(this.program.programId, userAccountPubkey),
3147
+ isWritable: true,
3148
+ isSigner: false,
3149
+ });
3150
+ }
3151
+ remainingAccounts.push(...makerAccountMetas);
3152
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3153
+ const user = await this.getUserAccountPublicKey();
3154
+ const placeAndMatchRFQOrdersIx = await this.program.instruction.placeAndMatchRfqOrders(rfqMatches, {
3155
+ accounts: {
3156
+ state: await this.getStatePublicKey(),
3157
+ user,
3158
+ userStats: userStatsPublicKey,
3159
+ authority: this.wallet.publicKey,
3160
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3161
+ },
3162
+ remainingAccounts,
3163
+ });
3164
+ return [...verifyIxs, placeAndMatchRFQOrdersIx];
3165
+ }
3166
+ async preparePlaceAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId) {
3167
+ const tx = await this.buildTransaction(await this.getPlaceAndTakeSpotOrderIx(orderParams, fulfillmentConfig, makerInfo, referrerInfo, subAccountId), txParams);
3168
+ return {
3169
+ placeAndTakeSpotOrderTx: tx,
3170
+ };
3171
+ }
3172
+ async placeAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId) {
3173
+ const { txSig, slot } = await this.sendTransaction((await this.preparePlaceAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId)).placeAndTakeSpotOrderTx, [], this.opts, false);
3174
+ this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
3175
+ this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
3176
+ return txSig;
3177
+ }
3178
+ async getPlaceAndTakeSpotOrderIx(orderParams, fulfillmentConfig, makerInfo, referrerInfo, subAccountId) {
3179
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
3180
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3181
+ const user = await this.getUserAccountPublicKey(subAccountId);
3182
+ const userAccounts = [this.getUserAccount(subAccountId)];
3183
+ if (makerInfo !== undefined) {
3184
+ userAccounts.push(makerInfo.makerUserAccount);
3185
+ }
3186
+ const remainingAccounts = this.getRemainingAccounts({
3187
+ userAccounts,
3188
+ useMarketLastSlotCache: true,
3189
+ writableSpotMarketIndexes: [
3190
+ orderParams.marketIndex,
3191
+ numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
3192
+ ],
3193
+ });
3194
+ let makerOrderId = null;
3195
+ if (makerInfo) {
3196
+ makerOrderId = makerInfo.order.orderId;
3197
+ remainingAccounts.push({
3198
+ pubkey: makerInfo.maker,
3199
+ isSigner: false,
3200
+ isWritable: true,
3201
+ });
3202
+ remainingAccounts.push({
3203
+ pubkey: makerInfo.makerStats,
3204
+ isSigner: false,
3205
+ isWritable: true,
3206
+ });
3207
+ }
3208
+ if (referrerInfo) {
3209
+ remainingAccounts.push({
3210
+ pubkey: referrerInfo.referrer,
3211
+ isWritable: true,
3212
+ isSigner: false,
3213
+ });
3214
+ remainingAccounts.push({
3215
+ pubkey: referrerInfo.referrerStats,
3216
+ isWritable: true,
3217
+ isSigner: false,
3218
+ });
3219
+ }
3220
+ this.addSpotFulfillmentAccounts(orderParams.marketIndex, remainingAccounts, fulfillmentConfig);
3221
+ return await this.program.instruction.placeAndTakeSpotOrder(orderParams, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, makerOrderId, {
3222
+ accounts: {
3223
+ state: await this.getStatePublicKey(),
3224
+ user,
3225
+ userStats: userStatsPublicKey,
3226
+ authority: this.wallet.publicKey,
3227
+ },
3228
+ remainingAccounts,
3229
+ });
3230
+ }
3231
+ async placeAndMakeSpotOrder(orderParams, takerInfo, fulfillmentConfig, referrerInfo, txParams, subAccountId) {
3232
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakeSpotOrderIx(orderParams, takerInfo, fulfillmentConfig, referrerInfo, subAccountId), txParams), [], this.opts);
3233
+ this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
3234
+ this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
3235
+ return txSig;
3236
+ }
3237
+ async getPlaceAndMakeSpotOrderIx(orderParams, takerInfo, fulfillmentConfig, referrerInfo, subAccountId) {
3238
+ orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
3239
+ const userStatsPublicKey = this.getUserStatsAccountPublicKey();
3240
+ const user = await this.getUserAccountPublicKey(subAccountId);
3241
+ const remainingAccounts = this.getRemainingAccounts({
3242
+ userAccounts: [
3243
+ this.getUserAccount(subAccountId),
3244
+ takerInfo.takerUserAccount,
3245
+ ],
3246
+ useMarketLastSlotCache: true,
3247
+ writableSpotMarketIndexes: [
3248
+ orderParams.marketIndex,
3249
+ numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
3250
+ ],
3251
+ });
3252
+ if (referrerInfo) {
3253
+ remainingAccounts.push({
3254
+ pubkey: referrerInfo.referrer,
3255
+ isWritable: true,
3256
+ isSigner: false,
3257
+ });
3258
+ remainingAccounts.push({
3259
+ pubkey: referrerInfo.referrerStats,
3260
+ isWritable: true,
3261
+ isSigner: false,
3262
+ });
3263
+ }
3264
+ this.addSpotFulfillmentAccounts(orderParams.marketIndex, remainingAccounts, fulfillmentConfig);
3265
+ const takerOrderId = takerInfo.order.orderId;
3266
+ return await this.program.instruction.placeAndMakeSpotOrder(orderParams, takerOrderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, {
3267
+ accounts: {
3268
+ state: await this.getStatePublicKey(),
3269
+ user,
3270
+ userStats: userStatsPublicKey,
3271
+ taker: takerInfo.taker,
3272
+ takerStats: takerInfo.takerStats,
3273
+ authority: this.wallet.publicKey,
3274
+ },
3275
+ remainingAccounts,
3276
+ });
3277
+ }
3278
+ /**
3279
+ * @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
3280
+ */
3281
+ async closePosition(marketIndex, limitPrice, subAccountId) {
3282
+ const userPosition = this.getUser(subAccountId).getPerpPosition(marketIndex);
3283
+ if (!userPosition) {
3284
+ throw Error(`No position in market ${marketIndex.toString()}`);
3285
+ }
3286
+ return await this.placeAndTakePerpOrder({
3287
+ orderType: types_1.OrderType.MARKET,
3288
+ marketIndex,
3289
+ direction: (0, position_1.findDirectionToClose)(userPosition),
3290
+ baseAssetAmount: userPosition.baseAssetAmount.abs(),
3291
+ reduceOnly: true,
3292
+ price: limitPrice,
3293
+ }, undefined, undefined, undefined, undefined, subAccountId);
3294
+ }
3295
+ /**
3296
+ * Modifies an open order by closing it and replacing it with a new order.
3297
+ * @deprecated use modifyOrder instead
3298
+ * @param orderId: The open order to modify
3299
+ * @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3300
+ * @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3301
+ * @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3302
+ * @returns
3303
+ */
3304
+ async modifyPerpOrder(orderId, newBaseAmount, newLimitPrice, newOraclePriceOffset) {
3305
+ return this.modifyOrder({
3306
+ orderId,
3307
+ newBaseAmount,
3308
+ newLimitPrice,
3309
+ newOraclePriceOffset,
3310
+ });
3311
+ }
3312
+ /**
3313
+ * Modifies an open order by closing it and replacing it with a new order.
3314
+ * @deprecated use modifyOrderByUserOrderId instead
3315
+ * @param userOrderId: The open order to modify
3316
+ * @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3317
+ * @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3318
+ * @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
3319
+ * @returns
3320
+ */
3321
+ async modifyPerpOrderByUserOrderId(userOrderId, newBaseAmount, newLimitPrice, newOraclePriceOffset) {
3322
+ return this.modifyOrderByUserOrderId({
3323
+ userOrderId,
3324
+ newBaseAmount,
3325
+ newLimitPrice,
3326
+ newOraclePriceOffset,
3327
+ });
3328
+ }
3329
+ /**
3330
+ * Modifies an open order (spot or perp) by closing it and replacing it with a new order.
3331
+ * @param orderParams.orderId: The open order to modify
3332
+ * @param orderParams.newDirection: The new direction for the order
3333
+ * @param orderParams.newBaseAmount: The new base amount for the order
3334
+ * @param orderParams.newLimitPice: The new limit price for the order
3335
+ * @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
3336
+ * @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
3337
+ * @param orderParams.auctionDuration:
3338
+ * @param orderParams.auctionStartPrice:
3339
+ * @param orderParams.auctionEndPrice:
3340
+ * @param orderParams.reduceOnly:
3341
+ * @param orderParams.postOnly:
3342
+ * @param orderParams.immediateOrCancel:
3343
+ * @param orderParams.policy:
3344
+ * @param orderParams.maxTs:
3345
+ * @returns
3346
+ */
3347
+ async modifyOrder(orderParams, txParams, subAccountId) {
3348
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getModifyOrderIx(orderParams, subAccountId), txParams), [], this.opts);
3349
+ return txSig;
3350
+ }
3351
+ async getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, immediateOrCancel, maxTs, policy, }, subAccountId) {
3352
+ const user = await this.getUserAccountPublicKey(subAccountId);
3353
+ const remainingAccounts = this.getRemainingAccounts({
3354
+ userAccounts: [this.getUserAccount(subAccountId)],
3355
+ useMarketLastSlotCache: true,
3356
+ });
3357
+ const orderParams = {
3358
+ baseAssetAmount: newBaseAmount || null,
3359
+ direction: newDirection || null,
3360
+ price: newLimitPrice || null,
3361
+ oraclePriceOffset: newOraclePriceOffset || null,
3362
+ triggerPrice: newTriggerPrice || null,
3363
+ triggerCondition: newTriggerCondition || null,
3364
+ auctionDuration: auctionDuration || null,
3365
+ auctionStartPrice: auctionStartPrice || null,
3366
+ auctionEndPrice: auctionEndPrice || null,
3367
+ reduceOnly: reduceOnly != undefined ? reduceOnly : null,
3368
+ postOnly: postOnly != undefined ? postOnly : null,
3369
+ immediateOrCancel: immediateOrCancel != undefined ? immediateOrCancel : null,
3370
+ policy: policy || null,
3371
+ maxTs: maxTs || null,
3372
+ };
3373
+ return await this.program.instruction.modifyOrder(orderId, orderParams, {
3374
+ accounts: {
3375
+ state: await this.getStatePublicKey(),
3376
+ user,
3377
+ userStats: this.getUserStatsAccountPublicKey(),
3378
+ authority: this.wallet.publicKey,
3379
+ },
3380
+ remainingAccounts,
3381
+ });
3382
+ }
3383
+ /**
3384
+ * Modifies an open order by closing it and replacing it with a new order.
3385
+ * @param orderParams.userOrderId: The open order to modify
3386
+ * @param orderParams.newDirection: The new direction for the order
3387
+ * @param orderParams.newBaseAmount: The new base amount for the order
3388
+ * @param orderParams.newLimitPice: The new limit price for the order
3389
+ * @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
3390
+ * @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
3391
+ * @param orderParams.auctionDuration: Only required if order type changed to market from something else
3392
+ * @param orderParams.auctionStartPrice: Only required if order type changed to market from something else
3393
+ * @param orderParams.auctionEndPrice: Only required if order type changed to market from something else
3394
+ * @param orderParams.reduceOnly:
3395
+ * @param orderParams.postOnly:
3396
+ * @param orderParams.immediateOrCancel:
3397
+ * @param orderParams.policy:
3398
+ * @param orderParams.maxTs:
3399
+ * @returns
3400
+ */
3401
+ async modifyOrderByUserOrderId(orderParams, txParams, subAccountId) {
3402
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getModifyOrderByUserIdIx(orderParams, subAccountId), txParams), [], this.opts);
3403
+ return txSig;
3404
+ }
3405
+ async getModifyOrderByUserIdIx({ userOrderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, immediateOrCancel, maxTs, policy, }, subAccountId) {
3406
+ const user = await this.getUserAccountPublicKey(subAccountId);
3407
+ const remainingAccounts = this.getRemainingAccounts({
3408
+ userAccounts: [this.getUserAccount(subAccountId)],
3409
+ useMarketLastSlotCache: true,
3410
+ });
3411
+ const orderParams = {
3412
+ baseAssetAmount: newBaseAmount || null,
3413
+ direction: newDirection || null,
3414
+ price: newLimitPrice || null,
3415
+ oraclePriceOffset: newOraclePriceOffset || null,
3416
+ triggerPrice: newTriggerPrice || null,
3417
+ triggerCondition: newTriggerCondition || null,
3418
+ auctionDuration: auctionDuration || null,
3419
+ auctionStartPrice: auctionStartPrice || null,
3420
+ auctionEndPrice: auctionEndPrice || null,
3421
+ reduceOnly: reduceOnly || false,
3422
+ postOnly: postOnly || null,
3423
+ immediateOrCancel: immediateOrCancel || false,
3424
+ policy: policy || null,
3425
+ maxTs: maxTs || null,
3426
+ };
3427
+ return await this.program.instruction.modifyOrderByUserId(userOrderId, orderParams, {
3428
+ accounts: {
3429
+ state: await this.getStatePublicKey(),
3430
+ user,
3431
+ userStats: this.getUserStatsAccountPublicKey(),
3432
+ authority: this.wallet.publicKey,
3433
+ },
3434
+ remainingAccounts,
3435
+ });
3436
+ }
3437
+ async settlePNLs(users, marketIndexes, opts, txParams) {
3438
+ const filterInvalidMarkets = opts === null || opts === void 0 ? void 0 : opts.filterInvalidMarkets;
3439
+ // # Filter market indexes by markets with valid oracle
3440
+ const marketIndexToSettle = filterInvalidMarkets
3441
+ ? []
3442
+ : marketIndexes;
3443
+ if (filterInvalidMarkets) {
3444
+ for (const marketIndex of marketIndexes) {
3445
+ const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
3446
+ const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
3447
+ const stateAccountAndSlot = this.accountSubscriber.getStateAccountAndSlot();
3448
+ const oracleGuardRails = stateAccountAndSlot.data.oracleGuardRails;
3449
+ const isValid = (0, oracles_1.isOracleValid)(perpMarketAccount, oraclePriceData, oracleGuardRails, stateAccountAndSlot.slot);
3450
+ if (isValid) {
3451
+ marketIndexToSettle.push(marketIndex);
3452
+ }
3453
+ }
3454
+ }
3455
+ // # Settle filtered market indexes
3456
+ const ixs = await this.getSettlePNLsIxs(users, marketIndexToSettle);
3457
+ const tx = await this.buildTransaction(ixs, txParams !== null && txParams !== void 0 ? txParams : {
3458
+ computeUnits: 1400000,
3459
+ });
3460
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
3461
+ return txSig;
3462
+ }
3463
+ async getSettlePNLsIxs(users, marketIndexes) {
3464
+ const ixs = [];
3465
+ for (const { settleeUserAccountPublicKey, settleeUserAccount } of users) {
3466
+ for (const marketIndex of marketIndexes) {
3467
+ ixs.push(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex));
3468
+ }
3469
+ }
3470
+ return ixs;
3471
+ }
3472
+ async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, txParams) {
3473
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex), txParams), [], this.opts);
3474
+ return txSig;
3475
+ }
3476
+ async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
3477
+ const remainingAccounts = this.getRemainingAccounts({
3478
+ userAccounts: [settleeUserAccount],
3479
+ writablePerpMarketIndexes: [marketIndex],
3480
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3481
+ });
3482
+ return await this.program.instruction.settlePnl(marketIndex, {
3483
+ accounts: {
3484
+ state: await this.getStatePublicKey(),
3485
+ authority: this.wallet.publicKey,
3486
+ user: settleeUserAccountPublicKey,
3487
+ spotMarketVault: this.getQuoteSpotMarketAccount().vault,
3488
+ },
3489
+ remainingAccounts: remainingAccounts,
3490
+ });
3491
+ }
3492
+ async settleMultiplePNLs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams) {
3493
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode), txParams), [], this.opts);
3494
+ return txSig;
3495
+ }
3496
+ async settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode) {
3497
+ const remainingAccounts = this.getRemainingAccounts({
3498
+ userAccounts: [settleeUserAccount],
3499
+ writablePerpMarketIndexes: marketIndexes,
3500
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3501
+ });
3502
+ return await this.program.instruction.settleMultiplePnls(marketIndexes, mode, {
3503
+ accounts: {
3504
+ state: await this.getStatePublicKey(),
3505
+ authority: this.wallet.publicKey,
3506
+ user: settleeUserAccountPublicKey,
3507
+ spotMarketVault: this.getQuoteSpotMarketAccount().vault,
3508
+ },
3509
+ remainingAccounts: remainingAccounts,
3510
+ });
3511
+ }
3512
+ async getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey, userAccount) {
3513
+ const remainingAccounts = this.getRemainingAccounts({
3514
+ userAccounts: [userAccount],
3515
+ });
3516
+ return await this.program.instruction.setUserStatusToBeingLiquidated({
3517
+ accounts: {
3518
+ state: await this.getStatePublicKey(),
3519
+ user: userAccountPublicKey,
3520
+ authority: this.wallet.publicKey,
3521
+ },
3522
+ remainingAccounts,
3523
+ });
3524
+ }
3525
+ async setUserStatusToBeingLiquidated(userAccountPublicKey, userAccount) {
3526
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey, userAccount)), [], this.opts);
3527
+ return txSig;
3528
+ }
3529
+ async liquidatePerp(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, txParams, liquidatorSubAccountId) {
3530
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
3531
+ this.perpMarketLastSlotCache.set(marketIndex, slot);
3532
+ return txSig;
3533
+ }
3534
+ async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId) {
3535
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3536
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3537
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3538
+ const remainingAccounts = this.getRemainingAccounts({
3539
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3540
+ useMarketLastSlotCache: true,
3541
+ writablePerpMarketIndexes: [marketIndex],
3542
+ });
3543
+ return await this.program.instruction.liquidatePerp(marketIndex, maxBaseAssetAmount, limitPrice !== null && limitPrice !== void 0 ? limitPrice : null, {
3544
+ accounts: {
3545
+ state: await this.getStatePublicKey(),
3546
+ authority: this.wallet.publicKey,
3547
+ user: userAccountPublicKey,
3548
+ userStats: userStatsPublicKey,
3549
+ liquidator,
3550
+ liquidatorStats: liquidatorStatsPublicKey,
3551
+ },
3552
+ remainingAccounts: remainingAccounts,
3553
+ });
3554
+ }
3555
+ async liquidatePerpWithFill(userAccountPublicKey, userAccount, marketIndex, makerInfos, txParams, liquidatorSubAccountId) {
3556
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId), txParams), [], this.opts);
3557
+ this.perpMarketLastSlotCache.set(marketIndex, slot);
3558
+ return txSig;
3559
+ }
3560
+ async getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId) {
3561
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3562
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3563
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3564
+ const remainingAccounts = this.getRemainingAccounts({
3565
+ userAccounts: [
3566
+ userAccount,
3567
+ ...makerInfos.map((makerInfo) => makerInfo.makerUserAccount),
3568
+ ],
3569
+ useMarketLastSlotCache: true,
3570
+ writablePerpMarketIndexes: [marketIndex],
3571
+ });
3572
+ for (const makerInfo of makerInfos) {
3573
+ remainingAccounts.push({
3574
+ pubkey: makerInfo.maker,
3575
+ isSigner: false,
3576
+ isWritable: true,
3577
+ });
3578
+ remainingAccounts.push({
3579
+ pubkey: makerInfo.makerStats,
3580
+ isSigner: false,
3581
+ isWritable: true,
3582
+ });
3583
+ }
3584
+ return await this.program.instruction.liquidatePerpWithFill(marketIndex, {
3585
+ accounts: {
3586
+ state: await this.getStatePublicKey(),
3587
+ authority: this.wallet.publicKey,
3588
+ user: userAccountPublicKey,
3589
+ userStats: userStatsPublicKey,
3590
+ liquidator,
3591
+ liquidatorStats: liquidatorStatsPublicKey,
3592
+ },
3593
+ remainingAccounts: remainingAccounts,
3594
+ });
3595
+ }
3596
+ async liquidateSpot(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
3597
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
3598
+ this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
3599
+ this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
3600
+ return txSig;
3601
+ }
3602
+ async getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
3603
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3604
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3605
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3606
+ const remainingAccounts = this.getRemainingAccounts({
3607
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3608
+ useMarketLastSlotCache: true,
3609
+ writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
3610
+ });
3611
+ return await this.program.instruction.liquidateSpot(assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice || null, {
3612
+ accounts: {
3613
+ state: await this.getStatePublicKey(),
3614
+ authority: this.wallet.publicKey,
3615
+ user: userAccountPublicKey,
3616
+ userStats: userStatsPublicKey,
3617
+ liquidator,
3618
+ liquidatorStats: liquidatorStatsPublicKey,
3619
+ },
3620
+ remainingAccounts: remainingAccounts,
3621
+ });
3622
+ }
3623
+ async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
3624
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
3625
+ this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
3626
+ this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
3627
+ return txSig;
3628
+ }
3629
+ async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
3630
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3631
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3632
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3633
+ const remainingAccounts = this.getRemainingAccounts({
3634
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3635
+ writablePerpMarketIndexes: [perpMarketIndex],
3636
+ writableSpotMarketIndexes: [liabilityMarketIndex],
3637
+ });
3638
+ return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice || null, {
3639
+ accounts: {
3640
+ state: await this.getStatePublicKey(),
3641
+ authority: this.wallet.publicKey,
3642
+ user: userAccountPublicKey,
3643
+ userStats: userStatsPublicKey,
3644
+ liquidator,
3645
+ liquidatorStats: liquidatorStatsPublicKey,
3646
+ },
3647
+ remainingAccounts: remainingAccounts,
3648
+ });
3649
+ }
3650
+ async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, txParams, liquidatorSubAccountId) {
3651
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
3652
+ this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
3653
+ this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
3654
+ return txSig;
3655
+ }
3656
+ async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId) {
3657
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3658
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3659
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3660
+ const remainingAccounts = this.getRemainingAccounts({
3661
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3662
+ writablePerpMarketIndexes: [perpMarketIndex],
3663
+ writableSpotMarketIndexes: [assetMarketIndex],
3664
+ });
3665
+ return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice || null, {
3666
+ accounts: {
3667
+ state: await this.getStatePublicKey(),
3668
+ authority: this.wallet.publicKey,
3669
+ user: userAccountPublicKey,
3670
+ userStats: userStatsPublicKey,
3671
+ liquidator,
3672
+ liquidatorStats: liquidatorStatsPublicKey,
3673
+ },
3674
+ remainingAccounts: remainingAccounts,
3675
+ });
3676
+ }
3677
+ async resolvePerpBankruptcy(userAccountPublicKey, userAccount, marketIndex, txParams, liquidatorSubAccountId) {
3678
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId), txParams), [], this.opts);
3679
+ return txSig;
3680
+ }
3681
+ async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId) {
3682
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3683
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3684
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3685
+ const remainingAccounts = this.getRemainingAccounts({
3686
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3687
+ writablePerpMarketIndexes: [marketIndex],
3688
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3689
+ });
3690
+ const spotMarket = this.getQuoteSpotMarketAccount();
3691
+ return await this.program.instruction.resolvePerpBankruptcy(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, marketIndex, {
3692
+ accounts: {
3693
+ state: await this.getStatePublicKey(),
3694
+ authority: this.wallet.publicKey,
3695
+ user: userAccountPublicKey,
3696
+ userStats: userStatsPublicKey,
3697
+ liquidator,
3698
+ liquidatorStats: liquidatorStatsPublicKey,
3699
+ spotMarketVault: spotMarket.vault,
3700
+ insuranceFundVault: spotMarket.insuranceFund.vault,
3701
+ driftSigner: this.getSignerPublicKey(),
3702
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3703
+ },
3704
+ remainingAccounts: remainingAccounts,
3705
+ });
3706
+ }
3707
+ async resolveSpotBankruptcy(userAccountPublicKey, userAccount, marketIndex, txParams, liquidatorSubAccountId) {
3708
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolveSpotBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId), txParams), [], this.opts);
3709
+ return txSig;
3710
+ }
3711
+ async getResolveSpotBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId) {
3712
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
3713
+ const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
3714
+ const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
3715
+ const remainingAccounts = this.getRemainingAccounts({
3716
+ userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
3717
+ writableSpotMarketIndexes: [marketIndex],
3718
+ });
3719
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
3720
+ this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
3721
+ return await this.program.instruction.resolveSpotBankruptcy(marketIndex, {
3722
+ accounts: {
3723
+ state: await this.getStatePublicKey(),
3724
+ authority: this.wallet.publicKey,
3725
+ user: userAccountPublicKey,
3726
+ userStats: userStatsPublicKey,
3727
+ liquidatorStats: liquidatorStatsPublicKey,
3728
+ liquidator,
3729
+ spotMarketVault: spotMarket.vault,
3730
+ insuranceFundVault: spotMarket.insuranceFund.vault,
3731
+ driftSigner: this.getSignerPublicKey(),
3732
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3733
+ },
3734
+ remainingAccounts: remainingAccounts,
3735
+ });
3736
+ }
3737
+ async updateFundingRate(perpMarketIndex, oracle, txParams) {
3738
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateFundingRateIx(perpMarketIndex, oracle), txParams), [], this.opts);
3739
+ return txSig;
3740
+ }
3741
+ async getUpdateFundingRateIx(perpMarketIndex, oracle) {
3742
+ const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, perpMarketIndex);
3743
+ return await this.program.instruction.updateFundingRate(perpMarketIndex, {
3744
+ accounts: {
3745
+ state: await this.getStatePublicKey(),
3746
+ perpMarket: perpMarketPublicKey,
3747
+ oracle: oracle,
3748
+ },
3749
+ });
3750
+ }
3751
+ async updatePrelaunchOracle(perpMarketIndex, txParams) {
3752
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdatePrelaunchOracleIx(perpMarketIndex), txParams), [], this.opts);
3753
+ return txSig;
3754
+ }
3755
+ async getUpdatePrelaunchOracleIx(perpMarketIndex) {
3756
+ const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
3757
+ if (!(0, types_1.isVariant)(perpMarket.amm.oracleSource, 'prelaunch')) {
3758
+ throw new Error(`Wrong oracle source ${perpMarket.amm.oracleSource}`);
3759
+ }
3760
+ return await this.program.instruction.updatePrelaunchOracle({
3761
+ accounts: {
3762
+ state: await this.getStatePublicKey(),
3763
+ perpMarket: perpMarket.pubkey,
3764
+ oracle: perpMarket.amm.oracle,
3765
+ },
3766
+ });
3767
+ }
3768
+ async updatePerpBidAskTwap(perpMarketIndex, makers, txParams) {
3769
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdatePerpBidAskTwapIx(perpMarketIndex, makers), txParams), [], this.opts);
3770
+ return txSig;
3771
+ }
3772
+ async getUpdatePerpBidAskTwapIx(perpMarketIndex, makers) {
3773
+ const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
3774
+ const remainingAccounts = [];
3775
+ for (const [maker, makerStats] of makers) {
3776
+ remainingAccounts.push({
3777
+ pubkey: maker,
3778
+ isWritable: false,
3779
+ isSigner: false,
3780
+ });
3781
+ remainingAccounts.push({
3782
+ pubkey: makerStats,
3783
+ isWritable: false,
3784
+ isSigner: false,
3785
+ });
3786
+ }
3787
+ return await this.program.instruction.updatePerpBidAskTwap({
3788
+ accounts: {
3789
+ state: await this.getStatePublicKey(),
3790
+ perpMarket: perpMarket.pubkey,
3791
+ oracle: perpMarket.amm.oracle,
3792
+ authority: this.wallet.publicKey,
3793
+ keeperStats: this.getUserStatsAccountPublicKey(),
3794
+ },
3795
+ remainingAccounts,
3796
+ });
3797
+ }
3798
+ async settleFundingPayment(userAccountPublicKey, txParams) {
3799
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleFundingPaymentIx(userAccountPublicKey), txParams), [], this.opts);
3800
+ return txSig;
3801
+ }
3802
+ async getSettleFundingPaymentIx(userAccountPublicKey) {
3803
+ const userAccount = (await this.program.account.user.fetch(userAccountPublicKey));
3804
+ const writablePerpMarketIndexes = [];
3805
+ for (const position of userAccount.perpPositions) {
3806
+ if (!(0, position_1.positionIsAvailable)(position)) {
3807
+ writablePerpMarketIndexes.push(position.marketIndex);
3808
+ }
3809
+ }
3810
+ const remainingAccounts = this.getRemainingAccounts({
3811
+ userAccounts: [userAccount],
3812
+ writablePerpMarketIndexes,
3813
+ });
3814
+ return await this.program.instruction.settleFundingPayment({
3815
+ accounts: {
3816
+ state: await this.getStatePublicKey(),
3817
+ user: userAccountPublicKey,
3818
+ },
3819
+ remainingAccounts,
3820
+ });
3821
+ }
3822
+ triggerEvent(eventName, data) {
3823
+ this.eventEmitter.emit(eventName, data);
3824
+ }
3825
+ getOracleDataForPerpMarket(marketIndex) {
3826
+ return this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(marketIndex).data;
3827
+ }
3828
+ getOracleDataForSpotMarket(marketIndex) {
3829
+ return this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(marketIndex).data;
3830
+ }
3831
+ async initializeInsuranceFundStake(marketIndex, txParams) {
3832
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getInitializeInsuranceFundStakeIx(marketIndex), txParams), [], this.opts);
3833
+ return txSig;
3834
+ }
3835
+ async getInitializeInsuranceFundStakeIx(marketIndex) {
3836
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
3837
+ return await this.program.instruction.initializeInsuranceFundStake(marketIndex, {
3838
+ accounts: {
3839
+ insuranceFundStake: ifStakeAccountPublicKey,
3840
+ spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
3841
+ userStats: this.getUserStatsAccountPublicKey(),
3842
+ authority: this.wallet.publicKey,
3843
+ payer: this.wallet.publicKey,
3844
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
3845
+ systemProgram: anchor.web3.SystemProgram.programId,
3846
+ state: await this.getStatePublicKey(),
3847
+ },
3848
+ });
3849
+ }
3850
+ async getAddInsuranceFundStakeIx(marketIndex, amount, collateralAccountPublicKey) {
3851
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
3852
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
3853
+ const remainingAccounts = [];
3854
+ this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
3855
+ const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
3856
+ const ix = this.program.instruction.addInsuranceFundStake(marketIndex, amount, {
3857
+ accounts: {
3858
+ state: await this.getStatePublicKey(),
3859
+ spotMarket: spotMarket.pubkey,
3860
+ insuranceFundStake: ifStakeAccountPublicKey,
3861
+ userStats: this.getUserStatsAccountPublicKey(),
3862
+ authority: this.wallet.publicKey,
3863
+ spotMarketVault: spotMarket.vault,
3864
+ insuranceFundVault: spotMarket.insuranceFund.vault,
3865
+ driftSigner: this.getSignerPublicKey(),
3866
+ userTokenAccount: collateralAccountPublicKey,
3867
+ tokenProgram,
3868
+ },
3869
+ remainingAccounts,
3870
+ });
3871
+ return ix;
3872
+ }
3873
+ /**
3874
+ * Add to an insurance fund stake and optionally initialize the account
3875
+ */
3876
+ async addInsuranceFundStake({ marketIndex, amount, collateralAccountPublicKey, initializeStakeAccount, fromSubaccount, txParams, }) {
3877
+ const addIfStakeIxs = [];
3878
+ const additionalSigners = [];
3879
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3880
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
3881
+ const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
3882
+ let tokenAccount;
3883
+ if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
3884
+ addIfStakeIxs.push(await this.getInitializeUserStatsIx());
3885
+ }
3886
+ if (createWSOLTokenAccount) {
3887
+ const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, true);
3888
+ tokenAccount = pubkey;
3889
+ ixs.forEach((ix) => {
3890
+ addIfStakeIxs.push(ix);
3891
+ });
3892
+ }
3893
+ else {
3894
+ tokenAccount = collateralAccountPublicKey;
3895
+ }
3896
+ if (fromSubaccount) {
3897
+ const withdrawIx = await this.getWithdrawIx(amount, marketIndex, tokenAccount);
3898
+ addIfStakeIxs.push(withdrawIx);
3899
+ }
3900
+ if (initializeStakeAccount) {
3901
+ const initializeIx = await this.getInitializeInsuranceFundStakeIx(marketIndex);
3902
+ addIfStakeIxs.push(initializeIx);
3903
+ }
3904
+ const addFundsIx = await this.getAddInsuranceFundStakeIx(marketIndex, amount, tokenAccount);
3905
+ addIfStakeIxs.push(addFundsIx);
3906
+ if (createWSOLTokenAccount) {
3907
+ addIfStakeIxs.push((0, spl_token_1.createCloseAccountInstruction)(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, []));
3908
+ }
3909
+ const tx = await this.buildTransaction(addIfStakeIxs, txParams);
3910
+ const { txSig } = await this.sendTransaction(tx, additionalSigners, this.opts);
3911
+ return txSig;
3912
+ }
3913
+ async requestRemoveInsuranceFundStake(marketIndex, amount, txParams) {
3914
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3915
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
3916
+ const ix = await this.program.instruction.requestRemoveInsuranceFundStake(marketIndex, amount, {
3917
+ accounts: {
3918
+ state: await this.getStatePublicKey(),
3919
+ spotMarket: spotMarketAccount.pubkey,
3920
+ insuranceFundStake: ifStakeAccountPublicKey,
3921
+ userStats: this.getUserStatsAccountPublicKey(),
3922
+ authority: this.wallet.publicKey,
3923
+ insuranceFundVault: spotMarketAccount.insuranceFund.vault,
3924
+ },
3925
+ });
3926
+ const tx = await this.buildTransaction(ix, txParams);
3927
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
3928
+ return txSig;
3929
+ }
3930
+ async cancelRequestRemoveInsuranceFundStake(marketIndex, txParams) {
3931
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3932
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
3933
+ const ix = await this.program.instruction.cancelRequestRemoveInsuranceFundStake(marketIndex, {
3934
+ accounts: {
3935
+ state: await this.getStatePublicKey(),
3936
+ spotMarket: spotMarketAccount.pubkey,
3937
+ insuranceFundStake: ifStakeAccountPublicKey,
3938
+ userStats: this.getUserStatsAccountPublicKey(),
3939
+ authority: this.wallet.publicKey,
3940
+ insuranceFundVault: spotMarketAccount.insuranceFund.vault,
3941
+ },
3942
+ });
3943
+ const tx = await this.buildTransaction(ix, txParams);
3944
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
3945
+ return txSig;
3946
+ }
3947
+ async removeInsuranceFundStake(marketIndex, collateralAccountPublicKey, txParams) {
3948
+ const removeIfStakeIxs = [];
3949
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3950
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
3951
+ const additionalSigners = [];
3952
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
3953
+ const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
3954
+ let tokenAccount;
3955
+ if (createWSOLTokenAccount) {
3956
+ const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(numericConstants_1.ZERO, true);
3957
+ tokenAccount = pubkey;
3958
+ ixs.forEach((ix) => {
3959
+ removeIfStakeIxs.push(ix);
3960
+ });
3961
+ }
3962
+ else {
3963
+ tokenAccount = collateralAccountPublicKey;
3964
+ const tokenAccountExists = await this.checkIfAccountExists(tokenAccount);
3965
+ if (!tokenAccountExists) {
3966
+ const createTokenAccountIx = await this.createAssociatedTokenAccountIdempotentInstruction(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, spotMarketAccount.mint);
3967
+ removeIfStakeIxs.push(createTokenAccountIx);
3968
+ }
3969
+ }
3970
+ const remainingAccounts = [];
3971
+ this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
3972
+ const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
3973
+ const removeStakeIx = await this.program.instruction.removeInsuranceFundStake(marketIndex, {
3974
+ accounts: {
3975
+ state: await this.getStatePublicKey(),
3976
+ spotMarket: spotMarketAccount.pubkey,
3977
+ insuranceFundStake: ifStakeAccountPublicKey,
3978
+ userStats: this.getUserStatsAccountPublicKey(),
3979
+ authority: this.wallet.publicKey,
3980
+ insuranceFundVault: spotMarketAccount.insuranceFund.vault,
3981
+ driftSigner: this.getSignerPublicKey(),
3982
+ userTokenAccount: tokenAccount,
3983
+ tokenProgram,
3984
+ },
3985
+ remainingAccounts,
3986
+ });
3987
+ removeIfStakeIxs.push(removeStakeIx);
3988
+ // Close the wrapped sol account at the end of the transaction
3989
+ if (createWSOLTokenAccount) {
3990
+ removeIfStakeIxs.push((0, spl_token_1.createCloseAccountInstruction)(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, []));
3991
+ }
3992
+ const tx = await this.buildTransaction(removeIfStakeIxs, txParams);
3993
+ const { txSig } = await this.sendTransaction(tx, additionalSigners, this.opts);
3994
+ return txSig;
3995
+ }
3996
+ async updateUserQuoteAssetInsuranceStake(authority, txParams) {
3997
+ const tx = await this.buildTransaction(await this.getUpdateUserQuoteAssetInsuranceStakeIx(authority), txParams);
3998
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
3999
+ return txSig;
4000
+ }
4001
+ async getUpdateUserQuoteAssetInsuranceStakeIx(authority) {
4002
+ const marketIndex = numericConstants_1.QUOTE_SPOT_MARKET_INDEX;
4003
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
4004
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
4005
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
4006
+ const ix = this.program.instruction.updateUserQuoteAssetInsuranceStake({
4007
+ accounts: {
4008
+ state: await this.getStatePublicKey(),
4009
+ spotMarket: spotMarket.pubkey,
4010
+ insuranceFundStake: ifStakeAccountPublicKey,
4011
+ userStats: userStatsPublicKey,
4012
+ signer: this.wallet.publicKey,
4013
+ insuranceFundVault: spotMarket.insuranceFund.vault,
4014
+ },
4015
+ });
4016
+ return ix;
4017
+ }
4018
+ async updateUserGovTokenInsuranceStake(authority, txParams) {
4019
+ const tx = await this.buildTransaction(await this.getUpdateUserGovTokenInsuranceStakeIx(authority), txParams);
4020
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
4021
+ return txSig;
4022
+ }
4023
+ async getUpdateUserGovTokenInsuranceStakeIx(authority) {
4024
+ const marketIndex = numericConstants_1.GOV_SPOT_MARKET_INDEX;
4025
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
4026
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
4027
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
4028
+ const ix = this.program.instruction.updateUserGovTokenInsuranceStake({
4029
+ accounts: {
4030
+ state: await this.getStatePublicKey(),
4031
+ spotMarket: spotMarket.pubkey,
4032
+ insuranceFundStake: ifStakeAccountPublicKey,
4033
+ userStats: userStatsPublicKey,
4034
+ signer: this.wallet.publicKey,
4035
+ insuranceFundVault: spotMarket.insuranceFund.vault,
4036
+ },
4037
+ });
4038
+ return ix;
4039
+ }
4040
+ async settleRevenueToInsuranceFund(spotMarketIndex, txParams) {
4041
+ const tx = await this.buildTransaction(await this.getSettleRevenueToInsuranceFundIx(spotMarketIndex), txParams);
4042
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
4043
+ return txSig;
4044
+ }
4045
+ async getSettleRevenueToInsuranceFundIx(spotMarketIndex) {
4046
+ const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
4047
+ const remainingAccounts = [];
4048
+ this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
4049
+ const ix = await this.program.instruction.settleRevenueToInsuranceFund(spotMarketIndex, {
4050
+ accounts: {
4051
+ state: await this.getStatePublicKey(),
4052
+ spotMarket: spotMarketAccount.pubkey,
4053
+ spotMarketVault: spotMarketAccount.vault,
4054
+ driftSigner: this.getSignerPublicKey(),
4055
+ insuranceFundVault: spotMarketAccount.insuranceFund.vault,
4056
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
4057
+ },
4058
+ remainingAccounts,
4059
+ });
4060
+ return ix;
4061
+ }
4062
+ async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, txParams) {
4063
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex), txParams), [], this.opts);
4064
+ return txSig;
4065
+ }
4066
+ async getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex) {
4067
+ const remainingAccounts = this.getRemainingAccounts({
4068
+ userAccounts: [this.getUserAccount()],
4069
+ useMarketLastSlotCache: true,
4070
+ writablePerpMarketIndexes: [perpMarketIndex],
4071
+ writableSpotMarketIndexes: [spotMarketIndex],
4072
+ });
4073
+ const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
4074
+ return await this.program.instruction.resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, {
4075
+ accounts: {
4076
+ state: await this.getStatePublicKey(),
4077
+ authority: this.wallet.publicKey,
4078
+ spotMarketVault: spotMarket.vault,
4079
+ insuranceFundVault: spotMarket.insuranceFund.vault,
4080
+ driftSigner: this.getSignerPublicKey(),
4081
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
4082
+ },
4083
+ remainingAccounts: remainingAccounts,
4084
+ });
4085
+ }
4086
+ async getDepositIntoSpotMarketRevenuePoolIx(marketIndex, amount, userTokenAccountPublicKey) {
4087
+ const spotMarket = await this.getSpotMarketAccount(marketIndex);
4088
+ const remainingAccounts = [];
4089
+ this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
4090
+ const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
4091
+ const ix = await this.program.instruction.depositIntoSpotMarketRevenuePool(amount, {
4092
+ accounts: {
4093
+ state: await this.getStatePublicKey(),
4094
+ spotMarket: spotMarket.pubkey,
4095
+ authority: this.wallet.publicKey,
4096
+ spotMarketVault: spotMarket.vault,
4097
+ userTokenAccount: userTokenAccountPublicKey,
4098
+ tokenProgram,
4099
+ },
4100
+ });
4101
+ return ix;
4102
+ }
4103
+ async depositIntoSpotMarketRevenuePool(marketIndex, amount, userTokenAccountPublicKey) {
4104
+ const ix = await this.getDepositIntoSpotMarketRevenuePoolIx(marketIndex, amount, userTokenAccountPublicKey);
4105
+ const tx = await this.buildTransaction([ix]);
4106
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
4107
+ return txSig;
4108
+ }
4109
+ getPerpMarketExtendedInfo(marketIndex) {
4110
+ var _a, _b;
4111
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
4112
+ const quoteAccount = this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
4113
+ const extendedInfo = {
4114
+ marketIndex,
4115
+ minOrderSize: (_a = marketAccount.amm) === null || _a === void 0 ? void 0 : _a.minOrderSize,
4116
+ marginMaintenance: marketAccount.marginRatioMaintenance,
4117
+ pnlPoolValue: (0, spotBalance_1.getTokenAmount)((_b = marketAccount.pnlPool) === null || _b === void 0 ? void 0 : _b.scaledBalance, quoteAccount, types_1.SpotBalanceType.DEPOSIT),
4118
+ contractTier: marketAccount.contractTier,
4119
+ availableInsurance: (0, market_1.calculateMarketMaxAvailableInsurance)(marketAccount, quoteAccount),
4120
+ };
4121
+ return extendedInfo;
4122
+ }
4123
+ /**
4124
+ * Calculates taker / maker fee (as a percentage, e.g. .001 = 10 basis points) for particular marketType
4125
+ * @param marketType
4126
+ * @param positionMarketIndex
4127
+ * @returns : {takerFee: number, makerFee: number} Precision None
4128
+ */
4129
+ getMarketFees(marketType, marketIndex, user) {
4130
+ let feeTier;
4131
+ if (user) {
4132
+ feeTier = user.getUserFeeTier(marketType);
4133
+ }
4134
+ else {
4135
+ const state = this.getStateAccount();
4136
+ feeTier = (0, types_1.isVariant)(marketType, 'perp')
4137
+ ? state.perpFeeStructure.feeTiers[0]
4138
+ : state.spotFeeStructure.feeTiers[0];
4139
+ }
4140
+ let takerFee = feeTier.feeNumerator / feeTier.feeDenominator;
4141
+ let makerFee = feeTier.makerRebateNumerator / feeTier.makerRebateDenominator;
4142
+ if (marketIndex !== undefined) {
4143
+ let marketAccount = null;
4144
+ if ((0, types_1.isVariant)(marketType, 'perp')) {
4145
+ marketAccount = this.getPerpMarketAccount(marketIndex);
4146
+ }
4147
+ else {
4148
+ marketAccount = this.getSpotMarketAccount(marketIndex);
4149
+ }
4150
+ takerFee += (takerFee * marketAccount.feeAdjustment) / 100;
4151
+ makerFee += (makerFee * marketAccount.feeAdjustment) / 100;
4152
+ }
4153
+ return {
4154
+ takerFee,
4155
+ makerFee,
4156
+ };
4157
+ }
4158
+ /**
4159
+ * Returns the market index and type for a given market name
4160
+ * E.g. "SOL-PERP" -> { marketIndex: 0, marketType: MarketType.PERP }
4161
+ *
4162
+ * @param name
4163
+ */
4164
+ getMarketIndexAndType(name) {
4165
+ name = name.toUpperCase();
4166
+ for (const perpMarketAccount of this.getPerpMarketAccounts()) {
4167
+ if ((0, userName_1.decodeName)(perpMarketAccount.name).toUpperCase() === name) {
4168
+ return {
4169
+ marketIndex: perpMarketAccount.marketIndex,
4170
+ marketType: types_1.MarketType.PERP,
4171
+ };
4172
+ }
4173
+ }
4174
+ for (const spotMarketAccount of this.getSpotMarketAccounts()) {
4175
+ if ((0, userName_1.decodeName)(spotMarketAccount.name).toUpperCase() === name) {
4176
+ return {
4177
+ marketIndex: spotMarketAccount.marketIndex,
4178
+ marketType: types_1.MarketType.SPOT,
4179
+ };
4180
+ }
4181
+ }
4182
+ return undefined;
4183
+ }
4184
+ getReceiverProgram() {
4185
+ if (this.receiverProgram === undefined) {
4186
+ this.receiverProgram = new anchor_1.Program(pyth_solana_receiver_json_1.default, pyth_solana_receiver_1.DEFAULT_RECEIVER_PROGRAM_ID, this.provider);
4187
+ }
4188
+ return this.receiverProgram;
4189
+ }
4190
+ async getSwitchboardOnDemandProgram() {
4191
+ const idl = (await anchor_30_1.Program.fetchIdl(this.sbOnDemandProgramdId, this.provider));
4192
+ if (this.sbOnDemandProgram === undefined) {
4193
+ this.sbOnDemandProgram = new anchor_30_1.Program(idl, this.provider);
4194
+ }
4195
+ return this.sbOnDemandProgram;
4196
+ }
4197
+ async postPythPullOracleUpdateAtomic(vaaString, feedId) {
4198
+ const postIxs = await this.getPostPythPullOracleUpdateAtomicIxs(vaaString, feedId);
4199
+ const tx = await this.buildTransaction(postIxs);
4200
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
4201
+ return txSig;
4202
+ }
4203
+ async postMultiPythPullOracleUpdatesAtomic(vaaString, feedIds) {
4204
+ const postIxs = await this.getPostPythPullOracleUpdateAtomicIxs(vaaString, feedIds);
4205
+ const tx = await this.buildTransaction(postIxs);
4206
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
4207
+ return txSig;
4208
+ }
4209
+ async getPostPythPullOracleUpdateAtomicIxs(vaaString, feedIds, numSignatures = 2) {
4210
+ const accumulatorUpdateData = (0, price_service_sdk_1.parseAccumulatorUpdateData)(Buffer.from(vaaString, 'base64'));
4211
+ const guardianSetIndex = accumulatorUpdateData.vaa.readUInt32BE(1);
4212
+ const guardianSet = (0, address_1.getGuardianSetPda)(guardianSetIndex, address_1.DEFAULT_WORMHOLE_PROGRAM_ID);
4213
+ const trimmedVaa = (0, oracles_1.trimVaaSignatures)(accumulatorUpdateData.vaa, numSignatures);
4214
+ const postIxs = [];
4215
+ if (accumulatorUpdateData.updates.length > 1) {
4216
+ const encodedParams = this.getReceiverProgram().coder.types.encode('PostMultiUpdatesAtomicParams', {
4217
+ vaa: trimmedVaa,
4218
+ merklePriceUpdates: accumulatorUpdateData.updates,
4219
+ });
4220
+ const feedIdsToUse = typeof feedIds === 'string' ? [feedIds] : feedIds;
4221
+ const pubkeys = feedIdsToUse.map((feedId) => {
4222
+ return (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, (0, pythPullOracleUtils_1.getFeedIdUint8Array)(feedId));
4223
+ });
4224
+ const remainingAccounts = pubkeys.map((pubkey) => {
4225
+ return {
4226
+ pubkey,
4227
+ isSigner: false,
4228
+ isWritable: true,
4229
+ };
4230
+ });
4231
+ postIxs.push(this.program.instruction.postMultiPythPullOracleUpdatesAtomic(encodedParams, {
4232
+ accounts: {
4233
+ keeper: this.wallet.publicKey,
4234
+ pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
4235
+ guardianSet,
4236
+ },
4237
+ remainingAccounts,
4238
+ }));
4239
+ }
4240
+ else {
4241
+ let feedIdToUse = typeof feedIds === 'string' ? feedIds : feedIds[0];
4242
+ feedIdToUse = (0, pythPullOracleUtils_1.trimFeedId)(feedIdToUse);
4243
+ postIxs.push(await this.getSinglePostPythPullOracleAtomicIx({
4244
+ vaa: trimmedVaa,
4245
+ merklePriceUpdate: accumulatorUpdateData.updates[0],
4246
+ }, feedIdToUse, guardianSet));
4247
+ }
4248
+ return postIxs;
4249
+ }
4250
+ async getSinglePostPythPullOracleAtomicIx(params, feedId, guardianSet) {
4251
+ const feedIdBuffer = (0, pythPullOracleUtils_1.getFeedIdUint8Array)(feedId);
4252
+ const receiverProgram = this.getReceiverProgram();
4253
+ const encodedParams = receiverProgram.coder.types.encode('PostUpdateAtomicParams', params);
4254
+ return this.program.instruction.postPythPullOracleUpdateAtomic(feedIdBuffer, encodedParams, {
4255
+ accounts: {
4256
+ keeper: this.wallet.publicKey,
4257
+ pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
4258
+ guardianSet,
4259
+ priceFeed: (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, feedIdBuffer),
4260
+ },
4261
+ });
4262
+ }
4263
+ async updatePythPullOracle(vaaString, feedId) {
4264
+ feedId = (0, pythPullOracleUtils_1.trimFeedId)(feedId);
4265
+ const accumulatorUpdateData = (0, price_service_sdk_1.parseAccumulatorUpdateData)(Buffer.from(vaaString, 'base64'));
4266
+ const guardianSetIndex = accumulatorUpdateData.vaa.readUInt32BE(1);
4267
+ const guardianSet = (0, address_1.getGuardianSetPda)(guardianSetIndex, address_1.DEFAULT_WORMHOLE_PROGRAM_ID);
4268
+ const [postIxs, encodedVaaAddress] = await this.getBuildEncodedVaaIxs(accumulatorUpdateData.vaa, guardianSet);
4269
+ for (const update of accumulatorUpdateData.updates) {
4270
+ postIxs.push(await this.getUpdatePythPullOracleIxs({
4271
+ merklePriceUpdate: update,
4272
+ }, feedId, encodedVaaAddress.publicKey));
4273
+ }
4274
+ const tx = await this.buildTransaction(postIxs);
4275
+ const { txSig } = await this.sendTransaction(tx, [encodedVaaAddress], this.opts);
4276
+ return txSig;
4277
+ }
4278
+ async getUpdatePythPullOracleIxs(params, feedId, encodedVaaAddress) {
4279
+ const feedIdBuffer = (0, pythPullOracleUtils_1.getFeedIdUint8Array)(feedId);
4280
+ const receiverProgram = this.getReceiverProgram();
4281
+ const encodedParams = receiverProgram.coder.types.encode('PostUpdateParams', params);
4282
+ return this.program.instruction.updatePythPullOracle(feedIdBuffer, encodedParams, {
4283
+ accounts: {
4284
+ keeper: this.wallet.publicKey,
4285
+ pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
4286
+ encodedVaa: encodedVaaAddress,
4287
+ priceFeed: (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, feedIdBuffer),
4288
+ },
4289
+ });
4290
+ }
4291
+ async getPostSwitchboardOnDemandUpdateAtomicIx(feed, numSignatures = 3) {
4292
+ const program = await this.getSwitchboardOnDemandProgram();
4293
+ const feedAccount = new on_demand_1.PullFeed(program, feed);
4294
+ if (!this.sbProgramFeedConfigs) {
4295
+ this.sbProgramFeedConfigs = new Map();
4296
+ }
4297
+ if (!this.sbProgramFeedConfigs.has(feedAccount.pubkey.toString())) {
4298
+ const feedConfig = await feedAccount.loadConfigs();
4299
+ this.sbProgramFeedConfigs.set(feed.toString(), feedConfig);
4300
+ }
4301
+ const [pullIx, _responses, success] = await feedAccount.fetchUpdateIx({
4302
+ numSignatures,
4303
+ });
4304
+ if (!success) {
4305
+ return undefined;
4306
+ }
4307
+ return pullIx;
4308
+ }
4309
+ async postSwitchboardOnDemandUpdate(feed, numSignatures = 3) {
4310
+ const pullIx = await this.getPostSwitchboardOnDemandUpdateAtomicIx(feed, numSignatures);
4311
+ if (!pullIx) {
4312
+ return undefined;
4313
+ }
4314
+ const tx = await (0, on_demand_1.asV0Tx)({
4315
+ connection: this.connection,
4316
+ ixs: [pullIx],
4317
+ payer: this.wallet.publicKey,
4318
+ computeUnitLimitMultiple: 1.3,
4319
+ lookupTables: [await this.fetchMarketLookupTableAccount()],
4320
+ });
4321
+ const { txSig } = await this.sendTransaction(tx, [], {
4322
+ commitment: 'processed',
4323
+ skipPreflight: true,
4324
+ maxRetries: 0,
4325
+ });
4326
+ return txSig;
4327
+ }
4328
+ async getBuildEncodedVaaIxs(vaa, guardianSet) {
4329
+ const postIxs = [];
4330
+ if (this.wormholeProgram === undefined) {
4331
+ this.wormholeProgram = new anchor_1.Program(pyth_solana_receiver_1.wormholeCoreBridgeIdl, address_1.DEFAULT_WORMHOLE_PROGRAM_ID, this.provider);
4332
+ }
4333
+ const encodedVaaKeypair = new web3_js_1.Keypair();
4334
+ postIxs.push(await this.wormholeProgram.account.encodedVaa.createInstruction(encodedVaaKeypair, vaa.length + 46));
4335
+ // Why do we need this too?
4336
+ postIxs.push(await this.wormholeProgram.methods
4337
+ .initEncodedVaa()
4338
+ .accounts({
4339
+ encodedVaa: encodedVaaKeypair.publicKey,
4340
+ })
4341
+ .instruction());
4342
+ // Split the write into two ixs
4343
+ postIxs.push(await this.wormholeProgram.methods
4344
+ .writeEncodedVaa({
4345
+ index: 0,
4346
+ data: vaa.subarray(0, 755),
4347
+ })
4348
+ .accounts({
4349
+ draftVaa: encodedVaaKeypair.publicKey,
4350
+ })
4351
+ .instruction());
4352
+ postIxs.push(await this.wormholeProgram.methods
4353
+ .writeEncodedVaa({
4354
+ index: 755,
4355
+ data: vaa.subarray(755),
4356
+ })
4357
+ .accounts({
4358
+ draftVaa: encodedVaaKeypair.publicKey,
4359
+ })
4360
+ .instruction());
4361
+ // Verify
4362
+ postIxs.push(await this.wormholeProgram.methods
4363
+ .verifyEncodedVaaV1()
4364
+ .accounts({
4365
+ guardianSet,
4366
+ draftVaa: encodedVaaKeypair.publicKey,
4367
+ })
4368
+ .instruction());
4369
+ return [postIxs, encodedVaaKeypair];
4370
+ }
4371
+ async enableUserHighLeverageMode(subAccountId, txParams) {
4372
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getEnableHighLeverageModeIx(subAccountId), txParams), [], this.opts);
4373
+ return txSig;
4374
+ }
4375
+ async getEnableHighLeverageModeIx(subAccountId) {
4376
+ const remainingAccounts = this.getRemainingAccounts({
4377
+ userAccounts: [this.getUserAccount(subAccountId)],
4378
+ });
4379
+ const ix = await this.program.instruction.enableUserHighLeverageMode(subAccountId, {
4380
+ accounts: {
4381
+ state: await this.getStatePublicKey(),
4382
+ user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
4383
+ authority: this.wallet.publicKey,
4384
+ highLeverageModeConfig: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
4385
+ },
4386
+ remainingAccounts,
4387
+ });
4388
+ return ix;
4389
+ }
4390
+ async disableUserHighLeverageMode(user, userAccount, txParams) {
4391
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getDisableHighLeverageModeIx(user, userAccount), txParams), [], this.opts);
4392
+ return txSig;
4393
+ }
4394
+ async getDisableHighLeverageModeIx(user, userAccount) {
4395
+ const remainingAccounts = userAccount
4396
+ ? this.getRemainingAccounts({
4397
+ userAccounts: [userAccount],
4398
+ })
4399
+ : undefined;
4400
+ const ix = await this.program.instruction.disableUserHighLeverageMode({
4401
+ accounts: {
4402
+ state: await this.getStatePublicKey(),
4403
+ user,
4404
+ authority: this.wallet.publicKey,
4405
+ highLeverageModeConfig: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
4406
+ },
4407
+ remainingAccounts,
4408
+ });
4409
+ return ix;
4410
+ }
4411
+ async fetchHighLeverageModeConfig() {
4412
+ const config = await this.program.account.highLeverageModeConfig.fetch((0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId));
4413
+ return config;
4414
+ }
4415
+ handleSignedTransaction(signedTxs) {
4416
+ if (this.enableMetricsEvents && this.metricsEventEmitter) {
4417
+ this.metricsEventEmitter.emit('txSigned', signedTxs);
4418
+ }
4419
+ }
4420
+ handlePreSignedTransaction() {
4421
+ if (this.enableMetricsEvents && this.metricsEventEmitter) {
4422
+ this.metricsEventEmitter.emit('preTxSigned');
4423
+ }
4424
+ }
4425
+ isVersionedTransaction(tx) {
4426
+ return (0, utils_2.isVersionedTransaction)(tx);
4427
+ }
4428
+ /**
4429
+ * Send a transaction.
4430
+ *
4431
+ * @param tx
4432
+ * @param additionalSigners
4433
+ * @param opts :: Will fallback to DriftClient's opts if not provided
4434
+ * @param preSigned
4435
+ * @returns
4436
+ */
4437
+ sendTransaction(tx, additionalSigners, opts, preSigned) {
4438
+ const isVersionedTx = this.isVersionedTransaction(tx);
4439
+ if (isVersionedTx) {
4440
+ return this.txSender.sendVersionedTransaction(tx, additionalSigners, opts !== null && opts !== void 0 ? opts : this.opts, preSigned);
4441
+ }
4442
+ else {
4443
+ return this.txSender.send(tx, additionalSigners, opts !== null && opts !== void 0 ? opts : this.opts, preSigned);
4444
+ }
4445
+ }
4446
+ async buildTransaction(instructions, txParams, txVersion, lookupTables, forceVersionedTransaction, recentBlockhash) {
4447
+ return this.txHandler.buildTransaction({
4448
+ instructions,
4449
+ txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
4450
+ txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
4451
+ connection: this.connection,
4452
+ preFlightCommitment: this.opts.preflightCommitment,
4453
+ fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
4454
+ lookupTables,
4455
+ forceVersionedTransaction,
4456
+ recentBlockhash,
4457
+ });
4458
+ }
4459
+ async buildBulkTransactions(instructions, txParams, txVersion, lookupTables, forceVersionedTransaction) {
4460
+ return this.txHandler.buildBulkTransactions({
4461
+ instructions,
4462
+ txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
4463
+ txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
4464
+ connection: this.connection,
4465
+ preFlightCommitment: this.opts.preflightCommitment,
4466
+ fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
4467
+ lookupTables,
4468
+ forceVersionedTransaction,
4469
+ });
4470
+ }
4471
+ async buildTransactionsMap(instructionsMap, txParams, txVersion, lookupTables, forceVersionedTransaction) {
4472
+ return this.txHandler.buildTransactionsMap({
4473
+ instructionsMap,
4474
+ txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
4475
+ txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
4476
+ connection: this.connection,
4477
+ preFlightCommitment: this.opts.preflightCommitment,
4478
+ fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
4479
+ lookupTables,
4480
+ forceVersionedTransaction,
4481
+ });
4482
+ }
4483
+ async buildAndSignTransactionsMap(instructionsMap, txParams, txVersion, lookupTables, forceVersionedTransaction) {
4484
+ return this.txHandler.buildAndSignTransactionMap({
4485
+ instructionsMap,
4486
+ txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
4487
+ txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
4488
+ connection: this.connection,
4489
+ preFlightCommitment: this.opts.preflightCommitment,
4490
+ fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
4491
+ lookupTables,
4492
+ forceVersionedTransaction,
4493
+ });
4494
+ }
4495
+ }
4496
+ exports.DriftClient = DriftClient;