@metamask-previews/perps-controller 0.0.0-preview-e4aa1532 → 0.0.0-preview-6dfa4aeba
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/CHANGELOG.md +1 -11
- package/dist/PerpsController.cjs +66 -2224
- package/dist/PerpsController.cjs.map +1 -1
- package/dist/PerpsController.d.cts +79 -933
- package/dist/PerpsController.d.cts.map +1 -1
- package/dist/PerpsController.d.mts +79 -933
- package/dist/PerpsController.d.mts.map +1 -1
- package/dist/PerpsController.mjs +64 -2221
- package/dist/PerpsController.mjs.map +1 -1
- package/dist/index.cjs +1 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -9
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -19
- package/dist/__mocks__/hyperliquidMock.cjs +0 -68
- package/dist/__mocks__/hyperliquidMock.cjs.map +0 -1
- package/dist/__mocks__/hyperliquidMock.d.cts +0 -15
- package/dist/__mocks__/hyperliquidMock.d.cts.map +0 -1
- package/dist/__mocks__/hyperliquidMock.d.mts +0 -15
- package/dist/__mocks__/hyperliquidMock.d.mts.map +0 -1
- package/dist/__mocks__/hyperliquidMock.mjs +0 -65
- package/dist/__mocks__/hyperliquidMock.mjs.map +0 -1
- package/dist/__mocks__/providerMocks.cjs +0 -144
- package/dist/__mocks__/providerMocks.cjs.map +0 -1
- package/dist/__mocks__/providerMocks.d.cts +0 -44
- package/dist/__mocks__/providerMocks.d.cts.map +0 -1
- package/dist/__mocks__/providerMocks.d.mts +0 -44
- package/dist/__mocks__/providerMocks.d.mts.map +0 -1
- package/dist/__mocks__/providerMocks.mjs +0 -136
- package/dist/__mocks__/providerMocks.mjs.map +0 -1
- package/dist/__mocks__/serviceMocks.cjs +0 -187
- package/dist/__mocks__/serviceMocks.cjs.map +0 -1
- package/dist/__mocks__/serviceMocks.d.cts +0 -58
- package/dist/__mocks__/serviceMocks.d.cts.map +0 -1
- package/dist/__mocks__/serviceMocks.d.mts +0 -58
- package/dist/__mocks__/serviceMocks.d.mts.map +0 -1
- package/dist/__mocks__/serviceMocks.mjs +0 -180
- package/dist/__mocks__/serviceMocks.mjs.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.cjs +0 -459
- package/dist/aggregation/SubscriptionMultiplexer.cjs.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.cts +0 -222
- package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.mts +0 -222
- package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +0 -1
- package/dist/aggregation/SubscriptionMultiplexer.mjs +0 -455
- package/dist/aggregation/SubscriptionMultiplexer.mjs.map +0 -1
- package/dist/aggregation/index.cjs +0 -9
- package/dist/aggregation/index.cjs.map +0 -1
- package/dist/aggregation/index.d.cts +0 -6
- package/dist/aggregation/index.d.cts.map +0 -1
- package/dist/aggregation/index.d.mts +0 -6
- package/dist/aggregation/index.d.mts.map +0 -1
- package/dist/aggregation/index.mjs +0 -5
- package/dist/aggregation/index.mjs.map +0 -1
- package/dist/constants/eventNames.cjs +0 -117
- package/dist/constants/eventNames.cjs.map +0 -1
- package/dist/constants/eventNames.d.cts +0 -106
- package/dist/constants/eventNames.d.cts.map +0 -1
- package/dist/constants/eventNames.d.mts +0 -106
- package/dist/constants/eventNames.d.mts.map +0 -1
- package/dist/constants/eventNames.mjs +0 -114
- package/dist/constants/eventNames.mjs.map +0 -1
- package/dist/constants/hyperLiquidConfig.cjs +0 -366
- package/dist/constants/hyperLiquidConfig.cjs.map +0 -1
- package/dist/constants/hyperLiquidConfig.d.cts +0 -276
- package/dist/constants/hyperLiquidConfig.d.cts.map +0 -1
- package/dist/constants/hyperLiquidConfig.d.mts +0 -276
- package/dist/constants/hyperLiquidConfig.d.mts.map +0 -1
- package/dist/constants/hyperLiquidConfig.mjs +0 -357
- package/dist/constants/hyperLiquidConfig.mjs.map +0 -1
- package/dist/constants/index.cjs +0 -23
- package/dist/constants/index.cjs.map +0 -1
- package/dist/constants/index.d.cts +0 -7
- package/dist/constants/index.d.cts.map +0 -1
- package/dist/constants/index.d.mts +0 -7
- package/dist/constants/index.d.mts.map +0 -1
- package/dist/constants/index.mjs +0 -7
- package/dist/constants/index.mjs.map +0 -1
- package/dist/constants/orderTypes.cjs +0 -31
- package/dist/constants/orderTypes.cjs.map +0 -1
- package/dist/constants/orderTypes.d.cts +0 -19
- package/dist/constants/orderTypes.d.cts.map +0 -1
- package/dist/constants/orderTypes.d.mts +0 -19
- package/dist/constants/orderTypes.d.mts.map +0 -1
- package/dist/constants/orderTypes.mjs +0 -27
- package/dist/constants/orderTypes.mjs.map +0 -1
- package/dist/constants/performanceMetrics.cjs +0 -61
- package/dist/constants/performanceMetrics.cjs.map +0 -1
- package/dist/constants/performanceMetrics.d.cts +0 -44
- package/dist/constants/performanceMetrics.d.cts.map +0 -1
- package/dist/constants/performanceMetrics.d.mts +0 -44
- package/dist/constants/performanceMetrics.d.mts.map +0 -1
- package/dist/constants/performanceMetrics.mjs +0 -58
- package/dist/constants/performanceMetrics.mjs.map +0 -1
- package/dist/constants/perpsConfig.cjs +0 -461
- package/dist/constants/perpsConfig.cjs.map +0 -1
- package/dist/constants/perpsConfig.d.cts +0 -343
- package/dist/constants/perpsConfig.d.cts.map +0 -1
- package/dist/constants/perpsConfig.d.mts +0 -343
- package/dist/constants/perpsConfig.d.mts.map +0 -1
- package/dist/constants/perpsConfig.mjs +0 -458
- package/dist/constants/perpsConfig.mjs.map +0 -1
- package/dist/constants/perpsErrorCodes.cjs +0 -79
- package/dist/constants/perpsErrorCodes.cjs.map +0 -1
- package/dist/constants/perpsErrorCodes.d.cts +0 -64
- package/dist/constants/perpsErrorCodes.d.cts.map +0 -1
- package/dist/constants/perpsErrorCodes.d.mts +0 -64
- package/dist/constants/perpsErrorCodes.d.mts.map +0 -1
- package/dist/constants/perpsErrorCodes.mjs +0 -76
- package/dist/constants/perpsErrorCodes.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.cjs +0 -857
- package/dist/platform-services/HyperLiquidClientService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.d.cts +0 -263
- package/dist/platform-services/HyperLiquidClientService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.d.mts +0 -263
- package/dist/platform-services/HyperLiquidClientService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidClientService.mjs +0 -853
- package/dist/platform-services/HyperLiquidClientService.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs +0 -2170
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts +0 -424
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts +0 -424
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs +0 -2166
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.cjs +0 -140
- package/dist/platform-services/HyperLiquidWalletService.cjs.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.d.cts +0 -78
- package/dist/platform-services/HyperLiquidWalletService.d.cts.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.d.mts +0 -78
- package/dist/platform-services/HyperLiquidWalletService.d.mts.map +0 -1
- package/dist/platform-services/HyperLiquidWalletService.mjs +0 -136
- package/dist/platform-services/HyperLiquidWalletService.mjs.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.cjs +0 -777
- package/dist/providers/AggregatedPerpsProvider.cjs.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.d.cts +0 -466
- package/dist/providers/AggregatedPerpsProvider.d.cts.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.d.mts +0 -466
- package/dist/providers/AggregatedPerpsProvider.d.mts.map +0 -1
- package/dist/providers/AggregatedPerpsProvider.mjs +0 -773
- package/dist/providers/AggregatedPerpsProvider.mjs.map +0 -1
- package/dist/providers/HyperLiquidProvider.cjs +0 -5172
- package/dist/providers/HyperLiquidProvider.cjs.map +0 -1
- package/dist/providers/HyperLiquidProvider.d.cts +0 -881
- package/dist/providers/HyperLiquidProvider.d.cts.map +0 -1
- package/dist/providers/HyperLiquidProvider.d.mts +0 -881
- package/dist/providers/HyperLiquidProvider.d.mts.map +0 -1
- package/dist/providers/HyperLiquidProvider.mjs +0 -5168
- package/dist/providers/HyperLiquidProvider.mjs.map +0 -1
- package/dist/providers/index.cjs +0 -11
- package/dist/providers/index.cjs.map +0 -1
- package/dist/providers/index.d.cts +0 -6
- package/dist/providers/index.d.cts.map +0 -1
- package/dist/providers/index.d.mts +0 -6
- package/dist/providers/index.d.mts.map +0 -1
- package/dist/providers/index.mjs +0 -6
- package/dist/providers/index.mjs.map +0 -1
- package/dist/routing/ProviderRouter.cjs +0 -148
- package/dist/routing/ProviderRouter.cjs.map +0 -1
- package/dist/routing/ProviderRouter.d.cts +0 -124
- package/dist/routing/ProviderRouter.d.cts.map +0 -1
- package/dist/routing/ProviderRouter.d.mts +0 -124
- package/dist/routing/ProviderRouter.d.mts.map +0 -1
- package/dist/routing/ProviderRouter.mjs +0 -144
- package/dist/routing/ProviderRouter.mjs.map +0 -1
- package/dist/routing/index.cjs +0 -9
- package/dist/routing/index.cjs.map +0 -1
- package/dist/routing/index.d.cts +0 -6
- package/dist/routing/index.d.cts.map +0 -1
- package/dist/routing/index.d.mts +0 -6
- package/dist/routing/index.d.mts.map +0 -1
- package/dist/routing/index.mjs +0 -5
- package/dist/routing/index.mjs.map +0 -1
- package/dist/selectors.cjs +0 -161
- package/dist/selectors.cjs.map +0 -1
- package/dist/selectors.d.cts +0 -345
- package/dist/selectors.d.cts.map +0 -1
- package/dist/selectors.d.mts +0 -345
- package/dist/selectors.d.mts.map +0 -1
- package/dist/selectors.mjs +0 -153
- package/dist/selectors.mjs.map +0 -1
- package/dist/services/AccountService.cjs +0 -313
- package/dist/services/AccountService.cjs.map +0 -1
- package/dist/services/AccountService.d.cts +0 -53
- package/dist/services/AccountService.d.cts.map +0 -1
- package/dist/services/AccountService.d.mts +0 -53
- package/dist/services/AccountService.d.mts.map +0 -1
- package/dist/services/AccountService.mjs +0 -309
- package/dist/services/AccountService.mjs.map +0 -1
- package/dist/services/DataLakeService.cjs +0 -219
- package/dist/services/DataLakeService.cjs.map +0 -1
- package/dist/services/DataLakeService.d.cts +0 -49
- package/dist/services/DataLakeService.d.cts.map +0 -1
- package/dist/services/DataLakeService.d.mts +0 -49
- package/dist/services/DataLakeService.d.mts.map +0 -1
- package/dist/services/DataLakeService.mjs +0 -215
- package/dist/services/DataLakeService.mjs.map +0 -1
- package/dist/services/DepositService.cjs +0 -96
- package/dist/services/DepositService.cjs.map +0 -1
- package/dist/services/DepositService.d.cts +0 -37
- package/dist/services/DepositService.d.cts.map +0 -1
- package/dist/services/DepositService.d.mts +0 -37
- package/dist/services/DepositService.d.mts.map +0 -1
- package/dist/services/DepositService.mjs +0 -92
- package/dist/services/DepositService.mjs.map +0 -1
- package/dist/services/EligibilityService.cjs +0 -156
- package/dist/services/EligibilityService.cjs.map +0 -1
- package/dist/services/EligibilityService.d.cts +0 -48
- package/dist/services/EligibilityService.d.cts.map +0 -1
- package/dist/services/EligibilityService.d.mts +0 -48
- package/dist/services/EligibilityService.d.mts.map +0 -1
- package/dist/services/EligibilityService.mjs +0 -152
- package/dist/services/EligibilityService.mjs.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.cjs +0 -258
- package/dist/services/FeatureFlagConfigurationService.cjs.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.d.cts +0 -100
- package/dist/services/FeatureFlagConfigurationService.d.cts.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.d.mts +0 -100
- package/dist/services/FeatureFlagConfigurationService.d.mts.map +0 -1
- package/dist/services/FeatureFlagConfigurationService.mjs +0 -254
- package/dist/services/FeatureFlagConfigurationService.mjs.map +0 -1
- package/dist/services/MarketDataService.cjs +0 -875
- package/dist/services/MarketDataService.cjs.map +0 -1
- package/dist/services/MarketDataService.d.cts +0 -289
- package/dist/services/MarketDataService.d.cts.map +0 -1
- package/dist/services/MarketDataService.d.mts +0 -289
- package/dist/services/MarketDataService.d.mts.map +0 -1
- package/dist/services/MarketDataService.mjs +0 -871
- package/dist/services/MarketDataService.mjs.map +0 -1
- package/dist/services/RewardsIntegrationService.cjs +0 -94
- package/dist/services/RewardsIntegrationService.cjs.map +0 -1
- package/dist/services/RewardsIntegrationService.d.cts +0 -30
- package/dist/services/RewardsIntegrationService.d.cts.map +0 -1
- package/dist/services/RewardsIntegrationService.d.mts +0 -30
- package/dist/services/RewardsIntegrationService.d.mts.map +0 -1
- package/dist/services/RewardsIntegrationService.mjs +0 -90
- package/dist/services/RewardsIntegrationService.mjs.map +0 -1
- package/dist/services/ServiceContext.cjs +0 -3
- package/dist/services/ServiceContext.cjs.map +0 -1
- package/dist/services/ServiceContext.d.cts +0 -110
- package/dist/services/ServiceContext.d.cts.map +0 -1
- package/dist/services/ServiceContext.d.mts +0 -110
- package/dist/services/ServiceContext.d.mts.map +0 -1
- package/dist/services/ServiceContext.mjs +0 -2
- package/dist/services/ServiceContext.mjs.map +0 -1
- package/dist/services/TradingService.cjs +0 -1481
- package/dist/services/TradingService.cjs.map +0 -1
- package/dist/services/TradingService.d.cts +0 -308
- package/dist/services/TradingService.d.cts.map +0 -1
- package/dist/services/TradingService.d.mts +0 -308
- package/dist/services/TradingService.d.mts.map +0 -1
- package/dist/services/TradingService.mjs +0 -1477
- package/dist/services/TradingService.mjs.map +0 -1
- package/dist/services/index.cjs +0 -26
- package/dist/services/index.cjs.map +0 -1
- package/dist/services/index.d.cts +0 -11
- package/dist/services/index.d.cts.map +0 -1
- package/dist/services/index.d.mts +0 -11
- package/dist/services/index.d.mts.map +0 -1
- package/dist/services/index.mjs +0 -10
- package/dist/services/index.mjs.map +0 -1
- package/dist/services/utils.cjs +0 -16
- package/dist/services/utils.cjs.map +0 -1
- package/dist/services/utils.d.cts +0 -8
- package/dist/services/utils.d.cts.map +0 -1
- package/dist/services/utils.d.mts +0 -8
- package/dist/services/utils.d.mts.map +0 -1
- package/dist/services/utils.mjs +0 -12
- package/dist/services/utils.mjs.map +0 -1
- package/dist/types/chart.cjs +0 -42
- package/dist/types/chart.cjs.map +0 -1
- package/dist/types/chart.d.cts +0 -62
- package/dist/types/chart.d.cts.map +0 -1
- package/dist/types/chart.d.mts +0 -62
- package/dist/types/chart.d.mts.map +0 -1
- package/dist/types/chart.mjs +0 -39
- package/dist/types/chart.mjs.map +0 -1
- package/dist/types/hyperliquid-types.cjs +0 -3
- package/dist/types/hyperliquid-types.cjs.map +0 -1
- package/dist/types/hyperliquid-types.d.cts +0 -52
- package/dist/types/hyperliquid-types.d.cts.map +0 -1
- package/dist/types/hyperliquid-types.d.mts +0 -52
- package/dist/types/hyperliquid-types.d.mts.map +0 -1
- package/dist/types/hyperliquid-types.mjs +0 -2
- package/dist/types/hyperliquid-types.mjs.map +0 -1
- package/dist/types/index.cjs +0 -96
- package/dist/types/index.cjs.map +0 -1
- package/dist/types/index.d.cts +0 -1153
- package/dist/types/index.d.cts.map +0 -1
- package/dist/types/index.d.mts +0 -1153
- package/dist/types/index.d.mts.map +0 -1
- package/dist/types/index.mjs +0 -79
- package/dist/types/index.mjs.map +0 -1
- package/dist/types/transactionTypes.cjs +0 -28
- package/dist/types/transactionTypes.cjs.map +0 -1
- package/dist/types/transactionTypes.d.cts +0 -64
- package/dist/types/transactionTypes.d.cts.map +0 -1
- package/dist/types/transactionTypes.d.mts +0 -64
- package/dist/types/transactionTypes.d.mts.map +0 -1
- package/dist/types/transactionTypes.mjs +0 -23
- package/dist/types/transactionTypes.mjs.map +0 -1
- package/dist/utils/accountUtils.cjs +0 -65
- package/dist/utils/accountUtils.cjs.map +0 -1
- package/dist/utils/accountUtils.d.cts +0 -26
- package/dist/utils/accountUtils.d.cts.map +0 -1
- package/dist/utils/accountUtils.d.mts +0 -26
- package/dist/utils/accountUtils.d.mts.map +0 -1
- package/dist/utils/accountUtils.mjs +0 -61
- package/dist/utils/accountUtils.mjs.map +0 -1
- package/dist/utils/amountConversion.cjs +0 -61
- package/dist/utils/amountConversion.cjs.map +0 -1
- package/dist/utils/amountConversion.d.cts +0 -16
- package/dist/utils/amountConversion.d.cts.map +0 -1
- package/dist/utils/amountConversion.d.mts +0 -16
- package/dist/utils/amountConversion.d.mts.map +0 -1
- package/dist/utils/amountConversion.mjs +0 -54
- package/dist/utils/amountConversion.mjs.map +0 -1
- package/dist/utils/chartUtils.cjs +0 -98
- package/dist/utils/chartUtils.cjs.map +0 -1
- package/dist/utils/chartUtils.d.cts +0 -14
- package/dist/utils/chartUtils.d.cts.map +0 -1
- package/dist/utils/chartUtils.d.mts +0 -14
- package/dist/utils/chartUtils.d.mts.map +0 -1
- package/dist/utils/chartUtils.mjs +0 -94
- package/dist/utils/chartUtils.mjs.map +0 -1
- package/dist/utils/errorUtils.cjs +0 -22
- package/dist/utils/errorUtils.cjs.map +0 -1
- package/dist/utils/errorUtils.d.cts +0 -13
- package/dist/utils/errorUtils.d.cts.map +0 -1
- package/dist/utils/errorUtils.d.mts +0 -13
- package/dist/utils/errorUtils.d.mts.map +0 -1
- package/dist/utils/errorUtils.mjs +0 -18
- package/dist/utils/errorUtils.mjs.map +0 -1
- package/dist/utils/formatUtils.cjs +0 -987
- package/dist/utils/formatUtils.cjs.map +0 -1
- package/dist/utils/formatUtils.d.cts +0 -387
- package/dist/utils/formatUtils.d.cts.map +0 -1
- package/dist/utils/formatUtils.d.mts +0 -387
- package/dist/utils/formatUtils.d.mts.map +0 -1
- package/dist/utils/formatUtils.mjs +0 -966
- package/dist/utils/formatUtils.mjs.map +0 -1
- package/dist/utils/hyperLiquidAdapter.cjs +0 -454
- package/dist/utils/hyperLiquidAdapter.cjs.map +0 -1
- package/dist/utils/hyperLiquidAdapter.d.cts +0 -158
- package/dist/utils/hyperLiquidAdapter.d.cts.map +0 -1
- package/dist/utils/hyperLiquidAdapter.d.mts +0 -158
- package/dist/utils/hyperLiquidAdapter.d.mts.map +0 -1
- package/dist/utils/hyperLiquidAdapter.mjs +0 -439
- package/dist/utils/hyperLiquidAdapter.mjs.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs +0 -89
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +0 -58
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +0 -58
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +0 -1
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs +0 -84
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +0 -1
- package/dist/utils/hyperLiquidValidation.cjs +0 -426
- package/dist/utils/hyperLiquidValidation.cjs.map +0 -1
- package/dist/utils/hyperLiquidValidation.d.cts +0 -143
- package/dist/utils/hyperLiquidValidation.d.cts.map +0 -1
- package/dist/utils/hyperLiquidValidation.d.mts +0 -143
- package/dist/utils/hyperLiquidValidation.d.mts.map +0 -1
- package/dist/utils/hyperLiquidValidation.mjs +0 -413
- package/dist/utils/hyperLiquidValidation.mjs.map +0 -1
- package/dist/utils/idUtils.cjs +0 -50
- package/dist/utils/idUtils.cjs.map +0 -1
- package/dist/utils/idUtils.d.cts +0 -38
- package/dist/utils/idUtils.d.cts.map +0 -1
- package/dist/utils/idUtils.d.mts +0 -38
- package/dist/utils/idUtils.d.mts.map +0 -1
- package/dist/utils/idUtils.mjs +0 -42
- package/dist/utils/idUtils.mjs.map +0 -1
- package/dist/utils/marginUtils.cjs +0 -137
- package/dist/utils/marginUtils.cjs.map +0 -1
- package/dist/utils/marginUtils.d.cts +0 -64
- package/dist/utils/marginUtils.d.cts.map +0 -1
- package/dist/utils/marginUtils.d.mts +0 -64
- package/dist/utils/marginUtils.d.mts.map +0 -1
- package/dist/utils/marginUtils.mjs +0 -131
- package/dist/utils/marginUtils.mjs.map +0 -1
- package/dist/utils/marketDataTransform.cjs +0 -227
- package/dist/utils/marketDataTransform.cjs.map +0 -1
- package/dist/utils/marketDataTransform.d.cts +0 -45
- package/dist/utils/marketDataTransform.d.cts.map +0 -1
- package/dist/utils/marketDataTransform.d.mts +0 -45
- package/dist/utils/marketDataTransform.d.mts.map +0 -1
- package/dist/utils/marketDataTransform.mjs +0 -220
- package/dist/utils/marketDataTransform.mjs.map +0 -1
- package/dist/utils/marketUtils.cjs +0 -420
- package/dist/utils/marketUtils.cjs.map +0 -1
- package/dist/utils/marketUtils.d.cts +0 -227
- package/dist/utils/marketUtils.d.cts.map +0 -1
- package/dist/utils/marketUtils.d.mts +0 -227
- package/dist/utils/marketUtils.d.mts.map +0 -1
- package/dist/utils/marketUtils.mjs +0 -404
- package/dist/utils/marketUtils.mjs.map +0 -1
- package/dist/utils/orderBookGrouping.cjs +0 -151
- package/dist/utils/orderBookGrouping.cjs.map +0 -1
- package/dist/utils/orderBookGrouping.d.cts +0 -76
- package/dist/utils/orderBookGrouping.d.cts.map +0 -1
- package/dist/utils/orderBookGrouping.d.mts +0 -76
- package/dist/utils/orderBookGrouping.d.mts.map +0 -1
- package/dist/utils/orderBookGrouping.mjs +0 -143
- package/dist/utils/orderBookGrouping.mjs.map +0 -1
- package/dist/utils/orderCalculations.cjs +0 -283
- package/dist/utils/orderCalculations.cjs.map +0 -1
- package/dist/utils/orderCalculations.d.cts +0 -107
- package/dist/utils/orderCalculations.d.cts.map +0 -1
- package/dist/utils/orderCalculations.d.mts +0 -107
- package/dist/utils/orderCalculations.d.mts.map +0 -1
- package/dist/utils/orderCalculations.mjs +0 -274
- package/dist/utils/orderCalculations.mjs.map +0 -1
- package/dist/utils/orderUtils.cjs +0 -159
- package/dist/utils/orderUtils.cjs.map +0 -1
- package/dist/utils/orderUtils.d.cts +0 -66
- package/dist/utils/orderUtils.d.cts.map +0 -1
- package/dist/utils/orderUtils.d.mts +0 -66
- package/dist/utils/orderUtils.d.mts.map +0 -1
- package/dist/utils/orderUtils.mjs +0 -151
- package/dist/utils/orderUtils.mjs.map +0 -1
- package/dist/utils/pnlCalculations.cjs +0 -107
- package/dist/utils/pnlCalculations.cjs.map +0 -1
- package/dist/utils/pnlCalculations.d.cts +0 -79
- package/dist/utils/pnlCalculations.d.cts.map +0 -1
- package/dist/utils/pnlCalculations.d.mts +0 -79
- package/dist/utils/pnlCalculations.d.mts.map +0 -1
- package/dist/utils/pnlCalculations.mjs +0 -97
- package/dist/utils/pnlCalculations.mjs.map +0 -1
- package/dist/utils/positionCalculations.cjs +0 -176
- package/dist/utils/positionCalculations.cjs.map +0 -1
- package/dist/utils/positionCalculations.d.cts +0 -85
- package/dist/utils/positionCalculations.d.cts.map +0 -1
- package/dist/utils/positionCalculations.d.mts +0 -85
- package/dist/utils/positionCalculations.d.mts.map +0 -1
- package/dist/utils/positionCalculations.mjs +0 -165
- package/dist/utils/positionCalculations.mjs.map +0 -1
- package/dist/utils/sortMarkets.cjs +0 -88
- package/dist/utils/sortMarkets.cjs.map +0 -1
- package/dist/utils/sortMarkets.d.cts +0 -21
- package/dist/utils/sortMarkets.d.cts.map +0 -1
- package/dist/utils/sortMarkets.d.mts +0 -21
- package/dist/utils/sortMarkets.d.mts.map +0 -1
- package/dist/utils/sortMarkets.mjs +0 -84
- package/dist/utils/sortMarkets.mjs.map +0 -1
- package/dist/utils/standaloneInfoClient.cjs +0 -34
- package/dist/utils/standaloneInfoClient.cjs.map +0 -1
- package/dist/utils/standaloneInfoClient.d.cts +0 -31
- package/dist/utils/standaloneInfoClient.d.cts.map +0 -1
- package/dist/utils/standaloneInfoClient.d.mts +0 -31
- package/dist/utils/standaloneInfoClient.d.mts.map +0 -1
- package/dist/utils/standaloneInfoClient.mjs +0 -30
- package/dist/utils/standaloneInfoClient.mjs.map +0 -1
- package/dist/utils/stringParseUtils.cjs +0 -49
- package/dist/utils/stringParseUtils.cjs.map +0 -1
- package/dist/utils/stringParseUtils.d.cts +0 -35
- package/dist/utils/stringParseUtils.d.cts.map +0 -1
- package/dist/utils/stringParseUtils.d.mts +0 -35
- package/dist/utils/stringParseUtils.d.mts.map +0 -1
- package/dist/utils/stringParseUtils.mjs +0 -44
- package/dist/utils/stringParseUtils.mjs.map +0 -1
- package/dist/utils/time.cjs +0 -37
- package/dist/utils/time.cjs.map +0 -1
- package/dist/utils/time.d.cts +0 -17
- package/dist/utils/time.d.cts.map +0 -1
- package/dist/utils/time.d.mts +0 -17
- package/dist/utils/time.d.mts.map +0 -1
- package/dist/utils/time.mjs +0 -33
- package/dist/utils/time.mjs.map +0 -1
- package/dist/utils/tpslValidation.cjs +0 -505
- package/dist/utils/tpslValidation.cjs.map +0 -1
- package/dist/utils/tpslValidation.d.cts +0 -182
- package/dist/utils/tpslValidation.d.cts.map +0 -1
- package/dist/utils/tpslValidation.d.mts +0 -182
- package/dist/utils/tpslValidation.d.mts.map +0 -1
- package/dist/utils/tpslValidation.mjs +0 -482
- package/dist/utils/tpslValidation.mjs.map +0 -1
- package/dist/utils/transactionUtils.cjs +0 -36
- package/dist/utils/transactionUtils.cjs.map +0 -1
- package/dist/utils/transactionUtils.d.cts +0 -17
- package/dist/utils/transactionUtils.d.cts.map +0 -1
- package/dist/utils/transactionUtils.d.mts +0 -17
- package/dist/utils/transactionUtils.d.mts.map +0 -1
- package/dist/utils/transactionUtils.mjs +0 -32
- package/dist/utils/transactionUtils.mjs.map +0 -1
- package/dist/utils/wait.cjs +0 -12
- package/dist/utils/wait.cjs.map +0 -1
- package/dist/utils/wait.d.cts +0 -8
- package/dist/utils/wait.d.cts.map +0 -1
- package/dist/utils/wait.d.mts +0 -8
- package/dist/utils/wait.d.mts.map +0 -1
- package/dist/utils/wait.mjs +0 -8
- package/dist/utils/wait.mjs.map +0 -1
|
@@ -1,2166 +0,0 @@
|
|
|
1
|
-
import { TP_SL_CONFIG, PERPS_CONSTANTS } from "../constants/perpsConfig.mjs";
|
|
2
|
-
import { calculateWeightedReturnOnEquity } from "../utils/accountUtils.mjs";
|
|
3
|
-
import { adaptPositionFromSDK, adaptOrderFromSDK, adaptAccountStateFromSDK, parseAssetName } from "../utils/hyperLiquidAdapter.mjs";
|
|
4
|
-
import { processBboData } from "../utils/hyperLiquidOrderBookProcessor.mjs";
|
|
5
|
-
import { calculateOpenInterestUSD } from "../utils/marketDataTransform.mjs";
|
|
6
|
-
/**
|
|
7
|
-
* Ensures we have a proper Error object for logging.
|
|
8
|
-
* Converts unknown/string errors to proper Error instances.
|
|
9
|
-
*
|
|
10
|
-
* @param error - The caught error (could be Error, string, or unknown)
|
|
11
|
-
* @returns A proper Error instance
|
|
12
|
-
*/
|
|
13
|
-
function ensureError(error) {
|
|
14
|
-
if (error instanceof Error) {
|
|
15
|
-
return error;
|
|
16
|
-
}
|
|
17
|
-
return new Error(String(error));
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Service for managing HyperLiquid WebSocket subscriptions
|
|
21
|
-
* Implements singleton subscription architecture with reference counting
|
|
22
|
-
*/
|
|
23
|
-
export class HyperLiquidSubscriptionService {
|
|
24
|
-
constructor(clientService, walletService, platformDependencies, hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets) {
|
|
25
|
-
this.discoveredDexNames = []; // DEX order for mapping webData3 perpDexStates indices
|
|
26
|
-
// DEX discovery synchronization - allows subscriptions to wait for HIP-3 DEX discovery
|
|
27
|
-
this.dexDiscoveryPromise = null;
|
|
28
|
-
this.dexDiscoveryResolver = null;
|
|
29
|
-
// Track DEXs for synchronized position notifications
|
|
30
|
-
// Ensures all DEXs send initial data before notifying subscribers
|
|
31
|
-
this.expectedDexs = new Set();
|
|
32
|
-
this.initializedDexs = new Set();
|
|
33
|
-
// Subscriber collections
|
|
34
|
-
this.priceSubscribers = new Map();
|
|
35
|
-
this.positionSubscribers = new Set();
|
|
36
|
-
// Order fill subscribers keyed by accountId (normalized: undefined -> 'default')
|
|
37
|
-
this.orderFillSubscribers = new Map();
|
|
38
|
-
this.orderSubscribers = new Set();
|
|
39
|
-
this.accountSubscribers = new Set();
|
|
40
|
-
// Track which subscribers want market data
|
|
41
|
-
this.marketDataSubscribers = new Map();
|
|
42
|
-
// Track which subscribers want top-of-book (best bid/ask) data
|
|
43
|
-
this.orderBookSubscribers = new Map();
|
|
44
|
-
this.globalActiveAssetSubscriptions = new Map();
|
|
45
|
-
this.globalBboSubscriptions = new Map();
|
|
46
|
-
// Order fill subscriptions keyed by accountId (normalized: undefined -> 'default')
|
|
47
|
-
this.orderFillSubscriptions = new Map();
|
|
48
|
-
this.symbolSubscriberCounts = new Map();
|
|
49
|
-
this.dexSubscriberCounts = new Map(); // Track subscribers per DEX for assetCtxs
|
|
50
|
-
// Multi-DEX webData3 subscription for all user data (positions, orders, account, OI caps)
|
|
51
|
-
this.webData3Subscriptions = new Map(); // Key: dex name ('' for main)
|
|
52
|
-
this.positionSubscriberCount = 0;
|
|
53
|
-
this.orderSubscriberCount = 0;
|
|
54
|
-
this.accountSubscriberCount = 0;
|
|
55
|
-
this.oiCapSubscriberCount = 0;
|
|
56
|
-
// Multi-DEX data caches
|
|
57
|
-
this.dexPositionsCache = new Map(); // Per-DEX positions
|
|
58
|
-
this.dexOrdersCache = new Map(); // Per-DEX orders
|
|
59
|
-
this.dexAccountCache = new Map(); // Per-DEX account state
|
|
60
|
-
this.cachedPositions = null; // Aggregated positions
|
|
61
|
-
this.cachedOrders = null; // Aggregated orders
|
|
62
|
-
this.cachedAccount = null; // Aggregated account
|
|
63
|
-
this.ordersCacheInitialized = false; // Track if orders cache has received WebSocket data
|
|
64
|
-
this.positionsCacheInitialized = false; // Track if positions cache has received WebSocket data
|
|
65
|
-
// OI Cap tracking (from webData3.perpDexStates[].perpsAtOpenInterestCap)
|
|
66
|
-
this.oiCapSubscribers = new Set();
|
|
67
|
-
this.cachedOICaps = [];
|
|
68
|
-
this.cachedOICapsHash = '';
|
|
69
|
-
this.oiCapsCacheInitialized = false;
|
|
70
|
-
// Global price data cache
|
|
71
|
-
this.cachedPriceData = null;
|
|
72
|
-
// HIP-3: assetCtxs subscriptions for multi-DEX market data
|
|
73
|
-
this.assetCtxsSubscriptions = new Map(); // Key: dex name ('' for main)
|
|
74
|
-
this.dexAssetCtxsCache = new Map(); // Per-DEX asset contexts
|
|
75
|
-
this.assetCtxsSubscriptionPromises = new Map(); // Track in-progress subscriptions
|
|
76
|
-
this.clearinghouseStateSubscriptions = new Map(); // Key: dex name ('' for main)
|
|
77
|
-
this.openOrdersSubscriptions = new Map(); // Key: dex name ('' for main)
|
|
78
|
-
// Meta cache per DEX - populated by metaAndAssetCtxs, used by createAssetCtxsSubscription
|
|
79
|
-
// This avoids redundant meta() API calls since metaAndAssetCtxs already returns meta data
|
|
80
|
-
this.dexMetaCache = new Map();
|
|
81
|
-
// Order book data cache
|
|
82
|
-
this.orderBookCache = new Map();
|
|
83
|
-
// Market data caching for multi-channel consolidation
|
|
84
|
-
this.marketDataCache = new Map();
|
|
85
|
-
// Cache hashes to avoid recomputation
|
|
86
|
-
this.cachedPositionsHash = '';
|
|
87
|
-
this.cachedOrdersHash = '';
|
|
88
|
-
this.cachedAccountHash = '';
|
|
89
|
-
this.clientService = clientService;
|
|
90
|
-
this.walletService = walletService;
|
|
91
|
-
this.deps = platformDependencies;
|
|
92
|
-
this.hip3Enabled = hip3Enabled ?? false;
|
|
93
|
-
this.enabledDexs = enabledDexs ?? [];
|
|
94
|
-
this.discoveredDexNames = enabledDexs ?? [];
|
|
95
|
-
this.allowlistMarkets = allowlistMarkets ?? [];
|
|
96
|
-
this.blocklistMarkets = blocklistMarkets ?? [];
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Get error context for logging with searchable tags and context.
|
|
100
|
-
* Enables Sentry dashboard filtering by feature, provider, and network.
|
|
101
|
-
*
|
|
102
|
-
* @param method - The method name where the error occurred
|
|
103
|
-
* @param extra - Optional additional context fields (merged into searchable context.data)
|
|
104
|
-
* @returns Error options with tags (searchable) and context (searchable)
|
|
105
|
-
*/
|
|
106
|
-
getErrorContext(method, extra) {
|
|
107
|
-
return {
|
|
108
|
-
tags: {
|
|
109
|
-
feature: PERPS_CONSTANTS.FeatureName,
|
|
110
|
-
provider: 'hyperliquid',
|
|
111
|
-
network: this.clientService.isTestnetMode() ? 'testnet' : 'mainnet',
|
|
112
|
-
},
|
|
113
|
-
context: {
|
|
114
|
-
name: 'HyperLiquidSubscriptionService',
|
|
115
|
-
data: {
|
|
116
|
-
method,
|
|
117
|
-
...extra,
|
|
118
|
-
},
|
|
119
|
-
},
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* Check if a DEX is enabled in our configuration
|
|
124
|
-
* Used to filter webData3 callback data to only process DEXs we care about
|
|
125
|
-
*
|
|
126
|
-
* @param dex - DEX name (null for main DEX, string for HIP-3)
|
|
127
|
-
* @returns true if this DEX should be processed
|
|
128
|
-
*/
|
|
129
|
-
isDexEnabled(dex) {
|
|
130
|
-
if (dex === null) {
|
|
131
|
-
return true; // Main DEX always enabled
|
|
132
|
-
}
|
|
133
|
-
if (!this.hip3Enabled) {
|
|
134
|
-
return false; // HIP-3 disabled entirely
|
|
135
|
-
}
|
|
136
|
-
return this.enabledDexs.includes(dex);
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Populate DEX meta cache with pre-fetched meta data
|
|
140
|
-
* Called by Provider after buildAssetMapping to share cached meta,
|
|
141
|
-
* avoiding redundant metaAndAssetCtxs/meta API calls during subscription setup
|
|
142
|
-
*
|
|
143
|
-
* @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
|
|
144
|
-
* @param meta - Meta response containing universe data
|
|
145
|
-
* @param meta.universe
|
|
146
|
-
*/
|
|
147
|
-
setDexMetaCache(dex, meta) {
|
|
148
|
-
this.dexMetaCache.set(dex, meta);
|
|
149
|
-
this.deps.debugLogger.log('[SubscriptionService] DEX meta cache populated', {
|
|
150
|
-
dex: dex || 'main',
|
|
151
|
-
universeSize: meta.universe.length,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
|
-
* Cache asset contexts for a specific DEX from API response
|
|
156
|
-
* This allows buildAssetMapping() to populate cache for getMarketDataWithPrices() to use
|
|
157
|
-
*
|
|
158
|
-
* @param dex - DEX name ('' for main perps)
|
|
159
|
-
* @param assetCtxs - Asset contexts from metaAndAssetCtxs response
|
|
160
|
-
*/
|
|
161
|
-
setDexAssetCtxsCache(dex, assetCtxs) {
|
|
162
|
-
this.dexAssetCtxsCache.set(dex, assetCtxs);
|
|
163
|
-
this.deps.debugLogger.log('[SubscriptionService] DEX assetCtxs cache populated', {
|
|
164
|
-
dex: dex || 'main',
|
|
165
|
-
ctxsCount: assetCtxs.length,
|
|
166
|
-
});
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Get cached assetCtxs for a DEX
|
|
170
|
-
* Returns the cached asset contexts from WebSocket subscription if available
|
|
171
|
-
*
|
|
172
|
-
* @param dex - DEX key ('' for main DEX, 'xyz'/'flx'/etc for HIP-3)
|
|
173
|
-
* @returns Array of asset contexts or undefined if not cached
|
|
174
|
-
*/
|
|
175
|
-
getDexAssetCtxsCache(dex) {
|
|
176
|
-
return this.dexAssetCtxsCache.get(dex);
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* Wait for DEX discovery to complete (with timeout)
|
|
180
|
-
* Used when HIP-3 is enabled but enabledDexs hasn't been populated yet.
|
|
181
|
-
* This allows subscriptions to wait for DEX discovery before creating per-DEX subscriptions.
|
|
182
|
-
*
|
|
183
|
-
* @param timeoutMs - Timeout in milliseconds (default: 5000)
|
|
184
|
-
*/
|
|
185
|
-
async waitForDexDiscovery(timeoutMs = 5000) {
|
|
186
|
-
// Already have DEXs, no need to wait
|
|
187
|
-
if (this.enabledDexs.length > 0) {
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
// Create promise if not exists
|
|
191
|
-
if (!this.dexDiscoveryPromise) {
|
|
192
|
-
this.dexDiscoveryPromise = new Promise((resolve) => {
|
|
193
|
-
this.dexDiscoveryResolver = resolve;
|
|
194
|
-
});
|
|
195
|
-
}
|
|
196
|
-
// Wait with timeout
|
|
197
|
-
let timeoutId;
|
|
198
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
199
|
-
timeoutId = setTimeout(() => reject(new Error('DEX discovery timeout')), timeoutMs);
|
|
200
|
-
});
|
|
201
|
-
try {
|
|
202
|
-
await Promise.race([this.dexDiscoveryPromise, timeoutPromise]);
|
|
203
|
-
}
|
|
204
|
-
catch {
|
|
205
|
-
this.deps.debugLogger.log('DEX discovery wait timed out, proceeding with main DEX only');
|
|
206
|
-
}
|
|
207
|
-
finally {
|
|
208
|
-
if (timeoutId) {
|
|
209
|
-
clearTimeout(timeoutId);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Update feature flags for HIP-3 support
|
|
215
|
-
* Called when provider configuration changes at runtime
|
|
216
|
-
* Note: Market filtering is NOT applied in subscription service - only in Provider
|
|
217
|
-
*
|
|
218
|
-
* @param hip3Enabled - Whether HIP-3 is enabled
|
|
219
|
-
* @param enabledDexs - List of enabled DEX identifiers
|
|
220
|
-
* @param allowlistMarkets - List of allowed markets
|
|
221
|
-
* @param blocklistMarkets - List of blocked markets
|
|
222
|
-
*/
|
|
223
|
-
async updateFeatureFlags(hip3Enabled, enabledDexs, allowlistMarkets, blocklistMarkets) {
|
|
224
|
-
const previousEnabledDexs = [...this.enabledDexs];
|
|
225
|
-
const previousAllowlistMarkets = [...this.allowlistMarkets];
|
|
226
|
-
const previousBlocklistMarkets = [...this.blocklistMarkets];
|
|
227
|
-
const previousHip3Enabled = this.hip3Enabled;
|
|
228
|
-
this.hip3Enabled = hip3Enabled;
|
|
229
|
-
this.enabledDexs = enabledDexs;
|
|
230
|
-
this.allowlistMarkets = allowlistMarkets;
|
|
231
|
-
this.blocklistMarkets = blocklistMarkets;
|
|
232
|
-
this.discoveredDexNames = enabledDexs; // Store DEX order for webData3 index mapping
|
|
233
|
-
// Resolve any pending DEX discovery wait now that DEXs are available
|
|
234
|
-
if (this.dexDiscoveryResolver && enabledDexs.length > 0) {
|
|
235
|
-
this.dexDiscoveryResolver();
|
|
236
|
-
this.dexDiscoveryPromise = null;
|
|
237
|
-
this.dexDiscoveryResolver = null;
|
|
238
|
-
}
|
|
239
|
-
this.deps.debugLogger.log('Feature flags updated:', {
|
|
240
|
-
previousHip3Enabled,
|
|
241
|
-
hip3Enabled,
|
|
242
|
-
previousEnabledDexs,
|
|
243
|
-
enabledDexs,
|
|
244
|
-
previousAllowlistMarkets,
|
|
245
|
-
allowlistMarkets,
|
|
246
|
-
previousBlocklistMarkets,
|
|
247
|
-
blocklistMarkets,
|
|
248
|
-
});
|
|
249
|
-
// If equity was just enabled or new DEXs were added
|
|
250
|
-
const newDexs = enabledDexs.filter((dex) => !previousEnabledDexs.includes(dex));
|
|
251
|
-
if ((!previousHip3Enabled && hip3Enabled && enabledDexs.length > 0) ||
|
|
252
|
-
newDexs.length > 0) {
|
|
253
|
-
this.deps.debugLogger.log('Establishing subscriptions for new DEXs:', newDexs);
|
|
254
|
-
// Establish assetCtxs subscriptions for new DEXs (for market data)
|
|
255
|
-
const hasMarketDataSubscribers = this.marketDataSubscribers.size > 0;
|
|
256
|
-
if (hasMarketDataSubscribers) {
|
|
257
|
-
await Promise.all(newDexs.map(async (dex) => {
|
|
258
|
-
try {
|
|
259
|
-
await this.ensureAssetCtxsSubscription(dex);
|
|
260
|
-
}
|
|
261
|
-
catch (assetCtxsError) {
|
|
262
|
-
this.deps.logger.error(ensureError(assetCtxsError), this.getErrorContext('updateFeatureFlags.ensureAssetCtxsSubscription', {
|
|
263
|
-
dex,
|
|
264
|
-
}));
|
|
265
|
-
}
|
|
266
|
-
}));
|
|
267
|
-
}
|
|
268
|
-
// Establish clearinghouseState/openOrders subscriptions for new DEXs
|
|
269
|
-
// (needed for positions, orders, and account data when using individual subscriptions)
|
|
270
|
-
const hasUserDataSubscribers = this.positionSubscriberCount > 0 ||
|
|
271
|
-
this.orderSubscriberCount > 0 ||
|
|
272
|
-
this.accountSubscriberCount > 0;
|
|
273
|
-
if (hasUserDataSubscribers && this.hip3Enabled) {
|
|
274
|
-
try {
|
|
275
|
-
const userAddress = await this.walletService.getUserAddressWithDefault();
|
|
276
|
-
await Promise.all(newDexs.map(async (dex) => {
|
|
277
|
-
try {
|
|
278
|
-
await this.ensureClearinghouseStateSubscription(userAddress, dex);
|
|
279
|
-
await this.ensureOpenOrdersSubscription(userAddress, dex);
|
|
280
|
-
this.deps.debugLogger.log(`Established user data subscriptions for new DEX: ${dex}`);
|
|
281
|
-
}
|
|
282
|
-
catch (userDataError) {
|
|
283
|
-
this.deps.logger.error(ensureError(userDataError), this.getErrorContext('updateFeatureFlags.ensureUserDataSubscription', { dex }));
|
|
284
|
-
}
|
|
285
|
-
}));
|
|
286
|
-
}
|
|
287
|
-
catch (addressError) {
|
|
288
|
-
this.deps.logger.error(ensureError(addressError), this.getErrorContext('updateFeatureFlags.getUserAddress'));
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
/**
|
|
294
|
-
* Fast hash function for change detection
|
|
295
|
-
* Uses string concatenation of key fields instead of JSON.stringify()
|
|
296
|
-
* Performance: ~100x faster than JSON.stringify() for typical objects
|
|
297
|
-
* Tracks structural changes (coin, size, entryPrice, leverage, TP/SL prices/counts)
|
|
298
|
-
* and value changes (unrealizedPnl, returnOnEquity) for live P&L updates
|
|
299
|
-
*
|
|
300
|
-
* @param positions - Positions to hash
|
|
301
|
-
* @returns Hash string
|
|
302
|
-
*/
|
|
303
|
-
hashPositions(positions) {
|
|
304
|
-
if (!positions || positions.length === 0) {
|
|
305
|
-
return '0';
|
|
306
|
-
}
|
|
307
|
-
return positions
|
|
308
|
-
.map((pos) => `${pos.symbol}:${pos.size}:${pos.entryPrice}:${pos.leverage.value}:${pos.takeProfitPrice || ''}:${pos.stopLossPrice || ''}:${pos.takeProfitCount}:${pos.stopLossCount}:${pos.unrealizedPnl}:${pos.returnOnEquity}`)
|
|
309
|
-
.join('|');
|
|
310
|
-
}
|
|
311
|
-
/**
|
|
312
|
-
* Fast hash function for orders
|
|
313
|
-
*
|
|
314
|
-
* @param orders - Orders to hash
|
|
315
|
-
* @returns Hash string
|
|
316
|
-
*/
|
|
317
|
-
hashOrders(orders) {
|
|
318
|
-
if (!orders || orders.length === 0) {
|
|
319
|
-
return '0';
|
|
320
|
-
}
|
|
321
|
-
return orders
|
|
322
|
-
.map((ord) => `${ord.symbol}:${ord.side}:${ord.size}:${ord.price}:${ord.orderType}`)
|
|
323
|
-
.join('|');
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* Fast hash function for account state
|
|
327
|
-
*
|
|
328
|
-
* @param account - Account state to hash
|
|
329
|
-
* @returns Hash string
|
|
330
|
-
*/
|
|
331
|
-
hashAccountState(account) {
|
|
332
|
-
return `${account.availableBalance}:${account.totalBalance}:${account.marginUsed}:${account.unrealizedPnl}`;
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* Extract TP/SL from orders and optionally convert raw SDK orders to Order format.
|
|
336
|
-
* DRY helper used by both webData2 and clearinghouseState callbacks.
|
|
337
|
-
*
|
|
338
|
-
* @param orders - Raw SDK orders from WebSocket event
|
|
339
|
-
* @param positions - Current positions for TP/SL matching
|
|
340
|
-
* @param cachedProcessedOrders - Optional pre-processed orders (skips conversion if provided)
|
|
341
|
-
* @returns Maps for TP/SL prices and counts, plus processed Order array
|
|
342
|
-
*/
|
|
343
|
-
extractTPSLFromOrders(orders, positions, cachedProcessedOrders) {
|
|
344
|
-
const tpslMap = new Map();
|
|
345
|
-
const tpslCountMap = new Map();
|
|
346
|
-
// If cached processed orders provided, extract TP/SL from them directly
|
|
347
|
-
if (cachedProcessedOrders) {
|
|
348
|
-
cachedProcessedOrders.forEach((order) => {
|
|
349
|
-
// Use triggerPrice for TP/SL (trigger condition price), falling back to price
|
|
350
|
-
// This ensures consistency with raw SDK order processing which uses triggerPx
|
|
351
|
-
const tpslPrice = order.triggerPrice || order.price;
|
|
352
|
-
if (order.isTrigger && tpslPrice) {
|
|
353
|
-
const isTakeProfit = order.detailedOrderType?.includes('Take Profit');
|
|
354
|
-
const isStop = order.detailedOrderType?.includes('Stop');
|
|
355
|
-
const matchingPosition = positions.find((pos) => pos.symbol === order.symbol);
|
|
356
|
-
// Determine TP vs SL classification for count and price updates
|
|
357
|
-
// Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
|
|
358
|
-
let classifiedAsTakeProfit = isTakeProfit;
|
|
359
|
-
let classifiedAsStop = isStop;
|
|
360
|
-
if (!isTakeProfit && !isStop && matchingPosition) {
|
|
361
|
-
// Fallback: determine based on trigger price vs entry price
|
|
362
|
-
// This handles orders with ambiguous type 'Trigger'
|
|
363
|
-
const triggerPrice = parseFloat(tpslPrice);
|
|
364
|
-
const entryPrice = parseFloat(matchingPosition.entryPrice || '0');
|
|
365
|
-
const isLong = parseFloat(matchingPosition.size) > 0;
|
|
366
|
-
if (isLong) {
|
|
367
|
-
if (triggerPrice > entryPrice) {
|
|
368
|
-
classifiedAsTakeProfit = true;
|
|
369
|
-
}
|
|
370
|
-
else {
|
|
371
|
-
classifiedAsStop = true;
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
else if (triggerPrice < entryPrice) {
|
|
375
|
-
classifiedAsTakeProfit = true;
|
|
376
|
-
}
|
|
377
|
-
else {
|
|
378
|
-
classifiedAsStop = true;
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
const currentTakeProfitCount = tpslCountMap.get(order.symbol)?.takeProfitCount || 0;
|
|
382
|
-
const currentStopLossCount = tpslCountMap.get(order.symbol)?.stopLossCount || 0;
|
|
383
|
-
tpslCountMap.set(order.symbol, {
|
|
384
|
-
takeProfitCount: classifiedAsTakeProfit
|
|
385
|
-
? currentTakeProfitCount + 1
|
|
386
|
-
: currentTakeProfitCount,
|
|
387
|
-
stopLossCount: classifiedAsStop
|
|
388
|
-
? currentStopLossCount + 1
|
|
389
|
-
: currentStopLossCount,
|
|
390
|
-
});
|
|
391
|
-
if (matchingPosition) {
|
|
392
|
-
const existing = tpslMap.get(order.symbol) || {};
|
|
393
|
-
if (classifiedAsTakeProfit) {
|
|
394
|
-
existing.takeProfitPrice = tpslPrice;
|
|
395
|
-
}
|
|
396
|
-
else if (classifiedAsStop) {
|
|
397
|
-
existing.stopLossPrice = tpslPrice;
|
|
398
|
-
}
|
|
399
|
-
tpslMap.set(order.symbol, existing);
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
});
|
|
403
|
-
return { tpslMap, tpslCountMap, processedOrders: cachedProcessedOrders };
|
|
404
|
-
}
|
|
405
|
-
// Process raw SDK orders
|
|
406
|
-
const processedOrders = [];
|
|
407
|
-
orders.forEach((order) => {
|
|
408
|
-
let position;
|
|
409
|
-
let positionForCoin;
|
|
410
|
-
const matchPositionToTpsl = (pos) => {
|
|
411
|
-
if (TP_SL_CONFIG.UsePositionBoundTpsl) {
|
|
412
|
-
return (pos.symbol === order.coin &&
|
|
413
|
-
order.reduceOnly &&
|
|
414
|
-
order.isPositionTpsl);
|
|
415
|
-
}
|
|
416
|
-
return (pos.symbol === order.coin &&
|
|
417
|
-
Math.abs(parseFloat(order.sz)) >= Math.abs(parseFloat(pos.size)));
|
|
418
|
-
};
|
|
419
|
-
const matchPositionToCoin = (pos) => pos.symbol === order.coin;
|
|
420
|
-
// Process trigger orders for TP/SL extraction
|
|
421
|
-
if (order.triggerPx) {
|
|
422
|
-
const isTakeProfit = order.orderType?.includes('Take Profit');
|
|
423
|
-
const isStop = order.orderType?.includes('Stop');
|
|
424
|
-
const { coin } = order;
|
|
425
|
-
position = positions.find(matchPositionToTpsl);
|
|
426
|
-
positionForCoin = positions.find(matchPositionToCoin);
|
|
427
|
-
// Determine TP vs SL classification for count and price updates
|
|
428
|
-
// Use order type first, fallback to price-based detection for ambiguous 'Trigger' types
|
|
429
|
-
// This matches the cached order processing logic for consistency
|
|
430
|
-
let classifiedAsTakeProfit = isTakeProfit;
|
|
431
|
-
let classifiedAsStop = isStop;
|
|
432
|
-
if (!isTakeProfit && !isStop && position) {
|
|
433
|
-
// Fallback: determine based on trigger price vs entry price
|
|
434
|
-
// This handles orders with ambiguous type 'Trigger'
|
|
435
|
-
const triggerPrice = parseFloat(order.triggerPx);
|
|
436
|
-
const entryPrice = parseFloat(position.entryPrice || '0');
|
|
437
|
-
const isLong = parseFloat(position.size) > 0;
|
|
438
|
-
if (isLong) {
|
|
439
|
-
if (triggerPrice > entryPrice) {
|
|
440
|
-
classifiedAsTakeProfit = true;
|
|
441
|
-
}
|
|
442
|
-
else {
|
|
443
|
-
classifiedAsStop = true;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
else if (triggerPrice < entryPrice) {
|
|
447
|
-
classifiedAsTakeProfit = true;
|
|
448
|
-
}
|
|
449
|
-
else {
|
|
450
|
-
classifiedAsStop = true;
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
const currentTakeProfitCount = tpslCountMap.get(coin)?.takeProfitCount || 0;
|
|
454
|
-
const currentStopLossCount = tpslCountMap.get(coin)?.stopLossCount || 0;
|
|
455
|
-
tpslCountMap.set(coin, {
|
|
456
|
-
takeProfitCount: classifiedAsTakeProfit
|
|
457
|
-
? currentTakeProfitCount + 1
|
|
458
|
-
: currentTakeProfitCount,
|
|
459
|
-
stopLossCount: classifiedAsStop
|
|
460
|
-
? currentStopLossCount + 1
|
|
461
|
-
: currentStopLossCount,
|
|
462
|
-
});
|
|
463
|
-
if (position) {
|
|
464
|
-
const existing = tpslMap.get(coin) || {};
|
|
465
|
-
// Use classified values for price assignment (consistent with count logic)
|
|
466
|
-
if (classifiedAsTakeProfit) {
|
|
467
|
-
existing.takeProfitPrice = order.triggerPx;
|
|
468
|
-
}
|
|
469
|
-
else if (classifiedAsStop) {
|
|
470
|
-
existing.stopLossPrice = order.triggerPx;
|
|
471
|
-
}
|
|
472
|
-
tpslMap.set(coin, existing);
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
// Convert ALL open orders to Order format
|
|
476
|
-
const convertedOrder = adaptOrderFromSDK(order, position || positionForCoin);
|
|
477
|
-
processedOrders.push(convertedOrder);
|
|
478
|
-
});
|
|
479
|
-
return { tpslMap, tpslCountMap, processedOrders };
|
|
480
|
-
}
|
|
481
|
-
/**
|
|
482
|
-
* Merge TP/SL data into positions
|
|
483
|
-
* DRY helper used by both webData2 and clearinghouseState callbacks
|
|
484
|
-
*
|
|
485
|
-
* @param positions - Base positions without TP/SL
|
|
486
|
-
* @param tpslMap - Map of coin -> TP/SL prices
|
|
487
|
-
* @param tpslCountMap - Map of coin -> TP/SL counts
|
|
488
|
-
* @returns Positions enhanced with TP/SL data
|
|
489
|
-
*/
|
|
490
|
-
mergeTPSLIntoPositions(positions, tpslMap, tpslCountMap) {
|
|
491
|
-
return positions.map((position) => {
|
|
492
|
-
const tpsl = tpslMap.get(position.symbol) || {};
|
|
493
|
-
const tpslCount = tpslCountMap.get(position.symbol) || {};
|
|
494
|
-
return {
|
|
495
|
-
...position,
|
|
496
|
-
takeProfitPrice: tpsl.takeProfitPrice || undefined,
|
|
497
|
-
stopLossPrice: tpsl.stopLossPrice || undefined,
|
|
498
|
-
takeProfitCount: tpslCount.takeProfitCount || 0,
|
|
499
|
-
stopLossCount: tpslCount.stopLossCount || 0,
|
|
500
|
-
};
|
|
501
|
-
});
|
|
502
|
-
}
|
|
503
|
-
/**
|
|
504
|
-
* Aggregate account states from all cached DEXs
|
|
505
|
-
* Sums balances and creates per-DEX breakdown for multi-DEX portfolio view
|
|
506
|
-
*
|
|
507
|
-
* @returns Aggregated account state with dexBreakdown field
|
|
508
|
-
*/
|
|
509
|
-
aggregateAccountStates() {
|
|
510
|
-
const subAccountBreakdown = {};
|
|
511
|
-
let totalAvailableBalance = 0;
|
|
512
|
-
let totalBalance = 0;
|
|
513
|
-
let totalMarginUsed = 0;
|
|
514
|
-
let totalUnrealizedPnl = 0;
|
|
515
|
-
// Collect account states for weighted ROE calculation
|
|
516
|
-
const accountStatesForROE = [];
|
|
517
|
-
// Aggregate all cached account states
|
|
518
|
-
Array.from(this.dexAccountCache.entries()).forEach(([currentDex, state]) => {
|
|
519
|
-
const dexKey = currentDex === '' ? 'main' : currentDex;
|
|
520
|
-
subAccountBreakdown[dexKey] = {
|
|
521
|
-
availableBalance: state.availableBalance,
|
|
522
|
-
totalBalance: state.totalBalance,
|
|
523
|
-
};
|
|
524
|
-
totalAvailableBalance += parseFloat(state.availableBalance);
|
|
525
|
-
totalBalance += parseFloat(state.totalBalance);
|
|
526
|
-
totalMarginUsed += parseFloat(state.marginUsed);
|
|
527
|
-
totalUnrealizedPnl += parseFloat(state.unrealizedPnl);
|
|
528
|
-
// Collect data for weighted ROE calculation
|
|
529
|
-
accountStatesForROE.push({
|
|
530
|
-
unrealizedPnl: state.unrealizedPnl,
|
|
531
|
-
returnOnEquity: state.returnOnEquity,
|
|
532
|
-
});
|
|
533
|
-
});
|
|
534
|
-
// Use first DEX's account state as base and override aggregated values
|
|
535
|
-
const firstDexAccount = this.dexAccountCache.values().next().value || {};
|
|
536
|
-
// Calculate weighted returnOnEquity across all DEXs
|
|
537
|
-
const returnOnEquity = calculateWeightedReturnOnEquity(accountStatesForROE);
|
|
538
|
-
return {
|
|
539
|
-
...firstDexAccount,
|
|
540
|
-
availableBalance: totalAvailableBalance.toString(),
|
|
541
|
-
totalBalance: totalBalance.toString(),
|
|
542
|
-
marginUsed: totalMarginUsed.toString(),
|
|
543
|
-
unrealizedPnl: totalUnrealizedPnl.toString(),
|
|
544
|
-
subAccountBreakdown,
|
|
545
|
-
returnOnEquity,
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
/**
|
|
549
|
-
* Subscribe to live price updates with singleton subscription architecture
|
|
550
|
-
* Uses allMids for fast price updates and predictedFundings for accurate funding rates
|
|
551
|
-
*
|
|
552
|
-
* @param params - Subscription parameters
|
|
553
|
-
* @returns Cleanup function
|
|
554
|
-
*/
|
|
555
|
-
async subscribeToPrices(params) {
|
|
556
|
-
const { symbols, callback, includeOrderBook = false, includeMarketData = false, } = params;
|
|
557
|
-
const unsubscribers = [];
|
|
558
|
-
symbols.forEach((symbol) => {
|
|
559
|
-
unsubscribers.push(this.createSubscription(this.priceSubscribers, callback, symbol));
|
|
560
|
-
// Track market data subscribers separately
|
|
561
|
-
if (includeMarketData) {
|
|
562
|
-
unsubscribers.push(this.createSubscription(this.marketDataSubscribers, callback, symbol));
|
|
563
|
-
}
|
|
564
|
-
// Track order book subscribers separately
|
|
565
|
-
if (includeOrderBook) {
|
|
566
|
-
unsubscribers.push(this.createSubscription(this.orderBookSubscribers, callback, symbol));
|
|
567
|
-
}
|
|
568
|
-
});
|
|
569
|
-
await this.clientService.ensureSubscriptionClient(this.walletService.createWalletAdapter());
|
|
570
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
571
|
-
if (!subscriptionClient) {
|
|
572
|
-
this.deps.debugLogger.log('SubscriptionClient not available for price subscription');
|
|
573
|
-
return () => unsubscribers.forEach((fn) => fn());
|
|
574
|
-
}
|
|
575
|
-
// Ensure global subscriptions are established
|
|
576
|
-
this.ensureGlobalAllMidsSubscription();
|
|
577
|
-
// HIP-3: Establish assetCtxs subscriptions ONLY for DEXs with requested symbols
|
|
578
|
-
// Performance: Avoid unnecessary WebSocket connections for unused DEXs
|
|
579
|
-
if (includeMarketData) {
|
|
580
|
-
// Extract unique DEXs from requested symbols
|
|
581
|
-
const dexsNeeded = new Set();
|
|
582
|
-
symbols.forEach((symbol) => {
|
|
583
|
-
const { dex } = parseAssetName(symbol);
|
|
584
|
-
dexsNeeded.add(dex);
|
|
585
|
-
});
|
|
586
|
-
// Only subscribe to DEXs that have requested symbols
|
|
587
|
-
dexsNeeded.forEach((dex) => {
|
|
588
|
-
const dexName = dex ?? '';
|
|
589
|
-
this.ensureAssetCtxsSubscription(dexName).catch((assetCtxsError) => {
|
|
590
|
-
this.deps.logger.error(ensureError(assetCtxsError), this.getErrorContext('subscribeToPrices.ensureAssetCtxsSubscription', { dex: dexName }));
|
|
591
|
-
});
|
|
592
|
-
});
|
|
593
|
-
}
|
|
594
|
-
// Note: Funding rates are now cached via assetCtxs WebSocket subscription
|
|
595
|
-
// (ensureAssetCtxsSubscription above), eliminating the need for a separate
|
|
596
|
-
// metaAndAssetCtxs API call here. The WebSocket callback in createAssetCtxsSubscription
|
|
597
|
-
// populates marketDataCache with funding rates as they arrive.
|
|
598
|
-
symbols.forEach((symbol) => {
|
|
599
|
-
// Subscribe to activeAssetCtx only when market data is requested
|
|
600
|
-
if (includeMarketData) {
|
|
601
|
-
this.ensureActiveAssetSubscription(symbol);
|
|
602
|
-
}
|
|
603
|
-
if (includeOrderBook) {
|
|
604
|
-
this.ensureBboSubscription(symbol);
|
|
605
|
-
}
|
|
606
|
-
});
|
|
607
|
-
// Send cached data immediately if available
|
|
608
|
-
symbols.forEach((symbol) => {
|
|
609
|
-
const cachedPrice = this.cachedPriceData?.get(symbol);
|
|
610
|
-
if (cachedPrice) {
|
|
611
|
-
callback([cachedPrice]);
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
// Return cleanup function
|
|
615
|
-
return () => {
|
|
616
|
-
unsubscribers.forEach((fn) => fn());
|
|
617
|
-
// Cleanup subscriptions with reference counting
|
|
618
|
-
symbols.forEach((symbol) => {
|
|
619
|
-
if (includeMarketData) {
|
|
620
|
-
this.cleanupActiveAssetSubscription(symbol);
|
|
621
|
-
}
|
|
622
|
-
if (includeOrderBook) {
|
|
623
|
-
this.cleanupBboSubscription(symbol);
|
|
624
|
-
}
|
|
625
|
-
});
|
|
626
|
-
// Cleanup DEX-level assetCtxs subscriptions
|
|
627
|
-
if (includeMarketData) {
|
|
628
|
-
// Extract unique DEXs from requested symbols
|
|
629
|
-
const dexsNeeded = new Set();
|
|
630
|
-
symbols.forEach((symbol) => {
|
|
631
|
-
const { dex } = parseAssetName(symbol);
|
|
632
|
-
dexsNeeded.add(dex);
|
|
633
|
-
});
|
|
634
|
-
// Cleanup assetCtxs subscription for each DEX
|
|
635
|
-
dexsNeeded.forEach((dex) => {
|
|
636
|
-
const dexName = dex ?? '';
|
|
637
|
-
this.cleanupAssetCtxsSubscription(dexName);
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
};
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Ensure shared webData3 subscription is active (singleton pattern with multi-DEX support)
|
|
644
|
-
* webData3 provides data for all DEXs (main + HIP-3) in a single subscription
|
|
645
|
-
*
|
|
646
|
-
* @param accountId - Optional account ID
|
|
647
|
-
*/
|
|
648
|
-
async ensureSharedWebData3Subscription(accountId) {
|
|
649
|
-
// Establish webData3 subscription (if not exists)
|
|
650
|
-
if (!this.webData3Subscriptions.has('')) {
|
|
651
|
-
if (!this.webData3SubscriptionPromise) {
|
|
652
|
-
this.webData3SubscriptionPromise =
|
|
653
|
-
this.createUserDataSubscription(accountId);
|
|
654
|
-
try {
|
|
655
|
-
await this.webData3SubscriptionPromise;
|
|
656
|
-
}
|
|
657
|
-
catch {
|
|
658
|
-
this.webData3SubscriptionPromise = undefined;
|
|
659
|
-
throw new Error('Failed to create user data subscription');
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
else {
|
|
663
|
-
await this.webData3SubscriptionPromise;
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
// Note: webData3 includes all DEX data, so no separate HIP-3 subscriptions needed
|
|
667
|
-
}
|
|
668
|
-
/**
|
|
669
|
-
* Create WebSocket subscription for user data (positions, orders, account)
|
|
670
|
-
* - Uses webData2 when HIP-3 disabled (main DEX only)
|
|
671
|
-
* - Uses webData3 when HIP-3 enabled (main + HIP-3 DEXs)
|
|
672
|
-
*
|
|
673
|
-
* webData2 provides data for main DEX only
|
|
674
|
-
* webData3 provides perpDexStates[] array containing data for all DEXs:
|
|
675
|
-
* - Index 0: Main DEX (dexName = '')
|
|
676
|
-
* - Index 1+: HIP-3 DEXs in order of enabledDexs array
|
|
677
|
-
*
|
|
678
|
-
* @param accountId - Optional account ID
|
|
679
|
-
*/
|
|
680
|
-
async createUserDataSubscription(accountId) {
|
|
681
|
-
await this.clientService.ensureSubscriptionClient(this.walletService.createWalletAdapter());
|
|
682
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
683
|
-
if (!subscriptionClient) {
|
|
684
|
-
throw new Error('Subscription client not initialized');
|
|
685
|
-
}
|
|
686
|
-
const userAddress = await this.walletService.getUserAddressWithDefault(accountId);
|
|
687
|
-
const dexName = ''; // Use empty string as key for single subscription
|
|
688
|
-
// Skip if subscription already exists
|
|
689
|
-
if (this.webData3Subscriptions.has(dexName)) {
|
|
690
|
-
return;
|
|
691
|
-
}
|
|
692
|
-
// Wait for DEX discovery if HIP-3 is enabled but DEXs haven't been discovered yet
|
|
693
|
-
// This ensures HIP-3 subscriptions are created together with main DEX
|
|
694
|
-
if (this.hip3Enabled && this.enabledDexs.length === 0) {
|
|
695
|
-
this.deps.debugLogger.log('Waiting for DEX discovery before creating subscriptions...');
|
|
696
|
-
await this.waitForDexDiscovery();
|
|
697
|
-
this.deps.debugLogger.log('DEX discovery complete, proceeding with subscriptions', {
|
|
698
|
-
enabledDexs: this.enabledDexs,
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
return new Promise((resolve, reject) => {
|
|
702
|
-
// Choose channel based on HIP-3 master switch
|
|
703
|
-
if (!this.hip3Enabled) {
|
|
704
|
-
// HIP-3 disabled: Use webData2 (main DEX only)
|
|
705
|
-
subscriptionClient
|
|
706
|
-
.webData2({ user: userAddress }, (data) => {
|
|
707
|
-
try {
|
|
708
|
-
// webData2 returns clearinghouseState for main DEX only
|
|
709
|
-
const currentDexName = ''; // Main DEX
|
|
710
|
-
// Check for removed fields before accessing
|
|
711
|
-
if (!data.clearinghouseState) {
|
|
712
|
-
return;
|
|
713
|
-
}
|
|
714
|
-
// Extract and process positions from clearinghouseState
|
|
715
|
-
const positions = data.clearinghouseState.assetPositions
|
|
716
|
-
.filter((assetPos) => assetPos.position.szi !== '0')
|
|
717
|
-
.map((assetPos) => adaptPositionFromSDK(assetPos));
|
|
718
|
-
// Extract TP/SL from orders
|
|
719
|
-
const { tpslMap, tpslCountMap, processedOrders: processedOrdersData, } = this.extractTPSLFromOrders(data.openOrders || [], positions);
|
|
720
|
-
// Merge TP/SL data into positions
|
|
721
|
-
const positionsWithTPSL = this.mergeTPSLIntoPositions(positions, tpslMap, tpslCountMap);
|
|
722
|
-
// Extract account data (webData2 provides clearinghouseState)
|
|
723
|
-
const accountState = adaptAccountStateFromSDK(data.clearinghouseState, undefined);
|
|
724
|
-
// Store in caches (main DEX only)
|
|
725
|
-
this.dexPositionsCache.set(currentDexName, positionsWithTPSL);
|
|
726
|
-
this.dexOrdersCache.set(currentDexName, processedOrdersData);
|
|
727
|
-
this.dexAccountCache.set(currentDexName, accountState);
|
|
728
|
-
// OI caps (main DEX only)
|
|
729
|
-
const oiCaps = data.perpsAtOpenInterestCap || [];
|
|
730
|
-
const oiCapsHash = [...oiCaps]
|
|
731
|
-
.sort((a, b) => a.localeCompare(b))
|
|
732
|
-
.join(',');
|
|
733
|
-
if (oiCapsHash !== this.cachedOICapsHash) {
|
|
734
|
-
this.cachedOICaps = oiCaps;
|
|
735
|
-
this.cachedOICapsHash = oiCapsHash;
|
|
736
|
-
this.oiCapsCacheInitialized = true;
|
|
737
|
-
this.oiCapSubscribers.forEach((oiCallback) => oiCallback(oiCaps));
|
|
738
|
-
}
|
|
739
|
-
// Notify subscribers (no aggregation needed - only main DEX)
|
|
740
|
-
const positionsHash = this.hashPositions(positionsWithTPSL);
|
|
741
|
-
const ordersHash = this.hashOrders(processedOrdersData);
|
|
742
|
-
const accountHash = this.hashAccountState(accountState);
|
|
743
|
-
if (positionsHash !== this.cachedPositionsHash) {
|
|
744
|
-
this.cachedPositions = positionsWithTPSL;
|
|
745
|
-
this.cachedPositionsHash = positionsHash;
|
|
746
|
-
this.positionsCacheInitialized = true;
|
|
747
|
-
this.positionSubscribers.forEach((posCallback) => posCallback(positionsWithTPSL));
|
|
748
|
-
}
|
|
749
|
-
if (ordersHash !== this.cachedOrdersHash) {
|
|
750
|
-
this.cachedOrders = processedOrdersData;
|
|
751
|
-
this.cachedOrdersHash = ordersHash;
|
|
752
|
-
this.ordersCacheInitialized = true;
|
|
753
|
-
this.orderSubscribers.forEach((ordCallback) => ordCallback(processedOrdersData));
|
|
754
|
-
}
|
|
755
|
-
if (accountHash !== this.cachedAccountHash) {
|
|
756
|
-
this.cachedAccount = accountState;
|
|
757
|
-
this.cachedAccountHash = accountHash;
|
|
758
|
-
this.accountSubscribers.forEach((accCallback) => accCallback(accountState));
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
catch (callbackError) {
|
|
762
|
-
this.deps.logger.error(ensureError(callbackError), this.getErrorContext('webData2 callback error', {
|
|
763
|
-
user: userAddress,
|
|
764
|
-
dataKeys: data ? Object.keys(data) : 'data is null/undefined',
|
|
765
|
-
hasClearinghouseState: data?.clearinghouseState !== undefined,
|
|
766
|
-
hasOpenOrders: data?.openOrders !== undefined,
|
|
767
|
-
hasPerpsAtOpenInterestCap: data?.perpsAtOpenInterestCap !== undefined,
|
|
768
|
-
}));
|
|
769
|
-
}
|
|
770
|
-
})
|
|
771
|
-
.then((subscription) => {
|
|
772
|
-
this.webData3Subscriptions.set(dexName, subscription);
|
|
773
|
-
this.deps.debugLogger.log('webData2 subscription established for main DEX only');
|
|
774
|
-
resolve();
|
|
775
|
-
})
|
|
776
|
-
.catch((subscribeError) => {
|
|
777
|
-
this.deps.logger.error(ensureError(subscribeError), this.getErrorContext('createUserDataSubscription (webData2)', {
|
|
778
|
-
dex: dexName,
|
|
779
|
-
}));
|
|
780
|
-
reject(ensureError(subscribeError));
|
|
781
|
-
});
|
|
782
|
-
}
|
|
783
|
-
else {
|
|
784
|
-
// HIP-3 enabled: Use individual subscriptions for positions/orders/account
|
|
785
|
-
// webData3 is only used for OI caps extraction
|
|
786
|
-
// Determine which DEXs to subscribe to
|
|
787
|
-
const dexsToSubscribe = [
|
|
788
|
-
'', // Main DEX
|
|
789
|
-
...this.enabledDexs.filter((dex) => this.isDexEnabled(dex)),
|
|
790
|
-
];
|
|
791
|
-
// Track expected DEXs for synchronized notifications
|
|
792
|
-
// Clear previous tracking and set new expected DEXs
|
|
793
|
-
this.expectedDexs = new Set(dexsToSubscribe);
|
|
794
|
-
this.initializedDexs = new Set();
|
|
795
|
-
// Set up individual subscriptions for each DEX
|
|
796
|
-
const subscriptionPromises = [];
|
|
797
|
-
for (const currentDexName of dexsToSubscribe) {
|
|
798
|
-
// Set up clearinghouseState subscription for positions + account
|
|
799
|
-
subscriptionPromises.push(this.ensureClearinghouseStateSubscription(userAddress, currentDexName));
|
|
800
|
-
// Set up openOrders subscription for orders
|
|
801
|
-
subscriptionPromises.push(this.ensureOpenOrdersSubscription(userAddress, currentDexName));
|
|
802
|
-
}
|
|
803
|
-
// Also set up webData3 for OI caps only
|
|
804
|
-
const webData3Promise = subscriptionClient
|
|
805
|
-
.webData3({ user: userAddress }, (data) => {
|
|
806
|
-
try {
|
|
807
|
-
// webData3 is ONLY used for OI caps extraction
|
|
808
|
-
// Positions, orders, and account data come from individual subscriptions
|
|
809
|
-
const allOICaps = [];
|
|
810
|
-
data.perpDexStates.forEach((dexState, index) => {
|
|
811
|
-
// Map webData3 index to DEX name
|
|
812
|
-
// Index 0 = main DEX (null), Index 1+ = HIP-3 DEXs from discoveredDexNames
|
|
813
|
-
const dexIdentifier = index === 0 ? null : this.discoveredDexNames[index - 1];
|
|
814
|
-
// Skip unknown DEXs (not in discoveredDexNames) to prevent main DEX cache corruption
|
|
815
|
-
if (index > 0 && dexIdentifier === undefined) {
|
|
816
|
-
return; // Unknown DEX - skip to prevent misidentifying as main DEX
|
|
817
|
-
}
|
|
818
|
-
// Only process DEXs we care about (skip others silently)
|
|
819
|
-
if (!this.isDexEnabled(dexIdentifier ?? null)) {
|
|
820
|
-
return; // Skip this DEX - not enabled in our configuration
|
|
821
|
-
}
|
|
822
|
-
const currentDexNameInLoop = dexIdentifier ?? '';
|
|
823
|
-
const oiCaps = dexState.perpsAtOpenInterestCap || [];
|
|
824
|
-
// Add DEX prefix for HIP-3 symbols (e.g., "xyz:TSLA")
|
|
825
|
-
if (currentDexNameInLoop) {
|
|
826
|
-
allOICaps.push(...oiCaps.map((symbolName) => `${currentDexNameInLoop}:${symbolName}`));
|
|
827
|
-
}
|
|
828
|
-
else {
|
|
829
|
-
// Main DEX - no prefix needed
|
|
830
|
-
allOICaps.push(...oiCaps);
|
|
831
|
-
}
|
|
832
|
-
});
|
|
833
|
-
// Update OI caps cache and notify if changed
|
|
834
|
-
const oiCapsHash = [...allOICaps]
|
|
835
|
-
.sort((a, b) => a.localeCompare(b))
|
|
836
|
-
.join(',');
|
|
837
|
-
if (oiCapsHash !== this.cachedOICapsHash) {
|
|
838
|
-
this.cachedOICaps = allOICaps;
|
|
839
|
-
this.cachedOICapsHash = oiCapsHash;
|
|
840
|
-
this.oiCapsCacheInitialized = true;
|
|
841
|
-
// Notify all subscribers
|
|
842
|
-
this.oiCapSubscribers.forEach((oiCallback) => oiCallback(allOICaps));
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
catch (callbackError) {
|
|
846
|
-
this.deps.logger.error(ensureError(callbackError), this.getErrorContext('webData3 callback error', {
|
|
847
|
-
user: userAddress,
|
|
848
|
-
hasPerpDexStates: data?.perpDexStates !== undefined,
|
|
849
|
-
perpDexStatesLength: data?.perpDexStates?.length ?? 0,
|
|
850
|
-
}));
|
|
851
|
-
}
|
|
852
|
-
})
|
|
853
|
-
.then((sub) => {
|
|
854
|
-
this.webData3Subscriptions.set(dexName, sub);
|
|
855
|
-
this.deps.debugLogger.log(`webData3 subscription established for OI caps (main + HIP-3)`);
|
|
856
|
-
})
|
|
857
|
-
.catch((subscribeError) => {
|
|
858
|
-
this.deps.logger.error(ensureError(subscribeError), this.getErrorContext('createUserDataSubscription (webData3)', {
|
|
859
|
-
dex: dexName,
|
|
860
|
-
}));
|
|
861
|
-
throw subscribeError;
|
|
862
|
-
});
|
|
863
|
-
subscriptionPromises.push(webData3Promise);
|
|
864
|
-
// Wait for all subscriptions to be established
|
|
865
|
-
Promise.all(subscriptionPromises)
|
|
866
|
-
.then(() => {
|
|
867
|
-
this.deps.debugLogger.log(`HIP-3 user data subscriptions established for ${dexsToSubscribe.length} DEXs`);
|
|
868
|
-
resolve();
|
|
869
|
-
})
|
|
870
|
-
.catch((allError) => {
|
|
871
|
-
this.deps.logger.error(ensureError(allError), this.getErrorContext('createUserDataSubscription (HIP-3)', {
|
|
872
|
-
dexs: dexsToSubscribe,
|
|
873
|
-
}));
|
|
874
|
-
reject(ensureError(allError));
|
|
875
|
-
});
|
|
876
|
-
}
|
|
877
|
-
});
|
|
878
|
-
}
|
|
879
|
-
/**
|
|
880
|
-
* Ensure clearinghouseState subscription exists for a DEX
|
|
881
|
-
*
|
|
882
|
-
* @param userAddress - User address
|
|
883
|
-
* @param dexName - DEX name ('' for main)
|
|
884
|
-
*/
|
|
885
|
-
async ensureClearinghouseStateSubscription(userAddress, dexName) {
|
|
886
|
-
if (this.clearinghouseStateSubscriptions.has(dexName)) {
|
|
887
|
-
return; // Already subscribed
|
|
888
|
-
}
|
|
889
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
890
|
-
if (!subscriptionClient) {
|
|
891
|
-
throw new Error('Subscription client not available');
|
|
892
|
-
}
|
|
893
|
-
try {
|
|
894
|
-
const subscription = await subscriptionClient.clearinghouseState({
|
|
895
|
-
user: userAddress,
|
|
896
|
-
dex: dexName || undefined, // Empty string -> undefined for main DEX
|
|
897
|
-
}, (data) => {
|
|
898
|
-
const cacheKey = data.dex || '';
|
|
899
|
-
// Update caches and notify subscribers if we have positions/account subscribers
|
|
900
|
-
if (this.positionSubscriberCount > 0 ||
|
|
901
|
-
this.accountSubscriberCount > 0) {
|
|
902
|
-
// Process positions from clearinghouse state
|
|
903
|
-
const positions = data.clearinghouseState.assetPositions
|
|
904
|
-
.filter((assetPos) => assetPos.position.szi !== '0')
|
|
905
|
-
.map((assetPos) => adaptPositionFromSDK(assetPos));
|
|
906
|
-
// Get cached orders to preserve TP/SL data (prevents flickering)
|
|
907
|
-
// Orders are cached by openOrders subscription
|
|
908
|
-
const cachedOrdersForDex = this.dexOrdersCache.get(cacheKey) || [];
|
|
909
|
-
// Re-extract TP/SL from cached orders for the new positions
|
|
910
|
-
// This ensures TP/SL data persists across clearinghouseState updates
|
|
911
|
-
let positionsWithTPSL = positions;
|
|
912
|
-
if (cachedOrdersForDex.length > 0) {
|
|
913
|
-
const { tpslMap, tpslCountMap } = this.extractTPSLFromOrders([], positions, cachedOrdersForDex);
|
|
914
|
-
positionsWithTPSL = this.mergeTPSLIntoPositions(positions, tpslMap, tpslCountMap);
|
|
915
|
-
}
|
|
916
|
-
// Update account state
|
|
917
|
-
const accountState = adaptAccountStateFromSDK(data.clearinghouseState, undefined);
|
|
918
|
-
// Update caches
|
|
919
|
-
this.dexPositionsCache.set(cacheKey, positionsWithTPSL);
|
|
920
|
-
this.dexAccountCache.set(cacheKey, accountState);
|
|
921
|
-
// Mark this DEX as initialized (has sent first data)
|
|
922
|
-
this.initializedDexs.add(cacheKey);
|
|
923
|
-
// Trigger aggregation and notify subscribers
|
|
924
|
-
this.aggregateAndNotifySubscribers();
|
|
925
|
-
}
|
|
926
|
-
});
|
|
927
|
-
this.clearinghouseStateSubscriptions.set(dexName, subscription);
|
|
928
|
-
this.deps.debugLogger.log(`clearinghouseState subscription established for DEX: ${dexName || 'main'}`);
|
|
929
|
-
}
|
|
930
|
-
catch (subscribeError) {
|
|
931
|
-
// Remove this DEX from expected set so it doesn't block notifications for other DEXs
|
|
932
|
-
this.expectedDexs.delete(dexName);
|
|
933
|
-
this.deps.logger.error(ensureError(subscribeError), this.getErrorContext('ensureClearinghouseStateSubscription', {
|
|
934
|
-
dex: dexName,
|
|
935
|
-
}));
|
|
936
|
-
throw subscribeError;
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
/**
|
|
940
|
-
* Ensure openOrders subscription exists for a DEX
|
|
941
|
-
*
|
|
942
|
-
* @param userAddress - User address
|
|
943
|
-
* @param dexName - DEX name ('' for main)
|
|
944
|
-
*/
|
|
945
|
-
async ensureOpenOrdersSubscription(userAddress, dexName) {
|
|
946
|
-
if (this.openOrdersSubscriptions.has(dexName)) {
|
|
947
|
-
return; // Already subscribed
|
|
948
|
-
}
|
|
949
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
950
|
-
if (!subscriptionClient) {
|
|
951
|
-
throw new Error('Subscription client not available');
|
|
952
|
-
}
|
|
953
|
-
try {
|
|
954
|
-
const subscription = await subscriptionClient.openOrders({
|
|
955
|
-
user: userAddress,
|
|
956
|
-
dex: dexName || undefined, // Empty string -> undefined for main DEX
|
|
957
|
-
}, (data) => {
|
|
958
|
-
const cacheKey = data.dex || '';
|
|
959
|
-
// Update caches and notify subscribers if we have order subscribers
|
|
960
|
-
if (this.orderSubscriberCount > 0 ||
|
|
961
|
-
this.positionSubscriberCount > 0) {
|
|
962
|
-
// Get cached positions for TP/SL processing
|
|
963
|
-
const cachedPositionsForDex = this.dexPositionsCache.get(cacheKey) || [];
|
|
964
|
-
// Extract TP/SL and process orders
|
|
965
|
-
const { tpslMap, tpslCountMap, processedOrders: ordersProcessed, } = this.extractTPSLFromOrders(data.orders, cachedPositionsForDex);
|
|
966
|
-
// Update orders cache with processed orders
|
|
967
|
-
this.dexOrdersCache.set(cacheKey, ordersProcessed);
|
|
968
|
-
// Update positions with TP/SL if we have positions
|
|
969
|
-
if (cachedPositionsForDex.length > 0) {
|
|
970
|
-
const positionsWithTPSL = this.mergeTPSLIntoPositions(cachedPositionsForDex, tpslMap, tpslCountMap);
|
|
971
|
-
this.dexPositionsCache.set(cacheKey, positionsWithTPSL);
|
|
972
|
-
}
|
|
973
|
-
// Mark this DEX as initialized (has sent first data)
|
|
974
|
-
this.initializedDexs.add(cacheKey);
|
|
975
|
-
// Trigger aggregation and notify subscribers
|
|
976
|
-
this.aggregateAndNotifySubscribers();
|
|
977
|
-
}
|
|
978
|
-
});
|
|
979
|
-
this.openOrdersSubscriptions.set(dexName, subscription);
|
|
980
|
-
this.deps.debugLogger.log(`openOrders subscription established for DEX: ${dexName || 'main'}`);
|
|
981
|
-
}
|
|
982
|
-
catch (subscribeError) {
|
|
983
|
-
// Remove this DEX from expected set so it doesn't block notifications for other DEXs
|
|
984
|
-
this.expectedDexs.delete(dexName);
|
|
985
|
-
this.deps.logger.error(ensureError(subscribeError), this.getErrorContext('ensureOpenOrdersSubscription', {
|
|
986
|
-
dex: dexName,
|
|
987
|
-
}));
|
|
988
|
-
throw subscribeError;
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
/**
|
|
992
|
-
* Aggregate data from all DEX caches and notify subscribers if data changed
|
|
993
|
-
* Used by both webData3 callback and fallback subscription callbacks
|
|
994
|
-
*/
|
|
995
|
-
aggregateAndNotifySubscribers() {
|
|
996
|
-
// Wait for all expected DEXs to send initial data before notifying
|
|
997
|
-
// This ensures positions from all DEXs appear simultaneously
|
|
998
|
-
if (this.expectedDexs.size > 0) {
|
|
999
|
-
const allDexsInitialized = Array.from(this.expectedDexs).every((dex) => this.initializedDexs.has(dex));
|
|
1000
|
-
if (!allDexsInitialized) {
|
|
1001
|
-
this.deps.debugLogger.log('Waiting for all DEXs to send initial data', {
|
|
1002
|
-
expected: Array.from(this.expectedDexs),
|
|
1003
|
-
initialized: Array.from(this.initializedDexs),
|
|
1004
|
-
});
|
|
1005
|
-
return; // Don't notify yet - waiting for more DEXs
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
// Aggregate data from all DEX caches
|
|
1009
|
-
// Order: Main DEX (crypto perps) first, then HIP-3 DEXs
|
|
1010
|
-
const mainDexPositions = this.dexPositionsCache.get('') || [];
|
|
1011
|
-
const hip3DexPositions = Array.from(this.dexPositionsCache.entries())
|
|
1012
|
-
.filter(([key]) => key !== '')
|
|
1013
|
-
.flatMap(([, positionsForDex]) => positionsForDex);
|
|
1014
|
-
const aggregatedPositions = [...mainDexPositions, ...hip3DexPositions];
|
|
1015
|
-
const mainDexOrders = this.dexOrdersCache.get('') || [];
|
|
1016
|
-
const hip3DexOrders = Array.from(this.dexOrdersCache.entries())
|
|
1017
|
-
.filter(([key]) => key !== '')
|
|
1018
|
-
.flatMap(([, ordersForDex]) => ordersForDex);
|
|
1019
|
-
const aggregatedOrders = [...mainDexOrders, ...hip3DexOrders];
|
|
1020
|
-
const aggregatedAccount = this.aggregateAccountStates();
|
|
1021
|
-
// Check if aggregated data changed using fast hash comparison
|
|
1022
|
-
const positionsHash = this.hashPositions(aggregatedPositions);
|
|
1023
|
-
const ordersHash = this.hashOrders(aggregatedOrders);
|
|
1024
|
-
const accountHash = this.hashAccountState(aggregatedAccount);
|
|
1025
|
-
const positionsChanged = positionsHash !== this.cachedPositionsHash;
|
|
1026
|
-
const ordersChanged = ordersHash !== this.cachedOrdersHash;
|
|
1027
|
-
const accountChanged = accountHash !== this.cachedAccountHash;
|
|
1028
|
-
// Only notify subscribers if aggregated data changed
|
|
1029
|
-
if (positionsChanged) {
|
|
1030
|
-
this.cachedPositions = aggregatedPositions;
|
|
1031
|
-
this.cachedPositionsHash = positionsHash;
|
|
1032
|
-
this.positionsCacheInitialized = true; // Mark cache as initialized
|
|
1033
|
-
this.positionSubscribers.forEach((posCallback) => {
|
|
1034
|
-
posCallback(aggregatedPositions);
|
|
1035
|
-
});
|
|
1036
|
-
}
|
|
1037
|
-
if (ordersChanged) {
|
|
1038
|
-
this.cachedOrders = aggregatedOrders;
|
|
1039
|
-
this.cachedOrdersHash = ordersHash;
|
|
1040
|
-
this.ordersCacheInitialized = true; // Mark cache as initialized
|
|
1041
|
-
this.orderSubscribers.forEach((ordCallback) => {
|
|
1042
|
-
ordCallback(aggregatedOrders);
|
|
1043
|
-
});
|
|
1044
|
-
}
|
|
1045
|
-
if (accountChanged) {
|
|
1046
|
-
this.cachedAccount = aggregatedAccount;
|
|
1047
|
-
this.cachedAccountHash = accountHash;
|
|
1048
|
-
this.accountSubscribers.forEach((accCallback) => {
|
|
1049
|
-
accCallback(aggregatedAccount);
|
|
1050
|
-
});
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
/**
|
|
1054
|
-
* Clean up webData3 subscription when no longer needed
|
|
1055
|
-
*/
|
|
1056
|
-
cleanupSharedWebData3ISubscription() {
|
|
1057
|
-
const totalSubscribers = this.positionSubscriberCount +
|
|
1058
|
-
this.orderSubscriberCount +
|
|
1059
|
-
this.accountSubscriberCount +
|
|
1060
|
-
this.oiCapSubscriberCount;
|
|
1061
|
-
if (totalSubscribers <= 0) {
|
|
1062
|
-
// Cleanup webData3 subscription (covers all DEXs)
|
|
1063
|
-
if (this.webData3Subscriptions.size > 0) {
|
|
1064
|
-
this.webData3Subscriptions.forEach((subscription, dexNameKey) => {
|
|
1065
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1066
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('cleanupSharedWebData3ISubscription.webData3', {
|
|
1067
|
-
dex: dexNameKey,
|
|
1068
|
-
}));
|
|
1069
|
-
});
|
|
1070
|
-
});
|
|
1071
|
-
this.webData3Subscriptions.clear();
|
|
1072
|
-
this.webData3SubscriptionPromise = undefined;
|
|
1073
|
-
}
|
|
1074
|
-
// Cleanup individual subscriptions (clearinghouseState + openOrders)
|
|
1075
|
-
if (this.clearinghouseStateSubscriptions.size > 0) {
|
|
1076
|
-
this.clearinghouseStateSubscriptions.forEach((subscription, dexNameKey) => {
|
|
1077
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1078
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('cleanupSharedWebData3ISubscription.clearinghouseState', {
|
|
1079
|
-
dex: dexNameKey,
|
|
1080
|
-
}));
|
|
1081
|
-
});
|
|
1082
|
-
});
|
|
1083
|
-
this.clearinghouseStateSubscriptions.clear();
|
|
1084
|
-
}
|
|
1085
|
-
if (this.openOrdersSubscriptions.size > 0) {
|
|
1086
|
-
this.openOrdersSubscriptions.forEach((subscription, dexNameKey) => {
|
|
1087
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1088
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('cleanupSharedWebData3ISubscription.openOrders', {
|
|
1089
|
-
dex: dexNameKey,
|
|
1090
|
-
}));
|
|
1091
|
-
});
|
|
1092
|
-
});
|
|
1093
|
-
this.openOrdersSubscriptions.clear();
|
|
1094
|
-
}
|
|
1095
|
-
// Clear subscriber counts
|
|
1096
|
-
this.positionSubscriberCount = 0;
|
|
1097
|
-
this.orderSubscriberCount = 0;
|
|
1098
|
-
this.accountSubscriberCount = 0;
|
|
1099
|
-
this.oiCapSubscriberCount = 0;
|
|
1100
|
-
// Clear per-DEX caches
|
|
1101
|
-
this.dexPositionsCache.clear();
|
|
1102
|
-
this.dexOrdersCache.clear();
|
|
1103
|
-
this.dexAccountCache.clear();
|
|
1104
|
-
// Clear DEX tracking for synchronized notifications
|
|
1105
|
-
this.expectedDexs.clear();
|
|
1106
|
-
this.initializedDexs.clear();
|
|
1107
|
-
// Clear aggregated caches
|
|
1108
|
-
this.cachedPositions = null;
|
|
1109
|
-
this.cachedOrders = null;
|
|
1110
|
-
this.cachedAccount = null;
|
|
1111
|
-
this.ordersCacheInitialized = false; // Reset cache initialization flag
|
|
1112
|
-
this.positionsCacheInitialized = false; // Reset cache initialization flag
|
|
1113
|
-
// Clear hash caches
|
|
1114
|
-
this.cachedPositionsHash = '';
|
|
1115
|
-
this.cachedOrdersHash = '';
|
|
1116
|
-
this.cachedAccountHash = '';
|
|
1117
|
-
this.deps.debugLogger.log('All multi-DEX subscriptions cleaned up (webData2/3 + individual subscriptions)');
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
/**
|
|
1121
|
-
* Subscribe to live position updates with TP/SL data
|
|
1122
|
-
*
|
|
1123
|
-
* @param params - Subscription parameters
|
|
1124
|
-
* @returns Cleanup function
|
|
1125
|
-
*/
|
|
1126
|
-
subscribeToPositions(params) {
|
|
1127
|
-
const { callback, accountId } = params;
|
|
1128
|
-
const unsubscribe = this.createSubscription(this.positionSubscribers, callback);
|
|
1129
|
-
// Increment position subscriber count
|
|
1130
|
-
this.positionSubscriberCount++;
|
|
1131
|
-
// Immediately provide cached data if available
|
|
1132
|
-
if (this.cachedPositions) {
|
|
1133
|
-
callback(this.cachedPositions);
|
|
1134
|
-
}
|
|
1135
|
-
// Ensure shared subscription is active
|
|
1136
|
-
this.ensureSharedWebData3Subscription(accountId).catch((subError) => {
|
|
1137
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToPositions'));
|
|
1138
|
-
});
|
|
1139
|
-
return () => {
|
|
1140
|
-
unsubscribe();
|
|
1141
|
-
this.positionSubscriberCount--;
|
|
1142
|
-
this.cleanupSharedWebData3ISubscription();
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Subscribe to open interest cap updates
|
|
1147
|
-
* OI caps are extracted from webData2 subscription (zero additional overhead)
|
|
1148
|
-
*
|
|
1149
|
-
* @param params - Subscription parameters
|
|
1150
|
-
* @returns Cleanup function
|
|
1151
|
-
*/
|
|
1152
|
-
subscribeToOICaps(params) {
|
|
1153
|
-
const { callback, accountId } = params;
|
|
1154
|
-
// Create subscription
|
|
1155
|
-
const unsubscribe = this.createSubscription(this.oiCapSubscribers, callback);
|
|
1156
|
-
// Increment OI cap subscriber count
|
|
1157
|
-
this.oiCapSubscriberCount++;
|
|
1158
|
-
// Immediately provide cached data if available
|
|
1159
|
-
if (this.cachedOICaps) {
|
|
1160
|
-
callback(this.cachedOICaps);
|
|
1161
|
-
}
|
|
1162
|
-
// Ensure webData3 subscription is active (OI caps come from webData3)
|
|
1163
|
-
this.ensureSharedWebData3Subscription(accountId).catch((subError) => {
|
|
1164
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToOICaps'));
|
|
1165
|
-
});
|
|
1166
|
-
return () => {
|
|
1167
|
-
unsubscribe();
|
|
1168
|
-
this.oiCapSubscriberCount--;
|
|
1169
|
-
this.cleanupSharedWebData3ISubscription();
|
|
1170
|
-
};
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Check if OI caps cache has been initialized
|
|
1174
|
-
* Useful for preventing UI flashing before first data arrives
|
|
1175
|
-
*
|
|
1176
|
-
* @returns True if cache is initialized
|
|
1177
|
-
*/
|
|
1178
|
-
isOICapsCacheInitialized() {
|
|
1179
|
-
return this.oiCapsCacheInitialized;
|
|
1180
|
-
}
|
|
1181
|
-
/**
|
|
1182
|
-
* Subscribe to live order fill updates
|
|
1183
|
-
* Shares subscriptions per accountId to avoid duplicate WebSocket connections
|
|
1184
|
-
*
|
|
1185
|
-
* @param params - Subscription parameters
|
|
1186
|
-
* @returns Cleanup function
|
|
1187
|
-
*/
|
|
1188
|
-
subscribeToOrderFills(params) {
|
|
1189
|
-
const { callback, accountId } = params;
|
|
1190
|
-
// Normalize accountId: undefined -> 'default' for Map key
|
|
1191
|
-
const normalizedAccountId = accountId ?? 'default';
|
|
1192
|
-
const unsubscribe = this.createSubscription(this.orderFillSubscribers, callback, normalizedAccountId);
|
|
1193
|
-
// Ensure subscription is established for this accountId
|
|
1194
|
-
this.ensureOrderFillISubscription(accountId).catch((subError) => {
|
|
1195
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToOrderFills'));
|
|
1196
|
-
});
|
|
1197
|
-
return () => {
|
|
1198
|
-
unsubscribe();
|
|
1199
|
-
// If no more subscribers for this accountId, clean up subscription
|
|
1200
|
-
const subscribers = this.orderFillSubscribers.get(normalizedAccountId);
|
|
1201
|
-
if (!subscribers || subscribers.size === 0) {
|
|
1202
|
-
const subscription = this.orderFillSubscriptions.get(normalizedAccountId);
|
|
1203
|
-
if (subscription) {
|
|
1204
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1205
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('subscribeToOrderFills.unsubscribe'));
|
|
1206
|
-
});
|
|
1207
|
-
this.orderFillSubscriptions.delete(normalizedAccountId);
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
};
|
|
1211
|
-
}
|
|
1212
|
-
/**
|
|
1213
|
-
* Ensure order fill subscription is active for the given accountId
|
|
1214
|
-
* Shares subscription across all callbacks for the same accountId
|
|
1215
|
-
*
|
|
1216
|
-
* @param accountId - Optional account ID
|
|
1217
|
-
*/
|
|
1218
|
-
async ensureOrderFillISubscription(accountId) {
|
|
1219
|
-
// Normalize accountId: undefined -> 'default' for Map key
|
|
1220
|
-
const normalizedAccountId = accountId ?? 'default';
|
|
1221
|
-
// If subscription already exists, no need to create another
|
|
1222
|
-
if (this.orderFillSubscriptions.has(normalizedAccountId)) {
|
|
1223
|
-
return;
|
|
1224
|
-
}
|
|
1225
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1226
|
-
if (!subscriptionClient) {
|
|
1227
|
-
await this.clientService.ensureSubscriptionClient(this.walletService.createWalletAdapter());
|
|
1228
|
-
const client = this.clientService.getSubscriptionClient();
|
|
1229
|
-
if (!client) {
|
|
1230
|
-
throw new Error('SubscriptionClient not available');
|
|
1231
|
-
}
|
|
1232
|
-
return this.ensureOrderFillISubscription(accountId);
|
|
1233
|
-
}
|
|
1234
|
-
const userAddress = await this.walletService.getUserAddressWithDefault(accountId);
|
|
1235
|
-
// userFills returns a Promise<ISubscription>, need to await it
|
|
1236
|
-
const subscription = await subscriptionClient.userFills({ user: userAddress }, (data) => {
|
|
1237
|
-
const orderFills = data.fills.map((fill) => ({
|
|
1238
|
-
orderId: fill.oid.toString(),
|
|
1239
|
-
symbol: fill.coin,
|
|
1240
|
-
side: fill.side,
|
|
1241
|
-
size: fill.sz,
|
|
1242
|
-
price: fill.px,
|
|
1243
|
-
fee: fill.fee,
|
|
1244
|
-
timestamp: fill.time,
|
|
1245
|
-
pnl: fill.closedPnl,
|
|
1246
|
-
direction: fill.dir,
|
|
1247
|
-
feeToken: fill.feeToken,
|
|
1248
|
-
startPosition: fill.startPosition,
|
|
1249
|
-
liquidation: fill.liquidation
|
|
1250
|
-
? {
|
|
1251
|
-
liquidatedUser: fill.liquidation.liquidatedUser,
|
|
1252
|
-
markPx: fill.liquidation.markPx,
|
|
1253
|
-
method: fill.liquidation.method,
|
|
1254
|
-
}
|
|
1255
|
-
: undefined,
|
|
1256
|
-
}));
|
|
1257
|
-
// Distribute to all callbacks for this accountId
|
|
1258
|
-
const subscribers = this.orderFillSubscribers.get(normalizedAccountId);
|
|
1259
|
-
if (subscribers) {
|
|
1260
|
-
subscribers.forEach((fillCallback) => {
|
|
1261
|
-
fillCallback(orderFills, data.isSnapshot);
|
|
1262
|
-
});
|
|
1263
|
-
}
|
|
1264
|
-
});
|
|
1265
|
-
this.orderFillSubscriptions.set(normalizedAccountId, subscription);
|
|
1266
|
-
}
|
|
1267
|
-
/**
|
|
1268
|
-
* Subscribe to live order updates
|
|
1269
|
-
* Uses the shared webData2 subscription to avoid duplicate connections
|
|
1270
|
-
*
|
|
1271
|
-
* @param params - Subscription parameters
|
|
1272
|
-
* @returns Cleanup function
|
|
1273
|
-
*/
|
|
1274
|
-
subscribeToOrders(params) {
|
|
1275
|
-
const { callback, accountId } = params;
|
|
1276
|
-
const unsubscribe = this.createSubscription(this.orderSubscribers, callback);
|
|
1277
|
-
// Increment order subscriber count
|
|
1278
|
-
this.orderSubscriberCount++;
|
|
1279
|
-
// Immediately provide cached data if available
|
|
1280
|
-
if (this.cachedOrders) {
|
|
1281
|
-
callback(this.cachedOrders);
|
|
1282
|
-
}
|
|
1283
|
-
// Ensure shared subscription is active
|
|
1284
|
-
this.ensureSharedWebData3Subscription(accountId).catch((subError) => {
|
|
1285
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToOrders'));
|
|
1286
|
-
});
|
|
1287
|
-
return () => {
|
|
1288
|
-
unsubscribe();
|
|
1289
|
-
this.orderSubscriberCount--;
|
|
1290
|
-
this.cleanupSharedWebData3ISubscription();
|
|
1291
|
-
};
|
|
1292
|
-
}
|
|
1293
|
-
/**
|
|
1294
|
-
* Subscribe to live account updates
|
|
1295
|
-
* Uses the shared webData2 subscription to avoid duplicate connections
|
|
1296
|
-
*
|
|
1297
|
-
* @param params - Subscription parameters
|
|
1298
|
-
* @returns Cleanup function
|
|
1299
|
-
*/
|
|
1300
|
-
subscribeToAccount(params) {
|
|
1301
|
-
const { callback, accountId } = params;
|
|
1302
|
-
const unsubscribe = this.createSubscription(this.accountSubscribers, callback);
|
|
1303
|
-
// Increment account subscriber count
|
|
1304
|
-
this.accountSubscriberCount++;
|
|
1305
|
-
// Immediately provide cached data if available
|
|
1306
|
-
if (this.cachedAccount) {
|
|
1307
|
-
callback(this.cachedAccount);
|
|
1308
|
-
}
|
|
1309
|
-
// Ensure shared subscription is active (reuses existing connection)
|
|
1310
|
-
this.ensureSharedWebData3Subscription(accountId).catch((subError) => {
|
|
1311
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToAccount'));
|
|
1312
|
-
});
|
|
1313
|
-
return () => {
|
|
1314
|
-
unsubscribe();
|
|
1315
|
-
this.accountSubscriberCount--;
|
|
1316
|
-
this.cleanupSharedWebData3ISubscription();
|
|
1317
|
-
};
|
|
1318
|
-
}
|
|
1319
|
-
/**
|
|
1320
|
-
* Check if orders cache has been initialized from WebSocket
|
|
1321
|
-
*
|
|
1322
|
-
* @returns true if WebSocket has sent at least one update, false otherwise
|
|
1323
|
-
*/
|
|
1324
|
-
isOrdersCacheInitialized() {
|
|
1325
|
-
return this.ordersCacheInitialized;
|
|
1326
|
-
}
|
|
1327
|
-
/**
|
|
1328
|
-
* Check if positions cache has been initialized from WebSocket
|
|
1329
|
-
*
|
|
1330
|
-
* @returns true if WebSocket has sent at least one update, false otherwise
|
|
1331
|
-
*/
|
|
1332
|
-
isPositionsCacheInitialized() {
|
|
1333
|
-
return this.positionsCacheInitialized;
|
|
1334
|
-
}
|
|
1335
|
-
/**
|
|
1336
|
-
* Get cached positions from WebSocket subscription
|
|
1337
|
-
*
|
|
1338
|
-
* @returns Cached positions array, or null if not initialized
|
|
1339
|
-
*/
|
|
1340
|
-
getCachedPositions() {
|
|
1341
|
-
return this.cachedPositions;
|
|
1342
|
-
}
|
|
1343
|
-
/**
|
|
1344
|
-
* Get cached orders from WebSocket subscription
|
|
1345
|
-
*
|
|
1346
|
-
* @returns Cached orders array, or null if not initialized
|
|
1347
|
-
*/
|
|
1348
|
-
getCachedOrders() {
|
|
1349
|
-
return this.cachedOrders;
|
|
1350
|
-
}
|
|
1351
|
-
/**
|
|
1352
|
-
* Create subscription with common error handling
|
|
1353
|
-
*
|
|
1354
|
-
* @param subscribers - Subscriber collection
|
|
1355
|
-
* @param callback - Callback to add
|
|
1356
|
-
* @param key - Optional key for Map-based collections
|
|
1357
|
-
* @returns Unsubscribe function
|
|
1358
|
-
*/
|
|
1359
|
-
createSubscription(subscribers, callback, key) {
|
|
1360
|
-
if (subscribers instanceof Map && key) {
|
|
1361
|
-
if (!subscribers.has(key)) {
|
|
1362
|
-
subscribers.set(key, new Set());
|
|
1363
|
-
}
|
|
1364
|
-
subscribers.get(key)?.add(callback);
|
|
1365
|
-
}
|
|
1366
|
-
else if (subscribers instanceof Set) {
|
|
1367
|
-
subscribers.add(callback);
|
|
1368
|
-
}
|
|
1369
|
-
return () => {
|
|
1370
|
-
if (subscribers instanceof Map && key) {
|
|
1371
|
-
const set = subscribers.get(key);
|
|
1372
|
-
set?.delete(callback);
|
|
1373
|
-
if (set?.size === 0) {
|
|
1374
|
-
subscribers.delete(key);
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
else if (subscribers instanceof Set) {
|
|
1378
|
-
subscribers.delete(callback);
|
|
1379
|
-
}
|
|
1380
|
-
};
|
|
1381
|
-
}
|
|
1382
|
-
/**
|
|
1383
|
-
* Helper function to create consolidated price updates with 24h change calculation
|
|
1384
|
-
*
|
|
1385
|
-
* @param symbol - Asset symbol
|
|
1386
|
-
* @param price - Current price
|
|
1387
|
-
* @returns Price update object
|
|
1388
|
-
*/
|
|
1389
|
-
createPriceUpdate(symbol, price) {
|
|
1390
|
-
const marketData = this.marketDataCache.get(symbol);
|
|
1391
|
-
const orderBookData = this.orderBookCache.get(symbol);
|
|
1392
|
-
const currentPrice = parseFloat(price);
|
|
1393
|
-
let percentChange24h;
|
|
1394
|
-
if (marketData?.prevDayPx !== undefined) {
|
|
1395
|
-
const change = ((currentPrice - marketData.prevDayPx) / marketData.prevDayPx) * 100;
|
|
1396
|
-
percentChange24h = change.toFixed(2);
|
|
1397
|
-
}
|
|
1398
|
-
// Check if any subscriber for this symbol wants market data
|
|
1399
|
-
const hasMarketDataSubscribers = this.marketDataSubscribers.has(symbol) &&
|
|
1400
|
-
(this.marketDataSubscribers.get(symbol)?.size ?? 0) > 0;
|
|
1401
|
-
const priceUpdate = {
|
|
1402
|
-
symbol,
|
|
1403
|
-
price, // This is the mid price from allMids
|
|
1404
|
-
timestamp: Date.now(),
|
|
1405
|
-
percentChange24h,
|
|
1406
|
-
// Add mark price from activeAssetCtx
|
|
1407
|
-
markPrice: marketData?.oraclePrice
|
|
1408
|
-
? marketData.oraclePrice.toString()
|
|
1409
|
-
: undefined,
|
|
1410
|
-
// Add order book data if available
|
|
1411
|
-
bestBid: orderBookData?.bestBid,
|
|
1412
|
-
bestAsk: orderBookData?.bestAsk,
|
|
1413
|
-
spread: orderBookData?.spread,
|
|
1414
|
-
// Always include funding when available (don't default to 0, preserve undefined)
|
|
1415
|
-
funding: marketData?.funding,
|
|
1416
|
-
// Add market data only if requested by at least one subscriber
|
|
1417
|
-
openInterest: hasMarketDataSubscribers
|
|
1418
|
-
? marketData?.openInterest
|
|
1419
|
-
: undefined,
|
|
1420
|
-
volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,
|
|
1421
|
-
};
|
|
1422
|
-
return priceUpdate;
|
|
1423
|
-
}
|
|
1424
|
-
/**
|
|
1425
|
-
* Ensure global allMids subscription is active (singleton pattern)
|
|
1426
|
-
*/
|
|
1427
|
-
ensureGlobalAllMidsSubscription() {
|
|
1428
|
-
// Check both the subscription AND the promise to prevent race conditions
|
|
1429
|
-
if (this.globalAllMidsSubscription || this.globalAllMidsPromise) {
|
|
1430
|
-
return;
|
|
1431
|
-
}
|
|
1432
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1433
|
-
if (!subscriptionClient) {
|
|
1434
|
-
return;
|
|
1435
|
-
}
|
|
1436
|
-
// Track WebSocket metrics
|
|
1437
|
-
const wsMetrics = {
|
|
1438
|
-
messagesReceived: 0,
|
|
1439
|
-
lastMessageTime: Date.now(),
|
|
1440
|
-
reconnectCount: 0,
|
|
1441
|
-
startTime: Date.now(),
|
|
1442
|
-
};
|
|
1443
|
-
// Store the promise immediately to prevent duplicate calls
|
|
1444
|
-
this.globalAllMidsPromise = subscriptionClient
|
|
1445
|
-
.allMids((data) => {
|
|
1446
|
-
wsMetrics.messagesReceived++;
|
|
1447
|
-
wsMetrics.lastMessageTime = Date.now();
|
|
1448
|
-
// Initialize cache if needed
|
|
1449
|
-
this.cachedPriceData ?? (this.cachedPriceData = new Map());
|
|
1450
|
-
const subscribedSymbols = new Set();
|
|
1451
|
-
// Collect all symbols that have subscribers
|
|
1452
|
-
for (const [symbol, subscriberSet] of this.priceSubscribers.entries()) {
|
|
1453
|
-
if (subscriberSet.size > 0) {
|
|
1454
|
-
subscribedSymbols.add(symbol);
|
|
1455
|
-
}
|
|
1456
|
-
}
|
|
1457
|
-
// Track if any subscribed symbol was updated
|
|
1458
|
-
let hasUpdates = false;
|
|
1459
|
-
// Only process symbols that are actually subscribed to
|
|
1460
|
-
for (const symbol in data.mids) {
|
|
1461
|
-
// Skip if nobody is subscribed to this symbol
|
|
1462
|
-
if (!subscribedSymbols.has(symbol)) {
|
|
1463
|
-
continue;
|
|
1464
|
-
}
|
|
1465
|
-
const priceValue = data.mids[symbol].toString();
|
|
1466
|
-
const cachedPrice = this.cachedPriceData.get(symbol);
|
|
1467
|
-
// Skip if price hasn't changed
|
|
1468
|
-
if (cachedPrice?.price === priceValue) {
|
|
1469
|
-
continue;
|
|
1470
|
-
}
|
|
1471
|
-
// Price changed or new symbol - update cache
|
|
1472
|
-
const priceUpdate = this.createPriceUpdate(symbol, priceValue);
|
|
1473
|
-
this.cachedPriceData.set(symbol, priceUpdate);
|
|
1474
|
-
hasUpdates = true;
|
|
1475
|
-
}
|
|
1476
|
-
// Only notify subscribers if we actually have updates
|
|
1477
|
-
// This prevents unnecessary React re-renders when prices haven't changed
|
|
1478
|
-
if (hasUpdates) {
|
|
1479
|
-
this.notifyAllPriceSubscribers();
|
|
1480
|
-
}
|
|
1481
|
-
})
|
|
1482
|
-
.then((sub) => {
|
|
1483
|
-
this.globalAllMidsSubscription = sub;
|
|
1484
|
-
this.deps.debugLogger.log('HyperLiquid: Global allMids subscription established');
|
|
1485
|
-
// Notify existing subscribers with any cached data now that subscription is established
|
|
1486
|
-
if (this.cachedPriceData && this.cachedPriceData.size > 0) {
|
|
1487
|
-
this.notifyAllPriceSubscribers();
|
|
1488
|
-
}
|
|
1489
|
-
})
|
|
1490
|
-
.catch((subError) => {
|
|
1491
|
-
// Clear the promise on error so it can be retried
|
|
1492
|
-
this.globalAllMidsPromise = undefined;
|
|
1493
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('ensureGlobalAllMidsSubscription'));
|
|
1494
|
-
});
|
|
1495
|
-
}
|
|
1496
|
-
/**
|
|
1497
|
-
* Ensure activeAssetCtx subscription for specific symbol (with reference counting)
|
|
1498
|
-
*
|
|
1499
|
-
* @param symbol - Asset symbol
|
|
1500
|
-
*/
|
|
1501
|
-
ensureActiveAssetSubscription(symbol) {
|
|
1502
|
-
// Increment subscriber count
|
|
1503
|
-
const currentCount = this.symbolSubscriberCounts.get(symbol) || 0;
|
|
1504
|
-
this.symbolSubscriberCounts.set(symbol, currentCount + 1);
|
|
1505
|
-
// If subscription already exists, just return
|
|
1506
|
-
if (this.globalActiveAssetSubscriptions.has(symbol)) {
|
|
1507
|
-
return;
|
|
1508
|
-
}
|
|
1509
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1510
|
-
if (!subscriptionClient) {
|
|
1511
|
-
return;
|
|
1512
|
-
}
|
|
1513
|
-
// Track metrics for this subscription
|
|
1514
|
-
const subscriptionMetrics = {
|
|
1515
|
-
messagesReceived: 0,
|
|
1516
|
-
startTime: Date.now(),
|
|
1517
|
-
};
|
|
1518
|
-
subscriptionClient
|
|
1519
|
-
.activeAssetCtx({ coin: symbol }, (data) => {
|
|
1520
|
-
subscriptionMetrics.messagesReceived++;
|
|
1521
|
-
if (data.coin === symbol && data.ctx) {
|
|
1522
|
-
// Type guard using SDK types: check if this is perps (has funding) or spot (no funding)
|
|
1523
|
-
const isPerpsContext = (event) => 'funding' in event.ctx &&
|
|
1524
|
-
'openInterest' in event.ctx &&
|
|
1525
|
-
'oraclePx' in event.ctx;
|
|
1526
|
-
const { ctx } = data;
|
|
1527
|
-
// Cache market data for consolidation with price updates
|
|
1528
|
-
const ctxPrice = ctx.midPx || ctx.markPx;
|
|
1529
|
-
const openInterestUSD = isPerpsContext(data) && ctxPrice
|
|
1530
|
-
? calculateOpenInterestUSD(data.ctx.openInterest, ctxPrice)
|
|
1531
|
-
: NaN;
|
|
1532
|
-
const marketDataEntry = {
|
|
1533
|
-
prevDayPx: ctx.prevDayPx
|
|
1534
|
-
? parseFloat(ctx.prevDayPx.toString())
|
|
1535
|
-
: undefined,
|
|
1536
|
-
// Cache funding rate from activeAssetCtx for real-time updates
|
|
1537
|
-
// SDK defines funding as string (not nullable) in ActiveAssetCtxEvent
|
|
1538
|
-
funding: isPerpsContext(data)
|
|
1539
|
-
? parseFloat(data.ctx.funding.toString())
|
|
1540
|
-
: undefined,
|
|
1541
|
-
openInterest: !isNaN(openInterestUSD)
|
|
1542
|
-
? openInterestUSD
|
|
1543
|
-
: undefined,
|
|
1544
|
-
volume24h: ctx.dayNtlVlm
|
|
1545
|
-
? parseFloat(ctx.dayNtlVlm.toString())
|
|
1546
|
-
: undefined,
|
|
1547
|
-
oraclePrice: isPerpsContext(data)
|
|
1548
|
-
? parseFloat(data.ctx.oraclePx.toString())
|
|
1549
|
-
: undefined,
|
|
1550
|
-
lastUpdated: Date.now(),
|
|
1551
|
-
};
|
|
1552
|
-
this.marketDataCache.set(symbol, marketDataEntry);
|
|
1553
|
-
// Update cached price data with new 24h change if we have current price
|
|
1554
|
-
const currentCachedPrice = this.cachedPriceData?.get(symbol);
|
|
1555
|
-
if (currentCachedPrice) {
|
|
1556
|
-
const updatedPrice = this.createPriceUpdate(symbol, currentCachedPrice.price);
|
|
1557
|
-
this.cachedPriceData ?? (this.cachedPriceData = new Map());
|
|
1558
|
-
this.cachedPriceData.set(symbol, updatedPrice);
|
|
1559
|
-
this.notifyAllPriceSubscribers();
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1562
|
-
})
|
|
1563
|
-
.then((sub) => {
|
|
1564
|
-
this.globalActiveAssetSubscriptions.set(symbol, sub);
|
|
1565
|
-
this.deps.debugLogger.log(`HyperLiquid: Market data subscription established for ${symbol}`);
|
|
1566
|
-
})
|
|
1567
|
-
.catch((subError) => {
|
|
1568
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('ensureActiveAssetSubscription', { symbol }));
|
|
1569
|
-
});
|
|
1570
|
-
}
|
|
1571
|
-
/**
|
|
1572
|
-
* Cleanup activeAssetCtx subscription when no longer needed
|
|
1573
|
-
*
|
|
1574
|
-
* @param symbol - Asset symbol
|
|
1575
|
-
*/
|
|
1576
|
-
cleanupActiveAssetSubscription(symbol) {
|
|
1577
|
-
const currentCount = this.symbolSubscriberCounts.get(symbol) || 0;
|
|
1578
|
-
if (currentCount <= 1) {
|
|
1579
|
-
// Last subscriber, cleanup subscription
|
|
1580
|
-
const subscription = this.globalActiveAssetSubscriptions.get(symbol);
|
|
1581
|
-
if (subscription && typeof subscription.unsubscribe === 'function') {
|
|
1582
|
-
const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
|
|
1583
|
-
unsubscribeResult.catch(() => {
|
|
1584
|
-
// Ignore errors during cleanup
|
|
1585
|
-
});
|
|
1586
|
-
this.globalActiveAssetSubscriptions.delete(symbol);
|
|
1587
|
-
this.symbolSubscriberCounts.delete(symbol);
|
|
1588
|
-
}
|
|
1589
|
-
else if (subscription) {
|
|
1590
|
-
// Subscription exists but unsubscribe is not a function or doesn't return a Promise
|
|
1591
|
-
// Just clean up the reference
|
|
1592
|
-
this.globalActiveAssetSubscriptions.delete(symbol);
|
|
1593
|
-
this.symbolSubscriberCounts.delete(symbol);
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
else {
|
|
1597
|
-
// Still has subscribers, just decrement count
|
|
1598
|
-
this.symbolSubscriberCounts.set(symbol, currentCount - 1);
|
|
1599
|
-
}
|
|
1600
|
-
}
|
|
1601
|
-
/**
|
|
1602
|
-
* Ensure assetCtxs subscription for specific DEX (HIP-3 support)
|
|
1603
|
-
* Uses WebSocket instead of REST polling for market data
|
|
1604
|
-
* Implements reference counting to track active subscribers per DEX
|
|
1605
|
-
*
|
|
1606
|
-
* @param dex - DEX identifier ('' for main)
|
|
1607
|
-
*/
|
|
1608
|
-
async ensureAssetCtxsSubscription(dex) {
|
|
1609
|
-
const dexKey = dex || '';
|
|
1610
|
-
// Increment subscriber count for this DEX
|
|
1611
|
-
const currentCount = this.dexSubscriberCounts.get(dexKey) || 0;
|
|
1612
|
-
this.dexSubscriberCounts.set(dexKey, currentCount + 1);
|
|
1613
|
-
// Return if subscription already exists
|
|
1614
|
-
if (this.assetCtxsSubscriptions.has(dexKey)) {
|
|
1615
|
-
return;
|
|
1616
|
-
}
|
|
1617
|
-
// Return existing promise if subscription is being established
|
|
1618
|
-
if (this.assetCtxsSubscriptionPromises.has(dexKey)) {
|
|
1619
|
-
return this.assetCtxsSubscriptionPromises.get(dexKey);
|
|
1620
|
-
}
|
|
1621
|
-
// Create new subscription promise
|
|
1622
|
-
const promise = this.createAssetCtxsSubscription(dex);
|
|
1623
|
-
this.assetCtxsSubscriptionPromises.set(dexKey, promise);
|
|
1624
|
-
try {
|
|
1625
|
-
await promise;
|
|
1626
|
-
}
|
|
1627
|
-
catch {
|
|
1628
|
-
// Clear promise on error so it can be retried
|
|
1629
|
-
this.assetCtxsSubscriptionPromises.delete(dexKey);
|
|
1630
|
-
throw new Error(`Failed to create assetCtxs subscription for DEX: ${dex}`);
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
/**
|
|
1634
|
-
* Create assetCtxs subscription for specific DEX
|
|
1635
|
-
* Provides real-time market data for all assets on the DEX
|
|
1636
|
-
*
|
|
1637
|
-
* Performance: Uses cached meta from dexMetaCache (populated by metaAndAssetCtxs)
|
|
1638
|
-
* to avoid redundant meta() API calls during subscription setup
|
|
1639
|
-
*
|
|
1640
|
-
* @param dex - DEX identifier ('' for main)
|
|
1641
|
-
*/
|
|
1642
|
-
async createAssetCtxsSubscription(dex) {
|
|
1643
|
-
await this.clientService.ensureSubscriptionClient(this.walletService.createWalletAdapter());
|
|
1644
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1645
|
-
if (!subscriptionClient) {
|
|
1646
|
-
throw new Error('Subscription client not initialized');
|
|
1647
|
-
}
|
|
1648
|
-
const dexKey = dex || '';
|
|
1649
|
-
const dexIdentifier = dex ?? 'main DEX';
|
|
1650
|
-
// Check cache first - populated by metaAndAssetCtxs in ensureAssetCtxsSubscription
|
|
1651
|
-
let perpsMeta = this.dexMetaCache.get(dexKey);
|
|
1652
|
-
if (!perpsMeta) {
|
|
1653
|
-
// Fallback: fetch meta if not in cache (shouldn't happen in normal flow)
|
|
1654
|
-
this.deps.debugLogger.log(`Meta cache miss for ${dexIdentifier}, fetching from API`);
|
|
1655
|
-
const infoClient = this.clientService.getInfoClient();
|
|
1656
|
-
const fetchedMeta = await infoClient.meta({ dex: dex || undefined });
|
|
1657
|
-
if (fetchedMeta?.universe) {
|
|
1658
|
-
perpsMeta = fetchedMeta;
|
|
1659
|
-
this.dexMetaCache.set(dexKey, fetchedMeta);
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
if (!perpsMeta?.universe) {
|
|
1663
|
-
const errorMessage = `No universe data available for ${dexIdentifier}`;
|
|
1664
|
-
throw new Error(errorMessage);
|
|
1665
|
-
}
|
|
1666
|
-
this.deps.debugLogger.log(`Using ${this.dexMetaCache.has(dexKey) ? 'cached' : 'fetched'} meta for ${dexIdentifier}`, {
|
|
1667
|
-
dex,
|
|
1668
|
-
universeCount: perpsMeta.universe.length,
|
|
1669
|
-
firstAssetSample: perpsMeta.universe[0]?.name,
|
|
1670
|
-
});
|
|
1671
|
-
// Capture perpsMeta in closure for callback
|
|
1672
|
-
const metaForCallback = perpsMeta;
|
|
1673
|
-
return new Promise((resolve, reject) => {
|
|
1674
|
-
const subscriptionParams = dex ? { dex } : {};
|
|
1675
|
-
subscriptionClient
|
|
1676
|
-
.assetCtxs(subscriptionParams, (data) => {
|
|
1677
|
-
// Cache asset contexts for this DEX
|
|
1678
|
-
this.dexAssetCtxsCache.set(dexKey, data.ctxs);
|
|
1679
|
-
// Use cached meta to map ctxs array indices to symbols (no REST API call!)
|
|
1680
|
-
metaForCallback.universe.forEach((asset, index) => {
|
|
1681
|
-
const ctx = data.ctxs[index];
|
|
1682
|
-
if (ctx && 'funding' in ctx) {
|
|
1683
|
-
// This is a perps context
|
|
1684
|
-
const ctxPrice = ctx.midPx || ctx.markPx;
|
|
1685
|
-
const openInterestUSD = calculateOpenInterestUSD(ctx.openInterest, ctxPrice);
|
|
1686
|
-
const marketDataEntry = {
|
|
1687
|
-
prevDayPx: ctx.prevDayPx
|
|
1688
|
-
? parseFloat(ctx.prevDayPx.toString())
|
|
1689
|
-
: undefined,
|
|
1690
|
-
funding: parseFloat(ctx.funding.toString()),
|
|
1691
|
-
openInterest: !isNaN(openInterestUSD)
|
|
1692
|
-
? openInterestUSD
|
|
1693
|
-
: undefined,
|
|
1694
|
-
volume24h: ctx.dayNtlVlm
|
|
1695
|
-
? parseFloat(ctx.dayNtlVlm.toString())
|
|
1696
|
-
: undefined,
|
|
1697
|
-
oraclePrice: parseFloat(ctx.oraclePx.toString()),
|
|
1698
|
-
lastUpdated: Date.now(),
|
|
1699
|
-
};
|
|
1700
|
-
this.marketDataCache.set(asset.name, marketDataEntry);
|
|
1701
|
-
// HIP-3: Extract price from assetCtx and update cached prices
|
|
1702
|
-
const priceValue = ctx.midPx?.toString() || ctx.markPx?.toString();
|
|
1703
|
-
if (priceValue) {
|
|
1704
|
-
// For HIP-3 DEXs, meta() returns asset.name already containing the DEX prefix
|
|
1705
|
-
// (e.g., "xyz:XYZ100"), so use it directly
|
|
1706
|
-
const assetSymbol = asset.name;
|
|
1707
|
-
const priceUpdate = this.createPriceUpdate(assetSymbol, priceValue);
|
|
1708
|
-
this.cachedPriceData ?? (this.cachedPriceData = new Map());
|
|
1709
|
-
this.cachedPriceData.set(assetSymbol, priceUpdate);
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
});
|
|
1713
|
-
// Notify price subscribers with updated market data
|
|
1714
|
-
this.notifyAllPriceSubscribers();
|
|
1715
|
-
})
|
|
1716
|
-
.then((sub) => {
|
|
1717
|
-
this.assetCtxsSubscriptions.set(dexKey, sub);
|
|
1718
|
-
this.deps.debugLogger.log(`assetCtxs subscription established for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
|
|
1719
|
-
resolve();
|
|
1720
|
-
})
|
|
1721
|
-
.catch((subError) => {
|
|
1722
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('createAssetCtxsSubscription', { dex }));
|
|
1723
|
-
reject(ensureError(subError));
|
|
1724
|
-
});
|
|
1725
|
-
});
|
|
1726
|
-
}
|
|
1727
|
-
/**
|
|
1728
|
-
* Cleanup assetCtxs subscription for specific DEX with reference counting
|
|
1729
|
-
* Only unsubscribes when the last subscriber for this DEX is removed
|
|
1730
|
-
*
|
|
1731
|
-
* @param dex - DEX identifier ('' for main)
|
|
1732
|
-
*/
|
|
1733
|
-
cleanupAssetCtxsSubscription(dex) {
|
|
1734
|
-
const dexKey = dex || '';
|
|
1735
|
-
// Decrement subscriber count for this DEX
|
|
1736
|
-
const currentCount = this.dexSubscriberCounts.get(dexKey) || 0;
|
|
1737
|
-
if (currentCount <= 1) {
|
|
1738
|
-
// Last subscriber - cleanup the subscription
|
|
1739
|
-
const subscription = this.assetCtxsSubscriptions.get(dexKey);
|
|
1740
|
-
if (subscription) {
|
|
1741
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1742
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('cleanupAssetCtxsSubscription', { dex }));
|
|
1743
|
-
});
|
|
1744
|
-
this.assetCtxsSubscriptions.delete(dexKey);
|
|
1745
|
-
this.dexAssetCtxsCache.delete(dexKey);
|
|
1746
|
-
this.assetCtxsSubscriptionPromises.delete(dexKey);
|
|
1747
|
-
this.dexSubscriberCounts.delete(dexKey);
|
|
1748
|
-
this.deps.debugLogger.log(`Cleaned up assetCtxs subscription for ${dex ? `DEX: ${dex}` : 'main DEX'}`);
|
|
1749
|
-
}
|
|
1750
|
-
}
|
|
1751
|
-
else {
|
|
1752
|
-
// Still has subscribers - just decrement count
|
|
1753
|
-
this.dexSubscriberCounts.set(dexKey, currentCount - 1);
|
|
1754
|
-
}
|
|
1755
|
-
}
|
|
1756
|
-
/**
|
|
1757
|
-
* Ensure BBO subscription for specific symbol (singleton)
|
|
1758
|
-
*
|
|
1759
|
-
* BBO provides best bid/ask without being affected by L2Book aggregation parameters,
|
|
1760
|
-
* keeping spread consistent across order book grouping selections (matches Hyperliquid UI).
|
|
1761
|
-
*
|
|
1762
|
-
* @param symbol - Asset symbol
|
|
1763
|
-
*/
|
|
1764
|
-
ensureBboSubscription(symbol) {
|
|
1765
|
-
if (this.globalBboSubscriptions.has(symbol)) {
|
|
1766
|
-
return;
|
|
1767
|
-
}
|
|
1768
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1769
|
-
if (!subscriptionClient) {
|
|
1770
|
-
return;
|
|
1771
|
-
}
|
|
1772
|
-
subscriptionClient
|
|
1773
|
-
.bbo({ coin: symbol }, (data) => {
|
|
1774
|
-
processBboData({
|
|
1775
|
-
symbol,
|
|
1776
|
-
data,
|
|
1777
|
-
orderBookCache: this.orderBookCache,
|
|
1778
|
-
cachedPriceData: this.cachedPriceData,
|
|
1779
|
-
createPriceUpdate: this.createPriceUpdate.bind(this),
|
|
1780
|
-
notifySubscribers: this.notifyAllPriceSubscribers.bind(this),
|
|
1781
|
-
});
|
|
1782
|
-
})
|
|
1783
|
-
.then((sub) => {
|
|
1784
|
-
this.globalBboSubscriptions.set(symbol, sub);
|
|
1785
|
-
this.deps.debugLogger.log(`HyperLiquid: BBO subscription established for ${symbol}`);
|
|
1786
|
-
})
|
|
1787
|
-
.catch((subError) => {
|
|
1788
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('ensureBboSubscription', { symbol }));
|
|
1789
|
-
});
|
|
1790
|
-
}
|
|
1791
|
-
/**
|
|
1792
|
-
* Cleanup BBO subscription when no longer needed
|
|
1793
|
-
*
|
|
1794
|
-
* @param symbol - Asset symbol
|
|
1795
|
-
*/
|
|
1796
|
-
cleanupBboSubscription(symbol) {
|
|
1797
|
-
// If anyone still wants order book (top-of-book) data for this symbol, keep the subscription alive.
|
|
1798
|
-
if ((this.orderBookSubscribers.get(symbol)?.size ?? 0) > 0) {
|
|
1799
|
-
return;
|
|
1800
|
-
}
|
|
1801
|
-
const subscription = this.globalBboSubscriptions.get(symbol);
|
|
1802
|
-
if (subscription && typeof subscription.unsubscribe === 'function') {
|
|
1803
|
-
const unsubscribeResult = Promise.resolve(subscription.unsubscribe());
|
|
1804
|
-
unsubscribeResult.catch(() => {
|
|
1805
|
-
// Ignore errors during cleanup
|
|
1806
|
-
});
|
|
1807
|
-
this.globalBboSubscriptions.delete(symbol);
|
|
1808
|
-
this.orderBookCache.delete(symbol);
|
|
1809
|
-
}
|
|
1810
|
-
else if (subscription) {
|
|
1811
|
-
// Subscription exists but unsubscribe is not a function or doesn't return a Promise
|
|
1812
|
-
// Just clean up the reference
|
|
1813
|
-
this.globalBboSubscriptions.delete(symbol);
|
|
1814
|
-
this.orderBookCache.delete(symbol);
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
/**
|
|
1818
|
-
* Subscribe to full order book updates with multiple depth levels
|
|
1819
|
-
* Creates a dedicated L2Book subscription for the requested symbol
|
|
1820
|
-
* and processes data into OrderBookData format for UI consumption
|
|
1821
|
-
*
|
|
1822
|
-
* @param params - Subscription parameters
|
|
1823
|
-
* @returns Cleanup function to unsubscribe
|
|
1824
|
-
*/
|
|
1825
|
-
subscribeToOrderBook(params) {
|
|
1826
|
-
const { symbol, levels = 10, nSigFigs = 5, mantissa, callback, onError, } = params;
|
|
1827
|
-
this.clientService.ensureSubscriptionClient(this.walletService.createWalletAdapter());
|
|
1828
|
-
const subscriptionClient = this.clientService.getSubscriptionClient();
|
|
1829
|
-
if (!subscriptionClient) {
|
|
1830
|
-
const subError = new Error('Subscription client not available');
|
|
1831
|
-
onError?.(subError);
|
|
1832
|
-
this.deps.debugLogger.log('subscribeToOrderBook: Subscription client not available');
|
|
1833
|
-
return () => {
|
|
1834
|
-
// No-op cleanup
|
|
1835
|
-
};
|
|
1836
|
-
}
|
|
1837
|
-
let subscription;
|
|
1838
|
-
let cancelled = false;
|
|
1839
|
-
subscriptionClient
|
|
1840
|
-
.l2Book({ coin: symbol, nSigFigs, mantissa }, (data) => {
|
|
1841
|
-
if (cancelled || data?.coin !== symbol || !data?.levels) {
|
|
1842
|
-
return;
|
|
1843
|
-
}
|
|
1844
|
-
const orderBookData = this.processOrderBookData(data, levels);
|
|
1845
|
-
callback(orderBookData);
|
|
1846
|
-
})
|
|
1847
|
-
.then((sub) => {
|
|
1848
|
-
if (cancelled) {
|
|
1849
|
-
sub.unsubscribe().catch((unsubError) => {
|
|
1850
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('subscribeToOrderBook.cleanup', { symbol }));
|
|
1851
|
-
});
|
|
1852
|
-
}
|
|
1853
|
-
else {
|
|
1854
|
-
subscription = sub;
|
|
1855
|
-
this.deps.debugLogger.log(`HyperLiquid: Order book subscription established for ${symbol}`);
|
|
1856
|
-
}
|
|
1857
|
-
})
|
|
1858
|
-
.catch((subError) => {
|
|
1859
|
-
this.deps.logger.error(ensureError(subError), this.getErrorContext('subscribeToOrderBook', { symbol }));
|
|
1860
|
-
onError?.(ensureError(subError));
|
|
1861
|
-
});
|
|
1862
|
-
return () => {
|
|
1863
|
-
cancelled = true;
|
|
1864
|
-
if (subscription) {
|
|
1865
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
1866
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('subscribeToOrderBook.unsubscribe', {
|
|
1867
|
-
symbol,
|
|
1868
|
-
}));
|
|
1869
|
-
});
|
|
1870
|
-
}
|
|
1871
|
-
};
|
|
1872
|
-
}
|
|
1873
|
-
/**
|
|
1874
|
-
* Process raw L2Book data into OrderBookData format
|
|
1875
|
-
* Calculates cumulative totals, notional values, and spread metrics
|
|
1876
|
-
*
|
|
1877
|
-
* @param data - Raw L2Book response from WebSocket
|
|
1878
|
-
* @param levels - Number of levels to return per side
|
|
1879
|
-
* @returns Processed OrderBookData
|
|
1880
|
-
*/
|
|
1881
|
-
processOrderBookData(data, levels) {
|
|
1882
|
-
const bidsRaw = data?.levels?.[0] || [];
|
|
1883
|
-
const asksRaw = data?.levels?.[1] || [];
|
|
1884
|
-
// Process bids (buy orders) - highest price first
|
|
1885
|
-
let bidCumulativeSize = 0;
|
|
1886
|
-
let bidCumulativeNotional = 0;
|
|
1887
|
-
const bids = bidsRaw.slice(0, levels).map((level) => {
|
|
1888
|
-
const price = parseFloat(level.px);
|
|
1889
|
-
const size = parseFloat(level.sz);
|
|
1890
|
-
const notional = price * size;
|
|
1891
|
-
bidCumulativeSize += size;
|
|
1892
|
-
bidCumulativeNotional += notional;
|
|
1893
|
-
return {
|
|
1894
|
-
price: level.px,
|
|
1895
|
-
size: level.sz,
|
|
1896
|
-
total: bidCumulativeSize.toString(),
|
|
1897
|
-
notional: notional.toFixed(2),
|
|
1898
|
-
totalNotional: bidCumulativeNotional.toFixed(2),
|
|
1899
|
-
};
|
|
1900
|
-
});
|
|
1901
|
-
// Process asks (sell orders) - lowest price first
|
|
1902
|
-
let askCumulativeSize = 0;
|
|
1903
|
-
let askCumulativeNotional = 0;
|
|
1904
|
-
const asks = asksRaw.slice(0, levels).map((level) => {
|
|
1905
|
-
const price = parseFloat(level.px);
|
|
1906
|
-
const size = parseFloat(level.sz);
|
|
1907
|
-
const notional = price * size;
|
|
1908
|
-
askCumulativeSize += size;
|
|
1909
|
-
askCumulativeNotional += notional;
|
|
1910
|
-
return {
|
|
1911
|
-
price: level.px,
|
|
1912
|
-
size: level.sz,
|
|
1913
|
-
total: askCumulativeSize.toString(),
|
|
1914
|
-
notional: notional.toFixed(2),
|
|
1915
|
-
totalNotional: askCumulativeNotional.toFixed(2),
|
|
1916
|
-
};
|
|
1917
|
-
});
|
|
1918
|
-
// Calculate spread and mid price
|
|
1919
|
-
const bestBid = bids[0];
|
|
1920
|
-
const bestAsk = asks[0];
|
|
1921
|
-
const bidPrice = bestBid ? parseFloat(bestBid.price) : 0;
|
|
1922
|
-
const askPrice = bestAsk ? parseFloat(bestAsk.price) : 0;
|
|
1923
|
-
const spread = askPrice > 0 && bidPrice > 0 ? askPrice - bidPrice : 0;
|
|
1924
|
-
const midPrice = askPrice > 0 && bidPrice > 0 ? (askPrice + bidPrice) / 2 : 0;
|
|
1925
|
-
const spreadPercentage = midPrice > 0 ? ((spread / midPrice) * 100).toFixed(4) : '0';
|
|
1926
|
-
// Calculate max total for depth chart scaling
|
|
1927
|
-
const maxTotal = Math.max(bidCumulativeSize, askCumulativeSize).toString();
|
|
1928
|
-
return {
|
|
1929
|
-
bids,
|
|
1930
|
-
asks,
|
|
1931
|
-
spread: spread.toFixed(5),
|
|
1932
|
-
spreadPercentage,
|
|
1933
|
-
midPrice: midPrice.toFixed(5),
|
|
1934
|
-
lastUpdated: Date.now(),
|
|
1935
|
-
maxTotal,
|
|
1936
|
-
};
|
|
1937
|
-
}
|
|
1938
|
-
/**
|
|
1939
|
-
* Notify all price subscribers with their requested symbols from cache
|
|
1940
|
-
* Optimized to batch updates per subscriber
|
|
1941
|
-
*/
|
|
1942
|
-
notifyAllPriceSubscribers() {
|
|
1943
|
-
// If no price data exists yet, don't notify
|
|
1944
|
-
if (!this.cachedPriceData) {
|
|
1945
|
-
return;
|
|
1946
|
-
}
|
|
1947
|
-
const priceData = this.cachedPriceData;
|
|
1948
|
-
// Group updates by subscriber to batch notifications
|
|
1949
|
-
const subscriberUpdates = new Map();
|
|
1950
|
-
this.priceSubscribers.forEach((subscriberSet, symbol) => {
|
|
1951
|
-
const priceUpdate = priceData.get(symbol);
|
|
1952
|
-
if (priceUpdate) {
|
|
1953
|
-
subscriberSet.forEach((priceCallback) => {
|
|
1954
|
-
if (!subscriberUpdates.has(priceCallback)) {
|
|
1955
|
-
subscriberUpdates.set(priceCallback, []);
|
|
1956
|
-
}
|
|
1957
|
-
const updates = subscriberUpdates.get(priceCallback);
|
|
1958
|
-
if (updates) {
|
|
1959
|
-
updates.push(priceUpdate);
|
|
1960
|
-
}
|
|
1961
|
-
});
|
|
1962
|
-
}
|
|
1963
|
-
});
|
|
1964
|
-
// Send batched updates to each subscriber
|
|
1965
|
-
subscriberUpdates.forEach((updates, priceCallback) => {
|
|
1966
|
-
if (updates.length > 0) {
|
|
1967
|
-
priceCallback(updates);
|
|
1968
|
-
}
|
|
1969
|
-
});
|
|
1970
|
-
}
|
|
1971
|
-
/**
|
|
1972
|
-
* Restore all active subscriptions after WebSocket reconnection
|
|
1973
|
-
* Re-establishes WebSocket subscriptions for all active subscribers
|
|
1974
|
-
*
|
|
1975
|
-
* IMPORTANT: This method verifies transport readiness before attempting
|
|
1976
|
-
* any subscriptions to prevent "subscribe error: undefined" errors.
|
|
1977
|
-
*/
|
|
1978
|
-
async restoreSubscriptions() {
|
|
1979
|
-
// CRITICAL: Verify transport is ready before attempting any subscriptions
|
|
1980
|
-
// This prevents race conditions where subscriptions are attempted while
|
|
1981
|
-
// the WebSocket is still in CONNECTING state
|
|
1982
|
-
try {
|
|
1983
|
-
await this.clientService.ensureTransportReady(5000);
|
|
1984
|
-
}
|
|
1985
|
-
catch (transportError) {
|
|
1986
|
-
this.deps.debugLogger.log('Transport not ready during subscription restore, will retry on next reconnect', {
|
|
1987
|
-
error: transportError instanceof Error
|
|
1988
|
-
? transportError.message
|
|
1989
|
-
: String(transportError),
|
|
1990
|
-
});
|
|
1991
|
-
return;
|
|
1992
|
-
}
|
|
1993
|
-
// Re-establish global allMids subscription if there are price subscribers
|
|
1994
|
-
if (this.priceSubscribers.size > 0) {
|
|
1995
|
-
// Clear existing subscription reference (it's dead after reconnection)
|
|
1996
|
-
this.globalAllMidsSubscription = undefined;
|
|
1997
|
-
this.globalAllMidsPromise = undefined;
|
|
1998
|
-
// Re-establish the subscription
|
|
1999
|
-
this.ensureGlobalAllMidsSubscription();
|
|
2000
|
-
}
|
|
2001
|
-
// Re-establish order fill subscriptions if there are fill subscribers
|
|
2002
|
-
if (this.orderFillSubscribers.size > 0) {
|
|
2003
|
-
// Clear existing subscription references (they're dead after reconnection)
|
|
2004
|
-
this.orderFillSubscriptions.clear();
|
|
2005
|
-
// Re-establish subscriptions for all accountIds with subscribers
|
|
2006
|
-
// Note: normalizedAccountId is 'default' for undefined, need to convert back
|
|
2007
|
-
const normalizedAccountIds = Array.from(this.orderFillSubscribers.keys());
|
|
2008
|
-
await Promise.all(normalizedAccountIds.map((normalizedAccountId) => {
|
|
2009
|
-
// Convert normalized key back to original accountId (undefined if 'default')
|
|
2010
|
-
const originalAccountId = normalizedAccountId === 'default'
|
|
2011
|
-
? undefined
|
|
2012
|
-
: normalizedAccountId;
|
|
2013
|
-
return this.ensureOrderFillISubscription(originalAccountId).catch(() => {
|
|
2014
|
-
// Ignore errors during order fill subscription restoration
|
|
2015
|
-
});
|
|
2016
|
-
}));
|
|
2017
|
-
}
|
|
2018
|
-
// Re-establish user data subscriptions if there are user data subscribers
|
|
2019
|
-
if (this.positionSubscribers.size > 0 ||
|
|
2020
|
-
this.orderSubscribers.size > 0 ||
|
|
2021
|
-
this.accountSubscribers.size > 0 ||
|
|
2022
|
-
this.oiCapSubscribers.size > 0) {
|
|
2023
|
-
// Clear existing subscription references (they're dead after reconnection)
|
|
2024
|
-
this.webData3Subscriptions.clear();
|
|
2025
|
-
this.webData3SubscriptionPromise = undefined;
|
|
2026
|
-
// Clear individual subscriptions (clearinghouseState + openOrders) for HIP-3 mode
|
|
2027
|
-
this.clearinghouseStateSubscriptions.clear();
|
|
2028
|
-
this.openOrdersSubscriptions.clear();
|
|
2029
|
-
// Re-establish the subscription (will use current account)
|
|
2030
|
-
// This will set up webData2 for non-HIP-3, or individual subscriptions + webData3 (OI caps only) for HIP-3
|
|
2031
|
-
await this.ensureSharedWebData3Subscription();
|
|
2032
|
-
}
|
|
2033
|
-
// Re-establish activeAsset subscriptions if there are market data subscribers
|
|
2034
|
-
if (this.marketDataSubscribers.size > 0) {
|
|
2035
|
-
// Clear existing subscriptions (they're dead after reconnection)
|
|
2036
|
-
this.globalActiveAssetSubscriptions.clear();
|
|
2037
|
-
// Clear reference counts to prevent double-counting after reconnection
|
|
2038
|
-
this.symbolSubscriberCounts.clear();
|
|
2039
|
-
// Re-establish subscriptions for all symbols with market data subscribers
|
|
2040
|
-
const symbolsNeedingMarketData = Array.from(this.marketDataSubscribers.keys());
|
|
2041
|
-
symbolsNeedingMarketData.forEach((symbol) => {
|
|
2042
|
-
this.ensureActiveAssetSubscription(symbol);
|
|
2043
|
-
});
|
|
2044
|
-
}
|
|
2045
|
-
// Re-establish BBO subscriptions if there are order book subscribers
|
|
2046
|
-
if (this.orderBookSubscribers.size > 0) {
|
|
2047
|
-
// Clear existing subscriptions (they're dead after reconnection)
|
|
2048
|
-
this.globalBboSubscriptions.clear();
|
|
2049
|
-
// Re-establish subscriptions for all symbols with order book subscribers
|
|
2050
|
-
const symbolsNeedingOrderBook = Array.from(this.orderBookSubscribers.keys());
|
|
2051
|
-
symbolsNeedingOrderBook.forEach((symbol) => {
|
|
2052
|
-
this.ensureBboSubscription(symbol);
|
|
2053
|
-
});
|
|
2054
|
-
}
|
|
2055
|
-
// Re-establish assetCtxs subscriptions if there are market data subscribers
|
|
2056
|
-
if (this.marketDataSubscribers.size > 0) {
|
|
2057
|
-
// Clear existing subscriptions (they're dead after reconnection)
|
|
2058
|
-
this.assetCtxsSubscriptions.clear();
|
|
2059
|
-
this.assetCtxsSubscriptionPromises.clear();
|
|
2060
|
-
// Clear reference counts to prevent double-counting after reconnection
|
|
2061
|
-
this.dexSubscriberCounts.clear();
|
|
2062
|
-
// Re-establish subscriptions for all DEXs with market data subscribers
|
|
2063
|
-
const dexsNeeded = new Set();
|
|
2064
|
-
this.marketDataSubscribers.forEach((_subscribers, symbol) => {
|
|
2065
|
-
const { dex } = parseAssetName(symbol);
|
|
2066
|
-
if (dex) {
|
|
2067
|
-
dexsNeeded.add(dex);
|
|
2068
|
-
}
|
|
2069
|
-
});
|
|
2070
|
-
// Add main DEX if any main DEX symbols have subscribers
|
|
2071
|
-
const hasMainDexSubscribers = Array.from(this.marketDataSubscribers.keys()).some((symbol) => {
|
|
2072
|
-
const { dex } = parseAssetName(symbol);
|
|
2073
|
-
return !dex;
|
|
2074
|
-
});
|
|
2075
|
-
if (hasMainDexSubscribers) {
|
|
2076
|
-
dexsNeeded.add('');
|
|
2077
|
-
}
|
|
2078
|
-
// Re-establish subscriptions
|
|
2079
|
-
await Promise.all(Array.from(dexsNeeded).map((dex) => this.ensureAssetCtxsSubscription(dex).catch(() => {
|
|
2080
|
-
// Ignore errors during assetCtxs subscription restoration
|
|
2081
|
-
})));
|
|
2082
|
-
}
|
|
2083
|
-
}
|
|
2084
|
-
/**
|
|
2085
|
-
* Clear all subscriptions and cached data (multi-DEX support)
|
|
2086
|
-
*/
|
|
2087
|
-
clearAll() {
|
|
2088
|
-
// Clear all local subscriber collections
|
|
2089
|
-
this.priceSubscribers.clear();
|
|
2090
|
-
this.positionSubscribers.clear();
|
|
2091
|
-
this.orderFillSubscribers.clear();
|
|
2092
|
-
this.orderSubscribers.clear();
|
|
2093
|
-
this.accountSubscribers.clear();
|
|
2094
|
-
this.marketDataSubscribers.clear();
|
|
2095
|
-
this.orderBookSubscribers.clear();
|
|
2096
|
-
// Clear order fill subscriptions
|
|
2097
|
-
this.orderFillSubscriptions.forEach((subscription) => {
|
|
2098
|
-
subscription.unsubscribe().catch(() => {
|
|
2099
|
-
// Ignore errors during cleanup
|
|
2100
|
-
});
|
|
2101
|
-
});
|
|
2102
|
-
this.orderFillSubscriptions.clear();
|
|
2103
|
-
// Clear cached data
|
|
2104
|
-
this.cachedPriceData = null;
|
|
2105
|
-
this.cachedPositions = null;
|
|
2106
|
-
this.cachedOrders = null;
|
|
2107
|
-
this.cachedAccount = null;
|
|
2108
|
-
this.ordersCacheInitialized = false; // Reset cache initialization flag
|
|
2109
|
-
this.positionsCacheInitialized = false; // Reset cache initialization flag
|
|
2110
|
-
this.marketDataCache.clear();
|
|
2111
|
-
this.orderBookCache.clear();
|
|
2112
|
-
this.symbolSubscriberCounts.clear();
|
|
2113
|
-
this.dexSubscriberCounts.clear();
|
|
2114
|
-
// Clear hash caches
|
|
2115
|
-
this.cachedPositionsHash = '';
|
|
2116
|
-
this.cachedOrdersHash = '';
|
|
2117
|
-
this.cachedAccountHash = '';
|
|
2118
|
-
// Clear multi-DEX caches
|
|
2119
|
-
this.deps.debugLogger.log('HyperLiquidSubscriptionService: Clearing per-DEX caches', {
|
|
2120
|
-
dexPositionsCacheSize: this.dexPositionsCache.size,
|
|
2121
|
-
dexOrdersCacheSize: this.dexOrdersCache.size,
|
|
2122
|
-
dexAccountCacheSize: this.dexAccountCache.size,
|
|
2123
|
-
dexAssetCtxsCacheSize: this.dexAssetCtxsCache.size,
|
|
2124
|
-
dexPositionsCacheKeys: Array.from(this.dexPositionsCache.keys()),
|
|
2125
|
-
dexAssetCtxsCacheKeys: Array.from(this.dexAssetCtxsCache.keys()),
|
|
2126
|
-
});
|
|
2127
|
-
this.dexPositionsCache.clear();
|
|
2128
|
-
this.dexOrdersCache.clear();
|
|
2129
|
-
this.dexAccountCache.clear();
|
|
2130
|
-
this.dexAssetCtxsCache.clear();
|
|
2131
|
-
// Clear subscription references (actual cleanup handled by client service)
|
|
2132
|
-
this.globalAllMidsSubscription = undefined;
|
|
2133
|
-
this.globalActiveAssetSubscriptions.clear();
|
|
2134
|
-
this.globalBboSubscriptions.clear();
|
|
2135
|
-
this.webData3Subscriptions.clear();
|
|
2136
|
-
this.webData3SubscriptionPromise = undefined;
|
|
2137
|
-
// HIP-3: Clear assetCtxs subscriptions (clearinghouseState no longer needed with webData3)
|
|
2138
|
-
this.assetCtxsSubscriptions.clear();
|
|
2139
|
-
this.assetCtxsSubscriptionPromises.clear();
|
|
2140
|
-
// Cleanup individual subscriptions (clearinghouseState + openOrders)
|
|
2141
|
-
if (this.clearinghouseStateSubscriptions.size > 0) {
|
|
2142
|
-
this.clearinghouseStateSubscriptions.forEach((subscription, dexNameKey) => {
|
|
2143
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
2144
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('clearAll.clearinghouseState', {
|
|
2145
|
-
dex: dexNameKey,
|
|
2146
|
-
}));
|
|
2147
|
-
});
|
|
2148
|
-
});
|
|
2149
|
-
this.clearinghouseStateSubscriptions.clear();
|
|
2150
|
-
}
|
|
2151
|
-
if (this.openOrdersSubscriptions.size > 0) {
|
|
2152
|
-
this.openOrdersSubscriptions.forEach((subscription, dexNameKey) => {
|
|
2153
|
-
subscription.unsubscribe().catch((unsubError) => {
|
|
2154
|
-
this.deps.logger.error(ensureError(unsubError), this.getErrorContext('clearAll.openOrders', {
|
|
2155
|
-
dex: dexNameKey,
|
|
2156
|
-
}));
|
|
2157
|
-
});
|
|
2158
|
-
});
|
|
2159
|
-
this.openOrdersSubscriptions.clear();
|
|
2160
|
-
}
|
|
2161
|
-
this.deps.debugLogger.log('HyperLiquid: Subscription service cleared (multi-DEX with individual subscriptions)', {
|
|
2162
|
-
timestamp: new Date().toISOString(),
|
|
2163
|
-
});
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
//# sourceMappingURL=HyperLiquidSubscriptionService.mjs.map
|