@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.
- package/lib/Config.d.ts +26 -0
- package/lib/Config.js +29 -0
- package/lib/Config.js.map +1 -0
- package/lib/EnvironmentConstants.d.ts +40 -0
- package/lib/EnvironmentConstants.js +64 -0
- package/lib/EnvironmentConstants.js.map +1 -0
- package/lib/actions/actionHelpers/accountDeletionHelpers.d.ts +16 -0
- package/lib/actions/actionHelpers/accountDeletionHelpers.js +151 -0
- package/lib/actions/actionHelpers/accountDeletionHelpers.js.map +1 -0
- package/lib/actions/actionHelpers/actionHelpers.d.ts +13 -0
- package/lib/actions/actionHelpers/actionHelpers.js +8 -0
- package/lib/actions/actionHelpers/actionHelpers.js.map +1 -0
- package/lib/chartConstants.d.ts +2 -0
- package/lib/chartConstants.js +14 -0
- package/lib/chartConstants.js.map +1 -0
- package/lib/clients/candleClient.d.ts +74 -0
- package/lib/clients/candleClient.js +364 -0
- package/lib/clients/candleClient.js.map +1 -0
- package/lib/clients/dataApiWsClient.d.ts +33 -0
- package/lib/clients/dataApiWsClient.js +118 -0
- package/lib/clients/dataApiWsClient.js.map +1 -0
- package/lib/clients/index.d.ts +1 -0
- package/lib/clients/index.js +19 -0
- package/lib/clients/index.js.map +1 -0
- package/lib/clients/marketDataFeed.d.ts +42 -0
- package/lib/clients/marketDataFeed.js +422 -0
- package/lib/clients/marketDataFeed.js.map +1 -0
- package/lib/clients/redisClient.d.ts +89 -0
- package/lib/clients/redisClient.js +647 -0
- package/lib/clients/redisClient.js.map +1 -0
- package/lib/clients/swiftClient.d.ts +57 -0
- package/lib/clients/swiftClient.js +289 -0
- package/lib/clients/swiftClient.js.map +1 -0
- package/lib/clients/tvFeed.d.ts +63 -0
- package/lib/clients/tvFeed.js +351 -0
- package/lib/clients/tvFeed.js.map +1 -0
- package/lib/common-ui-utils/commonUiUtils.d.ts +211 -0
- package/lib/common-ui-utils/commonUiUtils.js +624 -0
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -0
- package/lib/common-ui-utils/index.d.ts +6 -0
- package/lib/common-ui-utils/index.js +23 -0
- package/lib/common-ui-utils/index.js.map +1 -0
- package/lib/common-ui-utils/market.d.ts +27 -0
- package/lib/common-ui-utils/market.js +80 -0
- package/lib/common-ui-utils/market.js.map +1 -0
- package/lib/common-ui-utils/order.d.ts +11 -0
- package/lib/common-ui-utils/order.js +161 -0
- package/lib/common-ui-utils/order.js.map +1 -0
- package/lib/common-ui-utils/settings/settings.d.ts +51 -0
- package/lib/common-ui-utils/settings/settings.js +84 -0
- package/lib/common-ui-utils/settings/settings.js.map +1 -0
- package/lib/common-ui-utils/trading.d.ts +56 -0
- package/lib/common-ui-utils/trading.js +200 -0
- package/lib/common-ui-utils/trading.js.map +1 -0
- package/lib/common-ui-utils/user.d.ts +13 -0
- package/lib/common-ui-utils/user.js +124 -0
- package/lib/common-ui-utils/user.js.map +1 -0
- package/lib/constants/autogenerated/driftErrors.json +1787 -0
- package/lib/constants/autogenerated/jup-v4-error-codes.json +67 -0
- package/lib/constants/autogenerated/jup-v6-error-codes.json +115 -0
- package/lib/constants/dev.d.ts +15 -0
- package/lib/constants/dev.js +19 -0
- package/lib/constants/dev.js.map +1 -0
- package/lib/constants/geoblockList.d.ts +4 -0
- package/lib/constants/geoblockList.js +32 -0
- package/lib/constants/geoblockList.js.map +1 -0
- package/lib/constants/index.d.ts +9 -0
- package/lib/constants/index.js +26 -0
- package/lib/constants/index.js.map +1 -0
- package/lib/constants/markets.d.ts +1 -0
- package/lib/constants/markets.js +5 -0
- package/lib/constants/markets.js.map +1 -0
- package/lib/constants/misc.d.ts +23 -0
- package/lib/constants/misc.js +27 -0
- package/lib/constants/misc.js.map +1 -0
- package/lib/constants/orders.d.ts +12 -0
- package/lib/constants/orders.js +79 -0
- package/lib/constants/orders.js.map +1 -0
- package/lib/constants/pools.d.ts +5 -0
- package/lib/constants/pools.js +9 -0
- package/lib/constants/pools.js.map +1 -0
- package/lib/constants/predictionMarket.d.ts +3 -0
- package/lib/constants/predictionMarket.js +7 -0
- package/lib/constants/predictionMarket.js.map +1 -0
- package/lib/constants/superstake.d.ts +22 -0
- package/lib/constants/superstake.js +45 -0
- package/lib/constants/superstake.js.map +1 -0
- package/lib/constants/trade.d.ts +2 -0
- package/lib/constants/trade.js +9 -0
- package/lib/constants/trade.js.map +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +68 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js +146 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js.map +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +204 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +530 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +90 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js +3 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.d.ts +139 -0
- package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.js +287 -0
- package/lib/drift/Drift/clients/AuthorityDrift/SubscriptionManager.js.map +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +242 -0
- package/lib/drift/Drift/clients/AuthorityDrift/index.js +503 -0
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -0
- package/lib/drift/Drift/clients/CentralServerDrift.d.ts +91 -0
- package/lib/drift/Drift/clients/CentralServerDrift.js +326 -0
- package/lib/drift/Drift/clients/CentralServerDrift.js.map +1 -0
- package/lib/drift/Drift/clients/index.d.ts +3 -0
- package/lib/drift/Drift/clients/index.js +20 -0
- package/lib/drift/Drift/clients/index.js.map +1 -0
- package/lib/drift/Drift/constants/blockchain.d.ts +24 -0
- package/lib/drift/Drift/constants/blockchain.js +32 -0
- package/lib/drift/Drift/constants/blockchain.js.map +1 -0
- package/lib/drift/Drift/constants/errors.d.ts +6 -0
- package/lib/drift/Drift/constants/errors.js +14 -0
- package/lib/drift/Drift/constants/errors.js.map +1 -0
- package/lib/drift/Drift/constants/index.d.ts +3 -0
- package/lib/drift/Drift/constants/index.js +20 -0
- package/lib/drift/Drift/constants/index.js.map +1 -0
- package/lib/drift/Drift/constants/orderbook.d.ts +7 -0
- package/lib/drift/Drift/constants/orderbook.js +10 -0
- package/lib/drift/Drift/constants/orderbook.js.map +1 -0
- package/lib/drift/Drift/data/PollingDlob.d.ts +154 -0
- package/lib/drift/Drift/data/PollingDlob.js +387 -0
- package/lib/drift/Drift/data/PollingDlob.js.map +1 -0
- package/lib/drift/Drift/data/index.d.ts +1 -0
- package/lib/drift/Drift/data/index.js +18 -0
- package/lib/drift/Drift/data/index.js.map +1 -0
- package/lib/drift/Drift/index.d.ts +4 -0
- package/lib/drift/Drift/index.js +21 -0
- package/lib/drift/Drift/index.js.map +1 -0
- package/lib/drift/Drift/stores/MarkPriceCache.d.ts +27 -0
- package/lib/drift/Drift/stores/MarkPriceCache.js +59 -0
- package/lib/drift/Drift/stores/MarkPriceCache.js.map +1 -0
- package/lib/drift/Drift/stores/OraclePriceCache.d.ts +21 -0
- package/lib/drift/Drift/stores/OraclePriceCache.js +57 -0
- package/lib/drift/Drift/stores/OraclePriceCache.js.map +1 -0
- package/lib/drift/Drift/stores/UserAccountCache.d.ts +49 -0
- package/lib/drift/Drift/stores/UserAccountCache.js +107 -0
- package/lib/drift/Drift/stores/UserAccountCache.js.map +1 -0
- package/lib/drift/Drift/stores/index.d.ts +3 -0
- package/lib/drift/Drift/stores/index.js +20 -0
- package/lib/drift/Drift/stores/index.js.map +1 -0
- package/lib/drift/base/actions/index.d.ts +4 -0
- package/lib/drift/base/actions/index.js +21 -0
- package/lib/drift/base/actions/index.js.map +1 -0
- package/lib/drift/base/actions/perp/index.d.ts +2 -0
- package/lib/drift/base/actions/perp/index.js +19 -0
- package/lib/drift/base/actions/perp/index.js.map +1 -0
- package/lib/drift/base/actions/perp/settleFunding.d.ts +25 -0
- package/lib/drift/base/actions/perp/settleFunding.js +41 -0
- package/lib/drift/base/actions/perp/settleFunding.js.map +1 -0
- package/lib/drift/base/actions/perp/settlePnl.d.ts +35 -0
- package/lib/drift/base/actions/perp/settlePnl.js +44 -0
- package/lib/drift/base/actions/perp/settlePnl.js.map +1 -0
- package/lib/drift/base/actions/spot/borrow.d.ts +1 -0
- package/lib/drift/base/actions/spot/borrow.js +8 -0
- package/lib/drift/base/actions/spot/borrow.js.map +1 -0
- package/lib/drift/base/actions/spot/deposit.d.ts +40 -0
- package/lib/drift/base/actions/spot/deposit.js +82 -0
- package/lib/drift/base/actions/spot/deposit.js.map +1 -0
- package/lib/drift/base/actions/spot/index.d.ts +3 -0
- package/lib/drift/base/actions/spot/index.js +20 -0
- package/lib/drift/base/actions/spot/index.js.map +1 -0
- package/lib/drift/base/actions/spot/withdraw.d.ts +16 -0
- package/lib/drift/base/actions/spot/withdraw.js +39 -0
- package/lib/drift/base/actions/spot/withdraw.js.map +1 -0
- package/lib/drift/base/actions/trade/cancelOrder.d.ts +47 -0
- package/lib/drift/base/actions/trade/cancelOrder.js +55 -0
- package/lib/drift/base/actions/trade/cancelOrder.js.map +1 -0
- package/lib/drift/base/actions/trade/editOrder.d.ts +55 -0
- package/lib/drift/base/actions/trade/editOrder.js +35 -0
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -0
- package/lib/drift/base/actions/trade/index.d.ts +4 -0
- package/lib/drift/base/actions/trade/index.js +21 -0
- package/lib/drift/base/actions/trade/index.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/index.d.ts +3 -0
- package/lib/drift/base/actions/trade/openPerpOrder/index.js +20 -0
- package/lib/drift/base/actions/trade/openPerpOrder/index.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +84 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +293 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +19 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +161 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +166 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +156 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -0
- package/lib/drift/base/actions/trade/swap.d.ts +62 -0
- package/lib/drift/base/actions/trade/swap.js +60 -0
- package/lib/drift/base/actions/trade/swap.js.map +1 -0
- package/lib/drift/base/actions/user/create.d.ts +75 -0
- package/lib/drift/base/actions/user/create.js +104 -0
- package/lib/drift/base/actions/user/create.js.map +1 -0
- package/lib/drift/base/actions/user/delete.d.ts +47 -0
- package/lib/drift/base/actions/user/delete.js +39 -0
- package/lib/drift/base/actions/user/delete.js.map +1 -0
- package/lib/drift/base/actions/user/index.d.ts +1 -0
- package/lib/drift/base/actions/user/index.js +18 -0
- package/lib/drift/base/actions/user/index.js.map +1 -0
- package/lib/drift/base/constants/accountNames.d.ts +1 -0
- package/lib/drift/base/constants/accountNames.js +13 -0
- package/lib/drift/base/constants/accountNames.js.map +1 -0
- package/lib/drift/base/details/index.d.ts +2 -0
- package/lib/drift/base/details/index.js +19 -0
- package/lib/drift/base/details/index.js.map +1 -0
- package/lib/drift/base/details/market/funding.d.ts +9 -0
- package/lib/drift/base/details/market/funding.js +50 -0
- package/lib/drift/base/details/market/funding.js.map +1 -0
- package/lib/drift/base/details/market/index.d.ts +2 -0
- package/lib/drift/base/details/market/index.js +19 -0
- package/lib/drift/base/details/market/index.js.map +1 -0
- package/lib/drift/base/details/market/openInterest.d.ts +5 -0
- package/lib/drift/base/details/market/openInterest.js +12 -0
- package/lib/drift/base/details/market/openInterest.js.map +1 -0
- package/lib/drift/base/details/user/balances.d.ts +40 -0
- package/lib/drift/base/details/user/balances.js +39 -0
- package/lib/drift/base/details/user/balances.js.map +1 -0
- package/lib/drift/base/details/user/index.d.ts +4 -0
- package/lib/drift/base/details/user/index.js +21 -0
- package/lib/drift/base/details/user/index.js.map +1 -0
- package/lib/drift/base/details/user/marginInfo.d.ts +29 -0
- package/lib/drift/base/details/user/marginInfo.js +49 -0
- package/lib/drift/base/details/user/marginInfo.js.map +1 -0
- package/lib/drift/base/details/user/orders.d.ts +3 -0
- package/lib/drift/base/details/user/orders.js +11 -0
- package/lib/drift/base/details/user/orders.js.map +1 -0
- package/lib/drift/base/details/user/positions.d.ts +70 -0
- package/lib/drift/base/details/user/positions.js +146 -0
- package/lib/drift/base/details/user/positions.js.map +1 -0
- package/lib/drift/cli.d.ts +25 -0
- package/lib/drift/cli.js +900 -0
- package/lib/drift/cli.js.map +1 -0
- package/lib/drift/constants/apiUrls.d.ts +27 -0
- package/lib/drift/constants/apiUrls.js +31 -0
- package/lib/drift/constants/apiUrls.js.map +1 -0
- package/lib/drift/example.d.ts +19 -0
- package/lib/drift/example.js +249 -0
- package/lib/drift/example.js.map +1 -0
- package/lib/drift/index.d.ts +3 -0
- package/lib/drift/index.js +20 -0
- package/lib/drift/index.js.map +1 -0
- package/lib/drift/utils/auctionParamsResponseMapper.d.ts +45 -0
- package/lib/drift/utils/auctionParamsResponseMapper.js +148 -0
- package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -0
- package/lib/drift/utils/funding.d.ts +2 -0
- package/lib/drift/utils/funding.js +9 -0
- package/lib/drift/utils/funding.js.map +1 -0
- package/lib/drift/utils/index.d.ts +3 -0
- package/lib/drift/utils/index.js +23 -0
- package/lib/drift/utils/index.js.map +1 -0
- package/lib/drift/utils/orderParams.d.ts +48 -0
- package/lib/drift/utils/orderParams.js +140 -0
- package/lib/drift/utils/orderParams.js.map +1 -0
- package/lib/index.d.ts +45 -0
- package/lib/index.js +68 -0
- package/lib/index.js.map +1 -0
- package/lib/serializableTypes.d.ts +961 -0
- package/lib/serializableTypes.js +3887 -0
- package/lib/serializableTypes.js.map +1 -0
- package/lib/types/MarketId.d.ts +26 -0
- package/lib/types/MarketId.js +64 -0
- package/lib/types/MarketId.js.map +1 -0
- package/lib/types/Superstake.d.ts +7 -0
- package/lib/types/Superstake.js +3 -0
- package/lib/types/Superstake.js.map +1 -0
- package/lib/types/UIEnv.d.ts +26 -0
- package/lib/types/UIEnv.js +49 -0
- package/lib/types/UIEnv.js.map +1 -0
- package/lib/types/UIMarket.d.ts +94 -0
- package/lib/types/UIMarket.js +224 -0
- package/lib/types/UIMarket.js.map +1 -0
- package/lib/types/candles.d.ts +4 -0
- package/lib/types/candles.js +9 -0
- package/lib/types/candles.js.map +1 -0
- package/lib/types/dataServer.d.ts +53 -0
- package/lib/types/dataServer.js +3 -0
- package/lib/types/dataServer.js.map +1 -0
- package/lib/types/historyServer.d.ts +38 -0
- package/lib/types/historyServer.js +11 -0
- package/lib/types/historyServer.js.map +1 -0
- package/lib/types/index.d.ts +12 -0
- package/lib/types/index.js +29 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/leaderboard.d.ts +80 -0
- package/lib/types/leaderboard.js +11 -0
- package/lib/types/leaderboard.js.map +1 -0
- package/lib/types/remote-configs.d.ts +61 -0
- package/lib/types/remote-configs.js +3 -0
- package/lib/types/remote-configs.js.map +1 -0
- package/lib/types/trade.d.ts +18 -0
- package/lib/types/trade.js +3 -0
- package/lib/types/trade.js.map +1 -0
- package/lib/types/user.d.ts +40 -0
- package/lib/types/user.js +3 -0
- package/lib/types/user.js.map +1 -0
- package/lib/types/utility.d.ts +15 -0
- package/lib/types/utility.js +3 -0
- package/lib/types/utility.js.map +1 -0
- package/lib/utils/CircularBuffers/CircularBuffer.d.ts +22 -0
- package/lib/utils/CircularBuffers/CircularBuffer.js +73 -0
- package/lib/utils/CircularBuffers/CircularBuffer.js.map +1 -0
- package/lib/utils/CircularBuffers/UniqueCircularBuffer.d.ts +19 -0
- package/lib/utils/CircularBuffers/UniqueCircularBuffer.js +78 -0
- package/lib/utils/CircularBuffers/UniqueCircularBuffer.js.map +1 -0
- package/lib/utils/CircularBuffers/index.d.ts +2 -0
- package/lib/utils/CircularBuffers/index.js +19 -0
- package/lib/utils/CircularBuffers/index.js.map +1 -0
- package/lib/utils/MultiplexWebSocket.d.ts +95 -0
- package/lib/utils/MultiplexWebSocket.js +416 -0
- package/lib/utils/MultiplexWebSocket.js.map +1 -0
- package/lib/utils/NumLib.d.ts +106 -0
- package/lib/utils/NumLib.js +300 -0
- package/lib/utils/NumLib.js.map +1 -0
- package/lib/utils/SharedInterval.d.ts +21 -0
- package/lib/utils/SharedInterval.js +47 -0
- package/lib/utils/SharedInterval.js.map +1 -0
- package/lib/utils/SlotBasedResultValidator.d.ts +9 -0
- package/lib/utils/SlotBasedResultValidator.js +27 -0
- package/lib/utils/SlotBasedResultValidator.js.map +1 -0
- package/lib/utils/Stopwatch.d.ts +15 -0
- package/lib/utils/Stopwatch.js +31 -0
- package/lib/utils/Stopwatch.js.map +1 -0
- package/lib/utils/StrictEventEmitter.d.ts +15 -0
- package/lib/utils/StrictEventEmitter.js +55 -0
- package/lib/utils/StrictEventEmitter.js.map +1 -0
- package/lib/utils/WalletConnectionState.d.ts +31 -0
- package/lib/utils/WalletConnectionState.js +83 -0
- package/lib/utils/WalletConnectionState.js.map +1 -0
- package/lib/utils/assert.d.ts +1 -0
- package/lib/utils/assert.js +10 -0
- package/lib/utils/assert.js.map +1 -0
- package/lib/utils/candles/Candle.d.ts +94 -0
- package/lib/utils/candles/Candle.js +580 -0
- package/lib/utils/candles/Candle.js.map +1 -0
- package/lib/utils/candles/types.d.ts +8 -0
- package/lib/utils/candles/types.js +3 -0
- package/lib/utils/candles/types.js.map +1 -0
- package/lib/utils/dlob-server/DlobServerWebsocketUtils.d.ts +57 -0
- package/lib/utils/dlob-server/DlobServerWebsocketUtils.js +137 -0
- package/lib/utils/dlob-server/DlobServerWebsocketUtils.js.map +1 -0
- package/lib/utils/driftEvents.d.ts +10 -0
- package/lib/utils/driftEvents.js +123 -0
- package/lib/utils/driftEvents.js.map +1 -0
- package/lib/utils/equalityChecks.d.ts +12 -0
- package/lib/utils/equalityChecks.js +71 -0
- package/lib/utils/equalityChecks.js.map +1 -0
- package/lib/utils/featureFlags.d.ts +3 -0
- package/lib/utils/featureFlags.js +7 -0
- package/lib/utils/featureFlags.js.map +1 -0
- package/lib/utils/geoblock/index.d.ts +4 -0
- package/lib/utils/geoblock/index.js +20 -0
- package/lib/utils/geoblock/index.js.map +1 -0
- package/lib/utils/index.d.ts +181 -0
- package/lib/utils/index.js +608 -0
- package/lib/utils/index.js.map +1 -0
- package/lib/utils/insuranceFund.d.ts +15 -0
- package/lib/utils/insuranceFund.js +84 -0
- package/lib/utils/insuranceFund.js.map +1 -0
- package/lib/utils/logger.d.ts +5 -0
- package/lib/utils/logger.js +53 -0
- package/lib/utils/logger.js.map +1 -0
- package/lib/utils/math.d.ts +10 -0
- package/lib/utils/math.js +89 -0
- package/lib/utils/math.js.map +1 -0
- package/lib/utils/orderbook/index.d.ts +65 -0
- package/lib/utils/orderbook/index.js +80 -0
- package/lib/utils/orderbook/index.js.map +1 -0
- package/lib/utils/pollingSequenceGuard.d.ts +9 -0
- package/lib/utils/pollingSequenceGuard.js +24 -0
- package/lib/utils/pollingSequenceGuard.js.map +1 -0
- package/lib/utils/priority-fees/PriorityFeeCalculator.d.ts +24 -0
- package/lib/utils/priority-fees/PriorityFeeCalculator.js +53 -0
- package/lib/utils/priority-fees/PriorityFeeCalculator.js.map +1 -0
- package/lib/utils/priority-fees/PriorityFeeStrategies.d.ts +5 -0
- package/lib/utils/priority-fees/PriorityFeeStrategies.js +43 -0
- package/lib/utils/priority-fees/PriorityFeeStrategies.js.map +1 -0
- package/lib/utils/priority-fees/index.d.ts +2 -0
- package/lib/utils/priority-fees/index.js +19 -0
- package/lib/utils/priority-fees/index.js.map +1 -0
- package/lib/utils/priorityFees.d.ts +14 -0
- package/lib/utils/priorityFees.js +68 -0
- package/lib/utils/priorityFees.js.map +1 -0
- package/lib/utils/rpcLatency.d.ts +7 -0
- package/lib/utils/rpcLatency.js +49 -0
- package/lib/utils/rpcLatency.js.map +1 -0
- package/lib/utils/rxjs.d.ts +11 -0
- package/lib/utils/rxjs.js +24 -0
- package/lib/utils/rxjs.js.map +1 -0
- package/lib/utils/s3Buckets.d.ts +43 -0
- package/lib/utils/s3Buckets.js +108 -0
- package/lib/utils/s3Buckets.js.map +1 -0
- package/lib/utils/superstake.d.ts +86 -0
- package/lib/utils/superstake.js +224 -0
- package/lib/utils/superstake.js.map +1 -0
- package/lib/utils/token.d.ts +16 -0
- package/lib/utils/token.js +44 -0
- package/lib/utils/token.js.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
5
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
8
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
11
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
12
|
+
};
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
var _MultiplexWebSocket_webSocket;
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.MultiplexWebSocket = void 0;
|
|
19
|
+
const rxjs_1 = require("rxjs");
|
|
20
|
+
const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
|
|
21
|
+
const DEFAULT_MAX_RECONNECT_ATTEMPTS = 5;
|
|
22
|
+
const DEFAULT_MAX_RECONNECT_WINDOW_MS = 60 * 1000;
|
|
23
|
+
const DEFAULT_CONNECTION_CLOSE_DELAY_MS = 2 * 1000; // 2 seconds delay before closing connection
|
|
24
|
+
const DEFAULT_HEARTBEAT_TIMEOUT_MS = 60 * 1000; // Consider connection dead if no heartbeat within 60 seconds
|
|
25
|
+
/**
|
|
26
|
+
* Manages reconnection logic for WebSocket connections with exponential backoff and rate limiting.
|
|
27
|
+
*
|
|
28
|
+
* Features:
|
|
29
|
+
* - Tracks reconnection attempts within a time window
|
|
30
|
+
* - Implements exponential backoff (1s, 2s, 4s, 8s max)
|
|
31
|
+
* - Resets attempt counter after configurable time window
|
|
32
|
+
* - Throws error when max attempts exceeded
|
|
33
|
+
* - Provides configurable limits for attempts and time window
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* const manager = new ReconnectionManager(5, 60000); // 5 attempts in 60s
|
|
38
|
+
* const { shouldReconnect, delay } = manager.attemptReconnection('ws://example.com');
|
|
39
|
+
* if (shouldReconnect) {
|
|
40
|
+
* setTimeout(() => reconnect(), delay);
|
|
41
|
+
* }
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
class ReconnectionManager {
|
|
45
|
+
constructor(maxAttemptsCount = DEFAULT_MAX_RECONNECT_ATTEMPTS, maxAttemptsWindowMs = DEFAULT_MAX_RECONNECT_WINDOW_MS) {
|
|
46
|
+
this.reconnectAttempts = 0;
|
|
47
|
+
this.lastReconnectWindow = Date.now();
|
|
48
|
+
this.maxAttemptsCount = maxAttemptsCount;
|
|
49
|
+
this.maxAttemptsWindowMs = maxAttemptsWindowMs;
|
|
50
|
+
}
|
|
51
|
+
attemptReconnection(wsUrl) {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
// Reset reconnect attempts if more than a minute has passed
|
|
54
|
+
if (now - this.lastReconnectWindow > this.maxAttemptsWindowMs) {
|
|
55
|
+
this.reconnectAttempts = 0;
|
|
56
|
+
this.lastReconnectWindow = now;
|
|
57
|
+
}
|
|
58
|
+
// Check if we've exceeded the maximum reconnect attempts
|
|
59
|
+
if (this.reconnectAttempts >= this.maxAttemptsCount) {
|
|
60
|
+
throw new Error(`WebSocket reconnection failed: Maximum reconnect attempts (${this.maxAttemptsCount}) exceeded within ${this.maxAttemptsWindowMs}ms for ${wsUrl}`);
|
|
61
|
+
}
|
|
62
|
+
this.reconnectAttempts++;
|
|
63
|
+
// Calculate exponential backoff delay: 1s, 2s, 4s, 8s, etc. (capped at 8s)
|
|
64
|
+
const backoffDelay = Math.min(1000 * Math.pow(2, this.reconnectAttempts - 1), 8000);
|
|
65
|
+
return {
|
|
66
|
+
shouldReconnect: true,
|
|
67
|
+
delay: backoffDelay,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
reset() {
|
|
71
|
+
this.reconnectAttempts = 0;
|
|
72
|
+
this.lastReconnectWindow = Date.now();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
var WebSocketConnectionState;
|
|
76
|
+
(function (WebSocketConnectionState) {
|
|
77
|
+
WebSocketConnectionState[WebSocketConnectionState["CONNECTING"] = 0] = "CONNECTING";
|
|
78
|
+
WebSocketConnectionState[WebSocketConnectionState["CONNECTED"] = 1] = "CONNECTED";
|
|
79
|
+
WebSocketConnectionState[WebSocketConnectionState["DISCONNECTING"] = 2] = "DISCONNECTING";
|
|
80
|
+
WebSocketConnectionState[WebSocketConnectionState["DISCONNECTED"] = 3] = "DISCONNECTED";
|
|
81
|
+
})(WebSocketConnectionState || (WebSocketConnectionState = {}));
|
|
82
|
+
/**
|
|
83
|
+
* MultiplexWebSocket allows for multiple subscriptions to a single websocket of the same URL, improving efficiency and reducing the number of open connections.
|
|
84
|
+
*
|
|
85
|
+
* This implementation assumes the following:
|
|
86
|
+
* - All websocket streams are treated equally - reconnection attempts are performed at the same standards
|
|
87
|
+
* - All messages returned are in the `WebSocketMessage` format
|
|
88
|
+
* - A single instance of the websocket manager is created for each websocket URL - this means all subscriptions to the same websocket URL will share the same websocket instance
|
|
89
|
+
*
|
|
90
|
+
* Internal implementation details:
|
|
91
|
+
* - The websocket is closed when the number of subscriptions is 0
|
|
92
|
+
* - The websocket will be refreshed (new instance) when it disconnects unexpectedly or errors, until it reaches the maximum number of reconnect attempts
|
|
93
|
+
*/
|
|
94
|
+
class MultiplexWebSocket {
|
|
95
|
+
constructor(wsUrl, enableHeartbeatMonitoring = false) {
|
|
96
|
+
_MultiplexWebSocket_webSocket.set(this, void 0);
|
|
97
|
+
this.closeTimeout = null;
|
|
98
|
+
this.heartbeatTimeout = null;
|
|
99
|
+
this.heartbeatMonitoringEnabled = false;
|
|
100
|
+
if (MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl)) {
|
|
101
|
+
throw new Error(`Attempting to create a new websocket for ${wsUrl}, but it already exists`);
|
|
102
|
+
}
|
|
103
|
+
this.wsUrl = wsUrl;
|
|
104
|
+
this.customConnectionState = WebSocketConnectionState.CONNECTING;
|
|
105
|
+
this.subject = new rxjs_1.Subject();
|
|
106
|
+
this.subscriptions = new Map();
|
|
107
|
+
this.reconnectionManager = new ReconnectionManager();
|
|
108
|
+
this.heartbeatMonitoringEnabled = enableHeartbeatMonitoring;
|
|
109
|
+
this.webSocket = new isomorphic_ws_1.default(wsUrl);
|
|
110
|
+
MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.set(wsUrl, this);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates a new virtual websocket subscription. If an existing websocket for the given URL exists, the subscription will be added to the existing websocket.
|
|
114
|
+
* Returns a function that can be called to unsubscribe from the subscription.
|
|
115
|
+
*/
|
|
116
|
+
static createWebSocketSubscription(props) {
|
|
117
|
+
const { wsUrl } = props;
|
|
118
|
+
const doesWebSocketForWsUrlExist = MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl);
|
|
119
|
+
if (doesWebSocketForWsUrlExist) {
|
|
120
|
+
return this.handleNewSubForExistingWsUrl(props);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
// Create new websocket for new URL or reopen previously closed websocket
|
|
124
|
+
return this.handleNewSubForNewWsUrl(props);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
static handleNewSubForNewWsUrl(newSubscriptionProps) {
|
|
128
|
+
var _a;
|
|
129
|
+
const newMWS = new MultiplexWebSocket(newSubscriptionProps.wsUrl, (_a = newSubscriptionProps.enableHeartbeatMonitoring) !== null && _a !== void 0 ? _a : false);
|
|
130
|
+
newMWS.subscribe(newSubscriptionProps);
|
|
131
|
+
return {
|
|
132
|
+
unsubscribe: () => {
|
|
133
|
+
newMWS.unsubscribe(newSubscriptionProps.subscriptionId);
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
static handleNewSubForExistingWsUrl(newSubscriptionProps) {
|
|
138
|
+
var _a;
|
|
139
|
+
const { wsUrl, subscriptionId } = newSubscriptionProps;
|
|
140
|
+
if (!MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl)) {
|
|
141
|
+
throw new Error(`Attempting to subscribe to ${subscriptionId} on websocket ${wsUrl}, but websocket does not exist yet`);
|
|
142
|
+
}
|
|
143
|
+
const existingMWS = MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.get(wsUrl);
|
|
144
|
+
// Check if heartbeat monitoring settings match
|
|
145
|
+
const requestedHeartbeat = (_a = newSubscriptionProps.enableHeartbeatMonitoring) !== null && _a !== void 0 ? _a : false;
|
|
146
|
+
if (existingMWS.heartbeatMonitoringEnabled !== requestedHeartbeat) {
|
|
147
|
+
console.warn(`WebSocket for ${wsUrl} already exists with heartbeat monitoring ${existingMWS.heartbeatMonitoringEnabled ? 'enabled' : 'disabled'}, ` +
|
|
148
|
+
`but new subscription requests ${requestedHeartbeat ? 'enabled' : 'disabled'}. Using existing setting.`);
|
|
149
|
+
}
|
|
150
|
+
// Track new subscription for existing websocket
|
|
151
|
+
existingMWS.subscribe(newSubscriptionProps);
|
|
152
|
+
return {
|
|
153
|
+
unsubscribe: () => {
|
|
154
|
+
existingMWS.unsubscribe(newSubscriptionProps.subscriptionId);
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
get webSocket() {
|
|
159
|
+
return __classPrivateFieldGet(this, _MultiplexWebSocket_webSocket, "f");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Setting the WebSocket instance will automatically add event handlers to the WebSocket instance.
|
|
163
|
+
* When the WebSocket is connected, all existing subscriptions will be subscribed to.
|
|
164
|
+
*/
|
|
165
|
+
set webSocket(webSocket) {
|
|
166
|
+
webSocket.onopen = () => {
|
|
167
|
+
this.customConnectionState = WebSocketConnectionState.CONNECTED;
|
|
168
|
+
this.reconnectionManager.reset(); // Reset reconnection attempts on successful connection
|
|
169
|
+
// Start heartbeat monitoring if enabled
|
|
170
|
+
if (this.heartbeatMonitoringEnabled) {
|
|
171
|
+
this.startHeartbeatMonitoring();
|
|
172
|
+
}
|
|
173
|
+
// sends subscription message for each subscription for those that are added before the websocket is connected
|
|
174
|
+
for (const [subscriptionId] of this.subscriptions.entries()) {
|
|
175
|
+
this.subscribeToWebSocket(subscriptionId);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
webSocket.onmessage = (messageEvent) => {
|
|
179
|
+
const message = JSON.parse(messageEvent.data);
|
|
180
|
+
// Check for heartbeat message from server (only if heartbeat monitoring is enabled)
|
|
181
|
+
if (this.heartbeatMonitoringEnabled && this.isHeartbeatMessage(message)) {
|
|
182
|
+
this.handleHeartbeat(message);
|
|
183
|
+
return; // Don't forward heartbeat messages to subscriptions
|
|
184
|
+
}
|
|
185
|
+
this.subject.next(message);
|
|
186
|
+
};
|
|
187
|
+
webSocket.onclose = (event) => {
|
|
188
|
+
this.customConnectionState = WebSocketConnectionState.DISCONNECTED;
|
|
189
|
+
// Stop heartbeat monitoring when connection closes (if enabled)
|
|
190
|
+
if (this.heartbeatMonitoringEnabled) {
|
|
191
|
+
this.stopHeartbeatMonitoring();
|
|
192
|
+
}
|
|
193
|
+
// Restart websocket if it was closed unexpectedly (not by us)
|
|
194
|
+
if (!event.wasClean && this.subscriptions.size > 0) {
|
|
195
|
+
console.log('WebSocket closed unexpectedly, restarting...', event);
|
|
196
|
+
this.refreshWebSocket();
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
webSocket.onerror = (error) => {
|
|
200
|
+
console.error('MultiplexWebSocket Error', { error, webSocket });
|
|
201
|
+
// Forward error to all subscriptions for this websocket URL
|
|
202
|
+
const subscriptionIds = MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl);
|
|
203
|
+
if (subscriptionIds) {
|
|
204
|
+
for (const subscriptionId of subscriptionIds) {
|
|
205
|
+
const subscription = this.subscriptions.get(subscriptionId);
|
|
206
|
+
if (subscription) {
|
|
207
|
+
subscription.onError(error);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// Restart the websocket connection on error
|
|
212
|
+
this.refreshWebSocket();
|
|
213
|
+
};
|
|
214
|
+
__classPrivateFieldSet(this, _MultiplexWebSocket_webSocket, webSocket, "f");
|
|
215
|
+
}
|
|
216
|
+
subscribeToWebSocket(subscriptionId) {
|
|
217
|
+
const subscriptionState = this.subscriptions.get(subscriptionId);
|
|
218
|
+
const { subscribeMessage, onError, onMessage, messageFilter, errorMessageFilter, onClose, } = subscriptionState;
|
|
219
|
+
this.webSocket.send(subscribeMessage);
|
|
220
|
+
if (subscriptionState) {
|
|
221
|
+
subscriptionState.hasSentSubscribeMessage = true;
|
|
222
|
+
}
|
|
223
|
+
const subjectSubscription = this.subject
|
|
224
|
+
.pipe((0, rxjs_1.catchError)((err) => {
|
|
225
|
+
console.error('Caught websocket error', err);
|
|
226
|
+
onError();
|
|
227
|
+
return [];
|
|
228
|
+
}))
|
|
229
|
+
.subscribe({
|
|
230
|
+
next: (message) => {
|
|
231
|
+
try {
|
|
232
|
+
if (!messageFilter(message))
|
|
233
|
+
return;
|
|
234
|
+
if (errorMessageFilter(message)) {
|
|
235
|
+
onError();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
onMessage(message);
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
console.error('Error parsing websocket message', err);
|
|
242
|
+
onError();
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
error: (err) => {
|
|
246
|
+
console.error('Error subscribing to websocket', err);
|
|
247
|
+
onError();
|
|
248
|
+
},
|
|
249
|
+
complete: () => {
|
|
250
|
+
if (onClose) {
|
|
251
|
+
onClose();
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
subscriptionState.subjectSubscription = subjectSubscription;
|
|
256
|
+
}
|
|
257
|
+
subscribe(props) {
|
|
258
|
+
const { subscriptionId, subscribeMessage, unsubscribeMessage, onError, onMessage, messageFilter, errorMessageFilter, onClose, } = props;
|
|
259
|
+
if (this.subscriptions.get(subscriptionId)) {
|
|
260
|
+
throw new Error(`Attempting to subscribe to ${subscriptionId} on websocket ${this.wsUrl}, but subscription already exists`);
|
|
261
|
+
}
|
|
262
|
+
// Cancel any pending delayed close since we're adding a new subscription
|
|
263
|
+
this.cancelDelayedClose();
|
|
264
|
+
this.subscriptions.set(subscriptionId, {
|
|
265
|
+
subscribeMessage,
|
|
266
|
+
unsubscribeMessage,
|
|
267
|
+
onError,
|
|
268
|
+
onMessage,
|
|
269
|
+
messageFilter,
|
|
270
|
+
errorMessageFilter,
|
|
271
|
+
onClose,
|
|
272
|
+
hasSentSubscribeMessage: false,
|
|
273
|
+
});
|
|
274
|
+
// Update URL to subscription IDs lookup
|
|
275
|
+
if (!MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.has(this.wsUrl)) {
|
|
276
|
+
MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.set(this.wsUrl, new Set());
|
|
277
|
+
}
|
|
278
|
+
MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl).add(subscriptionId);
|
|
279
|
+
if (this.customConnectionState === WebSocketConnectionState.CONNECTED) {
|
|
280
|
+
this.subscribeToWebSocket(subscriptionId);
|
|
281
|
+
}
|
|
282
|
+
else if (this.customConnectionState === WebSocketConnectionState.CONNECTING) {
|
|
283
|
+
// do nothing, subscription will automatically start when websocket is connected
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
// handle case where websocket is disconnecting/disconnected
|
|
287
|
+
this.refreshWebSocket();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
unsubscribe(subscriptionId) {
|
|
291
|
+
var _a;
|
|
292
|
+
const subscriptionState = this.subscriptions.get(subscriptionId);
|
|
293
|
+
if (subscriptionState) {
|
|
294
|
+
(_a = subscriptionState.subjectSubscription) === null || _a === void 0 ? void 0 : _a.unsubscribe();
|
|
295
|
+
// Only send unsubscribe message if websocket is connected and ready to send.
|
|
296
|
+
//// Otherwise, when the websocket DOES connect we don't have to worry about this subscription because we are deleting it from the subscriptions map. (Which only trigger their connections once the websocket becomes connected)
|
|
297
|
+
if (this.customConnectionState === WebSocketConnectionState.CONNECTED &&
|
|
298
|
+
this.webSocket.readyState === isomorphic_ws_1.default.OPEN) {
|
|
299
|
+
this.webSocket.send(subscriptionState.unsubscribeMessage);
|
|
300
|
+
}
|
|
301
|
+
this.subscriptions.delete(subscriptionId);
|
|
302
|
+
// Update URL to subscription IDs lookup
|
|
303
|
+
const subscriptionIds = MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl);
|
|
304
|
+
if (subscriptionIds) {
|
|
305
|
+
subscriptionIds.delete(subscriptionId);
|
|
306
|
+
if (subscriptionIds.size === 0) {
|
|
307
|
+
MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.delete(this.wsUrl);
|
|
308
|
+
// Schedule delayed close when last subscriber unsubscribes
|
|
309
|
+
this.scheduleDelayedClose();
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
scheduleDelayedClose() {
|
|
315
|
+
// Cancel any existing delayed close timeout
|
|
316
|
+
this.cancelDelayedClose();
|
|
317
|
+
// Schedule new delayed close
|
|
318
|
+
this.closeTimeout = setTimeout(() => {
|
|
319
|
+
this.close();
|
|
320
|
+
}, DEFAULT_CONNECTION_CLOSE_DELAY_MS);
|
|
321
|
+
}
|
|
322
|
+
cancelDelayedClose() {
|
|
323
|
+
if (this.closeTimeout) {
|
|
324
|
+
clearTimeout(this.closeTimeout);
|
|
325
|
+
this.closeTimeout = null;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
close() {
|
|
329
|
+
// Cancel any pending delayed close
|
|
330
|
+
this.cancelDelayedClose();
|
|
331
|
+
// Stop heartbeat monitoring (if enabled)
|
|
332
|
+
if (this.heartbeatMonitoringEnabled) {
|
|
333
|
+
this.stopHeartbeatMonitoring();
|
|
334
|
+
}
|
|
335
|
+
for (const [subscriptionId] of this.subscriptions.entries()) {
|
|
336
|
+
this.unsubscribe(subscriptionId);
|
|
337
|
+
}
|
|
338
|
+
this.subscriptions.clear();
|
|
339
|
+
this.webSocket.close();
|
|
340
|
+
MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.delete(this.wsUrl);
|
|
341
|
+
MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.delete(this.wsUrl);
|
|
342
|
+
this.reconnectionManager.reset();
|
|
343
|
+
}
|
|
344
|
+
startHeartbeatMonitoring() {
|
|
345
|
+
// Start the heartbeat timeout - if we don't receive a heartbeat message within the timeout, refresh connection
|
|
346
|
+
this.resetHeartbeatTimeout();
|
|
347
|
+
}
|
|
348
|
+
stopHeartbeatMonitoring() {
|
|
349
|
+
if (this.heartbeatTimeout) {
|
|
350
|
+
clearTimeout(this.heartbeatTimeout);
|
|
351
|
+
this.heartbeatTimeout = null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
resetHeartbeatTimeout() {
|
|
355
|
+
// Clear existing timeout
|
|
356
|
+
if (this.heartbeatTimeout) {
|
|
357
|
+
clearTimeout(this.heartbeatTimeout);
|
|
358
|
+
}
|
|
359
|
+
// Set new timeout
|
|
360
|
+
this.heartbeatTimeout = setTimeout(() => {
|
|
361
|
+
console.warn(`No heartbeat received within ${DEFAULT_HEARTBEAT_TIMEOUT_MS}ms - connection appears dead`);
|
|
362
|
+
this.refreshWebSocket();
|
|
363
|
+
}, DEFAULT_HEARTBEAT_TIMEOUT_MS);
|
|
364
|
+
}
|
|
365
|
+
isHeartbeatMessage(message) {
|
|
366
|
+
// Check if message is a heartbeat message from server
|
|
367
|
+
return (message === null || message === void 0 ? void 0 : message.channel) === 'heartbeat';
|
|
368
|
+
}
|
|
369
|
+
handleHeartbeat(_message) {
|
|
370
|
+
// Reset the heartbeat timeout
|
|
371
|
+
this.resetHeartbeatTimeout();
|
|
372
|
+
}
|
|
373
|
+
refreshWebSocket() {
|
|
374
|
+
// Cancel any pending delayed close since we're refreshing
|
|
375
|
+
this.cancelDelayedClose();
|
|
376
|
+
// Reset heartbeat monitoring during refresh (if enabled) - it will restart when the new connection opens
|
|
377
|
+
if (this.heartbeatMonitoringEnabled) {
|
|
378
|
+
this.stopHeartbeatMonitoring();
|
|
379
|
+
}
|
|
380
|
+
const { shouldReconnect, delay } = this.reconnectionManager.attemptReconnection(this.wsUrl);
|
|
381
|
+
if (!shouldReconnect) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// Clean up current websocket
|
|
385
|
+
const currentWebSocket = this.webSocket;
|
|
386
|
+
if (currentWebSocket) {
|
|
387
|
+
currentWebSocket.onerror = () => { };
|
|
388
|
+
currentWebSocket.onclose = () => { };
|
|
389
|
+
currentWebSocket.onmessage = () => { };
|
|
390
|
+
currentWebSocket.onopen = () => {
|
|
391
|
+
// in the event where the websocket has yet to connect, we close the connection after it is connected
|
|
392
|
+
currentWebSocket.close();
|
|
393
|
+
};
|
|
394
|
+
currentWebSocket.close();
|
|
395
|
+
}
|
|
396
|
+
// Reset subscription states
|
|
397
|
+
this.subscriptions.forEach((subscription) => {
|
|
398
|
+
subscription.hasSentSubscribeMessage = false;
|
|
399
|
+
});
|
|
400
|
+
// Use exponential backoff before attempting to reconnect
|
|
401
|
+
setTimeout(() => {
|
|
402
|
+
this.webSocket = new isomorphic_ws_1.default(this.wsUrl);
|
|
403
|
+
}, delay);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
exports.MultiplexWebSocket = MultiplexWebSocket;
|
|
407
|
+
_MultiplexWebSocket_webSocket = new WeakMap();
|
|
408
|
+
/**
|
|
409
|
+
* A lookup of all websockets by their URL.
|
|
410
|
+
*/
|
|
411
|
+
MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP = new Map();
|
|
412
|
+
/**
|
|
413
|
+
* A lookup from websocket URL to all subscription IDs for that URL.
|
|
414
|
+
*/
|
|
415
|
+
MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP = new Map();
|
|
416
|
+
//# sourceMappingURL=MultiplexWebSocket.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MultiplexWebSocket.js","sourceRoot":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AAO,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;YACpC,gBAAgB,CAAC,SAAS,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;YACtC,gBAAgB,CAAC,MAAM,GAAG,GAAG,EAAE;gBAC9B,qGAAqG;gBACrG,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAC1B,CAAC,CAAC;YACF,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC1B,CAAC;QAED,4BAA4B;QAC5B,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE;YAC3C,YAAY,CAAC,uBAAuB,GAAG,KAAK,CAAC;QAC9C,CAAC,CAAC,CAAC;QAEH,yDAAyD;QACzD,UAAU,CAAC,GAAG,EAAE;YACf,IAAI,CAAC,SAAS,GAAG,IAAI,uBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5C,CAAC,EAAE,KAAK,CAAC,CAAC;IACX,CAAC;;AA7cF,gDA8cC;;AA3cA;;GAEG;AACY,2CAAwB,GAAG,IAAI,GAAG,EAG9C,AAHoC,CAGnC;AAEJ;;GAEG;AACY,iDAA8B,GAAG,IAAI,GAAG,EAGpD,AAH0C,CAGzC","sourcesContent":["import { Subject, catchError, Subscription } from 'rxjs';\nimport WebSocket, { MessageEvent } from 'isomorphic-ws';\n\ntype WebSocketMessage<T = Record<string, unknown>> = T;\n\ntype WebSocketSubscriptionProps<T = Record<string, unknown>> = {\n\twsUrl: string;\n\tsubscriptionId: string;\n\tsubscribeMessage: string;\n\tunsubscribeMessage: string;\n\tonError: (err?: any) => void;\n\tonMessage: (message: WebSocketMessage<T>) => void;\n\tmessageFilter: (message: WebSocketMessage<T>) => boolean;\n\terrorMessageFilter: (message: WebSocketMessage<T>) => boolean;\n\tonClose?: () => void;\n\tenableHeartbeatMonitoring?: boolean;\n};\n\ntype WebSocketSubscriptionState<T = Record<string, unknown>> =\n\tWebSocketSubscriptionProps<T> & {\n\t\thasSentSubscribeMessage?: boolean;\n\t\tsubjectSubscription?: Subscription;\n\t};\n\ntype WebSocketUrl = string;\ntype SubscriptionId = string;\n\nconst DEFAULT_MAX_RECONNECT_ATTEMPTS = 5;\nconst DEFAULT_MAX_RECONNECT_WINDOW_MS = 60 * 1000;\nconst DEFAULT_CONNECTION_CLOSE_DELAY_MS = 2 * 1000; // 2 seconds delay before closing connection\nconst DEFAULT_HEARTBEAT_TIMEOUT_MS = 60 * 1000; // Consider connection dead if no heartbeat within 60 seconds\n\n/**\n * Manages reconnection logic for WebSocket connections with exponential backoff and rate limiting.\n *\n * Features:\n * - Tracks reconnection attempts within a time window\n * - Implements exponential backoff (1s, 2s, 4s, 8s max)\n * - Resets attempt counter after configurable time window\n * - Throws error when max attempts exceeded\n * - Provides configurable limits for attempts and time window\n *\n * @example\n * ```ts\n * const manager = new ReconnectionManager(5, 60000); // 5 attempts in 60s\n * const { shouldReconnect, delay } = manager.attemptReconnection('ws://example.com');\n * if (shouldReconnect) {\n * setTimeout(() => reconnect(), delay);\n * }\n * ```\n */\nclass ReconnectionManager {\n\tprivate reconnectAttempts: number = 0;\n\tprivate lastReconnectWindow: number = Date.now();\n\tprivate maxAttemptsCount: number;\n\tprivate maxAttemptsWindowMs: number;\n\n\tconstructor(\n\t\tmaxAttemptsCount = DEFAULT_MAX_RECONNECT_ATTEMPTS,\n\t\tmaxAttemptsWindowMs = DEFAULT_MAX_RECONNECT_WINDOW_MS\n\t) {\n\t\tthis.maxAttemptsCount = maxAttemptsCount;\n\t\tthis.maxAttemptsWindowMs = maxAttemptsWindowMs;\n\t}\n\n\tpublic attemptReconnection(wsUrl: string): {\n\t\tshouldReconnect: boolean;\n\t\tdelay: number;\n\t} {\n\t\tconst now = Date.now();\n\n\t\t// Reset reconnect attempts if more than a minute has passed\n\t\tif (now - this.lastReconnectWindow > this.maxAttemptsWindowMs) {\n\t\t\tthis.reconnectAttempts = 0;\n\t\t\tthis.lastReconnectWindow = now;\n\t\t}\n\n\t\t// Check if we've exceeded the maximum reconnect attempts\n\t\tif (this.reconnectAttempts >= this.maxAttemptsCount) {\n\t\t\tthrow new Error(\n\t\t\t\t`WebSocket reconnection failed: Maximum reconnect attempts (${this.maxAttemptsCount}) exceeded within ${this.maxAttemptsWindowMs}ms for ${wsUrl}`\n\t\t\t);\n\t\t}\n\n\t\tthis.reconnectAttempts++;\n\n\t\t// Calculate exponential backoff delay: 1s, 2s, 4s, 8s, etc. (capped at 8s)\n\t\tconst backoffDelay = Math.min(\n\t\t\t1000 * Math.pow(2, this.reconnectAttempts - 1),\n\t\t\t8000\n\t\t);\n\n\t\treturn {\n\t\t\tshouldReconnect: true,\n\t\t\tdelay: backoffDelay,\n\t\t};\n\t}\n\n\tpublic reset(): void {\n\t\tthis.reconnectAttempts = 0;\n\t\tthis.lastReconnectWindow = Date.now();\n\t}\n}\n\nenum WebSocketConnectionState {\n\tCONNECTING,\n\tCONNECTED,\n\tDISCONNECTING,\n\tDISCONNECTED,\n}\n\ntype IMultiplexWebSocket<T = Record<string, unknown>> = {\n\twsUrl: WebSocketUrl;\n\twebSocket: WebSocket;\n\tcustomConnectionState: WebSocketConnectionState;\n\tsubject: Subject<WebSocketMessage<T>>;\n\tsubscriptions: Map<\n\t\tSubscriptionId,\n\t\tOmit<WebSocketSubscriptionProps<T>, 'wsUrl' | 'subscriptionId'>\n\t>;\n};\n\n/**\n * MultiplexWebSocket allows for multiple subscriptions to a single websocket of the same URL, improving efficiency and reducing the number of open connections.\n *\n * This implementation assumes the following:\n * - All websocket streams are treated equally - reconnection attempts are performed at the same standards\n * - All messages returned are in the `WebSocketMessage` format\n * - A single instance of the websocket manager is created for each websocket URL - this means all subscriptions to the same websocket URL will share the same websocket instance\n *\n * Internal implementation details:\n * - The websocket is closed when the number of subscriptions is 0\n * - The websocket will be refreshed (new instance) when it disconnects unexpectedly or errors, until it reaches the maximum number of reconnect attempts\n */\nexport class MultiplexWebSocket<T = Record<string, unknown>>\n\timplements IMultiplexWebSocket<T>\n{\n\t/**\n\t * A lookup of all websockets by their URL.\n\t */\n\tprivate static URL_TO_WEBSOCKETS_LOOKUP = new Map<\n\t\tWebSocketUrl,\n\t\tMultiplexWebSocket<any>\n\t>();\n\n\t/**\n\t * A lookup from websocket URL to all subscription IDs for that URL.\n\t */\n\tprivate static URL_TO_SUBSCRIPTION_IDS_LOOKUP = new Map<\n\t\tWebSocketUrl,\n\t\tSet<SubscriptionId>\n\t>();\n\n\twsUrl: WebSocketUrl;\n\t#webSocket: WebSocket;\n\tcustomConnectionState: WebSocketConnectionState;\n\tsubject: Subject<WebSocketMessage<T>>;\n\tsubscriptions: Map<\n\t\tSubscriptionId,\n\t\tOmit<WebSocketSubscriptionState<T>, 'wsUrl' | 'subscriptionId'>\n\t>;\n\tprivate reconnectionManager: ReconnectionManager;\n\tprivate closeTimeout: NodeJS.Timeout | null = null;\n\tprivate heartbeatTimeout: NodeJS.Timeout | null = null;\n\tprivate heartbeatMonitoringEnabled: boolean = false;\n\n\tprivate constructor(\n\t\twsUrl: WebSocketUrl,\n\t\tenableHeartbeatMonitoring: boolean = false\n\t) {\n\t\tif (MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Attempting to create a new websocket for ${wsUrl}, but it already exists`\n\t\t\t);\n\t\t}\n\n\t\tthis.wsUrl = wsUrl;\n\t\tthis.customConnectionState = WebSocketConnectionState.CONNECTING;\n\t\tthis.subject = new Subject<WebSocketMessage<T>>();\n\t\tthis.subscriptions = new Map<\n\t\t\tSubscriptionId,\n\t\t\tOmit<WebSocketSubscriptionProps<T>, 'wsUrl' | 'subscriptionId'>\n\t\t>();\n\n\t\tthis.reconnectionManager = new ReconnectionManager();\n\t\tthis.heartbeatMonitoringEnabled = enableHeartbeatMonitoring;\n\n\t\tthis.webSocket = new WebSocket(wsUrl);\n\n\t\tMultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.set(wsUrl, this);\n\t}\n\n\t/**\n\t * Creates a new virtual websocket subscription. If an existing websocket for the given URL exists, the subscription will be added to the existing websocket.\n\t * Returns a function that can be called to unsubscribe from the subscription.\n\t */\n\tpublic static createWebSocketSubscription<T = Record<string, unknown>>(\n\t\tprops: WebSocketSubscriptionProps<T>\n\t): { unsubscribe: () => void } {\n\t\tconst { wsUrl } = props;\n\n\t\tconst doesWebSocketForWsUrlExist =\n\t\t\tMultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl);\n\n\t\tif (doesWebSocketForWsUrlExist) {\n\t\t\treturn this.handleNewSubForExistingWsUrl<T>(props);\n\t\t} else {\n\t\t\t// Create new websocket for new URL or reopen previously closed websocket\n\t\t\treturn this.handleNewSubForNewWsUrl<T>(props);\n\t\t}\n\t}\n\n\tprivate static handleNewSubForNewWsUrl<T = Record<string, unknown>>(\n\t\tnewSubscriptionProps: WebSocketSubscriptionProps<T>\n\t) {\n\t\tconst newMWS = new MultiplexWebSocket<T>(\n\t\t\tnewSubscriptionProps.wsUrl,\n\t\t\tnewSubscriptionProps.enableHeartbeatMonitoring ?? false\n\t\t);\n\n\t\tnewMWS.subscribe(newSubscriptionProps);\n\n\t\treturn {\n\t\t\tunsubscribe: () => {\n\t\t\t\tnewMWS.unsubscribe(newSubscriptionProps.subscriptionId);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate static handleNewSubForExistingWsUrl<T = Record<string, unknown>>(\n\t\tnewSubscriptionProps: WebSocketSubscriptionProps<T>\n\t) {\n\t\tconst { wsUrl, subscriptionId } = newSubscriptionProps;\n\n\t\tif (!MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.has(wsUrl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Attempting to subscribe to ${subscriptionId} on websocket ${wsUrl}, but websocket does not exist yet`\n\t\t\t);\n\t\t}\n\n\t\tconst existingMWS = MultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.get(\n\t\t\twsUrl\n\t\t) as MultiplexWebSocket<T>;\n\n\t\t// Check if heartbeat monitoring settings match\n\t\tconst requestedHeartbeat =\n\t\t\tnewSubscriptionProps.enableHeartbeatMonitoring ?? false;\n\t\tif (existingMWS.heartbeatMonitoringEnabled !== requestedHeartbeat) {\n\t\t\tconsole.warn(\n\t\t\t\t`WebSocket for ${wsUrl} already exists with heartbeat monitoring ${\n\t\t\t\t\texistingMWS.heartbeatMonitoringEnabled ? 'enabled' : 'disabled'\n\t\t\t\t}, ` +\n\t\t\t\t\t`but new subscription requests ${\n\t\t\t\t\t\trequestedHeartbeat ? 'enabled' : 'disabled'\n\t\t\t\t\t}. Using existing setting.`\n\t\t\t);\n\t\t}\n\n\t\t// Track new subscription for existing websocket\n\t\texistingMWS.subscribe(newSubscriptionProps);\n\n\t\treturn {\n\t\t\tunsubscribe: () => {\n\t\t\t\texistingMWS.unsubscribe(newSubscriptionProps.subscriptionId);\n\t\t\t},\n\t\t};\n\t}\n\n\tget webSocket() {\n\t\treturn this.#webSocket;\n\t}\n\n\t/**\n\t * Setting the WebSocket instance will automatically add event handlers to the WebSocket instance.\n\t * When the WebSocket is connected, all existing subscriptions will be subscribed to.\n\t */\n\tset webSocket(webSocket: WebSocket) {\n\t\twebSocket.onopen = () => {\n\t\t\tthis.customConnectionState = WebSocketConnectionState.CONNECTED;\n\t\t\tthis.reconnectionManager.reset(); // Reset reconnection attempts on successful connection\n\n\t\t\t// Start heartbeat monitoring if enabled\n\t\t\tif (this.heartbeatMonitoringEnabled) {\n\t\t\t\tthis.startHeartbeatMonitoring();\n\t\t\t}\n\n\t\t\t// sends subscription message for each subscription for those that are added before the websocket is connected\n\t\t\tfor (const [subscriptionId] of this.subscriptions.entries()) {\n\t\t\t\tthis.subscribeToWebSocket(subscriptionId);\n\t\t\t}\n\t\t};\n\n\t\twebSocket.onmessage = (messageEvent: MessageEvent) => {\n\t\t\tconst message = JSON.parse(\n\t\t\t\tmessageEvent.data as string\n\t\t\t) as WebSocketMessage<T>;\n\n\t\t\t// Check for heartbeat message from server (only if heartbeat monitoring is enabled)\n\t\t\tif (this.heartbeatMonitoringEnabled && this.isHeartbeatMessage(message)) {\n\t\t\t\tthis.handleHeartbeat(message);\n\t\t\t\treturn; // Don't forward heartbeat messages to subscriptions\n\t\t\t}\n\n\t\t\tthis.subject.next(message);\n\t\t};\n\n\t\twebSocket.onclose = (event) => {\n\t\t\tthis.customConnectionState = WebSocketConnectionState.DISCONNECTED;\n\n\t\t\t// Stop heartbeat monitoring when connection closes (if enabled)\n\t\t\tif (this.heartbeatMonitoringEnabled) {\n\t\t\t\tthis.stopHeartbeatMonitoring();\n\t\t\t}\n\n\t\t\t// Restart websocket if it was closed unexpectedly (not by us)\n\t\t\tif (!event.wasClean && this.subscriptions.size > 0) {\n\t\t\t\tconsole.log('WebSocket closed unexpectedly, restarting...', event);\n\t\t\t\tthis.refreshWebSocket();\n\t\t\t}\n\t\t};\n\n\t\twebSocket.onerror = (error) => {\n\t\t\tconsole.error('MultiplexWebSocket Error', { error, webSocket });\n\n\t\t\t// Forward error to all subscriptions for this websocket URL\n\t\t\tconst subscriptionIds =\n\t\t\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl);\n\t\t\tif (subscriptionIds) {\n\t\t\t\tfor (const subscriptionId of subscriptionIds) {\n\t\t\t\t\tconst subscription = this.subscriptions.get(subscriptionId);\n\t\t\t\t\tif (subscription) {\n\t\t\t\t\t\tsubscription.onError(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Restart the websocket connection on error\n\t\t\tthis.refreshWebSocket();\n\t\t};\n\n\t\tthis.#webSocket = webSocket;\n\t}\n\n\tprivate subscribeToWebSocket(subscriptionId: SubscriptionId) {\n\t\tconst subscriptionState = this.subscriptions.get(subscriptionId);\n\n\t\tconst {\n\t\t\tsubscribeMessage,\n\t\t\tonError,\n\t\t\tonMessage,\n\t\t\tmessageFilter,\n\t\t\terrorMessageFilter,\n\t\t\tonClose,\n\t\t} = subscriptionState;\n\n\t\tthis.webSocket.send(subscribeMessage);\n\t\tif (subscriptionState) {\n\t\t\tsubscriptionState.hasSentSubscribeMessage = true;\n\t\t}\n\n\t\tconst subjectSubscription = this.subject\n\t\t\t.pipe(\n\t\t\t\tcatchError((err) => {\n\t\t\t\t\tconsole.error('Caught websocket error', err);\n\t\t\t\t\tonError();\n\t\t\t\t\treturn [];\n\t\t\t\t})\n\t\t\t)\n\t\t\t.subscribe({\n\t\t\t\tnext: (message: WebSocketMessage<T>) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!messageFilter(message)) return;\n\n\t\t\t\t\t\tif (errorMessageFilter(message)) {\n\t\t\t\t\t\t\tonError();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tonMessage(message);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconsole.error('Error parsing websocket message', err);\n\t\t\t\t\t\tonError();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror: (err) => {\n\t\t\t\t\tconsole.error('Error subscribing to websocket', err);\n\t\t\t\t\tonError();\n\t\t\t\t},\n\t\t\t\tcomplete: () => {\n\t\t\t\t\tif (onClose) {\n\t\t\t\t\t\tonClose();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\n\t\tsubscriptionState.subjectSubscription = subjectSubscription;\n\t}\n\n\tprivate subscribe(props: WebSocketSubscriptionProps<T>) {\n\t\tconst {\n\t\t\tsubscriptionId,\n\t\t\tsubscribeMessage,\n\t\t\tunsubscribeMessage,\n\t\t\tonError,\n\t\t\tonMessage,\n\t\t\tmessageFilter,\n\t\t\terrorMessageFilter,\n\t\t\tonClose,\n\t\t} = props;\n\n\t\tif (this.subscriptions.get(subscriptionId)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Attempting to subscribe to ${subscriptionId} on websocket ${this.wsUrl}, but subscription already exists`\n\t\t\t);\n\t\t}\n\n\t\t// Cancel any pending delayed close since we're adding a new subscription\n\t\tthis.cancelDelayedClose();\n\n\t\tthis.subscriptions.set(subscriptionId, {\n\t\t\tsubscribeMessage,\n\t\t\tunsubscribeMessage,\n\t\t\tonError,\n\t\t\tonMessage,\n\t\t\tmessageFilter,\n\t\t\terrorMessageFilter,\n\t\t\tonClose,\n\t\t\thasSentSubscribeMessage: false,\n\t\t});\n\n\t\t// Update URL to subscription IDs lookup\n\t\tif (!MultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.has(this.wsUrl)) {\n\t\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.set(\n\t\t\t\tthis.wsUrl,\n\t\t\t\tnew Set()\n\t\t\t);\n\t\t}\n\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl)!.add(\n\t\t\tsubscriptionId\n\t\t);\n\n\t\tif (this.customConnectionState === WebSocketConnectionState.CONNECTED) {\n\t\t\tthis.subscribeToWebSocket(subscriptionId);\n\t\t} else if (\n\t\t\tthis.customConnectionState === WebSocketConnectionState.CONNECTING\n\t\t) {\n\t\t\t// do nothing, subscription will automatically start when websocket is connected\n\t\t} else {\n\t\t\t// handle case where websocket is disconnecting/disconnected\n\t\t\tthis.refreshWebSocket();\n\t\t}\n\t}\n\n\tprivate unsubscribe(subscriptionId: SubscriptionId) {\n\t\tconst subscriptionState = this.subscriptions.get(subscriptionId);\n\t\tif (subscriptionState) {\n\t\t\tsubscriptionState.subjectSubscription?.unsubscribe();\n\n\t\t\t// Only send unsubscribe message if websocket is connected and ready to send.\n\t\t\t//// Otherwise, when the websocket DOES connect we don't have to worry about this subscription because we are deleting it from the subscriptions map. (Which only trigger their connections once the websocket becomes connected)\n\t\t\tif (\n\t\t\t\tthis.customConnectionState === WebSocketConnectionState.CONNECTED &&\n\t\t\t\tthis.webSocket.readyState === WebSocket.OPEN\n\t\t\t) {\n\t\t\t\tthis.webSocket.send(subscriptionState.unsubscribeMessage);\n\t\t\t}\n\n\t\t\tthis.subscriptions.delete(subscriptionId);\n\n\t\t\t// Update URL to subscription IDs lookup\n\t\t\tconst subscriptionIds =\n\t\t\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.get(this.wsUrl);\n\t\t\tif (subscriptionIds) {\n\t\t\t\tsubscriptionIds.delete(subscriptionId);\n\t\t\t\tif (subscriptionIds.size === 0) {\n\t\t\t\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.delete(this.wsUrl);\n\t\t\t\t\t// Schedule delayed close when last subscriber unsubscribes\n\t\t\t\t\tthis.scheduleDelayedClose();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate scheduleDelayedClose() {\n\t\t// Cancel any existing delayed close timeout\n\t\tthis.cancelDelayedClose();\n\n\t\t// Schedule new delayed close\n\t\tthis.closeTimeout = setTimeout(() => {\n\t\t\tthis.close();\n\t\t}, DEFAULT_CONNECTION_CLOSE_DELAY_MS);\n\t}\n\n\tprivate cancelDelayedClose() {\n\t\tif (this.closeTimeout) {\n\t\t\tclearTimeout(this.closeTimeout);\n\t\t\tthis.closeTimeout = null;\n\t\t}\n\t}\n\n\tprivate close() {\n\t\t// Cancel any pending delayed close\n\t\tthis.cancelDelayedClose();\n\n\t\t// Stop heartbeat monitoring (if enabled)\n\t\tif (this.heartbeatMonitoringEnabled) {\n\t\t\tthis.stopHeartbeatMonitoring();\n\t\t}\n\n\t\tfor (const [subscriptionId] of this.subscriptions.entries()) {\n\t\t\tthis.unsubscribe(subscriptionId);\n\t\t}\n\n\t\tthis.subscriptions.clear();\n\t\tthis.webSocket.close();\n\t\tMultiplexWebSocket.URL_TO_WEBSOCKETS_LOOKUP.delete(this.wsUrl);\n\t\tMultiplexWebSocket.URL_TO_SUBSCRIPTION_IDS_LOOKUP.delete(this.wsUrl);\n\t\tthis.reconnectionManager.reset();\n\t}\n\n\tprivate startHeartbeatMonitoring() {\n\t\t// Start the heartbeat timeout - if we don't receive a heartbeat message within the timeout, refresh connection\n\t\tthis.resetHeartbeatTimeout();\n\t}\n\n\tprivate stopHeartbeatMonitoring() {\n\t\tif (this.heartbeatTimeout) {\n\t\t\tclearTimeout(this.heartbeatTimeout);\n\t\t\tthis.heartbeatTimeout = null;\n\t\t}\n\t}\n\n\tprivate resetHeartbeatTimeout() {\n\t\t// Clear existing timeout\n\t\tif (this.heartbeatTimeout) {\n\t\t\tclearTimeout(this.heartbeatTimeout);\n\t\t}\n\n\t\t// Set new timeout\n\t\tthis.heartbeatTimeout = setTimeout(() => {\n\t\t\tconsole.warn(\n\t\t\t\t`No heartbeat received within ${DEFAULT_HEARTBEAT_TIMEOUT_MS}ms - connection appears dead`\n\t\t\t);\n\t\t\tthis.refreshWebSocket();\n\t\t}, DEFAULT_HEARTBEAT_TIMEOUT_MS);\n\t}\n\n\tprivate isHeartbeatMessage(message: WebSocketMessage<T>): boolean {\n\t\t// Check if message is a heartbeat message from server\n\t\treturn (message as any)?.channel === 'heartbeat';\n\t}\n\n\tprivate handleHeartbeat(_message: WebSocketMessage<T>) {\n\t\t// Reset the heartbeat timeout\n\t\tthis.resetHeartbeatTimeout();\n\t}\n\n\tprivate refreshWebSocket() {\n\t\t// Cancel any pending delayed close since we're refreshing\n\t\tthis.cancelDelayedClose();\n\n\t\t// Reset heartbeat monitoring during refresh (if enabled) - it will restart when the new connection opens\n\t\tif (this.heartbeatMonitoringEnabled) {\n\t\t\tthis.stopHeartbeatMonitoring();\n\t\t}\n\n\t\tconst { shouldReconnect, delay } =\n\t\t\tthis.reconnectionManager.attemptReconnection(this.wsUrl);\n\n\t\tif (!shouldReconnect) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Clean up current websocket\n\t\tconst currentWebSocket = this.webSocket;\n\t\tif (currentWebSocket) {\n\t\t\tcurrentWebSocket.onerror = () => {};\n\t\t\tcurrentWebSocket.onclose = () => {};\n\t\t\tcurrentWebSocket.onmessage = () => {};\n\t\t\tcurrentWebSocket.onopen = () => {\n\t\t\t\t// in the event where the websocket has yet to connect, we close the connection after it is connected\n\t\t\t\tcurrentWebSocket.close();\n\t\t\t};\n\t\t\tcurrentWebSocket.close();\n\t\t}\n\n\t\t// Reset subscription states\n\t\tthis.subscriptions.forEach((subscription) => {\n\t\t\tsubscription.hasSentSubscribeMessage = false;\n\t\t});\n\n\t\t// Use exponential backoff before attempting to reconnect\n\t\tsetTimeout(() => {\n\t\t\tthis.webSocket = new WebSocket(this.wsUrl);\n\t\t}, delay);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { BN, BigNum } from '@drift-labs/sdk';
|
|
2
|
+
/**
|
|
3
|
+
* Utilities to convert numbers and BigNumbers (BN) to different formats for the UI.
|
|
4
|
+
*/
|
|
5
|
+
export declare class NumLib {
|
|
6
|
+
private static locale;
|
|
7
|
+
static setLocale: (locale: string) => void;
|
|
8
|
+
/**
|
|
9
|
+
* Converts a Big Number to its regular number representation.
|
|
10
|
+
*
|
|
11
|
+
* This won't work when the precision, or bn/precision is larger than MAX_SAFE_INTEGER .. This shouldn't happen though unless using extremely large numbers
|
|
12
|
+
* */
|
|
13
|
+
private static toRawNum;
|
|
14
|
+
static formatNum: {
|
|
15
|
+
/**
|
|
16
|
+
* Converts a number to a precision suitable to trade with
|
|
17
|
+
* @param num
|
|
18
|
+
* @returns
|
|
19
|
+
*/
|
|
20
|
+
toTradePrecision: (num: number) => number;
|
|
21
|
+
toTradePrecisionString: (num: number, toLocaleString?: boolean) => string;
|
|
22
|
+
/**
|
|
23
|
+
* Formats a notional dollar value for UI. Goes to max. 2 decimals (accurate to 1 cent)
|
|
24
|
+
* @param num
|
|
25
|
+
* @returns
|
|
26
|
+
*/
|
|
27
|
+
toNotionalDisplay: (num: number) => string;
|
|
28
|
+
/**
|
|
29
|
+
* Formats a notional dollar value. Goes to max. 2 decimals (accurate to 1 cent)
|
|
30
|
+
* @param num
|
|
31
|
+
* @returns
|
|
32
|
+
*/
|
|
33
|
+
toNotionalNum: (num: number) => number;
|
|
34
|
+
/**
|
|
35
|
+
* This function prints the base amount of an asset with a number of decimals relative to the price of the asset, because for high priced assets we care about more accuracy in the base amount. Number of decimals corresponds to accuracy to ~ 1 cent
|
|
36
|
+
* @param baseAmount
|
|
37
|
+
* @param assetPrice in dollars
|
|
38
|
+
* @param skipLocaleFormatting Format using toFixed rather than localeString, which can't be parsed with regular number parsing
|
|
39
|
+
* @returns
|
|
40
|
+
*/
|
|
41
|
+
toBaseDisplay: (baseAmount: number, _assetPrice?: number, _skipLocaleFormatting?: boolean, customSigFigs?: number) => string;
|
|
42
|
+
/**
|
|
43
|
+
* This function prints the base amount of an asset with a number of decimals relative to the price of the asset, because for high priced assets we care about more accuracy in the base amount. Number of decimals corresponds to accuracy to ~ 1 cent
|
|
44
|
+
* @param baseAmount
|
|
45
|
+
* @param assetPrice in dollars
|
|
46
|
+
* @param skipLocaleFormatting Format using toFixed rather than localeString, which can't be parsed with regular number parsing
|
|
47
|
+
* @returns
|
|
48
|
+
*/
|
|
49
|
+
toBase: (baseAmount: number, assetPrice?: number) => number;
|
|
50
|
+
toBaseBN: (baseAmount: number) => BN;
|
|
51
|
+
toQuoteBN: (quoteAmount: number) => BN;
|
|
52
|
+
/**
|
|
53
|
+
* Formats to price in locale style
|
|
54
|
+
* @param assetPrice
|
|
55
|
+
* @returns
|
|
56
|
+
*/
|
|
57
|
+
toDisplayPrice: (assetPrice: number) => string;
|
|
58
|
+
/**
|
|
59
|
+
* Formats a price
|
|
60
|
+
* @param assetPrice
|
|
61
|
+
* @returns
|
|
62
|
+
*/
|
|
63
|
+
toPrice: (assetPrice: number) => number;
|
|
64
|
+
/**
|
|
65
|
+
* Convert a number to a BN based on the required precision
|
|
66
|
+
* @param num
|
|
67
|
+
* @param precision
|
|
68
|
+
* @returns
|
|
69
|
+
*/
|
|
70
|
+
toRawBn: (num: number, precision: BN) => BN;
|
|
71
|
+
/**
|
|
72
|
+
* Truncates a number to a certain number of decimal places. This differs from .toFixed() in that it rounds down, whereas .toFixed() rounds to the nearest number.
|
|
73
|
+
* @param num
|
|
74
|
+
* @param decimalPlaces
|
|
75
|
+
* @returns
|
|
76
|
+
*/
|
|
77
|
+
toDecimalPlaces: (num: number, decimalPlaces: number, noPadding?: boolean) => string;
|
|
78
|
+
};
|
|
79
|
+
static formatBn: {
|
|
80
|
+
toRawNum: (bn: BN, precision: BN, fixedAccuracity?: number) => number;
|
|
81
|
+
fromQuote: (bn: BN) => number;
|
|
82
|
+
fromBase: (bn: BN) => number;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Outputs information and formatted string for UI based on its log10 value
|
|
86
|
+
* @param value
|
|
87
|
+
* @returns
|
|
88
|
+
*/
|
|
89
|
+
static millify: (value: number) => {
|
|
90
|
+
mantissa: number;
|
|
91
|
+
symbol: string;
|
|
92
|
+
sigFigs: number;
|
|
93
|
+
displayValue: number;
|
|
94
|
+
displayString: string;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Get the precision to use for an asset so that base asset amounts are on the same scale as USD cents
|
|
98
|
+
* @param assetPrice
|
|
99
|
+
* @returns
|
|
100
|
+
*/
|
|
101
|
+
static getDisplayPrecision: (assetPrice: BigNum) => number;
|
|
102
|
+
static bp: (num: number) => number;
|
|
103
|
+
static isInvalid: (num: number) => boolean;
|
|
104
|
+
static sumBigNums: (nums: BigNum[], precision: BN) => BigNum;
|
|
105
|
+
static averageBigNums: (nums: BigNum[], precision: BN) => BigNum;
|
|
106
|
+
}
|