@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 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;AAAA,yCAuByB;AAKzB,mDAA0E;AAGnE,MAAM,SAAS,GAAG,CAAC,KAAU,EAAE,KAAK,EAAE,EAAE;IAC9C,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACxD,CAAC,CAAC;AAFW,QAAA,SAAS,aAEpB;AAEF,SAAS,SAAS,CAAC,OAAe;IACjC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAE/B,OAAO;QACN,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,EAAE,EAAE;KACnB,CAAC;AACH,CAAC;AAED,SAAS,SAAS,CAAC,OAA4B;;IAC9C,OAAO,MAAA,MAAM,CAAC,IAAI,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,0CAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAEY,QAAA,UAAU,GAAG;IACzB,KAAK,EAAE,iBAAS;IAChB,KAAK,EAAE,SAAS;IAChB,KAAK,EAAE,SAAS;CAChB,CAAC;AAEK,KAAK,UAAU,KAAK,CAAC,EAAE;IAC7B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAA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BASE_PRECISION,\n\tBN,\n\tEvent,\n\tPRICE_PRECISION,\n\tOrderAction,\n\tOrderActionRecord,\n\tOrderRecord,\n\tPublicKey,\n\tQUOTE_PRECISION,\n\tZERO,\n\tPRICE_PRECISION_EXP,\n\tBASE_PRECISION_EXP,\n\tBigNum,\n\tMarketType,\n\tDriftClient,\n\tSPOT_MARKET_RATE_PRECISION_EXP,\n\tcalculateDepositRate,\n\tcalculateBorrowRate,\n\tgetTokenAmount,\n\tSpotBalanceType,\n\tSpotMarketConfig,\n} from '@drift-labs/sdk';\nimport {\n\tUIMatchedOrderRecordAndAction,\n\tUISerializableOrderActionRecord,\n} from '../serializableTypes';\nimport { getIfStakingVaultApr, getIfVaultBalance } from './insuranceFund';\nimport { AccountInfo, Connection } from '@solana/web3.js';\n\nexport const matchEnum = (enum1: any, enum2) => {\n\treturn JSON.stringify(enum1) === JSON.stringify(enum2);\n};\n\nfunction enumToObj(enumStr: string) {\n\tif (!enumStr) return undefined;\n\n\treturn {\n\t\t[enumStr ?? '']: {},\n\t};\n}\n\nfunction enumToStr(enumStr: Record<string, any>) {\n\treturn Object.keys(enumStr ?? {})?.[0];\n}\n\nexport const ENUM_UTILS = {\n\tmatch: matchEnum,\n\ttoObj: enumToObj,\n\ttoStr: enumToStr,\n};\n\nexport async function sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nconst getStringifiableObjectEntry = (value: any): [any, string] => {\n\t// If BN\n\t// 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 */\n\tif (Object.keys(value).sort().join(',') === 'length,negative,red,words') {\n\t\treturn [value.toString(), '_bgnm_'];\n\t}\n\n\t// If PublicKey\n\t// 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 */\n\tif (Object.keys(value).sort().join(',') === '_bn') {\n\t\treturn [value.toString(), '_pbky_'];\n\t}\n\n\tif (typeof value === 'object') {\n\t\treturn [encodeStringifiableObject(value), ''];\n\t}\n\n\treturn [value, ''];\n};\n\n/**\n * 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.\n *\n * e.g.\n * input : {\n * QuoteAmount: BN\n * }\n *\n * output: {\n * _bgnm_QuoteAmount: string\n * }\n * @param value\n * @returns\n */\nexport const encodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => encodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tif (!value) return value;\n\n\tObject.entries(value).forEach(([key, val]) => {\n\t\tconst [convertedVal, keyTag] = getStringifiableObjectEntry(val);\n\t\tbuildJsonObject[`${keyTag}${key}`] = convertedVal;\n\t});\n\n\treturn buildJsonObject;\n};\n\n/**\n * 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_\n *\n * * e.g.\n * input : {\n * _bgnm_QuoteAmount: string\n * }\n *\n * output: {\n * QuoteAmount: BN\n * }\n * @param value\n * @returns\n */\nexport const decodeStringifiableObject = (value: any) => {\n\tif (typeof value !== 'object') return value;\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => decodeStringifiableObject(entry));\n\t}\n\n\tconst buildJsonObject = {};\n\n\tObject.entries(value)\n\t\t.filter((val) => val != undefined && val != null)\n\t\t.forEach(([key, val]) => {\n\t\t\tif (key.match(/^_pbky_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_pbky_', '')] = new PublicKey(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (key.match(/^_bgnm_/)) {\n\t\t\t\tbuildJsonObject[key.replace('_bgnm_', '')] = new BN(val as string);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof val === 'object' && val != undefined && val != null) {\n\t\t\t\tbuildJsonObject[key] = decodeStringifiableObject(val);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbuildJsonObject[key] = val;\n\t\t});\n\n\treturn buildJsonObject;\n};\n\nconst getChronologicalValueForOrderAction = (action: OrderAction) => {\n\treturn matchEnum(action, OrderAction.PLACE)\n\t\t? 0\n\t\t: matchEnum(action, OrderAction.FILL)\n\t\t? 1\n\t\t: 2;\n};\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderRecords = (\n\torderA: { slot: number },\n\torderB: { slot: number }\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\treturn 0;\n};\n\nexport const getTradeInfoFromActionRecord = (\n\tactionRecord: PartialUISerializableOrderActionRecord\n) => {\n\treturn {\n\t\tts: actionRecord.ts,\n\t\tbaseAssetAmount: actionRecord.taker\n\t\t\t? actionRecord.takerOrderBaseAssetAmount\n\t\t\t: actionRecord.makerOrderBaseAssetAmount,\n\t\tbaseAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeBaseAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeBaseAssetAmountFilled,\n\t\tquoteAssetAmountFilled: actionRecord.taker\n\t\t\t? actionRecord.takerOrderCumulativeQuoteAssetAmountFilled\n\t\t\t: actionRecord.makerOrderCumulativeQuoteAssetAmountFilled,\n\t};\n};\n\nexport type PartialOrderActionRecord =\n\t| PartialUISerializableOrderActionRecord\n\t| PartialOrderActionEventRecord;\n\nexport type PartialUISerializableOrderActionRecord = Pick<\n\tUISerializableOrderActionRecord,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'oraclePrice'\n>;\n\nexport type PartialOrderActionEventRecord = Pick<\n\tEvent<OrderActionRecord>,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n>;\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderActionRecords = (\n\torderA: PartialOrderActionRecord,\n\torderB: PartialOrderActionRecord\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\tif (!matchEnum(orderA.action, orderB.action)) {\n\t\t// @ts-ignore\n\t\tconst orderAActionVal = getChronologicalValueForOrderAction(orderA.action);\n\t\t// @ts-ignore\n\t\tconst orderBActionVal = getChronologicalValueForOrderAction(orderB.action);\n\n\t\treturn orderAActionVal > orderBActionVal ? 1 : -1;\n\t}\n\t// @ts-ignore\n\tif (orderA.fillRecordId && orderB.fillRecordId) {\n\t\tif (!orderA.fillRecordId.eq(orderB.fillRecordId)) {\n\t\t\t// @ts-ignore\n\t\t\treturn orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;\n\t\t}\n\t}\n\n\treturn 0;\n};\n\nexport const sortUIMatchedOrderRecordAndAction = (\n\trecords: UIMatchedOrderRecordAndAction[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort((a, b) =>\n\t\tgetSortScoreForOrderActionRecords(a.actionRecord, b.actionRecord)\n\t);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderActionRecords = (\n\trecords: PartialUISerializableOrderActionRecord[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderActionRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderRecords = <T extends { slot: number }>(\n\trecords: T[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortOrderRecords = (\n\trecords: Event<OrderRecord>[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const getLatestOfTwoUIOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getLatestOfTwoOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getUIOrderRecordsLaterThanTarget = <T extends { slot: number }>(\n\ttarget: T,\n\trecords: T[]\n) =>\n\trecords.filter(\n\t\t(record) => getLatestOfTwoUIOrderRecords(record, target) === record\n\t);\n\n// Trade records are order records which have been filled\nexport const orderActionRecordIsTrade = (orderRecord: OrderActionRecord) =>\n\torderRecord.baseAssetAmountFilled.gt(ZERO) &&\n\t// @ts-ignore\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\nexport const uiOrderActionRecordIsTrade = (\n\torderRecord: UISerializableOrderActionRecord\n) =>\n\torderRecord.baseAssetAmountFilled.gtZero() &&\n\tmatchEnum(orderRecord.action, OrderAction.FILL) &&\n\ttrue;\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromOrderActionRecords = (\n\torderRecords: OrderActionRecord[]\n): OrderActionRecord[] => orderRecords.filter(orderActionRecordIsTrade);\n\n// Trade records are order records which have been filled\nexport const filterTradeRecordsFromUIOrderRecords = (\n\torderRecords: UISerializableOrderActionRecord[]\n): UISerializableOrderActionRecord[] =>\n\torderRecords.filter(uiOrderActionRecordIsTrade);\n\n/**\n * Returns the average price for a given base amount and quote amount.\n * @param quoteAmount\n * @param baseAmount\n * @returns PRICE_PRECISION\n */\nexport const getPriceForBaseAndQuoteAmount = (\n\tquoteAmount: BN,\n\tbaseAmount: BN\n) => {\n\treturn quoteAmount\n\t\t.mul(PRICE_PRECISION)\n\t\t.mul(BASE_PRECISION)\n\t\t.div(QUOTE_PRECISION)\n\t\t.div(BigNum.from(baseAmount, BASE_PRECISION_EXP).val);\n};\n\nexport const getPriceForOrderRecord = (\n\torderRecord: Pick<\n\t\tOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn getPriceForBaseAndQuoteAmount(\n\t\t// @ts-ignore\n\t\torderRecord.quoteAssetAmountFilled,\n\t\t// @ts-ignore\n\t\torderRecord.baseAssetAmountFilled\n\t);\n};\n\nexport const getPriceForUIOrderRecord = (\n\torderRecord: Pick<\n\t\tUISerializableOrderActionRecord,\n\t\t'quoteAssetAmountFilled' | 'baseAssetAmountFilled'\n\t>\n) => {\n\treturn orderRecord.quoteAssetAmountFilled\n\t\t.shiftTo(AMM_RESERVE_PRECISION_EXP)\n\t\t.shift(PRICE_PRECISION_EXP)\n\t\t.div(orderRecord.baseAssetAmountFilled.shiftTo(BASE_PRECISION_EXP))\n\t\t.shiftTo(PRICE_PRECISION_EXP);\n};\n\nexport const orderIsNull = (\n\torder: UISerializableOrderActionRecord | Event<OrderActionRecord>,\n\tside: 'taker' | 'maker'\n) => {\n\treturn side === 'taker' ? !order.taker : !order.maker;\n};\n\nexport const getAnchorEnumString = (enumVal: Record<string, unknown>) => {\n\treturn Object.keys(enumVal)[0];\n};\nexport class Ref<T> {\n\tpublic val: T;\n\n\tconstructor(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tset(val: T) {\n\t\tthis.val = val;\n\t}\n\n\tget() {\n\t\treturn this.val;\n\t}\n}\n\nexport class Counter {\n\tprivate val = 0;\n\n\tget() {\n\t\treturn this.val;\n\t}\n\n\tincrement(value = 1) {\n\t\tthis.val += value;\n\t}\n\n\treset() {\n\t\tthis.val = 0;\n\t}\n}\n\n/**\n * 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\n *\n * If baseState is on => any switch being \"on\" will turn the multiswitch off.\n * If baseState is off => any switch being \"off\" will turn the multiswitch off.\n */\nexport class MultiSwitch {\n\tprivate switches: string[] = [];\n\tprivate switchValue = 0;\n\n\tconstructor(private baseState: 'on' | 'off' = 'off') {}\n\n\tprivate getSwitchKey(key: string) {\n\t\t// If first time using switch, add to list of switches\n\t\tif (!this.switches.includes(key)) {\n\t\t\tthis.switches.push(key);\n\t\t}\n\n\t\tconst switchIndex = this.switches.indexOf(key);\n\n\t\treturn 2 ** switchIndex;\n\t}\n\n\tpublic switchOn(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOff(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOn(key);\n\t}\n\n\tpublic switchOff(key: string) {\n\t\tif (this.baseState === 'on') {\n\t\t\tthis._switchOn(key);\n\t\t\treturn;\n\t\t}\n\t\tthis._switchOff(key);\n\t}\n\n\tprivate _switchOff(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue &= ~switchKey;\n\t}\n\n\tprivate _switchOn(key: string) {\n\t\tconst switchKey = this.getSwitchKey(key);\n\n\t\tthis.switchValue |= switchKey;\n\t}\n\n\tpublic get isOn() {\n\t\t// When the base state is on, then if any switch is on the multi-switch is off\n\t\tif (this.baseState === 'on') {\n\t\t\treturn this.switchValue === 0;\n\t\t}\n\n\t\tif (this.baseState === 'off') {\n\t\t\treturn this.switchValue > 0;\n\t\t}\n\t}\n}\n\n/**\n * Returns the quote amount of the current open interest for a market, using the current oracle price\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getCurrentOpenInterestForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.PERP)) {\n\t\tconst market = driftClient.getPerpMarketAccount(marketIndex);\n\t\tconst OI = BigNum.from(\n\t\t\tmarket.amm.baseAssetAmountLong.add(market.amm.baseAssetAmountShort.abs()),\n\t\t\tBASE_PRECISION_EXP\n\t\t);\n\n\t\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\t\tmarket.amm.oracle,\n\t\t\tmarket.amm.oracleSource\n\t\t);\n\n\t\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\t\tconst quoteOIforMarket = price.toNum() * OI.toNum();\n\n\t\treturn quoteOIforMarket;\n\t} else {\n\t\tthrow new Error('Invalid market type for Open Interest calculation');\n\t}\n};\n\n/**\n * Gets the deposit APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getDepositAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateDepositRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Deposit APR calculation');\n\t}\n};\n\n/**\n * Get's the borrow APR for a spot market, in percent\n * @param marketIndex\n * @param marketType\n * @param driftClient\n * @returns\n */\nconst getBorrowAprForMarket = (\n\tmarketIndex: number,\n\tmarketType: MarketType,\n\tdriftClient: DriftClient\n) => {\n\tif (ENUM_UTILS.match(marketType, MarketType.SPOT)) {\n\t\tconst marketAccount = driftClient.getSpotMarketAccount(marketIndex);\n\n\t\tconst depositApr = BigNum.from(\n\t\t\tcalculateBorrowRate(marketAccount),\n\t\t\tSPOT_MARKET_RATE_PRECISION_EXP\n\t\t);\n\n\t\tconst depositAprPct = depositApr.toNum() * 100;\n\n\t\treturn depositAprPct;\n\t} else {\n\t\tthrow new Error('Invalid market type for Borrow APR calculation');\n\t}\n};\n\nconst getTotalBorrowsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalBorrowsTokenAmount = getTokenAmount(\n\t\tmarketAccount.borrowBalance,\n\t\tdriftClient.getSpotMarketAccount(marketAccount.marketIndex),\n\t\tSpotBalanceType.BORROW\n\t);\n\n\tconst totalBorrowsAmountBigNum = BigNum.from(\n\t\ttotalBorrowsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalBorrowsQuote = price.toNum() * totalBorrowsAmountBigNum.toNum();\n\n\treturn Number(totalBorrowsQuote.toFixed(2));\n};\n\nconst getTotalDepositsForMarket = (\n\tmarket: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst marketAccount = driftClient.getSpotMarketAccount(market.marketIndex);\n\n\tconst totalDepositsTokenAmount = getTokenAmount(\n\t\tmarketAccount.depositBalance,\n\t\tmarketAccount,\n\t\tSpotBalanceType.DEPOSIT\n\t);\n\n\tconst totalDepositsTokenAmountBigNum = BigNum.from(\n\t\ttotalDepositsTokenAmount,\n\t\tmarket.precisionExp\n\t);\n\n\tconst priceData = driftClient.getOraclePriceDataAndSlot(\n\t\tmarketAccount.oracle,\n\t\tmarketAccount.oracleSource\n\t);\n\n\tconst price = BigNum.from(priceData.data.price, PRICE_PRECISION_EXP);\n\n\tconst totalDepositsBase = totalDepositsTokenAmountBigNum.toNum();\n\tconst totalDepositsQuote =\n\t\tprice.toNum() * totalDepositsTokenAmountBigNum.toNum();\n\n\treturn {\n\t\ttotalDepositsBase,\n\t\ttotalDepositsQuote,\n\t};\n};\n\n/**\n * Check if numbers divide exactly, accounting for floating point division annoyingness\n * @param numerator\n * @param denominator\n * @returns\n */\nconst dividesExactly = (numerator: number, denominator: number) => {\n\tconst division = numerator / denominator;\n\tconst remainder = division % 1;\n\n\tif (remainder === 0) return true;\n\n\t// 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\n\tif (Math.abs(remainder - 1) < 1 / 10 ** 6) return true;\n\n\treturn false;\n};\n\nconst toSnakeCase = (str: string): string =>\n\tstr.replace(/[^\\w]/g, '_').toLowerCase();\n\nconst toCamelCase = (str: string): string => {\n\tconst words = str.split(/[_\\-\\s]+/); // split on underscores, hyphens, and spaces\n\tconst firstWord = words[0].toLowerCase();\n\tconst restWords = words\n\t\t.slice(1)\n\t\t.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n\treturn [firstWord, ...restWords].join('');\n};\n\nexport const aprFromApy = (apy: number, compoundsPerYear: number) => {\n\tconst compoundedAmount = 1 + apy * 0.01;\n\tconst estimatedApr =\n\t\t(Math.pow(compoundedAmount, 1 / compoundsPerYear) - 1) * compoundsPerYear;\n\n\treturn estimatedApr * 100;\n};\n\n/**\n * Helper utility to get a sort score for \"tiered\" parameters.\n *\n * 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.\n *\n * @param aScores\n * @param bScores\n * @returns\n */\nexport const getTieredSortScore = (aScores: number[], bScores: number[]) => {\n\tconst maxIndex = Math.max(aScores.length, bScores.length);\n\n\tfor (let i = 0; i < maxIndex; i++) {\n\t\tconst aScore = aScores[i] ?? Number.MIN_SAFE_INTEGER;\n\t\tconst bScore = bScores[i] ?? Number.MIN_SAFE_INTEGER;\n\n\t\tif (aScore !== bScore) return aScore - bScore;\n\t}\n\n\treturn 0;\n};\n\nconst normalizeBaseAssetSymbol = (symbol: string) => {\n\treturn symbol.replace(/^1M/, '');\n};\n\n/**\n * Returns the number of standard deviations between a target value and the history of values to compare it to.\n * @param target\n * @param previousValues\n * @returns\n */\nconst calculateZScore = (target: number, previousValues: number[]): number => {\n\tconst meanValue = calculateMean(previousValues);\n\tconst standardDeviationValue = calculateStandardDeviation(\n\t\tpreviousValues,\n\t\tmeanValue\n\t);\n\n\tconst zScore = (target - meanValue) / standardDeviationValue;\n\treturn zScore;\n};\n\nconst calculateMean = (numbers: number[]): number => {\n\tconst sum = numbers.reduce((total, num) => total + num, 0);\n\treturn sum / numbers.length;\n};\n\nconst calculateMedian = (numbers: number[]): number => {\n\tconst sortedNumbers = numbers.sort();\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst calculateStandardDeviation = (\n\tnumbers: number[],\n\tmean: number\n): number => {\n\tconst squaredDifferences = numbers.map((num) => Math.pow(num - mean, 2));\n\tconst sumSquaredDifferences = squaredDifferences.reduce(\n\t\t(total, diff) => total + diff,\n\t\t0\n\t);\n\tconst variance = sumSquaredDifferences / numbers.length;\n\treturn Math.sqrt(variance);\n};\n\nconst glueArray = <T>(size: number, elements: T[]): T[][] => {\n\tconst gluedElements: T[][] = [];\n\n\telements.forEach((element, index) => {\n\t\tconst gluedIndex = Math.floor(index / size);\n\t\tif (gluedElements[gluedIndex]) {\n\t\t\tgluedElements[gluedIndex].push(element);\n\t\t} else {\n\t\t\tgluedElements[gluedIndex] = [element];\n\t\t}\n\t});\n\n\treturn gluedElements;\n};\n\nconst bnMin = (numbers: BN[]): BN => {\n\tlet min = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].lt(min)) {\n\t\t\tmin = numbers[i];\n\t\t}\n\t}\n\treturn min;\n};\n\nconst bnMax = (numbers: BN[]): BN => {\n\tlet max = numbers[0];\n\tfor (let i = 1; i < numbers.length; i++) {\n\t\tif (numbers[i].gt(max)) {\n\t\t\tmax = numbers[i];\n\t\t}\n\t}\n\treturn max;\n};\n\nconst bnMedian = (numbers: BN[]): BN => {\n\tconst sortedNumbers = numbers.sort((a, b) => a.cmp(b));\n\tconst middleIndex = Math.floor(sortedNumbers.length / 2);\n\tif (sortedNumbers.length % 2 === 0) {\n\t\treturn sortedNumbers[middleIndex - 1]\n\t\t\t.add(sortedNumbers[middleIndex])\n\t\t\t.div(new BN(2));\n\t} else {\n\t\treturn sortedNumbers[middleIndex];\n\t}\n};\n\nconst bnMean = (numbers: BN[]): BN => {\n\tlet sum = new BN(0);\n\tfor (let i = 0; i < numbers.length; i++) {\n\t\tsum = sum.add(numbers[i]);\n\t}\n\treturn sum.div(new BN(numbers.length));\n};\n\nconst timedPromise = async <T>(promise: T) => {\n\tconst start = Date.now();\n\tconst promiseResult = await promise;\n\n\treturn {\n\t\tpromiseTime: Date.now() - start,\n\t\tpromiseResult,\n\t};\n};\n\nconst chunks = <T>(array: readonly T[], size: number): T[][] => {\n\treturn new Array(Math.ceil(array.length / size))\n\t\t.fill(null)\n\t\t.map((_, index) => index * size)\n\t\t.map((begin) => array.slice(begin, begin + size));\n};\n\nconst getMultipleAccountsInfoChunked = async (\n\tconnection: Connection,\n\taccounts: PublicKey[]\n): Promise<(AccountInfo<Buffer> | null)[]> => {\n\tconst accountChunks = chunks(accounts, 100); // 100 is limit for getMultipleAccountsInfo\n\tconst responses = await Promise.all(\n\t\taccountChunks.map((chunk) => connection.getMultipleAccountsInfo(chunk))\n\t);\n\treturn responses.flat();\n};\n\nexport const COMMON_UTILS = {\n\tgetIfVaultBalance,\n\tgetIfStakingVaultApr,\n\tgetCurrentOpenInterestForMarket,\n\tgetDepositAprForMarket,\n\tgetBorrowAprForMarket,\n\tgetTotalBorrowsForMarket,\n\tgetTotalDepositsForMarket,\n\tdividesExactly,\n\ttoSnakeCase,\n\ttoCamelCase,\n\tgetTieredSortScore,\n\tnormalizeBaseAssetSymbol,\n\tcalculateZScore,\n\tglueArray,\n\ttimedPromise,\n\tchunks,\n\tgetMultipleAccountsInfoChunked,\n\tMATH: {\n\t\tNUM: {\n\t\t\tmean: calculateMean,\n\t\t\tmedian: calculateMedian,\n\t\t},\n\t\tBN: {\n\t\t\tbnMax,\n\t\t\tbnMin,\n\t\t\tbnMean,\n\t\t\tbnMedian,\n\t\t},\n\t},\n};\n"]}
@@ -0,0 +1,15 @@
1
+ import { BigNum, DriftClient, SpotMarketConfig } from '@drift-labs/sdk';
2
+ /**
3
+ * Get the size of an insurance fund vault
4
+ * @param spotMarketConfig
5
+ * @param driftClient
6
+ * @returns
7
+ */
8
+ export declare const getIfVaultBalance: (spotMarketConfig: SpotMarketConfig, driftClient: DriftClient) => Promise<BigNum>;
9
+ /**
10
+ * Get the current staking APR for a market.
11
+ * @param spotMarketConfig
12
+ * @param driftClient
13
+ * @returns APR Percentage .. e.g. 100 for 100%
14
+ */
15
+ export declare const getIfStakingVaultApr: (spotMarketConfig: SpotMarketConfig, driftClient: DriftClient) => Promise<number>;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getIfStakingVaultApr = exports.getIfVaultBalance = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const UIMarket_1 = require("../types/UIMarket");
6
+ /**
7
+ * Calculates the next APR for insurance fund staking
8
+ * This function extracts the APR calculation logic from the insurance fund staking implementation
9
+ * Reference: https://github.com/drift-labs/protocol-v2-mono/blob/ebbe7b8df7e81de59bd510a37d16f55d5c985ef5/ui/src/utils/insuranceFund.ts#L105
10
+ *
11
+ * @param spotMarket - Spot market account
12
+ * @param vaultBalanceBigNum - Current vault balance as BigNum
13
+ * @returns Next APR as a percentage (e.g., 35 means 35% APR)
14
+ */
15
+ function calculateVaultNextApr(spotMarket, vaultBalanceBigNum) {
16
+ const MAX_APR = 1000;
17
+ // Convert SDK constant from percentage precision to percentage
18
+ const GOV_MAX_APR = (sdk_1.MAX_APR_PER_REVENUE_SETTLE_TO_INSURANCE_FUND_VAULT_GOV.toNumber() /
19
+ sdk_1.PERCENTAGE_PRECISION.toNumber()) *
20
+ 100;
21
+ const DRIFT_MARKET_INDEX = 15;
22
+ const { precisionExp } = UIMarket_1.UIMarket.spotMarkets[spotMarket.marketIndex];
23
+ try {
24
+ const vaultBalance = vaultBalanceBigNum.toNum();
25
+ // Calculate revenue pool
26
+ const revenuePoolBN = (0, sdk_1.getTokenAmount)(spotMarket.revenuePool.scaledBalance, spotMarket, sdk_1.SpotBalanceType.DEPOSIT);
27
+ const revenuePoolBigNum = sdk_1.BigNum.from(revenuePoolBN, precisionExp);
28
+ const revenuePool = revenuePoolBigNum.toNum();
29
+ // APR calculation constants and factors
30
+ const payoutRatio = 0.1;
31
+ const ratioForStakers = spotMarket.insuranceFund.totalFactor > 0 &&
32
+ spotMarket.insuranceFund.userFactor > 0
33
+ ? spotMarket.insuranceFund.userFactor /
34
+ spotMarket.insuranceFund.totalFactor
35
+ : 0;
36
+ // Settle periods from on-chain data
37
+ const revSettlePeriod = spotMarket.insuranceFund.revenueSettlePeriod.toNumber() * 1000;
38
+ // Handle edge case where settle period is 0
39
+ if (revSettlePeriod === 0) {
40
+ return 0;
41
+ }
42
+ // Calculate settlements per year (31536000000 ms = 1 year)
43
+ const settlesPerYear = 31536000000 / revSettlePeriod;
44
+ // Calculate projected annual revenue
45
+ const projectedAnnualRev = revenuePool * settlesPerYear * payoutRatio;
46
+ // Calculate uncapped APR
47
+ const uncappedApr = vaultBalance === 0 ? 0 : (projectedAnnualRev / vaultBalance) * 100;
48
+ // Apply APR cap: DRIFT token (governance) capped at 20%, others at 1000%
49
+ const maxApr = spotMarket.marketIndex === DRIFT_MARKET_INDEX ? GOV_MAX_APR : MAX_APR;
50
+ const cappedApr = Math.min(uncappedApr, maxApr);
51
+ // Calculate final APR for stakers
52
+ const nextApr = cappedApr * ratioForStakers;
53
+ return nextApr;
54
+ }
55
+ catch (error) {
56
+ console.warn('Error calculating next APR:', error);
57
+ return 0;
58
+ }
59
+ }
60
+ /**
61
+ * Get the size of an insurance fund vault
62
+ * @param spotMarketConfig
63
+ * @param driftClient
64
+ * @returns
65
+ */
66
+ const getIfVaultBalance = async (spotMarketConfig, driftClient) => {
67
+ const spotMarket = driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex);
68
+ const vaultBalanceBN = new sdk_1.BN((await driftClient.provider.connection.getTokenAccountBalance(spotMarket.insuranceFund.vault)).value.amount);
69
+ const vaultBalanceBigNum = sdk_1.BigNum.from(vaultBalanceBN, spotMarketConfig.precisionExp);
70
+ return vaultBalanceBigNum;
71
+ };
72
+ exports.getIfVaultBalance = getIfVaultBalance;
73
+ /**
74
+ * Get the current staking APR for a market.
75
+ * @param spotMarketConfig
76
+ * @param driftClient
77
+ * @returns APR Percentage .. e.g. 100 for 100%
78
+ */
79
+ const getIfStakingVaultApr = async (spotMarketConfig, driftClient) => {
80
+ const vaultBalance = await (0, exports.getIfVaultBalance)(spotMarketConfig, driftClient);
81
+ return calculateVaultNextApr(driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex), vaultBalance);
82
+ };
83
+ exports.getIfStakingVaultApr = getIfStakingVaultApr;
84
+ //# sourceMappingURL=insuranceFund.js.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CACrC,cAAc,EACd,gBAAgB,CAAC,YAAY,CAC7B,CAAC;IAEF,OAAO,kBAAkB,CAAC;AAC3B,CAAC,CAAC;AAtBW,QAAA,iBAAiB,qBAsB5B;AAEF;;;;;GAKG;AACI,MAAM,oBAAoB,GAAG,KAAK,EACxC,gBAAkC,EAClC,WAAwB,EACvB,EAAE;IACH,MAAM,YAAY,GAAG,MAAM,IAAA,yBAAiB,EAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC;IAE5E,OAAO,qBAAqB,CAC3B,WAAW,CAAC,oBAAoB,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAC9D,YAAY,CACZ,CAAC;AACH,CAAC,CAAC;AAVW,QAAA,oBAAoB,wBAU/B","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tDriftClient,\n\tgetTokenAmount,\n\tSpotBalanceType,\n\tSpotMarketAccount,\n\tSpotMarketConfig,\n\tMAX_APR_PER_REVENUE_SETTLE_TO_INSURANCE_FUND_VAULT_GOV,\n\tPERCENTAGE_PRECISION,\n} from '@drift-labs/sdk';\nimport { UIMarket } from '../types/UIMarket';\n\n/**\n * Calculates the next APR for insurance fund staking\n * This function extracts the APR calculation logic from the insurance fund staking implementation\n * Reference: https://github.com/drift-labs/protocol-v2-mono/blob/ebbe7b8df7e81de59bd510a37d16f55d5c985ef5/ui/src/utils/insuranceFund.ts#L105\n *\n * @param spotMarket - Spot market account\n * @param vaultBalanceBigNum - Current vault balance as BigNum\n * @returns Next APR as a percentage (e.g., 35 means 35% APR)\n */\nfunction calculateVaultNextApr(\n\tspotMarket: SpotMarketAccount,\n\tvaultBalanceBigNum: BigNum\n): number {\n\tconst MAX_APR = 1000;\n\t// Convert SDK constant from percentage precision to percentage\n\tconst GOV_MAX_APR =\n\t\t(MAX_APR_PER_REVENUE_SETTLE_TO_INSURANCE_FUND_VAULT_GOV.toNumber() /\n\t\t\tPERCENTAGE_PRECISION.toNumber()) *\n\t\t100;\n\tconst DRIFT_MARKET_INDEX = 15;\n\n\tconst { precisionExp } = UIMarket.spotMarkets[spotMarket.marketIndex];\n\n\ttry {\n\t\tconst vaultBalance = vaultBalanceBigNum.toNum();\n\n\t\t// Calculate revenue pool\n\t\tconst revenuePoolBN = getTokenAmount(\n\t\t\tspotMarket.revenuePool.scaledBalance,\n\t\t\tspotMarket,\n\t\t\tSpotBalanceType.DEPOSIT\n\t\t);\n\t\tconst revenuePoolBigNum = BigNum.from(revenuePoolBN, precisionExp);\n\t\tconst revenuePool = revenuePoolBigNum.toNum();\n\n\t\t// APR calculation constants and factors\n\t\tconst payoutRatio = 0.1;\n\t\tconst ratioForStakers =\n\t\t\tspotMarket.insuranceFund.totalFactor > 0 &&\n\t\t\tspotMarket.insuranceFund.userFactor > 0\n\t\t\t\t? spotMarket.insuranceFund.userFactor /\n\t\t\t\t spotMarket.insuranceFund.totalFactor\n\t\t\t\t: 0;\n\n\t\t// Settle periods from on-chain data\n\t\tconst revSettlePeriod =\n\t\t\tspotMarket.insuranceFund.revenueSettlePeriod.toNumber() * 1000;\n\n\t\t// Handle edge case where settle period is 0\n\t\tif (revSettlePeriod === 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t// Calculate settlements per year (31536000000 ms = 1 year)\n\t\tconst settlesPerYear = 31536000000 / revSettlePeriod;\n\n\t\t// Calculate projected annual revenue\n\t\tconst projectedAnnualRev = revenuePool * settlesPerYear * payoutRatio;\n\n\t\t// Calculate uncapped APR\n\t\tconst uncappedApr =\n\t\t\tvaultBalance === 0 ? 0 : (projectedAnnualRev / vaultBalance) * 100;\n\n\t\t// Apply APR cap: DRIFT token (governance) capped at 20%, others at 1000%\n\t\tconst maxApr =\n\t\t\tspotMarket.marketIndex === DRIFT_MARKET_INDEX ? GOV_MAX_APR : MAX_APR;\n\t\tconst cappedApr = Math.min(uncappedApr, maxApr);\n\n\t\t// Calculate final APR for stakers\n\t\tconst nextApr = cappedApr * ratioForStakers;\n\n\t\treturn nextApr;\n\t} catch (error) {\n\t\tconsole.warn('Error calculating next APR:', error);\n\t\treturn 0;\n\t}\n}\n\n/**\n * Get the size of an insurance fund vault\n * @param spotMarketConfig\n * @param driftClient\n * @returns\n */\nexport const getIfVaultBalance = async (\n\tspotMarketConfig: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst spotMarket = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\n\tconst vaultBalanceBN = new BN(\n\t\t(\n\t\t\tawait driftClient.provider.connection.getTokenAccountBalance(\n\t\t\t\tspotMarket.insuranceFund.vault\n\t\t\t)\n\t\t).value.amount\n\t);\n\n\tconst vaultBalanceBigNum = BigNum.from(\n\t\tvaultBalanceBN,\n\t\tspotMarketConfig.precisionExp\n\t);\n\n\treturn vaultBalanceBigNum;\n};\n\n/**\n * Get the current staking APR for a market.\n * @param spotMarketConfig\n * @param driftClient\n * @returns APR Percentage .. e.g. 100 for 100%\n */\nexport const getIfStakingVaultApr = async (\n\tspotMarketConfig: SpotMarketConfig,\n\tdriftClient: DriftClient\n) => {\n\tconst vaultBalance = await getIfVaultBalance(spotMarketConfig, driftClient);\n\n\treturn calculateVaultNextApr(\n\t\tdriftClient.getSpotMarketAccount(spotMarketConfig.marketIndex),\n\t\tvaultBalance\n\t);\n};\n"]}
@@ -0,0 +1,5 @@
1
+ import { Logger as WinstonLogger } from 'winston';
2
+ export declare const logger: WinstonLogger;
3
+ export declare const setLogLevel: (logLevel: string) => void;
4
+ export type Logger = WinstonLogger;
5
+ export declare const allEnvDlog: (key: string, message: any, ...optionalParams: any[]) => void;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.allEnvDlog = exports.setLogLevel = exports.logger = void 0;
7
+ const winston_1 = require("winston");
8
+ const winston_slack_webhook_transport_1 = __importDefault(require("winston-slack-webhook-transport"));
9
+ const bypassAlert = process.env.RUNNING_LOCAL === 'true';
10
+ const loggerTransports = [
11
+ new winston_1.transports.Console({
12
+ level: 'info',
13
+ }),
14
+ ];
15
+ if (!bypassAlert) {
16
+ loggerTransports.push(new winston_slack_webhook_transport_1.default({
17
+ webhookUrl: process.env.WEBHOOK_URL,
18
+ level: 'alert',
19
+ formatter: ({ timestamp, level, message }) => {
20
+ return {
21
+ text: `[${timestamp}] ${level.toUpperCase()}: ${message}`,
22
+ };
23
+ },
24
+ }));
25
+ }
26
+ exports.logger = (0, winston_1.createLogger)({
27
+ levels: {
28
+ emerg: 0,
29
+ alert: 1,
30
+ crit: 2,
31
+ error: 3,
32
+ warning: 4,
33
+ notice: 5,
34
+ info: 6,
35
+ debug: 7,
36
+ },
37
+ level: 'info',
38
+ transports: loggerTransports,
39
+ format: winston_1.format.combine(winston_1.format.timestamp(), winston_1.format.printf(({ timestamp, level, message }) => {
40
+ return `[${timestamp}] ${level.toUpperCase()}: ${message}`;
41
+ })),
42
+ });
43
+ const setLogLevel = (logLevel) => {
44
+ exports.logger.level = logLevel;
45
+ };
46
+ exports.setLogLevel = setLogLevel;
47
+ //@ts-ignore
48
+ exports.logger.alert = (message) => exports.logger.log('alert', message);
49
+ const allEnvDlog = (key, message, ...optionalParams) => {
50
+ console.debug(`🔧::${key}::\n${message}`, ...optionalParams);
51
+ };
52
+ exports.allEnvDlog = allEnvDlog;
53
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/utils/logger.ts"],"names":[],"mappings":";;;;;;AAAA,qCAKiB;AACjB,sGAAoE;AAGpE,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,KAAK,MAAM,CAAC;AAEzD,MAAM,gBAAgB,GAAsB;IAC3C,IAAI,oBAAU,CAAC,OAAO,CAAC;QACtB,KAAK,EAAE,MAAM;KACb,CAAC;CACF,CAAC;AAEF,IAAI,CAAC,WAAW,EAAE,CAAC;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,OAAY,EACZ,GAAG,cAAqB,EACvB,EAAE;IACH,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,OAAO,OAAO,EAAE,EAAE,GAAG,cAAc,CAAC,CAAC;AAC9D,CAAC,CAAC;AANW,QAAA,UAAU,cAMrB","sourcesContent":["import {\n\tcreateLogger,\n\ttransports,\n\tformat,\n\tLogger as WinstonLogger,\n} from 'winston';\nimport SlackWebhookTransport from 'winston-slack-webhook-transport';\nimport TransportStream from 'winston-transport';\n\nconst bypassAlert = process.env.RUNNING_LOCAL === 'true';\n\nconst loggerTransports: TransportStream[] = [\n\tnew transports.Console({\n\t\tlevel: 'info',\n\t}),\n];\n\nif (!bypassAlert) {\n\tloggerTransports.push(\n\t\tnew SlackWebhookTransport({\n\t\t\twebhookUrl: process.env.WEBHOOK_URL,\n\t\t\tlevel: 'alert',\n\t\t\tformatter: ({ timestamp, level, message }) => {\n\t\t\t\treturn {\n\t\t\t\t\ttext: `[${timestamp}] ${level.toUpperCase()}: ${message}`,\n\t\t\t\t};\n\t\t\t},\n\t\t})\n\t);\n}\n\nexport const logger = createLogger({\n\tlevels: {\n\t\temerg: 0,\n\t\talert: 1,\n\t\tcrit: 2,\n\t\terror: 3,\n\t\twarning: 4,\n\t\tnotice: 5,\n\t\tinfo: 6,\n\t\tdebug: 7,\n\t},\n\tlevel: 'info',\n\ttransports: loggerTransports,\n\tformat: format.combine(\n\t\tformat.timestamp(),\n\t\tformat.printf(({ timestamp, level, message }) => {\n\t\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}`;\n\t\t})\n\t),\n});\n\nexport const setLogLevel = (logLevel: string) => {\n\tlogger.level = logLevel;\n};\n\n//@ts-ignore\nlogger.alert = (message: string) => logger.log('alert', message);\n\nexport type Logger = WinstonLogger;\n\nexport const allEnvDlog = (\n\tkey: string,\n\tmessage: any,\n\t...optionalParams: any[]\n) => {\n\tconsole.debug(`🔧::${key}::\\n${message}`, ...optionalParams);\n};\n"]}
@@ -0,0 +1,10 @@
1
+ import { BN, L2OrderBook } from '@drift-labs/sdk';
2
+ export declare const COMMON_MATH: {
3
+ calculateSpreadBidAskMark: (l2: Pick<L2OrderBook, 'bids' | 'asks'>, oraclePrice?: BN) => {
4
+ bestBidPrice: BN;
5
+ bestAskPrice: BN;
6
+ markPrice: BN;
7
+ spreadPct: BN;
8
+ spreadQuote: BN;
9
+ };
10
+ };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COMMON_MATH = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const calculateMarkPrice = (bestBidPrice, bestAskPrice, oraclePrice) => {
6
+ const bid = bestBidPrice;
7
+ const ask = bestAskPrice;
8
+ let mid;
9
+ // if bid/ask cross, force it to be the one closer to oracle, if oracle is in the middle, use oracle price
10
+ if (bid && ask && bid.gt(ask) && oraclePrice) {
11
+ if (bid.gt(oraclePrice) && ask.gt(oraclePrice)) {
12
+ mid = sdk_1.BN.min(bid, ask);
13
+ }
14
+ else if (bid.lt(oraclePrice) && ask.lt(oraclePrice)) {
15
+ mid = sdk_1.BN.max(bid, ask);
16
+ }
17
+ else {
18
+ mid = oraclePrice;
19
+ }
20
+ }
21
+ else {
22
+ if (bid && ask) {
23
+ mid = bid.add(ask).divn(2);
24
+ }
25
+ else if (oraclePrice) {
26
+ mid = oraclePrice;
27
+ }
28
+ else {
29
+ mid = undefined;
30
+ }
31
+ }
32
+ return mid;
33
+ };
34
+ const calculateBidAskAndmarkPrice = (l2, oraclePrice) => {
35
+ const bestBidPrice = l2.bids.reduce((previousMax, currentBid) => {
36
+ if (!previousMax)
37
+ return currentBid.price;
38
+ return sdk_1.BN.max(currentBid.price, previousMax);
39
+ }, undefined);
40
+ const bestAskPrice = l2.asks.reduce((previousMin, currentBid) => {
41
+ if (!previousMin)
42
+ return currentBid.price;
43
+ return sdk_1.BN.min(currentBid.price, previousMin);
44
+ }, undefined);
45
+ const markPrice = calculateMarkPrice(bestBidPrice, bestAskPrice, oraclePrice);
46
+ return {
47
+ bestBidPrice,
48
+ bestAskPrice,
49
+ markPrice,
50
+ };
51
+ };
52
+ const calculateSpreadQuote = (bestBidPrice, bestAskPrice) => {
53
+ return bestBidPrice.sub(bestAskPrice).abs();
54
+ };
55
+ function calculateSpreadPct(markPricePrice, spreadQuote) {
56
+ return spreadQuote.muln(100).mul(sdk_1.PERCENTAGE_PRECISION).div(markPricePrice);
57
+ }
58
+ const calculateSpread = (bestBidPrice, bestAskPrice, markPrice) => {
59
+ const spreadQuote = calculateSpreadQuote(bestBidPrice, bestAskPrice);
60
+ const spreadPct = calculateSpreadPct(markPrice, spreadQuote);
61
+ return {
62
+ spreadPct,
63
+ spreadQuote,
64
+ };
65
+ };
66
+ const calculateSpreadBidAskMark = (l2, oraclePrice) => {
67
+ if (l2.asks.length === 0 || l2.bids.length === 0) {
68
+ return {
69
+ spreadQuote: undefined,
70
+ spreadPct: undefined,
71
+ markPrice: undefined,
72
+ bestBidPrice: undefined,
73
+ bestAskPrice: undefined,
74
+ };
75
+ }
76
+ const { bestBidPrice, bestAskPrice, markPrice } = calculateBidAskAndmarkPrice(l2, oraclePrice);
77
+ const { spreadPct, spreadQuote } = calculateSpread(bestBidPrice, bestAskPrice, markPrice);
78
+ return {
79
+ bestBidPrice,
80
+ bestAskPrice,
81
+ markPrice,
82
+ spreadPct,
83
+ spreadQuote,
84
+ };
85
+ };
86
+ exports.COMMON_MATH = {
87
+ calculateSpreadBidAskMark,
88
+ };
89
+ //# sourceMappingURL=math.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"math.js","sourceRoot":"","sources":["../../src/utils/math.ts"],"names":[],"mappings":";;;AAAA,yCAAwE;AAExE,MAAM,kBAAkB,GAAG,CAC1B,YAAiB,EACjB,YAAiB,EACjB,WAAgB,EACf,EAAE;IACH,MAAM,GAAG,GAAG,YAAY,CAAC;IACzB,MAAM,GAAG,GAAG,YAAY,CAAC;IAEzB,IAAI,GAAO,CAAC;IAEZ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SAAS;YACtB,SAAS,EAAE,SAAS;YACpB,SAAS,EAAE,SAAS;YACpB,YAAY,EAAE,SAAS;YACvB,YAAY,EAAE,SAAS;SACvB,CAAC;IACH,CAAC;IAED,MAAM,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,GAAG,2BAA2B,CAC5E,EAAE,EACF,WAAW,CACX,CAAC;IAEF,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,eAAe,CACjD,YAAY,EACZ,YAAY,EACZ,SAAS,CACT,CAAC;IACF,OAAO;QACN,YAAY;QACZ,YAAY;QACZ,SAAS;QACT,SAAS;QACT,WAAW;KACX,CAAC;AACH,CAAC,CAAC;AAEW,QAAA,WAAW,GAAG;IAC1B,yBAAyB;CACzB,CAAC","sourcesContent":["import { BN, L2OrderBook, PERCENTAGE_PRECISION } from '@drift-labs/sdk';\n\nconst calculateMarkPrice = (\n\tbestBidPrice?: BN,\n\tbestAskPrice?: BN,\n\toraclePrice?: BN\n) => {\n\tconst bid = bestBidPrice;\n\tconst ask = bestAskPrice;\n\n\tlet mid: BN;\n\n\t// if bid/ask cross, force it to be the one closer to oracle, if oracle is in the middle, use oracle price\n\tif (bid && ask && bid.gt(ask) && oraclePrice) {\n\t\tif (bid.gt(oraclePrice) && ask.gt(oraclePrice)) {\n\t\t\tmid = BN.min(bid, ask);\n\t\t} else if (bid.lt(oraclePrice) && ask.lt(oraclePrice)) {\n\t\t\tmid = BN.max(bid, ask);\n\t\t} else {\n\t\t\tmid = oraclePrice;\n\t\t}\n\t} else {\n\t\tif (bid && ask) {\n\t\t\tmid = bid.add(ask).divn(2);\n\t\t} else if (oraclePrice) {\n\t\t\tmid = oraclePrice;\n\t\t} else {\n\t\t\tmid = undefined;\n\t\t}\n\t}\n\n\treturn mid;\n};\n\nconst calculateBidAskAndmarkPrice = (l2: L2OrderBook, oraclePrice?: BN) => {\n\tconst bestBidPrice = l2.bids.reduce((previousMax, currentBid) => {\n\t\tif (!previousMax) return currentBid.price;\n\t\treturn BN.max(currentBid.price, previousMax);\n\t}, undefined as BN);\n\n\tconst bestAskPrice = l2.asks.reduce((previousMin, currentBid) => {\n\t\tif (!previousMin) return currentBid.price;\n\t\treturn BN.min(currentBid.price, previousMin);\n\t}, undefined as BN);\n\n\tconst markPrice = calculateMarkPrice(bestBidPrice, bestAskPrice, oraclePrice);\n\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t};\n};\n\nconst calculateSpreadQuote = (bestBidPrice: BN, bestAskPrice: BN) => {\n\treturn bestBidPrice.sub(bestAskPrice).abs();\n};\n\nfunction calculateSpreadPct(markPricePrice: BN, spreadQuote: BN) {\n\treturn spreadQuote.muln(100).mul(PERCENTAGE_PRECISION).div(markPricePrice);\n}\n\nconst calculateSpread = (bestBidPrice: BN, bestAskPrice: BN, markPrice: BN) => {\n\tconst spreadQuote = calculateSpreadQuote(bestBidPrice, bestAskPrice);\n\tconst spreadPct = calculateSpreadPct(markPrice, spreadQuote);\n\n\treturn {\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nconst calculateSpreadBidAskMark = (\n\tl2: Pick<L2OrderBook, 'bids' | 'asks'>,\n\toraclePrice?: BN\n) => {\n\tif (l2.asks.length === 0 || l2.bids.length === 0) {\n\t\treturn {\n\t\t\tspreadQuote: undefined,\n\t\t\tspreadPct: undefined,\n\t\t\tmarkPrice: undefined,\n\t\t\tbestBidPrice: undefined,\n\t\t\tbestAskPrice: undefined,\n\t\t};\n\t}\n\n\tconst { bestBidPrice, bestAskPrice, markPrice } = calculateBidAskAndmarkPrice(\n\t\tl2,\n\t\toraclePrice\n\t);\n\n\tconst { spreadPct, spreadQuote } = calculateSpread(\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice\n\t);\n\treturn {\n\t\tbestBidPrice,\n\t\tbestAskPrice,\n\t\tmarkPrice,\n\t\tspreadPct,\n\t\tspreadQuote,\n\t};\n};\n\nexport const COMMON_MATH = {\n\tcalculateSpreadBidAskMark,\n};\n"]}
@@ -0,0 +1,65 @@
1
+ import { MarketType, OraclePriceData, L2OrderBook, BN, MMOraclePriceData } from '@drift-labs/sdk';
2
+ export interface L2WithOracle extends L2OrderBook {
3
+ oracleData: OraclePriceData;
4
+ markPrice: BN;
5
+ bestBidPrice: BN;
6
+ bestAskPrice: BN;
7
+ spreadPct: BN;
8
+ spreadQuote: BN;
9
+ mmOracleData?: MMOraclePriceData;
10
+ }
11
+ export interface L2WithOracleAndMarketData extends L2WithOracle {
12
+ marketSlot: number;
13
+ marketIndex: number;
14
+ marketName: string;
15
+ marketType?: MarketType;
16
+ }
17
+ export type RawL2Output = {
18
+ marketIndex: number;
19
+ marketType: MarketType;
20
+ marketName: string;
21
+ marketSlot: number;
22
+ asks: {
23
+ price: string;
24
+ size: string;
25
+ sources: {
26
+ [key: string]: string;
27
+ };
28
+ }[];
29
+ bids: {
30
+ price: string;
31
+ size: string;
32
+ sources: {
33
+ [key: string]: string;
34
+ };
35
+ }[];
36
+ oracleData: {
37
+ price: string;
38
+ slot: string;
39
+ confidence: string;
40
+ hasSufficientNumberOfDataPoints: boolean;
41
+ twap?: string;
42
+ twapConfidence?: string;
43
+ maxPrice?: string;
44
+ };
45
+ mmOracleData?: {
46
+ price: string;
47
+ slot: string;
48
+ confidence: string;
49
+ hasSufficientNumberOfDataPoints: boolean;
50
+ isMMOracleActive: boolean;
51
+ };
52
+ markPrice: string;
53
+ bestBidPrice: string;
54
+ bestAskPrice: string;
55
+ spreadPct: string;
56
+ spreadQuote: string;
57
+ slot?: number;
58
+ };
59
+ export type LiquidityType = 'vamm' | 'dlob' | 'serum' | 'phoenix' | 'openbook';
60
+ /**
61
+ * Helper function to deserialize the response from the dlob server. (See https://drift-labs.github.io/v2-teacher/#get-l2-l3)
62
+ * @param serializedOrderbook
63
+ * @returns
64
+ */
65
+ export declare const deserializeL2Response: (serializedOrderbook: RawL2Output) => L2WithOracleAndMarketData;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deserializeL2Response = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ /**
6
+ * Helper function to deserialize the response from the dlob server. (See https://drift-labs.github.io/v2-teacher/#get-l2-l3)
7
+ * @param serializedOrderbook
8
+ * @returns
9
+ */
10
+ const deserializeL2Response = (serializedOrderbook) => {
11
+ var _a, _b, _c, _d, _e, _f;
12
+ return {
13
+ asks: serializedOrderbook.asks.map((ask) => ({
14
+ price: new sdk_1.BN(ask.price),
15
+ size: new sdk_1.BN(ask.size),
16
+ sources: Object.entries(ask.sources).reduce((previous, [key, val]) => {
17
+ return {
18
+ ...previous,
19
+ [key]: new sdk_1.BN(val),
20
+ };
21
+ }, {}),
22
+ })),
23
+ bids: serializedOrderbook.bids.map((bid) => ({
24
+ price: new sdk_1.BN(bid.price),
25
+ size: new sdk_1.BN(bid.size),
26
+ sources: Object.entries(bid.sources).reduce((previous, [key, val]) => {
27
+ return {
28
+ ...previous,
29
+ [key]: new sdk_1.BN(val),
30
+ };
31
+ }, {}),
32
+ })),
33
+ oracleData: {
34
+ price: serializedOrderbook.oracleData.price
35
+ ? new sdk_1.BN(serializedOrderbook.oracleData.price)
36
+ : undefined,
37
+ slot: serializedOrderbook.oracleData.slot
38
+ ? new sdk_1.BN(serializedOrderbook.oracleData.slot)
39
+ : undefined,
40
+ confidence: serializedOrderbook.oracleData.confidence
41
+ ? new sdk_1.BN(serializedOrderbook.oracleData.confidence)
42
+ : undefined,
43
+ hasSufficientNumberOfDataPoints: serializedOrderbook.oracleData.hasSufficientNumberOfDataPoints,
44
+ twap: serializedOrderbook.oracleData.twap
45
+ ? new sdk_1.BN(serializedOrderbook.oracleData.twap)
46
+ : undefined,
47
+ twapConfidence: serializedOrderbook.oracleData.twapConfidence
48
+ ? new sdk_1.BN(serializedOrderbook.oracleData.twapConfidence)
49
+ : undefined,
50
+ maxPrice: serializedOrderbook.oracleData.maxPrice
51
+ ? new sdk_1.BN(serializedOrderbook.oracleData.maxPrice)
52
+ : undefined,
53
+ },
54
+ mmOracleData: {
55
+ price: ((_a = serializedOrderbook.mmOracleData) === null || _a === void 0 ? void 0 : _a.price)
56
+ ? new sdk_1.BN(serializedOrderbook.mmOracleData.price)
57
+ : undefined,
58
+ slot: ((_b = serializedOrderbook.mmOracleData) === null || _b === void 0 ? void 0 : _b.slot)
59
+ ? new sdk_1.BN(serializedOrderbook.mmOracleData.slot)
60
+ : undefined,
61
+ confidence: ((_c = serializedOrderbook.mmOracleData) === null || _c === void 0 ? void 0 : _c.confidence)
62
+ ? new sdk_1.BN(serializedOrderbook.mmOracleData.confidence)
63
+ : undefined,
64
+ hasSufficientNumberOfDataPoints: (_d = serializedOrderbook.mmOracleData) === null || _d === void 0 ? void 0 : _d.hasSufficientNumberOfDataPoints,
65
+ isMMOracleActive: (_f = (_e = serializedOrderbook.mmOracleData) === null || _e === void 0 ? void 0 : _e.isMMOracleActive) !== null && _f !== void 0 ? _f : false,
66
+ },
67
+ slot: serializedOrderbook.slot,
68
+ marketSlot: serializedOrderbook.marketSlot,
69
+ marketType: serializedOrderbook.marketType,
70
+ marketIndex: serializedOrderbook.marketIndex,
71
+ marketName: serializedOrderbook.marketName,
72
+ markPrice: new sdk_1.BN(serializedOrderbook.markPrice),
73
+ bestBidPrice: new sdk_1.BN(serializedOrderbook.bestBidPrice),
74
+ bestAskPrice: new sdk_1.BN(serializedOrderbook.bestAskPrice),
75
+ spreadPct: new sdk_1.BN(serializedOrderbook.spreadPct),
76
+ spreadQuote: new sdk_1.BN(serializedOrderbook.spreadQuote),
77
+ };
78
+ };
79
+ exports.deserializeL2Response = deserializeL2Response;
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/orderbook/index.ts"],"names":[],"mappings":";;;AAAA,yCAMyB;AAgEzB;;;;GAIG;AACI,MAAM,qBAAqB,GAAG,CACpC,mBAAgC,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,CAAC,CAAC,IAAI,QAAE,CAAC,mBAAmB,CAAC,YAAY,CAAC,UAAU,CAAC;gBACrD,CAAC,CAAC,SAAS;YACZ,+BAA+B,EAC9B,MAAA,mBAAmB,CAAC,YAAY,0CAAE,+BAA+B;YAClE,gBAAgB,EACf,MAAA,MAAA,mBAAmB,CAAC,YAAY,0CAAE,gBAAgB,mCAAI,KAAK;SAC5D;QACD,IAAI,EAAE,mBAAmB,CAAC,IAAI;QAC9B,UAAU,EAAE,mBAAmB,CAAC,UAAU;QAC1C,UAAU,EAAE,mBAAmB,CAAC,UAAU;QAC1C,WAAW,EAAE,mBAAmB,CAAC,WAAW;QAC5C,UAAU,EAAE,mBAAmB,CAAC,UAAU;QAC1C,SAAS,EAAE,IAAI,QAAE,CAAC,mBAAmB,CAAC,SAAS,CAAC;QAChD,YAAY,EAAE,IAAI,QAAE,CAAC,mBAAmB,CAAC,YAAY,CAAC;QACtD,YAAY,EAAE,IAAI,QAAE,CAAC,mBAAmB,CAAC,YAAY,CAAC;QACtD,SAAS,EAAE,IAAI,QAAE,CAAC,mBAAmB,CAAC,SAAS,CAAC;QAChD,WAAW,EAAE,IAAI,QAAE,CAAC,mBAAmB,CAAC,WAAW,CAAC;KACpD,CAAC;AACH,CAAC,CAAC;AAxEW,QAAA,qBAAqB,yBAwEhC","sourcesContent":["import {\n\tMarketType,\n\tOraclePriceData,\n\tL2OrderBook,\n\tBN,\n\tMMOraclePriceData,\n} from '@drift-labs/sdk';\n\nexport interface L2WithOracle extends L2OrderBook {\n\toracleData: OraclePriceData;\n\tmarkPrice: BN;\n\tbestBidPrice: BN;\n\tbestAskPrice: BN;\n\tspreadPct: BN;\n\tspreadQuote: BN;\n\tmmOracleData?: MMOraclePriceData;\n}\n\nexport interface L2WithOracleAndMarketData extends L2WithOracle {\n\tmarketSlot: number;\n\tmarketIndex: number;\n\tmarketName: string;\n\tmarketType?: MarketType;\n}\n\nexport type RawL2Output = {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tmarketName: string;\n\tmarketSlot: number;\n\tasks: {\n\t\tprice: string;\n\t\tsize: string;\n\t\tsources: {\n\t\t\t[key: string]: string;\n\t\t};\n\t}[];\n\tbids: {\n\t\tprice: string;\n\t\tsize: string;\n\t\tsources: {\n\t\t\t[key: string]: string;\n\t\t};\n\t}[];\n\toracleData: {\n\t\tprice: string;\n\t\tslot: string;\n\t\tconfidence: string;\n\t\thasSufficientNumberOfDataPoints: boolean;\n\t\ttwap?: string;\n\t\ttwapConfidence?: string;\n\t\tmaxPrice?: string;\n\t};\n\tmmOracleData?: {\n\t\tprice: string;\n\t\tslot: string;\n\t\tconfidence: string;\n\t\thasSufficientNumberOfDataPoints: boolean;\n\t\tisMMOracleActive: boolean;\n\t};\n\tmarkPrice: string;\n\tbestBidPrice: string;\n\tbestAskPrice: string;\n\tspreadPct: string;\n\tspreadQuote: string;\n\tslot?: number;\n};\n\nexport type LiquidityType = 'vamm' | 'dlob' | 'serum' | 'phoenix' | 'openbook';\n\n/**\n * Helper function to deserialize the response from the dlob server. (See https://drift-labs.github.io/v2-teacher/#get-l2-l3)\n * @param serializedOrderbook\n * @returns\n */\nexport const deserializeL2Response = (\n\tserializedOrderbook: RawL2Output\n): L2WithOracleAndMarketData => {\n\treturn {\n\t\tasks: serializedOrderbook.asks.map((ask) => ({\n\t\t\tprice: new BN(ask.price),\n\t\t\tsize: new BN(ask.size),\n\t\t\tsources: Object.entries(ask.sources).reduce((previous, [key, val]) => {\n\t\t\t\treturn {\n\t\t\t\t\t...previous,\n\t\t\t\t\t[key]: new BN(val),\n\t\t\t\t};\n\t\t\t}, {}),\n\t\t})),\n\t\tbids: serializedOrderbook.bids.map((bid) => ({\n\t\t\tprice: new BN(bid.price),\n\t\t\tsize: new BN(bid.size),\n\t\t\tsources: Object.entries(bid.sources).reduce((previous, [key, val]) => {\n\t\t\t\treturn {\n\t\t\t\t\t...previous,\n\t\t\t\t\t[key]: new BN(val),\n\t\t\t\t};\n\t\t\t}, {}),\n\t\t})),\n\t\toracleData: {\n\t\t\tprice: serializedOrderbook.oracleData.price\n\t\t\t\t? new BN(serializedOrderbook.oracleData.price)\n\t\t\t\t: undefined,\n\t\t\tslot: serializedOrderbook.oracleData.slot\n\t\t\t\t? new BN(serializedOrderbook.oracleData.slot)\n\t\t\t\t: undefined,\n\t\t\tconfidence: serializedOrderbook.oracleData.confidence\n\t\t\t\t? new BN(serializedOrderbook.oracleData.confidence)\n\t\t\t\t: undefined,\n\t\t\thasSufficientNumberOfDataPoints:\n\t\t\t\tserializedOrderbook.oracleData.hasSufficientNumberOfDataPoints,\n\t\t\ttwap: serializedOrderbook.oracleData.twap\n\t\t\t\t? new BN(serializedOrderbook.oracleData.twap)\n\t\t\t\t: undefined,\n\t\t\ttwapConfidence: serializedOrderbook.oracleData.twapConfidence\n\t\t\t\t? new BN(serializedOrderbook.oracleData.twapConfidence)\n\t\t\t\t: undefined,\n\t\t\tmaxPrice: serializedOrderbook.oracleData.maxPrice\n\t\t\t\t? new BN(serializedOrderbook.oracleData.maxPrice)\n\t\t\t\t: undefined,\n\t\t},\n\t\tmmOracleData: {\n\t\t\tprice: serializedOrderbook.mmOracleData?.price\n\t\t\t\t? new BN(serializedOrderbook.mmOracleData.price)\n\t\t\t\t: undefined,\n\t\t\tslot: serializedOrderbook.mmOracleData?.slot\n\t\t\t\t? new BN(serializedOrderbook.mmOracleData.slot)\n\t\t\t\t: undefined,\n\t\t\tconfidence: serializedOrderbook.mmOracleData?.confidence\n\t\t\t\t? new BN(serializedOrderbook.mmOracleData.confidence)\n\t\t\t\t: undefined,\n\t\t\thasSufficientNumberOfDataPoints:\n\t\t\t\tserializedOrderbook.mmOracleData?.hasSufficientNumberOfDataPoints,\n\t\t\tisMMOracleActive:\n\t\t\t\tserializedOrderbook.mmOracleData?.isMMOracleActive ?? false,\n\t\t},\n\t\tslot: serializedOrderbook.slot,\n\t\tmarketSlot: serializedOrderbook.marketSlot,\n\t\tmarketType: serializedOrderbook.marketType,\n\t\tmarketIndex: serializedOrderbook.marketIndex,\n\t\tmarketName: serializedOrderbook.marketName,\n\t\tmarkPrice: new BN(serializedOrderbook.markPrice),\n\t\tbestBidPrice: new BN(serializedOrderbook.bestBidPrice),\n\t\tbestAskPrice: new BN(serializedOrderbook.bestAskPrice),\n\t\tspreadPct: new BN(serializedOrderbook.spreadPct),\n\t\tspreadQuote: new BN(serializedOrderbook.spreadQuote),\n\t};\n};\n"]}
@@ -0,0 +1,9 @@
1
+ export declare const LATE_POLLING_RESPONSE: unique symbol;
2
+ /**
3
+ * Utility class which makes sure that asyncronous responses get rejected when we expect them to return in the same sequence that we request them but they don't
4
+ */
5
+ export declare class PollingSequenceGuard {
6
+ static pollingCounts: Map<string | symbol, number>;
7
+ static LATE_POLLING_RESPONSE: symbol;
8
+ static fetch<T>(key: string | symbol, cb: () => Promise<T>): Promise<T>;
9
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PollingSequenceGuard = exports.LATE_POLLING_RESPONSE = void 0;
4
+ exports.LATE_POLLING_RESPONSE = Symbol('Late polling response');
5
+ /**
6
+ * Utility class which makes sure that asyncronous responses get rejected when we expect them to return in the same sequence that we request them but they don't
7
+ */
8
+ class PollingSequenceGuard {
9
+ static async fetch(key, cb) {
10
+ var _a, _b;
11
+ const newCount = ((_a = this.pollingCounts.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
12
+ const promise = await cb();
13
+ const latestCount = (_b = this.pollingCounts.get(key)) !== null && _b !== void 0 ? _b : 0;
14
+ if (latestCount > newCount) {
15
+ return Promise.reject(exports.LATE_POLLING_RESPONSE);
16
+ }
17
+ this.pollingCounts.set(key, newCount);
18
+ return promise;
19
+ }
20
+ }
21
+ exports.PollingSequenceGuard = PollingSequenceGuard;
22
+ PollingSequenceGuard.pollingCounts = new Map();
23
+ PollingSequenceGuard.LATE_POLLING_RESPONSE = exports.LATE_POLLING_RESPONSE;
24
+ //# sourceMappingURL=pollingSequenceGuard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pollingSequenceGuard.js","sourceRoot":"","sources":["../../src/utils/pollingSequenceGuard.ts"],"names":[],"mappings":";;;AAAa,QAAA,qBAAqB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAErE;;GAEG;AACH,MAAa,oBAAoB;IAGhC,MAAM,CAAC,KAAK,CAAC,KAAK,CACjB,GAAoB,EACpB,EAAoB;;QAEpB,MAAM,QAAQ,GAAG,CAAC,MAAA,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,mCAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QAExD,MAAM,OAAO,GAAG,MAAM,EAAE,EAAE,CAAC;QAE3B,MAAM,WAAW,GAAG,MAAA,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,mCAAI,CAAC,CAAC;QAErD,IAAI,WAAW,GAAG,QAAQ,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,MAAM,CAAC,6BAAqB,CAAC,CAAC;QAC9C,CAAC;QAED,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAEtC,OAAO,OAAO,CAAC;IAChB,CAAC;;AApBF,oDAqBC;AApBO,kCAAa,GAAG,IAAI,GAAG,EAA2B,CAAC;AACnD,0CAAqB,GAAG,6BAAqB,CAAC","sourcesContent":["export const LATE_POLLING_RESPONSE = Symbol('Late polling response');\n\n/**\n * Utility class which makes sure that asyncronous responses get rejected when we expect them to return in the same sequence that we request them but they don't\n */\nexport class PollingSequenceGuard {\n\tstatic pollingCounts = new Map<string | symbol, number>();\n\tstatic LATE_POLLING_RESPONSE = LATE_POLLING_RESPONSE;\n\tstatic async fetch<T>(\n\t\tkey: string | symbol,\n\t\tcb: () => Promise<T>\n\t): Promise<T> {\n\t\tconst newCount = (this.pollingCounts.get(key) ?? 0) + 1;\n\n\t\tconst promise = await cb();\n\n\t\tconst latestCount = this.pollingCounts.get(key) ?? 0;\n\n\t\tif (latestCount > newCount) {\n\t\t\treturn Promise.reject(LATE_POLLING_RESPONSE);\n\t\t}\n\n\t\tthis.pollingCounts.set(key, newCount);\n\n\t\treturn promise;\n\t}\n}\n"]}