@drift-labs/common 1.0.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 (400) hide show
  1. package/lib/Config.d.ts +26 -0
  2. package/lib/Config.js +29 -0
  3. package/lib/Config.js.map +1 -0
  4. package/lib/EnvironmentConstants.d.ts +40 -0
  5. package/lib/EnvironmentConstants.js +64 -0
  6. package/lib/EnvironmentConstants.js.map +1 -0
  7. package/lib/actions/actionHelpers/accountDeletionHelpers.d.ts +16 -0
  8. package/lib/actions/actionHelpers/accountDeletionHelpers.js +151 -0
  9. package/lib/actions/actionHelpers/accountDeletionHelpers.js.map +1 -0
  10. package/lib/actions/actionHelpers/actionHelpers.d.ts +13 -0
  11. package/lib/actions/actionHelpers/actionHelpers.js +8 -0
  12. package/lib/actions/actionHelpers/actionHelpers.js.map +1 -0
  13. package/lib/chartConstants.d.ts +2 -0
  14. package/lib/chartConstants.js +14 -0
  15. package/lib/chartConstants.js.map +1 -0
  16. package/lib/clients/candleClient.d.ts +74 -0
  17. package/lib/clients/candleClient.js +364 -0
  18. package/lib/clients/candleClient.js.map +1 -0
  19. package/lib/clients/dataApiWsClient.d.ts +33 -0
  20. package/lib/clients/dataApiWsClient.js +118 -0
  21. package/lib/clients/dataApiWsClient.js.map +1 -0
  22. package/lib/clients/index.d.ts +1 -0
  23. package/lib/clients/index.js +19 -0
  24. package/lib/clients/index.js.map +1 -0
  25. package/lib/clients/marketDataFeed.d.ts +42 -0
  26. package/lib/clients/marketDataFeed.js +422 -0
  27. package/lib/clients/marketDataFeed.js.map +1 -0
  28. package/lib/clients/redisClient.d.ts +89 -0
  29. package/lib/clients/redisClient.js +647 -0
  30. package/lib/clients/redisClient.js.map +1 -0
  31. package/lib/clients/swiftClient.d.ts +57 -0
  32. package/lib/clients/swiftClient.js +289 -0
  33. package/lib/clients/swiftClient.js.map +1 -0
  34. package/lib/clients/tvFeed.d.ts +63 -0
  35. package/lib/clients/tvFeed.js +351 -0
  36. package/lib/clients/tvFeed.js.map +1 -0
  37. package/lib/common-ui-utils/commonUiUtils.d.ts +211 -0
  38. package/lib/common-ui-utils/commonUiUtils.js +624 -0
  39. package/lib/common-ui-utils/commonUiUtils.js.map +1 -0
  40. package/lib/common-ui-utils/index.d.ts +6 -0
  41. package/lib/common-ui-utils/index.js +23 -0
  42. package/lib/common-ui-utils/index.js.map +1 -0
  43. package/lib/common-ui-utils/market.d.ts +27 -0
  44. package/lib/common-ui-utils/market.js +80 -0
  45. package/lib/common-ui-utils/market.js.map +1 -0
  46. package/lib/common-ui-utils/order.d.ts +11 -0
  47. package/lib/common-ui-utils/order.js +161 -0
  48. package/lib/common-ui-utils/order.js.map +1 -0
  49. package/lib/common-ui-utils/settings/settings.d.ts +51 -0
  50. package/lib/common-ui-utils/settings/settings.js +84 -0
  51. package/lib/common-ui-utils/settings/settings.js.map +1 -0
  52. package/lib/common-ui-utils/trading.d.ts +56 -0
  53. package/lib/common-ui-utils/trading.js +200 -0
  54. package/lib/common-ui-utils/trading.js.map +1 -0
  55. package/lib/common-ui-utils/user.d.ts +13 -0
  56. package/lib/common-ui-utils/user.js +124 -0
  57. package/lib/common-ui-utils/user.js.map +1 -0
  58. package/lib/constants/autogenerated/driftErrors.json +1787 -0
  59. package/lib/constants/autogenerated/jup-v4-error-codes.json +67 -0
  60. package/lib/constants/autogenerated/jup-v6-error-codes.json +115 -0
  61. package/lib/constants/dev.d.ts +15 -0
  62. package/lib/constants/dev.js +19 -0
  63. package/lib/constants/dev.js.map +1 -0
  64. package/lib/constants/geoblockList.d.ts +4 -0
  65. package/lib/constants/geoblockList.js +32 -0
  66. package/lib/constants/geoblockList.js.map +1 -0
  67. package/lib/constants/index.d.ts +9 -0
  68. package/lib/constants/index.js +26 -0
  69. package/lib/constants/index.js.map +1 -0
  70. package/lib/constants/markets.d.ts +1 -0
  71. package/lib/constants/markets.js +5 -0
  72. package/lib/constants/markets.js.map +1 -0
  73. package/lib/constants/misc.d.ts +23 -0
  74. package/lib/constants/misc.js +27 -0
  75. package/lib/constants/misc.js.map +1 -0
  76. package/lib/constants/orders.d.ts +12 -0
  77. package/lib/constants/orders.js +79 -0
  78. package/lib/constants/orders.js.map +1 -0
  79. package/lib/constants/pools.d.ts +5 -0
  80. package/lib/constants/pools.js +9 -0
  81. package/lib/constants/pools.js.map +1 -0
  82. package/lib/constants/predictionMarket.d.ts +3 -0
  83. package/lib/constants/predictionMarket.js +7 -0
  84. package/lib/constants/predictionMarket.js.map +1 -0
  85. package/lib/constants/superstake.d.ts +22 -0
  86. package/lib/constants/superstake.js +45 -0
  87. package/lib/constants/superstake.js.map +1 -0
  88. package/lib/constants/trade.d.ts +2 -0
  89. package/lib/constants/trade.js +9 -0
  90. package/lib/constants/trade.js.map +1 -0
  91. package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +68 -0
  92. package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js +146 -0
  93. package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js.map +1 -0
  94. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +204 -0
  95. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +530 -0
  96. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -0
  97. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +90 -0
  98. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js +3 -0
  99. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -0
  100. package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.d.ts +139 -0
  101. package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.js +287 -0
  102. package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.js.map +1 -0
  103. package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +242 -0
  104. package/lib/drift/Drift/clients/AuthorityDrift/index.js +503 -0
  105. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -0
  106. package/lib/drift/Drift/clients/CentralServerDrift.d.ts +91 -0
  107. package/lib/drift/Drift/clients/CentralServerDrift.js +326 -0
  108. package/lib/drift/Drift/clients/CentralServerDrift.js.map +1 -0
  109. package/lib/drift/Drift/clients/index.d.ts +3 -0
  110. package/lib/drift/Drift/clients/index.js +20 -0
  111. package/lib/drift/Drift/clients/index.js.map +1 -0
  112. package/lib/drift/Drift/constants/blockchain.d.ts +24 -0
  113. package/lib/drift/Drift/constants/blockchain.js +32 -0
  114. package/lib/drift/Drift/constants/blockchain.js.map +1 -0
  115. package/lib/drift/Drift/constants/errors.d.ts +6 -0
  116. package/lib/drift/Drift/constants/errors.js +14 -0
  117. package/lib/drift/Drift/constants/errors.js.map +1 -0
  118. package/lib/drift/Drift/constants/index.d.ts +3 -0
  119. package/lib/drift/Drift/constants/index.js +20 -0
  120. package/lib/drift/Drift/constants/index.js.map +1 -0
  121. package/lib/drift/Drift/constants/orderbook.d.ts +7 -0
  122. package/lib/drift/Drift/constants/orderbook.js +10 -0
  123. package/lib/drift/Drift/constants/orderbook.js.map +1 -0
  124. package/lib/drift/Drift/data/PollingDlob.d.ts +154 -0
  125. package/lib/drift/Drift/data/PollingDlob.js +387 -0
  126. package/lib/drift/Drift/data/PollingDlob.js.map +1 -0
  127. package/lib/drift/Drift/data/index.d.ts +1 -0
  128. package/lib/drift/Drift/data/index.js +18 -0
  129. package/lib/drift/Drift/data/index.js.map +1 -0
  130. package/lib/drift/Drift/index.d.ts +4 -0
  131. package/lib/drift/Drift/index.js +21 -0
  132. package/lib/drift/Drift/index.js.map +1 -0
  133. package/lib/drift/Drift/stores/MarkPriceCache.d.ts +27 -0
  134. package/lib/drift/Drift/stores/MarkPriceCache.js +59 -0
  135. package/lib/drift/Drift/stores/MarkPriceCache.js.map +1 -0
  136. package/lib/drift/Drift/stores/OraclePriceCache.d.ts +21 -0
  137. package/lib/drift/Drift/stores/OraclePriceCache.js +57 -0
  138. package/lib/drift/Drift/stores/OraclePriceCache.js.map +1 -0
  139. package/lib/drift/Drift/stores/UserAccountCache.d.ts +49 -0
  140. package/lib/drift/Drift/stores/UserAccountCache.js +107 -0
  141. package/lib/drift/Drift/stores/UserAccountCache.js.map +1 -0
  142. package/lib/drift/Drift/stores/index.d.ts +3 -0
  143. package/lib/drift/Drift/stores/index.js +20 -0
  144. package/lib/drift/Drift/stores/index.js.map +1 -0
  145. package/lib/drift/base/actions/index.d.ts +4 -0
  146. package/lib/drift/base/actions/index.js +21 -0
  147. package/lib/drift/base/actions/index.js.map +1 -0
  148. package/lib/drift/base/actions/perp/index.d.ts +2 -0
  149. package/lib/drift/base/actions/perp/index.js +19 -0
  150. package/lib/drift/base/actions/perp/index.js.map +1 -0
  151. package/lib/drift/base/actions/perp/settleFunding.d.ts +25 -0
  152. package/lib/drift/base/actions/perp/settleFunding.js +41 -0
  153. package/lib/drift/base/actions/perp/settleFunding.js.map +1 -0
  154. package/lib/drift/base/actions/perp/settlePnl.d.ts +35 -0
  155. package/lib/drift/base/actions/perp/settlePnl.js +44 -0
  156. package/lib/drift/base/actions/perp/settlePnl.js.map +1 -0
  157. package/lib/drift/base/actions/spot/borrow.d.ts +1 -0
  158. package/lib/drift/base/actions/spot/borrow.js +8 -0
  159. package/lib/drift/base/actions/spot/borrow.js.map +1 -0
  160. package/lib/drift/base/actions/spot/deposit.d.ts +40 -0
  161. package/lib/drift/base/actions/spot/deposit.js +82 -0
  162. package/lib/drift/base/actions/spot/deposit.js.map +1 -0
  163. package/lib/drift/base/actions/spot/index.d.ts +3 -0
  164. package/lib/drift/base/actions/spot/index.js +20 -0
  165. package/lib/drift/base/actions/spot/index.js.map +1 -0
  166. package/lib/drift/base/actions/spot/withdraw.d.ts +16 -0
  167. package/lib/drift/base/actions/spot/withdraw.js +39 -0
  168. package/lib/drift/base/actions/spot/withdraw.js.map +1 -0
  169. package/lib/drift/base/actions/trade/cancelOrder.d.ts +47 -0
  170. package/lib/drift/base/actions/trade/cancelOrder.js +55 -0
  171. package/lib/drift/base/actions/trade/cancelOrder.js.map +1 -0
  172. package/lib/drift/base/actions/trade/editOrder.d.ts +55 -0
  173. package/lib/drift/base/actions/trade/editOrder.js +35 -0
  174. package/lib/drift/base/actions/trade/editOrder.js.map +1 -0
  175. package/lib/drift/base/actions/trade/index.d.ts +4 -0
  176. package/lib/drift/base/actions/trade/index.js +21 -0
  177. package/lib/drift/base/actions/trade/index.js.map +1 -0
  178. package/lib/drift/base/actions/trade/openPerpOrder/index.d.ts +3 -0
  179. package/lib/drift/base/actions/trade/openPerpOrder/index.js +20 -0
  180. package/lib/drift/base/actions/trade/openPerpOrder/index.js.map +1 -0
  181. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +84 -0
  182. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +293 -0
  183. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -0
  184. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +19 -0
  185. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +161 -0
  186. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -0
  187. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +166 -0
  188. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +156 -0
  189. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -0
  190. package/lib/drift/base/actions/trade/swap.d.ts +62 -0
  191. package/lib/drift/base/actions/trade/swap.js +60 -0
  192. package/lib/drift/base/actions/trade/swap.js.map +1 -0
  193. package/lib/drift/base/actions/user/create.d.ts +75 -0
  194. package/lib/drift/base/actions/user/create.js +104 -0
  195. package/lib/drift/base/actions/user/create.js.map +1 -0
  196. package/lib/drift/base/actions/user/delete.d.ts +47 -0
  197. package/lib/drift/base/actions/user/delete.js +39 -0
  198. package/lib/drift/base/actions/user/delete.js.map +1 -0
  199. package/lib/drift/base/actions/user/index.d.ts +1 -0
  200. package/lib/drift/base/actions/user/index.js +18 -0
  201. package/lib/drift/base/actions/user/index.js.map +1 -0
  202. package/lib/drift/base/constants/accountNames.d.ts +1 -0
  203. package/lib/drift/base/constants/accountNames.js +13 -0
  204. package/lib/drift/base/constants/accountNames.js.map +1 -0
  205. package/lib/drift/base/details/index.d.ts +2 -0
  206. package/lib/drift/base/details/index.js +19 -0
  207. package/lib/drift/base/details/index.js.map +1 -0
  208. package/lib/drift/base/details/market/funding.d.ts +9 -0
  209. package/lib/drift/base/details/market/funding.js +50 -0
  210. package/lib/drift/base/details/market/funding.js.map +1 -0
  211. package/lib/drift/base/details/market/index.d.ts +2 -0
  212. package/lib/drift/base/details/market/index.js +19 -0
  213. package/lib/drift/base/details/market/index.js.map +1 -0
  214. package/lib/drift/base/details/market/openInterest.d.ts +5 -0
  215. package/lib/drift/base/details/market/openInterest.js +12 -0
  216. package/lib/drift/base/details/market/openInterest.js.map +1 -0
  217. package/lib/drift/base/details/user/balances.d.ts +40 -0
  218. package/lib/drift/base/details/user/balances.js +39 -0
  219. package/lib/drift/base/details/user/balances.js.map +1 -0
  220. package/lib/drift/base/details/user/index.d.ts +4 -0
  221. package/lib/drift/base/details/user/index.js +21 -0
  222. package/lib/drift/base/details/user/index.js.map +1 -0
  223. package/lib/drift/base/details/user/marginInfo.d.ts +29 -0
  224. package/lib/drift/base/details/user/marginInfo.js +49 -0
  225. package/lib/drift/base/details/user/marginInfo.js.map +1 -0
  226. package/lib/drift/base/details/user/orders.d.ts +3 -0
  227. package/lib/drift/base/details/user/orders.js +11 -0
  228. package/lib/drift/base/details/user/orders.js.map +1 -0
  229. package/lib/drift/base/details/user/positions.d.ts +70 -0
  230. package/lib/drift/base/details/user/positions.js +146 -0
  231. package/lib/drift/base/details/user/positions.js.map +1 -0
  232. package/lib/drift/cli.d.ts +25 -0
  233. package/lib/drift/cli.js +900 -0
  234. package/lib/drift/cli.js.map +1 -0
  235. package/lib/drift/constants/apiUrls.d.ts +27 -0
  236. package/lib/drift/constants/apiUrls.js +31 -0
  237. package/lib/drift/constants/apiUrls.js.map +1 -0
  238. package/lib/drift/example.d.ts +19 -0
  239. package/lib/drift/example.js +249 -0
  240. package/lib/drift/example.js.map +1 -0
  241. package/lib/drift/index.d.ts +3 -0
  242. package/lib/drift/index.js +20 -0
  243. package/lib/drift/index.js.map +1 -0
  244. package/lib/drift/utils/auctionParamsResponseMapper.d.ts +45 -0
  245. package/lib/drift/utils/auctionParamsResponseMapper.js +148 -0
  246. package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -0
  247. package/lib/drift/utils/funding.d.ts +2 -0
  248. package/lib/drift/utils/funding.js +9 -0
  249. package/lib/drift/utils/funding.js.map +1 -0
  250. package/lib/drift/utils/index.d.ts +3 -0
  251. package/lib/drift/utils/index.js +23 -0
  252. package/lib/drift/utils/index.js.map +1 -0
  253. package/lib/drift/utils/orderParams.d.ts +48 -0
  254. package/lib/drift/utils/orderParams.js +140 -0
  255. package/lib/drift/utils/orderParams.js.map +1 -0
  256. package/lib/index.d.ts +45 -0
  257. package/lib/index.js +68 -0
  258. package/lib/index.js.map +1 -0
  259. package/lib/serializableTypes.d.ts +961 -0
  260. package/lib/serializableTypes.js +3887 -0
  261. package/lib/serializableTypes.js.map +1 -0
  262. package/lib/types/MarketId.d.ts +26 -0
  263. package/lib/types/MarketId.js +64 -0
  264. package/lib/types/MarketId.js.map +1 -0
  265. package/lib/types/Superstake.d.ts +7 -0
  266. package/lib/types/Superstake.js +3 -0
  267. package/lib/types/Superstake.js.map +1 -0
  268. package/lib/types/UIEnv.d.ts +26 -0
  269. package/lib/types/UIEnv.js +49 -0
  270. package/lib/types/UIEnv.js.map +1 -0
  271. package/lib/types/UIMarket.d.ts +94 -0
  272. package/lib/types/UIMarket.js +224 -0
  273. package/lib/types/UIMarket.js.map +1 -0
  274. package/lib/types/candles.d.ts +4 -0
  275. package/lib/types/candles.js +9 -0
  276. package/lib/types/candles.js.map +1 -0
  277. package/lib/types/dataServer.d.ts +53 -0
  278. package/lib/types/dataServer.js +3 -0
  279. package/lib/types/dataServer.js.map +1 -0
  280. package/lib/types/historyServer.d.ts +38 -0
  281. package/lib/types/historyServer.js +11 -0
  282. package/lib/types/historyServer.js.map +1 -0
  283. package/lib/types/index.d.ts +12 -0
  284. package/lib/types/index.js +29 -0
  285. package/lib/types/index.js.map +1 -0
  286. package/lib/types/leaderboard.d.ts +80 -0
  287. package/lib/types/leaderboard.js +11 -0
  288. package/lib/types/leaderboard.js.map +1 -0
  289. package/lib/types/remote-configs.d.ts +61 -0
  290. package/lib/types/remote-configs.js +3 -0
  291. package/lib/types/remote-configs.js.map +1 -0
  292. package/lib/types/trade.d.ts +18 -0
  293. package/lib/types/trade.js +3 -0
  294. package/lib/types/trade.js.map +1 -0
  295. package/lib/types/user.d.ts +40 -0
  296. package/lib/types/user.js +3 -0
  297. package/lib/types/user.js.map +1 -0
  298. package/lib/types/utility.d.ts +15 -0
  299. package/lib/types/utility.js +3 -0
  300. package/lib/types/utility.js.map +1 -0
  301. package/lib/utils/CircularBuffers/CircularBuffer.d.ts +22 -0
  302. package/lib/utils/CircularBuffers/CircularBuffer.js +73 -0
  303. package/lib/utils/CircularBuffers/CircularBuffer.js.map +1 -0
  304. package/lib/utils/CircularBuffers/UniqueCircularBuffer.d.ts +19 -0
  305. package/lib/utils/CircularBuffers/UniqueCircularBuffer.js +78 -0
  306. package/lib/utils/CircularBuffers/UniqueCircularBuffer.js.map +1 -0
  307. package/lib/utils/CircularBuffers/index.d.ts +2 -0
  308. package/lib/utils/CircularBuffers/index.js +19 -0
  309. package/lib/utils/CircularBuffers/index.js.map +1 -0
  310. package/lib/utils/MultiplexWebSocket.d.ts +95 -0
  311. package/lib/utils/MultiplexWebSocket.js +416 -0
  312. package/lib/utils/MultiplexWebSocket.js.map +1 -0
  313. package/lib/utils/NumLib.d.ts +106 -0
  314. package/lib/utils/NumLib.js +300 -0
  315. package/lib/utils/NumLib.js.map +1 -0
  316. package/lib/utils/SharedInterval.d.ts +21 -0
  317. package/lib/utils/SharedInterval.js +47 -0
  318. package/lib/utils/SharedInterval.js.map +1 -0
  319. package/lib/utils/SlotBasedResultValidator.d.ts +9 -0
  320. package/lib/utils/SlotBasedResultValidator.js +27 -0
  321. package/lib/utils/SlotBasedResultValidator.js.map +1 -0
  322. package/lib/utils/Stopwatch.d.ts +15 -0
  323. package/lib/utils/Stopwatch.js +31 -0
  324. package/lib/utils/Stopwatch.js.map +1 -0
  325. package/lib/utils/StrictEventEmitter.d.ts +15 -0
  326. package/lib/utils/StrictEventEmitter.js +55 -0
  327. package/lib/utils/StrictEventEmitter.js.map +1 -0
  328. package/lib/utils/WalletConnectionState.d.ts +31 -0
  329. package/lib/utils/WalletConnectionState.js +83 -0
  330. package/lib/utils/WalletConnectionState.js.map +1 -0
  331. package/lib/utils/assert.d.ts +1 -0
  332. package/lib/utils/assert.js +10 -0
  333. package/lib/utils/assert.js.map +1 -0
  334. package/lib/utils/candles/Candle.d.ts +94 -0
  335. package/lib/utils/candles/Candle.js +580 -0
  336. package/lib/utils/candles/Candle.js.map +1 -0
  337. package/lib/utils/candles/types.d.ts +8 -0
  338. package/lib/utils/candles/types.js +3 -0
  339. package/lib/utils/candles/types.js.map +1 -0
  340. package/lib/utils/dlob-server/DlobServerWebsocketUtils.d.ts +57 -0
  341. package/lib/utils/dlob-server/DlobServerWebsocketUtils.js +137 -0
  342. package/lib/utils/dlob-server/DlobServerWebsocketUtils.js.map +1 -0
  343. package/lib/utils/driftEvents.d.ts +10 -0
  344. package/lib/utils/driftEvents.js +123 -0
  345. package/lib/utils/driftEvents.js.map +1 -0
  346. package/lib/utils/equalityChecks.d.ts +12 -0
  347. package/lib/utils/equalityChecks.js +71 -0
  348. package/lib/utils/equalityChecks.js.map +1 -0
  349. package/lib/utils/featureFlags.d.ts +3 -0
  350. package/lib/utils/featureFlags.js +7 -0
  351. package/lib/utils/featureFlags.js.map +1 -0
  352. package/lib/utils/geoblock/index.d.ts +4 -0
  353. package/lib/utils/geoblock/index.js +20 -0
  354. package/lib/utils/geoblock/index.js.map +1 -0
  355. package/lib/utils/index.d.ts +181 -0
  356. package/lib/utils/index.js +608 -0
  357. package/lib/utils/index.js.map +1 -0
  358. package/lib/utils/insuranceFund.d.ts +15 -0
  359. package/lib/utils/insuranceFund.js +84 -0
  360. package/lib/utils/insuranceFund.js.map +1 -0
  361. package/lib/utils/logger.d.ts +5 -0
  362. package/lib/utils/logger.js +53 -0
  363. package/lib/utils/logger.js.map +1 -0
  364. package/lib/utils/math.d.ts +10 -0
  365. package/lib/utils/math.js +89 -0
  366. package/lib/utils/math.js.map +1 -0
  367. package/lib/utils/orderbook/index.d.ts +65 -0
  368. package/lib/utils/orderbook/index.js +80 -0
  369. package/lib/utils/orderbook/index.js.map +1 -0
  370. package/lib/utils/pollingSequenceGuard.d.ts +9 -0
  371. package/lib/utils/pollingSequenceGuard.js +24 -0
  372. package/lib/utils/pollingSequenceGuard.js.map +1 -0
  373. package/lib/utils/priority-fees/PriorityFeeCalculator.d.ts +24 -0
  374. package/lib/utils/priority-fees/PriorityFeeCalculator.js +53 -0
  375. package/lib/utils/priority-fees/PriorityFeeCalculator.js.map +1 -0
  376. package/lib/utils/priority-fees/PriorityFeeStrategies.d.ts +5 -0
  377. package/lib/utils/priority-fees/PriorityFeeStrategies.js +43 -0
  378. package/lib/utils/priority-fees/PriorityFeeStrategies.js.map +1 -0
  379. package/lib/utils/priority-fees/index.d.ts +2 -0
  380. package/lib/utils/priority-fees/index.js +19 -0
  381. package/lib/utils/priority-fees/index.js.map +1 -0
  382. package/lib/utils/priorityFees.d.ts +14 -0
  383. package/lib/utils/priorityFees.js +68 -0
  384. package/lib/utils/priorityFees.js.map +1 -0
  385. package/lib/utils/rpcLatency.d.ts +7 -0
  386. package/lib/utils/rpcLatency.js +49 -0
  387. package/lib/utils/rpcLatency.js.map +1 -0
  388. package/lib/utils/rxjs.d.ts +11 -0
  389. package/lib/utils/rxjs.js +24 -0
  390. package/lib/utils/rxjs.js.map +1 -0
  391. package/lib/utils/s3Buckets.d.ts +43 -0
  392. package/lib/utils/s3Buckets.js +108 -0
  393. package/lib/utils/s3Buckets.js.map +1 -0
  394. package/lib/utils/superstake.d.ts +86 -0
  395. package/lib/utils/superstake.js +224 -0
  396. package/lib/utils/superstake.js.map +1 -0
  397. package/lib/utils/token.d.ts +16 -0
  398. package/lib/utils/token.js +44 -0
  399. package/lib/utils/token.js.map +1 -0
  400. package/package.json +87 -0
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createUserAndDepositCollateralBaseTxn = exports.createUserAndDepositCollateralBaseIxs = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const token_1 = require("../../../../utils/token");
6
+ const accountNames_1 = require("../../constants/accountNames");
7
+ const pools_1 = require("../../../../constants/pools");
8
+ const user_1 = require("../../../../common-ui-utils/user");
9
+ /**
10
+ * Creates transaction instructions for initializing a new user account and depositing collateral.
11
+ *
12
+ * This function generates the necessary transaction instructions to:
13
+ * 1. Initialize a new user account in the Drift protocol
14
+ * 2. Deposit collateral into the newly created account
15
+ *
16
+ * @param driftClient - The Drift client instance for interacting with the protocol
17
+ * @param amount - The amount of collateral to deposit (in base units)
18
+ * @param spotMarketConfig - The spot market config of the deposit collateral
19
+ * @param authority - The public key of the account authority (wallet owner)
20
+ * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID
21
+ * @param referrerName - Optional name of the referrer for referral tracking
22
+ * @param accountName - Optional custom name for the account (defaults to pool-specific name)
23
+ * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)
24
+ * @param fromSubAccountId - Optional sub-account ID to transfer funds from
25
+ * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
26
+ *
27
+ * @returns Promise resolving to an object containing:
28
+ * - subAccountId: The ID of the newly created sub-account
29
+ * - userAccountPublicKey: The public key of the created user account
30
+ * - ixs: Array of transaction instructions to execute
31
+ */
32
+ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, }) => {
33
+ var _a;
34
+ const nextUserId = (_a = userStatsAccount === null || userStatsAccount === void 0 ? void 0 : userStatsAccount.numberOfSubAccountsCreated) !== null && _a !== void 0 ? _a : 0; // userId is zero indexed
35
+ const associatedDepositTokenAddressPromise = (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketConfig.mint, authority);
36
+ const referrerInfoPromise = referrerName
37
+ ? driftClient.fetchReferrerNameAccount(referrerName)
38
+ : Promise.resolve(undefined);
39
+ const subaccountExistsPromise = user_1.USER_UTILS.checkIfUserAccountExists(driftClient, {
40
+ type: 'subAccountId',
41
+ subAccountId: nextUserId,
42
+ authority,
43
+ });
44
+ const [associatedDepositTokenAddress, referrerInfo, subaccountExists] = await Promise.all([
45
+ associatedDepositTokenAddressPromise,
46
+ referrerInfoPromise,
47
+ subaccountExistsPromise,
48
+ ]);
49
+ if (subaccountExists) {
50
+ throw new Error('Subaccount already exists');
51
+ }
52
+ const accountNameToUse = accountName !== null && accountName !== void 0 ? accountName : (poolId !== pools_1.MAIN_POOL_ID || nextUserId === 0
53
+ ? accountNames_1.DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]
54
+ : `Account ${nextUserId}`);
55
+ const { ixs, userAccountPublicKey } = await driftClient.createInitializeUserAccountAndDepositCollateralIxs(amount, associatedDepositTokenAddress, spotMarketConfig.marketIndex, nextUserId, accountNameToUse, fromSubAccountId, referrerInfo, sdk_1.ZERO, customMaxMarginRatio, poolId);
56
+ return {
57
+ subAccountId: nextUserId,
58
+ userAccountPublicKey,
59
+ ixs,
60
+ };
61
+ };
62
+ exports.createUserAndDepositCollateralBaseIxs = createUserAndDepositCollateralBaseIxs;
63
+ /**
64
+ * Creates a complete transaction for initializing a new user account and depositing collateral.
65
+ *
66
+ * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:
67
+ * 1. Generates the necessary transaction instructions
68
+ * 2. Builds a complete transaction ready for signing and submission
69
+ *
70
+ * @param driftClient - The Drift client instance for interacting with the protocol
71
+ * @param amount - The amount of collateral to deposit (in base units)
72
+ * @param spotMarketConfig - The spot market config of the deposit collateral
73
+ * @param authority - The public key of the account authority (wallet owner)
74
+ * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID
75
+ * @param referrerName - Optional name of the referrer for referral tracking
76
+ * @param accountName - Optional custom name for the account (defaults to pool-specific name)
77
+ * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)
78
+ * @param fromSubAccountId - Optional sub-account ID to transfer funds from
79
+ * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
80
+ * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)
81
+ *
82
+ * @returns Promise resolving to an object containing:
83
+ * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)
84
+ * - userAccountPublicKey: The public key of the created user account
85
+ * - subAccountId: The ID of the newly created sub-account
86
+ */
87
+ const createUserAndDepositCollateralBaseTxn = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, txParams, }) => {
88
+ const { ixs, userAccountPublicKey, subAccountId } = await (0, exports.createUserAndDepositCollateralBaseIxs)({
89
+ driftClient,
90
+ amount,
91
+ spotMarketConfig,
92
+ authority,
93
+ userStatsAccount,
94
+ referrerName,
95
+ accountName,
96
+ poolId,
97
+ fromSubAccountId,
98
+ customMaxMarginRatio,
99
+ });
100
+ const tx = await driftClient.buildTransaction(ixs, txParams);
101
+ return { transaction: tx, userAccountPublicKey, subAccountId };
102
+ };
103
+ exports.createUserAndDepositCollateralBaseTxn = createUserAndDepositCollateralBaseTxn;
104
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCASyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,2DAA8D;AAe9D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,GACyB,EAI3C,EAAE;;IACJ,MAAM,UAAU,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAE/F,MAAM,oCAAoC,GACzC,IAAA,4CAAoC,EAAC,gBAAgB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACxE,MAAM,mBAAmB,GAAsC,YAAY;QAC1E,CAAC,CAAC,WAAW,CAAC,wBAAwB,CAAC,YAAY,CAAC;QACpD,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAC9B,MAAM,uBAAuB,GAAG,iBAAU,CAAC,wBAAwB,CAClE,WAAW,EACX;QACC,IAAI,EAAE,cAAc;QACpB,YAAY,EAAE,UAAU;QACxB,SAAS;KACT,CACD,CAAC;IAEF,MAAM,CAAC,6BAA6B,EAAE,YAAY,EAAE,gBAAgB,CAAC,GACpE,MAAM,OAAO,CAAC,GAAG,CAAC;QACjB,oCAAoC;QACpC,mBAAmB;QACnB,uBAAuB;KACvB,CAAC,CAAC;IAEJ,IAAI,gBAAgB,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,gBAAgB,GACrB,WAAW,aAAX,WAAW,cAAX,WAAW,GACX,CAAC,MAAM,KAAK,oBAAY,IAAI,UAAU,KAAK,CAAC;QAC3C,CAAC,CAAC,+CAAgC,CAAC,MAAM,CAAC;QAC1C,CAAC,CAAC,WAAW,UAAU,EAAE,CAAC,CAAC;IAE7B,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAClC,MAAM,WAAW,CAAC,kDAAkD,CACnE,MAAM,EACN,6BAA6B,EAC7B,gBAAgB,CAAC,WAAW,EAC5B,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,UAAI,EACJ,oBAAoB,EACpB,MAAM,CACN,CAAC;IAEH,OAAO;QACN,YAAY,EAAE,UAAU;QACxB,oBAAoB;QACpB,GAAG;KACH,CAAC;AACH,CAAC,CAAC;AApEW,QAAA,qCAAqC,yCAoEhD;AAOF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,GACqC,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;KACpB,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AAlCW,QAAA,qCAAqC,yCAkChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tPublicKey,\n\tReferrerInfo,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../common-ui-utils/user';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextUserId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(spotMarketConfig.mint, authority);\n\tconst referrerInfoPromise: Promise<ReferrerInfo | undefined> = referrerName\n\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextUserId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerInfo, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerInfoPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextUserId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextUserId}`);\n\n\tconst { ixs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextUserId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId\n\t\t);\n\n\treturn {\n\t\tsubAccountId: nextUserId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
@@ -0,0 +1,47 @@
1
+ import { DriftClient, TxParams, User } from '@drift-labs/sdk';
2
+ /**
3
+ * Parameters required for deleting a user instruction
4
+ */
5
+ interface DeleteUserIxParams {
6
+ /** The Drift protocol client instance */
7
+ driftClient: DriftClient;
8
+ /** The user account to be deleted */
9
+ user: User;
10
+ }
11
+ /**
12
+ * Creates a user deletion instruction.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const deleteIx = await deleteUserIx({
17
+ * driftClient: driftClient,
18
+ * user: userClient
19
+ * });
20
+ * ```
21
+ */
22
+ export declare const deleteUserIx: ({ driftClient, user, }: DeleteUserIxParams) => Promise<import("@solana/web3.js").TransactionInstruction>;
23
+ /**
24
+ * Parameters required for creating a user deletion transaction
25
+ * Extends DeleteUserIxParams with optional transaction parameters
26
+ */
27
+ interface DeleteUserTxnParams extends DeleteUserIxParams {
28
+ /** Optional transaction parameters for customizing the transaction */
29
+ txParams?: TxParams;
30
+ }
31
+ /**
32
+ * Creates a user deletion transaction.
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const deleteTxn = await deleteUserTxn({
37
+ * driftClient: driftClient,
38
+ * user: userClient,
39
+ * txParams: { useSimulatedComputeUnits: true }
40
+ * });
41
+ *
42
+ * // Sign and send the transaction
43
+ * const signature = await driftClient.sendTransaction(deleteTxn);
44
+ * ```
45
+ */
46
+ export declare const deleteUserTxn: ({ driftClient, user, txParams, }: DeleteUserTxnParams) => Promise<import("@solana/web3.js").Transaction | import("@solana/web3.js").VersionedTransaction>;
47
+ export {};
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteUserTxn = exports.deleteUserIx = void 0;
4
+ /**
5
+ * Creates a user deletion instruction.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const deleteIx = await deleteUserIx({
10
+ * driftClient: driftClient,
11
+ * user: userClient
12
+ * });
13
+ * ```
14
+ */
15
+ const deleteUserIx = async ({ driftClient, user, }) => {
16
+ return driftClient.getUserDeletionIx(user.userAccountPublicKey);
17
+ };
18
+ exports.deleteUserIx = deleteUserIx;
19
+ /**
20
+ * Creates a user deletion transaction.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const deleteTxn = await deleteUserTxn({
25
+ * driftClient: driftClient,
26
+ * user: userClient,
27
+ * txParams: { useSimulatedComputeUnits: true }
28
+ * });
29
+ *
30
+ * // Sign and send the transaction
31
+ * const signature = await driftClient.sendTransaction(deleteTxn);
32
+ * ```
33
+ */
34
+ const deleteUserTxn = async ({ driftClient, user, txParams, }) => {
35
+ const deleteIx = await (0, exports.deleteUserIx)({ driftClient, user });
36
+ return driftClient.buildTransaction(deleteIx, txParams);
37
+ };
38
+ exports.deleteUserTxn = deleteUserTxn;
39
+ //# sourceMappingURL=delete.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/delete.ts"],"names":[],"mappings":";;;AAYA;;;;;;;;;;GAUG;AACI,MAAM,YAAY,GAAG,KAAK,EAAE,EAClC,WAAW,EACX,IAAI,GACgB,EAAE,EAAE;IACxB,OAAO,WAAW,CAAC,iBAAiB,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACjE,CAAC,CAAC;AALW,QAAA,YAAY,gBAKvB;AAWF;;;;;;;;;;;;;;GAcG;AACI,MAAM,aAAa,GAAG,KAAK,EAAE,EACnC,WAAW,EACX,IAAI,EACJ,QAAQ,GACa,EAAE,EAAE;IACzB,MAAM,QAAQ,GAAG,MAAM,IAAA,oBAAY,EAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3D,OAAO,WAAW,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACzD,CAAC,CAAC;AAPW,QAAA,aAAa,iBAOxB","sourcesContent":["import { DriftClient, TxParams, User } from '@drift-labs/sdk';\n\n/**\n * Parameters required for deleting a user instruction\n */\ninterface DeleteUserIxParams {\n\t/** The Drift protocol client instance */\n\tdriftClient: DriftClient;\n\t/** The user account to be deleted */\n\tuser: User;\n}\n\n/**\n * Creates a user deletion instruction.\n *\n * @example\n * ```typescript\n * const deleteIx = await deleteUserIx({\n * driftClient: driftClient,\n * user: userClient\n * });\n * ```\n */\nexport const deleteUserIx = async ({\n\tdriftClient,\n\tuser,\n}: DeleteUserIxParams) => {\n\treturn driftClient.getUserDeletionIx(user.userAccountPublicKey);\n};\n\n/**\n * Parameters required for creating a user deletion transaction\n * Extends DeleteUserIxParams with optional transaction parameters\n */\ninterface DeleteUserTxnParams extends DeleteUserIxParams {\n\t/** Optional transaction parameters for customizing the transaction */\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a user deletion transaction.\n *\n * @example\n * ```typescript\n * const deleteTxn = await deleteUserTxn({\n * driftClient: driftClient,\n * user: userClient,\n * txParams: { useSimulatedComputeUnits: true }\n * });\n *\n * // Sign and send the transaction\n * const signature = await driftClient.sendTransaction(deleteTxn);\n * ```\n */\nexport const deleteUserTxn = async ({\n\tdriftClient,\n\tuser,\n\ttxParams,\n}: DeleteUserTxnParams) => {\n\tconst deleteIx = await deleteUserIx({ driftClient, user });\n\treturn driftClient.buildTransaction(deleteIx, txParams);\n};\n"]}
@@ -0,0 +1 @@
1
+ export * from './create';
@@ -0,0 +1,18 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./create"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB","sourcesContent":["export * from './create';\n"]}
@@ -0,0 +1 @@
1
+ export declare const DEFAULT_ACCOUNT_NAMES_BY_POOL_ID: Record<number, string>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_ACCOUNT_NAMES_BY_POOL_ID = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const pools_1 = require("../../../constants/pools");
6
+ exports.DEFAULT_ACCOUNT_NAMES_BY_POOL_ID = {
7
+ [pools_1.MAIN_POOL_ID]: sdk_1.DEFAULT_USER_NAME,
8
+ [pools_1.JLP_POOL_ID]: 'JLP Market - Isolated Pool',
9
+ [pools_1.EXPONENT_POOL_ID]: 'Exponent Market - Isolated Pool',
10
+ [pools_1.SACRED_POOL_ID]: 'ACRED Market - Isolated Pool',
11
+ [pools_1.LST_POOL_ID]: 'LST Market - Isolated Pool',
12
+ };
13
+ //# sourceMappingURL=accountNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountNames.js","sourceRoot":"","sources":["../../../../src/drift/base/constants/accountNames.ts"],"names":[],"mappings":";;;AAAA,yCAAoD;AACpD,oDAMkC;AAErB,QAAA,gCAAgC,GAA2B;IACvE,CAAC,oBAAY,CAAC,EAAE,uBAAiB;IACjC,CAAC,mBAAW,CAAC,EAAE,4BAA4B;IAC3C,CAAC,wBAAgB,CAAC,EAAE,iCAAiC;IACrD,CAAC,sBAAc,CAAC,EAAE,8BAA8B;IAChD,CAAC,mBAAW,CAAC,EAAE,4BAA4B;CAC3C,CAAC","sourcesContent":["import { DEFAULT_USER_NAME } from '@drift-labs/sdk';\nimport {\n\tJLP_POOL_ID,\n\tMAIN_POOL_ID,\n\tSACRED_POOL_ID,\n\tLST_POOL_ID,\n\tEXPONENT_POOL_ID,\n} from '../../../constants/pools';\n\nexport const DEFAULT_ACCOUNT_NAMES_BY_POOL_ID: Record<number, string> = {\n\t[MAIN_POOL_ID]: DEFAULT_USER_NAME,\n\t[JLP_POOL_ID]: 'JLP Market - Isolated Pool',\n\t[EXPONENT_POOL_ID]: 'Exponent Market - Isolated Pool',\n\t[SACRED_POOL_ID]: 'ACRED Market - Isolated Pool',\n\t[LST_POOL_ID]: 'LST Market - Isolated Pool',\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './user';
2
+ export * from './market';
@@ -0,0 +1,19 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./user"), exports);
18
+ __exportStar(require("./market"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/drift/base/details/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,2CAAyB","sourcesContent":["export * from './user';\nexport * from './market';\n"]}
@@ -0,0 +1,9 @@
1
+ import { DriftClient } from '@drift-labs/sdk';
2
+ export declare const getMarketPredictedFunding: (driftClient: DriftClient, marketIndex: number) => {
3
+ longFundingRate: number;
4
+ shortFundingRate: number;
5
+ };
6
+ export declare const getMarketHistoricalFunding: (marketSymbol?: string) => Promise<Array<{
7
+ slot: number;
8
+ fundingRatePct: number;
9
+ }>>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMarketHistoricalFunding = exports.getMarketPredictedFunding = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const Drift_1 = require("../../../Drift");
6
+ const types_1 = require("../../../../types");
7
+ const funding_1 = require("../../../utils/funding");
8
+ const apiUrls_1 = require("../../../constants/apiUrls");
9
+ const getMarketPredictedFunding = (driftClient, marketIndex) => {
10
+ const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);
11
+ const rawMmOraclePriceData = driftClient.getMMOracleDataForPerpMarket(marketIndex);
12
+ const rawOraclePriceData = driftClient.getOracleDataForPerpMarket(marketIndex);
13
+ const markPriceCache = new Drift_1.MarkPriceCache();
14
+ const marketId = types_1.MarketId.createPerpMarket(marketIndex);
15
+ const markPrice = markPriceCache.getMarkPrice(marketId.key);
16
+ const nowBN = new sdk_1.BN(Date.now());
17
+ const [_markTwapLive, oracleTwapLive, longFundingRate, shortFundingRate] = (0, sdk_1.calculateLongShortFundingRateAndLiveTwaps)(perpMarketAccount, rawMmOraclePriceData, rawOraclePriceData, markPrice, nowBN);
18
+ return {
19
+ longFundingRate: (0, funding_1.getFundingRate)(longFundingRate, oracleTwapLive),
20
+ shortFundingRate: (0, funding_1.getFundingRate)(shortFundingRate, oracleTwapLive),
21
+ };
22
+ };
23
+ exports.getMarketPredictedFunding = getMarketPredictedFunding;
24
+ const getMarketHistoricalFunding = async (marketSymbol = 'SOL-PERP') => {
25
+ // TODO: if we're hitting the data api a lot we should set up a client file for it.. not sure if necessary
26
+ const url = `${apiUrls_1.API_URLS.DATA_API}${apiUrls_1.API_ENDPOINTS.FUNDING_RATES}?marketName=${marketSymbol}`;
27
+ try {
28
+ const response = await fetch(url);
29
+ if (!response.ok) {
30
+ throw new Error(`HTTP error! status: ${response.status}`);
31
+ }
32
+ const data = await response.json();
33
+ const rates = data.fundingRates || [];
34
+ return rates.map((rate) => {
35
+ const fundingRateBN = new sdk_1.BN(rate.fundingRate);
36
+ const oracleTwapBN = new sdk_1.BN(rate.oraclePriceTwap);
37
+ const fundingRatePct = (0, funding_1.getFundingRate)(fundingRateBN, oracleTwapBN);
38
+ return {
39
+ slot: rate.slot,
40
+ fundingRatePct,
41
+ };
42
+ });
43
+ }
44
+ catch (error) {
45
+ console.error('Error fetching funding rates:', error);
46
+ return [];
47
+ }
48
+ };
49
+ exports.getMarketHistoricalFunding = getMarketHistoricalFunding;
50
+ //# sourceMappingURL=funding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"funding.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/market/funding.ts"],"names":[],"mappings":";;;AAAA,yCAIyB;AACzB,0CAAgD;AAChD,6CAA6C;AAC7C,oDAAwD;AACxD,wDAAqE;AAE9D,MAAM,yBAAyB,GAAG,CACxC,WAAwB,EACxB,WAAmB,EAIlB,EAAE;IACH,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxE,MAAM,oBAAoB,GACzB,WAAW,CAAC,4BAA4B,CAAC,WAAW,CAAC,CAAC;IACvD,MAAM,kBAAkB,GACvB,WAAW,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC;IAErD,MAAM,cAAc,GAAG,IAAI,sBAAc,EAAE,CAAC;IAC5C,MAAM,QAAQ,GAAG,gBAAQ,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAExD,MAAM,SAAS,GAAG,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,KAAK,GAAG,IAAI,QAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IAEjC,MAAM,CAAC,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,CAAC,GACvE,IAAA,+CAAyC,EACxC,iBAAiB,EACjB,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,KAAK,CACL,CAAC;IAEH,OAAO;QACN,eAAe,EAAE,IAAA,wBAAc,EAAC,eAAe,EAAE,cAAc,CAAC;QAChE,gBAAgB,EAAE,IAAA,wBAAc,EAAC,gBAAgB,EAAE,cAAc,CAAC;KAClE,CAAC;AACH,CAAC,CAAC;AAhCW,QAAA,yBAAyB,6BAgCpC;AAQK,MAAM,0BAA0B,GAAG,KAAK,EAC9C,eAAuB,UAAU,EAC0B,EAAE;IAC7D,0GAA0G;IAC1G,MAAM,GAAG,GAAG,GAAG,kBAAQ,CAAC,QAAQ,GAAG,uBAAa,CAAC,aAAa,eAAe,YAAY,EAAE,CAAC;IAE5F,IAAI,CAAC;QACJ,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,uBAAuB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3D,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,MAAM,KAAK,GAA6B,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC;QAEhE,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;YACzB,MAAM,aAAa,GAAG,IAAI,QAAE,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAC/C,MAAM,YAAY,GAAG,IAAI,QAAE,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YAClD,MAAM,cAAc,GAAG,IAAA,wBAAc,EAAC,aAAa,EAAE,YAAY,CAAC,CAAC;YAEnE,OAAO;gBACN,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,cAAc;aACd,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,KAAK,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;QACtD,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC,CAAC;AA5BW,QAAA,0BAA0B,8BA4BrC","sourcesContent":["import {\n\tBN,\n\tcalculateLongShortFundingRateAndLiveTwaps,\n\tDriftClient,\n} from '@drift-labs/sdk';\nimport { MarkPriceCache } from '../../../Drift';\nimport { MarketId } from '../../../../types';\nimport { getFundingRate } from '../../../utils/funding';\nimport { API_URLS, API_ENDPOINTS } from '../../../constants/apiUrls';\n\nexport const getMarketPredictedFunding = (\n\tdriftClient: DriftClient,\n\tmarketIndex: number\n): {\n\tlongFundingRate: number;\n\tshortFundingRate: number;\n} => {\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\tconst rawMmOraclePriceData =\n\t\tdriftClient.getMMOracleDataForPerpMarket(marketIndex);\n\tconst rawOraclePriceData =\n\t\tdriftClient.getOracleDataForPerpMarket(marketIndex);\n\n\tconst markPriceCache = new MarkPriceCache();\n\tconst marketId = MarketId.createPerpMarket(marketIndex);\n\n\tconst markPrice = markPriceCache.getMarkPrice(marketId.key);\n\tconst nowBN = new BN(Date.now());\n\n\tconst [_markTwapLive, oracleTwapLive, longFundingRate, shortFundingRate] =\n\t\tcalculateLongShortFundingRateAndLiveTwaps(\n\t\t\tperpMarketAccount,\n\t\t\trawMmOraclePriceData,\n\t\t\trawOraclePriceData,\n\t\t\tmarkPrice,\n\t\t\tnowBN\n\t\t);\n\n\treturn {\n\t\tlongFundingRate: getFundingRate(longFundingRate, oracleTwapLive),\n\t\tshortFundingRate: getFundingRate(shortFundingRate, oracleTwapLive),\n\t};\n};\n\ninterface FundingRateApiResponse {\n\tslot: number;\n\tfundingRate: string;\n\toraclePriceTwap: string;\n}\n\nexport const getMarketHistoricalFunding = async (\n\tmarketSymbol: string = 'SOL-PERP'\n): Promise<Array<{ slot: number; fundingRatePct: number }>> => {\n\t// TODO: if we're hitting the data api a lot we should set up a client file for it.. not sure if necessary\n\tconst url = `${API_URLS.DATA_API}${API_ENDPOINTS.FUNDING_RATES}?marketName=${marketSymbol}`;\n\n\ttry {\n\t\tconst response = await fetch(url);\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`HTTP error! status: ${response.status}`);\n\t\t}\n\t\tconst data = await response.json();\n\t\tconst rates: FundingRateApiResponse[] = data.fundingRates || [];\n\n\t\treturn rates.map((rate) => {\n\t\t\tconst fundingRateBN = new BN(rate.fundingRate);\n\t\t\tconst oracleTwapBN = new BN(rate.oraclePriceTwap);\n\t\t\tconst fundingRatePct = getFundingRate(fundingRateBN, oracleTwapBN);\n\n\t\t\treturn {\n\t\t\t\tslot: rate.slot,\n\t\t\t\tfundingRatePct,\n\t\t\t};\n\t\t});\n\t} catch (error) {\n\t\tconsole.error('Error fetching funding rates:', error);\n\t\treturn [];\n\t}\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './funding';
2
+ export * from './openInterest';
@@ -0,0 +1,19 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./funding"), exports);
18
+ __exportStar(require("./openInterest"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/market/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,iDAA+B","sourcesContent":["export * from './funding';\nexport * from './openInterest';\n"]}
@@ -0,0 +1,5 @@
1
+ import { BigNum, DriftClient } from '@drift-labs/sdk';
2
+ export declare const getMarketOpenInterest: (driftClient: DriftClient, marketIndex: number) => {
3
+ longOpenInterest: BigNum;
4
+ shortOpenInterest: BigNum;
5
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMarketOpenInterest = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const getMarketOpenInterest = (driftClient, marketIndex) => {
6
+ const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);
7
+ const longOpenInterest = sdk_1.BigNum.from(perpMarketAccount.amm.baseAssetAmountLong, sdk_1.BASE_PRECISION_EXP);
8
+ const shortOpenInterest = sdk_1.BigNum.from(perpMarketAccount.amm.baseAssetAmountShort, sdk_1.BASE_PRECISION_EXP);
9
+ return { longOpenInterest, shortOpenInterest };
10
+ };
11
+ exports.getMarketOpenInterest = getMarketOpenInterest;
12
+ //# sourceMappingURL=openInterest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openInterest.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/market/openInterest.ts"],"names":[],"mappings":";;;AAAA,yCAA0E;AAEnE,MAAM,qBAAqB,GAAG,CACpC,WAAwB,EACxB,WAAmB,EACuC,EAAE;IAC5D,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxE,MAAM,gBAAgB,GAAG,YAAM,CAAC,IAAI,CACnC,iBAAiB,CAAC,GAAG,CAAC,mBAAmB,EACzC,wBAAkB,CAClB,CAAC;IACF,MAAM,iBAAiB,GAAG,YAAM,CAAC,IAAI,CACpC,iBAAiB,CAAC,GAAG,CAAC,oBAAoB,EAC1C,wBAAkB,CAClB,CAAC;IACF,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,CAAC;AAChD,CAAC,CAAC;AAdW,QAAA,qBAAqB,yBAchC","sourcesContent":["import { BASE_PRECISION_EXP, BigNum, DriftClient } from '@drift-labs/sdk';\n\nexport const getMarketOpenInterest = (\n\tdriftClient: DriftClient,\n\tmarketIndex: number\n): { longOpenInterest: BigNum; shortOpenInterest: BigNum } => {\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\tconst longOpenInterest = BigNum.from(\n\t\tperpMarketAccount.amm.baseAssetAmountLong,\n\t\tBASE_PRECISION_EXP\n\t);\n\tconst shortOpenInterest = BigNum.from(\n\t\tperpMarketAccount.amm.baseAssetAmountShort,\n\t\tBASE_PRECISION_EXP\n\t);\n\treturn { longOpenInterest, shortOpenInterest };\n};\n"]}
@@ -0,0 +1,40 @@
1
+ import { BigNum, BN, DriftClient, User } from '@drift-labs/sdk';
2
+ /**
3
+ * Essential balance information for a spot market position.
4
+ * Contains the three key metrics needed for balance display and analysis.
5
+ */
6
+ export interface SpotBalanceInfo {
7
+ marketIndex: number;
8
+ /**
9
+ * Net balance in base asset terms (deposits - borrows).
10
+ * Positive values indicate net deposits, negative values indicate net borrows.
11
+ */
12
+ baseBalance: BigNum;
13
+ /**
14
+ * USD notional value of the net balance based on oracle price.
15
+ * This represents the current market value of the position.
16
+ */
17
+ notionalBalance: BigNum;
18
+ /**
19
+ * Oracle price at which this balance would contribute to account liquidation.
20
+ * Returns zero if liquidation price cannot be calculated.
21
+ */
22
+ liquidationPrice: BigNum;
23
+ }
24
+ /**
25
+ * Derives essential balance display information from a User's SpotPosition.
26
+ *
27
+ * Key features:
28
+ * - Calculates net balance (deposits minus borrows) in base asset terms
29
+ * - Computes USD notional value using current oracle price
30
+ * - Determines liquidation price for the specific market
31
+ * - Handles edge cases like zero balances and invalid liquidation prices
32
+ *
33
+ * @param driftClient - The DriftClient instance.
34
+ * @param user - The User instance.
35
+ * @param marketIndex - The market index for the spot market.
36
+ * @param oraclePrice - The oracle price for the spot market.
37
+ *
38
+ * @returns SpotBalanceInfo object containing the three essential balance metrics
39
+ */
40
+ export declare const getSpotBalanceInfo: (driftClient: DriftClient, user: User, marketIndex: number, oraclePrice: BN) => SpotBalanceInfo;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSpotBalanceInfo = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const market_1 = require("../../../../common-ui-utils/market");
6
+ /**
7
+ * Derives essential balance display information from a User's SpotPosition.
8
+ *
9
+ * Key features:
10
+ * - Calculates net balance (deposits minus borrows) in base asset terms
11
+ * - Computes USD notional value using current oracle price
12
+ * - Determines liquidation price for the specific market
13
+ * - Handles edge cases like zero balances and invalid liquidation prices
14
+ *
15
+ * @param driftClient - The DriftClient instance.
16
+ * @param user - The User instance.
17
+ * @param marketIndex - The market index for the spot market.
18
+ * @param oraclePrice - The oracle price for the spot market.
19
+ *
20
+ * @returns SpotBalanceInfo object containing the three essential balance metrics
21
+ */
22
+ const getSpotBalanceInfo = (driftClient, user, marketIndex, oraclePrice) => {
23
+ const spotMarketConfig = market_1.MARKET_UTILS.getMarketConfig(driftClient.env, sdk_1.MarketType.SPOT, marketIndex);
24
+ const baseBalance = user.getTokenAmount(marketIndex);
25
+ const baseBalanceBigNum = sdk_1.BigNum.from(baseBalance, spotMarketConfig.precisionExp);
26
+ const notionalBalance = baseBalanceBigNum
27
+ .mul(sdk_1.BigNum.from(oraclePrice, sdk_1.PRICE_PRECISION_EXP))
28
+ .shiftTo(sdk_1.QUOTE_PRECISION_EXP);
29
+ const liqPrice = user.spotLiquidationPrice(marketIndex);
30
+ const liquidationPrice = sdk_1.BigNum.from(liqPrice, sdk_1.PRICE_PRECISION_EXP);
31
+ return {
32
+ marketIndex,
33
+ baseBalance: baseBalanceBigNum,
34
+ notionalBalance,
35
+ liquidationPrice,
36
+ };
37
+ };
38
+ exports.getSpotBalanceInfo = getSpotBalanceInfo;
39
+ //# sourceMappingURL=balances.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balances.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/balances.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AACzB,+DAAkE;AA2BlE;;;;;;;;;;;;;;;GAeG;AACI,MAAM,kBAAkB,GAAG,CACjC,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,WAAe,EACG,EAAE;IACpB,MAAM,gBAAgB,GAAG,qBAAY,CAAC,eAAe,CACpD,WAAW,CAAC,GAAG,EACf,gBAAU,CAAC,IAAI,EACf,WAAW,CACX,CAAC;IAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,iBAAiB,GAAG,YAAM,CAAC,IAAI,CACpC,WAAW,EACX,gBAAgB,CAAC,YAAY,CAC7B,CAAC;IAEF,MAAM,eAAe,GAAG,iBAAiB;SACvC,GAAG,CAAC,YAAM,CAAC,IAAI,CAAC,WAAW,EAAE,yBAAmB,CAAC,CAAC;SAClD,OAAO,CAAC,yBAAmB,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxD,MAAM,gBAAgB,GAAG,YAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAmB,CAAC,CAAC;IAEpE,OAAO;QACN,WAAW;QACX,WAAW,EAAE,iBAAiB;QAC9B,eAAe;QACf,gBAAgB;KAChB,CAAC;AACH,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tDriftClient,\n\tMarketType,\n\tPRICE_PRECISION_EXP,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n} from '@drift-labs/sdk';\nimport { MARKET_UTILS } from '../../../../common-ui-utils/market';\n\n/**\n * Essential balance information for a spot market position.\n * Contains the three key metrics needed for balance display and analysis.\n */\nexport interface SpotBalanceInfo {\n\tmarketIndex: number;\n\t/**\n\t * Net balance in base asset terms (deposits - borrows).\n\t * Positive values indicate net deposits, negative values indicate net borrows.\n\t */\n\tbaseBalance: BigNum;\n\n\t/**\n\t * USD notional value of the net balance based on oracle price.\n\t * This represents the current market value of the position.\n\t */\n\tnotionalBalance: BigNum;\n\n\t/**\n\t * Oracle price at which this balance would contribute to account liquidation.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n}\n\n/**\n * Derives essential balance display information from a User's SpotPosition.\n *\n * Key features:\n * - Calculates net balance (deposits minus borrows) in base asset terms\n * - Computes USD notional value using current oracle price\n * - Determines liquidation price for the specific market\n * - Handles edge cases like zero balances and invalid liquidation prices\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param marketIndex - The market index for the spot market.\n * @param oraclePrice - The oracle price for the spot market.\n *\n * @returns SpotBalanceInfo object containing the three essential balance metrics\n */\nexport const getSpotBalanceInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\toraclePrice: BN\n): SpotBalanceInfo => {\n\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\tdriftClient.env,\n\t\tMarketType.SPOT,\n\t\tmarketIndex\n\t);\n\n\tconst baseBalance = user.getTokenAmount(marketIndex);\n\tconst baseBalanceBigNum = BigNum.from(\n\t\tbaseBalance,\n\t\tspotMarketConfig.precisionExp\n\t);\n\n\tconst notionalBalance = baseBalanceBigNum\n\t\t.mul(BigNum.from(oraclePrice, PRICE_PRECISION_EXP))\n\t\t.shiftTo(QUOTE_PRECISION_EXP);\n\n\tconst liqPrice = user.spotLiquidationPrice(marketIndex);\n\tconst liquidationPrice = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseBalance: baseBalanceBigNum,\n\t\tnotionalBalance,\n\t\tliquidationPrice,\n\t};\n};\n"]}
@@ -0,0 +1,4 @@
1
+ export * from './positions';
2
+ export * from './balances';
3
+ export * from './orders';
4
+ export * from './marginInfo';
@@ -0,0 +1,21 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./positions"), exports);
18
+ __exportStar(require("./balances"), exports);
19
+ __exportStar(require("./orders"), exports);
20
+ __exportStar(require("./marginInfo"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,6CAA2B;AAC3B,2CAAyB;AACzB,+CAA6B","sourcesContent":["export * from './positions';\nexport * from './balances';\nexport * from './orders';\nexport * from './marginInfo';\n"]}
@@ -0,0 +1,29 @@
1
+ import { BN, BigNum, User, DriftClient } from '@drift-labs/sdk';
2
+ import { MarketKey } from '../../../../types';
3
+ export type AccountMarginInfo = {
4
+ /** Net USD value of the account, including spot balances and unsettled P&L from perp positions. */
5
+ netUsdValue: BigNum;
6
+ /** Total unsettled P&L from perp positions. Includes position P&L and funding P&L. */
7
+ totalUnsettledPnl: BigNum;
8
+ /** Total unsettled funding P&L from perp positions. */
9
+ totalUnsettledFundingPnL: BigNum;
10
+ /** Total claimable P&L from the P&L pool for perp positions. */
11
+ totalClaimablePnl: BigNum;
12
+ /** Total initial margin in the account. Includes weighted values of spot balances and unsettled P&L from perp positions. */
13
+ totalInitialMargin: BigNum;
14
+ /** Total maintenance margin in the account. Includes weighted values of spot balances and unsettled P&L from perp positions. */
15
+ totalMaintenanceMargin: BigNum;
16
+ /** Free initial margin in the account, used to open new positions. */
17
+ freeInitialMargin: BigNum;
18
+ /** Free maintenance margin in the account, used to avoid liquidations. */
19
+ freeMaintenanceMargin: BigNum;
20
+ /** Current leverage multiplier of the account. */
21
+ leverage: number;
22
+ /** Initial margin required to open a new position. */
23
+ initialReq: BigNum;
24
+ /** Maintenance margin required to avoid liquidations. */
25
+ maintenanceReq: BigNum;
26
+ /** Margin ratio of the account. */
27
+ marginRatioPct: number;
28
+ };
29
+ export declare const getAccountMarginInfo: (driftClient: DriftClient, user: User, getOraclePrice: (marketKey: MarketKey) => BN) => AccountMarginInfo;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAccountMarginInfo = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const constants_1 = require("../../../../constants");
6
+ const types_1 = require("../../../../types");
7
+ const getAccountMarginInfo = (driftClient, user, getOraclePrice) => {
8
+ const netUsdValue = user.getNetUsdValue();
9
+ const totalUnsettledPnl = user.getUnrealizedPNL(true); // method from SDK is inappropriately named, totalUnsettledPnl is the right definition here
10
+ const totalUnsettledFundingPnL = user.getUnrealizedFundingPNL();
11
+ const totalInitialMargin = user.getTotalCollateral();
12
+ const totalMaintenanceMargin = user.getTotalCollateral('Maintenance');
13
+ const freeInitialMargin = user.getFreeCollateral();
14
+ const freeMaintenanceMargin = user.getFreeCollateral('Maintenance');
15
+ const initialReq = user.getInitialMarginRequirement();
16
+ const maintenanceReq = user.getMaintenanceMarginRequirement();
17
+ const userLeverage = user.getLeverage();
18
+ let userMarginRatio = user.getMarginRatio();
19
+ // weird to display massive fraction when really it just means that their position is zero
20
+ if (userMarginRatio.eq(new sdk_1.BN(Number.MAX_SAFE_INTEGER)))
21
+ userMarginRatio = sdk_1.ZERO;
22
+ const usdcSpotMarketAccount = driftClient.getSpotMarketAccount(constants_1.USDC_SPOT_MARKET_INDEX);
23
+ const totalClaimablePnl = user
24
+ .getActivePerpPositions()
25
+ .reduce((acc, position) => {
26
+ const perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);
27
+ const oraclePrice = getOraclePrice(types_1.MarketId.createPerpMarket(position.marketIndex).key);
28
+ const positionClaimablePnl = (0, sdk_1.calculateClaimablePnl)(perpMarket, usdcSpotMarketAccount, position, {
29
+ price: oraclePrice,
30
+ });
31
+ return acc.add(positionClaimablePnl);
32
+ }, sdk_1.ZERO);
33
+ return {
34
+ netUsdValue: sdk_1.BigNum.from(netUsdValue, sdk_1.QUOTE_PRECISION_EXP),
35
+ totalUnsettledPnl: sdk_1.BigNum.from(totalUnsettledPnl, sdk_1.QUOTE_PRECISION_EXP),
36
+ totalUnsettledFundingPnL: sdk_1.BigNum.from(totalUnsettledFundingPnL, sdk_1.QUOTE_PRECISION_EXP),
37
+ totalClaimablePnl: sdk_1.BigNum.from(totalClaimablePnl, sdk_1.QUOTE_PRECISION_EXP),
38
+ totalInitialMargin: sdk_1.BigNum.from(totalInitialMargin, sdk_1.QUOTE_PRECISION_EXP),
39
+ totalMaintenanceMargin: sdk_1.BigNum.from(totalMaintenanceMargin, sdk_1.QUOTE_PRECISION_EXP),
40
+ freeInitialMargin: sdk_1.BigNum.from(freeInitialMargin, sdk_1.QUOTE_PRECISION_EXP),
41
+ freeMaintenanceMargin: sdk_1.BigNum.from(freeMaintenanceMargin, sdk_1.QUOTE_PRECISION_EXP),
42
+ leverage: sdk_1.BigNum.from(userLeverage, sdk_1.FOUR).toNum(),
43
+ maintenanceReq: sdk_1.BigNum.from(maintenanceReq, sdk_1.QUOTE_PRECISION_EXP),
44
+ initialReq: sdk_1.BigNum.from(initialReq, sdk_1.QUOTE_PRECISION_EXP),
45
+ marginRatioPct: sdk_1.BigNum.from(userMarginRatio, sdk_1.TWO).toNum(),
46
+ };
47
+ };
48
+ exports.getAccountMarginInfo = getAccountMarginInfo;
49
+ //# sourceMappingURL=marginInfo.js.map