@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,90 @@
1
+ import { BigNum, PositionDirection, PostOnlyParams, QuoteResponse } from '@drift-labs/sdk';
2
+ import { AuctionParamsRequestOptions } from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';
3
+ /**
4
+ * Interface for deposit operation parameters.
5
+ */
6
+ export interface DepositParams {
7
+ subAccountId: number;
8
+ amount: BigNum;
9
+ spotMarketIndex: number;
10
+ isMaxBorrowRepayment?: boolean;
11
+ }
12
+ /**
13
+ * Interface for withdraw operation parameters.
14
+ */
15
+ export interface WithdrawParams {
16
+ subAccountId: number;
17
+ amount: BigNum;
18
+ spotMarketIndex: number;
19
+ isBorrow?: boolean;
20
+ isMax?: boolean;
21
+ }
22
+ /**
23
+ * Interface for create user and deposit operation parameters.
24
+ */
25
+ export interface CreateUserAndDepositParams {
26
+ depositAmount: BigNum;
27
+ depositSpotMarketIndex: number;
28
+ newAccountName?: string;
29
+ maxLeverage?: number;
30
+ poolId?: number;
31
+ subAccountId?: number;
32
+ referrerName?: string;
33
+ }
34
+ /**
35
+ * Interface for perp market order parameters.
36
+ */
37
+ export type PerpOrderParams = {
38
+ subAccountId: number;
39
+ marketIndex: number;
40
+ direction: PositionDirection;
41
+ assetType: 'base' | 'quote';
42
+ size: BigNum;
43
+ reduceOnly?: boolean;
44
+ postOnly?: PostOnlyParams;
45
+ orderConfig: {
46
+ orderType: 'market';
47
+ disableSwift?: boolean;
48
+ auctionParamsOptions?: AuctionParamsRequestOptions;
49
+ postOnly?: never;
50
+ bracketOrders?: {
51
+ takeProfitPrice?: BigNum;
52
+ stopLossPrice?: BigNum;
53
+ };
54
+ } | {
55
+ orderType: 'limit';
56
+ limitPrice: BigNum;
57
+ disableSwift?: boolean;
58
+ bracketOrders?: {
59
+ takeProfitPrice?: BigNum;
60
+ stopLossPrice?: BigNum;
61
+ };
62
+ } | {
63
+ orderType: 'takeProfit' | 'stopLoss';
64
+ triggerPrice: BigNum;
65
+ limitPrice?: BigNum;
66
+ } | {
67
+ orderType: 'oracleLimit';
68
+ oraclePriceOffset: BigNum;
69
+ };
70
+ };
71
+ /**
72
+ * Interface for swap operation parameters.
73
+ */
74
+ export interface SwapParams {
75
+ fromMarketIndex: number;
76
+ toMarketIndex: number;
77
+ amount: BigNum;
78
+ subAccountId: number;
79
+ jupiterQuote?: QuoteResponse;
80
+ }
81
+ /**
82
+ * Interface for settle account P&Ls.
83
+ */
84
+ export interface SettleAccountPnlParams {
85
+ subAccountId: number;
86
+ }
87
+ export interface CancelOrdersParams {
88
+ subAccountId: number;
89
+ orderIds: number[];
90
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBigNum,\n\tPositionDirection,\n\tPostOnlyParams,\n\tQuoteResponse,\n} from '@drift-labs/sdk';\nimport { AuctionParamsRequestOptions } from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\n\n/**\n * Interface for deposit operation parameters.\n */\nexport interface DepositParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisMaxBorrowRepayment?: boolean;\n}\n\n/**\n * Interface for withdraw operation parameters.\n */\nexport interface WithdrawParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\n/**\n * Interface for create user and deposit operation parameters.\n */\nexport interface CreateUserAndDepositParams {\n\tdepositAmount: BigNum;\n\tdepositSpotMarketIndex: number;\n\tnewAccountName?: string;\n\tmaxLeverage?: number;\n\tpoolId?: number;\n\tsubAccountId?: number;\n\treferrerName?: string;\n}\n\n/**\n * Interface for perp market order parameters.\n */\nexport type PerpOrderParams = {\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tassetType: 'base' | 'quote';\n\tsize: BigNum;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\torderConfig:\n\t\t| {\n\t\t\t\torderType: 'market';\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tauctionParamsOptions?: AuctionParamsRequestOptions;\n\t\t\t\tpostOnly?: never;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\t// TODO: isMaxLeverage?\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'limit';\n\t\t\t\tlimitPrice: BigNum;\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\t// TODO: isMaxLeverage?\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'takeProfit' | 'stopLoss';\n\t\t\t\ttriggerPrice: BigNum;\n\t\t\t\tlimitPrice?: BigNum;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'oracleLimit';\n\t\t\t\toraclePriceOffset: BigNum;\n\t\t };\n};\n\n/**\n * Interface for swap operation parameters.\n */\nexport interface SwapParams {\n\tfromMarketIndex: number;\n\ttoMarketIndex: number;\n\tamount: BigNum;\n\tsubAccountId: number;\n\tjupiterQuote?: QuoteResponse;\n}\n\n/**\n * Interface for settle account P&Ls.\n */\nexport interface SettleAccountPnlParams {\n\tsubAccountId: number;\n}\n\nexport interface CancelOrdersParams {\n\tsubAccountId: number;\n\torderIds: number[];\n}\n"]}
@@ -0,0 +1,139 @@
1
+ import { CustomizedCadenceBulkAccountLoader, DriftClient, IWallet, User } from '@drift-labs/sdk';
2
+ import { MarketId } from '../../../../types';
3
+ import { PollingDlob } from '../../data/PollingDlob';
4
+ import { UserAccountCache } from '../../stores/UserAccountCache';
5
+ import { DriftL2OrderbookManager } from './DriftL2OrderbookManager';
6
+ /**
7
+ * Comprehensive subscription and market operations manager for the Drift protocol.
8
+ *
9
+ * This class handles all aspects of subscription management including:
10
+ * - User account subscriptions and event listeners
11
+ * - Market account and oracle polling optimization
12
+ * - Markets are categorized based on user involvement, and polling cadences are updated accordingly
13
+ * - DLOB server polling configuration (for lesser used markets)
14
+ * - DLOB server websocket subscription configuration (for selected trade market). Used to get orderbook data too.
15
+ * - Authority (wallet) management with full resubscription
16
+ *
17
+ * By combining subscription and market operations, this provides a unified
18
+ * interface for all subscription-related optimizations.
19
+ */
20
+ export declare class SubscriptionManager {
21
+ private driftClient;
22
+ private accountLoader;
23
+ private pollingDlob;
24
+ private orderbookManager;
25
+ private userAccountCache;
26
+ private tradableMarkets;
27
+ private selectedTradeMarket;
28
+ /**
29
+ * Creates a new SubscriptionManager instance.
30
+ *
31
+ * @param driftClient - The DriftClient instance for managing subscriptions
32
+ * @param accountLoader - Handles bulk account loading and polling frequency management
33
+ * @param pollingDlob - Manages DLOB server polling for market data
34
+ * @param userAccountCache - Cache for user account data updates
35
+ * @param tradableMarkets - Array of markets that are available for trading
36
+ * @param selectedTradeMarket - The market that is currently being traded
37
+ */
38
+ constructor(driftClient: DriftClient, accountLoader: CustomizedCadenceBulkAccountLoader, pollingDlob: PollingDlob, orderbookManager: DriftL2OrderbookManager, userAccountCache: UserAccountCache, tradableMarkets: MarketId[], selectedTradeMarket: MarketId | null);
39
+ /**
40
+ * Updates the tradable markets list.
41
+ *
42
+ * @param tradableMarkets - The new tradable markets list
43
+ */
44
+ updateTradableMarkets(tradableMarkets: MarketId[]): void;
45
+ /**
46
+ * Subscribes to updates for all user accounts under the current authority.
47
+ *
48
+ * This method sets up event listeners for user account updates and ensures
49
+ * that market subscriptions are properly configured based on user positions.
50
+ * When a user's account data changes, it automatically triggers subscription
51
+ * updates to maintain optimal polling frequencies.
52
+ */
53
+ subscribeToAllUsersUpdates(): void;
54
+ /**
55
+ * Categorizes markets based on user involvement (active positions).
56
+ *
57
+ * Markets are classified as "user-involved" if any of the provided users
58
+ * have active positions (perp or spot) in those markets. This categorization
59
+ * is used to optimize polling frequencies - user-involved markets are polled
60
+ * more frequently to ensure accurate close to real-time data for user positions.
61
+ */
62
+ categorizeMarketsByUserInvolvement(users: User[]): {
63
+ userInvolvedMarkets: MarketId[];
64
+ userNotInvolvedMarkets: MarketId[];
65
+ };
66
+ /**
67
+ * Updates the polling cadence for a market account and its associated oracle account.
68
+ *
69
+ * This method optimizes data fetching by adjusting how frequently market and oracle
70
+ * accounts are polled from the RPC. Higher cadences (lower numbers) mean more frequent polling.
71
+ */
72
+ updateMarketAccountCadence(market: MarketId, newCadence: number): void;
73
+ /**
74
+ * Updates account loader polling cadences for multiple markets based on their categorization.
75
+ *
76
+ * This method applies different polling frequencies based on market importance:
77
+ * - Selected trade market: Highest frequency (most important for active trading)
78
+ * - User-involved markets: Medium frequency (user has positions)
79
+ * - User-not-involved markets: Lowest frequency (background monitoring)
80
+ */
81
+ private updateAccountLoaderCadenceForMarkets;
82
+ /**
83
+ * Updates DLOB (Decentralized Limit Order Book) polling intervals for market data.
84
+ *
85
+ * This method configures how frequently the DLOB server is polled for market data
86
+ * including mark prices, oracle prices, and orderbook data. Different markets are
87
+ * assigned to different polling intervals based on their importance.
88
+ */
89
+ private updatePollingDlobIntervals;
90
+ /**
91
+ * Handles comprehensive subscription updates when user account data changes.
92
+ *
93
+ * This is the main orchestration method that ensures optimal polling frequencies
94
+ * are maintained when user positions change. It automatically:
95
+ *
96
+ * 1. Categorizes markets based on current user involvement
97
+ * 2. Updates account loader cadences for market and oracle accounts
98
+ * 3. Updates DLOB polling intervals for price data
99
+ *
100
+ * The method ensures that markets with user positions get higher priority polling
101
+ * to maintain accurate real-time data for position management.
102
+ */
103
+ handleSubscriptionUpdatesOnUserUpdates(users: User[]): void;
104
+ /**
105
+ * Subscribes to markets that users are involved in but aren't in the default tradable markets list.
106
+ *
107
+ * This method ensures that if users have positions in markets that weren't initially
108
+ * included in the tradable markets list, those markets are still properly subscribed to.
109
+ * This is important for maintaining accurate account data even for edge cases.
110
+ */
111
+ subscribeToNonWhitelistedButUserInvolvedMarkets(users: User[]): Promise<void>;
112
+ private checkIsUserInvolvedInMarket;
113
+ /**
114
+ * Updates the selected trade market and optimizes all subscription polling accordingly.
115
+ *
116
+ * This method handles:
117
+ * 1. Removing the previous market from high-frequency polling
118
+ * 2. Adding the new market to high-frequency polling
119
+ * 3. Updating market account cadences for optimal performance
120
+ * 4. Categorizing the previous market based on user involvement
121
+ * 5. Assigning appropriate polling intervals to the previous market
122
+ *
123
+ * @param newSelectedTradeMarket - The new market to prioritize for trading
124
+ */
125
+ updateSelectedTradeMarket(newSelectedTradeMarket: MarketId | null): void;
126
+ /**
127
+ * Updates the authority (wallet) for the drift client and reestablishes subscriptions.
128
+ *
129
+ * This method handles the complete process of switching to a new wallet:
130
+ * 1. Checks if the wallet is actually different
131
+ * 2. Unsubscribes from current user accounts
132
+ * 3. Resets the user account cache
133
+ * 4. Updates the DriftClient with the new wallet
134
+ * 5. Resubscribes to markets based on new user positions
135
+ * 6. Switches to the specified subaccount if provided
136
+ * 7. Reestablishes user account subscriptions
137
+ */
138
+ updateAuthority(wallet: IWallet, activeSubAccountId?: number): Promise<void>;
139
+ }
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SubscriptionManager = void 0;
4
+ const types_1 = require("../../../../types");
5
+ const constants_1 = require("../../constants");
6
+ const orderbook_1 = require("../../constants/orderbook");
7
+ /**
8
+ * Comprehensive subscription and market operations manager for the Drift protocol.
9
+ *
10
+ * This class handles all aspects of subscription management including:
11
+ * - User account subscriptions and event listeners
12
+ * - Market account and oracle polling optimization
13
+ * - Markets are categorized based on user involvement, and polling cadences are updated accordingly
14
+ * - DLOB server polling configuration (for lesser used markets)
15
+ * - DLOB server websocket subscription configuration (for selected trade market). Used to get orderbook data too.
16
+ * - Authority (wallet) management with full resubscription
17
+ *
18
+ * By combining subscription and market operations, this provides a unified
19
+ * interface for all subscription-related optimizations.
20
+ */
21
+ class SubscriptionManager {
22
+ /**
23
+ * Creates a new SubscriptionManager instance.
24
+ *
25
+ * @param driftClient - The DriftClient instance for managing subscriptions
26
+ * @param accountLoader - Handles bulk account loading and polling frequency management
27
+ * @param pollingDlob - Manages DLOB server polling for market data
28
+ * @param userAccountCache - Cache for user account data updates
29
+ * @param tradableMarkets - Array of markets that are available for trading
30
+ * @param selectedTradeMarket - The market that is currently being traded
31
+ */
32
+ constructor(driftClient, accountLoader, pollingDlob, orderbookManager, userAccountCache, tradableMarkets, selectedTradeMarket) {
33
+ this.driftClient = driftClient;
34
+ this.accountLoader = accountLoader;
35
+ this.pollingDlob = pollingDlob;
36
+ this.orderbookManager = orderbookManager;
37
+ this.userAccountCache = userAccountCache;
38
+ this.tradableMarkets = tradableMarkets;
39
+ this.selectedTradeMarket = selectedTradeMarket;
40
+ }
41
+ /**
42
+ * Updates the tradable markets list.
43
+ *
44
+ * @param tradableMarkets - The new tradable markets list
45
+ */
46
+ updateTradableMarkets(tradableMarkets) {
47
+ this.tradableMarkets = tradableMarkets;
48
+ }
49
+ /**
50
+ * Subscribes to updates for all user accounts under the current authority.
51
+ *
52
+ * This method sets up event listeners for user account updates and ensures
53
+ * that market subscriptions are properly configured based on user positions.
54
+ * When a user's account data changes, it automatically triggers subscription
55
+ * updates to maintain optimal polling frequencies.
56
+ */
57
+ subscribeToAllUsersUpdates() {
58
+ const users = this.driftClient.getUsers();
59
+ this.handleSubscriptionUpdatesOnUserUpdates(users);
60
+ users.forEach((user) => {
61
+ this.userAccountCache.updateUserAccount(user); // initial hydration of user account data in the store
62
+ user.eventEmitter.on('update', () => {
63
+ this.handleSubscriptionUpdatesOnUserUpdates(users);
64
+ this.userAccountCache.updateUserAccount(user);
65
+ });
66
+ });
67
+ }
68
+ /**
69
+ * Categorizes markets based on user involvement (active positions).
70
+ *
71
+ * Markets are classified as "user-involved" if any of the provided users
72
+ * have active positions (perp or spot) in those markets. This categorization
73
+ * is used to optimize polling frequencies - user-involved markets are polled
74
+ * more frequently to ensure accurate close to real-time data for user positions.
75
+ */
76
+ categorizeMarketsByUserInvolvement(users) {
77
+ const perpMarketIndexesSet = new Set();
78
+ const spotMarketIndexesSet = new Set();
79
+ users.forEach((user) => {
80
+ const { activePerpPositions, activeSpotPositions } = user.getActivePositions();
81
+ activePerpPositions.forEach((marketIndex) => perpMarketIndexesSet.add(marketIndex));
82
+ activeSpotPositions.forEach((marketIndex) => spotMarketIndexesSet.add(marketIndex));
83
+ });
84
+ const userInvolvedMarkets = Array.from(perpMarketIndexesSet)
85
+ .map((index) => types_1.MarketId.createPerpMarket(index))
86
+ .concat(Array.from(spotMarketIndexesSet).map((index) => types_1.MarketId.createSpotMarket(index)));
87
+ const userInvolvedMarketKeys = userInvolvedMarkets.map((market) => market.key);
88
+ const userNotInvolvedMarkets = this.tradableMarkets.filter((market) => !userInvolvedMarketKeys.includes(market.key));
89
+ return { userInvolvedMarkets, userNotInvolvedMarkets };
90
+ }
91
+ /**
92
+ * Updates the polling cadence for a market account and its associated oracle account.
93
+ *
94
+ * This method optimizes data fetching by adjusting how frequently market and oracle
95
+ * accounts are polled from the RPC. Higher cadences (lower numbers) mean more frequent polling.
96
+ */
97
+ updateMarketAccountCadence(market, newCadence) {
98
+ const marketAccount = market.isPerp
99
+ ? this.driftClient.getPerpMarketAccount(market.marketIndex)
100
+ : this.driftClient.getSpotMarketAccount(market.marketIndex);
101
+ if (!marketAccount) {
102
+ throw new Error(`Market account not found for market ${market.key}`);
103
+ }
104
+ const currentMarketCadence = this.accountLoader.getAccountCadence(marketAccount.pubkey);
105
+ if (currentMarketCadence !== newCadence) {
106
+ this.accountLoader.setCustomPollingFrequency(marketAccount.pubkey, newCadence);
107
+ }
108
+ const oracleAccountPubKey = market.isPerp
109
+ ? marketAccount.amm.oracle
110
+ : marketAccount.oracle;
111
+ const currentOracleCadence = this.accountLoader.getAccountCadence(oracleAccountPubKey);
112
+ if (currentOracleCadence !== newCadence) {
113
+ this.accountLoader.setCustomPollingFrequency(oracleAccountPubKey, newCadence);
114
+ }
115
+ }
116
+ /**
117
+ * Updates account loader polling cadences for multiple markets based on their categorization.
118
+ *
119
+ * This method applies different polling frequencies based on market importance:
120
+ * - Selected trade market: Highest frequency (most important for active trading)
121
+ * - User-involved markets: Medium frequency (user has positions)
122
+ * - User-not-involved markets: Lowest frequency (background monitoring)
123
+ */
124
+ updateAccountLoaderCadenceForMarkets(userInvolvedMarkets, userNotInvolvedMarkets, selectedTradeMarket) {
125
+ if (selectedTradeMarket) {
126
+ this.updateMarketAccountCadence(selectedTradeMarket, constants_1.SELECTED_MARKET_ACCOUNT_POLLING_CADENCE);
127
+ }
128
+ userInvolvedMarkets.forEach((market) => {
129
+ this.updateMarketAccountCadence(market, constants_1.USER_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE);
130
+ });
131
+ userNotInvolvedMarkets.forEach((market) => {
132
+ this.updateMarketAccountCadence(market, constants_1.USER_NOT_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE);
133
+ });
134
+ }
135
+ /**
136
+ * Updates DLOB (Decentralized Limit Order Book) polling intervals for market data.
137
+ *
138
+ * This method configures how frequently the DLOB server is polled for market data
139
+ * including mark prices, oracle prices, and orderbook data. Different markets are
140
+ * assigned to different polling intervals based on their importance.
141
+ */
142
+ updatePollingDlobIntervals(userInvolvedMarkets, userNotInvolvedMarkets) {
143
+ this.pollingDlob.addMarketsToInterval(constants_1.PollingCategory.USER_INVOLVED, userInvolvedMarkets);
144
+ this.pollingDlob.addMarketsToInterval(constants_1.PollingCategory.USER_NOT_INVOLVED, userNotInvolvedMarkets);
145
+ }
146
+ /**
147
+ * Handles comprehensive subscription updates when user account data changes.
148
+ *
149
+ * This is the main orchestration method that ensures optimal polling frequencies
150
+ * are maintained when user positions change. It automatically:
151
+ *
152
+ * 1. Categorizes markets based on current user involvement
153
+ * 2. Updates account loader cadences for market and oracle accounts
154
+ * 3. Updates DLOB polling intervals for price data
155
+ *
156
+ * The method ensures that markets with user positions get higher priority polling
157
+ * to maintain accurate real-time data for position management.
158
+ */
159
+ handleSubscriptionUpdatesOnUserUpdates(users) {
160
+ const { userInvolvedMarkets, userNotInvolvedMarkets } = this.categorizeMarketsByUserInvolvement(users);
161
+ // Filter out selected trade market from the other categories
162
+ const filteredUserInvolvedMarkets = userInvolvedMarkets.filter((market) => { var _a; return market.key !== ((_a = this.selectedTradeMarket) === null || _a === void 0 ? void 0 : _a.key); });
163
+ const filteredUserNotInvolvedMarkets = userNotInvolvedMarkets.filter((market) => { var _a; return market.key !== ((_a = this.selectedTradeMarket) === null || _a === void 0 ? void 0 : _a.key); });
164
+ // Update market account cadences
165
+ this.updateAccountLoaderCadenceForMarkets(filteredUserInvolvedMarkets, filteredUserNotInvolvedMarkets, this.selectedTradeMarket);
166
+ // Handle polling dlob polling intervals
167
+ this.updatePollingDlobIntervals(filteredUserInvolvedMarkets.map((market) => market.key), filteredUserNotInvolvedMarkets.map((market) => market.key)
168
+ // this.selectedTradeMarket
169
+ );
170
+ }
171
+ /**
172
+ * Subscribes to markets that users are involved in but aren't in the default tradable markets list.
173
+ *
174
+ * This method ensures that if users have positions in markets that weren't initially
175
+ * included in the tradable markets list, those markets are still properly subscribed to.
176
+ * This is important for maintaining accurate account data even for edge cases.
177
+ */
178
+ async subscribeToNonWhitelistedButUserInvolvedMarkets(users) {
179
+ const perpMarketIndexesSet = new Set(this.driftClient
180
+ .accountSubscriber.perpMarketIndexes);
181
+ const spotMarketIndexesSet = new Set(this.driftClient
182
+ .accountSubscriber.spotMarketIndexes);
183
+ const { userInvolvedMarkets } = this.categorizeMarketsByUserInvolvement(users);
184
+ userInvolvedMarkets.forEach((market) => {
185
+ if (market.isPerp) {
186
+ perpMarketIndexesSet.add(market.marketIndex);
187
+ }
188
+ else {
189
+ spotMarketIndexesSet.add(market.marketIndex);
190
+ }
191
+ });
192
+ this.driftClient.accountSubscriber.perpMarketIndexes = Array.from(perpMarketIndexesSet);
193
+ this.driftClient.accountSubscriber.spotMarketIndexes = Array.from(spotMarketIndexesSet);
194
+ // TODO: see if this can be optimized - instead of unsubscribing and resubscribing, find a way to add the new markets to the existing subscription
195
+ await this.driftClient.accountSubscriber.unsubscribe();
196
+ await this.driftClient.accountSubscriber.subscribe();
197
+ }
198
+ checkIsUserInvolvedInMarket(marketId) {
199
+ let isUserInvolvedInPreviousSelectedTradeMarket = false;
200
+ const allUsers = this.userAccountCache.allUsers;
201
+ for (const user of allUsers) {
202
+ const { activePerpPositions, activeSpotPositions } = user.userClient.getActivePositions();
203
+ if (marketId.isPerp &&
204
+ activePerpPositions.includes(marketId.marketIndex)) {
205
+ isUserInvolvedInPreviousSelectedTradeMarket = true;
206
+ break;
207
+ }
208
+ if (marketId.isSpot &&
209
+ activeSpotPositions.includes(marketId.marketIndex)) {
210
+ isUserInvolvedInPreviousSelectedTradeMarket = true;
211
+ break;
212
+ }
213
+ }
214
+ return isUserInvolvedInPreviousSelectedTradeMarket;
215
+ }
216
+ /**
217
+ * Updates the selected trade market and optimizes all subscription polling accordingly.
218
+ *
219
+ * This method handles:
220
+ * 1. Removing the previous market from high-frequency polling
221
+ * 2. Adding the new market to high-frequency polling
222
+ * 3. Updating market account cadences for optimal performance
223
+ * 4. Categorizing the previous market based on user involvement
224
+ * 5. Assigning appropriate polling intervals to the previous market
225
+ *
226
+ * @param newSelectedTradeMarket - The new market to prioritize for trading
227
+ */
228
+ updateSelectedTradeMarket(newSelectedTradeMarket) {
229
+ const previousSelectedTradeMarket = this.selectedTradeMarket;
230
+ this.orderbookManager.unsubscribe();
231
+ if (previousSelectedTradeMarket) {
232
+ const isUserInvolvedInPreviousSelectedTradeMarket = this.checkIsUserInvolvedInMarket(previousSelectedTradeMarket);
233
+ const pollingCategoryOfPreviousSelectedMarket = isUserInvolvedInPreviousSelectedTradeMarket
234
+ ? constants_1.PollingCategory.USER_INVOLVED
235
+ : constants_1.PollingCategory.USER_NOT_INVOLVED;
236
+ this.pollingDlob.addMarketToInterval(pollingCategoryOfPreviousSelectedMarket, previousSelectedTradeMarket.key);
237
+ const pollingCadenceOfPreviousSelectedMarket = isUserInvolvedInPreviousSelectedTradeMarket
238
+ ? constants_1.USER_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE
239
+ : constants_1.USER_NOT_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE;
240
+ this.updateMarketAccountCadence(previousSelectedTradeMarket, pollingCadenceOfPreviousSelectedMarket);
241
+ }
242
+ // Update the selected trade market
243
+ this.selectedTradeMarket = newSelectedTradeMarket;
244
+ if (newSelectedTradeMarket) {
245
+ const isUserInvolvedInNewSelectedTradeMarket = this.checkIsUserInvolvedInMarket(newSelectedTradeMarket);
246
+ const pollingCategoryOfNewsSelectedMarket = isUserInvolvedInNewSelectedTradeMarket
247
+ ? constants_1.PollingCategory.USER_INVOLVED
248
+ : constants_1.PollingCategory.USER_NOT_INVOLVED;
249
+ this.pollingDlob.removeMarketFromInterval(pollingCategoryOfNewsSelectedMarket, newSelectedTradeMarket.key);
250
+ this.updateMarketAccountCadence(newSelectedTradeMarket, constants_1.SELECTED_MARKET_ACCOUNT_POLLING_CADENCE);
251
+ this.orderbookManager.updateSubscription({
252
+ ...orderbook_1.DEFAULT_ORDERBOOK_SUBSCRIPTION_CONFIG,
253
+ marketId: newSelectedTradeMarket,
254
+ });
255
+ }
256
+ }
257
+ /**
258
+ * Updates the authority (wallet) for the drift client and reestablishes subscriptions.
259
+ *
260
+ * This method handles the complete process of switching to a new wallet:
261
+ * 1. Checks if the wallet is actually different
262
+ * 2. Unsubscribes from current user accounts
263
+ * 3. Resets the user account cache
264
+ * 4. Updates the DriftClient with the new wallet
265
+ * 5. Resubscribes to markets based on new user positions
266
+ * 6. Switches to the specified subaccount if provided
267
+ * 7. Reestablishes user account subscriptions
268
+ */
269
+ async updateAuthority(wallet, activeSubAccountId) {
270
+ if (this.driftClient.wallet.publicKey.equals(wallet.publicKey)) {
271
+ return;
272
+ }
273
+ await Promise.all(this.driftClient.unsubscribeUsers());
274
+ this.userAccountCache.reset();
275
+ const updateWalletResult = await this.driftClient.updateWallet(wallet, undefined, activeSubAccountId, true, undefined);
276
+ await this.subscribeToNonWhitelistedButUserInvolvedMarkets(this.driftClient.getUsers());
277
+ if (!updateWalletResult) {
278
+ throw new Error('Failed to update wallet');
279
+ }
280
+ if (activeSubAccountId) {
281
+ await this.driftClient.switchActiveUser(activeSubAccountId);
282
+ }
283
+ this.subscribeToAllUsersUpdates();
284
+ }
285
+ }
286
+ exports.SubscriptionManager = SubscriptionManager;
287
+ //# sourceMappingURL=SubscriptionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubscriptionManager.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/AuthorityDrift/SubscriptionManager.ts"],"names":[],"mappings":";;;AASA,6CAAwD;AAExD,+CAKyB;AAGzB,yDAAkF;AAElF;;;;;;;;;;;;;GAaG;AACH,MAAa,mBAAmB;IAC/B;;;;;;;;;OASG;IACH,YACS,WAAwB,EACxB,aAAiD,EACjD,WAAwB,EACxB,gBAAyC,EACzC,gBAAkC,EAClC,eAA2B,EAC3B,mBAAoC;QANpC,gBAAW,GAAX,WAAW,CAAa;QACxB,kBAAa,GAAb,aAAa,CAAoC;QACjD,gBAAW,GAAX,WAAW,CAAa;QACxB,qBAAgB,GAAhB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AC;gBACxC,GAAG,iDAAqC;gBACxC,QAAQ,EAAE,sBAAsB;aAChC,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,eAAe,CACpB,MAAe,EACf,kBAA2B;QAE3B,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC;YAChE,OAAO;QACR,CAAC;QAED,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;QACvD,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAE9B,MAAM,kBAAkB,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,YAAY,CAC7D,MAAM,EACN,SAAS,EACT,kBAAkB,EAClB,IAAI,EACJ,SAAS,CACT,CAAC;QAEF,MAAM,IAAI,CAAC,+CAA+C,CACzD,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAC3B,CAAC;QAEF,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;QAC5C,CAAC;QAED,IAAI,kBAAkB,EAAE,CAAC;YACxB,MAAM,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;QAC7D,CAAC;QAED,IAAI,CAAC,0BAA0B,EAAE,CAAC;IACnC,CAAC;CACD;AAtaD,kDAsaC","sourcesContent":["import {\n\tCustomizedCadenceBulkAccountLoader,\n\tDriftClient,\n\tIWallet,\n\tPerpMarketAccount,\n\tPollingDriftClientAccountSubscriber,\n\tSpotMarketAccount,\n\tUser,\n} from '@drift-labs/sdk';\nimport { MarketId, MarketKey } from '../../../../types';\nimport { PollingDlob } from '../../data/PollingDlob';\nimport {\n\tPollingCategory,\n\tSELECTED_MARKET_ACCOUNT_POLLING_CADENCE,\n\tUSER_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE,\n\tUSER_NOT_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE,\n} from '../../constants';\nimport { UserAccountCache } from '../../stores/UserAccountCache';\nimport { DriftL2OrderbookManager } from './DriftL2OrderbookManager';\nimport { DEFAULT_ORDERBOOK_SUBSCRIPTION_CONFIG } from '../../constants/orderbook';\n\n/**\n * Comprehensive subscription and market operations manager for the Drift protocol.\n *\n * This class handles all aspects of subscription management including:\n * - User account subscriptions and event listeners\n * - Market account and oracle polling optimization\n * \t- Markets are categorized based on user involvement, and polling cadences are updated accordingly\n * - DLOB server polling configuration (for lesser used markets)\n * - DLOB server websocket subscription configuration (for selected trade market). Used to get orderbook data too.\n * - Authority (wallet) management with full resubscription\n *\n * By combining subscription and market operations, this provides a unified\n * interface for all subscription-related optimizations.\n */\nexport class SubscriptionManager {\n\t/**\n\t * Creates a new SubscriptionManager instance.\n\t *\n\t * @param driftClient - The DriftClient instance for managing subscriptions\n\t * @param accountLoader - Handles bulk account loading and polling frequency management\n\t * @param pollingDlob - Manages DLOB server polling for market data\n\t * @param userAccountCache - Cache for user account data updates\n\t * @param tradableMarkets - Array of markets that are available for trading\n\t * @param selectedTradeMarket - The market that is currently being traded\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate accountLoader: CustomizedCadenceBulkAccountLoader,\n\t\tprivate pollingDlob: PollingDlob,\n\t\tprivate orderbookManager: DriftL2OrderbookManager,\n\t\tprivate userAccountCache: UserAccountCache,\n\t\tprivate tradableMarkets: MarketId[],\n\t\tprivate selectedTradeMarket: MarketId | null\n\t) {}\n\n\t/**\n\t * Updates the tradable markets list.\n\t *\n\t * @param tradableMarkets - The new tradable markets list\n\t */\n\tupdateTradableMarkets(tradableMarkets: MarketId[]): void {\n\t\tthis.tradableMarkets = tradableMarkets;\n\t}\n\n\t/**\n\t * Subscribes to updates for all user accounts under the current authority.\n\t *\n\t * This method sets up event listeners for user account updates and ensures\n\t * that market subscriptions are properly configured based on user positions.\n\t * When a user's account data changes, it automatically triggers subscription\n\t * updates to maintain optimal polling frequencies.\n\t */\n\tsubscribeToAllUsersUpdates(): void {\n\t\tconst users = this.driftClient.getUsers();\n\n\t\tthis.handleSubscriptionUpdatesOnUserUpdates(users);\n\n\t\tusers.forEach((user) => {\n\t\t\tthis.userAccountCache.updateUserAccount(user); // initial hydration of user account data in the store\n\n\t\t\tuser.eventEmitter.on('update', () => {\n\t\t\t\tthis.handleSubscriptionUpdatesOnUserUpdates(users);\n\t\t\t\tthis.userAccountCache.updateUserAccount(user);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Categorizes markets based on user involvement (active positions).\n\t *\n\t * Markets are classified as \"user-involved\" if any of the provided users\n\t * have active positions (perp or spot) in those markets. This categorization\n\t * is used to optimize polling frequencies - user-involved markets are polled\n\t * more frequently to ensure accurate close to real-time data for user positions.\n\t */\n\tcategorizeMarketsByUserInvolvement(users: User[]): {\n\t\tuserInvolvedMarkets: MarketId[];\n\t\tuserNotInvolvedMarkets: MarketId[];\n\t} {\n\t\tconst perpMarketIndexesSet = new Set<number>();\n\t\tconst spotMarketIndexesSet = new Set<number>();\n\t\tusers.forEach((user) => {\n\t\t\tconst { activePerpPositions, activeSpotPositions } =\n\t\t\t\tuser.getActivePositions();\n\t\t\tactivePerpPositions.forEach((marketIndex) =>\n\t\t\t\tperpMarketIndexesSet.add(marketIndex)\n\t\t\t);\n\t\t\tactiveSpotPositions.forEach((marketIndex) =>\n\t\t\t\tspotMarketIndexesSet.add(marketIndex)\n\t\t\t);\n\t\t});\n\n\t\tconst userInvolvedMarkets = Array.from(perpMarketIndexesSet)\n\t\t\t.map((index) => MarketId.createPerpMarket(index))\n\t\t\t.concat(\n\t\t\t\tArray.from(spotMarketIndexesSet).map((index) =>\n\t\t\t\t\tMarketId.createSpotMarket(index)\n\t\t\t\t)\n\t\t\t);\n\n\t\tconst userInvolvedMarketKeys = userInvolvedMarkets.map(\n\t\t\t(market) => market.key\n\t\t);\n\t\tconst userNotInvolvedMarkets = this.tradableMarkets.filter(\n\t\t\t(market) => !userInvolvedMarketKeys.includes(market.key)\n\t\t);\n\n\t\treturn { userInvolvedMarkets, userNotInvolvedMarkets };\n\t}\n\n\t/**\n\t * Updates the polling cadence for a market account and its associated oracle account.\n\t *\n\t * This method optimizes data fetching by adjusting how frequently market and oracle\n\t * accounts are polled from the RPC. Higher cadences (lower numbers) mean more frequent polling.\n\t */\n\tupdateMarketAccountCadence(market: MarketId, newCadence: number): void {\n\t\tconst marketAccount = market.isPerp\n\t\t\t? this.driftClient.getPerpMarketAccount(market.marketIndex)\n\t\t\t: this.driftClient.getSpotMarketAccount(market.marketIndex);\n\n\t\tif (!marketAccount) {\n\t\t\tthrow new Error(`Market account not found for market ${market.key}`);\n\t\t}\n\n\t\tconst currentMarketCadence = this.accountLoader.getAccountCadence(\n\t\t\tmarketAccount.pubkey\n\t\t);\n\n\t\tif (currentMarketCadence !== newCadence) {\n\t\t\tthis.accountLoader.setCustomPollingFrequency(\n\t\t\t\tmarketAccount.pubkey,\n\t\t\t\tnewCadence\n\t\t\t);\n\t\t}\n\n\t\tconst oracleAccountPubKey = market.isPerp\n\t\t\t? (marketAccount as PerpMarketAccount).amm.oracle\n\t\t\t: (marketAccount as SpotMarketAccount).oracle;\n\n\t\tconst currentOracleCadence =\n\t\t\tthis.accountLoader.getAccountCadence(oracleAccountPubKey);\n\n\t\tif (currentOracleCadence !== newCadence) {\n\t\t\tthis.accountLoader.setCustomPollingFrequency(\n\t\t\t\toracleAccountPubKey,\n\t\t\t\tnewCadence\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Updates account loader polling cadences for multiple markets based on their categorization.\n\t *\n\t * This method applies different polling frequencies based on market importance:\n\t * - Selected trade market: Highest frequency (most important for active trading)\n\t * - User-involved markets: Medium frequency (user has positions)\n\t * - User-not-involved markets: Lowest frequency (background monitoring)\n\t */\n\tprivate updateAccountLoaderCadenceForMarkets(\n\t\tuserInvolvedMarkets: MarketId[],\n\t\tuserNotInvolvedMarkets: MarketId[],\n\t\tselectedTradeMarket?: MarketId | null\n\t): void {\n\t\tif (selectedTradeMarket) {\n\t\t\tthis.updateMarketAccountCadence(\n\t\t\t\tselectedTradeMarket,\n\t\t\t\tSELECTED_MARKET_ACCOUNT_POLLING_CADENCE\n\t\t\t);\n\t\t}\n\n\t\tuserInvolvedMarkets.forEach((market) => {\n\t\t\tthis.updateMarketAccountCadence(\n\t\t\t\tmarket,\n\t\t\t\tUSER_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE\n\t\t\t);\n\t\t});\n\n\t\tuserNotInvolvedMarkets.forEach((market) => {\n\t\t\tthis.updateMarketAccountCadence(\n\t\t\t\tmarket,\n\t\t\t\tUSER_NOT_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Updates DLOB (Decentralized Limit Order Book) polling intervals for market data.\n\t *\n\t * This method configures how frequently the DLOB server is polled for market data\n\t * including mark prices, oracle prices, and orderbook data. Different markets are\n\t * assigned to different polling intervals based on their importance.\n\t */\n\tprivate updatePollingDlobIntervals(\n\t\tuserInvolvedMarkets: MarketKey[],\n\t\tuserNotInvolvedMarkets: MarketKey[]\n\t): void {\n\t\tthis.pollingDlob.addMarketsToInterval(\n\t\t\tPollingCategory.USER_INVOLVED,\n\t\t\tuserInvolvedMarkets\n\t\t);\n\t\tthis.pollingDlob.addMarketsToInterval(\n\t\t\tPollingCategory.USER_NOT_INVOLVED,\n\t\t\tuserNotInvolvedMarkets\n\t\t);\n\t}\n\n\t/**\n\t * Handles comprehensive subscription updates when user account data changes.\n\t *\n\t * This is the main orchestration method that ensures optimal polling frequencies\n\t * are maintained when user positions change. It automatically:\n\t *\n\t * 1. Categorizes markets based on current user involvement\n\t * 2. Updates account loader cadences for market and oracle accounts\n\t * 3. Updates DLOB polling intervals for price data\n\t *\n\t * The method ensures that markets with user positions get higher priority polling\n\t * to maintain accurate real-time data for position management.\n\t */\n\thandleSubscriptionUpdatesOnUserUpdates(users: User[]): void {\n\t\tconst { userInvolvedMarkets, userNotInvolvedMarkets } =\n\t\t\tthis.categorizeMarketsByUserInvolvement(users);\n\n\t\t// Filter out selected trade market from the other categories\n\t\tconst filteredUserInvolvedMarkets = userInvolvedMarkets.filter(\n\t\t\t(market) => market.key !== this.selectedTradeMarket?.key\n\t\t);\n\t\tconst filteredUserNotInvolvedMarkets = userNotInvolvedMarkets.filter(\n\t\t\t(market) => market.key !== this.selectedTradeMarket?.key\n\t\t);\n\n\t\t// Update market account cadences\n\t\tthis.updateAccountLoaderCadenceForMarkets(\n\t\t\tfilteredUserInvolvedMarkets,\n\t\t\tfilteredUserNotInvolvedMarkets,\n\t\t\tthis.selectedTradeMarket\n\t\t);\n\n\t\t// Handle polling dlob polling intervals\n\t\tthis.updatePollingDlobIntervals(\n\t\t\tfilteredUserInvolvedMarkets.map((market) => market.key),\n\t\t\tfilteredUserNotInvolvedMarkets.map((market) => market.key)\n\t\t\t// this.selectedTradeMarket\n\t\t);\n\t}\n\n\t/**\n\t * Subscribes to markets that users are involved in but aren't in the default tradable markets list.\n\t *\n\t * This method ensures that if users have positions in markets that weren't initially\n\t * included in the tradable markets list, those markets are still properly subscribed to.\n\t * This is important for maintaining accurate account data even for edge cases.\n\t */\n\tasync subscribeToNonWhitelistedButUserInvolvedMarkets(\n\t\tusers: User[]\n\t): Promise<void> {\n\t\tconst perpMarketIndexesSet = new Set(\n\t\t\t(\n\t\t\t\tthis.driftClient\n\t\t\t\t\t.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t\t).perpMarketIndexes\n\t\t);\n\t\tconst spotMarketIndexesSet = new Set(\n\t\t\t(\n\t\t\t\tthis.driftClient\n\t\t\t\t\t.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t\t).spotMarketIndexes\n\t\t);\n\n\t\tconst { userInvolvedMarkets } =\n\t\t\tthis.categorizeMarketsByUserInvolvement(users);\n\n\t\tuserInvolvedMarkets.forEach((market) => {\n\t\t\tif (market.isPerp) {\n\t\t\t\tperpMarketIndexesSet.add(market.marketIndex);\n\t\t\t} else {\n\t\t\t\tspotMarketIndexesSet.add(market.marketIndex);\n\t\t\t}\n\t\t});\n\n\t\t(\n\t\t\tthis.driftClient.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t).perpMarketIndexes = Array.from(perpMarketIndexesSet);\n\t\t(\n\t\t\tthis.driftClient.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t).spotMarketIndexes = Array.from(spotMarketIndexesSet);\n\n\t\t// TODO: see if this can be optimized - instead of unsubscribing and resubscribing, find a way to add the new markets to the existing subscription\n\t\tawait (\n\t\t\tthis.driftClient.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t).unsubscribe();\n\t\tawait (\n\t\t\tthis.driftClient.accountSubscriber as PollingDriftClientAccountSubscriber\n\t\t).subscribe();\n\t}\n\n\tprivate checkIsUserInvolvedInMarket(marketId: MarketId): boolean {\n\t\tlet isUserInvolvedInPreviousSelectedTradeMarket = false;\n\t\tconst allUsers = this.userAccountCache.allUsers;\n\t\tfor (const user of allUsers) {\n\t\t\tconst { activePerpPositions, activeSpotPositions } =\n\t\t\t\tuser.userClient.getActivePositions();\n\n\t\t\tif (\n\t\t\t\tmarketId.isPerp &&\n\t\t\t\tactivePerpPositions.includes(marketId.marketIndex)\n\t\t\t) {\n\t\t\t\tisUserInvolvedInPreviousSelectedTradeMarket = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tmarketId.isSpot &&\n\t\t\t\tactiveSpotPositions.includes(marketId.marketIndex)\n\t\t\t) {\n\t\t\t\tisUserInvolvedInPreviousSelectedTradeMarket = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn isUserInvolvedInPreviousSelectedTradeMarket;\n\t}\n\n\t/**\n\t * Updates the selected trade market and optimizes all subscription polling accordingly.\n\t *\n\t * This method handles:\n\t * 1. Removing the previous market from high-frequency polling\n\t * 2. Adding the new market to high-frequency polling\n\t * 3. Updating market account cadences for optimal performance\n\t * 4. Categorizing the previous market based on user involvement\n\t * 5. Assigning appropriate polling intervals to the previous market\n\t *\n\t * @param newSelectedTradeMarket - The new market to prioritize for trading\n\t */\n\tupdateSelectedTradeMarket(newSelectedTradeMarket: MarketId | null): void {\n\t\tconst previousSelectedTradeMarket = this.selectedTradeMarket;\n\n\t\tthis.orderbookManager.unsubscribe();\n\n\t\tif (previousSelectedTradeMarket) {\n\t\t\tconst isUserInvolvedInPreviousSelectedTradeMarket =\n\t\t\t\tthis.checkIsUserInvolvedInMarket(previousSelectedTradeMarket);\n\n\t\t\tconst pollingCategoryOfPreviousSelectedMarket =\n\t\t\t\tisUserInvolvedInPreviousSelectedTradeMarket\n\t\t\t\t\t? PollingCategory.USER_INVOLVED\n\t\t\t\t\t: PollingCategory.USER_NOT_INVOLVED;\n\t\t\tthis.pollingDlob.addMarketToInterval(\n\t\t\t\tpollingCategoryOfPreviousSelectedMarket,\n\t\t\t\tpreviousSelectedTradeMarket.key\n\t\t\t);\n\n\t\t\tconst pollingCadenceOfPreviousSelectedMarket =\n\t\t\t\tisUserInvolvedInPreviousSelectedTradeMarket\n\t\t\t\t\t? USER_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE\n\t\t\t\t\t: USER_NOT_INVOLVED_MARKET_ACCOUNT_POLLING_CADENCE;\n\t\t\tthis.updateMarketAccountCadence(\n\t\t\t\tpreviousSelectedTradeMarket,\n\t\t\t\tpollingCadenceOfPreviousSelectedMarket\n\t\t\t);\n\t\t}\n\n\t\t// Update the selected trade market\n\t\tthis.selectedTradeMarket = newSelectedTradeMarket;\n\n\t\tif (newSelectedTradeMarket) {\n\t\t\tconst isUserInvolvedInNewSelectedTradeMarket =\n\t\t\t\tthis.checkIsUserInvolvedInMarket(newSelectedTradeMarket);\n\n\t\t\tconst pollingCategoryOfNewsSelectedMarket =\n\t\t\t\tisUserInvolvedInNewSelectedTradeMarket\n\t\t\t\t\t? PollingCategory.USER_INVOLVED\n\t\t\t\t\t: PollingCategory.USER_NOT_INVOLVED;\n\t\t\tthis.pollingDlob.removeMarketFromInterval(\n\t\t\t\tpollingCategoryOfNewsSelectedMarket,\n\t\t\t\tnewSelectedTradeMarket.key\n\t\t\t);\n\n\t\t\tthis.updateMarketAccountCadence(\n\t\t\t\tnewSelectedTradeMarket,\n\t\t\t\tSELECTED_MARKET_ACCOUNT_POLLING_CADENCE\n\t\t\t);\n\n\t\t\tthis.orderbookManager.updateSubscription({\n\t\t\t\t...DEFAULT_ORDERBOOK_SUBSCRIPTION_CONFIG,\n\t\t\t\tmarketId: newSelectedTradeMarket,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Updates the authority (wallet) for the drift client and reestablishes subscriptions.\n\t *\n\t * This method handles the complete process of switching to a new wallet:\n\t * 1. Checks if the wallet is actually different\n\t * 2. Unsubscribes from current user accounts\n\t * 3. Resets the user account cache\n\t * 4. Updates the DriftClient with the new wallet\n\t * 5. Resubscribes to markets based on new user positions\n\t * 6. Switches to the specified subaccount if provided\n\t * 7. Reestablishes user account subscriptions\n\t */\n\tasync updateAuthority(\n\t\twallet: IWallet,\n\t\tactiveSubAccountId?: number\n\t): Promise<void> {\n\t\tif (this.driftClient.wallet.publicKey.equals(wallet.publicKey)) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait Promise.all(this.driftClient.unsubscribeUsers());\n\t\tthis.userAccountCache.reset();\n\n\t\tconst updateWalletResult = await this.driftClient.updateWallet(\n\t\t\twallet,\n\t\t\tundefined,\n\t\t\tactiveSubAccountId,\n\t\t\ttrue,\n\t\t\tundefined\n\t\t);\n\n\t\tawait this.subscribeToNonWhitelistedButUserInvolvedMarkets(\n\t\t\tthis.driftClient.getUsers()\n\t\t);\n\n\t\tif (!updateWalletResult) {\n\t\t\tthrow new Error('Failed to update wallet');\n\t\t}\n\n\t\tif (activeSubAccountId) {\n\t\t\tawait this.driftClient.switchActiveUser(activeSubAccountId);\n\t\t}\n\n\t\tthis.subscribeToAllUsersUpdates();\n\t}\n}\n"]}