@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,608 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COMMON_UTILS = exports.getTieredSortScore = exports.aprFromApy = exports.MultiSwitch = exports.Counter = exports.Ref = exports.getAnchorEnumString = exports.orderIsNull = exports.getPriceForUIOrderRecord = exports.getPriceForOrderRecord = exports.getPriceForBaseAndQuoteAmount = exports.filterTradeRecordsFromUIOrderRecords = exports.filterTradeRecordsFromOrderActionRecords = exports.uiOrderActionRecordIsTrade = exports.orderActionRecordIsTrade = exports.getUIOrderRecordsLaterThanTarget = exports.getLatestOfTwoOrderRecords = exports.getLatestOfTwoUIOrderRecords = exports.sortOrderRecords = exports.sortUIOrderRecords = exports.sortUIOrderActionRecords = exports.sortUIMatchedOrderRecordAndAction = exports.getSortScoreForOrderActionRecords = exports.getTradeInfoFromActionRecord = exports.getSortScoreForOrderRecords = exports.decodeStringifiableObject = exports.encodeStringifiableObject = exports.sleep = exports.ENUM_UTILS = exports.matchEnum = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const insuranceFund_1 = require("./insuranceFund");
6
+ const matchEnum = (enum1, enum2) => {
7
+ return JSON.stringify(enum1) === JSON.stringify(enum2);
8
+ };
9
+ exports.matchEnum = matchEnum;
10
+ function enumToObj(enumStr) {
11
+ if (!enumStr)
12
+ return undefined;
13
+ return {
14
+ [enumStr !== null && enumStr !== void 0 ? enumStr : '']: {},
15
+ };
16
+ }
17
+ function enumToStr(enumStr) {
18
+ var _a;
19
+ return (_a = Object.keys(enumStr !== null && enumStr !== void 0 ? enumStr : {})) === null || _a === void 0 ? void 0 : _a[0];
20
+ }
21
+ exports.ENUM_UTILS = {
22
+ match: exports.matchEnum,
23
+ toObj: enumToObj,
24
+ toStr: enumToStr,
25
+ };
26
+ async function sleep(ms) {
27
+ return new Promise((resolve) => setTimeout(resolve, ms));
28
+ }
29
+ exports.sleep = sleep;
30
+ const getStringifiableObjectEntry = (value) => {
31
+ // If BN
32
+ // if (value instanceof BN) { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */
33
+ if (Object.keys(value).sort().join(',') === 'length,negative,red,words') {
34
+ return [value.toString(), '_bgnm_'];
35
+ }
36
+ // If PublicKey
37
+ // if (value instanceof PublicKey) { { /* This method would be much safer but don't think it's possible to ensure that instances of classes match when they're in different npm packages */
38
+ if (Object.keys(value).sort().join(',') === '_bn') {
39
+ return [value.toString(), '_pbky_'];
40
+ }
41
+ if (typeof value === 'object') {
42
+ return [(0, exports.encodeStringifiableObject)(value), ''];
43
+ }
44
+ return [value, ''];
45
+ };
46
+ /**
47
+ * Converts an objects with potential Pubkeys and BNs in it into a form that can be JSON stringified. When pubkeys get converted a _pbky_ suffix will be added to their key, and _bgnm_ for BNs.
48
+ *
49
+ * e.g.
50
+ * input : {
51
+ * QuoteAmount: BN
52
+ * }
53
+ *
54
+ * output: {
55
+ * _bgnm_QuoteAmount: string
56
+ * }
57
+ * @param value
58
+ * @returns
59
+ */
60
+ const encodeStringifiableObject = (value) => {
61
+ if (typeof value !== 'object')
62
+ return value;
63
+ if (Array.isArray(value)) {
64
+ return value.map((entry) => (0, exports.encodeStringifiableObject)(entry));
65
+ }
66
+ const buildJsonObject = {};
67
+ if (!value)
68
+ return value;
69
+ Object.entries(value).forEach(([key, val]) => {
70
+ const [convertedVal, keyTag] = getStringifiableObjectEntry(val);
71
+ buildJsonObject[`${keyTag}${key}`] = convertedVal;
72
+ });
73
+ return buildJsonObject;
74
+ };
75
+ exports.encodeStringifiableObject = encodeStringifiableObject;
76
+ /**
77
+ * Converts a parsed object with potential Pubkeys and BNs in it (in string form) to their proper form. Pubkey values must have a key starting in _pbky_ and BN values must have a key starting in _bnnm_
78
+ *
79
+ * * e.g.
80
+ * input : {
81
+ * _bgnm_QuoteAmount: string
82
+ * }
83
+ *
84
+ * output: {
85
+ * QuoteAmount: BN
86
+ * }
87
+ * @param value
88
+ * @returns
89
+ */
90
+ const decodeStringifiableObject = (value) => {
91
+ if (typeof value !== 'object')
92
+ return value;
93
+ if (Array.isArray(value)) {
94
+ return value.map((entry) => (0, exports.decodeStringifiableObject)(entry));
95
+ }
96
+ const buildJsonObject = {};
97
+ Object.entries(value)
98
+ .filter((val) => val != undefined && val != null)
99
+ .forEach(([key, val]) => {
100
+ if (key.match(/^_pbky_/)) {
101
+ buildJsonObject[key.replace('_pbky_', '')] = new sdk_1.PublicKey(val);
102
+ return;
103
+ }
104
+ if (key.match(/^_bgnm_/)) {
105
+ buildJsonObject[key.replace('_bgnm_', '')] = new sdk_1.BN(val);
106
+ return;
107
+ }
108
+ if (typeof val === 'object' && val != undefined && val != null) {
109
+ buildJsonObject[key] = (0, exports.decodeStringifiableObject)(val);
110
+ return;
111
+ }
112
+ buildJsonObject[key] = val;
113
+ });
114
+ return buildJsonObject;
115
+ };
116
+ exports.decodeStringifiableObject = decodeStringifiableObject;
117
+ const getChronologicalValueForOrderAction = (action) => {
118
+ return (0, exports.matchEnum)(action, sdk_1.OrderAction.PLACE)
119
+ ? 0
120
+ : (0, exports.matchEnum)(action, sdk_1.OrderAction.FILL)
121
+ ? 1
122
+ : 2;
123
+ };
124
+ /**
125
+ * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal
126
+ * @param orderA
127
+ * @param orderB
128
+ * @returns
129
+ */
130
+ const getSortScoreForOrderRecords = (orderA, orderB) => {
131
+ if (orderA.slot !== orderB.slot) {
132
+ return orderA.slot > orderB.slot ? 1 : -1;
133
+ }
134
+ return 0;
135
+ };
136
+ exports.getSortScoreForOrderRecords = getSortScoreForOrderRecords;
137
+ const getTradeInfoFromActionRecord = (actionRecord) => {
138
+ return {
139
+ ts: actionRecord.ts,
140
+ baseAssetAmount: actionRecord.taker
141
+ ? actionRecord.takerOrderBaseAssetAmount
142
+ : actionRecord.makerOrderBaseAssetAmount,
143
+ baseAssetAmountFilled: actionRecord.taker
144
+ ? actionRecord.takerOrderCumulativeBaseAssetAmountFilled
145
+ : actionRecord.makerOrderCumulativeBaseAssetAmountFilled,
146
+ quoteAssetAmountFilled: actionRecord.taker
147
+ ? actionRecord.takerOrderCumulativeQuoteAssetAmountFilled
148
+ : actionRecord.makerOrderCumulativeQuoteAssetAmountFilled,
149
+ };
150
+ };
151
+ exports.getTradeInfoFromActionRecord = getTradeInfoFromActionRecord;
152
+ /**
153
+ * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal
154
+ * @param orderA
155
+ * @param orderB
156
+ * @returns
157
+ */
158
+ const getSortScoreForOrderActionRecords = (orderA, orderB) => {
159
+ if (orderA.slot !== orderB.slot) {
160
+ return orderA.slot > orderB.slot ? 1 : -1;
161
+ }
162
+ if (!(0, exports.matchEnum)(orderA.action, orderB.action)) {
163
+ // @ts-ignore
164
+ const orderAActionVal = getChronologicalValueForOrderAction(orderA.action);
165
+ // @ts-ignore
166
+ const orderBActionVal = getChronologicalValueForOrderAction(orderB.action);
167
+ return orderAActionVal > orderBActionVal ? 1 : -1;
168
+ }
169
+ // @ts-ignore
170
+ if (orderA.fillRecordId && orderB.fillRecordId) {
171
+ if (!orderA.fillRecordId.eq(orderB.fillRecordId)) {
172
+ // @ts-ignore
173
+ return orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;
174
+ }
175
+ }
176
+ return 0;
177
+ };
178
+ exports.getSortScoreForOrderActionRecords = getSortScoreForOrderActionRecords;
179
+ const sortUIMatchedOrderRecordAndAction = (records, direction = 'desc') => {
180
+ const ascSortedRecords = records.sort((a, b) => (0, exports.getSortScoreForOrderActionRecords)(a.actionRecord, b.actionRecord));
181
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
182
+ };
183
+ exports.sortUIMatchedOrderRecordAndAction = sortUIMatchedOrderRecordAndAction;
184
+ const sortUIOrderActionRecords = (records, direction = 'desc') => {
185
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderActionRecords);
186
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
187
+ };
188
+ exports.sortUIOrderActionRecords = sortUIOrderActionRecords;
189
+ const sortUIOrderRecords = (records, direction = 'desc') => {
190
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderRecords);
191
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
192
+ };
193
+ exports.sortUIOrderRecords = sortUIOrderRecords;
194
+ const sortOrderRecords = (records, direction = 'desc') => {
195
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderRecords);
196
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
197
+ };
198
+ exports.sortOrderRecords = sortOrderRecords;
199
+ const getLatestOfTwoUIOrderRecords = (orderA, orderB) => {
200
+ return (0, exports.getSortScoreForOrderRecords)(orderA, orderB) === 1 ? orderA : orderB;
201
+ };
202
+ exports.getLatestOfTwoUIOrderRecords = getLatestOfTwoUIOrderRecords;
203
+ const getLatestOfTwoOrderRecords = (orderA, orderB) => {
204
+ return (0, exports.getSortScoreForOrderRecords)(orderA, orderB) === 1 ? orderA : orderB;
205
+ };
206
+ exports.getLatestOfTwoOrderRecords = getLatestOfTwoOrderRecords;
207
+ const getUIOrderRecordsLaterThanTarget = (target, records) => records.filter((record) => (0, exports.getLatestOfTwoUIOrderRecords)(record, target) === record);
208
+ exports.getUIOrderRecordsLaterThanTarget = getUIOrderRecordsLaterThanTarget;
209
+ // Trade records are order records which have been filled
210
+ const orderActionRecordIsTrade = (orderRecord) => orderRecord.baseAssetAmountFilled.gt(sdk_1.ZERO) &&
211
+ // @ts-ignore
212
+ (0, exports.matchEnum)(orderRecord.action, sdk_1.OrderAction.FILL) &&
213
+ true;
214
+ exports.orderActionRecordIsTrade = orderActionRecordIsTrade;
215
+ const uiOrderActionRecordIsTrade = (orderRecord) => orderRecord.baseAssetAmountFilled.gtZero() &&
216
+ (0, exports.matchEnum)(orderRecord.action, sdk_1.OrderAction.FILL) &&
217
+ true;
218
+ exports.uiOrderActionRecordIsTrade = uiOrderActionRecordIsTrade;
219
+ // Trade records are order records which have been filled
220
+ const filterTradeRecordsFromOrderActionRecords = (orderRecords) => orderRecords.filter(exports.orderActionRecordIsTrade);
221
+ exports.filterTradeRecordsFromOrderActionRecords = filterTradeRecordsFromOrderActionRecords;
222
+ // Trade records are order records which have been filled
223
+ const filterTradeRecordsFromUIOrderRecords = (orderRecords) => orderRecords.filter(exports.uiOrderActionRecordIsTrade);
224
+ exports.filterTradeRecordsFromUIOrderRecords = filterTradeRecordsFromUIOrderRecords;
225
+ /**
226
+ * Returns the average price for a given base amount and quote amount.
227
+ * @param quoteAmount
228
+ * @param baseAmount
229
+ * @returns PRICE_PRECISION
230
+ */
231
+ const getPriceForBaseAndQuoteAmount = (quoteAmount, baseAmount) => {
232
+ return quoteAmount
233
+ .mul(sdk_1.PRICE_PRECISION)
234
+ .mul(sdk_1.BASE_PRECISION)
235
+ .div(sdk_1.QUOTE_PRECISION)
236
+ .div(sdk_1.BigNum.from(baseAmount, sdk_1.BASE_PRECISION_EXP).val);
237
+ };
238
+ exports.getPriceForBaseAndQuoteAmount = getPriceForBaseAndQuoteAmount;
239
+ const getPriceForOrderRecord = (orderRecord) => {
240
+ return (0, exports.getPriceForBaseAndQuoteAmount)(
241
+ // @ts-ignore
242
+ orderRecord.quoteAssetAmountFilled,
243
+ // @ts-ignore
244
+ orderRecord.baseAssetAmountFilled);
245
+ };
246
+ exports.getPriceForOrderRecord = getPriceForOrderRecord;
247
+ const getPriceForUIOrderRecord = (orderRecord) => {
248
+ return orderRecord.quoteAssetAmountFilled
249
+ .shiftTo(sdk_1.AMM_RESERVE_PRECISION_EXP)
250
+ .shift(sdk_1.PRICE_PRECISION_EXP)
251
+ .div(orderRecord.baseAssetAmountFilled.shiftTo(sdk_1.BASE_PRECISION_EXP))
252
+ .shiftTo(sdk_1.PRICE_PRECISION_EXP);
253
+ };
254
+ exports.getPriceForUIOrderRecord = getPriceForUIOrderRecord;
255
+ const orderIsNull = (order, side) => {
256
+ return side === 'taker' ? !order.taker : !order.maker;
257
+ };
258
+ exports.orderIsNull = orderIsNull;
259
+ const getAnchorEnumString = (enumVal) => {
260
+ return Object.keys(enumVal)[0];
261
+ };
262
+ exports.getAnchorEnumString = getAnchorEnumString;
263
+ class Ref {
264
+ constructor(val) {
265
+ this.val = val;
266
+ }
267
+ set(val) {
268
+ this.val = val;
269
+ }
270
+ get() {
271
+ return this.val;
272
+ }
273
+ }
274
+ exports.Ref = Ref;
275
+ class Counter {
276
+ constructor() {
277
+ this.val = 0;
278
+ }
279
+ get() {
280
+ return this.val;
281
+ }
282
+ increment(value = 1) {
283
+ this.val += value;
284
+ }
285
+ reset() {
286
+ this.val = 0;
287
+ }
288
+ }
289
+ exports.Counter = Counter;
290
+ /**
291
+ * A class which allows a group of switches to seperately turn a multiswitch on or off. The base state is the state of the "multiswitch" when all of the constituent switches are off. When any of the switches are "on" then the multiswitch flips to the opposite state
292
+ *
293
+ * If baseState is on => any switch being "on" will turn the multiswitch off.
294
+ * If baseState is off => any switch being "off" will turn the multiswitch off.
295
+ */
296
+ class MultiSwitch {
297
+ constructor(baseState = 'off') {
298
+ this.baseState = baseState;
299
+ this.switches = [];
300
+ this.switchValue = 0;
301
+ }
302
+ getSwitchKey(key) {
303
+ // If first time using switch, add to list of switches
304
+ if (!this.switches.includes(key)) {
305
+ this.switches.push(key);
306
+ }
307
+ const switchIndex = this.switches.indexOf(key);
308
+ return 2 ** switchIndex;
309
+ }
310
+ switchOn(key) {
311
+ if (this.baseState === 'on') {
312
+ this._switchOff(key);
313
+ return;
314
+ }
315
+ this._switchOn(key);
316
+ }
317
+ switchOff(key) {
318
+ if (this.baseState === 'on') {
319
+ this._switchOn(key);
320
+ return;
321
+ }
322
+ this._switchOff(key);
323
+ }
324
+ _switchOff(key) {
325
+ const switchKey = this.getSwitchKey(key);
326
+ this.switchValue &= ~switchKey;
327
+ }
328
+ _switchOn(key) {
329
+ const switchKey = this.getSwitchKey(key);
330
+ this.switchValue |= switchKey;
331
+ }
332
+ get isOn() {
333
+ // When the base state is on, then if any switch is on the multi-switch is off
334
+ if (this.baseState === 'on') {
335
+ return this.switchValue === 0;
336
+ }
337
+ if (this.baseState === 'off') {
338
+ return this.switchValue > 0;
339
+ }
340
+ }
341
+ }
342
+ exports.MultiSwitch = MultiSwitch;
343
+ /**
344
+ * Returns the quote amount of the current open interest for a market, using the current oracle price
345
+ * @param marketIndex
346
+ * @param marketType
347
+ * @param driftClient
348
+ * @returns
349
+ */
350
+ const getCurrentOpenInterestForMarket = (marketIndex, marketType, driftClient) => {
351
+ if (exports.ENUM_UTILS.match(marketType, sdk_1.MarketType.PERP)) {
352
+ const market = driftClient.getPerpMarketAccount(marketIndex);
353
+ const OI = sdk_1.BigNum.from(market.amm.baseAssetAmountLong.add(market.amm.baseAssetAmountShort.abs()), sdk_1.BASE_PRECISION_EXP);
354
+ const priceData = driftClient.getOraclePriceDataAndSlot(market.amm.oracle, market.amm.oracleSource);
355
+ const price = sdk_1.BigNum.from(priceData.data.price, sdk_1.PRICE_PRECISION_EXP);
356
+ const quoteOIforMarket = price.toNum() * OI.toNum();
357
+ return quoteOIforMarket;
358
+ }
359
+ else {
360
+ throw new Error('Invalid market type for Open Interest calculation');
361
+ }
362
+ };
363
+ /**
364
+ * Gets the deposit APR for a spot market, in percent
365
+ * @param marketIndex
366
+ * @param marketType
367
+ * @param driftClient
368
+ * @returns
369
+ */
370
+ const getDepositAprForMarket = (marketIndex, marketType, driftClient) => {
371
+ if (exports.ENUM_UTILS.match(marketType, sdk_1.MarketType.SPOT)) {
372
+ const marketAccount = driftClient.getSpotMarketAccount(marketIndex);
373
+ const depositApr = sdk_1.BigNum.from((0, sdk_1.calculateDepositRate)(marketAccount), sdk_1.SPOT_MARKET_RATE_PRECISION_EXP);
374
+ const depositAprPct = depositApr.toNum() * 100;
375
+ return depositAprPct;
376
+ }
377
+ else {
378
+ throw new Error('Invalid market type for Deposit APR calculation');
379
+ }
380
+ };
381
+ /**
382
+ * Get's the borrow APR for a spot market, in percent
383
+ * @param marketIndex
384
+ * @param marketType
385
+ * @param driftClient
386
+ * @returns
387
+ */
388
+ const getBorrowAprForMarket = (marketIndex, marketType, driftClient) => {
389
+ if (exports.ENUM_UTILS.match(marketType, sdk_1.MarketType.SPOT)) {
390
+ const marketAccount = driftClient.getSpotMarketAccount(marketIndex);
391
+ const depositApr = sdk_1.BigNum.from((0, sdk_1.calculateBorrowRate)(marketAccount), sdk_1.SPOT_MARKET_RATE_PRECISION_EXP);
392
+ const depositAprPct = depositApr.toNum() * 100;
393
+ return depositAprPct;
394
+ }
395
+ else {
396
+ throw new Error('Invalid market type for Borrow APR calculation');
397
+ }
398
+ };
399
+ const getTotalBorrowsForMarket = (market, driftClient) => {
400
+ const marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);
401
+ const totalBorrowsTokenAmount = (0, sdk_1.getTokenAmount)(marketAccount.borrowBalance, driftClient.getSpotMarketAccount(marketAccount.marketIndex), sdk_1.SpotBalanceType.BORROW);
402
+ const totalBorrowsAmountBigNum = sdk_1.BigNum.from(totalBorrowsTokenAmount, market.precisionExp);
403
+ const priceData = driftClient.getOraclePriceDataAndSlot(marketAccount.oracle, marketAccount.oracleSource);
404
+ const price = sdk_1.BigNum.from(priceData.data.price, sdk_1.PRICE_PRECISION_EXP);
405
+ const totalBorrowsQuote = price.toNum() * totalBorrowsAmountBigNum.toNum();
406
+ return Number(totalBorrowsQuote.toFixed(2));
407
+ };
408
+ const getTotalDepositsForMarket = (market, driftClient) => {
409
+ const marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);
410
+ const totalDepositsTokenAmount = (0, sdk_1.getTokenAmount)(marketAccount.depositBalance, marketAccount, sdk_1.SpotBalanceType.DEPOSIT);
411
+ const totalDepositsTokenAmountBigNum = sdk_1.BigNum.from(totalDepositsTokenAmount, market.precisionExp);
412
+ const priceData = driftClient.getOraclePriceDataAndSlot(marketAccount.oracle, marketAccount.oracleSource);
413
+ const price = sdk_1.BigNum.from(priceData.data.price, sdk_1.PRICE_PRECISION_EXP);
414
+ const totalDepositsBase = totalDepositsTokenAmountBigNum.toNum();
415
+ const totalDepositsQuote = price.toNum() * totalDepositsTokenAmountBigNum.toNum();
416
+ return {
417
+ totalDepositsBase,
418
+ totalDepositsQuote,
419
+ };
420
+ };
421
+ /**
422
+ * Check if numbers divide exactly, accounting for floating point division annoyingness
423
+ * @param numerator
424
+ * @param denominator
425
+ * @returns
426
+ */
427
+ const dividesExactly = (numerator, denominator) => {
428
+ const division = numerator / denominator;
429
+ const remainder = division % 1;
430
+ if (remainder === 0)
431
+ return true;
432
+ // Because of floating point weirdness, we're just going to assume that if the remainder after dividing is less than 1/10^6 then the numbers do divide exactly
433
+ if (Math.abs(remainder - 1) < 1 / 10 ** 6)
434
+ return true;
435
+ return false;
436
+ };
437
+ const toSnakeCase = (str) => str.replace(/[^\w]/g, '_').toLowerCase();
438
+ const toCamelCase = (str) => {
439
+ const words = str.split(/[_\-\s]+/); // split on underscores, hyphens, and spaces
440
+ const firstWord = words[0].toLowerCase();
441
+ const restWords = words
442
+ .slice(1)
443
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
444
+ return [firstWord, ...restWords].join('');
445
+ };
446
+ const aprFromApy = (apy, compoundsPerYear) => {
447
+ const compoundedAmount = 1 + apy * 0.01;
448
+ const estimatedApr = (Math.pow(compoundedAmount, 1 / compoundsPerYear) - 1) * compoundsPerYear;
449
+ return estimatedApr * 100;
450
+ };
451
+ exports.aprFromApy = aprFromApy;
452
+ /**
453
+ * Helper utility to get a sort score for "tiered" parameters.
454
+ *
455
+ * Example: Want to sort students by Grade, but fall back to using Age if they are equal. This method will accept an array for each student of [grade, age] and return the appropriate sort score for each.
456
+ *
457
+ * @param aScores
458
+ * @param bScores
459
+ * @returns
460
+ */
461
+ const getTieredSortScore = (aScores, bScores) => {
462
+ var _a, _b;
463
+ const maxIndex = Math.max(aScores.length, bScores.length);
464
+ for (let i = 0; i < maxIndex; i++) {
465
+ const aScore = (_a = aScores[i]) !== null && _a !== void 0 ? _a : Number.MIN_SAFE_INTEGER;
466
+ const bScore = (_b = bScores[i]) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER;
467
+ if (aScore !== bScore)
468
+ return aScore - bScore;
469
+ }
470
+ return 0;
471
+ };
472
+ exports.getTieredSortScore = getTieredSortScore;
473
+ const normalizeBaseAssetSymbol = (symbol) => {
474
+ return symbol.replace(/^1M/, '');
475
+ };
476
+ /**
477
+ * Returns the number of standard deviations between a target value and the history of values to compare it to.
478
+ * @param target
479
+ * @param previousValues
480
+ * @returns
481
+ */
482
+ const calculateZScore = (target, previousValues) => {
483
+ const meanValue = calculateMean(previousValues);
484
+ const standardDeviationValue = calculateStandardDeviation(previousValues, meanValue);
485
+ const zScore = (target - meanValue) / standardDeviationValue;
486
+ return zScore;
487
+ };
488
+ const calculateMean = (numbers) => {
489
+ const sum = numbers.reduce((total, num) => total + num, 0);
490
+ return sum / numbers.length;
491
+ };
492
+ const calculateMedian = (numbers) => {
493
+ const sortedNumbers = numbers.sort();
494
+ const middleIndex = Math.floor(sortedNumbers.length / 2);
495
+ if (sortedNumbers.length % 2 === 0) {
496
+ return (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;
497
+ }
498
+ else {
499
+ return sortedNumbers[middleIndex];
500
+ }
501
+ };
502
+ const calculateStandardDeviation = (numbers, mean) => {
503
+ const squaredDifferences = numbers.map((num) => Math.pow(num - mean, 2));
504
+ const sumSquaredDifferences = squaredDifferences.reduce((total, diff) => total + diff, 0);
505
+ const variance = sumSquaredDifferences / numbers.length;
506
+ return Math.sqrt(variance);
507
+ };
508
+ const glueArray = (size, elements) => {
509
+ const gluedElements = [];
510
+ elements.forEach((element, index) => {
511
+ const gluedIndex = Math.floor(index / size);
512
+ if (gluedElements[gluedIndex]) {
513
+ gluedElements[gluedIndex].push(element);
514
+ }
515
+ else {
516
+ gluedElements[gluedIndex] = [element];
517
+ }
518
+ });
519
+ return gluedElements;
520
+ };
521
+ const bnMin = (numbers) => {
522
+ let min = numbers[0];
523
+ for (let i = 1; i < numbers.length; i++) {
524
+ if (numbers[i].lt(min)) {
525
+ min = numbers[i];
526
+ }
527
+ }
528
+ return min;
529
+ };
530
+ const bnMax = (numbers) => {
531
+ let max = numbers[0];
532
+ for (let i = 1; i < numbers.length; i++) {
533
+ if (numbers[i].gt(max)) {
534
+ max = numbers[i];
535
+ }
536
+ }
537
+ return max;
538
+ };
539
+ const bnMedian = (numbers) => {
540
+ const sortedNumbers = numbers.sort((a, b) => a.cmp(b));
541
+ const middleIndex = Math.floor(sortedNumbers.length / 2);
542
+ if (sortedNumbers.length % 2 === 0) {
543
+ return sortedNumbers[middleIndex - 1]
544
+ .add(sortedNumbers[middleIndex])
545
+ .div(new sdk_1.BN(2));
546
+ }
547
+ else {
548
+ return sortedNumbers[middleIndex];
549
+ }
550
+ };
551
+ const bnMean = (numbers) => {
552
+ let sum = new sdk_1.BN(0);
553
+ for (let i = 0; i < numbers.length; i++) {
554
+ sum = sum.add(numbers[i]);
555
+ }
556
+ return sum.div(new sdk_1.BN(numbers.length));
557
+ };
558
+ const timedPromise = async (promise) => {
559
+ const start = Date.now();
560
+ const promiseResult = await promise;
561
+ return {
562
+ promiseTime: Date.now() - start,
563
+ promiseResult,
564
+ };
565
+ };
566
+ const chunks = (array, size) => {
567
+ return new Array(Math.ceil(array.length / size))
568
+ .fill(null)
569
+ .map((_, index) => index * size)
570
+ .map((begin) => array.slice(begin, begin + size));
571
+ };
572
+ const getMultipleAccountsInfoChunked = async (connection, accounts) => {
573
+ const accountChunks = chunks(accounts, 100); // 100 is limit for getMultipleAccountsInfo
574
+ const responses = await Promise.all(accountChunks.map((chunk) => connection.getMultipleAccountsInfo(chunk)));
575
+ return responses.flat();
576
+ };
577
+ exports.COMMON_UTILS = {
578
+ getIfVaultBalance: insuranceFund_1.getIfVaultBalance,
579
+ getIfStakingVaultApr: insuranceFund_1.getIfStakingVaultApr,
580
+ getCurrentOpenInterestForMarket,
581
+ getDepositAprForMarket,
582
+ getBorrowAprForMarket,
583
+ getTotalBorrowsForMarket,
584
+ getTotalDepositsForMarket,
585
+ dividesExactly,
586
+ toSnakeCase,
587
+ toCamelCase,
588
+ getTieredSortScore: exports.getTieredSortScore,
589
+ normalizeBaseAssetSymbol,
590
+ calculateZScore,
591
+ glueArray,
592
+ timedPromise,
593
+ chunks,
594
+ getMultipleAccountsInfoChunked,
595
+ MATH: {
596
+ NUM: {
597
+ mean: calculateMean,
598
+ median: calculateMedian,
599
+ },
600
+ BN: {
601
+ bnMax,
602
+ bnMin,
603
+ bnMean,
604
+ bnMedian,
605
+ },
606
+ },
607
+ };
608
+ //# sourceMappingURL=index.js.map