@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,24 @@
1
+ export declare const DRIFT_TX_COMPUTE_UNIT_ESTIMATE = 600000;
2
+ export declare const SANITY_CHECK_ABS_MAX_FEE_IN_SOL = 1;
3
+ export declare const SANITY_CHECK_ABS_MAX_CU_PRICE: number;
4
+ /**
5
+ * The goal of this class is to encapsulate all logic around "priority fee calculation". The majority of the complexity is in calculating the dynamic priority fees, because the other settings are very simple.
6
+ *
7
+ * Priority Fees are determined by a "compute unit price". The compute unit price is denominated in "micro-lamports per compute unit". The end fee for the transactions is calculated as:
8
+ * FEE_LAMPORTS = COMPUTE_UNIT_PRICE_MICRO_LAMPORTS * COMPUTE_UNITS / 10^6
9
+ */
10
+ export declare class PriorityFeeCalculator {
11
+ constructor();
12
+ /**
13
+ * The baseline dynamic compute units price is the "target" price to use. It is based on the latest
14
+ * results on the priority fee subscriber, and some other contextual information.
15
+ */
16
+ static calculateDynamicCUPriceToUse({ latestFeeSample, boostMultiplier, extraMultiplier, }: {
17
+ latestFeeSample: number;
18
+ boostMultiplier?: number;
19
+ extraMultiplier?: number;
20
+ }): number;
21
+ static getPriorityFeeInSolForComputeUnitPrice(computeUnitPrice: number, txComputeUnits?: number): number;
22
+ static calculatePriorityFeeInUsd(computeUnitPrice: number, solPrice: number, txComputeUnits?: number): number;
23
+ static calculateCUPriceForTargetSolValue(targetSolValue: number, txComputeUnits?: number): number;
24
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PriorityFeeCalculator = exports.SANITY_CHECK_ABS_MAX_CU_PRICE = exports.SANITY_CHECK_ABS_MAX_FEE_IN_SOL = exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ function calculateCUPriceForTargetSolValue(targetSolValue, txComputeUnits = exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE) {
6
+ const targetFeeInLamports = targetSolValue * web3_js_1.LAMPORTS_PER_SOL;
7
+ const targetFeeInMicroLamports = targetFeeInLamports * 10 ** 6;
8
+ const targetMicroLamportsPerComputeUnit = Math.round(targetFeeInMicroLamports / txComputeUnits);
9
+ return targetMicroLamportsPerComputeUnit;
10
+ }
11
+ exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE = 600000;
12
+ exports.SANITY_CHECK_ABS_MAX_FEE_IN_SOL = 1;
13
+ exports.SANITY_CHECK_ABS_MAX_CU_PRICE = calculateCUPriceForTargetSolValue(exports.SANITY_CHECK_ABS_MAX_FEE_IN_SOL, exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE);
14
+ const getSanityCheckedCUPrice = (cuPrice) => {
15
+ return Math.min(cuPrice, exports.SANITY_CHECK_ABS_MAX_CU_PRICE);
16
+ };
17
+ /**
18
+ * The goal of this class is to encapsulate all logic around "priority fee calculation". The majority of the complexity is in calculating the dynamic priority fees, because the other settings are very simple.
19
+ *
20
+ * Priority Fees are determined by a "compute unit price". The compute unit price is denominated in "micro-lamports per compute unit". The end fee for the transactions is calculated as:
21
+ * FEE_LAMPORTS = COMPUTE_UNIT_PRICE_MICRO_LAMPORTS * COMPUTE_UNITS / 10^6
22
+ */
23
+ class PriorityFeeCalculator {
24
+ constructor() { }
25
+ /**
26
+ * The baseline dynamic compute units price is the "target" price to use. It is based on the latest
27
+ * results on the priority fee subscriber, and some other contextual information.
28
+ */
29
+ static calculateDynamicCUPriceToUse({ latestFeeSample, boostMultiplier = 1, extraMultiplier = 1, }) {
30
+ // Calculate baseline fee using the average of the most recent subscriber fee results, to normalise swings in priority fee from block to block
31
+ let baseLineCUPrice = latestFeeSample;
32
+ // add the boost multiplier
33
+ baseLineCUPrice *= boostMultiplier;
34
+ // add an extra multiplier (default to 1) that comes from env var, can be increased thru vercel during turbulence
35
+ baseLineCUPrice *= extraMultiplier;
36
+ // round
37
+ baseLineCUPrice = Math.round(baseLineCUPrice);
38
+ return getSanityCheckedCUPrice(baseLineCUPrice);
39
+ }
40
+ static getPriorityFeeInSolForComputeUnitPrice(computeUnitPrice, txComputeUnits = exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE) {
41
+ const priorityFeeInLamports = Math.round(txComputeUnits * (computeUnitPrice / 10 ** 6)); // Compute units are in microLamports (10**6) / computeUnit
42
+ const priorityFeeInSol = priorityFeeInLamports / web3_js_1.LAMPORTS_PER_SOL;
43
+ return +priorityFeeInSol.toFixed(Math.log10(web3_js_1.LAMPORTS_PER_SOL));
44
+ }
45
+ static calculatePriorityFeeInUsd(computeUnitPrice, solPrice, txComputeUnits = exports.DRIFT_TX_COMPUTE_UNIT_ESTIMATE) {
46
+ return (this.getPriorityFeeInSolForComputeUnitPrice(computeUnitPrice, txComputeUnits) * solPrice);
47
+ }
48
+ static calculateCUPriceForTargetSolValue(targetSolValue, txComputeUnits) {
49
+ return calculateCUPriceForTargetSolValue(targetSolValue, txComputeUnits);
50
+ }
51
+ }
52
+ exports.PriorityFeeCalculator = PriorityFeeCalculator;
53
+ //# sourceMappingURL=PriorityFeeCalculator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PriorityFeeCalculator.js","sourceRoot":"","sources":["../../../src/utils/priority-fees/PriorityFeeCalculator.ts"],"names":[],"mappings":";;;AAAA,6CAAmD;AAEnD,SAAS,iCAAiC,CACzC,cAAsB,EACtB,cAAc,GAAG,sCAA8B;IAE/C,MAAM,mBAAmB,GAAG,cAAc,G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B,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,0BAAgB,CAAC,CAAC,CAAC;IAChE,CAAC;IAEM,MAAM,CAAC,yBAAyB,CACtC,gBAAwB,EACxB,QAAgB,EAChB,cAAc,GAAG,sCAA8B;QAE/C,OAAO,CACN,IAAI,CAAC,sCAAsC,CAC1C,gBAAgB,EAChB,cAAc,CACd,GAAG,QAAQ,CACZ,CAAC;IACH,CAAC;IAEM,MAAM,CAAC,iCAAiC,CAC9C,cAAsB,EACtB,cAAuB;QAEvB,OAAO,iCAAiC,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IAC1E,CAAC;CACD;AA9DD,sDA8DC","sourcesContent":["import { LAMPORTS_PER_SOL } from '@solana/web3.js';\n\nfunction calculateCUPriceForTargetSolValue(\n\ttargetSolValue: number,\n\ttxComputeUnits = DRIFT_TX_COMPUTE_UNIT_ESTIMATE\n) {\n\tconst targetFeeInLamports = targetSolValue * LAMPORTS_PER_SOL;\n\tconst targetFeeInMicroLamports = targetFeeInLamports * 10 ** 6;\n\n\tconst targetMicroLamportsPerComputeUnit = Math.round(\n\t\ttargetFeeInMicroLamports / txComputeUnits\n\t);\n\n\treturn targetMicroLamportsPerComputeUnit;\n}\n\nexport const DRIFT_TX_COMPUTE_UNIT_ESTIMATE = 600_000;\n\nexport const SANITY_CHECK_ABS_MAX_FEE_IN_SOL = 1;\nexport const SANITY_CHECK_ABS_MAX_CU_PRICE = calculateCUPriceForTargetSolValue(\n\tSANITY_CHECK_ABS_MAX_FEE_IN_SOL,\n\tDRIFT_TX_COMPUTE_UNIT_ESTIMATE\n);\n\nconst getSanityCheckedCUPrice = (cuPrice: number) => {\n\treturn Math.min(cuPrice, SANITY_CHECK_ABS_MAX_CU_PRICE);\n};\n\n/**\n * The goal of this class is to encapsulate all logic around \"priority fee calculation\". The majority of the complexity is in calculating the dynamic priority fees, because the other settings are very simple.\n *\n * Priority Fees are determined by a \"compute unit price\". The compute unit price is denominated in \"micro-lamports per compute unit\". The end fee for the transactions is calculated as:\n * FEE_LAMPORTS = COMPUTE_UNIT_PRICE_MICRO_LAMPORTS * COMPUTE_UNITS / 10^6\n */\nexport class PriorityFeeCalculator {\n\tconstructor() {}\n\n\t/**\n\t * The baseline dynamic compute units price is the \"target\" price to use. It is based on the latest\n\t * results on the priority fee subscriber, and some other contextual information.\n\t */\n\tpublic static calculateDynamicCUPriceToUse({\n\t\tlatestFeeSample,\n\t\tboostMultiplier = 1,\n\t\textraMultiplier = 1,\n\t}: {\n\t\tlatestFeeSample: number;\n\t\tboostMultiplier?: number;\n\t\textraMultiplier?: number;\n\t}) {\n\t\t// Calculate baseline fee using the average of the most recent subscriber fee results, to normalise swings in priority fee from block to block\n\t\tlet baseLineCUPrice = latestFeeSample;\n\n\t\t// add the boost multiplier\n\t\tbaseLineCUPrice *= boostMultiplier;\n\n\t\t// add an extra multiplier (default to 1) that comes from env var, can be increased thru vercel during turbulence\n\t\tbaseLineCUPrice *= extraMultiplier;\n\n\t\t// round\n\t\tbaseLineCUPrice = Math.round(baseLineCUPrice);\n\n\t\treturn getSanityCheckedCUPrice(baseLineCUPrice);\n\t}\n\n\tpublic static getPriorityFeeInSolForComputeUnitPrice(\n\t\tcomputeUnitPrice: number,\n\t\ttxComputeUnits = DRIFT_TX_COMPUTE_UNIT_ESTIMATE\n\t) {\n\t\tconst priorityFeeInLamports = Math.round(\n\t\t\ttxComputeUnits * (computeUnitPrice / 10 ** 6)\n\t\t); // Compute units are in microLamports (10**6) / computeUnit\n\t\tconst priorityFeeInSol = priorityFeeInLamports / LAMPORTS_PER_SOL;\n\n\t\treturn +priorityFeeInSol.toFixed(Math.log10(LAMPORTS_PER_SOL));\n\t}\n\n\tpublic static calculatePriorityFeeInUsd(\n\t\tcomputeUnitPrice: number,\n\t\tsolPrice: number,\n\t\ttxComputeUnits = DRIFT_TX_COMPUTE_UNIT_ESTIMATE\n\t) {\n\t\treturn (\n\t\t\tthis.getPriorityFeeInSolForComputeUnitPrice(\n\t\t\t\tcomputeUnitPrice,\n\t\t\t\ttxComputeUnits\n\t\t\t) * solPrice\n\t\t);\n\t}\n\n\tpublic static calculateCUPriceForTargetSolValue(\n\t\ttargetSolValue: number,\n\t\ttxComputeUnits?: number\n\t) {\n\t\treturn calculateCUPriceForTargetSolValue(targetSolValue, txComputeUnits);\n\t}\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { PriorityFeeStrategy } from '@drift-labs/sdk';
2
+ export declare const PriorityFeeStrategyFactory: {
3
+ default: (feeStrategyTargetPercentile: number, feeSubscriptionSlotLookback: number) => PriorityFeeStrategy;
4
+ movingWindowTargetPercentileStrategy: (feeStrategyTargetPercentile: number, feeSubscriptionSlotLookback: number) => PriorityFeeStrategy;
5
+ };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PriorityFeeStrategyFactory = void 0;
4
+ /**
5
+ * Default strategy. Keeps a moving window of fee samples from the past x slots, and returns the target percentile fee from the samples.
6
+ *
7
+ * @param feeStrategyTargetPercentile
8
+ * @param feeSubscriptionSlotLookback
9
+ * @returns
10
+ */
11
+ const movingWindowTargetPercentileStrategy = (feeStrategyTargetPercentile, feeSubscriptionSlotLookback) => {
12
+ const RECENT_SAMPLES = [];
13
+ let LAST_SEEN_SLOT_IN_SAMPLES = 0;
14
+ return {
15
+ calculate(newSamples) {
16
+ if (!(newSamples === null || newSamples === void 0 ? void 0 : newSamples.length))
17
+ return 0;
18
+ const filteredSamples = newSamples.filter((sample) => sample.slot > LAST_SEEN_SLOT_IN_SAMPLES &&
19
+ sample.prioritizationFee > 0);
20
+ RECENT_SAMPLES.unshift(filteredSamples.map((s) => s.prioritizationFee));
21
+ RECENT_SAMPLES.splice(feeSubscriptionSlotLookback);
22
+ const allRecentSamplesAscendingSorted = RECENT_SAMPLES.flat().sort((a, b) => {
23
+ return a - b;
24
+ });
25
+ const targetPercentileIndex = Math.min(allRecentSamplesAscendingSorted.length - 1, Math.ceil((allRecentSamplesAscendingSorted.length / 100) *
26
+ feeStrategyTargetPercentile));
27
+ const shouldSplitWithBelow = feeStrategyTargetPercentile < 100 &&
28
+ targetPercentileIndex >= allRecentSamplesAscendingSorted.length - 1; // If the number of samples being returned are sufficiently small then in practise the target percentile is just selecting the MAX priority fee every time. For some safety, average top two instead when we get this case.
29
+ const pFee = shouldSplitWithBelow
30
+ ? (allRecentSamplesAscendingSorted[targetPercentileIndex] +
31
+ allRecentSamplesAscendingSorted[targetPercentileIndex - 1]) /
32
+ 2
33
+ : allRecentSamplesAscendingSorted[targetPercentileIndex];
34
+ LAST_SEEN_SLOT_IN_SAMPLES = Math.max(...filteredSamples.map((sample) => sample.slot));
35
+ return pFee;
36
+ },
37
+ };
38
+ };
39
+ exports.PriorityFeeStrategyFactory = {
40
+ default: movingWindowTargetPercentileStrategy,
41
+ movingWindowTargetPercentileStrategy: movingWindowTargetPercentileStrategy,
42
+ };
43
+ //# sourceMappingURL=PriorityFeeStrategies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PriorityFeeStrategies.js","sourceRoot":"","sources":["../../../src/utils/priority-fees/PriorityFeeStrategies.ts"],"names":[],"mappings":";;;AAKA;;;;;;GAMG;AACH,MAAM,oCAAoC,GAAG,CAC5C,2BAAmC,EACnC,2BAAmC,EACb,EAAE;IACxB,MAAM,cAAc,GAAe,EAAE,CAAC;IACtC,IAAI,yBAAyB,GAAG,CAAC,CAAC;IAElC,OAAO;QACN,SAAS,CAAC,UAAuC;YAChD,IAAI,CAAC,CAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,MAAM,CAAA;gBAAE,OAAO,CAAC,CAAC;YAElC,MAAM,eAAe,GAAG,UAAU,CAAC,MAAM,CACxC,CAAC,MAAM,EAAE,EAAE,CACV,MAAM,CAAC,IAAI,GAAG,yBAAyB;gBACvC,MAAM,CAAC,iBAAiB,GAAG,CAAC,CAC7B,CAAC;YAEF,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC;YACxE,cAAc,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;YAEnD,MAAM,+BAA+B,GAAG,cAAc,CAAC,IAAI,EAAE,CAAC,IAAI,CACjE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBACR,OAAO,CAAC,GAAG,CAAC,CAAC;YACd,CAAC,CACD,CAAC;YAEF,MAAM,qBAAqB,GAAG,IAAI,CAAC,GAAG,CACrC,+BAA+B,CAAC,MAAM,GAAG,CAAC,EAC1C,IAAI,CAAC,IAAI,CACR,CAAC,+BAA+B,CAAC,MAAM,GAAG,GAAG,CAAC;gBAC7C,2BAA2B,CAC5B,CACD,CAAC;YAEF,MAAM,oBAAoB,GACzB,2BAA2B,GAAG,GAAG;gBACjC,qBAAqB,IAAI,+BAA+B,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,2NAA2N;YAEjS,MAAM,IAAI,GAAG,oBAAoB;gBAChC,CAAC,CAAC,CAAC,+BAA+B,CAAC,qBAAqB,CAAC;oBACvD,+BAA+B,CAAC,qBAAqB,GAAG,CAAC,CAAC,CAAC;oBAC3D,CAAC;gBACH,CAAC,CAAC,+BAA+B,CAAC,qBAAqB,CAAC,CAAC;YAE1D,yBAAyB,GAAG,IAAI,CAAC,GAAG,CACnC,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAC/C,CAAC;YAEF,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC,CAAC;AAEW,QAAA,0BAA0B,GAAG;IACzC,OAAO,EAAE,oCAAoC;IAC7C,oCAAoC,EAAE,oCAAoC;CAC1E,CAAC","sourcesContent":["import {\n\tPriorityFeeStrategy,\n\tSolanaPriorityFeeResponse,\n} from '@drift-labs/sdk';\n\n/**\n * Default strategy. Keeps a moving window of fee samples from the past x slots, and returns the target percentile fee from the samples.\n *\n * @param feeStrategyTargetPercentile\n * @param feeSubscriptionSlotLookback\n * @returns\n */\nconst movingWindowTargetPercentileStrategy = (\n\tfeeStrategyTargetPercentile: number,\n\tfeeSubscriptionSlotLookback: number\n): PriorityFeeStrategy => {\n\tconst RECENT_SAMPLES: number[][] = [];\n\tlet LAST_SEEN_SLOT_IN_SAMPLES = 0;\n\n\treturn {\n\t\tcalculate(newSamples: SolanaPriorityFeeResponse[]) {\n\t\t\tif (!newSamples?.length) return 0;\n\n\t\t\tconst filteredSamples = newSamples.filter(\n\t\t\t\t(sample) =>\n\t\t\t\t\tsample.slot > LAST_SEEN_SLOT_IN_SAMPLES &&\n\t\t\t\t\tsample.prioritizationFee > 0\n\t\t\t);\n\n\t\t\tRECENT_SAMPLES.unshift(filteredSamples.map((s) => s.prioritizationFee));\n\t\t\tRECENT_SAMPLES.splice(feeSubscriptionSlotLookback);\n\n\t\t\tconst allRecentSamplesAscendingSorted = RECENT_SAMPLES.flat().sort(\n\t\t\t\t(a, b) => {\n\t\t\t\t\treturn a - b;\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tconst targetPercentileIndex = Math.min(\n\t\t\t\tallRecentSamplesAscendingSorted.length - 1,\n\t\t\t\tMath.ceil(\n\t\t\t\t\t(allRecentSamplesAscendingSorted.length / 100) *\n\t\t\t\t\t\tfeeStrategyTargetPercentile\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tconst shouldSplitWithBelow =\n\t\t\t\tfeeStrategyTargetPercentile < 100 &&\n\t\t\t\ttargetPercentileIndex >= allRecentSamplesAscendingSorted.length - 1; // If the number of samples being returned are sufficiently small then in practise the target percentile is just selecting the MAX priority fee every time. For some safety, average top two instead when we get this case.\n\n\t\t\tconst pFee = shouldSplitWithBelow\n\t\t\t\t? (allRecentSamplesAscendingSorted[targetPercentileIndex] +\n\t\t\t\t\t\tallRecentSamplesAscendingSorted[targetPercentileIndex - 1]) /\n\t\t\t\t 2\n\t\t\t\t: allRecentSamplesAscendingSorted[targetPercentileIndex];\n\n\t\t\tLAST_SEEN_SLOT_IN_SAMPLES = Math.max(\n\t\t\t\t...filteredSamples.map((sample) => sample.slot)\n\t\t\t);\n\n\t\t\treturn pFee;\n\t\t},\n\t};\n};\n\nexport const PriorityFeeStrategyFactory = {\n\tdefault: movingWindowTargetPercentileStrategy,\n\tmovingWindowTargetPercentileStrategy: movingWindowTargetPercentileStrategy,\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './PriorityFeeCalculator';
2
+ export * from './PriorityFeeStrategies';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./PriorityFeeCalculator"), exports);
18
+ __exportStar(require("./PriorityFeeStrategies"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/priority-fees/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0DAAwC;AACxC,0DAAwC","sourcesContent":["export * from './PriorityFeeCalculator';\nexport * from './PriorityFeeStrategies';\n"]}
@@ -0,0 +1,14 @@
1
+ import { MarketId } from 'src/types';
2
+ export declare const getPriorityFeeLevelFromPercentile: (percentile: number) => "min" | "low" | "medium" | "high" | "veryHigh" | "unsafeMax";
3
+ /**
4
+ * Helius fee buckets are as follows:
5
+ *
6
+ * none: 0th percentile
7
+ * low: 25th percentile
8
+ * medium: 50th percentile
9
+ * high: 75th percentile
10
+ * veryHigh: 95th percentile
11
+ * unsafeMax: 100th percentile
12
+ * default: 50th percentile
13
+ */
14
+ export declare const getHeliusPriorityFeeEstimate: (marketIds: MarketId[], priorityFeeLevel?: 'min' | 'low' | 'medium' | 'high' | 'veryHigh' | 'unsafeMax') => Promise<number[]>;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHeliusPriorityFeeEstimate = exports.getPriorityFeeLevelFromPercentile = void 0;
4
+ const FEE_ENDPOINT = 'https://dlob.drift.trade/batchPriorityFees';
5
+ const getPriorityFeeLevelFromPercentile = (percentile) => {
6
+ if (percentile < 0 || percentile > 100) {
7
+ throw new Error('Percentile must be between 0 and 100');
8
+ }
9
+ if (percentile === 0) {
10
+ return 'min';
11
+ }
12
+ if (percentile <= 25) {
13
+ return 'low';
14
+ }
15
+ if (percentile <= 50) {
16
+ return 'medium';
17
+ }
18
+ if (percentile <= 75) {
19
+ return 'high';
20
+ }
21
+ if (percentile <= 95) {
22
+ return 'veryHigh';
23
+ }
24
+ return 'unsafeMax';
25
+ };
26
+ exports.getPriorityFeeLevelFromPercentile = getPriorityFeeLevelFromPercentile;
27
+ /**
28
+ * Helius fee buckets are as follows:
29
+ *
30
+ * none: 0th percentile
31
+ * low: 25th percentile
32
+ * medium: 50th percentile
33
+ * high: 75th percentile
34
+ * veryHigh: 95th percentile
35
+ * unsafeMax: 100th percentile
36
+ * default: 50th percentile
37
+ */
38
+ const getHeliusPriorityFeeEstimate = async (marketIds, priorityFeeLevel = 'high') => {
39
+ try {
40
+ if (!(marketIds === null || marketIds === void 0 ? void 0 : marketIds.length)) {
41
+ return [];
42
+ }
43
+ const queryParamsMap = {
44
+ marketType: marketIds.map((market) => market.marketTypeStr).join(','),
45
+ marketIndex: marketIds.map((market) => market.marketIndex).join(','),
46
+ };
47
+ const queryParams = Object.entries(queryParamsMap)
48
+ .filter(([_key, param]) => param !== undefined)
49
+ .map(([key, param]) => {
50
+ return `${key}=${param}`;
51
+ });
52
+ const queryParamsString = `${queryParams.join('&')}`;
53
+ const response = await fetch(`${FEE_ENDPOINT}?${queryParamsString}`, {
54
+ headers: { 'Content-Type': 'application/json' },
55
+ });
56
+ const result = (await response.json());
57
+ if (!response.ok) {
58
+ return undefined;
59
+ }
60
+ const feeLevelValues = result.map((result) => result === null || result === void 0 ? void 0 : result[priorityFeeLevel]);
61
+ return feeLevelValues;
62
+ }
63
+ catch (e) {
64
+ return undefined;
65
+ }
66
+ };
67
+ exports.getHeliusPriorityFeeEstimate = getHeliusPriorityFeeEstimate;
68
+ //# sourceMappingURL=priorityFees.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"priorityFees.js","sourceRoot":"","sources":["../../src/utils/priorityFees.ts"],"names":[],"mappings":";;;AAEA,MAAM,YAAY,GAAG,4CAA4C,CAAC;AAE3D,MAAM,iCAAiC,GAAG,CAAC,UAAkB,EAAE,EAAE;IACvE,IAAI,UAAU,GAAG,CAAC,IAAI,UAAU,GAAG,GAAG,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;QACtB,OAAO,KAAK,CAAC;IACd,CAAC;IAED,IAAI,UAAU,IAAI,EAAE,EAAE,CAAC;QACtB,OAAO,KAAK,CAAC;IACd,CAAC;IACD,IAAI,UAAU,IAAI,EAAE,EAAE,CAAC;QACtB,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,IAAI,UAAU,IAAI,EAAE,EAAE,CAAC;QACtB,OAAO,MAAM,CAAC;IACf,CAAC;IACD,IAAI,UAAU,IAAI,EAAE,EAAE,CAAC;QACtB,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,O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EAAE,CAAC;YAClB,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAG,gBAAgB,CAAC,CAAC,CAAC;QAE1E,OAAO,cAAc,CAAC;IACvB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC,CAAC;AAjDW,QAAA,4BAA4B,gCAiDvC","sourcesContent":["import { MarketId } from 'src/types';\n\nconst FEE_ENDPOINT = 'https://dlob.drift.trade/batchPriorityFees';\n\nexport const getPriorityFeeLevelFromPercentile = (percentile: number) => {\n\tif (percentile < 0 || percentile > 100) {\n\t\tthrow new Error('Percentile must be between 0 and 100');\n\t}\n\n\tif (percentile === 0) {\n\t\treturn 'min';\n\t}\n\n\tif (percentile <= 25) {\n\t\treturn 'low';\n\t}\n\tif (percentile <= 50) {\n\t\treturn 'medium';\n\t}\n\tif (percentile <= 75) {\n\t\treturn 'high';\n\t}\n\tif (percentile <= 95) {\n\t\treturn 'veryHigh';\n\t}\n\n\treturn 'unsafeMax';\n};\n\n/**\n * Helius fee buckets are as follows:\n *\n * none: 0th percentile\n * low: 25th percentile\n * medium: 50th percentile\n * high: 75th percentile\n * veryHigh: 95th percentile\n * unsafeMax: 100th percentile\n * default: 50th percentile\n */\nexport const getHeliusPriorityFeeEstimate = async (\n\tmarketIds: MarketId[],\n\tpriorityFeeLevel:\n\t\t| 'min'\n\t\t| 'low'\n\t\t| 'medium'\n\t\t| 'high'\n\t\t| 'veryHigh'\n\t\t| 'unsafeMax' = 'high'\n): Promise<number[]> => {\n\ttry {\n\t\tif (!marketIds?.length) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst queryParamsMap = {\n\t\t\tmarketType: marketIds.map((market) => market.marketTypeStr).join(','),\n\t\t\tmarketIndex: marketIds.map((market) => market.marketIndex).join(','),\n\t\t};\n\t\tconst queryParams = Object.entries(queryParamsMap)\n\t\t\t.filter(([_key, param]) => param !== undefined)\n\t\t\t.map(([key, param]) => {\n\t\t\t\treturn `${key}=${param}`;\n\t\t\t});\n\t\tconst queryParamsString = `${queryParams.join('&')}`;\n\n\t\tconst response = await fetch(`${FEE_ENDPOINT}?${queryParamsString}`, {\n\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t});\n\n\t\tconst result = (await response.json()) as {\n\t\t\tmin: number;\n\t\t\tlow: number;\n\t\t\tmedium: number;\n\t\t\thigh: number;\n\t\t\tveryHigh: number;\n\t\t\tunsafeMax: number;\n\t\t}[];\n\n\t\tif (!response.ok) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst feeLevelValues = result.map((result) => result?.[priorityFeeLevel]);\n\n\t\treturn feeLevelValues;\n\t} catch (e) {\n\t\treturn undefined;\n\t}\n};\n"]}
@@ -0,0 +1,7 @@
1
+ import { RpcEndpoint } from 'src/EnvironmentConstants';
2
+ export declare const getResponseTimes: (rpcOptions: RpcEndpoint[]) => Promise<{
3
+ value: string;
4
+ latency: number;
5
+ }[]>;
6
+ export declare const getRpcWithLowestPing: (rpcEndpoints: RpcEndpoint[]) => Promise<RpcEndpoint>;
7
+ export declare const getResponseTime: (endpoint: string) => Promise<number>;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getResponseTime = exports.getRpcWithLowestPing = exports.getResponseTimes = void 0;
4
+ const getResponseTimes = async (rpcOptions) => {
5
+ const responseTimes = await Promise.all(rpcOptions.map(async (rpc) => {
6
+ const responseTime = await (0, exports.getResponseTime)(rpc.value);
7
+ return { value: rpc.value, latency: responseTime };
8
+ }));
9
+ return responseTimes.filter((result) => result.latency != null);
10
+ };
11
+ exports.getResponseTimes = getResponseTimes;
12
+ const getRpcWithLowestPing = async (rpcEndpoints) => {
13
+ const results = await Promise.all(rpcEndpoints.map((endpoint) => (0, exports.getResponseTime)(endpoint.value)));
14
+ const validResults = results.filter((responseTime) => responseTime !== -1 && responseTime != null);
15
+ if (validResults.length <= 0)
16
+ return undefined;
17
+ const lowestResponseTime = Math.min(...validResults);
18
+ const rpcIndex = results.indexOf(lowestResponseTime);
19
+ return rpcEndpoints[rpcIndex];
20
+ };
21
+ exports.getRpcWithLowestPing = getRpcWithLowestPing;
22
+ const getResponseTime = async (endpoint) => {
23
+ if (!endpoint)
24
+ return null;
25
+ const storage = typeof localStorage !== 'undefined'
26
+ ? localStorage
27
+ : require('localstorage-memory');
28
+ const accessToken = storage.getItem('auth-token');
29
+ const startTime = Date.now();
30
+ const result = await fetch(`${endpoint}`, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'Content-Type': 'application/json',
34
+ Authorization: 'Bearer ' + accessToken,
35
+ },
36
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
37
+ }).catch((err) => {
38
+ console.error('Error checking RPC response time ', err);
39
+ return null;
40
+ });
41
+ if (!result)
42
+ return -1;
43
+ if (!result.ok)
44
+ return -1;
45
+ const endTime = Date.now();
46
+ return endTime - startTime;
47
+ };
48
+ exports.getResponseTime = getResponseTime;
49
+ //# sourceMappingURL=rpcLatency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcLatency.js","sourceRoot":"","sources":["../../src/utils/rpcLatency.ts"],"names":[],"mappings":";;;AAEO,MAAM,gBAAgB,GAAG,KAAK,EAAE,UAAyB,EAAE,EAAE;IACnE,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CACtC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QAC5B,MAAM,YAAY,GAAG,MAAM,IAAA,uBAAe,EAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACtD,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC;IACpD,CAAC,CAAC,CACF,CAAC;IAEF,OAAO,aA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AE;QACzC,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACR,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,SAAS,GAAG,WAAW;SACtC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;KACpE,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;QAChB,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAC;QACxD,OAAO,IAAI,CAAC;IACb,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,MAAM;QAAE,OAAO,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,OAAO,CAAC,CAAC,CAAC;IAE1B,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAE3B,OAAO,OAAO,GAAG,SAAS,CAAC;AAC5B,CAAC,CAAC;AA7BW,QAAA,eAAe,mBA6B1B","sourcesContent":["import { RpcEndpoint } from 'src/EnvironmentConstants';\n\nexport const getResponseTimes = async (rpcOptions: RpcEndpoint[]) => {\n\tconst responseTimes = await Promise.all(\n\t\trpcOptions.map(async (rpc) => {\n\t\t\tconst responseTime = await getResponseTime(rpc.value);\n\t\t\treturn { value: rpc.value, latency: responseTime };\n\t\t})\n\t);\n\n\treturn responseTimes.filter((result) => result.latency != null);\n};\n\nexport const getRpcWithLowestPing = async (rpcEndpoints: RpcEndpoint[]) => {\n\tconst results = await Promise.all(\n\t\trpcEndpoints.map((endpoint) => getResponseTime(endpoint.value))\n\t);\n\n\tconst validResults = results.filter(\n\t\t(responseTime) => responseTime !== -1 && responseTime != null\n\t);\n\n\tif (validResults.length <= 0) return undefined;\n\n\tconst lowestResponseTime = Math.min(...validResults);\n\n\tconst rpcIndex = results.indexOf(lowestResponseTime);\n\n\treturn rpcEndpoints[rpcIndex];\n};\n\nexport const getResponseTime = async (endpoint: string): Promise<number> => {\n\tif (!endpoint) return null;\n\n\tconst storage =\n\t\ttypeof localStorage !== 'undefined'\n\t\t\t? localStorage\n\t\t\t: require('localstorage-memory');\n\n\tconst accessToken = storage.getItem('auth-token');\n\n\tconst startTime = Date.now();\n\tconst result = await fetch(`${endpoint}`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: 'Bearer ' + accessToken,\n\t\t},\n\t\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),\n\t}).catch((err) => {\n\t\tconsole.error('Error checking RPC response time ', err);\n\t\treturn null;\n\t});\n\n\tif (!result) return -1;\n\tif (!result.ok) return -1;\n\n\tconst endTime = Date.now();\n\n\treturn endTime - startTime;\n};\n"]}
@@ -0,0 +1,11 @@
1
+ import { Subject, Observable } from 'rxjs';
2
+ /**
3
+ * Deduplicated subject, using UniqueCircularBuffer to dedupe the input subject.
4
+ *
5
+ * The windowSize defines the amount of unique elements to keep in memory for the sake of deduplicating. Any incoming duplicate objects will NOT be added to the buffer so won't take up space.
6
+ * @param inputSubject
7
+ * @param windowSize maximum size of recent unique objects which will be stored to use for deduplication
8
+ * @param uniquenessKeyGenerator function that generates a unique key for an object
9
+ * @returns
10
+ */
11
+ export declare function dedupeSubject<T>(inputSubject: Subject<T>, windowSize: number, uniquenessKeyGenerator: (a: T) => string): Observable<T>;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dedupeSubject = void 0;
4
+ const operators_1 = require("rxjs/operators");
5
+ const UniqueCircularBuffer_1 = require("./CircularBuffers/UniqueCircularBuffer");
6
+ /**
7
+ * Deduplicated subject, using UniqueCircularBuffer to dedupe the input subject.
8
+ *
9
+ * The windowSize defines the amount of unique elements to keep in memory for the sake of deduplicating. Any incoming duplicate objects will NOT be added to the buffer so won't take up space.
10
+ * @param inputSubject
11
+ * @param windowSize maximum size of recent unique objects which will be stored to use for deduplication
12
+ * @param uniquenessKeyGenerator function that generates a unique key for an object
13
+ * @returns
14
+ */
15
+ function dedupeSubject(inputSubject, windowSize, uniquenessKeyGenerator) {
16
+ const buffer = new UniqueCircularBuffer_1.UniqueCircularBuffer(windowSize, uniquenessKeyGenerator);
17
+ const dedupedObservable = inputSubject.pipe((0, operators_1.filter)((value) => {
18
+ const added = buffer.add(value);
19
+ return added;
20
+ }), (0, operators_1.share)());
21
+ return dedupedObservable;
22
+ }
23
+ exports.dedupeSubject = dedupeSubject;
24
+ //# sourceMappingURL=rxjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rxjs.js","sourceRoot":"","sources":["../../src/utils/rxjs.ts"],"names":[],"mappings":";;;AACA,8CAA+C;AAC/C,iFAA8E;AAE9E;;;;;;;;GAQG;AACH,SAAgB,aAAa,CAC5B,YAAwB,EACxB,UAAkB,EAClB,sBAAwC;IAExC,MAAM,MAAM,GAAG,IAAI,2CAAoB,CACtC,UAAU,EACV,sBAAsB,CACtB,CAAC;IAEF,MAAM,iBAAiB,GAAG,YAAY,CAAC,IAAI,CAC1C,IAAA,kBAAM,EAAC,CAAC,KAAK,EAAE,EAAE;QAChB,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAEhC,OAAO,KAAK,CAAC;IACd,CAAC,CAAC,EACF,IAAA,iBAAK,GAAE,CACP,CAAC;IAEF,OAAO,iBAAiB,CAAC;AAC1B,CAAC;AApBD,sCAoBC","sourcesContent":["import { Subject, Observable } from 'rxjs';\nimport { filter, share } from 'rxjs/operators';\nimport { UniqueCircularBuffer } from './CircularBuffers/UniqueCircularBuffer';\n\n/**\n * Deduplicated subject, using UniqueCircularBuffer to dedupe the input subject.\n *\n * The windowSize defines the amount of unique elements to keep in memory for the sake of deduplicating. Any incoming duplicate objects will NOT be added to the buffer so won't take up space.\n * @param inputSubject\n * @param windowSize maximum size of recent unique objects which will be stored to use for deduplication\n * @param uniquenessKeyGenerator function that generates a unique key for an object\n * @returns\n */\nexport function dedupeSubject<T>(\n\tinputSubject: Subject<T>,\n\twindowSize: number,\n\tuniquenessKeyGenerator: (a: T) => string\n): Observable<T> {\n\tconst buffer = new UniqueCircularBuffer<T>(\n\t\twindowSize,\n\t\tuniquenessKeyGenerator\n\t);\n\n\tconst dedupedObservable = inputSubject.pipe(\n\t\tfilter((value) => {\n\t\t\tconst added = buffer.add(value);\n\n\t\t\treturn added;\n\t\t}),\n\t\tshare()\n\t);\n\n\treturn dedupedObservable;\n}\n"]}
@@ -0,0 +1,43 @@
1
+ import { DriftEnv } from '@drift-labs/sdk';
2
+ import { PnlSnapshotOrderOption, SnapshotEpochResolution } from '../types';
3
+ export type DownloadFile = {
4
+ key: string;
5
+ requestParams: DownloadRequestParams;
6
+ lastModifiedTs: number;
7
+ downloadUrl?: string;
8
+ };
9
+ export type DownloadRequestParams = {
10
+ fileType: DownloadRecordType;
11
+ requestedDate: string;
12
+ fromDate: string;
13
+ toDate: string;
14
+ user: string;
15
+ programId: string;
16
+ authority: string;
17
+ isEmulationMode: boolean;
18
+ marketSymbol?: string;
19
+ };
20
+ export type DownloadRecordType = 'trades' | 'market-trades' | 'funding-rates' | 'funding-payments' | 'deposits' | 'liquidations' | 'settle-pnl-records' | 'lp-records' | 'if-stake-records' | 'swap-records' | 'rewards';
21
+ export type DownloadPeriod = 'week' | 'month' | '3mo' | 'ytd' | 'year' | 'custom';
22
+ export declare const getFileRedisKeyFromParams: (downloadRequestParams: DownloadRequestParams) => string;
23
+ export declare const dateToS3DateString: (date: Date) => string;
24
+ export declare const s3DateStringToDate: (dateStr: string) => Date;
25
+ export declare const getDateRangeFromSelection: (downloadPeriod: DownloadPeriod, customOpts?: {
26
+ day?: number;
27
+ month?: number;
28
+ year: number;
29
+ }) => {
30
+ from: string;
31
+ to: string;
32
+ };
33
+ export declare const S3_LEADERBOARD_CLIENT: {
34
+ getFileName: (orderBy: PnlSnapshotOrderOption, resolution: SnapshotEpochResolution) => string;
35
+ getLeaderboardValue: (env: DriftEnv, leaderboardBucketName: string, orderBy: PnlSnapshotOrderOption, resolution: SnapshotEpochResolution) => Promise<import("../serializableTypes").UISerializableLeaderboardResult>;
36
+ };
37
+ declare const S3_BUCKET_UTILS: {
38
+ S3_LEADERBOARD_CLIENT: {
39
+ getFileName: (orderBy: PnlSnapshotOrderOption, resolution: SnapshotEpochResolution) => string;
40
+ getLeaderboardValue: (env: DriftEnv, leaderboardBucketName: string, orderBy: PnlSnapshotOrderOption, resolution: SnapshotEpochResolution) => Promise<import("../serializableTypes").UISerializableLeaderboardResult>;
41
+ };
42
+ };
43
+ export default S3_BUCKET_UTILS;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.S3_LEADERBOARD_CLIENT = exports.getDateRangeFromSelection = exports.s3DateStringToDate = exports.dateToS3DateString = exports.getFileRedisKeyFromParams = void 0;
4
+ const _1 = require(".");
5
+ const serializableTypes_1 = require("../serializableTypes");
6
+ const constants_1 = require("../constants");
7
+ // # Redis key for download requests is the downloadRequestParams with colon delimeters.
8
+ // # Stringifies the keys alphabetically so we don't have mismatches for identical requests
9
+ const getFileRedisKeyFromParams = (downloadRequestParams) => {
10
+ return Object.keys(downloadRequestParams)
11
+ .sort((a, b) => a.localeCompare(b))
12
+ .map((sortedKey) => downloadRequestParams[sortedKey])
13
+ .filter((val) => val !== undefined)
14
+ .join(':');
15
+ };
16
+ exports.getFileRedisKeyFromParams = getFileRedisKeyFromParams;
17
+ // # Converts a date object into the string format used for S3 files
18
+ const dateToS3DateString = (date) => {
19
+ const year = date.getFullYear();
20
+ const month = date.getMonth() + 1;
21
+ const day = date.getDate();
22
+ return `${year}${month < 10 ? '0' + month : month}${day < 10 ? '0' + day : day}`;
23
+ };
24
+ exports.dateToS3DateString = dateToS3DateString;
25
+ // # Converts a string date in S3 file format into a Date object
26
+ const s3DateStringToDate = (dateStr) => {
27
+ return new Date(parseFloat(dateStr.slice(0, 4)), parseFloat(dateStr.slice(4, 6)) - 1, parseFloat(dateStr.slice(6, 8)));
28
+ };
29
+ exports.s3DateStringToDate = s3DateStringToDate;
30
+ // # Get the from and to dates in S3 file format for a download request
31
+ // # For custom opts, month number should be the index (ie: January is index 0)
32
+ const getDateRangeFromSelection = (downloadPeriod, customOpts) => {
33
+ let from, to;
34
+ const now = new Date();
35
+ switch (downloadPeriod) {
36
+ case 'week':
37
+ from = (0, exports.dateToS3DateString)(new Date(now.getTime() - 7 * constants_1.ONE_DAY_MS));
38
+ to = (0, exports.dateToS3DateString)(now);
39
+ break;
40
+ case 'month':
41
+ from = (0, exports.dateToS3DateString)(new Date(now.getFullYear(), now.getMonth(), 1));
42
+ to = (0, exports.dateToS3DateString)(now);
43
+ break;
44
+ case '3mo': {
45
+ const fromDate = new Date();
46
+ fromDate.setMonth(now.getMonth() - 3);
47
+ from = (0, exports.dateToS3DateString)(fromDate);
48
+ to = (0, exports.dateToS3DateString)(now);
49
+ break;
50
+ }
51
+ case 'ytd':
52
+ from = (0, exports.dateToS3DateString)(new Date(now.getFullYear(), 0, 1));
53
+ to = (0, exports.dateToS3DateString)(now);
54
+ break;
55
+ case 'year':
56
+ from = (0, exports.dateToS3DateString)(new Date(now.getTime() - 365 * constants_1.ONE_DAY_MS));
57
+ to = (0, exports.dateToS3DateString)(now);
58
+ break;
59
+ case 'custom':
60
+ if (!customOpts || (customOpts === null || customOpts === void 0 ? void 0 : customOpts.year) == undefined) {
61
+ console.error('Requested custom date range without providing customOpts');
62
+ break;
63
+ }
64
+ if (customOpts.day == undefined && customOpts.month == undefined) {
65
+ // request a full year
66
+ from = (0, exports.dateToS3DateString)(new Date(customOpts.year, 0, 1));
67
+ to = (0, exports.dateToS3DateString)(new Date(customOpts.year, 11, 31));
68
+ }
69
+ else if (customOpts.day == undefined &&
70
+ customOpts.month !== undefined) {
71
+ // request a month
72
+ from = (0, exports.dateToS3DateString)(new Date(customOpts.year, customOpts.month, 1));
73
+ // if December, to date should be 12/31
74
+ if (customOpts.month === 11) {
75
+ to = (0, exports.dateToS3DateString)(new Date(customOpts.year, customOpts.month, 31));
76
+ }
77
+ else {
78
+ to = (0, exports.dateToS3DateString)(new Date(customOpts.year, customOpts.month + 1, 0));
79
+ }
80
+ }
81
+ else {
82
+ // request a day
83
+ from = (0, exports.dateToS3DateString)(new Date(customOpts.year, customOpts.month, customOpts.day));
84
+ to = (0, exports.dateToS3DateString)(new Date(customOpts.year, customOpts.month, customOpts.day));
85
+ }
86
+ break;
87
+ }
88
+ return { from, to };
89
+ };
90
+ exports.getDateRangeFromSelection = getDateRangeFromSelection;
91
+ const getLeaderboardFilename = (orderBy, resolution) => `${orderBy}_${_1.ENUM_UTILS.toStr(resolution)}_leaderboard.json`;
92
+ exports.S3_LEADERBOARD_CLIENT = {
93
+ getFileName: (orderBy, resolution) => {
94
+ return getLeaderboardFilename(orderBy, resolution);
95
+ },
96
+ getLeaderboardValue: async (env, leaderboardBucketName, orderBy, resolution) => {
97
+ const leadboardLocation = env === 'mainnet-beta' ? 's3.eu-west-1' : 's3.us-east-1';
98
+ const s3Url = `https://${leaderboardBucketName}.${leadboardLocation}.amazonaws.com/${getLeaderboardFilename(orderBy, resolution)}`;
99
+ const result = await (await fetch(s3Url, { cache: 'no-cache' })).json();
100
+ const deserializedResult = serializableTypes_1.Serializer.Deserialize.UISerializableLeaderboardResult(result);
101
+ return deserializedResult;
102
+ },
103
+ };
104
+ const S3_BUCKET_UTILS = {
105
+ S3_LEADERBOARD_CLIENT: exports.S3_LEADERBOARD_CLIENT,
106
+ };
107
+ exports.default = S3_BUCKET_UTILS;
108
+ //# sourceMappingURL=s3Buckets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"s3Buckets.js","sourceRoot":"","sources":["../../src/utils/s3Buckets.ts"],"names":[],"mappings":";;;AACA,wBAA+B;AAC/B,4DAAkD;AAElD,4CAA0C;AA0C1C,wFAAwF;AACxF,2FAA2F;AACpF,MAAM,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AC,MAAM,KAAK,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAExE,MAAM,kBAAkB,GACvB,8BAAU,CAAC,WAAW,CAAC,+BAA+B,CAAC,MAAM,CAAC,CAAC;QAEhE,OAAO,kBAAkB,CAAC;IAC3B,CAAC;CACD,CAAC;AAEF,MAAM,eAAe,GAAG;IACvB,qBAAqB,EAArB,6BAAqB;CACrB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { DriftEnv } from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '.';\nimport { Serializer } from '../serializableTypes';\nimport { PnlSnapshotOrderOption, SnapshotEpochResolution } from '../types';\nimport { ONE_DAY_MS } from '../constants';\n\nexport type DownloadFile = {\n\tkey: string;\n\trequestParams: DownloadRequestParams;\n\tlastModifiedTs: number;\n\tdownloadUrl?: string;\n};\n\nexport type DownloadRequestParams = {\n\tfileType: DownloadRecordType;\n\trequestedDate: string;\n\tfromDate: string;\n\ttoDate: string;\n\tuser: string;\n\tprogramId: string;\n\tauthority: string;\n\tisEmulationMode: boolean;\n\tmarketSymbol?: string;\n};\n\nexport type DownloadRecordType =\n\t| 'trades'\n\t| 'market-trades'\n\t| 'funding-rates'\n\t| 'funding-payments'\n\t| 'deposits'\n\t| 'liquidations'\n\t| 'settle-pnl-records'\n\t| 'lp-records'\n\t| 'if-stake-records'\n\t| 'swap-records'\n\t| 'rewards';\n\nexport type DownloadPeriod =\n\t| 'week'\n\t| 'month'\n\t| '3mo'\n\t| 'ytd'\n\t| 'year'\n\t| 'custom';\n\n// # Redis key for download requests is the downloadRequestParams with colon delimeters.\n// # Stringifies the keys alphabetically so we don't have mismatches for identical requests\nexport const getFileRedisKeyFromParams = (\n\tdownloadRequestParams: DownloadRequestParams\n): string => {\n\treturn Object.keys(downloadRequestParams)\n\t\t.sort((a, b) => a.localeCompare(b))\n\t\t.map((sortedKey) => downloadRequestParams[sortedKey])\n\t\t.filter((val) => val !== undefined)\n\t\t.join(':');\n};\n\n// # Converts a date object into the string format used for S3 files\nexport const dateToS3DateString = (date: Date): string => {\n\tconst year = date.getFullYear();\n\tconst month = date.getMonth() + 1;\n\tconst day = date.getDate();\n\n\treturn `${year}${month < 10 ? '0' + month : month}${\n\t\tday < 10 ? '0' + day : day\n\t}`;\n};\n\n// # Converts a string date in S3 file format into a Date object\nexport const s3DateStringToDate = (dateStr: string): Date => {\n\treturn new Date(\n\t\tparseFloat(dateStr.slice(0, 4)),\n\t\tparseFloat(dateStr.slice(4, 6)) - 1,\n\t\tparseFloat(dateStr.slice(6, 8))\n\t);\n};\n\n// # Get the from and to dates in S3 file format for a download request\n// # For custom opts, month number should be the index (ie: January is index 0)\nexport const getDateRangeFromSelection = (\n\tdownloadPeriod: DownloadPeriod,\n\tcustomOpts?: { day?: number; month?: number; year: number }\n): { from: string; to: string } => {\n\tlet from, to;\n\tconst now = new Date();\n\n\tswitch (downloadPeriod) {\n\t\tcase 'week':\n\t\t\tfrom = dateToS3DateString(new Date(now.getTime() - 7 * ONE_DAY_MS));\n\t\t\tto = dateToS3DateString(now);\n\t\t\tbreak;\n\t\tcase 'month':\n\t\t\tfrom = dateToS3DateString(new Date(now.getFullYear(), now.getMonth(), 1));\n\t\t\tto = dateToS3DateString(now);\n\t\t\tbreak;\n\t\tcase '3mo': {\n\t\t\tconst fromDate = new Date();\n\t\t\tfromDate.setMonth(now.getMonth() - 3);\n\t\t\tfrom = dateToS3DateString(fromDate);\n\t\t\tto = dateToS3DateString(now);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'ytd':\n\t\t\tfrom = dateToS3DateString(new Date(now.getFullYear(), 0, 1));\n\t\t\tto = dateToS3DateString(now);\n\t\t\tbreak;\n\t\tcase 'year':\n\t\t\tfrom = dateToS3DateString(new Date(now.getTime() - 365 * ONE_DAY_MS));\n\t\t\tto = dateToS3DateString(now);\n\t\t\tbreak;\n\t\tcase 'custom':\n\t\t\tif (!customOpts || customOpts?.year == undefined) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Requested custom date range without providing customOpts'\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (customOpts.day == undefined && customOpts.month == undefined) {\n\t\t\t\t// request a full year\n\t\t\t\tfrom = dateToS3DateString(new Date(customOpts.year, 0, 1));\n\t\t\t\tto = dateToS3DateString(new Date(customOpts.year, 11, 31));\n\t\t\t} else if (\n\t\t\t\tcustomOpts.day == undefined &&\n\t\t\t\tcustomOpts.month !== undefined\n\t\t\t) {\n\t\t\t\t// request a month\n\t\t\t\tfrom = dateToS3DateString(\n\t\t\t\t\tnew Date(customOpts.year, customOpts.month, 1)\n\t\t\t\t);\n\n\t\t\t\t// if December, to date should be 12/31\n\t\t\t\tif (customOpts.month === 11) {\n\t\t\t\t\tto = dateToS3DateString(\n\t\t\t\t\t\tnew Date(customOpts.year, customOpts.month, 31)\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tto = dateToS3DateString(\n\t\t\t\t\t\tnew Date(customOpts.year, customOpts.month + 1, 0)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// request a day\n\t\t\t\tfrom = dateToS3DateString(\n\t\t\t\t\tnew Date(customOpts.year, customOpts.month, customOpts.day)\n\t\t\t\t);\n\t\t\t\tto = dateToS3DateString(\n\t\t\t\t\tnew Date(customOpts.year, customOpts.month, customOpts.day)\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\treturn { from, to };\n};\n\nconst getLeaderboardFilename = (\n\torderBy: PnlSnapshotOrderOption,\n\tresolution: SnapshotEpochResolution\n) => `${orderBy}_${ENUM_UTILS.toStr(resolution)}_leaderboard.json`;\n\nexport const S3_LEADERBOARD_CLIENT = {\n\tgetFileName: (\n\t\torderBy: PnlSnapshotOrderOption,\n\t\tresolution: SnapshotEpochResolution\n\t) => {\n\t\treturn getLeaderboardFilename(orderBy, resolution);\n\t},\n\tgetLeaderboardValue: async (\n\t\tenv: DriftEnv,\n\t\tleaderboardBucketName: string,\n\t\torderBy: PnlSnapshotOrderOption,\n\t\tresolution: SnapshotEpochResolution\n\t) => {\n\t\tconst leadboardLocation =\n\t\t\tenv === 'mainnet-beta' ? 's3.eu-west-1' : 's3.us-east-1';\n\n\t\tconst s3Url = `https://${leaderboardBucketName}.${leadboardLocation}.amazonaws.com/${getLeaderboardFilename(\n\t\t\torderBy,\n\t\t\tresolution\n\t\t)}`;\n\n\t\tconst result = await (await fetch(s3Url, { cache: 'no-cache' })).json();\n\n\t\tconst deserializedResult =\n\t\t\tSerializer.Deserialize.UISerializableLeaderboardResult(result);\n\n\t\treturn deserializedResult;\n\t},\n};\n\nconst S3_BUCKET_UTILS = {\n\tS3_LEADERBOARD_CLIENT,\n};\n\nexport default S3_BUCKET_UTILS;\n"]}