@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,624 @@
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.COMMON_UI_UTILS = void 0;
30
+ const sdk_1 = require("@drift-labs/sdk");
31
+ const utils_1 = require("../utils");
32
+ const web3_js_1 = require("@solana/web3.js");
33
+ const bcryptjs_react_1 = __importDefault(require("bcryptjs-react"));
34
+ const tweetnacl_1 = __importStar(require("tweetnacl"));
35
+ const spl_token_1 = require("@solana/spl-token");
36
+ const user_1 = require("./user");
37
+ const trading_1 = require("./trading");
38
+ const market_1 = require("./market");
39
+ const order_1 = require("./order");
40
+ const trade_1 = require("../constants/trade");
41
+ // When creating an account, try 5 times over 5 seconds to wait for the new account to hit the blockchain.
42
+ const ACCOUNT_INITIALIZATION_RETRY_DELAY_MS = 1000;
43
+ const ACCOUNT_INITIALIZATION_RETRY_ATTEMPTS = 5;
44
+ const abbreviateAddress = (address, length = 4) => {
45
+ if (!address)
46
+ return '';
47
+ const authString = address.toString();
48
+ return `${authString.slice(0, length)}...${authString.slice(-length)}`;
49
+ };
50
+ /**
51
+ * Get a unique key for an authority's subaccount
52
+ * @param userId
53
+ * @param authority
54
+ * @returns
55
+ */
56
+ const getUserKey = (userId, authority) => {
57
+ if (userId == undefined || !authority)
58
+ return '';
59
+ return `${userId}_${authority.toString()}`;
60
+ };
61
+ /**
62
+ * Get the authority and subAccountId from a user's account key
63
+ * @param key
64
+ * @returns
65
+ */
66
+ const getIdAndAuthorityFromKey = (key) => {
67
+ const splitKey = key === null || key === void 0 ? void 0 : key.split('_');
68
+ if (!splitKey || splitKey.length !== 2)
69
+ return { userId: undefined, userAuthority: undefined };
70
+ return {
71
+ userId: Number(splitKey[0]),
72
+ userAuthority: new sdk_1.PublicKey(splitKey[1]),
73
+ };
74
+ };
75
+ const fetchCurrentSubaccounts = (driftClient) => {
76
+ return driftClient.getUsers().map((user) => user.getUserAccount());
77
+ };
78
+ const fetchUserClientsAndAccounts = (driftClient) => {
79
+ const accounts = fetchCurrentSubaccounts(driftClient);
80
+ const allUsersAndUserAccounts = accounts.map((acct) => {
81
+ return {
82
+ user: driftClient.getUser(acct.subAccountId, acct.authority),
83
+ userAccount: acct,
84
+ };
85
+ });
86
+ return allUsersAndUserAccounts;
87
+ };
88
+ const awaitAccountInitializationChainState = async (driftClient, userId, authority) => {
89
+ var _a;
90
+ const user = driftClient.getUser(userId, authority);
91
+ if (!user.isSubscribed) {
92
+ await user.subscribe();
93
+ }
94
+ let retryCount = 0;
95
+ do {
96
+ try {
97
+ await updateUserAccount(user);
98
+ if (((_a = user === null || user === void 0 ? void 0 : user.getUserAccountAndSlot()) === null || _a === void 0 ? void 0 : _a.data) !== undefined) {
99
+ return true;
100
+ }
101
+ }
102
+ catch (err) {
103
+ retryCount++;
104
+ await (0, utils_1.sleep)(ACCOUNT_INITIALIZATION_RETRY_DELAY_MS);
105
+ }
106
+ } while (retryCount < ACCOUNT_INITIALIZATION_RETRY_ATTEMPTS);
107
+ throw new Error('awaitAccountInitializationFailed');
108
+ };
109
+ /**
110
+ * Using your own callback to do the account initialization, this method will run the initialization step, switch to the drift user, await for the account to be available on chain, subscribe to the user account, and switch to the user account using the drift client.
111
+ *
112
+ * It provides extra callbacks to handle steps directly after the initialiation tx, and after fully initializing+subscribing to the account.
113
+ *
114
+ * Callbacks available:
115
+ * - initializationStep: This callback should send the transaction to initialize the user account
116
+ * - postInitializationStep: This callback will run after the successful initialization transaction, but before trying to load/subscribe to the new account
117
+ * - handleSuccessStep: This callback will run after everything has initialized+subscribed successfully
118
+ *
119
+ * // TODO : Need to do the subscription step
120
+ */
121
+ const initializeAndSubscribeToNewUserAccount = async (driftClient, userIdToInit, authority, callbacks) => {
122
+ var _a;
123
+ await driftClient.addUser(userIdToInit, authority);
124
+ const accountAlreadyExisted = await ((_a = driftClient
125
+ .getUser(userIdToInit)) === null || _a === void 0 ? void 0 : _a.exists());
126
+ // Do the account initialization step
127
+ let result = await callbacks.initializationStep();
128
+ // Fetch account to make sure it's loaded
129
+ await updateUserAccount(driftClient.getUser(userIdToInit));
130
+ if (!result) {
131
+ return 'failed_initializationStep';
132
+ }
133
+ // Do the post-initialization step
134
+ result = callbacks.postInitializationStep
135
+ ? await callbacks.postInitializationStep()
136
+ : result;
137
+ if (!result) {
138
+ return 'failed_postInitializationStep';
139
+ }
140
+ // Await the account initialization step to update the blockchain
141
+ result = await awaitAccountInitializationChainState(driftClient, userIdToInit, authority);
142
+ if (!result) {
143
+ return 'failed_awaitAccountInitializationChainState';
144
+ }
145
+ await driftClient.switchActiveUser(userIdToInit, authority);
146
+ // Do the subscription step
147
+ // Run the success handler
148
+ result = callbacks.handleSuccessStep
149
+ ? await callbacks.handleSuccessStep(accountAlreadyExisted)
150
+ : result;
151
+ if (!result) {
152
+ return 'failed_handleSuccessStep';
153
+ }
154
+ return 'ok';
155
+ };
156
+ async function updateUserAccount(user) {
157
+ const publicKey = user.userAccountPublicKey;
158
+ try {
159
+ const dataAndContext = await user.driftClient.program.account.user.fetchAndContext(publicKey, 'processed');
160
+ user.accountSubscriber.updateData(dataAndContext.data, dataAndContext.context.slot);
161
+ }
162
+ catch (e) {
163
+ // noop
164
+ }
165
+ }
166
+ const getMarketKey = (marketIndex, marketType) => `${utils_1.ENUM_UTILS.toStr(marketType)}_${marketIndex}`;
167
+ /**
168
+ * @deprecated Use createPlaceholderIWallet instead, since this is poorly named.
169
+ */
170
+ const createThrowawayIWallet = (walletPubKey) => {
171
+ const newKeypair = walletPubKey
172
+ ? new web3_js_1.Keypair({
173
+ publicKey: walletPubKey.toBytes(),
174
+ secretKey: new web3_js_1.Keypair().publicKey.toBytes(),
175
+ })
176
+ : new web3_js_1.Keypair();
177
+ const newWallet = {
178
+ publicKey: newKeypair.publicKey,
179
+ //@ts-ignore
180
+ signTransaction: () => {
181
+ return Promise.resolve();
182
+ },
183
+ //@ts-ignore
184
+ signAllTransactions: () => {
185
+ return Promise.resolve();
186
+ },
187
+ };
188
+ return newWallet;
189
+ };
190
+ /**
191
+ * Creates an IWallet wrapper, with redundant methods. If a `walletPubKey` is passed in,
192
+ * the `publicKey` will be based on that.
193
+ */
194
+ const createPlaceholderIWallet = (walletPubKey) => {
195
+ const newKeypair = walletPubKey
196
+ ? new web3_js_1.Keypair({
197
+ publicKey: walletPubKey.toBytes(),
198
+ secretKey: new web3_js_1.Keypair().publicKey.toBytes(),
199
+ })
200
+ : new web3_js_1.Keypair();
201
+ const newWallet = {
202
+ publicKey: newKeypair.publicKey,
203
+ //@ts-ignore
204
+ signTransaction: () => {
205
+ return Promise.resolve();
206
+ },
207
+ //@ts-ignore
208
+ signAllTransactions: () => {
209
+ return Promise.resolve();
210
+ },
211
+ };
212
+ return newWallet;
213
+ };
214
+ const getSignatureVerificationMessageForSettings = (authority, signTs) => {
215
+ return new TextEncoder().encode(`Verify you are the owner of this wallet to update trade settings: \n${authority.toBase58()}\n\nThis signature will be valid for the next 30 minutes.\n\nTS: ${signTs.toString()}`);
216
+ };
217
+ const verifySignature = (signature, message, pubKey) => {
218
+ return tweetnacl_1.sign.detached.verify(message, signature, pubKey.toBytes());
219
+ };
220
+ const hashSignature = async (signature) => {
221
+ bcryptjs_react_1.default.setRandomFallback((num) => {
222
+ return Array.from(tweetnacl_1.default.randomBytes(num));
223
+ });
224
+ const hashedSignature = await bcryptjs_react_1.default.hash(signature, bcryptjs_react_1.default.genSaltSync(10));
225
+ return hashedSignature;
226
+ };
227
+ const compareSignatures = async (original, hashed) => {
228
+ const signaturesMatch = await bcryptjs_react_1.default.compare(original, hashed);
229
+ return signaturesMatch;
230
+ };
231
+ /* Trading-related helper functions */
232
+ const calculateAverageEntryPrice = (quoteAssetAmount, baseAssetAmount) => {
233
+ if (baseAssetAmount.eqZero())
234
+ return sdk_1.BigNum.zero();
235
+ return sdk_1.BigNum.from(quoteAssetAmount.val
236
+ .mul(sdk_1.PRICE_PRECISION)
237
+ .mul(sdk_1.AMM_TO_QUOTE_PRECISION_RATIO)
238
+ .div(baseAssetAmount.shiftTo(sdk_1.BASE_PRECISION_EXP).val)
239
+ .abs(), sdk_1.PRICE_PRECISION_EXP);
240
+ };
241
+ const getMarketOrderLimitPrice = ({ direction, baselinePrice, slippageTolerance, }) => {
242
+ let limitPrice;
243
+ if (!baselinePrice)
244
+ return sdk_1.ZERO;
245
+ if (slippageTolerance === 0)
246
+ return baselinePrice;
247
+ // infinite slippage capped at 15% currently
248
+ if (slippageTolerance == undefined)
249
+ slippageTolerance = 15;
250
+ // if manually entered, cap at 99%
251
+ if (slippageTolerance > 99)
252
+ slippageTolerance = 99;
253
+ let limitPricePctDiff;
254
+ if ((0, sdk_1.isVariant)(direction, 'long')) {
255
+ limitPricePctDiff = sdk_1.PRICE_PRECISION.add(new sdk_1.BN(slippageTolerance * sdk_1.PRICE_PRECISION.toNumber()).div(new sdk_1.BN(100)));
256
+ limitPrice = baselinePrice.mul(limitPricePctDiff).div(sdk_1.PRICE_PRECISION);
257
+ }
258
+ else {
259
+ limitPricePctDiff = sdk_1.PRICE_PRECISION.sub(new sdk_1.BN(slippageTolerance * sdk_1.PRICE_PRECISION.toNumber()).div(new sdk_1.BN(100)));
260
+ limitPrice = baselinePrice.mul(limitPricePctDiff).div(sdk_1.PRICE_PRECISION);
261
+ }
262
+ return limitPrice;
263
+ };
264
+ const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, }) => {
265
+ let auctionStartPrice;
266
+ let auctionEndPrice;
267
+ let constrainedBySlippage;
268
+ const auctionEndPriceBuffer = sdk_1.BigNum.from(sdk_1.PRICE_PRECISION).scale(Math.abs(auctionEndPriceOffset * 100), 10000).val;
269
+ const auctionStartPriceBuffer = sdk_1.BigNum.from(startPriceFromSettings).scale(Math.abs(auctionStartPriceOffset * 100), 10000).val;
270
+ if ((0, sdk_1.isVariant)(direction, 'long')) {
271
+ auctionStartPrice = startPriceFromSettings.sub(auctionStartPriceBuffer);
272
+ const worstPriceToUse = sdk_1.BN.max(endPriceFromSettings, startPriceFromSettings); // Handles edge cases like if the worst price on the book was better than the oracle price, and the settings are asking to be relative to the oracle price
273
+ auctionEndPrice = sdk_1.PRICE_PRECISION.add(auctionEndPriceBuffer)
274
+ .mul(worstPriceToUse)
275
+ .div(sdk_1.PRICE_PRECISION);
276
+ constrainedBySlippage = limitPrice.lt(auctionEndPrice);
277
+ // if forceUpToSlippage is passed, use max slippage price as end price
278
+ if (forceUpToSlippage) {
279
+ auctionEndPrice = limitPrice;
280
+ constrainedBySlippage = false;
281
+ }
282
+ else {
283
+ // use BEST (limit price, auction end price) as end price
284
+ auctionEndPrice = sdk_1.BN.min(limitPrice, auctionEndPrice);
285
+ }
286
+ // apply additional buffer if provided
287
+ if (additionalEndPriceBuffer) {
288
+ auctionEndPrice = auctionEndPrice.add(additionalEndPriceBuffer);
289
+ constrainedBySlippage = limitPrice.lt(auctionEndPrice);
290
+ }
291
+ auctionStartPrice = sdk_1.BN.min(auctionStartPrice, auctionEndPrice);
292
+ }
293
+ else {
294
+ auctionStartPrice = startPriceFromSettings.add(auctionStartPriceBuffer);
295
+ const worstPriceToUse = sdk_1.BN.min(endPriceFromSettings, startPriceFromSettings); // Handles edge cases like if the worst price on the book was better than the oracle price, and the settings are asking to be relative to the oracle price
296
+ auctionEndPrice = sdk_1.PRICE_PRECISION.sub(auctionEndPriceBuffer)
297
+ .mul(worstPriceToUse)
298
+ .div(sdk_1.PRICE_PRECISION);
299
+ constrainedBySlippage = limitPrice.gt(auctionEndPrice);
300
+ // if forceUpToSlippage is passed, use max slippage price as end price
301
+ if (forceUpToSlippage) {
302
+ auctionEndPrice = limitPrice;
303
+ constrainedBySlippage = false;
304
+ }
305
+ else {
306
+ // use BEST (limit price, auction end price) as end price
307
+ auctionEndPrice = sdk_1.BN.max(limitPrice, auctionEndPrice);
308
+ }
309
+ // apply additional buffer if provided
310
+ if (additionalEndPriceBuffer) {
311
+ auctionEndPrice = auctionEndPrice.sub(additionalEndPriceBuffer);
312
+ constrainedBySlippage = limitPrice.gt(auctionEndPrice);
313
+ }
314
+ auctionStartPrice = sdk_1.BN.max(auctionStartPrice, auctionEndPrice);
315
+ }
316
+ return {
317
+ auctionStartPrice,
318
+ auctionEndPrice,
319
+ auctionDuration: duration,
320
+ constrainedBySlippage,
321
+ };
322
+ };
323
+ /**
324
+ * Helper function which derived market order params from the CORE data that is used to create them.
325
+ * @param param0
326
+ * @returns
327
+ */
328
+ const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, }) => {
329
+ const priceObject = getPriceObject({
330
+ oraclePrice,
331
+ markPrice,
332
+ bestOffer: bestPrice,
333
+ entryPrice,
334
+ worstPrice,
335
+ direction,
336
+ });
337
+ // max slippage price
338
+ let limitPrice = getMarketOrderLimitPrice({
339
+ direction,
340
+ baselinePrice: priceObject[auctionStartPriceOffsetFrom],
341
+ slippageTolerance: allowInfSlippage ? undefined : slippageTolerance,
342
+ });
343
+ if (additionalEndPriceBuffer) {
344
+ limitPrice = (0, sdk_1.isVariant)(direction, 'long')
345
+ ? limitPrice.add(additionalEndPriceBuffer)
346
+ : limitPrice.sub(additionalEndPriceBuffer);
347
+ }
348
+ const auctionParams = getMarketAuctionParams({
349
+ direction,
350
+ startPriceFromSettings: priceObject[auctionStartPriceOffsetFrom],
351
+ endPriceFromSettings: priceObject[auctionEndPriceOffsetFrom],
352
+ limitPrice,
353
+ duration: auctionDuration,
354
+ auctionStartPriceOffset: auctionStartPriceOffset,
355
+ auctionEndPriceOffset: auctionEndPriceOffset,
356
+ additionalEndPriceBuffer,
357
+ forceUpToSlippage,
358
+ });
359
+ let orderParams = (0, sdk_1.getMarketOrderParams)({
360
+ marketType,
361
+ marketIndex,
362
+ direction,
363
+ baseAssetAmount: maxLeverageSelected ? maxLeverageOrderSize : baseAmount,
364
+ reduceOnly,
365
+ price: allowInfSlippage ? undefined : limitPrice,
366
+ ...auctionParams,
367
+ });
368
+ if (isOracleOrder) {
369
+ // wont work if oracle is zero
370
+ if (!oraclePrice.eq(sdk_1.ZERO)) {
371
+ // BEST (slippageLimitPrice, auctionEndPrice)
372
+ const oracleAuctionEndPrice = (0, sdk_1.isVariant)(direction, 'long')
373
+ ? sdk_1.BN.min(limitPrice, auctionParams.auctionEndPrice)
374
+ : sdk_1.BN.max(limitPrice, auctionParams.auctionEndPrice);
375
+ const oracleAuctionParams = (0, sdk_1.deriveOracleAuctionParams)({
376
+ direction: direction,
377
+ oraclePrice,
378
+ auctionStartPrice: auctionParams.auctionStartPrice,
379
+ auctionEndPrice: oracleAuctionEndPrice,
380
+ limitPrice: oracleAuctionEndPrice,
381
+ auctionPriceCaps: auctionPriceCaps,
382
+ });
383
+ orderParams = {
384
+ ...orderParams,
385
+ ...oracleAuctionParams,
386
+ price: undefined,
387
+ orderType: sdk_1.OrderType.ORACLE,
388
+ };
389
+ }
390
+ }
391
+ return orderParams;
392
+ };
393
+ const getLimitAuctionParams = ({ direction, inputPrice, startPriceFromSettings, duration, auctionStartPriceOffset, oraclePriceBands, }) => {
394
+ let limitAuctionParams = trade_1.EMPTY_AUCTION_PARAMS;
395
+ const auctionStartPriceBuffer = inputPrice.scale(Math.abs(auctionStartPriceOffset * 100), 10000).val;
396
+ if ((0, sdk_1.isVariant)(direction, 'long') &&
397
+ startPriceFromSettings &&
398
+ startPriceFromSettings.lt(inputPrice.val) &&
399
+ startPriceFromSettings.gt(sdk_1.ZERO)) {
400
+ limitAuctionParams = {
401
+ auctionStartPrice: startPriceFromSettings.sub(auctionStartPriceBuffer),
402
+ auctionEndPrice: inputPrice.val,
403
+ auctionDuration: duration,
404
+ };
405
+ }
406
+ else if ((0, sdk_1.isVariant)(direction, 'short') &&
407
+ startPriceFromSettings &&
408
+ startPriceFromSettings.gt(sdk_1.ZERO) &&
409
+ startPriceFromSettings.gt(inputPrice.val)) {
410
+ limitAuctionParams = {
411
+ auctionStartPrice: startPriceFromSettings.add(auctionStartPriceBuffer),
412
+ auctionEndPrice: inputPrice.val,
413
+ auctionDuration: duration,
414
+ };
415
+ }
416
+ if (oraclePriceBands && limitAuctionParams.auctionDuration) {
417
+ const [minPrice, maxPrice] = oraclePriceBands;
418
+ // start and end price cant be outside of the oracle price bands
419
+ limitAuctionParams.auctionStartPrice = sdk_1.BN.max(sdk_1.BN.min(limitAuctionParams.auctionStartPrice, maxPrice), minPrice);
420
+ limitAuctionParams.auctionEndPrice = sdk_1.BN.max(sdk_1.BN.min(limitAuctionParams.auctionEndPrice, maxPrice), minPrice);
421
+ }
422
+ return limitAuctionParams;
423
+ };
424
+ const getPriceObject = ({ oraclePrice, bestOffer, entryPrice, worstPrice, markPrice, direction, }) => {
425
+ let best;
426
+ const nonZeroOptions = [oraclePrice, bestOffer, markPrice].filter((price) => price !== undefined && (price === null || price === void 0 ? void 0 : price.gt(sdk_1.ZERO)));
427
+ if (nonZeroOptions.length === 0) {
428
+ // console.error('Unable to create valid auction params');
429
+ return {
430
+ oracle: sdk_1.ZERO,
431
+ bestOffer: sdk_1.ZERO,
432
+ entry: sdk_1.ZERO,
433
+ best: sdk_1.ZERO,
434
+ worst: sdk_1.ZERO,
435
+ mark: sdk_1.ZERO,
436
+ };
437
+ }
438
+ if ((0, sdk_1.isVariant)(direction, 'long')) {
439
+ best = nonZeroOptions.reduce((a, b) => (a.lt(b) ? a : b)); // lowest price
440
+ }
441
+ else {
442
+ best = nonZeroOptions.reduce((a, b) => (a.gt(b) ? a : b)); // highest price
443
+ }
444
+ // if zero values come through, fallback to nonzero value
445
+ return {
446
+ oracle: (oraclePrice === null || oraclePrice === void 0 ? void 0 : oraclePrice.gt(sdk_1.ZERO)) ? oraclePrice : best,
447
+ bestOffer: (bestOffer === null || bestOffer === void 0 ? void 0 : bestOffer.gt(sdk_1.ZERO)) ? bestOffer : best,
448
+ entry: entryPrice,
449
+ best,
450
+ worst: worstPrice,
451
+ mark: (markPrice === null || markPrice === void 0 ? void 0 : markPrice.gt(sdk_1.ZERO)) ? markPrice : best,
452
+ };
453
+ };
454
+ /* LP Utils */
455
+ const getLpSharesAmountForQuote = (driftClient, marketIndex, quoteAmount) => {
456
+ const tenMillionBigNum = sdk_1.BigNum.fromPrint('10000000', sdk_1.QUOTE_PRECISION_EXP);
457
+ const pricePerLpShare = sdk_1.BigNum.from(driftClient.getQuoteValuePerLpShare(marketIndex), sdk_1.QUOTE_PRECISION_EXP);
458
+ return sdk_1.BigNum.from(quoteAmount, sdk_1.QUOTE_PRECISION_EXP)
459
+ .scale(tenMillionBigNum.toNum(), pricePerLpShare.mul(tenMillionBigNum).toNum())
460
+ .shiftTo(sdk_1.AMM_RESERVE_PRECISION_EXP);
461
+ };
462
+ const getQuoteValueForLpShares = (driftClient, marketIndex, sharesAmount) => {
463
+ const pricePerLpShare = sdk_1.BigNum.from(driftClient.getQuoteValuePerLpShare(marketIndex), sdk_1.QUOTE_PRECISION_EXP).shiftTo(sdk_1.AMM_RESERVE_PRECISION_EXP);
464
+ const lpSharesBigNum = sdk_1.BigNum.from(sharesAmount, sdk_1.AMM_RESERVE_PRECISION_EXP);
465
+ return lpSharesBigNum.mul(pricePerLpShare).shiftTo(sdk_1.QUOTE_PRECISION_EXP);
466
+ };
467
+ const getTokenAddress = (mintAddress, userPubKey) => {
468
+ return (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, userPubKey, true);
469
+ };
470
+ const getBalanceFromTokenAccountResult = (account) => {
471
+ var _a, _b, _c, _d;
472
+ return (_d = (_c = (_b = (_a = account === null || account === void 0 ? void 0 : account.account.data) === null || _a === void 0 ? void 0 : _a.parsed) === null || _b === void 0 ? void 0 : _b.info) === null || _c === void 0 ? void 0 : _c.tokenAmount) === null || _d === void 0 ? void 0 : _d.uiAmount;
473
+ };
474
+ const getTokenAccount = async (connection, mintAddress, userPubKey) => {
475
+ const tokenAccounts = await connection.getParsedTokenAccountsByOwner(userPubKey, { mint: mintAddress });
476
+ const associatedAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, userPubKey, true);
477
+ const targetAccount = tokenAccounts.value.filter((account) => account.pubkey.equals(associatedAddress))[0] || tokenAccounts.value[0];
478
+ const anotherBalanceExists = tokenAccounts.value.find((account) => {
479
+ return (!!getBalanceFromTokenAccountResult(account) &&
480
+ !account.pubkey.equals(targetAccount.pubkey));
481
+ });
482
+ let tokenAccountWarning = false;
483
+ if (anotherBalanceExists) {
484
+ tokenAccountWarning = true;
485
+ }
486
+ return {
487
+ tokenAccount: targetAccount,
488
+ tokenAccountWarning,
489
+ };
490
+ };
491
+ const getMultipleAccounts = async (connection, keys, commitment) => {
492
+ const result = await Promise.all(chunks(keys, 99).map((chunk) => getMultipleAccountsCore(connection, chunk, commitment)));
493
+ const array = result
494
+ .map((a) => a.array
495
+ .map((acc) => {
496
+ if (!acc) {
497
+ return undefined;
498
+ }
499
+ const { data, ...rest } = acc;
500
+ const obj = {
501
+ ...rest,
502
+ data: Buffer.from(data[0], 'base64'),
503
+ };
504
+ return obj;
505
+ })
506
+ .filter((_) => _))
507
+ .flat();
508
+ return { keys, array };
509
+ };
510
+ const getMultipleAccountsCore = async (connection, keys, commitment) => {
511
+ const args = connection._buildArgs([keys], commitment, 'base64');
512
+ const unsafeRes = await connection._rpcRequest('getMultipleAccounts', args);
513
+ if (unsafeRes.error) {
514
+ throw new Error('failed to get info about account ' + unsafeRes.error.message);
515
+ }
516
+ if (unsafeRes.result.value) {
517
+ const array = unsafeRes.result.value;
518
+ return { keys, array };
519
+ }
520
+ // TODO: fix
521
+ throw new Error();
522
+ };
523
+ const userExists = async (driftClient, userId, authority) => {
524
+ let userAccountExists = false;
525
+ try {
526
+ const user = driftClient.getUser(userId, authority);
527
+ userAccountExists = await user.exists();
528
+ }
529
+ catch (e) {
530
+ // user account does not exist so we leave userAccountExists false
531
+ }
532
+ return userAccountExists;
533
+ };
534
+ function chunks(array, size) {
535
+ return Array.apply(0, new Array(Math.ceil(array.length / size))).map((_, index) => array.slice(index * size, (index + 1) * size));
536
+ }
537
+ /**
538
+ * Trim trailing zeros from a numerical string
539
+ * @param str - numerical string to format
540
+ * @param zerosToShow - max number of zeros to show after the decimal. Similar to number.toFixed() but won't trim non-zero values. Optional, default value is 1
541
+ */
542
+ const trimTrailingZeros = (str, zerosToShow = 1) => {
543
+ // Ignore strings with no decimal point
544
+ if (!str.includes('.'))
545
+ return str;
546
+ const sides = str.split('.');
547
+ sides[1] = sides[1].replace(/0+$/, '');
548
+ if (sides[1].length < zerosToShow) {
549
+ const zerosToAdd = zerosToShow - sides[1].length;
550
+ sides[1] = `${sides[1]}${Array(zerosToAdd).fill('0').join('')}`;
551
+ }
552
+ if (sides[1].length === 0) {
553
+ return sides[0];
554
+ }
555
+ else {
556
+ return sides.join('.');
557
+ }
558
+ };
559
+ const formatTokenInputCurried = (setAmount, spotMarketConfig) => (newAmount) => {
560
+ var _a, _b;
561
+ if (isNaN(+newAmount))
562
+ return;
563
+ if (newAmount === '') {
564
+ setAmount('');
565
+ return;
566
+ }
567
+ const lastChar = newAmount[newAmount.length - 1];
568
+ // if last char of string is a decimal point, don't format
569
+ if (lastChar === '.') {
570
+ setAmount(newAmount);
571
+ return;
572
+ }
573
+ if (lastChar === '0') {
574
+ // if last char of string is a zero in the decimal places, cut it off if it exceeds precision
575
+ const numOfDigitsAfterDecimal = (_b = (_a = newAmount.split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
576
+ if (numOfDigitsAfterDecimal > spotMarketConfig.precisionExp.toNumber()) {
577
+ setAmount(newAmount.slice(0, -1));
578
+ }
579
+ else {
580
+ setAmount(newAmount);
581
+ }
582
+ return;
583
+ }
584
+ const formattedAmount = Number((+newAmount).toFixed(spotMarketConfig.precisionExp.toNumber()));
585
+ setAmount(formattedAmount.toString());
586
+ };
587
+ // --- Export The Utils
588
+ exports.COMMON_UI_UTILS = {
589
+ abbreviateAddress,
590
+ calculateAverageEntryPrice,
591
+ chunks,
592
+ compareSignatures,
593
+ createThrowawayIWallet,
594
+ createPlaceholderIWallet,
595
+ deriveMarketOrderParams,
596
+ fetchCurrentSubaccounts,
597
+ fetchUserClientsAndAccounts,
598
+ formatTokenInputCurried,
599
+ getBalanceFromTokenAccountResult,
600
+ getIdAndAuthorityFromKey,
601
+ getLimitAuctionParams,
602
+ getLpSharesAmountForQuote,
603
+ getMarketAuctionParams,
604
+ getMarketKey,
605
+ getMarketOrderLimitPrice,
606
+ getMultipleAccounts,
607
+ getMultipleAccountsCore,
608
+ getPriceObject,
609
+ getQuoteValueForLpShares,
610
+ getSignatureVerificationMessageForSettings,
611
+ getTokenAccount,
612
+ getTokenAddress,
613
+ getUserKey,
614
+ hashSignature,
615
+ initializeAndSubscribeToNewUserAccount,
616
+ userExists,
617
+ verifySignature,
618
+ trimTrailingZeros,
619
+ ...user_1.USER_UTILS,
620
+ ...trading_1.TRADING_UTILS,
621
+ ...market_1.MARKET_UTILS,
622
+ ...order_1.ORDER_COMMON_UTILS,
623
+ };
624
+ //# sourceMappingURL=commonUiUtils.js.map