@metamask-previews/perps-controller 0.0.0-preview-ae46ab603 → 0.0.0-preview-e4aa1532
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 +11 -1
- package/dist/PerpsController.cjs +2224 -66
- package/dist/PerpsController.cjs.map +1 -1
- package/dist/PerpsController.d.cts +933 -79
- package/dist/PerpsController.d.cts.map +1 -1
- package/dist/PerpsController.d.mts +933 -79
- package/dist/PerpsController.d.mts.map +1 -1
- package/dist/PerpsController.mjs +2221 -64
- package/dist/PerpsController.mjs.map +1 -1
- package/dist/__mocks__/hyperliquidMock.cjs +68 -0
- package/dist/__mocks__/hyperliquidMock.cjs.map +1 -0
- package/dist/__mocks__/hyperliquidMock.d.cts +15 -0
- package/dist/__mocks__/hyperliquidMock.d.cts.map +1 -0
- package/dist/__mocks__/hyperliquidMock.d.mts +15 -0
- package/dist/__mocks__/hyperliquidMock.d.mts.map +1 -0
- package/dist/__mocks__/hyperliquidMock.mjs +65 -0
- package/dist/__mocks__/hyperliquidMock.mjs.map +1 -0
- package/dist/__mocks__/providerMocks.cjs +144 -0
- package/dist/__mocks__/providerMocks.cjs.map +1 -0
- package/dist/__mocks__/providerMocks.d.cts +44 -0
- package/dist/__mocks__/providerMocks.d.cts.map +1 -0
- package/dist/__mocks__/providerMocks.d.mts +44 -0
- package/dist/__mocks__/providerMocks.d.mts.map +1 -0
- package/dist/__mocks__/providerMocks.mjs +136 -0
- package/dist/__mocks__/providerMocks.mjs.map +1 -0
- package/dist/__mocks__/serviceMocks.cjs +187 -0
- package/dist/__mocks__/serviceMocks.cjs.map +1 -0
- package/dist/__mocks__/serviceMocks.d.cts +58 -0
- package/dist/__mocks__/serviceMocks.d.cts.map +1 -0
- package/dist/__mocks__/serviceMocks.d.mts +58 -0
- package/dist/__mocks__/serviceMocks.d.mts.map +1 -0
- package/dist/__mocks__/serviceMocks.mjs +180 -0
- package/dist/__mocks__/serviceMocks.mjs.map +1 -0
- package/dist/aggregation/SubscriptionMultiplexer.cjs +459 -0
- package/dist/aggregation/SubscriptionMultiplexer.cjs.map +1 -0
- package/dist/aggregation/SubscriptionMultiplexer.d.cts +222 -0
- package/dist/aggregation/SubscriptionMultiplexer.d.cts.map +1 -0
- package/dist/aggregation/SubscriptionMultiplexer.d.mts +222 -0
- package/dist/aggregation/SubscriptionMultiplexer.d.mts.map +1 -0
- package/dist/aggregation/SubscriptionMultiplexer.mjs +455 -0
- package/dist/aggregation/SubscriptionMultiplexer.mjs.map +1 -0
- package/dist/aggregation/index.cjs +9 -0
- package/dist/aggregation/index.cjs.map +1 -0
- package/dist/aggregation/index.d.cts +6 -0
- package/dist/aggregation/index.d.cts.map +1 -0
- package/dist/aggregation/index.d.mts +6 -0
- package/dist/aggregation/index.d.mts.map +1 -0
- package/dist/aggregation/index.mjs +5 -0
- package/dist/aggregation/index.mjs.map +1 -0
- package/dist/constants/eventNames.cjs +117 -0
- package/dist/constants/eventNames.cjs.map +1 -0
- package/dist/constants/eventNames.d.cts +106 -0
- package/dist/constants/eventNames.d.cts.map +1 -0
- package/dist/constants/eventNames.d.mts +106 -0
- package/dist/constants/eventNames.d.mts.map +1 -0
- package/dist/constants/eventNames.mjs +114 -0
- package/dist/constants/eventNames.mjs.map +1 -0
- package/dist/constants/hyperLiquidConfig.cjs +366 -0
- package/dist/constants/hyperLiquidConfig.cjs.map +1 -0
- package/dist/constants/hyperLiquidConfig.d.cts +276 -0
- package/dist/constants/hyperLiquidConfig.d.cts.map +1 -0
- package/dist/constants/hyperLiquidConfig.d.mts +276 -0
- package/dist/constants/hyperLiquidConfig.d.mts.map +1 -0
- package/dist/constants/hyperLiquidConfig.mjs +357 -0
- package/dist/constants/hyperLiquidConfig.mjs.map +1 -0
- package/dist/constants/index.cjs +23 -0
- package/dist/constants/index.cjs.map +1 -0
- package/dist/constants/index.d.cts +7 -0
- package/dist/constants/index.d.cts.map +1 -0
- package/dist/constants/index.d.mts +7 -0
- package/dist/constants/index.d.mts.map +1 -0
- package/dist/constants/index.mjs +7 -0
- package/dist/constants/index.mjs.map +1 -0
- package/dist/constants/orderTypes.cjs +31 -0
- package/dist/constants/orderTypes.cjs.map +1 -0
- package/dist/constants/orderTypes.d.cts +19 -0
- package/dist/constants/orderTypes.d.cts.map +1 -0
- package/dist/constants/orderTypes.d.mts +19 -0
- package/dist/constants/orderTypes.d.mts.map +1 -0
- package/dist/constants/orderTypes.mjs +27 -0
- package/dist/constants/orderTypes.mjs.map +1 -0
- package/dist/constants/performanceMetrics.cjs +61 -0
- package/dist/constants/performanceMetrics.cjs.map +1 -0
- package/dist/constants/performanceMetrics.d.cts +44 -0
- package/dist/constants/performanceMetrics.d.cts.map +1 -0
- package/dist/constants/performanceMetrics.d.mts +44 -0
- package/dist/constants/performanceMetrics.d.mts.map +1 -0
- package/dist/constants/performanceMetrics.mjs +58 -0
- package/dist/constants/performanceMetrics.mjs.map +1 -0
- package/dist/constants/perpsConfig.cjs +461 -0
- package/dist/constants/perpsConfig.cjs.map +1 -0
- package/dist/constants/perpsConfig.d.cts +343 -0
- package/dist/constants/perpsConfig.d.cts.map +1 -0
- package/dist/constants/perpsConfig.d.mts +343 -0
- package/dist/constants/perpsConfig.d.mts.map +1 -0
- package/dist/constants/perpsConfig.mjs +458 -0
- package/dist/constants/perpsConfig.mjs.map +1 -0
- package/dist/constants/perpsErrorCodes.cjs +79 -0
- package/dist/constants/perpsErrorCodes.cjs.map +1 -0
- package/dist/constants/perpsErrorCodes.d.cts +64 -0
- package/dist/constants/perpsErrorCodes.d.cts.map +1 -0
- package/dist/constants/perpsErrorCodes.d.mts +64 -0
- package/dist/constants/perpsErrorCodes.d.mts.map +1 -0
- package/dist/constants/perpsErrorCodes.mjs +76 -0
- package/dist/constants/perpsErrorCodes.mjs.map +1 -0
- package/dist/index.cjs +32 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +6 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -1
- package/dist/index.mjs.map +1 -1
- package/dist/platform-services/HyperLiquidClientService.cjs +857 -0
- package/dist/platform-services/HyperLiquidClientService.cjs.map +1 -0
- package/dist/platform-services/HyperLiquidClientService.d.cts +263 -0
- package/dist/platform-services/HyperLiquidClientService.d.cts.map +1 -0
- package/dist/platform-services/HyperLiquidClientService.d.mts +263 -0
- package/dist/platform-services/HyperLiquidClientService.d.mts.map +1 -0
- package/dist/platform-services/HyperLiquidClientService.mjs +853 -0
- package/dist/platform-services/HyperLiquidClientService.mjs.map +1 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs +2170 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.cjs.map +1 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts +424 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.d.cts.map +1 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts +424 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.d.mts.map +1 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs +2166 -0
- package/dist/platform-services/HyperLiquidSubscriptionService.mjs.map +1 -0
- package/dist/platform-services/HyperLiquidWalletService.cjs +140 -0
- package/dist/platform-services/HyperLiquidWalletService.cjs.map +1 -0
- package/dist/platform-services/HyperLiquidWalletService.d.cts +78 -0
- package/dist/platform-services/HyperLiquidWalletService.d.cts.map +1 -0
- package/dist/platform-services/HyperLiquidWalletService.d.mts +78 -0
- package/dist/platform-services/HyperLiquidWalletService.d.mts.map +1 -0
- package/dist/platform-services/HyperLiquidWalletService.mjs +136 -0
- package/dist/platform-services/HyperLiquidWalletService.mjs.map +1 -0
- package/dist/providers/AggregatedPerpsProvider.cjs +777 -0
- package/dist/providers/AggregatedPerpsProvider.cjs.map +1 -0
- package/dist/providers/AggregatedPerpsProvider.d.cts +466 -0
- package/dist/providers/AggregatedPerpsProvider.d.cts.map +1 -0
- package/dist/providers/AggregatedPerpsProvider.d.mts +466 -0
- package/dist/providers/AggregatedPerpsProvider.d.mts.map +1 -0
- package/dist/providers/AggregatedPerpsProvider.mjs +773 -0
- package/dist/providers/AggregatedPerpsProvider.mjs.map +1 -0
- package/dist/providers/HyperLiquidProvider.cjs +5172 -0
- package/dist/providers/HyperLiquidProvider.cjs.map +1 -0
- package/dist/providers/HyperLiquidProvider.d.cts +881 -0
- package/dist/providers/HyperLiquidProvider.d.cts.map +1 -0
- package/dist/providers/HyperLiquidProvider.d.mts +881 -0
- package/dist/providers/HyperLiquidProvider.d.mts.map +1 -0
- package/dist/providers/HyperLiquidProvider.mjs +5168 -0
- package/dist/providers/HyperLiquidProvider.mjs.map +1 -0
- package/dist/providers/index.cjs +11 -0
- package/dist/providers/index.cjs.map +1 -0
- package/dist/providers/index.d.cts +6 -0
- package/dist/providers/index.d.cts.map +1 -0
- package/dist/providers/index.d.mts +6 -0
- package/dist/providers/index.d.mts.map +1 -0
- package/dist/providers/index.mjs +6 -0
- package/dist/providers/index.mjs.map +1 -0
- package/dist/routing/ProviderRouter.cjs +148 -0
- package/dist/routing/ProviderRouter.cjs.map +1 -0
- package/dist/routing/ProviderRouter.d.cts +124 -0
- package/dist/routing/ProviderRouter.d.cts.map +1 -0
- package/dist/routing/ProviderRouter.d.mts +124 -0
- package/dist/routing/ProviderRouter.d.mts.map +1 -0
- package/dist/routing/ProviderRouter.mjs +144 -0
- package/dist/routing/ProviderRouter.mjs.map +1 -0
- package/dist/routing/index.cjs +9 -0
- package/dist/routing/index.cjs.map +1 -0
- package/dist/routing/index.d.cts +6 -0
- package/dist/routing/index.d.cts.map +1 -0
- package/dist/routing/index.d.mts +6 -0
- package/dist/routing/index.d.mts.map +1 -0
- package/dist/routing/index.mjs +5 -0
- package/dist/routing/index.mjs.map +1 -0
- package/dist/selectors.cjs +161 -0
- package/dist/selectors.cjs.map +1 -0
- package/dist/selectors.d.cts +345 -0
- package/dist/selectors.d.cts.map +1 -0
- package/dist/selectors.d.mts +345 -0
- package/dist/selectors.d.mts.map +1 -0
- package/dist/selectors.mjs +153 -0
- package/dist/selectors.mjs.map +1 -0
- package/dist/services/AccountService.cjs +313 -0
- package/dist/services/AccountService.cjs.map +1 -0
- package/dist/services/AccountService.d.cts +53 -0
- package/dist/services/AccountService.d.cts.map +1 -0
- package/dist/services/AccountService.d.mts +53 -0
- package/dist/services/AccountService.d.mts.map +1 -0
- package/dist/services/AccountService.mjs +309 -0
- package/dist/services/AccountService.mjs.map +1 -0
- package/dist/services/DataLakeService.cjs +219 -0
- package/dist/services/DataLakeService.cjs.map +1 -0
- package/dist/services/DataLakeService.d.cts +49 -0
- package/dist/services/DataLakeService.d.cts.map +1 -0
- package/dist/services/DataLakeService.d.mts +49 -0
- package/dist/services/DataLakeService.d.mts.map +1 -0
- package/dist/services/DataLakeService.mjs +215 -0
- package/dist/services/DataLakeService.mjs.map +1 -0
- package/dist/services/DepositService.cjs +96 -0
- package/dist/services/DepositService.cjs.map +1 -0
- package/dist/services/DepositService.d.cts +37 -0
- package/dist/services/DepositService.d.cts.map +1 -0
- package/dist/services/DepositService.d.mts +37 -0
- package/dist/services/DepositService.d.mts.map +1 -0
- package/dist/services/DepositService.mjs +92 -0
- package/dist/services/DepositService.mjs.map +1 -0
- package/dist/services/EligibilityService.cjs +156 -0
- package/dist/services/EligibilityService.cjs.map +1 -0
- package/dist/services/EligibilityService.d.cts +48 -0
- package/dist/services/EligibilityService.d.cts.map +1 -0
- package/dist/services/EligibilityService.d.mts +48 -0
- package/dist/services/EligibilityService.d.mts.map +1 -0
- package/dist/services/EligibilityService.mjs +152 -0
- package/dist/services/EligibilityService.mjs.map +1 -0
- package/dist/services/FeatureFlagConfigurationService.cjs +258 -0
- package/dist/services/FeatureFlagConfigurationService.cjs.map +1 -0
- package/dist/services/FeatureFlagConfigurationService.d.cts +100 -0
- package/dist/services/FeatureFlagConfigurationService.d.cts.map +1 -0
- package/dist/services/FeatureFlagConfigurationService.d.mts +100 -0
- package/dist/services/FeatureFlagConfigurationService.d.mts.map +1 -0
- package/dist/services/FeatureFlagConfigurationService.mjs +254 -0
- package/dist/services/FeatureFlagConfigurationService.mjs.map +1 -0
- package/dist/services/MarketDataService.cjs +875 -0
- package/dist/services/MarketDataService.cjs.map +1 -0
- package/dist/services/MarketDataService.d.cts +289 -0
- package/dist/services/MarketDataService.d.cts.map +1 -0
- package/dist/services/MarketDataService.d.mts +289 -0
- package/dist/services/MarketDataService.d.mts.map +1 -0
- package/dist/services/MarketDataService.mjs +871 -0
- package/dist/services/MarketDataService.mjs.map +1 -0
- package/dist/services/RewardsIntegrationService.cjs +94 -0
- package/dist/services/RewardsIntegrationService.cjs.map +1 -0
- package/dist/services/RewardsIntegrationService.d.cts +30 -0
- package/dist/services/RewardsIntegrationService.d.cts.map +1 -0
- package/dist/services/RewardsIntegrationService.d.mts +30 -0
- package/dist/services/RewardsIntegrationService.d.mts.map +1 -0
- package/dist/services/RewardsIntegrationService.mjs +90 -0
- package/dist/services/RewardsIntegrationService.mjs.map +1 -0
- package/dist/services/ServiceContext.cjs +3 -0
- package/dist/services/ServiceContext.cjs.map +1 -0
- package/dist/services/ServiceContext.d.cts +110 -0
- package/dist/services/ServiceContext.d.cts.map +1 -0
- package/dist/services/ServiceContext.d.mts +110 -0
- package/dist/services/ServiceContext.d.mts.map +1 -0
- package/dist/services/ServiceContext.mjs +2 -0
- package/dist/services/ServiceContext.mjs.map +1 -0
- package/dist/services/TradingService.cjs +1481 -0
- package/dist/services/TradingService.cjs.map +1 -0
- package/dist/services/TradingService.d.cts +308 -0
- package/dist/services/TradingService.d.cts.map +1 -0
- package/dist/services/TradingService.d.mts +308 -0
- package/dist/services/TradingService.d.mts.map +1 -0
- package/dist/services/TradingService.mjs +1477 -0
- package/dist/services/TradingService.mjs.map +1 -0
- package/dist/services/index.cjs +26 -0
- package/dist/services/index.cjs.map +1 -0
- package/dist/services/index.d.cts +11 -0
- package/dist/services/index.d.cts.map +1 -0
- package/dist/services/index.d.mts +11 -0
- package/dist/services/index.d.mts.map +1 -0
- package/dist/services/index.mjs +10 -0
- package/dist/services/index.mjs.map +1 -0
- package/dist/services/utils.cjs +16 -0
- package/dist/services/utils.cjs.map +1 -0
- package/dist/services/utils.d.cts +8 -0
- package/dist/services/utils.d.cts.map +1 -0
- package/dist/services/utils.d.mts +8 -0
- package/dist/services/utils.d.mts.map +1 -0
- package/dist/services/utils.mjs +12 -0
- package/dist/services/utils.mjs.map +1 -0
- package/dist/types/chart.cjs +42 -0
- package/dist/types/chart.cjs.map +1 -0
- package/dist/types/chart.d.cts +62 -0
- package/dist/types/chart.d.cts.map +1 -0
- package/dist/types/chart.d.mts +62 -0
- package/dist/types/chart.d.mts.map +1 -0
- package/dist/types/chart.mjs +39 -0
- package/dist/types/chart.mjs.map +1 -0
- package/dist/types/hyperliquid-types.cjs +3 -0
- package/dist/types/hyperliquid-types.cjs.map +1 -0
- package/dist/types/hyperliquid-types.d.cts +52 -0
- package/dist/types/hyperliquid-types.d.cts.map +1 -0
- package/dist/types/hyperliquid-types.d.mts +52 -0
- package/dist/types/hyperliquid-types.d.mts.map +1 -0
- package/dist/types/hyperliquid-types.mjs +2 -0
- package/dist/types/hyperliquid-types.mjs.map +1 -0
- package/dist/types/index.cjs +96 -0
- package/dist/types/index.cjs.map +1 -0
- package/dist/types/index.d.cts +1153 -0
- package/dist/types/index.d.cts.map +1 -0
- package/dist/types/index.d.mts +1153 -0
- package/dist/types/index.d.mts.map +1 -0
- package/dist/types/index.mjs +79 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/types/transactionTypes.cjs +28 -0
- package/dist/types/transactionTypes.cjs.map +1 -0
- package/dist/types/transactionTypes.d.cts +64 -0
- package/dist/types/transactionTypes.d.cts.map +1 -0
- package/dist/types/transactionTypes.d.mts +64 -0
- package/dist/types/transactionTypes.d.mts.map +1 -0
- package/dist/types/transactionTypes.mjs +23 -0
- package/dist/types/transactionTypes.mjs.map +1 -0
- package/dist/utils/accountUtils.cjs +65 -0
- package/dist/utils/accountUtils.cjs.map +1 -0
- package/dist/utils/accountUtils.d.cts +26 -0
- package/dist/utils/accountUtils.d.cts.map +1 -0
- package/dist/utils/accountUtils.d.mts +26 -0
- package/dist/utils/accountUtils.d.mts.map +1 -0
- package/dist/utils/accountUtils.mjs +61 -0
- package/dist/utils/accountUtils.mjs.map +1 -0
- package/dist/utils/amountConversion.cjs +61 -0
- package/dist/utils/amountConversion.cjs.map +1 -0
- package/dist/utils/amountConversion.d.cts +16 -0
- package/dist/utils/amountConversion.d.cts.map +1 -0
- package/dist/utils/amountConversion.d.mts +16 -0
- package/dist/utils/amountConversion.d.mts.map +1 -0
- package/dist/utils/amountConversion.mjs +54 -0
- package/dist/utils/amountConversion.mjs.map +1 -0
- package/dist/utils/chartUtils.cjs +98 -0
- package/dist/utils/chartUtils.cjs.map +1 -0
- package/dist/utils/chartUtils.d.cts +14 -0
- package/dist/utils/chartUtils.d.cts.map +1 -0
- package/dist/utils/chartUtils.d.mts +14 -0
- package/dist/utils/chartUtils.d.mts.map +1 -0
- package/dist/utils/chartUtils.mjs +94 -0
- package/dist/utils/chartUtils.mjs.map +1 -0
- package/dist/utils/errorUtils.cjs +22 -0
- package/dist/utils/errorUtils.cjs.map +1 -0
- package/dist/utils/errorUtils.d.cts +13 -0
- package/dist/utils/errorUtils.d.cts.map +1 -0
- package/dist/utils/errorUtils.d.mts +13 -0
- package/dist/utils/errorUtils.d.mts.map +1 -0
- package/dist/utils/errorUtils.mjs +18 -0
- package/dist/utils/errorUtils.mjs.map +1 -0
- package/dist/utils/formatUtils.cjs +987 -0
- package/dist/utils/formatUtils.cjs.map +1 -0
- package/dist/utils/formatUtils.d.cts +387 -0
- package/dist/utils/formatUtils.d.cts.map +1 -0
- package/dist/utils/formatUtils.d.mts +387 -0
- package/dist/utils/formatUtils.d.mts.map +1 -0
- package/dist/utils/formatUtils.mjs +966 -0
- package/dist/utils/formatUtils.mjs.map +1 -0
- package/dist/utils/hyperLiquidAdapter.cjs +454 -0
- package/dist/utils/hyperLiquidAdapter.cjs.map +1 -0
- package/dist/utils/hyperLiquidAdapter.d.cts +158 -0
- package/dist/utils/hyperLiquidAdapter.d.cts.map +1 -0
- package/dist/utils/hyperLiquidAdapter.d.mts +158 -0
- package/dist/utils/hyperLiquidAdapter.d.mts.map +1 -0
- package/dist/utils/hyperLiquidAdapter.mjs +439 -0
- package/dist/utils/hyperLiquidAdapter.mjs.map +1 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs +89 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.cjs.map +1 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts +58 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.d.cts.map +1 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts +58 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.d.mts.map +1 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs +84 -0
- package/dist/utils/hyperLiquidOrderBookProcessor.mjs.map +1 -0
- package/dist/utils/hyperLiquidValidation.cjs +426 -0
- package/dist/utils/hyperLiquidValidation.cjs.map +1 -0
- package/dist/utils/hyperLiquidValidation.d.cts +143 -0
- package/dist/utils/hyperLiquidValidation.d.cts.map +1 -0
- package/dist/utils/hyperLiquidValidation.d.mts +143 -0
- package/dist/utils/hyperLiquidValidation.d.mts.map +1 -0
- package/dist/utils/hyperLiquidValidation.mjs +413 -0
- package/dist/utils/hyperLiquidValidation.mjs.map +1 -0
- package/dist/utils/idUtils.cjs +50 -0
- package/dist/utils/idUtils.cjs.map +1 -0
- package/dist/utils/idUtils.d.cts +38 -0
- package/dist/utils/idUtils.d.cts.map +1 -0
- package/dist/utils/idUtils.d.mts +38 -0
- package/dist/utils/idUtils.d.mts.map +1 -0
- package/dist/utils/idUtils.mjs +42 -0
- package/dist/utils/idUtils.mjs.map +1 -0
- package/dist/utils/marginUtils.cjs +137 -0
- package/dist/utils/marginUtils.cjs.map +1 -0
- package/dist/utils/marginUtils.d.cts +64 -0
- package/dist/utils/marginUtils.d.cts.map +1 -0
- package/dist/utils/marginUtils.d.mts +64 -0
- package/dist/utils/marginUtils.d.mts.map +1 -0
- package/dist/utils/marginUtils.mjs +131 -0
- package/dist/utils/marginUtils.mjs.map +1 -0
- package/dist/utils/marketDataTransform.cjs +227 -0
- package/dist/utils/marketDataTransform.cjs.map +1 -0
- package/dist/utils/marketDataTransform.d.cts +45 -0
- package/dist/utils/marketDataTransform.d.cts.map +1 -0
- package/dist/utils/marketDataTransform.d.mts +45 -0
- package/dist/utils/marketDataTransform.d.mts.map +1 -0
- package/dist/utils/marketDataTransform.mjs +220 -0
- package/dist/utils/marketDataTransform.mjs.map +1 -0
- package/dist/utils/marketUtils.cjs +420 -0
- package/dist/utils/marketUtils.cjs.map +1 -0
- package/dist/utils/marketUtils.d.cts +227 -0
- package/dist/utils/marketUtils.d.cts.map +1 -0
- package/dist/utils/marketUtils.d.mts +227 -0
- package/dist/utils/marketUtils.d.mts.map +1 -0
- package/dist/utils/marketUtils.mjs +404 -0
- package/dist/utils/marketUtils.mjs.map +1 -0
- package/dist/utils/orderBookGrouping.cjs +151 -0
- package/dist/utils/orderBookGrouping.cjs.map +1 -0
- package/dist/utils/orderBookGrouping.d.cts +76 -0
- package/dist/utils/orderBookGrouping.d.cts.map +1 -0
- package/dist/utils/orderBookGrouping.d.mts +76 -0
- package/dist/utils/orderBookGrouping.d.mts.map +1 -0
- package/dist/utils/orderBookGrouping.mjs +143 -0
- package/dist/utils/orderBookGrouping.mjs.map +1 -0
- package/dist/utils/orderCalculations.cjs +283 -0
- package/dist/utils/orderCalculations.cjs.map +1 -0
- package/dist/utils/orderCalculations.d.cts +107 -0
- package/dist/utils/orderCalculations.d.cts.map +1 -0
- package/dist/utils/orderCalculations.d.mts +107 -0
- package/dist/utils/orderCalculations.d.mts.map +1 -0
- package/dist/utils/orderCalculations.mjs +274 -0
- package/dist/utils/orderCalculations.mjs.map +1 -0
- package/dist/utils/orderUtils.cjs +159 -0
- package/dist/utils/orderUtils.cjs.map +1 -0
- package/dist/utils/orderUtils.d.cts +66 -0
- package/dist/utils/orderUtils.d.cts.map +1 -0
- package/dist/utils/orderUtils.d.mts +66 -0
- package/dist/utils/orderUtils.d.mts.map +1 -0
- package/dist/utils/orderUtils.mjs +151 -0
- package/dist/utils/orderUtils.mjs.map +1 -0
- package/dist/utils/pnlCalculations.cjs +107 -0
- package/dist/utils/pnlCalculations.cjs.map +1 -0
- package/dist/utils/pnlCalculations.d.cts +79 -0
- package/dist/utils/pnlCalculations.d.cts.map +1 -0
- package/dist/utils/pnlCalculations.d.mts +79 -0
- package/dist/utils/pnlCalculations.d.mts.map +1 -0
- package/dist/utils/pnlCalculations.mjs +97 -0
- package/dist/utils/pnlCalculations.mjs.map +1 -0
- package/dist/utils/positionCalculations.cjs +176 -0
- package/dist/utils/positionCalculations.cjs.map +1 -0
- package/dist/utils/positionCalculations.d.cts +85 -0
- package/dist/utils/positionCalculations.d.cts.map +1 -0
- package/dist/utils/positionCalculations.d.mts +85 -0
- package/dist/utils/positionCalculations.d.mts.map +1 -0
- package/dist/utils/positionCalculations.mjs +165 -0
- package/dist/utils/positionCalculations.mjs.map +1 -0
- package/dist/utils/sortMarkets.cjs +88 -0
- package/dist/utils/sortMarkets.cjs.map +1 -0
- package/dist/utils/sortMarkets.d.cts +21 -0
- package/dist/utils/sortMarkets.d.cts.map +1 -0
- package/dist/utils/sortMarkets.d.mts +21 -0
- package/dist/utils/sortMarkets.d.mts.map +1 -0
- package/dist/utils/sortMarkets.mjs +84 -0
- package/dist/utils/sortMarkets.mjs.map +1 -0
- package/dist/utils/standaloneInfoClient.cjs +34 -0
- package/dist/utils/standaloneInfoClient.cjs.map +1 -0
- package/dist/utils/standaloneInfoClient.d.cts +31 -0
- package/dist/utils/standaloneInfoClient.d.cts.map +1 -0
- package/dist/utils/standaloneInfoClient.d.mts +31 -0
- package/dist/utils/standaloneInfoClient.d.mts.map +1 -0
- package/dist/utils/standaloneInfoClient.mjs +30 -0
- package/dist/utils/standaloneInfoClient.mjs.map +1 -0
- package/dist/utils/stringParseUtils.cjs +49 -0
- package/dist/utils/stringParseUtils.cjs.map +1 -0
- package/dist/utils/stringParseUtils.d.cts +35 -0
- package/dist/utils/stringParseUtils.d.cts.map +1 -0
- package/dist/utils/stringParseUtils.d.mts +35 -0
- package/dist/utils/stringParseUtils.d.mts.map +1 -0
- package/dist/utils/stringParseUtils.mjs +44 -0
- package/dist/utils/stringParseUtils.mjs.map +1 -0
- package/dist/utils/time.cjs +37 -0
- package/dist/utils/time.cjs.map +1 -0
- package/dist/utils/time.d.cts +17 -0
- package/dist/utils/time.d.cts.map +1 -0
- package/dist/utils/time.d.mts +17 -0
- package/dist/utils/time.d.mts.map +1 -0
- package/dist/utils/time.mjs +33 -0
- package/dist/utils/time.mjs.map +1 -0
- package/dist/utils/tpslValidation.cjs +505 -0
- package/dist/utils/tpslValidation.cjs.map +1 -0
- package/dist/utils/tpslValidation.d.cts +182 -0
- package/dist/utils/tpslValidation.d.cts.map +1 -0
- package/dist/utils/tpslValidation.d.mts +182 -0
- package/dist/utils/tpslValidation.d.mts.map +1 -0
- package/dist/utils/tpslValidation.mjs +482 -0
- package/dist/utils/tpslValidation.mjs.map +1 -0
- package/dist/utils/transactionUtils.cjs +36 -0
- package/dist/utils/transactionUtils.cjs.map +1 -0
- package/dist/utils/transactionUtils.d.cts +17 -0
- package/dist/utils/transactionUtils.d.cts.map +1 -0
- package/dist/utils/transactionUtils.d.mts +17 -0
- package/dist/utils/transactionUtils.d.mts.map +1 -0
- package/dist/utils/transactionUtils.mjs +32 -0
- package/dist/utils/transactionUtils.mjs.map +1 -0
- package/dist/utils/wait.cjs +12 -0
- package/dist/utils/wait.cjs.map +1 -0
- package/dist/utils/wait.d.cts +8 -0
- package/dist/utils/wait.d.cts.map +1 -0
- package/dist/utils/wait.d.mts +8 -0
- package/dist/utils/wait.d.mts.map +1 -0
- package/dist/utils/wait.mjs +8 -0
- package/dist/utils/wait.mjs.map +1 -0
- package/package.json +19 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HyperLiquidProvider.mjs","sourceRoot":"","sources":["../../src/providers/HyperLiquidProvider.ts"],"names":[],"mappings":"AAAA,8TAA8T;AAC9T,4BAA4B;AAC5B,iFAAiF;AACjF,iDAAiD;AACjD,yFAAyF;AACzF,sDAAsD;AACtD,qFAAqF;AACrF,wDAAwD;AACxD,sHAAsH;AACtH,6DAA6D;AAC7D,uEAAuE;AAIvE,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAEpC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,UAAU,EACV,uBAAuB,EACvB,eAAe,EACf,kBAAkB,EAClB,8BAA8B,EAC9B,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,WAAW,EACZ,2CAAuC;AACxC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,oCAAoC,EACrC,qCAAiC;AAClC,OAAO,EAAE,iBAAiB,EAAE,yCAAqC;AACjE,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACzB,0DAAsD;AACvD,OAAO,EAAE,8BAA8B,EAAE,gEAA4D;AACrG,OAAO,EAAE,wBAAwB,EAAE,0DAAsD;AAmEzF,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAClD,OAAO,EACL,wBAAwB,EACxB,6CAA6C,EAC7C,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,cAAc,EACf,wCAAoC;AACrC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EACpB,eAAe,EACf,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,wBAAwB,EACzB,2CAAuC;AACxC,OAAO,EAAE,mBAAmB,EAAE,yCAAqC;AACnE,OAAO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cAAc,GAAG,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,CAAC;YAC9D,MAAM,YAAY,GAAG,IAAI,CAAC,eAAe,CACvC,IAAI,CAAC,aAAa,CAAC,aAAa,EAAE,CACnC,CAAC;YAEF,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,yCAAyC,EAAE;gBACnE,IAAI,EAAE,YAAY;gBAClB,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;aACpE,CAAC,CAAC;YAEH,wBAAwB;YACxB,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC;gBAC9C,IAAI,EAAE,YAAY;aACnB,CAAC,CAAC;YAEH,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CACvB,4CAA4C,EAC5C,MAAM,CACP,CAAC;YAEF,OAAO,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CACpB,WAAW,CAAC,KAAK,CAAC,EAClB,IAAI,CAAC,eAAe,CAAC,iBAAiB,EAAE;gBACtC,IAAI,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,aAAa,CAAC,aAAa,EAAE,CAAC;aAC/D,CAAC,CACH,CAAC;YACF,2DAA2D;YAC3D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["/* eslint-disable no-restricted-syntax, jsdoc/require-returns, jsdoc/check-param-names, jsdoc/require-param-description, @typescript-eslint/explicit-function-return-type, no-invalid-this, no-negated-condition, no-nested-ternary, @typescript-eslint/prefer-nullish-coalescing, consistent-return, promise/always-return */\n// Remaining disabled rules:\n// - no-restricted-syntax: Core requires `#` private fields but uses class syntax\n// - jsdoc/*: JSDoc improvements are low priority\n// - @typescript-eslint/explicit-function-return-type: Auto-inferred types are acceptable\n// - no-invalid-this: False positives in class methods\n// - no-negated-condition: Style preference, ~54 occurrences - too invasive to change\n// - no-nested-ternary: Only 2 occurrences, low priority\n// - @typescript-eslint/prefer-nullish-coalescing: ~44 occurrences - requires careful review for falsy value semantics\n// - consistent-return: Multiple occurrences in async methods\n// - promise/always-return: Requires returns in .then()/.catch() chains\n\nimport { CaipAccountId } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport {\n BASIS_POINTS_DIVISOR,\n BUILDER_FEE_CONFIG,\n FEE_RATES,\n getBridgeInfo,\n getChainId,\n HIP3_ASSET_MARKET_TYPES,\n HIP3_FEE_CONFIG,\n HIP3_MARGIN_CONFIG,\n HYPERLIQUID_WITHDRAWAL_MINUTES,\n REFERRAL_CONFIG,\n TESTNET_HIP3_CONFIG,\n TRADING_DEFAULTS,\n USDC_DECIMALS,\n USDH_CONFIG,\n} from '../constants/hyperLiquidConfig';\nimport {\n ORDER_SLIPPAGE_CONFIG,\n PERFORMANCE_CONFIG,\n PERPS_CONSTANTS,\n TP_SL_CONFIG,\n WITHDRAWAL_CONSTANTS,\n PERPS_TRANSACTIONS_HISTORY_CONSTANTS,\n} from '../constants/perpsConfig';\nimport { PERPS_ERROR_CODES } from '../constants/perpsErrorCodes';\nimport {\n HyperLiquidClientService,\n WebSocketConnectionState,\n} from '../platform-services/HyperLiquidClientService';\nimport { HyperLiquidSubscriptionService } from '../platform-services/HyperLiquidSubscriptionService';\nimport { HyperLiquidWalletService } from '../platform-services/HyperLiquidWalletService';\nimport type {\n AccountState,\n AssetRoute,\n BatchCancelOrdersParams,\n CancelOrderParams,\n CancelOrderResult,\n CancelOrdersResult,\n ClosePositionParams,\n ClosePositionsParams,\n ClosePositionsResult,\n DepositParams,\n DisconnectResult,\n EditOrderParams,\n FeeCalculationParams,\n FeeCalculationResult,\n Funding,\n GetAccountStateParams,\n GetAvailableDexsParams,\n GetFundingParams,\n GetHistoricalPortfolioParams,\n GetMarketsParams,\n GetOrderFillsParams,\n GetOrdersParams,\n GetPositionsParams,\n GetSupportedPathsParams,\n HistoricalPortfolioResult,\n InitializeResult,\n PerpsPlatformDependencies,\n PerpsProvider,\n LiquidationPriceParams,\n LiveDataConfig,\n MaintenanceMarginParams,\n MarginResult,\n MarketInfo,\n Order,\n OrderFill,\n OrderParams,\n OrderResult,\n PerpsMarketData,\n Position,\n RawHyperLiquidLedgerUpdate,\n ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n TransferBetweenDexsParams,\n TransferBetweenDexsResult,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n} from '../types';\nimport type {\n SDKOrderParams,\n MetaResponse,\n PerpsAssetCtx,\n FrontendOrder,\n ExtendedAssetMeta,\n ExtendedPerpDex,\n} from '../types/hyperliquid-types';\nimport { ensureError } from '../utils/errorUtils';\nimport {\n adaptAccountStateFromSDK,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n adaptMarketFromSDK,\n adaptOrderFromSDK,\n adaptPositionFromSDK,\n buildAssetMapping,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n parseAssetName,\n} from '../utils/hyperLiquidAdapter';\nimport {\n createErrorResult,\n getMaxOrderValue,\n getSupportedPaths,\n validateAssetSupport,\n validateBalance,\n validateCoinExists,\n validateDepositParams,\n validateOrderParams,\n validateWithdrawalParams,\n} from '../utils/hyperLiquidValidation';\nimport { transformMarketData } from '../utils/marketDataTransform';\nimport {\n compileMarketPattern,\n shouldIncludeMarket,\n} from '../utils/marketUtils';\nimport type { CompiledMarketPattern } from '../utils/marketUtils';\nimport {\n buildOrdersArray,\n calculateFinalPositionSize,\n calculateOrderPriceAndSize,\n} from '../utils/orderCalculations';\nimport { createStandaloneInfoClient } from '../utils/standaloneInfoClient';\n\n/**\n * Type guard to check if a status is an object (not a string literal like \"waitingForFill\")\n * The SDK returns status as a union of object types and string literals.\n *\n * @param status - The status value to check.\n * @returns True if the status is an object (not a string literal).\n */\nconst isStatusObject = (status: unknown): status is Record<string, unknown> =>\n typeof status === 'object' && status !== null;\n\n// Helper method parameter interfaces (module-level for class-dependent methods only)\ntype GetAssetInfoParams = {\n symbol: string;\n dexName: string | null;\n};\n\ntype GetAssetInfoResult = {\n assetInfo: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n };\n currentPrice: number;\n meta: MetaResponse;\n};\n\ntype PrepareAssetForTradingParams = {\n symbol: string;\n assetId: number;\n leverage?: number;\n};\n\ntype HandleHip3PreOrderParams = {\n dexName: string;\n symbol: string;\n orderPrice: number;\n positionSize: number;\n leverage: number;\n isBuy: boolean;\n maxLeverage: number;\n};\n\ntype HandleHip3PreOrderResult = {\n transferInfo: { amount: number; sourceDex: string } | null;\n};\n\ntype SubmitOrderWithRollbackParams = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n isHip3Order: boolean;\n dexName: string | null;\n transferInfo: { amount: number; sourceDex: string } | null;\n symbol: string;\n assetId: number;\n};\n\ntype HandleOrderErrorParams = {\n error: unknown;\n symbol: string;\n orderType: 'market' | 'limit';\n isBuy: boolean;\n};\n\n/**\n * HyperLiquid provider implementation\n *\n * Implements the PerpsProvider interface for HyperLiquid protocol.\n * Uses the @nktkas/hyperliquid SDK for all operations.\n * Delegates to service classes for client management, wallet integration, and subscriptions.\n *\n * HIP-3 Balance Management:\n * Attempts to use HyperLiquid's native DEX abstraction for automatic collateral transfers.\n * If not supported, falls back to programmatic balance management using SDK's sendAsset.\n */\nexport class HyperLiquidProvider implements PerpsProvider {\n readonly protocolId = 'hyperliquid';\n\n // Platform dependencies for logging and debugging\n private readonly deps: PerpsPlatformDependencies;\n\n // Service instances\n private readonly clientService: HyperLiquidClientService;\n\n private readonly walletService: HyperLiquidWalletService;\n\n private readonly subscriptionService: HyperLiquidSubscriptionService;\n\n // Asset mapping\n private readonly symbolToAssetId = new Map<string, number>();\n\n // Cache for user fee rates to avoid excessive API calls\n private readonly userFeeCache = new Map<\n string,\n {\n perpsTakerRate: number;\n perpsMakerRate: number;\n spotTakerRate: number;\n spotMakerRate: number;\n timestamp: number;\n ttl: number;\n }\n >();\n\n // Cache for max leverage values to avoid excessive API calls\n private readonly maxLeverageCache = new Map<\n string,\n { value: number; timestamp: number }\n >();\n\n // Cache for raw meta responses (shared across methods to avoid redundant API calls)\n // Filtering is applied on-demand (cheap array operations) - no need for separate processed cache\n private readonly cachedMetaByDex = new Map<string, MetaResponse>();\n\n // Cache for perpDexs data (deployerFeeScale for dynamic fee calculation)\n // TTL-based cache - fee scales rarely change\n private perpDexsCache: {\n data: ExtendedPerpDex[] | null;\n timestamp: number;\n } = { data: null, timestamp: 0 };\n\n // Session cache for referral state (cleared on disconnect/reconnect)\n // Key: `network:userAddress`, Value: true if referral is set\n private readonly referralCheckCache = new Map<string, boolean>();\n\n // Session cache for builder fee approval state (cleared on disconnect/reconnect)\n // Key: `network:userAddress`, Value: true if builder fee is approved\n private readonly builderFeeCheckCache = new Map<string, boolean>();\n\n // Pending promise trackers for deduplicating concurrent calls\n // Prevents multiple signature requests when methods called simultaneously\n private ensureReadyPromise: Promise<void> | null = null;\n\n private readonly pendingBuilderFeeApprovals = new Map<\n string,\n Promise<void>\n >();\n\n // Pre-compiled patterns for fast filtering\n private readonly compiledAllowlistPatterns: CompiledMarketPattern[] = [];\n\n private readonly compiledBlocklistPatterns: CompiledMarketPattern[] = [];\n\n // Fee discount context for MetaMask reward discounts (in basis points)\n private userFeeDiscountBips?: number;\n\n // Feature flag configuration for HIP-3 market filtering\n private readonly hip3Enabled: boolean;\n\n private readonly allowlistMarkets: string[];\n\n private readonly blocklistMarkets: string[];\n\n private useDexAbstraction: boolean;\n\n // Cache for validated DEXs to avoid redundant perpDexs() API calls\n private cachedValidatedDexs: (string | null)[] | null = null;\n\n private cachedAllPerpDexs: Awaited<\n ReturnType<ReturnType<typeof this.clientService.getInfoClient>['perpDexs']>\n > | null = null;\n\n // Pending promise to deduplicate concurrent getValidatedDexs() calls\n private pendingValidatedDexsPromise: Promise<(string | null)[]> | null = null;\n\n // Cache for USDC token ID from spot metadata\n private cachedUsdcTokenId?: string;\n\n // Error mappings from HyperLiquid API errors to standardized PERPS_ERROR_CODES\n private readonly errorMappings = {\n 'isolated position does not have sufficient margin available to decrease leverage':\n PERPS_ERROR_CODES.ORDER_LEVERAGE_REDUCTION_FAILED,\n 'could not immediately match': PERPS_ERROR_CODES.IOC_CANCEL,\n };\n\n // Track whether clients have been initialized (lazy initialization)\n private clientsInitialized = false;\n\n // Promise-based lock to prevent race conditions in concurrent initialization\n private initializationPromise: Promise<void> | null = null;\n\n constructor(options: {\n isTestnet?: boolean;\n hip3Enabled?: boolean;\n allowlistMarkets?: string[];\n blocklistMarkets?: string[];\n useDexAbstraction?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n }) {\n this.deps = options.platformDependencies;\n const isTestnet = options.isTestnet ?? false;\n\n // Dev-friendly defaults: Enable all markets by default for easier testing (discovery mode)\n this.hip3Enabled = options.hip3Enabled ?? false;\n this.allowlistMarkets = options.allowlistMarkets ?? [];\n this.blocklistMarkets = options.blocklistMarkets ?? [];\n\n // Attempt native balance abstraction, fallback to programmatic transfer if unsupported\n this.useDexAbstraction = options.useDexAbstraction ?? true;\n\n // Initialize services with injected platform dependencies\n this.clientService = new HyperLiquidClientService(this.deps, { isTestnet });\n this.walletService = new HyperLiquidWalletService(this.deps, { isTestnet });\n this.subscriptionService = new HyperLiquidSubscriptionService(\n this.clientService,\n this.walletService,\n this.deps,\n this.hip3Enabled,\n [], // enabledDexs - will be populated after DEX discovery in buildAssetMapping\n this.allowlistMarkets,\n this.blocklistMarkets,\n );\n\n // NOTE: Clients are NOT initialized here - they'll be initialized lazily\n // when first needed. This avoids accessing Engine.context before it's ready.\n\n // Pre-compile filter patterns for performance\n this.compiledAllowlistPatterns = this.allowlistMarkets.map((pattern) => ({\n pattern,\n matcher: compileMarketPattern(pattern),\n }));\n this.compiledBlocklistPatterns = this.blocklistMarkets.map((pattern) => ({\n pattern,\n matcher: compileMarketPattern(pattern),\n }));\n\n // Debug: Confirm batch methods exist and show HIP-3 config\n this.deps.debugLogger.log('[HyperLiquidProvider] Constructor complete', {\n hasBatchCancel: typeof this.cancelOrders === 'function',\n hasBatchClose: typeof this.closePositions === 'function',\n protocolId: this.protocolId,\n hip3Enabled: this.hip3Enabled,\n allowlistMarkets: this.allowlistMarkets,\n blocklistMarkets: this.blocklistMarkets,\n isTestnet,\n });\n }\n\n /**\n * Initialize HyperLiquid SDK clients (lazy initialization)\n *\n * This is called on first API operation to ensure Engine.context is ready.\n * Creating the wallet adapter requires accessing Engine.context.AccountTreeController,\n * which may not be available during early app initialization.\n *\n * IMPORTANT: This method awaits the WebSocket transport.ready() to ensure\n * the connection is fully established before marking initialization complete.\n */\n private async ensureClientsInitialized(): Promise<void> {\n if (this.clientsInitialized) {\n return; // Already initialized\n }\n\n // Reuse existing initialization promise if one is in progress\n // This prevents race conditions when multiple methods call concurrently\n if (this.initializationPromise) {\n await this.initializationPromise;\n return;\n }\n\n // Create and cache the initialization promise\n this.initializationPromise = (async () => {\n // Double-check after acquiring the \"lock\"\n if (this.clientsInitialized) {\n return;\n }\n\n const wallet = this.walletService.createWalletAdapter();\n await this.clientService.initialize(wallet);\n\n // Set termination callback for logging when WebSocket terminates\n // Note: Do NOT restore subscriptions here - termination means connection failed permanently\n this.clientService.setOnTerminateCallback((error: Error) => {\n this.deps.debugLogger.log(\n '[HyperLiquidProvider] WebSocket terminated',\n {\n error: error.message,\n },\n );\n });\n\n // Set reconnection callback to restore subscriptions after successful reconnection\n // This is called in handleConnectionDrop() after the WebSocket reconnects successfully\n this.clientService.setOnReconnectCallback(async () => {\n try {\n this.deps.debugLogger.log(\n '[HyperLiquidProvider] WebSocket reconnected, restoring subscriptions',\n );\n await this.subscriptionService.restoreSubscriptions();\n const { streamManager } = this.deps;\n streamManager.clearAllChannels();\n } catch (restoreError) {\n this.deps.debugLogger.log(\n '[HyperLiquidProvider] Failed to restore subscriptions',\n restoreError,\n );\n }\n });\n\n // Only set flag AFTER successful initialization\n this.clientsInitialized = true;\n\n this.deps.debugLogger.log(\n '[HyperLiquidProvider] Clients initialized lazily',\n );\n })();\n\n try {\n await this.initializationPromise;\n } finally {\n // Clear promise after completion (success or failure)\n // so future calls can retry if needed\n this.initializationPromise = null;\n }\n }\n\n /**\n * Attempt to enable HIP-3 native balance abstraction\n *\n * If successful, HyperLiquid automatically manages collateral transfers for HIP-3 orders.\n * If not supported, disables the flag to trigger programmatic transfer fallback.\n *\n * @private\n */\n private async ensureDexAbstractionEnabled(): Promise<void> {\n if (!this.useDexAbstraction) {\n return; // Feature disabled\n }\n\n try {\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n // Check if already enabled (returns boolean | null)\n const isEnabled = await infoClient.userDexAbstraction({\n user: userAddress,\n });\n\n if (isEnabled === true) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction already enabled',\n {\n user: userAddress,\n },\n );\n return;\n }\n\n // Enable DEX abstraction (one-time, irreversible)\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Enabling DEX abstraction',\n {\n user: userAddress,\n note: 'HyperLiquid will auto-manage collateral for HIP-3 orders',\n },\n );\n\n const exchangeClient = this.clientService.getExchangeClient();\n await exchangeClient.agentEnableDexAbstraction();\n\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: DEX abstraction enabled successfully',\n );\n } catch (error) {\n // Don't blindly disable the flag on any error\n // Network errors or unknown issues shouldn't trigger fallback to manual transfer\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('ensureDexAbstractionEnabled', {\n note: 'Could not enable DEX abstraction (may already be enabled or network error), will verify on first order',\n }),\n );\n // Keep useDexAbstraction flag as-is, let placeOrder() verify actual status if needed\n }\n }\n\n /**\n * Ensure clients are initialized and asset mapping is loaded\n * Asset mapping is built once on first call and reused for the provider's lifetime\n * since HIP-3 configuration is immutable after construction\n */\n private async ensureReady(): Promise<void> {\n // If already initializing or completed, wait for/return that promise\n // This prevents duplicate initialization flows when multiple methods called concurrently\n if (this.ensureReadyPromise) {\n this.deps.debugLogger.log(\n '[ensureReady] Reusing existing initialization promise',\n );\n await this.ensureReadyPromise;\n return;\n }\n\n this.deps.debugLogger.log('[ensureReady] Starting new initialization');\n\n // Create and track initialization promise\n this.ensureReadyPromise = (async () => {\n // Lazy initialization: ensure clients are created (safe after Engine.context is ready)\n // This awaits WebSocket transport.ready() to ensure connection is established\n await this.ensureClientsInitialized();\n\n // Verify clients are properly initialized\n this.clientService.ensureInitialized();\n\n // Build asset mapping on first call only (flags are immutable)\n if (this.symbolToAssetId.size === 0) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Building asset mapping',\n {\n hip3Enabled: this.hip3Enabled,\n allowlistMarkets: this.allowlistMarkets,\n blocklistMarkets: this.blocklistMarkets,\n },\n );\n await this.buildAssetMapping();\n }\n\n // Attempt to enable native balance abstraction\n await this.ensureDexAbstractionEnabled();\n\n // Set up builder fee approval (non-blocking for viewing data)\n // This happens once per session and is cached until disconnect/reconnect\n // Note: Wrapped in try-catch so accounts without deposits can still view markets\n try {\n await this.ensureBuilderFeeApproval();\n } catch (error) {\n // Log but don't throw - builder fee is only needed for trading, not viewing\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Builder fee approval failed (will retry on first trade)',\n error,\n );\n }\n\n // Set up referral code (blocks initialization to ensure attribution attempt)\n // Non-throwing: errors caught internally, logged to Sentry, retry next session\n // User can trade immediately after init even if referral setup failed\n await this.ensureReferralSet();\n })();\n\n // Await initialization - keep the promise so subsequent calls resolve immediately\n // The promise is only reset in disconnect() for clean reconnection\n await this.ensureReadyPromise;\n this.deps.debugLogger.log('[ensureReady] Initialization complete');\n }\n\n /**\n * Get all available DEXs without allowlist filtering\n * Used when skipFilters=true in getMarkets()\n *\n * @returns Array of all DEX names (null for main DEX, strings for HIP-3 DEXs)\n */\n private async getAllAvailableDexs(): Promise<(string | null)[]> {\n // If already cached by getValidatedDexs, use that\n if (\n this.cachedAllPerpDexs !== null &&\n Array.isArray(this.cachedAllPerpDexs)\n ) {\n const availableHip3Dexs: string[] = [];\n this.cachedAllPerpDexs.forEach((dex) => {\n if (dex !== null) {\n availableHip3Dexs.push(dex.name);\n }\n });\n return [null, ...availableHip3Dexs];\n }\n\n // Fetch fresh from API\n const infoClient = this.clientService.getInfoClient();\n try {\n const allDexs = await infoClient.perpDexs();\n if (!allDexs || !Array.isArray(allDexs)) {\n return [null]; // Fallback to main DEX only\n }\n\n this.cachedAllPerpDexs = allDexs;\n const availableHip3Dexs: string[] = [];\n allDexs.forEach((dex) => {\n if (dex !== null) {\n availableHip3Dexs.push(dex.name);\n }\n });\n return [null, ...availableHip3Dexs];\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getAllAvailableDexs'),\n );\n return [null]; // Fallback to main DEX only\n }\n }\n\n /**\n * Get validated list of DEXs to use based on feature flags and allowlist\n * Implements Step 3b from HIP-3-IMPLEMENTATION.md (lines 108-134)\n *\n * Logic Flow:\n * 1. If hip3Enabled === false → Return [null] (main DEX only)\n * 2. Fetch available DEXs via SDK: infoClient.perpDexs()\n * 3. If enabledDexs is empty [] → Return [null, ...allDiscoveredDexs] (auto-discover)\n * 4. Else filter enabledDexs against available DEXs → Return [null, ...validatedDexs] (allowlist)\n *\n * Invalid DEX names are silently filtered with debugLogger warning.\n *\n * @returns Array of DEX names to use (null = main DEX, strings = HIP-3 DEXs)\n */\n private async getValidatedDexs(): Promise<(string | null)[]> {\n // Return cached result if available\n if (this.cachedValidatedDexs !== null) {\n return this.cachedValidatedDexs;\n }\n\n // If a fetch is already in progress, reuse the pending promise\n // This prevents duplicate perpDexs() API calls from concurrent callers\n if (this.pendingValidatedDexsPromise !== null) {\n this.deps.debugLogger.log(\n '[getValidatedDexs] Reusing pending promise for perpDexs fetch',\n );\n return this.pendingValidatedDexsPromise;\n }\n\n // Create and cache the pending promise for deduplication\n this.pendingValidatedDexsPromise = this.fetchValidatedDexsInternal();\n\n try {\n const result = await this.pendingValidatedDexsPromise;\n return result;\n } finally {\n // Clear the pending promise when done (success or error)\n this.pendingValidatedDexsPromise = null;\n }\n }\n\n /**\n * Internal method that performs the actual perpDexs fetch and caching\n * Separated from getValidatedDexs to enable promise deduplication\n */\n private async fetchValidatedDexsInternal(): Promise<(string | null)[]> {\n // Kill switch: HIP-3 disabled, return main DEX only\n if (!this.hip3Enabled) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: HIP-3 disabled via hip3Enabled flag',\n );\n this.cachedAllPerpDexs = [null];\n this.cachedValidatedDexs = [null];\n return this.cachedValidatedDexs;\n }\n\n // Fetch all available DEXs from HyperLiquid\n const infoClient = this.clientService.getInfoClient();\n let allDexs;\n try {\n allDexs = await infoClient.perpDexs();\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getValidatedDexs.perpDexs'),\n );\n this.cachedAllPerpDexs = [null];\n this.cachedValidatedDexs = [null];\n return this.cachedValidatedDexs;\n }\n\n // Cache for buildAssetMapping() to avoid duplicate call\n this.cachedAllPerpDexs = allDexs;\n\n // Validate API response\n if (!allDexs || !Array.isArray(allDexs)) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Failed to fetch DEX list (invalid response), falling back to main DEX only',\n { allDexs },\n );\n this.cachedAllPerpDexs = [null];\n this.cachedValidatedDexs = [null];\n return this.cachedValidatedDexs;\n }\n\n // Extract HIP-3 DEX names (filter out null which represents main DEX)\n const availableHip3Dexs: string[] = [];\n allDexs.forEach((dex) => {\n if (dex !== null) {\n availableHip3Dexs.push(dex.name);\n }\n });\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Available DEXs (market filtering applied at data layer)',\n {\n count: availableHip3Dexs.length,\n dexNames: availableHip3Dexs,\n },\n );\n\n // Testnet-specific filtering: Limit DEXs to avoid subscription overload\n // On testnet, there are many HIP-3 DEXs (test deployments) that cause instability\n if (this.clientService.isTestnetMode()) {\n const { EnabledDexs, AutoDiscoverAll } = TESTNET_HIP3_CONFIG;\n\n if (!AutoDiscoverAll) {\n if (EnabledDexs.length === 0) {\n // Main DEX only - no HIP-3 DEXs on testnet\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Testnet - using main DEX only (HIP-3 DEXs filtered)',\n {\n availableHip3Dexs: availableHip3Dexs.length,\n reason: 'TESTNET_HIP3_CONFIG.EnabledDexs is empty',\n },\n );\n this.cachedValidatedDexs = [null];\n return this.cachedValidatedDexs;\n }\n\n // Filter to specific allowed DEXs on testnet\n const filteredDexs = availableHip3Dexs.filter((dex) =>\n EnabledDexs.includes(dex),\n );\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Testnet - filtered to allowed DEXs',\n {\n allowedDexs: EnabledDexs,\n filteredDexs,\n availableHip3Dexs: availableHip3Dexs.length,\n },\n );\n this.cachedValidatedDexs = [null, ...filteredDexs];\n return this.cachedValidatedDexs;\n }\n\n // AUTO_DISCOVER_ALL is true - proceed with all DEXs (not recommended for testnet)\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Testnet - AUTO_DISCOVER_ALL enabled, using all DEXs',\n { totalDexCount: availableHip3Dexs.length + 1 },\n );\n }\n\n // Mainnet (or testnet with AUTO_DISCOVER_ALL): Return all DEXs\n // Market filtering is applied at subscription data layer\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: All DEXs enabled (market filtering at data layer)',\n {\n mainDex: true,\n hip3Dexs: availableHip3Dexs,\n totalDexCount: availableHip3Dexs.length + 1,\n },\n );\n this.cachedValidatedDexs = [null, ...availableHip3Dexs];\n return this.cachedValidatedDexs;\n }\n\n /**\n * Get cached meta response for a DEX, fetching from API if not cached\n * This helper consolidates cache logic to avoid redundant API calls across the provider\n *\n * @param params.dexName - DEX name (null for main DEX)\n * @param params.skipCache - If true, bypass cache and fetch fresh data\n * @param params\n * @returns MetaResponse with universe data\n * @throws Error if API returns invalid data\n */\n private async getCachedMeta(params: {\n dexName: string | null;\n skipCache?: boolean;\n }): Promise<MetaResponse> {\n const { dexName, skipCache } = params;\n // Use empty string for main DEX key (consistent with buildAssetMapping cache population)\n const dexKey = dexName ?? '';\n const dexDisplayName = dexKey || 'main';\n\n // Skip cache if requested (forces fresh fetch)\n if (!skipCache) {\n const cached = this.cachedMetaByDex.get(dexKey);\n if (cached) {\n this.deps.debugLogger.log(\n '[getCachedMeta] Using cached meta response',\n {\n dex: dexDisplayName,\n universeSize: cached.universe.length,\n },\n );\n return cached;\n }\n }\n\n // Cache miss or skipCache=true - fetch from API\n const infoClient = this.clientService.getInfoClient();\n const meta = await infoClient.meta({ dex: dexKey });\n\n // Defensive validation before caching\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n throw new Error(\n `[HyperLiquidProvider] Invalid meta response for DEX ${dexDisplayName}: universe is ${meta?.universe ? 'not an array' : 'missing'}`,\n );\n }\n\n // Store raw meta response for reuse\n this.cachedMetaByDex.set(dexKey, meta);\n\n this.deps.debugLogger.log(\n '[getCachedMeta] Fetched and cached meta response',\n {\n dex: dexDisplayName,\n universeSize: meta.universe.length,\n skipCache,\n },\n );\n\n return meta;\n }\n\n /**\n * Fetch perpDexs data with TTL-based caching\n * Returns deployerFeeScale info needed for dynamic fee calculation\n *\n * @returns Array of ExtendedPerpDex objects (null entries represent main DEX)\n */\n private async getCachedPerpDexs(): Promise<ExtendedPerpDex[]> {\n const now = Date.now();\n\n // Return cached data if still valid\n if (\n this.perpDexsCache.data &&\n now - this.perpDexsCache.timestamp < HIP3_FEE_CONFIG.PerpDexsCacheTtlMs\n ) {\n this.deps.debugLogger.log(\n '[getCachedPerpDexs] Using cached perpDexs data',\n {\n age: `${Math.round((now - this.perpDexsCache.timestamp) / 1000)}s`,\n count: this.perpDexsCache.data.length,\n },\n );\n return this.perpDexsCache.data;\n }\n\n // Fetch fresh data from API\n // Note: SDK types are incomplete, but API returns deployerFeeScale\n await this.ensureClientsInitialized();\n const infoClient = this.clientService.getInfoClient();\n const perpDexs =\n (await infoClient.perpDexs()) as unknown as ExtendedPerpDex[];\n\n // Cache the result\n this.perpDexsCache = { data: perpDexs, timestamp: now };\n\n this.deps.debugLogger.log(\n '[getCachedPerpDexs] Fetched and cached perpDexs data',\n {\n count: perpDexs.length,\n dexes: perpDexs\n .filter((dex) => dex !== null)\n .map((dex) => ({\n name: dex.name,\n deployerFeeScale: dex.deployerFeeScale,\n })),\n },\n );\n\n return perpDexs;\n }\n\n /**\n * Calculate HIP-3 fee multiplier using HyperLiquid's official formula\n * Fetches deployerFeeScale from perpDexs API and growthMode from meta API\n *\n * Formula from HyperLiquid docs:\n * - scaleIfHip3 = deployerFeeScale < 1 ? deployerFeeScale + 1 : deployerFeeScale * 2\n * - growthModeScale = growthMode ? 0.1 : 1\n * - finalMultiplier = scaleIfHip3 * growthModeScale\n *\n * @param params\n * @param params.dexName\n * @param params.assetSymbol\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees#fee-formula-for-developers\n */\n private async calculateHip3FeeMultiplier(params: {\n dexName: string;\n assetSymbol: string;\n }): Promise<number> {\n const { dexName, assetSymbol } = params;\n\n try {\n // Get deployerFeeScale from perpDexs\n const perpDexs = await this.getCachedPerpDexs();\n const dexInfo = perpDexs.find((dex) => dex?.name === dexName);\n const parsedScale = parseFloat(dexInfo?.deployerFeeScale ?? '');\n const deployerFeeScale = Number.isNaN(parsedScale)\n ? HIP3_FEE_CONFIG.DefaultDeployerFeeScale\n : parsedScale;\n\n // Get growthMode from meta for this specific asset\n const meta = await this.getCachedMeta({ dexName });\n const fullAssetName = `${dexName}:${assetSymbol}`;\n const assetMeta = meta.universe.find(\n (univ) => (univ as ExtendedAssetMeta).name === fullAssetName,\n ) as ExtendedAssetMeta | undefined;\n const isGrowthMode = assetMeta?.growthMode === 'enabled';\n\n // Apply official formula\n const scaleIfHip3 =\n deployerFeeScale < 1 ? deployerFeeScale + 1 : deployerFeeScale * 2;\n const growthModeScale = isGrowthMode\n ? HIP3_FEE_CONFIG.GrowthModeScale\n : 1;\n\n const finalMultiplier = scaleIfHip3 * growthModeScale;\n\n this.deps.debugLogger.log('HIP-3 Dynamic Fee Calculation', {\n dexName,\n assetSymbol,\n fullAssetName,\n deployerFeeScale,\n isGrowthMode,\n scaleIfHip3,\n growthModeScale,\n finalMultiplier,\n });\n\n return finalMultiplier;\n } catch (error) {\n this.deps.debugLogger.log(\n 'HIP-3 Fee Calculation Failed, using fallback',\n {\n dexName,\n assetSymbol,\n error: ensureError(error).message,\n },\n );\n // Safe fallback: standard HIP-3 2x multiplier (no Growth Mode discount)\n return HIP3_FEE_CONFIG.DefaultDeployerFeeScale * 2;\n }\n }\n\n /**\n * Generate session cache key for user-specific caches\n * Format: \"network:userAddress\" (address normalized to lowercase)\n *\n * @param network - 'mainnet' or 'testnet'\n * @param userAddress - User's Ethereum address\n * @returns Cache key for session-based caches\n */\n private getCacheKey(network: string, userAddress: string): string {\n return `${network}:${userAddress.toLowerCase()}`;\n }\n\n /**\n * Fetch markets for a specific DEX with optional filtering\n * Uses session-based caching via getCachedMeta() - no TTL, cleared on disconnect\n *\n * @param params.dex - DEX name (null for main DEX)\n * @param params.skipFilters - If true, skip HIP-3 filtering (return all markets)\n * @param params.skipCache - If true, bypass cache and fetch fresh data\n * @param params\n * @returns Array of MarketInfo objects\n */\n private async fetchMarketsForDex(params: {\n dex: string | null;\n skipFilters?: boolean;\n skipCache?: boolean;\n }): Promise<MarketInfo[]> {\n const { dex, skipFilters = false, skipCache = false } = params;\n\n // Get raw meta response (uses session cache unless skipCache=true)\n const meta = await this.getCachedMeta({ dexName: dex, skipCache });\n\n if (!meta.universe || !Array.isArray(meta.universe)) {\n this.deps.debugLogger.log(\n `HyperLiquidProvider: Invalid universe data for DEX ${dex || 'main'}`,\n );\n return [];\n }\n\n // Transform to MarketInfo format\n const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset));\n\n // Apply HIP-3 filtering on-demand (cheap array operation)\n // Skip filtering for main DEX (null) or if explicitly requested\n const filteredMarkets =\n skipFilters || dex === null\n ? markets\n : markets.filter((market) =>\n shouldIncludeMarket(\n market.name,\n dex,\n this.hip3Enabled,\n this.compiledAllowlistPatterns,\n this.compiledBlocklistPatterns,\n ),\n );\n\n this.deps.debugLogger.log('HyperLiquidProvider: Fetched markets for DEX', {\n dex: dex || 'main',\n marketCount: filteredMarkets.length,\n skipFilters,\n skipCache,\n });\n\n return filteredMarkets;\n }\n\n /**\n * Get USDC token ID from spot metadata\n * Returns format: \"USDC:{hex_token_id}\"\n * Caches result to avoid repeated API calls\n */\n private async getUsdcTokenId(): Promise<string> {\n if (this.cachedUsdcTokenId) {\n return this.cachedUsdcTokenId;\n }\n\n const infoClient = this.clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n const usdcToken = spotMeta.tokens.find((tok) => tok.name === 'USDC');\n if (!usdcToken) {\n throw new Error('USDC token not found in spot metadata');\n }\n\n this.cachedUsdcTokenId = `USDC:${usdcToken.tokenId}`;\n this.deps.debugLogger.log('HyperLiquidProvider: USDC token ID cached', {\n tokenId: this.cachedUsdcTokenId,\n });\n\n return this.cachedUsdcTokenId;\n }\n\n /**\n * Check if a HIP-3 DEX uses USDH as collateral (vs USDC)\n * Per HyperLiquid docs: USDH DEXs pull collateral from spot balance automatically\n *\n * @param dexName\n */\n private async isUsdhCollateralDex(dexName: string): Promise<boolean> {\n const meta = await this.getCachedMeta({ dexName });\n const infoClient = this.clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n const collateralToken = spotMeta.tokens.find(\n (tok: { index: number }) => tok.index === meta.collateralToken,\n );\n\n const isUsdh = collateralToken?.name === USDH_CONFIG.TokenName;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Checked DEX collateral type',\n {\n dexName,\n collateralTokenIndex: meta.collateralToken,\n collateralTokenName: collateralToken?.name,\n isUsdh,\n },\n );\n\n return isUsdh;\n }\n\n /**\n * Get user's USDH balance in spot wallet\n */\n private async getSpotUsdhBalance(): Promise<number> {\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n const spotState = await infoClient.spotClearinghouseState({\n user: userAddress,\n });\n\n const usdhBalance = spotState.balances.find(\n (b: { coin: string }) => b.coin === USDH_CONFIG.TokenName,\n );\n\n const balance = usdhBalance ? parseFloat(usdhBalance.total) : 0;\n\n this.deps.debugLogger.log('HyperLiquidProvider: Spot USDH balance', {\n balance,\n userAddress,\n });\n\n return balance;\n }\n\n /**\n * Get user's USDC balance in spot wallet\n * Required for USDH DEX orders - need USDC in spot to swap to USDH\n */\n private async getSpotUsdcBalance(): Promise<number> {\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n const spotState = await infoClient.spotClearinghouseState({\n user: userAddress,\n });\n\n const usdcBalance = spotState.balances.find(\n (b: { coin: string }) => b.coin === 'USDC',\n );\n\n const balance = usdcBalance ? parseFloat(usdcBalance.total) : 0;\n\n this.deps.debugLogger.log('HyperLiquidProvider: Spot USDC balance', {\n balance,\n userAddress,\n });\n\n return balance;\n }\n\n /**\n * Transfer USDC from main perps wallet to spot wallet\n * Required before swapping USDC→USDH for USDH DEX orders\n *\n * @param amount\n */\n private async transferUsdcToSpot(\n amount: number,\n ): Promise<{ success: boolean; error?: string }> {\n const exchangeClient = this.clientService.getExchangeClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Transferring USDC to spot',\n {\n amount,\n userAddress,\n },\n );\n\n try {\n const result = await exchangeClient.sendAsset({\n destination: userAddress,\n sourceDex: '', // Main perps DEX (empty string)\n destinationDex: 'spot',\n token: await this.getUsdcTokenId(),\n amount: amount.toString(),\n });\n\n if (result.status === 'ok') {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USDC transferred to spot',\n {\n amount,\n },\n );\n return { success: true };\n }\n\n return { success: false, error: PERPS_ERROR_CODES.TRANSFER_FAILED };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USDC transfer to spot failed',\n {\n error: errorMsg,\n },\n );\n return { success: false, error: errorMsg };\n }\n }\n\n /**\n * Swap USDC to USDH on spot market\n * Returns the result of the swap including filled size\n *\n * @param amount\n */\n private async swapUsdcToUsdh(\n amount: number,\n ): Promise<{ success: boolean; filledSize?: number; error?: string }> {\n const infoClient = this.clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n // Find USDH and USDC tokens by name\n const usdhToken = spotMeta.tokens.find(\n (tok: { name: string }) => tok.name === USDH_CONFIG.TokenName,\n );\n const usdcToken = spotMeta.tokens.find(\n (tok: { name: string }) => tok.name === 'USDC',\n );\n\n if (!usdhToken || !usdcToken) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.SPOT_PAIR_NOT_FOUND,\n };\n }\n\n // Find USDH/USDC pair by token indices (NOT by name - name is @230)\n const usdhUsdcPair = spotMeta.universe.find(\n (univ: { tokens: number[] }) =>\n univ.tokens.includes(usdhToken.index) &&\n univ.tokens.includes(usdcToken.index),\n );\n\n if (!usdhUsdcPair) {\n return { success: false, error: PERPS_ERROR_CODES.SPOT_PAIR_NOT_FOUND };\n }\n\n const spotAssetId = 10000 + usdhUsdcPair.index;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Found USDH/USDC spot pair',\n {\n pairIndex: usdhUsdcPair.index,\n pairName: usdhUsdcPair.name,\n spotAssetId,\n usdhTokenIndex: usdhToken.index,\n usdcTokenIndex: usdcToken.index,\n },\n );\n\n // Get current mid price\n const allMids = await infoClient.allMids();\n const pairKey = `@${usdhUsdcPair.index}`;\n const usdhPrice = parseFloat(allMids[pairKey] || '1');\n\n if (usdhPrice === 0) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.PRICE_UNAVAILABLE,\n };\n }\n\n // Calculate order parameters\n // USDH is pegged 1:1 to USDC, add small slippage buffer\n const slippageMultiplier =\n 1 + USDH_CONFIG.SwapSlippageBps / BASIS_POINTS_DIVISOR;\n const maxPrice = usdhPrice * slippageMultiplier;\n\n // Size in USDH = amount / price (since we're buying USDH with USDC)\n let sizeInUsdh = amount / usdhPrice;\n\n // Format size according to HyperLiquid requirements\n let formattedSize = sizeInUsdh.toFixed(usdhToken.szDecimals);\n\n // CRITICAL: Ensure USDC cost meets $10 minimum after rounding\n // At price ~0.999995, buying 10.00 USDH costs 9.99995 USDC (under minimum)\n // Bump up by one increment if needed to meet minimum\n const minSpotOrderValue = TRADING_DEFAULTS.amount.mainnet;\n const estimatedCost = parseFloat(formattedSize) * usdhPrice;\n if (estimatedCost < minSpotOrderValue) {\n const increment = Math.pow(10, -usdhToken.szDecimals); // 0.01 for szDecimals=2\n sizeInUsdh = parseFloat(formattedSize) + increment;\n formattedSize = sizeInUsdh.toFixed(usdhToken.szDecimals);\n }\n\n // Format price according to HyperLiquid requirements\n const formattedPrice = formatHyperLiquidPrice({\n price: maxPrice,\n szDecimals: usdhToken.szDecimals,\n });\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Placing USDC→USDH swap order',\n {\n usdcAmount: amount,\n usdhPrice,\n maxPrice: formattedPrice,\n size: formattedSize,\n szDecimals: usdhToken.szDecimals,\n },\n );\n\n try {\n const exchangeClient = this.clientService.getExchangeClient();\n const result = await exchangeClient.order({\n orders: [\n {\n a: spotAssetId,\n b: true, // Buy USDH\n p: formattedPrice,\n s: formattedSize,\n r: false, // Not reduce-only\n t: { limit: { tif: 'Ioc' } }, // Immediate-or-cancel\n },\n ],\n grouping: 'na',\n });\n\n if (result.status !== 'ok') {\n return {\n success: false,\n error: PERPS_ERROR_CODES.SWAP_FAILED,\n };\n }\n\n // Check order status\n const status = result.response?.data?.statuses?.[0];\n if (isStatusObject(status) && 'error' in status) {\n return { success: false, error: String(status.error) };\n }\n\n const filledSize =\n isStatusObject(status) && 'filled' in status\n ? parseFloat(status.filled?.totalSz || '0')\n : 0;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USDC→USDH swap completed',\n {\n success: true,\n filledSize,\n requestedSize: formattedSize,\n },\n );\n\n return { success: true, filledSize };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.deps.debugLogger.log('HyperLiquidProvider: USDC→USDH swap error', {\n error: errorMsg,\n });\n return { success: false, error: errorMsg };\n }\n }\n\n /**\n * Ensure sufficient USDH collateral in spot for HIP-3 DEX order\n * If user lacks USDH, auto-swap from USDC\n *\n * @param dexName\n * @param requiredMargin\n */\n private async ensureUsdhCollateralForOrder(\n dexName: string,\n requiredMargin: number,\n ): Promise<void> {\n const spotUsdhBalance = await this.getSpotUsdhBalance();\n\n this.deps.debugLogger.log('HyperLiquidProvider: Checking USDH collateral', {\n dexName,\n requiredMargin,\n spotUsdhBalance,\n });\n\n if (spotUsdhBalance >= requiredMargin) {\n this.deps.debugLogger.log('HyperLiquidProvider: Sufficient USDH in spot');\n return;\n }\n\n const shortfall = requiredMargin - spotUsdhBalance;\n // HyperLiquid spot has $10 minimum order value\n const minSpotOrderValue = TRADING_DEFAULTS.amount.mainnet;\n\n // If user has some USDH already, we can swap just the shortfall (if >= $10)\n // If user has zero USDH, they need at least $10 for first swap\n const swapAmount =\n spotUsdhBalance > 0 && shortfall >= minSpotOrderValue\n ? shortfall\n : Math.max(shortfall, minSpotOrderValue);\n\n // Step 1: Check spot USDC balance\n const spotUsdcBalance = await this.getSpotUsdcBalance();\n\n // Calculate total available USDC (spot + what we can transfer from perps)\n // For now, check if we have enough in spot first\n const totalUsdcNeeded = swapAmount - spotUsdcBalance;\n\n // Step 2: If insufficient USDC in spot, transfer from main perps\n if (spotUsdcBalance < swapAmount) {\n const transferAmount = totalUsdcNeeded;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Transferring USDC to spot for swap',\n {\n spotUsdcBalance,\n swapAmount,\n transferAmount,\n },\n );\n\n const transferResult = await this.transferUsdcToSpot(transferAmount);\n if (!transferResult.success) {\n // Provide user-friendly error for insufficient funds\n if (transferResult.error?.includes('Insufficient balance')) {\n throw new Error(\n `Insufficient USDC balance. Need $${swapAmount.toFixed(2)} for USDH swap but transfer failed. Please deposit more USDC to your HyperLiquid account.`,\n );\n }\n throw new Error(\n `Failed to transfer USDC to spot: ${transferResult.error}`,\n );\n }\n }\n\n // Step 3: Swap USDC → USDH\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Swapping USDC→USDH for collateral',\n {\n shortfall,\n swapAmount,\n minOrderValue: minSpotOrderValue,\n },\n );\n\n const swapResult = await this.swapUsdcToUsdh(swapAmount);\n\n if (!swapResult.success) {\n throw new Error(\n `Failed to acquire USDH collateral for ${dexName}: ${swapResult.error}`,\n );\n }\n\n this.deps.debugLogger.log('HyperLiquidProvider: USDH collateral acquired', {\n dexName,\n filledSize: swapResult.filledSize,\n });\n }\n\n /**\n * Build asset ID mapping from market metadata\n * Fetches metadata for feature-flag-enabled DEXs and builds a unified mapping\n * with DEX-prefixed keys for HIP-3 assets (e.g., \"xyz:XYZ100\" → assetId)\n *\n * Per HIP-3-IMPLEMENTATION.md:\n * - Main DEX: assetId = index (0, 1, 2, ...)\n * - HIP-3 DEX: assetId = BASE_ASSET_ID + (perpDexIndex × DEX_MULTIPLIER) + index\n *\n * This enables proper order routing - when placeOrder({ symbol: \"xyz:XYZ100\" }) is called,\n * the asset ID lookup succeeds and the order routes to the correct DEX.\n */\n private async buildAssetMapping(): Promise<void> {\n // Get feature-flag-validated DEXs to map (respects hip3Enabled and enabledDexs)\n const dexsToMap = await this.getValidatedDexs();\n\n // Use cached perpDexs array (populated by getValidatedDexs)\n const allPerpDexs = this.cachedAllPerpDexs;\n if (!allPerpDexs) {\n throw new Error(\n 'perpDexs not cached - getValidatedDexs must be called first',\n );\n }\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Starting asset mapping rebuild',\n {\n dexs: dexsToMap,\n previousMapSize: this.symbolToAssetId.size,\n hip3Enabled: this.hip3Enabled,\n allowlistMarkets: this.allowlistMarkets,\n blocklistMarkets: this.blocklistMarkets,\n timestamp: new Date().toISOString(),\n },\n );\n\n // Update subscription service with current feature flags\n // Extract HIP-3 DEX names (filter out null which represents main DEX)\n const enabledDexs = dexsToMap.filter((dex): dex is string => dex !== null);\n\n await this.subscriptionService.updateFeatureFlags(\n this.hip3Enabled,\n enabledDexs,\n this.allowlistMarkets,\n this.blocklistMarkets,\n );\n\n // Fetch metadata for each DEX in parallel using metaAndAssetCtxs\n // Optimization: Check cache first - getMarketDataWithPrices may have already fetched\n // If not cached, fetch via metaAndAssetCtxs and populate cache for other methods\n const infoClient = this.clientService.getInfoClient();\n const allMetas = await Promise.allSettled(\n dexsToMap.map((dex) => {\n const dexKey = dex ?? '';\n\n // Check if already cached (e.g., by getMarketDataWithPrices running in parallel)\n const cachedMeta = this.cachedMetaByDex.get(dexKey);\n if (cachedMeta) {\n this.deps.debugLogger.log(\n `[buildAssetMapping] Using cached meta for ${dex || 'main'}`,\n { universeSize: cachedMeta.universe.length },\n );\n return Promise.resolve({\n dex,\n meta: cachedMeta,\n success: true as const,\n });\n }\n\n // Not cached, fetch and populate cache\n const dexParam = dex || undefined;\n return infoClient\n .metaAndAssetCtxs(dexParam ? { dex: dexParam } : undefined)\n .then((result) => {\n const meta = result?.[0] || null;\n const assetCtxs = result?.[1] || [];\n // Cache meta for later use by getCachedMeta\n if (meta?.universe) {\n this.cachedMetaByDex.set(dexKey, meta);\n // Also populate subscription service cache to avoid redundant API calls\n this.subscriptionService.setDexMetaCache(dexKey, meta);\n // Cache assetCtxs for getMarketDataWithPrices (avoids duplicate metaAndAssetCtxs calls)\n this.subscriptionService.setDexAssetCtxsCache(dexKey, assetCtxs);\n }\n return { dex, meta, success: true as const };\n })\n .catch((error) => {\n this.deps.debugLogger.log(\n `HyperLiquidProvider: Failed to fetch metaAndAssetCtxs for DEX ${\n dex || 'main'\n }`,\n { error },\n );\n return { dex, meta: null, success: false as const };\n });\n }),\n );\n\n // Build mapping with DEX prefixes for HIP-3 DEXs using the utility function\n this.symbolToAssetId.clear();\n\n allMetas.forEach((result) => {\n if (\n result.status === 'fulfilled' &&\n result.value.success &&\n result.value.meta\n ) {\n const { dex, meta } = result.value;\n\n // Validate that meta.universe exists and is an array\n if (!meta.universe || !Array.isArray(meta.universe)) {\n this.deps.debugLogger.log(\n `HyperLiquidProvider: Skipping DEX ${\n dex || 'main'\n } - invalid or missing universe data`,\n {\n hasUniverse: Boolean(meta.universe),\n isArray: Array.isArray(meta.universe),\n },\n );\n return;\n }\n\n // Find perpDexIndex for this DEX in the perpDexs array\n // Main DEX (dex=null) is at index 0\n // HIP-3 DEXs are at indices 1, 2, 3, etc.\n const perpDexIndex = allPerpDexs.findIndex((entry) => {\n if (dex === null) {\n return entry === null; // Main DEX\n }\n return entry !== null && entry.name === dex;\n });\n\n if (perpDexIndex === -1) {\n this.deps.debugLogger.log(\n `HyperLiquidProvider: Could not find perpDexIndex for DEX ${\n dex || 'main'\n }`,\n );\n return;\n }\n\n // Use the utility function to build mapping for this DEX\n const { symbolToAssetId } = buildAssetMapping({\n metaUniverse: meta.universe,\n dex,\n perpDexIndex,\n });\n\n // Merge into provider's map\n symbolToAssetId.forEach((assetId, coin) => {\n this.symbolToAssetId.set(coin, assetId);\n });\n }\n });\n\n const allKeys = Array.from(this.symbolToAssetId.keys());\n const mainDexKeys = allKeys.filter((key) => !key.includes(':')).slice(0, 5);\n const hip3Keys = allKeys.filter((key) => key.includes(':')).slice(0, 10);\n\n this.deps.debugLogger.log('HyperLiquidProvider: Asset mapping built', {\n totalAssets: this.symbolToAssetId.size,\n dexCount: dexsToMap.length,\n mainDexSample: mainDexKeys,\n hip3Sample: hip3Keys,\n });\n }\n\n /**\n * Set user fee discount context for next operations\n * Used by PerpsController to apply MetaMask reward discounts\n *\n * @param discountBips - The discount in basis points (e.g., 550 = 5.5%)\n */\n setUserFeeDiscount(discountBips: number | undefined): void {\n this.userFeeDiscountBips = discountBips;\n\n this.deps.debugLogger.log('HyperLiquid: Fee discount context updated', {\n discountBips,\n discountPercentage: discountBips ? discountBips / 100 : undefined,\n isActive: discountBips !== undefined,\n });\n }\n\n /**\n * Query user data across all enabled DEXs in parallel\n *\n * DRY helper for multi-DEX user data queries. Handles feature flag logic\n * and DEX iteration in one place. Uses cached getValidatedDexs() to avoid\n * redundant perpDexs() API calls.\n *\n * @param baseParams - Base parameters (e.g., { user: '0x...' })\n * @param queryFn - API method to call per DEX\n * @returns Array of results per DEX with DEX identifier\n *\n * @example\n * ```typescript\n * const results = await this.queryUserDataAcrossDexs(\n * { user: userAddress },\n * (p) => infoClient.clearinghouseState(p)\n * );\n * ```\n */\n private async queryUserDataAcrossDexs<\n TParams extends Record<string, unknown>,\n TResult,\n >(\n baseParams: TParams,\n queryFn: (params: TParams & { dex?: string }) => Promise<TResult>,\n ): Promise<{ dex: string | null; data: TResult }[]> {\n const enabledDexs = await this.getValidatedDexs();\n\n const results = await Promise.all(\n enabledDexs.map(async (dex) => {\n const params = dex\n ? ({ ...baseParams, dex } as TParams & { dex: string })\n : (baseParams as TParams & { dex?: string });\n const data = await queryFn(params);\n return { dex, data };\n }),\n );\n\n return results;\n }\n\n /**\n * Map HyperLiquid API errors to standardized PERPS_ERROR_CODES\n *\n * @param error\n */\n private mapError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n\n for (const [pattern, code] of Object.entries(this.errorMappings)) {\n if (message.toLowerCase().includes(pattern.toLowerCase())) {\n return new Error(code);\n }\n }\n\n // Return original error to preserve stack trace for unmapped errors\n return error instanceof Error ? error : new Error(String(error));\n }\n\n /**\n * Get error context for logging with searchable tags and context.\n * Enables Sentry dashboard filtering by feature, provider, and network.\n *\n * @param method - The method name where the error occurred\n * @param extra - Optional additional context fields (becomes searchable context data)\n * @returns LoggerErrorOptions with tags (searchable) and context (searchable)\n * @private\n *\n * @example\n * this.deps.logger.error(error, this.getErrorContext('placeOrder', { symbol: 'BTC', orderType: 'limit' }));\n * // Creates searchable tags: feature:perps, provider:hyperliquid, network:mainnet\n * // Creates searchable context: perps_provider.method:placeOrder, perps_provider.symbol:BTC, perps_provider.orderType:limit\n */\n private getErrorContext(\n method: string,\n extra?: Record<string, unknown>,\n ): {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n } {\n return {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: this.protocolId,\n network: this.clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n },\n context: {\n name: 'HyperLiquidProvider',\n data: {\n method,\n ...extra,\n },\n },\n };\n }\n\n /**\n * Get supported deposit routes with complete asset and routing information\n *\n * @param params\n */\n getDepositRoutes(params?: GetSupportedPathsParams): AssetRoute[] {\n const isTestnet = params?.isTestnet ?? this.clientService.isTestnetMode();\n const supportedAssets = getSupportedPaths({ ...params, isTestnet });\n const bridgeInfo = getBridgeInfo(isTestnet);\n\n return supportedAssets.map((assetId) => ({\n assetId,\n chainId: bridgeInfo.chainId,\n contractAddress: bridgeInfo.contractAddress,\n constraints: {\n minAmount: WITHDRAWAL_CONSTANTS.DefaultMinAmount,\n estimatedMinutes: HYPERLIQUID_WITHDRAWAL_MINUTES,\n fees: {\n fixed: WITHDRAWAL_CONSTANTS.DefaultFeeAmount,\n token: WITHDRAWAL_CONSTANTS.DefaultFeeToken,\n },\n },\n }));\n }\n\n /**\n * Get supported withdrawal routes with complete asset and routing information\n *\n * @param params\n */\n getWithdrawalRoutes(params?: GetSupportedPathsParams): AssetRoute[] {\n // For HyperLiquid, withdrawal routes are the same as deposit routes\n return this.getDepositRoutes(params);\n }\n\n /**\n * Check current builder fee approval for the user\n *\n * @param builder - Builder address to check approval for\n * @returns Current max fee rate or null if not approved\n */\n private async checkBuilderFeeApproval(): Promise<number | null> {\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n const builder = this.getBuilderAddress(this.clientService.isTestnetMode());\n\n return infoClient.maxBuilderFee({\n user: userAddress,\n builder,\n });\n }\n\n /**\n * Ensure builder fee is approved for MetaMask\n * Called once during initialization (ensureReady) to set up builder fee for the session\n * Uses session cache to avoid redundant API calls until disconnect/reconnect\n *\n * Cache semantics: Only caches successful approvals (never caches \"not approved\" state)\n * This allows detection of external approvals between retries while avoiding redundant checks\n *\n * Note: This is network-specific - testnet and mainnet have separate builder fee states\n */\n private async ensureBuilderFeeApproval(): Promise<void> {\n const isTestnet = this.clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const builderAddress = this.getBuilderAddress(isTestnet);\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n // Check session cache first to avoid redundant API calls\n // Cache only stores true (approval confirmed), never false\n const cacheKey = this.getCacheKey(network, userAddress);\n const cached = this.builderFeeCheckCache.get(cacheKey);\n\n if (cached === true) {\n this.deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Using session cache',\n {\n network,\n },\n );\n return; // Already approved this session, skip\n }\n\n // Check if approval already in-flight for this cache key\n // This prevents race conditions when multiple concurrent calls happen\n const pendingApproval = this.pendingBuilderFeeApprovals.get(cacheKey);\n if (pendingApproval) {\n this.deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Waiting for in-flight approval',\n {\n network,\n },\n );\n return pendingApproval; // Wait for existing approval to complete\n }\n\n // Create promise for this approval and track it to prevent duplicates\n const approvalPromise = (async () => {\n const { isApproved, requiredDecimal } =\n await this.checkBuilderFeeStatus();\n\n if (!isApproved) {\n this.deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval required',\n {\n builder: builderAddress,\n currentApproval: isApproved,\n requiredDecimal,\n },\n );\n\n const exchangeClient = this.clientService.getExchangeClient();\n const maxFeeRate = BUILDER_FEE_CONFIG.MaxFeeRate;\n\n await exchangeClient.approveBuilderFee({\n builder: builderAddress,\n maxFeeRate,\n });\n\n // Verify approval was successful before caching\n const afterApprovalDecimal = await this.checkBuilderFeeApproval();\n\n if (\n afterApprovalDecimal === null ||\n afterApprovalDecimal < requiredDecimal\n ) {\n throw new Error(\n '[HyperLiquidProvider] Builder fee approval verification failed',\n );\n }\n\n // Only cache after verification succeeds\n this.builderFeeCheckCache.set(cacheKey, true);\n\n this.deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval successful',\n {\n builder: builderAddress,\n approvedDecimal: afterApprovalDecimal,\n maxFeeRate,\n },\n );\n } else {\n // User already has approval (possibly from external approval or previous session)\n // Cache success to avoid redundant checks\n this.builderFeeCheckCache.set(cacheKey, true);\n\n this.deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Already approved',\n {\n network,\n },\n );\n }\n })();\n\n // Track the pending approval promise\n this.pendingBuilderFeeApprovals.set(cacheKey, approvalPromise);\n\n try {\n await approvalPromise;\n } finally {\n // Clean up tracking after completion (success or failure)\n this.pendingBuilderFeeApprovals.delete(cacheKey);\n }\n }\n\n /**\n * Check if builder fee is approved for the current user\n *\n * @returns Object with approval status and current rate\n */\n private async checkBuilderFeeStatus(): Promise<{\n isApproved: boolean;\n currentRate: number | null;\n requiredDecimal: number;\n }> {\n const currentApproval = await this.checkBuilderFeeApproval();\n const requiredDecimal = BUILDER_FEE_CONFIG.MaxFeeDecimal;\n\n return {\n isApproved:\n currentApproval !== null && currentApproval >= requiredDecimal,\n currentRate: currentApproval,\n requiredDecimal,\n };\n }\n\n /**\n * Get available balance for a specific DEX\n *\n * @param params - Balance query parameters\n * @param params.dex - DEX name (null = main, 'xyz' = HIP-3)\n * @returns Available balance in USDC\n * @private\n */\n private async getBalanceForDex(params: {\n dex: string | null;\n }): Promise<number> {\n const { dex } = params;\n const userAddress = await this.walletService.getUserAddressWithDefault();\n const infoClient = this.clientService.getInfoClient();\n\n const queryParams = dex\n ? { user: userAddress, dex }\n : { user: userAddress };\n\n const accountState = await infoClient.clearinghouseState(queryParams);\n const adapted = adaptAccountStateFromSDK(accountState);\n return parseFloat(adapted.availableBalance);\n }\n\n /**\n * Find source DEX with sufficient balance for transfer\n * Strategy: Prefer main DEX → other HIP-3 DEXs\n *\n * @param params - Source search parameters\n * @param params.targetDex - Target DEX name\n * @param params.requiredAmount - Required balance shortfall\n * @returns Source DEX info or null if insufficient funds\n * @private\n */\n private async findSourceDexWithBalance(params: {\n targetDex: string;\n requiredAmount: number;\n }): Promise<{ sourceDex: string; available: number } | null> {\n const { targetDex, requiredAmount } = params;\n\n // Try main DEX first\n try {\n const mainBalance = await this.getBalanceForDex({ dex: null });\n if (mainBalance >= requiredAmount) {\n return { sourceDex: '', available: mainBalance };\n }\n } catch (error) {\n this.deps.debugLogger.log('Could not fetch main DEX balance', { error });\n }\n\n // Try other HIP-3 DEXs\n // Get all available DEXs from cache (includes all HIP-3 DEXs since we no longer filter)\n const availableDexs =\n this.cachedValidatedDexs?.filter((dex): dex is string => dex !== null) ??\n [];\n for (const dex of availableDexs) {\n if (dex === targetDex) {\n continue;\n }\n\n try {\n const balance = await this.getBalanceForDex({ dex });\n if (balance >= requiredAmount) {\n return { sourceDex: dex, available: balance };\n }\n } catch (error) {\n this.deps.debugLogger.log(`Could not fetch balance for DEX ${dex}`, {\n error,\n });\n }\n }\n\n return null;\n }\n\n /**\n * Auto-transfer funds for HIP-3 orders when insufficient balance\n * Only called for HIP-3 markets (not main DEX)\n *\n * @param params - Transfer parameters\n * @param params.targetDex - HIP-3 DEX name (e.g., 'xyz')\n * @param params.requiredMargin - Required margin with buffer\n * @returns Transfer info for rollback, or null if no transfer needed\n * @private\n */\n private async autoTransferForHip3Order(params: {\n targetDex: string;\n requiredMargin: number;\n }): Promise<{ amount: number; sourceDex: string } | null> {\n const { targetDex, requiredMargin } = params;\n\n // Check target DEX balance\n const targetBalance = await this.getBalanceForDex({ dex: targetDex });\n\n this.deps.debugLogger.log('HyperLiquidProvider: HIP-3 balance check', {\n targetDex,\n targetBalance: targetBalance.toFixed(2),\n requiredMargin: requiredMargin.toFixed(2),\n shortfall: Math.max(0, requiredMargin - targetBalance).toFixed(2),\n });\n\n // Sufficient balance - no transfer needed\n if (targetBalance >= requiredMargin) {\n return null;\n }\n\n // Calculate shortfall and find source\n const shortfall = requiredMargin - targetBalance;\n const source = await this.findSourceDexWithBalance({\n targetDex,\n requiredAmount: shortfall,\n });\n\n if (!source) {\n throw new Error(\n `Insufficient balance for HIP-3 order. Required: ${requiredMargin.toFixed(\n 2,\n )} USDC on ${targetDex} DEX, Available: ${targetBalance.toFixed(\n 2,\n )} USDC. Please transfer funds to ${targetDex} DEX.`,\n );\n }\n\n // Execute transfer\n const transferAmount = Math.min(shortfall, source.available).toFixed(\n USDC_DECIMALS,\n );\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Executing HIP-3 auto-transfer',\n {\n from: source.sourceDex || 'main',\n to: targetDex,\n amount: transferAmount,\n },\n );\n\n const result = await this.transferBetweenDexs({\n sourceDex: source.sourceDex,\n destinationDex: targetDex,\n amount: transferAmount,\n });\n\n if (!result.success) {\n throw new Error(\n `Auto-transfer failed: ${result.error || 'Unknown error'}`,\n );\n }\n\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: HIP-3 auto-transfer complete',\n {\n amount: transferAmount,\n from: source.sourceDex || 'main',\n to: targetDex,\n },\n );\n\n return {\n amount: parseFloat(transferAmount),\n sourceDex: source.sourceDex,\n };\n }\n\n /**\n * Auto-transfer freed margin back to main DEX after closing a HIP-3 position\n *\n * This method transfers the margin released from closing a position back to\n * the main DEX to prevent balance fragmentation across HIP-3 DEXs.\n *\n * Design: Non-blocking operation - failures are logged but don't affect the\n * position close operation. Extensible for future configuration options.\n *\n * @param params - Transfer configuration\n * @param params.sourceDex - HIP-3 DEX name to transfer from\n * @param params.freedMargin - Amount of margin released from position close\n * @param params.transferAll - (Future) Transfer all available balance instead\n * @param params.skipTransfer - (Future) Skip auto-transfer if disabled\n * @returns Transfer info if successful, null if skipped/failed\n * @private\n */\n private async autoTransferBackAfterClose(params: {\n sourceDex: string;\n freedMargin: number;\n transferAll?: boolean;\n skipTransfer?: boolean;\n }): Promise<{ amount: number; destinationDex: string } | null> {\n const {\n sourceDex,\n freedMargin,\n transferAll = false,\n skipTransfer = false,\n } = params;\n\n // Future: Check user preference to skip auto-transfer\n if (skipTransfer) {\n this.deps.debugLogger.log(\n 'Auto-transfer back skipped (disabled by config)',\n );\n return null;\n }\n\n try {\n this.deps.debugLogger.log('Attempting auto-transfer back to main DEX', {\n sourceDex,\n freedMargin: freedMargin.toFixed(2),\n transferAll,\n });\n\n // Get current balance on HIP-3 DEX\n const sourceBalance = await this.getBalanceForDex({ dex: sourceDex });\n\n if (sourceBalance <= 0) {\n this.deps.debugLogger.log('No balance to transfer back', {\n sourceBalance,\n });\n return null;\n }\n\n // Determine transfer amount\n const transferAmount = transferAll\n ? sourceBalance\n : Math.min(freedMargin, sourceBalance);\n\n if (transferAmount <= 0) {\n this.deps.debugLogger.log('Transfer amount too small', {\n transferAmount,\n });\n return null;\n }\n\n this.deps.debugLogger.log('Transferring back to main DEX', {\n amount: transferAmount.toFixed(USDC_DECIMALS),\n from: sourceDex,\n to: 'main',\n });\n\n // Execute transfer back to main DEX (empty string '' represents main DEX)\n const result = await this.transferBetweenDexs({\n sourceDex,\n destinationDex: '',\n amount: transferAmount.toFixed(USDC_DECIMALS),\n });\n\n if (!result.success) {\n this.deps.debugLogger.log('❌ Auto-transfer back failed', {\n error: result.error,\n });\n return null;\n }\n\n this.deps.debugLogger.log('✅ Auto-transfer back successful', {\n amount: transferAmount.toFixed(USDC_DECIMALS),\n from: sourceDex,\n to: 'main',\n });\n\n return {\n amount: transferAmount,\n destinationDex: '',\n };\n } catch (error) {\n // Non-blocking: Log error but don't throw\n this.deps.debugLogger.log('❌ Auto-transfer back exception', {\n error,\n sourceDex,\n freedMargin,\n });\n return null;\n }\n }\n\n /**\n * Calculate required margin for HIP-3 order based on existing position\n * Handles three scenarios:\n * 1. Increasing existing position - requires TOTAL margin (temporary over-funding)\n * 2. Reducing/flipping position - requires margin for new order only\n * 3. New position - requires margin for new order only\n *\n * @param params\n * @param params.symbol\n * @param params.dexName\n * @param params.positionSize\n * @param params.orderPrice\n * @param params.leverage\n * @param params.isBuy\n * @private\n */\n private async calculateHip3RequiredMargin(params: {\n symbol: string;\n dexName: string;\n positionSize: number;\n orderPrice: number;\n leverage: number;\n isBuy: boolean;\n }): Promise<number> {\n const { symbol, dexName, positionSize, orderPrice, leverage, isBuy } =\n params;\n\n // Get existing position to check if we're increasing\n const positions = await this.getPositions();\n const existingPosition = positions.find((pos) => pos.symbol === symbol);\n\n let requiredMarginWithBuffer: number;\n\n // HyperLiquid validates isolated margin by checking if available balance >= TOTAL position margin\n // When increasing a position, we need to ensure enough funds are available for the TOTAL combined size\n if (existingPosition) {\n const existingIsLong = parseFloat(existingPosition.size) > 0;\n const orderIsLong = isBuy;\n\n if (existingIsLong === orderIsLong) {\n // Increasing position - HyperLiquid validates availableBalance >= totalRequiredMargin\n // BEFORE reallocating existing locked margin. Must transfer TOTAL margin temporarily.\n const existingSize = Math.abs(parseFloat(existingPosition.size));\n const existingMargin = parseFloat(existingPosition.marginUsed);\n const totalSize = existingSize + positionSize;\n const totalNotionalValue = totalSize * orderPrice;\n const totalRequiredMargin = totalNotionalValue / leverage;\n\n // Accept temporary over-funding - excess will be reclaimed after order succeeds\n requiredMarginWithBuffer =\n totalRequiredMargin * HIP3_MARGIN_CONFIG.BufferMultiplier;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: HIP-3 margin calculation (TOTAL margin - temporary over-funding)',\n {\n symbol,\n dex: dexName,\n existingSize: existingSize.toFixed(4),\n existingMargin: existingMargin.toFixed(2),\n newSize: positionSize.toFixed(4),\n totalSize: totalSize.toFixed(4),\n totalNotionalValue: totalNotionalValue.toFixed(2),\n leverage,\n totalRequiredMargin: totalRequiredMargin.toFixed(2),\n requiredMarginWithBuffer: requiredMarginWithBuffer.toFixed(2),\n note: 'Transferring TOTAL margin (HyperLiquid validates before reallocation). Will auto-rebalance excess after success.',\n },\n );\n } else {\n // Reducing or flipping position - just need margin for new order\n const notionalValue = positionSize * orderPrice;\n const requiredMargin = notionalValue / leverage;\n requiredMarginWithBuffer =\n requiredMargin * HIP3_MARGIN_CONFIG.BufferMultiplier;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: HIP-3 margin calculation (reducing position)',\n {\n symbol,\n dex: dexName,\n notionalValue: notionalValue.toFixed(2),\n leverage,\n requiredMargin: requiredMargin.toFixed(2),\n requiredMarginWithBuffer: requiredMarginWithBuffer.toFixed(2),\n },\n );\n }\n } else {\n // No existing position - just need margin for this order\n const notionalValue = positionSize * orderPrice;\n const requiredMargin = notionalValue / leverage;\n requiredMarginWithBuffer =\n requiredMargin * HIP3_MARGIN_CONFIG.BufferMultiplier;\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: HIP-3 margin calculation (new position)',\n {\n symbol,\n dex: dexName,\n notionalValue: notionalValue.toFixed(2),\n leverage,\n requiredMargin: requiredMargin.toFixed(2),\n requiredMarginWithBuffer: requiredMarginWithBuffer.toFixed(2),\n },\n );\n }\n\n return requiredMarginWithBuffer;\n }\n\n /**\n * Handle post-order balance check and auto-rebalance for HIP-3 orders\n * After a successful order, checks available balance and transfers excess back to main DEX\n * Does not throw errors - logs them for monitoring\n *\n * @param params\n * @param params.dexName\n * @param params.transferInfo\n * @param params.transferInfo.amount\n * @param params.transferInfo.sourceDex\n * @private\n */\n private async handleHip3PostOrderRebalance(params: {\n dexName: string;\n transferInfo: { amount: number; sourceDex: string };\n }): Promise<void> {\n const { dexName, transferInfo } = params;\n\n try {\n const postOrderBalance = await this.getBalanceForDex({ dex: dexName });\n const transferredAmount = transferInfo.amount;\n const leftoverAmount = postOrderBalance;\n const leftoverPercentage =\n transferredAmount > 0 ? (leftoverAmount / transferredAmount) * 100 : 0;\n\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: Order succeeded - post-order balance',\n {\n dex: dexName,\n transferredAmount: transferredAmount.toFixed(2),\n availableAfterOrder: leftoverAmount.toFixed(2),\n leftoverPercentage: `${leftoverPercentage.toFixed(2)}%`,\n },\n );\n\n // Auto-rebalance: Reclaim excess funds back to main DEX\n const desiredBuffer = HIP3_MARGIN_CONFIG.RebalanceDesiredBuffer;\n const excessAmount = postOrderBalance - desiredBuffer;\n const minimumTransferThreshold = HIP3_MARGIN_CONFIG.RebalanceMinThreshold;\n\n if (excessAmount > minimumTransferThreshold) {\n try {\n this.deps.debugLogger.log(\n '🔄 HyperLiquidProvider: Auto-rebalancing excess margin back to main DEX',\n {\n dex: dexName,\n availableBalance: postOrderBalance.toFixed(2),\n desiredBuffer: desiredBuffer.toFixed(2),\n excessAmount: excessAmount.toFixed(2),\n destinationDex: transferInfo.sourceDex,\n },\n );\n\n await this.transferBetweenDexs({\n sourceDex: dexName,\n destinationDex: transferInfo.sourceDex,\n amount: excessAmount.toFixed(USDC_DECIMALS),\n });\n\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: Auto-rebalance completed',\n {\n transferredBack: excessAmount.toFixed(2),\n from: dexName,\n to: transferInfo.sourceDex,\n },\n );\n } catch (rebalanceError) {\n // Don't fail the order if rebalance fails (order already succeeded)\n this.deps.logger.error(\n ensureError(rebalanceError),\n this.getErrorContext('placeOrder:autoRebalance', {\n dex: dexName,\n excessAmount: excessAmount.toFixed(2),\n note: 'Auto-rebalance failed - funds remain on HIP-3 DEX',\n }),\n );\n }\n } else {\n this.deps.debugLogger.log(\n 'ℹ️ HyperLiquidProvider: No auto-rebalance needed',\n {\n excessAmount: excessAmount.toFixed(2),\n threshold: minimumTransferThreshold.toFixed(2),\n note: 'Excess below minimum transfer threshold',\n },\n );\n }\n } catch (balanceCheckError) {\n // Don't fail the order if balance check fails - log for monitoring\n this.deps.logger.error(\n ensureError(balanceCheckError),\n this.getErrorContext('placeOrder:postOrderBalanceCheck', {\n dex: dexName,\n note: 'Failed to verify post-order balance for auto-rebalance',\n }),\n );\n }\n }\n\n /**\n * Handle rollback of HIP-3 transfer when order fails\n * Attempts to return funds to source DEX\n * Does not throw errors - logs them for monitoring\n *\n * @param params\n * @param params.dexName\n * @param params.transferInfo\n * @param params.transferInfo.amount\n * @param params.transferInfo.sourceDex\n * @private\n */\n private async handleHip3OrderRollback(params: {\n dexName: string;\n transferInfo: { amount: number; sourceDex: string };\n }): Promise<void> {\n const { dexName, transferInfo } = params;\n\n try {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Rolling back failed order transfer',\n {\n from: dexName,\n to: transferInfo.sourceDex || 'main',\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n reason: 'order_failed',\n },\n );\n\n const rollbackResult = await this.transferBetweenDexs({\n sourceDex: dexName, // From HIP-3 DEX\n destinationDex: transferInfo.sourceDex, // Back to source\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n });\n\n if (rollbackResult.success) {\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: Rollback successful',\n {\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n returnedTo: transferInfo.sourceDex || 'main',\n },\n );\n } else {\n this.deps.logger.error(\n new Error(rollbackResult.error || 'Rollback transfer failed'),\n this.getErrorContext('placeOrder:rollback', {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback failed - funds remain on HIP-3 DEX',\n }),\n );\n }\n } catch (rollbackError) {\n // Log but don't throw - original order error is more important\n this.deps.logger.error(\n ensureError(rollbackError),\n this.getErrorContext('placeOrder:rollback:exception', {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback threw exception - funds remain on HIP-3 DEX',\n }),\n );\n }\n }\n\n // ============================================================================\n // Helper Methods for placeOrder Refactoring\n // ============================================================================\n\n /**\n * Validates order parameters before placement using provider-level validation\n *\n * @param params\n * @throws Error if validation fails\n */\n private async validateOrderBeforePlacement(\n params: OrderParams,\n ): Promise<void> {\n this.deps.debugLogger.log(\n 'Provider: Validating order before placement:',\n params,\n );\n\n const validation = await this.validateOrder(params);\n if (!validation.isValid) {\n throw new Error(\n validation.error || 'Order validation failed at provider level',\n );\n }\n }\n\n /**\n * Gets asset info and current price from the correct DEX\n *\n * @param params\n */\n private async getAssetInfo(\n params: GetAssetInfoParams,\n ): Promise<GetAssetInfoResult> {\n const { symbol, dexName } = params;\n\n const infoClient = this.clientService.getInfoClient();\n const meta = await this.getCachedMeta({ dexName });\n\n const assetInfo = meta.universe.find((asset) => asset.name === symbol);\n if (!assetInfo) {\n throw new Error(\n `Asset ${symbol} not found in ${dexName || 'main'} DEX universe`,\n );\n }\n\n const mids = await infoClient.allMids({ dex: dexName ?? '' });\n const currentPrice = parseFloat(mids[symbol] || '0');\n if (currentPrice === 0) {\n throw new Error(`No price available for ${symbol}`);\n }\n\n return { assetInfo, currentPrice, meta };\n }\n\n /**\n * Prepares asset for trading by updating leverage if specified\n *\n * @param params\n */\n private async prepareAssetForTrading(\n params: PrepareAssetForTradingParams,\n ): Promise<void> {\n const { symbol, assetId, leverage } = params;\n\n if (!leverage) {\n return;\n }\n\n this.deps.debugLogger.log('Updating leverage before order:', {\n symbol,\n assetId,\n requestedLeverage: leverage,\n leverageType: 'isolated',\n });\n\n const exchangeClient = this.clientService.getExchangeClient();\n const leverageResult = await exchangeClient.updateLeverage({\n asset: assetId,\n isCross: false,\n leverage,\n });\n\n if (leverageResult.status !== 'ok') {\n throw new Error(\n `Failed to update leverage: ${JSON.stringify(leverageResult)}`,\n );\n }\n\n this.deps.debugLogger.log('Leverage updated successfully:', {\n symbol,\n leverage,\n });\n }\n\n /**\n * Handles HIP-3 pre-order balance management\n *\n * @param params\n */\n private async handleHip3PreOrder(\n params: HandleHip3PreOrderParams,\n ): Promise<HandleHip3PreOrderResult> {\n const { dexName, symbol, orderPrice, positionSize, leverage, isBuy } =\n params;\n\n // Check if this DEX uses USDH collateral (vs USDC)\n // For USDH DEXs, HyperLiquid automatically pulls from spot balance\n const isUsdhDex = await this.isUsdhCollateralDex(dexName);\n if (isUsdhDex) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USDH-collateralized DEX detected',\n {\n dexName,\n symbol,\n },\n );\n\n // Calculate required margin and ensure USDH is in spot\n const requiredMargin = await this.calculateHip3RequiredMargin({\n symbol,\n dexName,\n positionSize,\n orderPrice,\n leverage,\n isBuy,\n });\n\n await this.ensureUsdhCollateralForOrder(dexName, requiredMargin);\n\n // DEX abstraction will pull USDH from spot automatically\n return { transferInfo: null };\n }\n\n if (this.useDexAbstraction) {\n this.deps.debugLogger.log('Using DEX abstraction (no manual transfer)', {\n symbol,\n dex: dexName,\n });\n return { transferInfo: null };\n }\n\n this.deps.debugLogger.log('Using manual auto-transfer', {\n symbol,\n dex: dexName,\n });\n\n const requiredMarginWithBuffer = await this.calculateHip3RequiredMargin({\n symbol,\n dexName,\n positionSize,\n orderPrice,\n leverage,\n isBuy,\n });\n\n try {\n const transferInfo = await this.autoTransferForHip3Order({\n targetDex: dexName,\n requiredMargin: requiredMarginWithBuffer,\n });\n return { transferInfo };\n } catch (transferError) {\n const errorMsg = (transferError as Error)?.message || '';\n\n if (errorMsg.includes('Cannot transfer with DEX abstraction enabled')) {\n this.deps.debugLogger.log(\n 'Detected DEX abstraction is enabled, switching mode',\n );\n this.useDexAbstraction = true;\n return { transferInfo: null };\n }\n\n throw transferError;\n }\n }\n\n /**\n * Submits order with atomic rollback for HIP-3 failures\n *\n * @param params\n */\n private async submitOrderWithRollback(\n params: SubmitOrderWithRollbackParams,\n ): Promise<OrderResult> {\n const { orders, grouping, isHip3Order, dexName, transferInfo, symbol } =\n params;\n\n const exchangeClient = this.clientService.getExchangeClient();\n\n // Calculate discounted builder fee\n let builderFee = BUILDER_FEE_CONFIG.MaxFeeTenthsBps;\n if (this.userFeeDiscountBips !== undefined) {\n builderFee = Math.floor(\n builderFee * (1 - this.userFeeDiscountBips / BASIS_POINTS_DIVISOR),\n );\n this.deps.debugLogger.log('Applying builder fee discount', {\n originalFee: BUILDER_FEE_CONFIG.MaxFeeTenthsBps,\n discountBips: this.userFeeDiscountBips,\n discountedFee: builderFee,\n });\n }\n\n this.deps.debugLogger.log('Submitting order via asset ID routing', {\n symbol,\n assetId: orders[0].a,\n orderCount: orders.length,\n mainOrder: orders[0],\n dexName: dexName || 'main',\n isHip3: Boolean(dexName),\n });\n\n try {\n const result = await exchangeClient.order({\n orders,\n grouping,\n builder: {\n b: this.getBuilderAddress(this.clientService.isTestnetMode()),\n f: builderFee,\n },\n });\n\n if (result.status !== 'ok') {\n throw new Error(`Order failed: ${JSON.stringify(result)}`);\n }\n\n const status = result.response?.data?.statuses?.[0];\n const restingOrder =\n isStatusObject(status) && 'resting' in status ? status.resting : null;\n const filledOrder =\n isStatusObject(status) && 'filled' in status ? status.filled : null;\n\n // Success - auto-rebalance excess funds\n if (isHip3Order && transferInfo && dexName) {\n await this.handleHip3PostOrderRebalance({ dexName, transferInfo });\n }\n\n return {\n success: true,\n orderId: restingOrder?.oid?.toString() || filledOrder?.oid?.toString(),\n filledSize: filledOrder?.totalSz,\n averagePrice: filledOrder?.avgPx,\n };\n } catch (orderError) {\n // Failure - rollback transfer\n if (transferInfo && dexName) {\n await this.handleHip3OrderRollback({ dexName, transferInfo });\n }\n throw orderError;\n }\n }\n\n /**\n * Handles order errors with proper error mapping\n *\n * @param params\n */\n private handleOrderError(params: HandleOrderErrorParams): OrderResult {\n const { error, symbol, orderType, isBuy } = params;\n\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('placeOrder', {\n symbol,\n orderType,\n isBuy,\n }),\n );\n\n const mappedError = this.mapError(error);\n return createErrorResult(mappedError, { success: false });\n }\n\n /**\n * Place an order using direct wallet signing\n *\n * Refactored to use helper methods for better maintainability and reduced complexity.\n * Each helper method is focused on a single responsibility.\n *\n * @param params - Order parameters\n * @param retryCount - Internal retry counter to prevent infinite loops (default: 0)\n */\n async placeOrder(params: OrderParams, retryCount = 0): Promise<OrderResult> {\n try {\n this.deps.debugLogger.log('Placing order via HyperLiquid SDK:', params);\n\n // Basic sync validation (backward compatibility)\n const validation = validateOrderParams({\n coin: params.symbol,\n size: params.size,\n price: params.price,\n orderType: params.orderType,\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n // Validate order at provider level (enforces USD validation rules)\n await this.validateOrderBeforePlacement(params);\n\n await this.ensureReady();\n\n // Explicitly ensure builder fee approval for trading\n // This is critical for orders and will throw if not approved or if account has no deposits\n await this.ensureBuilderFeeApproval();\n\n // Debug: Log asset map state before order placement\n const allMapKeys = Array.from(this.symbolToAssetId.keys());\n const hip3Keys = allMapKeys.filter((key) => key.includes(':'));\n const assetExists = this.symbolToAssetId.has(params.symbol);\n this.deps.debugLogger.log('Asset map state at order time', {\n requestedCoin: params.symbol,\n assetExistsInMap: assetExists,\n totalAssetsInMap: this.symbolToAssetId.size,\n hip3AssetsCount: hip3Keys.length,\n hip3AssetsSample: hip3Keys.slice(0, 10),\n hip3Enabled: this.hip3Enabled,\n allowlistMarkets: this.allowlistMarkets,\n blocklistMarkets: this.blocklistMarkets,\n });\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(params.symbol);\n\n // 1. Get asset info and current price\n const { assetInfo, currentPrice } = await this.getAssetInfo({\n symbol: params.symbol,\n dexName,\n });\n\n // Allow override with UI-provided price (optimization to avoid API call)\n const effectivePrice =\n params.currentPrice && params.currentPrice > 0\n ? params.currentPrice\n : currentPrice;\n\n if (params.currentPrice && params.currentPrice > 0) {\n this.deps.debugLogger.log('Using provided current price:', {\n coin: params.symbol,\n providedPrice: effectivePrice,\n source: 'UI price feed',\n });\n }\n\n // 2. Calculate final position size with USD reconciliation\n const { finalPositionSize } = calculateFinalPositionSize({\n usdAmount: params.usdAmount,\n size: params.size,\n currentPrice: effectivePrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n szDecimals: assetInfo.szDecimals,\n leverage: params.leverage,\n });\n\n // 3. Calculate order price and formatted size\n const { orderPrice, formattedSize, formattedPrice } =\n calculateOrderPriceAndSize({\n orderType: params.orderType,\n isBuy: params.isBuy,\n finalPositionSize,\n currentPrice: effectivePrice,\n limitPrice: params.price,\n slippage: params.slippage,\n szDecimals: assetInfo.szDecimals,\n });\n\n // 4. Get asset ID and validate it exists\n const assetId = this.symbolToAssetId.get(params.symbol);\n if (assetId === undefined) {\n this.deps.debugLogger.log('Asset ID lookup failed', {\n requestedCoin: params.symbol,\n dexName: dexName || 'main',\n mapSize: this.symbolToAssetId.size,\n mapContainsAsset: this.symbolToAssetId.has(params.symbol),\n allKeys: Array.from(this.symbolToAssetId.keys()).slice(0, 20),\n });\n throw new Error(`Asset ID not found for ${params.symbol}`);\n }\n\n this.deps.debugLogger.log('Resolved DEX-specific asset ID', {\n coin: params.symbol,\n dex: dexName || 'main',\n assetId,\n });\n\n // 5. Update leverage if specified\n await this.prepareAssetForTrading({\n symbol: params.symbol,\n assetId,\n leverage: params.leverage,\n });\n\n // 6. Handle HIP-3 balance management (if applicable)\n const isHip3Order = dexName !== null;\n let transferInfo: { amount: number; sourceDex: string } | null = null;\n\n if (isHip3Order && dexName) {\n const effectiveLeverage = params.leverage || assetInfo.maxLeverage || 1;\n const hip3Result = await this.handleHip3PreOrder({\n dexName,\n symbol: params.symbol,\n orderPrice,\n positionSize: parseFloat(formattedSize),\n leverage: effectiveLeverage,\n isBuy: params.isBuy,\n maxLeverage: assetInfo.maxLeverage,\n });\n transferInfo = hip3Result.transferInfo;\n }\n\n // 7. Build orders array (main + TP/SL if specified)\n const { orders, grouping } = buildOrdersArray({\n assetId,\n isBuy: params.isBuy,\n formattedPrice,\n formattedSize,\n reduceOnly: params.reduceOnly || false,\n orderType: params.orderType,\n clientOrderId: params.clientOrderId,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n szDecimals: assetInfo.szDecimals,\n grouping: params.grouping,\n });\n\n // 8. Submit order with atomic rollback\n return await this.submitOrderWithRollback({\n orders,\n grouping,\n isHip3Order,\n dexName,\n transferInfo,\n symbol: params.symbol,\n assetId,\n });\n } catch (error) {\n // Retry mechanism for $10 minimum order errors\n // This handles the case where UI price feed slightly differs from HyperLiquid's orderbook price\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const isMinimumOrderError =\n errorMessage.includes('Order must have minimum value of $10') ||\n errorMessage.includes('Order 0: Order must have minimum value');\n\n if (isMinimumOrderError && retryCount === 0) {\n let adjustedUsdAmount: string;\n let originalValue: string | undefined;\n\n if (params.usdAmount) {\n // USD-based order: adjust the USD amount directly\n originalValue = params.usdAmount;\n adjustedUsdAmount = (parseFloat(params.usdAmount) * 1.015).toFixed(2);\n } else if (params.currentPrice) {\n // Size-based order: calculate USD from size and adjust\n const sizeValue = parseFloat(params.size);\n const estimatedUsd = sizeValue * params.currentPrice;\n originalValue = `${estimatedUsd.toFixed(2)} (calculated from size ${params.size})`;\n adjustedUsdAmount = (estimatedUsd * 1.015).toFixed(2);\n } else {\n // No price information available - cannot retry\n return this.handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n });\n }\n\n this.deps.debugLogger.log(\n 'Retrying order with adjusted size due to minimum value error',\n {\n originalValue,\n adjustedUsdAmount,\n retryCount,\n },\n );\n\n return this.placeOrder(\n {\n ...params,\n usdAmount: adjustedUsdAmount,\n },\n 1, // Retry count = 1, prevents further retries\n );\n }\n\n return this.handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n });\n }\n }\n\n /**\n * Edit an existing order (pending/unfilled order)\n *\n * Note: This modifies price/size of a pending order. It CANNOT add TP/SL to an existing order.\n * For adding TP/SL to an existing position, use updatePositionTPSL instead.\n *\n * @param params.orderId - The order ID to modify\n * @param params.newOrder - New order parameters (price, size, etc.)\n * @param params\n */\n async editOrder(params: EditOrderParams): Promise<OrderResult> {\n try {\n this.deps.debugLogger.log('Editing order:', params);\n\n // Validate size is positive (validateOrderParams no longer validates size)\n const size = parseFloat(params.newOrder.size || '0');\n if (size <= 0) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE,\n };\n }\n\n // Validate new order parameters\n const validation = validateOrderParams({\n coin: params.newOrder.symbol,\n size: params.newOrder.size,\n price: params.newOrder.price,\n orderType: params.newOrder.orderType,\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n await this.ensureReady();\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureBuilderFeeApproval();\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(params.newOrder.symbol);\n\n // Get asset info and prices (uses cache to avoid redundant API calls)\n const infoClient = this.clientService.getInfoClient();\n const meta = await this.getCachedMeta({ dexName });\n const mids = await infoClient.allMids({ dex: dexName ?? '' });\n\n // asset.name format: \"BTC\" for main DEX, \"xyz:XYZ100\" for HIP-3\n const assetInfo = meta.universe.find(\n (asset) => asset.name === params.newOrder.symbol,\n );\n if (!assetInfo) {\n throw new Error(\n `Asset ${params.newOrder.symbol} not found in ${\n dexName || 'main'\n } DEX universe`,\n );\n }\n\n const currentPrice = parseFloat(mids[params.newOrder.symbol] || '0');\n if (currentPrice === 0) {\n throw new Error(`No price available for ${params.newOrder.symbol}`);\n }\n\n // Calculate order parameters using the same logic as placeOrder\n let orderPrice: number;\n let formattedSize: string;\n\n if (params.newOrder.orderType === 'market') {\n const positionSize = parseFloat(params.newOrder.size);\n const slippage =\n params.newOrder.slippage ??\n ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps / 10000;\n orderPrice = params.newOrder.isBuy\n ? currentPrice * (1 + slippage)\n : currentPrice * (1 - slippage);\n formattedSize = formatHyperLiquidSize({\n size: positionSize,\n szDecimals: assetInfo.szDecimals,\n });\n } else {\n if (!params.newOrder.price) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED);\n }\n orderPrice = parseFloat(params.newOrder.price);\n formattedSize = formatHyperLiquidSize({\n size: parseFloat(params.newOrder.size),\n szDecimals: assetInfo.szDecimals,\n });\n }\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals: assetInfo.szDecimals,\n });\n const assetId = this.symbolToAssetId.get(params.newOrder.symbol);\n if (assetId === undefined) {\n throw new Error(`Asset ID not found for ${params.newOrder.symbol}`);\n }\n\n // Build new order parameters\n const newOrder: SDKOrderParams = {\n a: assetId,\n b: params.newOrder.isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: params.newOrder.reduceOnly || false,\n // Same TIF logic as placeOrder - see documentation above for details\n t:\n params.newOrder.orderType === 'limit'\n ? { limit: { tif: 'Gtc' } } // Standard limit order\n : { limit: { tif: 'FrontendMarket' } }, // True market order\n c: params.newOrder.clientOrderId\n ? (params.newOrder.clientOrderId as Hex)\n : undefined,\n };\n\n // Submit modification via SDK\n const exchangeClient = this.clientService.getExchangeClient();\n const result = await exchangeClient.modify({\n oid:\n typeof params.orderId === 'string'\n ? (params.orderId as Hex)\n : params.orderId,\n order: newOrder,\n });\n\n if (result.status !== 'ok') {\n throw new Error(`Order modification failed: ${JSON.stringify(result)}`);\n }\n\n return {\n success: true,\n orderId: params.orderId.toString(),\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('editOrder', {\n orderId: params.orderId,\n coin: params.newOrder.symbol,\n orderType: params.newOrder.orderType,\n }),\n );\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Cancel an order\n *\n * @param params\n */\n async cancelOrder(params: CancelOrderParams): Promise<CancelOrderResult> {\n try {\n this.deps.debugLogger.log('Canceling order:', params);\n\n // Validate coin exists\n const coinValidation = validateCoinExists(\n params.symbol,\n this.symbolToAssetId,\n );\n if (!coinValidation.isValid) {\n throw new Error(coinValidation.error);\n }\n\n await this.ensureReady();\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureBuilderFeeApproval();\n\n const exchangeClient = this.clientService.getExchangeClient();\n const asset = this.symbolToAssetId.get(params.symbol);\n if (asset === undefined) {\n throw new Error(`Asset not found for symbol: ${params.symbol}`);\n }\n\n const result = await exchangeClient.cancel({\n cancels: [\n {\n a: asset,\n o: parseInt(params.orderId, 10),\n },\n ],\n });\n\n const success = result.response?.data?.statuses?.[0] === 'success';\n\n return {\n success,\n orderId: params.orderId,\n error: success ? undefined : 'Order cancellation failed',\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('cancelOrder', {\n orderId: params.orderId,\n coin: params.symbol,\n }),\n );\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Cancel multiple orders in a single batch API call\n * Optimized implementation that uses HyperLiquid's batch cancel endpoint\n *\n * @param params\n */\n async cancelOrders(\n params: BatchCancelOrdersParams,\n ): Promise<CancelOrdersResult> {\n try {\n this.deps.debugLogger.log('Batch canceling orders:', {\n count: params.length,\n });\n\n if (params.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: 0,\n results: [],\n };\n }\n\n await this.ensureReady();\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureBuilderFeeApproval();\n\n const exchangeClient = this.clientService.getExchangeClient();\n\n // Map orders to SDK format and validate coins\n const cancelRequests = params.map((order) => {\n const asset = this.symbolToAssetId.get(order.symbol);\n if (asset === undefined) {\n throw new Error(`Asset not found for symbol: ${order.symbol}`);\n }\n return {\n a: asset,\n o: parseInt(order.orderId, 10),\n };\n });\n\n // Single batch API call\n const result = await exchangeClient.cancel({\n cancels: cancelRequests,\n });\n\n // Parse response statuses (one per order)\n const { statuses } = result.response.data;\n const successCount = statuses.filter(\n (status) => status === 'success',\n ).length;\n const failureCount = statuses.length - successCount;\n\n return {\n success: successCount > 0,\n successCount,\n failureCount,\n results: statuses.map((status, index) => ({\n orderId: params[index].orderId,\n symbol: params[index].symbol,\n success: status === 'success',\n error:\n status !== 'success'\n ? (status as { error: string }).error\n : undefined,\n })),\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('cancelOrders', {\n orderCount: params.length,\n }),\n );\n // Return all orders as failed\n return {\n success: false,\n successCount: 0,\n failureCount: params.length,\n results: params.map((order) => ({\n orderId: order.orderId,\n symbol: order.symbol,\n success: false,\n error:\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.BATCH_CANCEL_FAILED,\n })),\n };\n }\n }\n\n async closePositions(\n params: ClosePositionsParams,\n ): Promise<ClosePositionsResult> {\n // Declare outside try block so it's accessible in catch block\n let positionsToClose: Position[] = [];\n\n try {\n await this.ensureReady();\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureBuilderFeeApproval();\n\n // Get all current positions\n // Force fresh API data (not WebSocket cache) since we're about to mutate positions\n const positions = await this.getPositions({ skipCache: true });\n\n // Filter positions based on params\n positionsToClose =\n params.closeAll || !params.symbols || params.symbols.length === 0\n ? positions\n : positions.filter((pos) => params.symbols?.includes(pos.symbol));\n\n this.deps.debugLogger.log('Batch closing positions:', {\n count: positionsToClose.length,\n closeAll: params.closeAll,\n coins: params.symbols,\n });\n\n if (positionsToClose.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: 0,\n results: [],\n };\n }\n\n // Get exchange client and meta for price/size formatting\n const exchangeClient = this.clientService.getExchangeClient();\n const infoClient = this.clientService.getInfoClient();\n\n // Pre-fetch meta for all unique DEXs to avoid N API calls in loop\n const uniqueDexs = [\n ...new Set(\n positionsToClose.map(\n (pos) => parseAssetName(pos.symbol).dex || 'main',\n ),\n ),\n ];\n await Promise.all(\n uniqueDexs.map((dex) =>\n this.getCachedMeta({ dexName: dex === 'main' ? null : dex }),\n ),\n );\n\n // Track HIP-3 positions and freed margins for post-close transfers\n const hip3Transfers: {\n sourceDex: string;\n freedMargin: number;\n }[] = [];\n\n // Build orders array\n const orders: SDKOrderParams[] = [];\n\n for (const position of positionsToClose) {\n // Extract DEX name for HIP-3 positions\n const { dex: dexName } = parseAssetName(position.symbol);\n const isHip3Position = position.symbol.includes(':');\n\n // Get asset info for formatting (uses cache populated above)\n const meta = await this.getCachedMeta({ dexName });\n\n const assetInfo = meta.universe.find(\n (asset) => asset.name === position.symbol,\n );\n if (!assetInfo) {\n throw new Error(\n `Asset ${position.symbol} not found in ${\n dexName || 'main'\n } DEX universe`,\n );\n }\n\n // Get asset ID\n const assetId = this.symbolToAssetId.get(position.symbol);\n if (assetId === undefined) {\n throw new Error(`Asset ID not found for ${position.symbol}`);\n }\n\n // Calculate position details (always full close)\n const positionSize = parseFloat(position.size);\n const isBuy = positionSize < 0; // Close opposite side\n const closeSize = Math.abs(positionSize);\n const totalMarginUsed = parseFloat(position.marginUsed);\n\n // Track HIP-3 transfers (full position close means all margin is freed)\n if (isHip3Position && dexName && !this.useDexAbstraction) {\n hip3Transfers.push({\n sourceDex: dexName,\n freedMargin: totalMarginUsed,\n });\n }\n\n // Get current price for market order slippage\n const mids = await infoClient.allMids({ dex: dexName ?? '' });\n const currentPrice = parseFloat(mids[position.symbol] || '0');\n if (currentPrice === 0) {\n throw new Error(`No price available for ${position.symbol}`);\n }\n\n // Calculate order price with slippage\n const slippage = ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps / 10000;\n const orderPrice = isBuy\n ? currentPrice * (1 + slippage)\n : currentPrice * (1 - slippage);\n\n // Format size and price\n const formattedSize = formatHyperLiquidSize({\n size: closeSize,\n szDecimals: assetInfo.szDecimals,\n });\n\n const formattedPrice = formatHyperLiquidPrice({\n price: orderPrice,\n szDecimals: assetInfo.szDecimals,\n });\n\n // Build reduce-only order\n orders.push({\n a: assetId,\n b: isBuy,\n p: formattedPrice,\n s: formattedSize,\n r: true, // reduceOnly\n t: { limit: { tif: 'Ioc' } }, // Immediate or cancel for market-like execution\n });\n }\n\n // Calculate discounted builder fee if reward discount is active\n let builderFee = BUILDER_FEE_CONFIG.MaxFeeTenthsBps;\n if (this.userFeeDiscountBips !== undefined) {\n builderFee = Math.floor(\n builderFee * (1 - this.userFeeDiscountBips / BASIS_POINTS_DIVISOR),\n );\n }\n\n // Single batch API call\n const result = await exchangeClient.order({\n orders,\n grouping: 'na',\n builder: {\n b: this.getBuilderAddress(this.clientService.isTestnetMode()),\n f: builderFee,\n },\n });\n\n // Parse response statuses (one per order)\n const { statuses } = result.response.data;\n const successCount = statuses.filter(\n (stat) =>\n isStatusObject(stat) && ('filled' in stat || 'resting' in stat),\n ).length;\n const failureCount = statuses.length - successCount;\n\n // Handle HIP-3 margin transfers for successful closes\n if (!this.useDexAbstraction) {\n for (let i = 0; i < statuses.length; i++) {\n const status = statuses[i];\n const isSuccess =\n isStatusObject(status) &&\n ('filled' in status || 'resting' in status);\n\n if (isSuccess && hip3Transfers[i]) {\n const { sourceDex, freedMargin } = hip3Transfers[i];\n this.deps.debugLogger.log(\n 'Position closed successfully, initiating manual auto-transfer back',\n { symbol: positionsToClose[i].symbol, freedMargin },\n );\n\n // Non-blocking: Transfer freed margin back to main DEX\n await this.autoTransferBackAfterClose({\n sourceDex,\n freedMargin,\n });\n }\n }\n }\n\n return {\n success: successCount > 0,\n successCount,\n failureCount,\n results: statuses.map((status, index) => ({\n symbol: positionsToClose[index].symbol,\n success:\n isStatusObject(status) &&\n ('filled' in status || 'resting' in status),\n error:\n isStatusObject(status) && 'error' in status\n ? String(status.error)\n : undefined,\n })),\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('closePositions', {\n positionCount: positionsToClose.length,\n }),\n );\n // Return all positions as failed\n return {\n success: false,\n successCount: 0,\n failureCount: positionsToClose.length,\n results: positionsToClose.map((position) => ({\n symbol: position.symbol,\n success: false,\n error:\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,\n })),\n };\n }\n }\n\n /**\n * Update TP/SL for an existing position\n *\n * This creates new TP/SL orders for the position using 'positionTpsl' grouping.\n * These are separate orders that will close the position when triggered.\n *\n * Key differences from editOrder:\n * - editOrder: Modifies pending orders (before fill)\n * - updatePositionTPSL: Creates TP/SL orders for filled positions\n *\n * HyperLiquid supports two TP/SL types:\n * 1. 'normalTpsl' - Tied to a parent order (set when placing the order)\n * 2. 'positionTpsl' - Tied to a position (can be set/modified after fill)\n *\n * @param params.symbol - Asset symbol of the position\n * @param params.takeProfitPrice - TP price (undefined to remove)\n * @param params.stopLossPrice - SL price (undefined to remove)\n * @param params\n */\n async updatePositionTPSL(\n params: UpdatePositionTPSLParams,\n ): Promise<OrderResult> {\n try {\n this.deps.debugLogger.log('Updating position TP/SL:', params);\n\n const { symbol, takeProfitPrice, stopLossPrice } = params;\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureReady();\n await this.ensureBuilderFeeApproval();\n\n // Get current position to validate it exists\n // Force fresh API data (not WebSocket cache) since we're about to mutate the position\n let positions: Position[];\n try {\n positions = await this.getPositions({ skipCache: true });\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('updatePositionTPSL > getPositions', {\n symbol,\n }),\n );\n throw error;\n }\n\n const position = positions.find((pos) => pos.symbol === symbol);\n\n if (!position) {\n throw new Error(`No position found for ${symbol}`);\n }\n\n const positionSize = Math.abs(parseFloat(position.size));\n const isLong = parseFloat(position.size) > 0;\n\n await this.ensureReady();\n\n // See ensureReady() - builder fee and referral are session-cached\n\n // Get current price for the asset\n const infoClient = this.clientService.getInfoClient();\n const exchangeClient = this.clientService.getExchangeClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(symbol);\n\n // Fetch current price for this asset's DEX\n const mids = await infoClient.allMids(\n dexName ? { dex: dexName } : undefined,\n );\n const currentPrice = parseFloat(mids[symbol] || '0');\n\n if (currentPrice === 0) {\n throw new Error(`No price available for ${symbol}`);\n }\n\n // Cancel existing TP/SL orders for this position across all DEXs\n this.deps.debugLogger.log(\n 'Fetching open orders to cancel existing TP/SL...',\n );\n const orderResults = await this.queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.frontendOpenOrders(userParam),\n );\n\n // Combine orders from all DEXs\n const allOrders = orderResults.flatMap((result) => result.data);\n\n const tpslOrdersToCancel = allOrders.filter(\n (order) =>\n order.coin === symbol &&\n order.reduceOnly &&\n order.isPositionTpsl === Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&\n order.isTrigger &&\n (order.orderType.includes('Take Profit') ||\n order.orderType.includes('Stop')),\n );\n\n if (tpslOrdersToCancel.length > 0) {\n this.deps.debugLogger.log(\n `Canceling ${tpslOrdersToCancel.length} existing TP/SL orders for ${symbol}`,\n );\n const assetId = this.symbolToAssetId.get(symbol);\n if (assetId === undefined) {\n throw new Error(`Asset ID not found for ${symbol}`);\n }\n const cancelRequests = tpslOrdersToCancel.map((order) => ({\n a: assetId,\n o: order.oid,\n }));\n\n const cancelResult = await exchangeClient.cancel({\n cancels: cancelRequests,\n });\n this.deps.debugLogger.log('Cancel result:', cancelResult);\n }\n\n // Get asset info (dexName already extracted above) - uses cache\n const meta = await this.getCachedMeta({ dexName });\n\n // Check if meta is an error response (string) or doesn't have universe property\n if (\n !meta ||\n typeof meta === 'string' ||\n !meta.universe ||\n !Array.isArray(meta.universe)\n ) {\n this.deps.debugLogger.log(\n 'Failed to fetch metadata for asset mapping',\n {\n meta,\n dex: dexName || 'main',\n },\n );\n throw new Error(\n `Failed to fetch market metadata for DEX ${dexName || 'main'}`,\n );\n }\n\n // asset.name format: \"BTC\" for main DEX, \"xyz:XYZ100\" for HIP-3\n const assetInfo = meta.universe.find((asset) => asset.name === symbol);\n if (!assetInfo) {\n throw new Error(\n `Asset ${symbol} not found in ${dexName || 'main'} DEX universe`,\n );\n }\n\n const assetId = this.symbolToAssetId.get(symbol);\n if (assetId === undefined) {\n throw new Error(`Asset ID not found for ${symbol}`);\n }\n\n // Build orders array for TP/SL\n const orders: SDKOrderParams[] = [];\n\n const size = TP_SL_CONFIG.UsePositionBoundTpsl\n ? '0'\n : formatHyperLiquidSize({\n size: positionSize,\n szDecimals: assetInfo.szDecimals,\n });\n // Take Profit order\n if (takeProfitPrice) {\n const tpOrder: SDKOrderParams = {\n a: assetId,\n b: !isLong, // Opposite side to close position\n p: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals: assetInfo.szDecimals,\n }),\n s: size,\n r: true, // Always reduce-only for position TP\n t: {\n trigger: {\n isMarket: false, // Limit order when triggered\n triggerPx: formatHyperLiquidPrice({\n price: parseFloat(takeProfitPrice),\n szDecimals: assetInfo.szDecimals,\n }),\n tpsl: 'tp',\n },\n },\n };\n orders.push(tpOrder);\n }\n\n // Stop Loss order\n if (stopLossPrice) {\n const slOrder: SDKOrderParams = {\n a: assetId,\n b: !isLong, // Opposite side to close position\n p: formatHyperLiquidPrice({\n price: parseFloat(stopLossPrice),\n szDecimals: assetInfo.szDecimals,\n }),\n s: size,\n r: true, // Always reduce-only for position SL\n t: {\n trigger: {\n isMarket: true, // Market order when triggered for faster execution\n triggerPx: formatHyperLiquidPrice({\n price: parseFloat(stopLossPrice),\n szDecimals: assetInfo.szDecimals,\n }),\n tpsl: 'sl',\n },\n },\n };\n orders.push(slOrder);\n }\n\n // If no new orders, we've just cancelled existing ones (clearing TP/SL)\n if (orders.length === 0) {\n this.deps.debugLogger.log(\n 'No new TP/SL orders to place - existing ones cancelled',\n );\n return {\n success: true,\n // No orderId since we only cancelled orders, didn't place new ones\n };\n }\n\n // Calculate discounted builder fee if reward discount is active\n let builderFee = BUILDER_FEE_CONFIG.MaxFeeTenthsBps;\n if (this.userFeeDiscountBips !== undefined) {\n builderFee = Math.floor(\n builderFee * (1 - this.userFeeDiscountBips / BASIS_POINTS_DIVISOR),\n );\n this.deps.debugLogger.log(\n 'HyperLiquid: Applying builder fee discount to TP/SL',\n {\n originalFee: BUILDER_FEE_CONFIG.MaxFeeTenthsBps,\n discountBips: this.userFeeDiscountBips,\n discountedFee: builderFee,\n },\n );\n }\n\n // Submit via SDK exchange client with positionTpsl grouping\n const result = await exchangeClient.order({\n orders,\n grouping: 'positionTpsl',\n builder: {\n b: this.getBuilderAddress(this.clientService.isTestnetMode()),\n f: builderFee,\n },\n });\n\n if (result.status !== 'ok') {\n throw new Error(`TP/SL update failed: ${JSON.stringify(result)}`);\n }\n\n return {\n success: true,\n orderId: 'TP/SL orders placed',\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('updatePositionTPSL', {\n symbol: params.symbol,\n hasTakeProfit: params.takeProfitPrice !== undefined,\n hasStopLoss: params.stopLossPrice !== undefined,\n }),\n );\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Close a position\n *\n * For HIP-3 positions, this method automatically transfers freed margin\n * back to the main DEX after successfully closing the position.\n *\n * @param params\n */\n async closePosition(params: ClosePositionParams): Promise<OrderResult> {\n try {\n this.deps.debugLogger.log('Closing position:', params);\n\n // Explicitly ensure builder fee approval for trading\n await this.ensureReady();\n await this.ensureBuilderFeeApproval();\n\n // Force fresh API data (not WebSocket cache) since we're about to mutate the position\n const positions = await this.getPositions({ skipCache: true });\n const position = positions.find((pos) => pos.symbol === params.symbol);\n\n if (!position) {\n throw new Error(`No position found for ${params.symbol}`);\n }\n\n const positionSize = parseFloat(position.size);\n const isBuy = positionSize < 0;\n const closeSize = params.size || Math.abs(positionSize).toString();\n\n // Capture position details BEFORE closing for freed margin calculation\n const totalMarginUsed = parseFloat(position.marginUsed);\n const totalPositionSize = Math.abs(positionSize);\n const closeSizeNum = parseFloat(closeSize);\n const isHip3Position = position.symbol.includes(':');\n const hip3Dex = isHip3Position ? position.symbol.split(':')[0] : null;\n\n // Calculate freed margin proportionally\n const freedMarginRatio = closeSizeNum / totalPositionSize;\n const freedMargin = totalMarginUsed * freedMarginRatio;\n\n // Get current price for validation if not provided (and not a full close)\n // Full closes don't need price for validation\n let { currentPrice } = params;\n if (!currentPrice && params.size && !params.usdAmount) {\n // Partial close without USD or price: use limit price as fallback for validation\n // For limit orders, the limit price is a reasonable proxy for validation purposes\n if (params.price && params.orderType === 'limit') {\n currentPrice = parseFloat(params.price);\n this.deps.debugLogger.log(\n 'Using limit price for close position validation (limit order)',\n {\n coin: params.symbol,\n currentPrice,\n },\n );\n }\n // Note: For market orders without usdAmount/currentPrice, validation will fail\n // with \"price_required\" error, which is correct behavior (prevents invalid orders)\n }\n\n this.deps.debugLogger.log('Position close details', {\n coin: position.symbol,\n isHip3Position,\n hip3Dex,\n totalMarginUsed,\n closedSize: closeSize,\n freedMargin: freedMargin.toFixed(2),\n });\n\n // Execute position close with consistent slippage handling\n const result = await this.placeOrder({\n symbol: params.symbol,\n isBuy,\n size: closeSize,\n orderType: params.orderType || 'market',\n price: params.price,\n reduceOnly: true,\n isFullClose: !params.size, // True if closing 100% (size not provided)\n // Pass through price and slippage parameters for consistent validation\n currentPrice,\n usdAmount: params.usdAmount,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n });\n\n // Return freed margin using native abstraction or programmatic transfer\n if (\n result.success &&\n isHip3Position &&\n hip3Dex &&\n !this.useDexAbstraction\n ) {\n this.deps.debugLogger.log(\n 'Position closed successfully, initiating manual auto-transfer back',\n );\n\n // Non-blocking: Transfer freed margin back to main DEX\n await this.autoTransferBackAfterClose({\n sourceDex: hip3Dex,\n freedMargin,\n });\n } else if (\n result.success &&\n isHip3Position &&\n hip3Dex &&\n this.useDexAbstraction\n ) {\n this.deps.debugLogger.log(\n 'Position closed - DEX abstraction will auto-return freed margin',\n {\n coin: params.symbol,\n dex: hip3Dex,\n note: 'HyperLiquid handles return automatically',\n },\n );\n }\n\n return result;\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('closePosition', {\n coin: params.symbol,\n orderType: params.orderType,\n }),\n );\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Update margin for an existing position (add or remove)\n *\n * @param params - Margin adjustment parameters\n * @param params.symbol - Asset symbol (e.g., 'BTC', 'ETH')\n * @param params.amount - Amount to adjust as string (positive = add, negative = remove)\n * @returns Promise resolving to margin adjustment result\n *\n * Note: HyperLiquid uses micro-units (multiply by 1e6) for the ntli parameter.\n * The SDK's updateIsolatedMargin requires:\n * - asset: Asset ID (number)\n * - isBuy: Position direction (true for long, false for short)\n * - ntli: Amount in micro-units (amount * 1e6)\n */\n async updateMargin(params: {\n symbol: string;\n amount: string;\n }): Promise<MarginResult> {\n try {\n this.deps.debugLogger.log('Updating position margin:', params);\n\n const { symbol, amount } = params;\n\n // Ensure provider is ready\n await this.ensureReady();\n\n // Get current position to determine direction\n // Force fresh API data since we're about to mutate the position\n const positions = await this.getPositions({ skipCache: true });\n const position = positions.find((pos) => pos.symbol === symbol);\n\n if (!position) {\n throw new Error(`No position found for ${symbol}`);\n }\n\n // Determine position direction\n const isBuy = parseFloat(position.size) > 0; // true for long, false for short\n\n // Get asset ID for the symbol\n const assetId = this.symbolToAssetId.get(symbol);\n if (assetId === undefined) {\n throw new Error(`Asset ID not found for ${symbol}`);\n }\n\n // Convert amount to micro-units (HyperLiquid SDK requirement)\n const amountFloat = parseFloat(amount);\n const ntli = Math.floor(amountFloat * 1e6);\n\n this.deps.debugLogger.log('Margin adjustment details', {\n symbol,\n assetId,\n isBuy,\n amount: amountFloat,\n ntli,\n });\n\n // Call SDK to update isolated margin\n const exchangeClient = this.clientService.getExchangeClient();\n const result = await exchangeClient.updateIsolatedMargin({\n asset: assetId,\n isBuy,\n ntli,\n });\n\n this.deps.debugLogger.log('Margin update result:', result);\n\n if (result.status !== 'ok') {\n throw new Error(`Margin adjustment failed: ${JSON.stringify(result)}`);\n }\n\n return {\n success: true,\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('updateMargin', {\n symbol: params.symbol,\n amount: params.amount,\n }),\n );\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Get current positions with TP/SL prices\n *\n * Note on TP/SL orders:\n * - normalTpsl: TP/SL tied to parent order, only placed after parent fills\n * - positionTpsl: TP/SL tied to position, placed immediately\n *\n * This means TP/SL prices may not appear immediately after placing an order\n * with TP/SL. They will only show up once the parent order is filled and\n * the child TP/SL orders are actually placed on the order book.\n *\n * @param params\n */\n async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n try {\n // Try WebSocket cache first (unless explicitly bypassed)\n if (\n !params?.skipCache &&\n this.subscriptionService.isPositionsCacheInitialized()\n ) {\n const cachedPositions =\n this.subscriptionService.getCachedPositions() || [];\n this.deps.debugLogger.log('Using cached positions from WebSocket', {\n count: cachedPositions.length,\n });\n return cachedPositions;\n }\n\n // Fallback to API call\n this.deps.debugLogger.log(\n 'Fetching positions via API',\n params?.skipCache ? '(skipCache requested)' : '(cache not initialized)',\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n // Query positions and orders across all enabled DEXs in parallel\n const [stateResults, orderResults] = await Promise.all([\n this.queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n this.queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.frontendOpenOrders(userParam),\n ),\n ]);\n\n // Combine all orders from all DEXs for TP/SL lookup\n const allOrders = orderResults.flatMap((result) => result.data);\n\n this.deps.debugLogger.log('Frontend open orders (all DEXs):', {\n count: allOrders.length,\n orders: allOrders.map((ord) => ({\n coin: ord.coin,\n oid: ord.oid,\n orderType: ord.orderType,\n reduceOnly: ord.reduceOnly,\n isTrigger: ord.isTrigger,\n triggerPx: ord.triggerPx,\n isPositionTpsl: ord.isPositionTpsl,\n side: ord.side,\n sz: ord.sz,\n })),\n });\n\n // Combine and process positions from all DEXs\n const allPositions = stateResults.flatMap((result) =>\n result.data.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => {\n const position = adaptPositionFromSDK(assetPos);\n\n // Find TP/SL orders for this position\n // First check direct trigger orders (raw SDK uses 'coin', adapted position uses 'symbol')\n const positionOrders = allOrders.filter(\n (order) =>\n order.coin === position.symbol &&\n order.isTrigger &&\n order.reduceOnly,\n );\n\n // Also check for parent orders that might have TP/SL children\n const parentOrdersWithChildren = allOrders.filter(\n (order) =>\n order.coin === position.symbol &&\n order.children &&\n order.children.length > 0,\n );\n\n // Look for TP and SL trigger orders\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n\n // Check direct trigger orders\n positionOrders.forEach((order) => {\n // Frontend orders have explicit orderType field\n if (\n order.orderType === 'Take Profit Market' ||\n order.orderType === 'Take Profit Limit'\n ) {\n takeProfitPrice = order.triggerPx;\n this.deps.debugLogger.log(\n `Found TP order for ${position.symbol}:`,\n {\n triggerPrice: order.triggerPx,\n orderId: order.oid,\n orderType: order.orderType,\n isPositionTpsl: order.isPositionTpsl,\n },\n );\n } else if (\n order.orderType === 'Stop Market' ||\n order.orderType === 'Stop Limit'\n ) {\n stopLossPrice = order.triggerPx;\n this.deps.debugLogger.log(\n `Found SL order for ${position.symbol}:`,\n {\n triggerPrice: order.triggerPx,\n orderId: order.oid,\n orderType: order.orderType,\n isPositionTpsl: order.isPositionTpsl,\n },\n );\n }\n });\n\n // Check child orders (for normalTpsl grouping)\n parentOrdersWithChildren.forEach((parentOrder) => {\n this.deps.debugLogger.log(\n `Parent order with children for ${position.symbol}:`,\n {\n parentOid: parentOrder.oid,\n childrenCount: parentOrder.children.length,\n },\n );\n\n parentOrder.children.forEach((childOrderUnknown) => {\n const childOrder = childOrderUnknown as FrontendOrder;\n if (childOrder.isTrigger && childOrder.reduceOnly) {\n if (\n childOrder.orderType === 'Take Profit Market' ||\n childOrder.orderType === 'Take Profit Limit'\n ) {\n takeProfitPrice = childOrder.triggerPx;\n this.deps.debugLogger.log(\n `Found TP child order for ${position.symbol}:`,\n {\n triggerPrice: childOrder.triggerPx,\n orderId: childOrder.oid,\n orderType: childOrder.orderType,\n },\n );\n } else if (\n childOrder.orderType === 'Stop Market' ||\n childOrder.orderType === 'Stop Limit'\n ) {\n stopLossPrice = childOrder.triggerPx;\n this.deps.debugLogger.log(\n `Found SL child order for ${position.symbol}:`,\n {\n triggerPrice: childOrder.triggerPx,\n orderId: childOrder.oid,\n orderType: childOrder.orderType,\n },\n );\n }\n }\n });\n });\n\n return {\n ...position,\n takeProfitPrice,\n stopLossPrice,\n };\n }),\n );\n\n return allPositions;\n } catch (error) {\n this.deps.debugLogger.log('Error getting positions:', error);\n return [];\n }\n }\n\n /**\n * Get historical user fills (trade executions)\n *\n * @param params\n */\n async getOrderFills(params?: GetOrderFillsParams): Promise<OrderFill[]> {\n try {\n this.deps.debugLogger.log(\n 'Getting user fills via HyperLiquid SDK:',\n params,\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n // Use userFillsByTime when startTime is provided for time-filtered queries,\n // otherwise use userFills for backward compatibility\n const rawFills = params?.startTime\n ? await infoClient.userFillsByTime({\n user: userAddress,\n startTime: params.startTime,\n endTime: params.endTime,\n aggregateByTime: params?.aggregateByTime || false,\n })\n : await infoClient.userFills({\n user: userAddress,\n aggregateByTime: params?.aggregateByTime || false,\n });\n\n this.deps.debugLogger.log('User fills received:', rawFills);\n\n // Transform HyperLiquid fills to abstract OrderFill type\n const fills = (rawFills || []).reduce((acc: OrderFill[], fill) => {\n // Perps only, no Spots\n if (!['Buy', 'Sell'].includes(fill.dir)) {\n acc.push({\n orderId: fill.oid?.toString() || '',\n symbol: fill.coin,\n side: fill.side === 'A' ? 'sell' : 'buy',\n startPosition: fill.startPosition,\n size: fill.sz,\n price: fill.px,\n fee: fill.fee,\n feeToken: fill.feeToken,\n timestamp: fill.time,\n pnl: fill.closedPnl,\n direction: fill.dir,\n success: true,\n liquidation: fill.liquidation\n ? {\n liquidatedUser: fill.liquidation.liquidatedUser,\n markPx: fill.liquidation.markPx,\n method: fill.liquidation.method,\n }\n : undefined,\n });\n }\n\n return acc;\n }, []);\n\n return fills;\n } catch (error) {\n this.deps.debugLogger.log('Error getting user fills:', error);\n return [];\n }\n }\n\n /**\n * Get historical orders (order lifecycle)\n *\n * @param params\n */\n async getOrders(params?: GetOrdersParams): Promise<Order[]> {\n try {\n this.deps.debugLogger.log(\n 'Getting user orders via HyperLiquid SDK:',\n params,\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n const rawOrders = await infoClient.historicalOrders({\n user: userAddress,\n });\n\n this.deps.debugLogger.log('User orders received:', rawOrders);\n\n // Transform HyperLiquid orders to abstract Order type\n const orders: Order[] = (rawOrders || []).map((rawOrder) => {\n const { order, status, statusTimestamp } = rawOrder;\n // Normalize side: HyperLiquid uses 'A' (Ask/Sell) and 'B' (Bid/Buy)\n const normalizedSide = order.side === 'B' ? 'buy' : 'sell';\n\n // Normalize status\n let normalizedStatus: Order['status'];\n switch (status) {\n case 'open':\n normalizedStatus = 'open';\n break;\n case 'filled':\n normalizedStatus = 'filled';\n break;\n case 'canceled':\n case 'marginCanceled':\n case 'vaultWithdrawalCanceled':\n case 'openInterestCapCanceled':\n case 'selfTradeCanceled':\n case 'reduceOnlyCanceled':\n case 'siblingFilledCanceled':\n case 'delistedCanceled':\n case 'liquidatedCanceled':\n case 'scheduledCancel':\n case 'reduceOnlyRejected':\n normalizedStatus = 'canceled';\n break;\n case 'rejected':\n // case 'minTradeNtlRejected':\n normalizedStatus = 'rejected';\n break;\n case 'triggered':\n normalizedStatus = 'triggered';\n break;\n default:\n normalizedStatus = 'queued';\n }\n\n // Calculate filled and remaining size\n const originalSize = parseFloat(order.origSz || order.sz);\n const currentSize = parseFloat(order.sz);\n const filledSize = originalSize - currentSize;\n\n return {\n orderId: order.oid?.toString() || '',\n symbol: order.coin,\n side: normalizedSide,\n orderType: order.orderType?.toLowerCase().includes('limit')\n ? 'limit'\n : 'market',\n size: order.sz,\n originalSize: order.origSz || order.sz,\n price: order.limitPx || '0',\n filledSize: filledSize.toString(),\n remainingSize: currentSize.toString(),\n status: normalizedStatus,\n timestamp: statusTimestamp,\n lastUpdated: statusTimestamp,\n detailedOrderType: order.orderType, // Full order type from exchange (e.g., 'Take Profit Limit', 'Stop Market')\n isTrigger: order.isTrigger,\n reduceOnly: order.reduceOnly,\n };\n });\n\n return orders;\n } catch (error) {\n this.deps.debugLogger.log('Error getting user orders:', error);\n return [];\n }\n }\n\n /**\n * Get currently open orders (real-time status)\n * Uses frontendOpenOrders API to get only currently active orders\n * Aggregates orders from all enabled DEXs (main + HIP-3)\n *\n * @param params\n */\n async getOpenOrders(params?: GetOrdersParams): Promise<Order[]> {\n try {\n // Try WebSocket cache first (unless explicitly bypassed)\n if (\n !params?.skipCache &&\n this.subscriptionService.isOrdersCacheInitialized()\n ) {\n const cachedOrders = this.subscriptionService.getCachedOrders() || [];\n this.deps.debugLogger.log('Using cached open orders from WebSocket', {\n count: cachedOrders.length,\n });\n return cachedOrders;\n }\n\n // Fallback to API call\n this.deps.debugLogger.log(\n 'Fetching open orders via API',\n params?.skipCache ? '(skipCache requested)' : '(cache not initialized)',\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n // Query orders across all enabled DEXs in parallel\n const orderResults = await this.queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.frontendOpenOrders(userParam),\n );\n\n // Combine all orders from all DEXs\n const rawOrders = orderResults.flatMap((result) => result.data);\n\n // Get positions for order context (already multi-DEX aware)\n const positions = await this.getPositions();\n\n this.deps.debugLogger.log('Currently open orders received (all DEXs):', {\n count: rawOrders.length,\n });\n\n // Transform HyperLiquid open orders to abstract Order type using adapter\n // Raw SDK orders use 'coin', adapted positions use 'symbol'\n const orders: Order[] = (rawOrders || []).map((order) => {\n const position = positions.find((pos) => pos.symbol === order.coin);\n return adaptOrderFromSDK(order, position);\n });\n\n return orders;\n } catch (error) {\n this.deps.debugLogger.log('Error getting currently open orders:', error);\n return [];\n }\n }\n\n /**\n * Get user funding history\n *\n * @param params\n */\n async getFunding(params?: GetFundingParams): Promise<Funding[]> {\n try {\n this.deps.debugLogger.log(\n 'Getting user funding via HyperLiquid SDK:',\n params,\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n // HyperLiquid API requires startTime to be a number (not undefined)\n // Default to configured days ago to get recent funding payments\n // Using 0 (epoch) would return oldest 500 records, missing latest payments\n const defaultStartTime =\n Date.now() -\n PERPS_TRANSACTIONS_HISTORY_CONSTANTS.DefaultFundingHistoryDays *\n 24 *\n 60 *\n 60 *\n 1000;\n const rawFunding = await infoClient.userFunding({\n user: userAddress,\n startTime: params?.startTime ?? defaultStartTime,\n endTime: params?.endTime,\n });\n\n this.deps.debugLogger.log('User funding received:', rawFunding);\n\n // Transform HyperLiquid funding to abstract Funding type\n const funding: Funding[] = (rawFunding || []).map((rawFundingItem) => {\n const { delta, hash, time } = rawFundingItem;\n\n return {\n symbol: delta.coin,\n amountUsd: delta.usdc,\n rate: delta.fundingRate,\n timestamp: time,\n transactionHash: hash,\n };\n });\n\n return funding;\n } catch (error) {\n this.deps.debugLogger.log('Error getting user funding:', error);\n return [];\n }\n }\n\n /**\n * Get user non-funding ledger updates (deposits, transfers, withdrawals)\n *\n * @param params\n * @param params.accountId\n * @param params.startTime\n * @param params.endTime\n */\n async getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawHyperLiquidLedgerUpdate[]> {\n try {\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId as CaipAccountId | undefined,\n );\n\n const rawLedgerUpdates = await infoClient.userNonFundingLedgerUpdates({\n user: userAddress,\n startTime: params?.startTime || 0,\n endTime: params?.endTime,\n });\n\n return rawLedgerUpdates || [];\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getUserNonFundingLedgerUpdates', params),\n );\n return [];\n }\n }\n\n /**\n * Get user history (deposits, withdrawals, transfers)\n *\n * @param params\n * @param params.accountId\n * @param params.startTime\n * @param params.endTime\n */\n async getUserHistory(params?: {\n accountId?: CaipAccountId;\n startTime?: number;\n endTime?: number;\n }): Promise<UserHistoryItem[]> {\n try {\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n const rawLedgerUpdates = await infoClient.userNonFundingLedgerUpdates({\n user: userAddress,\n startTime: params?.startTime || 0,\n endTime: params?.endTime,\n });\n\n // Transform the raw ledger updates to UserHistoryItem format\n return adaptHyperLiquidLedgerUpdateToUserHistoryItem(rawLedgerUpdates);\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getUserHistory'),\n );\n return [];\n }\n }\n\n async getHistoricalPortfolio(\n params?: GetHistoricalPortfolioParams,\n ): Promise<HistoricalPortfolioResult> {\n try {\n this.deps.debugLogger.log(\n 'Getting historical portfolio via HyperLiquid SDK:',\n params,\n );\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n // Get portfolio data\n const portfolioData = await infoClient.portfolio({\n user: userAddress,\n });\n\n // Calculate target time (default to 24 hours ago)\n const targetTime = Date.now() - 24 * 60 * 60 * 1000;\n\n // Get UTC 00:00 of the target day\n const targetDate = new Date(targetTime);\n const targetTimestamp = targetDate.getTime();\n\n // Get the account value history from the last week's data\n const weeklyPeriod = portfolioData?.[1];\n const weekData = weeklyPeriod?.[1];\n const accountValueHistory = weekData?.accountValueHistory || [];\n\n // Find entries that are before the target timestamp, then get the closest one\n const entriesBeforeTarget = accountValueHistory.filter(\n ([timestamp]) => timestamp < targetTimestamp,\n );\n\n let closestEntry = null;\n let smallestDiff = Infinity;\n for (const entry of entriesBeforeTarget) {\n const [timestamp] = entry;\n const diff = targetTimestamp - timestamp;\n if (diff < smallestDiff) {\n smallestDiff = diff;\n closestEntry = entry;\n }\n }\n\n const result: HistoricalPortfolioResult = closestEntry\n ? {\n accountValue1dAgo: closestEntry[1] || '0',\n timestamp: closestEntry[0] || 0,\n }\n : {\n accountValue1dAgo:\n accountValueHistory?.[accountValueHistory.length - 1]?.[1] || '0',\n timestamp: 0,\n };\n\n this.deps.debugLogger.log('Historical portfolio result:', result);\n return result;\n } catch (error) {\n this.deps.debugLogger.log('Error getting historical portfolio:', error);\n return {\n accountValue1dAgo: '0',\n timestamp: 0,\n };\n }\n }\n\n /**\n * Get account state\n * Aggregates balances across all enabled DEXs (main + HIP-3)\n *\n * @param params\n */\n async getAccountState(params?: GetAccountStateParams): Promise<AccountState> {\n try {\n this.deps.debugLogger.log('Getting account state via HyperLiquid SDK');\n\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n this.deps.debugLogger.log('User address for account state:', userAddress);\n this.deps.debugLogger.log(\n 'Network mode:',\n this.clientService.isTestnetMode() ? 'TESTNET' : 'MAINNET',\n );\n\n // Get Spot balance (global, not DEX-specific) and Perps states across all DEXs\n const [spotState, perpsStateResults] = await Promise.all([\n infoClient.spotClearinghouseState({ user: userAddress }),\n this.queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n ]);\n\n this.deps.debugLogger.log('Spot state:', spotState);\n this.deps.debugLogger.log('Perps states (all DEXs):', {\n dexCount: perpsStateResults.length,\n });\n\n // Aggregate account states from all DEXs\n // Each DEX has independent positions and margin, we sum them\n const aggregatedAccountState = perpsStateResults.reduce<AccountState>(\n (acc, result, index) => {\n const { dex, data: perpsState } = result;\n\n // Adapt this DEX's state (without spot - we'll add spot once at the end)\n const dexAccountState = adaptAccountStateFromSDK(perpsState);\n\n // Log each DEX contribution\n this.deps.debugLogger.log(`DEX ${dex || 'main'} account state:`, {\n totalBalance: dexAccountState.totalBalance,\n availableBalance: dexAccountState.availableBalance,\n marginUsed: dexAccountState.marginUsed,\n unrealizedPnl: dexAccountState.unrealizedPnl,\n });\n\n // Sum up numeric values across all DEXs\n if (index === 0) {\n // First DEX - initialize with its values\n return dexAccountState;\n }\n\n // Subsequent DEXs - aggregate\n return {\n availableBalance: (\n parseFloat(acc.availableBalance) +\n parseFloat(dexAccountState.availableBalance)\n ).toString(),\n totalBalance: (\n parseFloat(acc.totalBalance) +\n parseFloat(dexAccountState.totalBalance)\n ).toString(),\n marginUsed: (\n parseFloat(acc.marginUsed) +\n parseFloat(dexAccountState.marginUsed)\n ).toString(),\n unrealizedPnl: (\n parseFloat(acc.unrealizedPnl) +\n parseFloat(dexAccountState.unrealizedPnl)\n ).toString(),\n // Return on equity is weighted average, but for simplicity we'll recalculate\n // ROE = (unrealizedPnl / marginUsed) * 100\n returnOnEquity: '0', // Will recalculate below\n };\n },\n {\n availableBalance: '0',\n totalBalance: '0',\n marginUsed: '0',\n unrealizedPnl: '0',\n returnOnEquity: '0',\n },\n );\n\n // Recalculate return on equity across all DEXs\n const totalMarginUsed = parseFloat(aggregatedAccountState.marginUsed);\n const totalUnrealizedPnl = parseFloat(\n aggregatedAccountState.unrealizedPnl,\n );\n if (totalMarginUsed > 0) {\n aggregatedAccountState.returnOnEquity = (\n (totalUnrealizedPnl / totalMarginUsed) *\n 100\n ).toFixed(1);\n } else {\n aggregatedAccountState.returnOnEquity = '0';\n }\n\n // Add spot balance to totalBalance (spot is global, not per-DEX)\n let spotBalance = 0;\n if (spotState?.balances && Array.isArray(spotState.balances)) {\n spotBalance = spotState.balances.reduce(\n (sum, balance) => sum + parseFloat(balance.total || '0'),\n 0,\n );\n }\n aggregatedAccountState.totalBalance = (\n parseFloat(aggregatedAccountState.totalBalance) + spotBalance\n ).toString();\n\n // Build per-sub-account breakdown (HIP-3 DEXs map to sub-accounts)\n const subAccountBreakdown: Record<\n string,\n { availableBalance: string; totalBalance: string }\n > = {};\n perpsStateResults.forEach((result) => {\n const { dex, data: perpsState } = result;\n const dexAccountState = adaptAccountStateFromSDK(perpsState);\n const subAccountKey = dex || ''; // Empty string for main DEX\n\n subAccountBreakdown[subAccountKey] = {\n availableBalance: dexAccountState.availableBalance,\n totalBalance: dexAccountState.totalBalance,\n };\n });\n\n // Add sub-account breakdown to result\n aggregatedAccountState.subAccountBreakdown = subAccountBreakdown;\n\n this.deps.debugLogger.log(\n 'Aggregated account state:',\n aggregatedAccountState,\n );\n\n return aggregatedAccountState;\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getAccountState', {\n accountId: params?.accountId,\n }),\n );\n // Re-throw the error so the controller can handle it properly\n // This allows the UI to show proper error messages instead of zeros\n throw error;\n }\n }\n\n /**\n * Get available markets with multi-DEX aggregation support (HIP-3)\n * Handles three query patterns:\n * 1. Symbol filtering: Groups symbols by DEX, fetches in parallel\n * 2. Multi-DEX aggregation: Fetches from all enabled DEXs when no specific DEX requested\n * 3. Single DEX query: Fetches from main or specific DEX\n *\n * @param params - Optional parameters for filtering\n */\n async getMarkets(params?: GetMarketsParams): Promise<MarketInfo[]> {\n try {\n // Path 0: Read-only mode for lightweight discovery queries\n // Creates a standalone InfoClient without requiring full initialization\n // No wallet, WebSocket, or account setup needed - just HTTP API call\n // Use for discovery use cases like checking if a perps market exists\n if (params?.readOnly) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Getting markets in readOnly mode (standalone client)',\n { symbolCount: params?.symbols?.length },\n );\n\n // Create standalone client - bypasses all initialization (wallet, WebSocket, etc.)\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.clientService.isTestnetMode(),\n });\n\n // Simple path: fetch main DEX markets only (no HIP-3 multi-DEX)\n const meta = await standaloneInfoClient.meta();\n\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n throw new Error(\n 'Invalid universe data received from HyperLiquid API',\n );\n }\n\n // Transform to MarketInfo format\n const markets = meta.universe.map((asset) => adaptMarketFromSDK(asset));\n\n // Filter by symbols if provided\n if (params?.symbols?.length) {\n return markets.filter((market) =>\n params.symbols?.some(\n (symbol) => market.name.toUpperCase() === symbol.toUpperCase(),\n ),\n );\n }\n\n return markets;\n }\n\n // Ensure full initialization including asset mapping\n // This is deduplicated - concurrent calls wait for the same promise\n await this.ensureReady();\n\n // Path 1: Symbol filtering - group by DEX and fetch in parallel\n if (params?.symbols && params.symbols.length > 0) {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Getting markets with symbol filter',\n {\n symbolCount: params.symbols.length,\n },\n );\n\n // Group symbols by DEX\n const symbolsByDex = new Map<string | null, string[]>();\n params.symbols.forEach((symbol) => {\n const { dex } = parseAssetName(symbol);\n const existing = symbolsByDex.get(dex);\n if (existing) {\n existing.push(symbol);\n } else {\n symbolsByDex.set(dex, [symbol]);\n }\n });\n\n // Query each unique DEX in parallel (with caching)\n const marketArrays = await Promise.all(\n Array.from(symbolsByDex.keys()).map(async (dex) =>\n this.fetchMarketsForDex({\n dex,\n skipFilters: params?.skipFilters,\n }),\n ),\n );\n\n // Combine and filter by requested symbols\n const allMarkets = marketArrays.flat();\n return allMarkets.filter((market) =>\n params.symbols?.some(\n (symbol) => market.name.toLowerCase() === symbol.toLowerCase(),\n ),\n );\n }\n\n // Path 2: Multi-DEX aggregation - fetch from all enabled DEXs\n if (!params?.dex && this.hip3Enabled) {\n // Determine which DEXs to query based on skipFilters flag\n const dexsToQuery = params?.skipFilters\n ? await this.getAllAvailableDexs()\n : await this.getValidatedDexs();\n\n if (dexsToQuery.length > 1) {\n // More than just main DEX\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Fetching markets from DEXs',\n {\n dexCount: dexsToQuery.length,\n skipFilters: params?.skipFilters || false,\n },\n );\n\n const marketArrays = await Promise.all(\n dexsToQuery.map(async (dex) => {\n try {\n return await this.fetchMarketsForDex({\n dex,\n skipFilters: params?.skipFilters,\n });\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getMarkets.multiDex', {\n dex: dex ?? 'main',\n }),\n );\n return []; // Continue with other DEXs on error\n }\n }),\n );\n\n return marketArrays.flat();\n }\n }\n\n // Path 3: Single DEX query (main DEX or specific DEX) - with caching\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Getting markets for single DEX',\n {\n dex: params?.dex || 'main',\n },\n );\n\n return await this.fetchMarketsForDex({\n dex: params?.dex ?? null,\n skipFilters: params?.skipFilters,\n });\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getMarkets', {\n dex: params?.dex,\n symbolCount: params?.symbols?.length,\n }),\n );\n return [];\n }\n }\n\n /**\n * Get list of available HIP-3 DEXs that have markets\n * Useful for debugging and manual DEX selection\n *\n * @returns Array of DEX names (excluding main DEX)\n */\n async getAvailableHip3Dexs(): Promise<string[]> {\n try {\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n if (!this.hip3Enabled) {\n this.deps.debugLogger.log('HIP-3 disabled, no DEXs available');\n return [];\n }\n\n const infoClient = this.clientService.getInfoClient();\n\n // Get all DEXs from API\n const allDexs = await infoClient.perpDexs();\n\n if (!allDexs || !Array.isArray(allDexs)) {\n this.deps.debugLogger.log('perpDexs() returned invalid data');\n return [];\n }\n\n // Extract HIP-3 DEX names (filter out null which is main DEX)\n const hip3DexNames: string[] = [];\n allDexs.forEach((dex) => {\n if (dex !== null && 'name' in dex) {\n hip3DexNames.push(dex.name);\n }\n });\n\n this.deps.debugLogger.log(\n `Found ${hip3DexNames.length} HIP-3 DEXs from perpDexs() API`,\n );\n\n // Filter to only DEXs that have markets\n const dexsWithMarkets: string[] = [];\n await Promise.all(\n hip3DexNames.map(async (dexName) => {\n try {\n const meta = await this.getCachedMeta({ dexName });\n if (\n meta.universe &&\n Array.isArray(meta.universe) &&\n meta.universe.length > 0\n ) {\n dexsWithMarkets.push(dexName);\n this.deps.debugLogger.log(\n ` ✅ ${dexName}: ${meta.universe.length} markets`,\n );\n } else {\n this.deps.debugLogger.log(` ⚠️ ${dexName}: no markets`);\n }\n } catch (error) {\n this.deps.debugLogger.log(` ❌ ${dexName}: error querying`, error);\n }\n }),\n );\n\n this.deps.debugLogger.log(\n `${dexsWithMarkets.length} DEXs have markets:`,\n dexsWithMarkets,\n );\n return dexsWithMarkets.sort((a, b) => a.localeCompare(b));\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getAvailableHip3Dexs'),\n );\n return [];\n }\n }\n\n /**\n * Get market data with prices, volumes, and 24h changes\n * Aggregates data from all enabled DEXs (main + HIP-3) when equity is enabled\n *\n * Note: This is called once during initialization and cached by PerpsStreamManager.\n * Real-time price updates come from WebSocket subscriptions, not this method.\n */\n async getMarketDataWithPrices(): Promise<PerpsMarketData[]> {\n this.deps.debugLogger.log(\n 'Getting market data with prices via HyperLiquid SDK',\n );\n\n // Ensure asset mapping is built first (populates meta cache)\n // This guarantees buildAssetMapping has run before we check cache,\n // eliminating duplicate metaAndAssetCtxs API calls from race conditions\n await this.ensureReady();\n\n const infoClient = this.clientService.getInfoClient();\n\n // Get enabled DEXs respecting feature flags (uses cached perpDexs)\n const enabledDexs = await this.getValidatedDexs();\n\n // Fetch meta, assetCtxs, and allMids for each enabled DEX in parallel\n // Optimization: Check cache first to avoid redundant API calls when buildAssetMapping\n // has already fetched, or populate cache for buildAssetMapping to reuse\n const dexDataResults = await Promise.all(\n enabledDexs.map(async (dex) => {\n const dexKey = dex ?? '';\n const dexParam = dex ?? '';\n try {\n let meta: MetaResponse | null = null;\n let assetCtxs: PerpsAssetCtx[] = [];\n\n // Check if meta is already cached (e.g., from previous fetch or buildAssetMapping)\n const cachedMeta = this.cachedMetaByDex.get(dexKey);\n if (cachedMeta) {\n this.deps.debugLogger.log(\n `[getMarketDataWithPrices] Using cached meta for ${dex || 'main'}`,\n { universeSize: cachedMeta.universe.length },\n );\n meta = cachedMeta;\n // Try to get cached assetCtxs from subscription service\n const cachedCtxs =\n this.subscriptionService.getDexAssetCtxsCache(dexKey);\n if (cachedCtxs) {\n assetCtxs = cachedCtxs;\n } else {\n // Need fresh assetCtxs, fetch via metaAndAssetCtxs (meta will be same)\n const metaAndCtxs = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\n assetCtxs = metaAndCtxs?.[1] || [];\n // Cache assetCtxs for future calls\n this.subscriptionService.setDexAssetCtxsCache(dexKey, assetCtxs);\n }\n } else {\n // Cache miss - fetch and populate cache for buildAssetMapping to reuse\n this.deps.debugLogger.log(\n `[getMarketDataWithPrices] Cache miss for ${dex || 'main'}, fetching`,\n );\n const metaAndCtxs = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\n meta = metaAndCtxs?.[0] || null;\n assetCtxs = metaAndCtxs?.[1] || [];\n\n // IMPORTANT: Populate cache for buildAssetMapping and other methods to reuse\n if (meta?.universe) {\n this.cachedMetaByDex.set(dexKey, meta);\n this.subscriptionService.setDexMetaCache(dexKey, meta);\n // Also cache assetCtxs for consistency with buildAssetMapping\n this.subscriptionService.setDexAssetCtxsCache(dexKey, assetCtxs);\n this.deps.debugLogger.log(\n `[getMarketDataWithPrices] Cached meta for ${dex || 'main'}`,\n { universeSize: meta.universe.length },\n );\n }\n }\n\n // Always fetch fresh allMids for current prices\n const dexAllMids = await infoClient.allMids(\n dexParam ? { dex: dexParam } : undefined,\n );\n\n return {\n dex,\n meta,\n assetCtxs,\n allMids: dexAllMids || {},\n success: true,\n };\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getMarketDataWithPrices.fetchDex', {\n dex: dex ?? 'main',\n }),\n );\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n };\n }\n }),\n );\n\n // Combine universe, assetCtxs, and allMids from all DEXs\n const combinedUniverse: MetaResponse['universe'] = [];\n const combinedAssetCtxs: PerpsAssetCtx[] = [];\n const combinedAllMids: Record<string, string> = {};\n\n dexDataResults.forEach((result) => {\n if (result.success && result.meta?.universe) {\n // Apply market filtering for HIP-3 DEXs only (main DEX returns all markets)\n const marketsFromDex = result.meta.universe;\n const filteredMarkets =\n result.dex === null\n ? marketsFromDex // Main DEX: no filtering\n : marketsFromDex.filter((asset) =>\n shouldIncludeMarket(\n asset.name,\n result.dex,\n this.hip3Enabled,\n this.compiledAllowlistPatterns,\n this.compiledBlocklistPatterns,\n ),\n );\n\n combinedUniverse.push(...filteredMarkets);\n combinedAssetCtxs.push(...result.assetCtxs);\n // Merge price data from this DEX into combined prices\n Object.assign(combinedAllMids, result.allMids);\n }\n });\n\n if (combinedUniverse.length === 0) {\n throw new Error('Failed to fetch market data - no markets available');\n }\n\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: Aggregated market data from all DEXs',\n {\n dexCount: enabledDexs.length,\n totalMarkets: combinedUniverse.length,\n mainDexMarkets: dexDataResults[0]?.meta?.universe?.length || 0,\n hip3Markets:\n combinedUniverse.length -\n (dexDataResults[0]?.meta?.universe?.length || 0),\n },\n );\n\n // Debug: Log combinedAllMids to diagnose price lookup issues\n const hip3Keys = Object.keys(combinedAllMids).filter((key) =>\n key.includes(':'),\n );\n this.deps.debugLogger.log('Combined allMids price data:', {\n totalKeys: Object.keys(combinedAllMids).length,\n allKeys: Object.keys(combinedAllMids),\n hip3Keys,\n hip3Prices: Object.fromEntries(\n hip3Keys.map((key) => [key, combinedAllMids[key]]),\n ),\n samplePrices: Object.fromEntries(\n Object.entries(combinedAllMids).slice(0, 5),\n ),\n });\n\n // Transform to UI-friendly format using standalone utility\n return transformMarketData(\n {\n universe: combinedUniverse,\n assetCtxs: combinedAssetCtxs,\n allMids: combinedAllMids,\n },\n HIP3_ASSET_MARKET_TYPES,\n );\n }\n\n /**\n * Validate deposit parameters according to HyperLiquid-specific rules\n * This method enforces protocol-specific requirements like minimum amounts\n *\n * @param params\n */\n async validateDeposit(\n params: DepositParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n return validateDepositParams({\n amount: params.amount,\n assetId: params.assetId,\n isTestnet: this.clientService.isTestnetMode(),\n });\n }\n\n /**\n * Validate order parameters according to HyperLiquid-specific rules\n * This includes minimum order sizes, leverage limits, and other protocol requirements\n *\n * @param params\n */\n async validateOrder(\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n try {\n // Basic parameter validation\n const basicValidation = validateOrderParams({\n coin: params.symbol,\n size: params.size,\n price: params.price,\n orderType: params.orderType,\n });\n if (!basicValidation.isValid) {\n return basicValidation;\n }\n\n // Check minimum order size using consistent defaults (matching useMinimumOrderAmount hook)\n // Note: For full validation with market-specific limits, use async methods\n const minimumOrderSize = this.clientService.isTestnetMode()\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n // Skip USD validation and minimum check for full closes (100% position close)\n if (params.reduceOnly && params.isFullClose) {\n this.deps.debugLogger.log(\n 'Full close detected: skipping USD validation and $10 minimum',\n );\n } else {\n // Calculate order value in USD for minimum validation\n let orderValueUSD: number;\n\n if (params.usdAmount) {\n // Preferred: Use provided USD amount (source of truth, no rounding loss)\n orderValueUSD = parseFloat(params.usdAmount);\n\n this.deps.debugLogger.log(\n 'Validating USD amount (source of truth):',\n {\n usdAmount: orderValueUSD,\n minimumRequired: minimumOrderSize,\n },\n );\n } else {\n // Fallback: Calculate from size × price\n const size = parseFloat(params.size || '0');\n let priceForValidation = params.currentPrice;\n\n // For limit orders without currentPrice, use limit price as fallback\n if (\n !priceForValidation &&\n params.price &&\n params.orderType === 'limit'\n ) {\n priceForValidation = parseFloat(params.price);\n this.deps.debugLogger.log(\n 'Using limit price for order validation (limit order):',\n {\n size,\n limitPrice: priceForValidation,\n },\n );\n }\n\n if (!priceForValidation) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_PRICE_REQUIRED,\n };\n }\n\n orderValueUSD = size * priceForValidation;\n\n this.deps.debugLogger.log('Validating calculated USD from size:', {\n size,\n price: priceForValidation,\n calculatedUsd: orderValueUSD,\n minimumRequired: minimumOrderSize,\n });\n }\n\n // Validate minimum order size\n if (orderValueUSD < minimumOrderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n };\n }\n }\n\n // Asset-specific leverage validation\n if (params.leverage && params.symbol) {\n try {\n const maxLeverage = await this.getMaxLeverage(params.symbol);\n if (params.leverage < 1 || params.leverage > maxLeverage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID,\n };\n }\n } catch (error) {\n // Log the error before falling back\n this.deps.debugLogger.log(\n 'Failed to get max leverage for symbol',\n error,\n );\n // If we can't get max leverage, use the default as fallback\n const defaultMaxLeverage = PERPS_CONSTANTS.DefaultMaxLeverage;\n if (params.leverage < 1 || params.leverage > defaultMaxLeverage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID,\n };\n }\n }\n }\n\n // Check if order leverage meets existing position requirement (HyperLiquid protocol constraint)\n if (\n params.leverage &&\n params.existingPositionLeverage &&\n params.leverage < params.existingPositionLeverage\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LEVERAGE_BELOW_POSITION,\n };\n }\n\n // Validate order value against max limits\n if (params.currentPrice && params.leverage) {\n try {\n const maxLeverage = await this.getMaxLeverage(params.symbol);\n\n const maxOrderValue = getMaxOrderValue(maxLeverage, params.orderType);\n const orderValue = parseFloat(params.size) * params.currentPrice;\n\n if (orderValue > maxOrderValue) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MAX_VALUE_EXCEEDED,\n };\n }\n } catch (error) {\n this.deps.debugLogger.log(\n 'Failed to validate max order value',\n error,\n );\n // Continue without max order validation if we can't get leverage\n }\n }\n\n return { isValid: true };\n } catch (error) {\n return {\n isValid: false,\n error:\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n }\n }\n\n /**\n * Validate close position parameters according to HyperLiquid-specific rules\n * Note: Full validation including remaining position size requires position data\n * which should be passed from the UI layer\n *\n * @param params\n */\n async validateClosePosition(\n params: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n try {\n // Basic validation\n if (!params.symbol) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_COIN_REQUIRED,\n };\n }\n\n // If closing with limit order, must have price\n if (params.orderType === 'limit' && !params.price) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,\n };\n }\n\n // Determine minimum order size (needed for precedence logic)\n const minimumOrderSize = this.clientService.isTestnetMode()\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n // Validate close size & minimum only if size provided (partial close)\n if (params.size) {\n const closeSize = parseFloat(params.size);\n const price = params.currentPrice\n ? parseFloat(params.currentPrice.toString())\n : undefined;\n const orderValueUSD =\n price && !isNaN(closeSize) ? closeSize * price : undefined;\n\n // Precedence rule: if size <= 0 treat as minimum_amount failure (more actionable)\n if (isNaN(closeSize) || closeSize <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n };\n }\n\n // Enforce minimum order value for partial closes when price known\n if (orderValueUSD !== undefined && orderValueUSD < minimumOrderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n };\n }\n\n // Note: Remaining position validation stays in UI layer.\n }\n // Full closes (size undefined) bypass minimum check by design\n // Note: For full closes (when size is undefined), there is no minimum\n // This allows users to close positions worth less than $10 completely\n\n return { isValid: true };\n } catch (error) {\n return {\n isValid: false,\n error:\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n }\n }\n\n /**\n * Validate withdrawal parameters - placeholder for future implementation\n *\n * @param _params\n */\n async validateWithdrawal(\n _params: WithdrawParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n // Placeholder - to be implemented when needed\n return { isValid: true };\n }\n\n /**\n * Withdraw funds from HyperLiquid trading account\n *\n * This initiates a withdrawal request via HyperLiquid's API (withdraw3 endpoint).\n *\n * HyperLiquid Bridge Process:\n * - Funds are immediately deducted from L1 balance on HyperLiquid\n * - Validators sign the withdrawal (2/3 of staking power required)\n * - Bridge contract on destination chain processes the withdrawal\n * - After dispute period, USDC is sent to destination address\n * - Total time: ~5 minutes\n * - Fee: 1 USDC (covers Arbitrum gas costs)\n * - No ETH required from user\n *\n * Note: Withdrawals won't appear as incoming transactions until the\n * finalization phase completes (~5 minutes after initiation)\n *\n * @param params Withdrawal parameters\n * @returns Result with txHash (HyperLiquid internal) and withdrawal ID\n */\n async withdraw(params: WithdrawParams): Promise<WithdrawResult> {\n try {\n this.deps.debugLogger.log('HyperLiquidProvider: STARTING WITHDRAWAL', {\n params,\n timestamp: new Date().toISOString(),\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n isTestnet: this.clientService.isTestnetMode(),\n });\n\n // Step 1: Validate withdrawal parameters\n this.deps.debugLogger.log('HyperLiquidProvider: VALIDATING PARAMETERS');\n const validation = validateWithdrawalParams(params);\n if (!validation.isValid) {\n this.deps.debugLogger.log(\n '❌ HyperLiquidProvider: PARAMETER VALIDATION FAILED',\n {\n error: validation.error,\n params,\n validationResult: validation,\n },\n );\n throw new Error(validation.error);\n }\n this.deps.debugLogger.log('HyperLiquidProvider: PARAMETERS VALIDATED');\n\n // Step 2: Get supported withdrawal routes and validate asset\n this.deps.debugLogger.log('HyperLiquidProvider: CHECKING ASSET SUPPORT');\n const supportedRoutes = this.getWithdrawalRoutes();\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: SUPPORTED WITHDRAWAL ROUTES',\n {\n routeCount: supportedRoutes.length,\n routes: supportedRoutes.map((route) => ({\n assetId: route.assetId,\n chainId: route.chainId,\n contractAddress: route.contractAddress,\n })),\n },\n );\n\n // This check is already done in validateWithdrawalParams, but TypeScript needs explicit check\n if (!params.assetId) {\n this.deps.debugLogger.log('HyperLiquidProvider: MISSING ASSET ID', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n params,\n });\n throw new Error(PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED);\n }\n\n const assetValidation = validateAssetSupport(\n params.assetId,\n supportedRoutes,\n );\n if (!assetValidation.isValid) {\n this.deps.debugLogger.log(\n '❌ HyperLiquidProvider: ASSET NOT SUPPORTED',\n {\n error: assetValidation.error,\n assetId: params.assetId,\n supportedAssets: supportedRoutes.map((route) => route.assetId),\n },\n );\n throw new Error(assetValidation.error);\n }\n this.deps.debugLogger.log('HyperLiquidProvider: ASSET SUPPORTED', {\n assetId: params.assetId,\n });\n\n // Step 3: Determine destination address\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: DETERMINING DESTINATION ADDRESS',\n );\n let destination: Hex;\n if (params.destination) {\n destination = params.destination;\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USING PROVIDED DESTINATION',\n {\n destination,\n },\n );\n } else {\n destination = await this.walletService.getUserAddressWithDefault();\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: USING USER WALLET ADDRESS',\n {\n destination,\n },\n );\n }\n\n // Step 4: Ensure client is ready\n this.deps.debugLogger.log('HyperLiquidProvider: ENSURING CLIENT READY');\n await this.ensureReady();\n const exchangeClient = this.clientService.getExchangeClient();\n this.deps.debugLogger.log('HyperLiquidProvider: CLIENT READY');\n\n // Step 5: Validate amount against account balance\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: CHECKING ACCOUNT BALANCE',\n );\n const accountState = await this.getAccountState();\n const availableBalance = parseFloat(accountState.availableBalance);\n this.deps.debugLogger.log('HyperLiquidProvider: ACCOUNT BALANCE', {\n availableBalance,\n totalBalance: accountState.totalBalance,\n marginUsed: accountState.marginUsed,\n unrealizedPnl: accountState.unrealizedPnl,\n });\n\n // This check is already done in validateWithdrawalParams, but TypeScript needs explicit check\n if (!params.amount) {\n this.deps.debugLogger.log('HyperLiquidProvider: MISSING AMOUNT', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n params,\n });\n throw new Error(PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED);\n }\n\n const withdrawAmount = parseFloat(params.amount);\n this.deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL AMOUNT', {\n requestedAmount: withdrawAmount,\n availableBalance,\n sufficientBalance: withdrawAmount <= availableBalance,\n });\n\n const balanceValidation = validateBalance(\n withdrawAmount,\n availableBalance,\n );\n if (!balanceValidation.isValid) {\n this.deps.debugLogger.log('HyperLiquidProvider: INSUFFICIENT BALANCE', {\n error: balanceValidation.error,\n requestedAmount: withdrawAmount,\n availableBalance,\n difference: withdrawAmount - availableBalance,\n });\n throw new Error(balanceValidation.error);\n }\n this.deps.debugLogger.log('✅ HyperLiquidProvider: BALANCE SUFFICIENT');\n\n // Step 6: Execute withdrawal via HyperLiquid SDK (API call)\n this.deps.debugLogger.log('HyperLiquidProvider: CALLING WITHDRAW3 API', {\n destination,\n amount: params.amount,\n endpoint: 'withdraw3',\n timestamp: new Date().toISOString(),\n });\n\n const result = await exchangeClient.withdraw3({\n destination,\n amount: params.amount,\n });\n\n this.deps.debugLogger.log('HyperLiquidProvider: WITHDRAW3 API RESPONSE', {\n status: result.status,\n response: result,\n timestamp: new Date().toISOString(),\n });\n\n if (result.status === 'ok') {\n this.deps.debugLogger.log(\n 'HyperLiquidProvider: WITHDRAWAL SUBMITTED SUCCESSFULLY',\n {\n destination,\n amount: params.amount,\n assetId: params.assetId,\n status: result.status,\n },\n );\n\n const now = Date.now();\n const withdrawalId = `hl_${uuidv4()}`;\n\n return {\n success: true,\n withdrawalId,\n estimatedArrivalTime: now + 5 * 60 * 1000, // HyperLiquid typically takes ~5 minutes\n // Don't set txHash if we don't have a real transaction hash\n // HyperLiquid's withdraw3 API doesn't return a transaction hash immediately\n };\n }\n\n const errorMessage = `Withdrawal failed: ${String(result.status)}`;\n this.deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL FAILED', {\n error: errorMessage,\n status: result.status,\n response: result,\n params,\n });\n return {\n success: false,\n error: errorMessage,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n this.deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL EXCEPTION', {\n error: errorMessage,\n errorType:\n error instanceof Error ? error.constructor.name : typeof error,\n stack: error instanceof Error ? error.stack : undefined,\n params,\n timestamp: new Date().toISOString(),\n });\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('withdraw', {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n }),\n );\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Transfer USDC collateral between DEXs (main ↔ HIP-3)\n *\n * Verified working on mainnet via Phantom wallet testing (10/15/2025).\n * See docs/perps/HIP-3-IMPLEMENTATION.md for complete transaction flow.\n *\n * @param params - Transfer parameters\n * @param params.sourceDex - Source DEX name ('' = main, 'xyz' = HIP-3)\n * @param params.destinationDex - Destination DEX name ('' = main, 'xyz' = HIP-3)\n * @param params.amount - USDC amount to transfer\n * @returns Transfer result with success status and transaction hash\n *\n * @example\n * // Transfer 10 USDC from main DEX to xyz HIP-3 DEX\n * await transferBetweenDexs({\n * sourceDex: '',\n * destinationDex: 'xyz',\n * amount: '10'\n * });\n */\n async transferBetweenDexs(\n params: TransferBetweenDexsParams,\n ): Promise<TransferBetweenDexsResult> {\n try {\n this.deps.debugLogger.log('HyperLiquidProvider: STARTING DEX TRANSFER', {\n params,\n timestamp: new Date().toISOString(),\n });\n\n // Validate parameters\n if (!params.amount || parseFloat(params.amount) <= 0) {\n throw new Error('Transfer amount must be greater than 0');\n }\n\n if (params.sourceDex === params.destinationDex) {\n throw new Error('Source and destination DEX must be different');\n }\n\n // Get user address\n const userAddress = await this.walletService.getUserAddressWithDefault();\n this.deps.debugLogger.log('HyperLiquidProvider: USER ADDRESS', {\n userAddress,\n });\n\n // Ensure client ready\n await this.ensureReady();\n const exchangeClient = this.clientService.getExchangeClient();\n\n // Execute transfer using SDK sendAsset()\n // Note: SDK docs say \"testnet-only\" but it works on mainnet (verified via Phantom)\n this.deps.debugLogger.log('HyperLiquidProvider: CALLING SEND_ASSET API', {\n sourceDex: params.sourceDex || '(main)',\n destinationDex: params.destinationDex || '(main)',\n amount: params.amount,\n });\n\n const result = await exchangeClient.sendAsset({\n destination: userAddress,\n sourceDex: params.sourceDex,\n destinationDex: params.destinationDex,\n token: await this.getUsdcTokenId(), // Query correct USDC token ID dynamically\n amount: params.amount,\n });\n\n this.deps.debugLogger.log('HyperLiquidProvider: SEND_ASSET RESPONSE', {\n status: result.status,\n timestamp: new Date().toISOString(),\n });\n\n if (result.status === 'ok') {\n this.deps.debugLogger.log(\n '✅ HyperLiquidProvider: TRANSFER SUCCESSFUL',\n );\n return {\n success: true,\n // Note: sendAsset doesn't return txHash in response\n // User can verify transfer in explorer by timestamp\n };\n }\n\n throw new Error(PERPS_ERROR_CODES.TRANSFER_FAILED);\n } catch (error) {\n this.deps.debugLogger.log('❌ HyperLiquidProvider: TRANSFER FAILED', {\n error: error instanceof Error ? error.message : String(error),\n params,\n });\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('transferBetweenDexs', { ...params }),\n );\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Subscribe to live price updates\n *\n * @param params\n */\n subscribeToPrices(params: SubscribePricesParams): () => void {\n // Handle async subscription service by immediately returning cleanup function\n // The subscription service will load correct funding rates before any callbacks\n let unsubscribe: (() => void) | undefined;\n let cancelled = false;\n\n this.subscriptionService\n .subscribeToPrices(params)\n .then((unsub) => {\n // If cleanup was called before subscription completed, immediately unsubscribe\n if (cancelled) {\n unsub();\n } else {\n unsubscribe = unsub;\n }\n })\n .catch((error) => {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('subscribeToPrices', {\n symbols: params.symbols,\n }),\n );\n return undefined;\n });\n\n return () => {\n cancelled = true;\n if (unsubscribe) {\n unsubscribe();\n }\n };\n }\n\n /**\n * Subscribe to live position updates\n *\n * @param params\n */\n subscribeToPositions(params: SubscribePositionsParams): () => void {\n return this.subscriptionService.subscribeToPositions(params);\n }\n\n /**\n * Subscribe to live order fill updates\n *\n * @param params\n */\n subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void {\n return this.subscriptionService.subscribeToOrderFills(params);\n }\n\n /**\n * Subscribe to live order updates\n *\n * @param params\n */\n subscribeToOrders(params: SubscribeOrdersParams): () => void {\n return this.subscriptionService.subscribeToOrders(params);\n }\n\n /**\n * Subscribe to live account updates\n *\n * @param params\n */\n subscribeToAccount(params: SubscribeAccountParams): () => void {\n return this.subscriptionService.subscribeToAccount(params);\n }\n\n /**\n * Subscribe to open interest cap updates\n * Zero additional overhead - data extracted from existing webData2 subscription\n *\n * @param params\n */\n subscribeToOICaps(params: SubscribeOICapsParams): () => void {\n return this.subscriptionService.subscribeToOICaps(params);\n }\n\n /**\n * Subscribe to full order book updates with multiple depth levels\n * Creates a dedicated L2Book subscription for real-time order book data\n *\n * @param params\n */\n subscribeToOrderBook(params: SubscribeOrderBookParams): () => void {\n return this.subscriptionService.subscribeToOrderBook(params);\n }\n\n /**\n * Subscribe to live candle updates\n *\n * @param params\n */\n subscribeToCandles(params: SubscribeCandlesParams): () => void {\n return this.clientService.subscribeToCandles(params);\n }\n\n /**\n * Configure live data settings\n *\n * @param config\n */\n setLiveDataConfig(config: Partial<LiveDataConfig>): void {\n this.deps.debugLogger.log('Live data config updated:', config);\n }\n\n /**\n * Toggle testnet mode\n */\n async toggleTestnet(): Promise<ToggleTestnetResult> {\n try {\n const newIsTestnet = !this.clientService.isTestnetMode();\n\n // Await pending initialization to prevent race condition where\n // the IIFE sets clientsInitialized = true after we reset it\n const pendingInit = this.initializationPromise;\n this.initializationPromise = null;\n\n if (pendingInit) {\n try {\n await pendingInit;\n } catch {\n // Ignore - we're switching networks anyway\n }\n }\n\n // Update all services\n this.clientService.setTestnetMode(newIsTestnet);\n this.walletService.setTestnetMode(newIsTestnet);\n\n // Reset initialization flag so clients will be recreated on next use\n this.clientsInitialized = false;\n\n return {\n success: true,\n isTestnet: newIsTestnet,\n };\n } catch (error) {\n return createErrorResult(error, {\n success: false,\n isTestnet: this.clientService.isTestnetMode(),\n });\n }\n }\n\n /**\n * Initialize provider (ensures clients are ready)\n */\n async initialize(): Promise<InitializeResult> {\n try {\n // Ensure clients are initialized (lazy initialization)\n await this.ensureClientsInitialized();\n return {\n success: true,\n chainId: getChainId(this.clientService.isTestnetMode()),\n };\n } catch (error) {\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Check if ready to trade\n */\n async isReadyToTrade(): Promise<ReadyToTradeResult> {\n try {\n const exchangeClient = this.clientService.getExchangeClient();\n const infoClient = this.clientService.getInfoClient();\n const walletConnected = Boolean(exchangeClient) && Boolean(infoClient);\n\n let accountConnected = false;\n try {\n await this.walletService.getCurrentAccountId();\n accountConnected = true;\n } catch (error) {\n this.deps.debugLogger.log('Account not connected:', error);\n accountConnected = false;\n }\n\n const ready = walletConnected && accountConnected;\n\n return {\n ready,\n walletConnected,\n networkSupported: true,\n };\n } catch (error) {\n return {\n ready: false,\n walletConnected: false,\n networkSupported: false,\n error:\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n }\n }\n\n /**\n * Calculate liquidation price using HyperLiquid's formula\n * Formula: liq_price = price - side * margin_available / position_size / (1 - l * side)\n * where l = 1 / MAINTENANCE_LEVERAGE = 1 / (2 * max_leverage)\n *\n * @param params\n */\n async calculateLiquidationPrice(\n params: LiquidationPriceParams,\n ): Promise<string> {\n const { entryPrice, leverage, direction, asset } = params;\n\n // Validate inputs\n if (\n !isFinite(entryPrice) ||\n !isFinite(leverage) ||\n entryPrice <= 0 ||\n leverage <= 0\n ) {\n return '0.00';\n }\n\n // Get asset's max leverage to calculate maintenance margin\n let maxLeverage = PERPS_CONSTANTS.DefaultMaxLeverage; // Default fallback\n if (asset) {\n try {\n maxLeverage = await this.getMaxLeverage(asset);\n } catch (error) {\n this.deps.debugLogger.log(\n 'Failed to get max leverage for asset, using default',\n {\n asset,\n error,\n },\n );\n // Use default if we can't fetch the asset's max leverage\n }\n }\n\n // Calculate maintenance leverage and margin according to HyperLiquid docs\n const maintenanceLeverage = 2 * maxLeverage;\n const maintenanceMarginRatio = 1 / maintenanceLeverage;\n const side = direction === 'long' ? 1 : -1;\n\n // For isolated margin, we use the standard formula\n // margin_available = initial_margin - maintenance_margin_required\n const initialMargin = 1 / leverage;\n const maintenanceMargin = 1 / maintenanceLeverage;\n\n // Check if position can be opened\n if (initialMargin < maintenanceMargin) {\n // Position cannot be opened - leverage exceeds maximum allowed (2 * maxLeverage)\n throw new Error(\n `Invalid leverage: ${leverage}x exceeds maximum allowed leverage of ${maintenanceLeverage}x`,\n );\n }\n\n try {\n // HyperLiquid liquidation formula\n // For isolated margin: margin_available = isolated_margin - maintenance_margin_required\n const marginAvailable = initialMargin - maintenanceMargin;\n\n // Simplified calculation when position size is 1 unit\n // liq_price = price - side * margin_available * price / (1 - maintenanceMarginRatio * side)\n const denominator = 1 - maintenanceMarginRatio * side;\n if (Math.abs(denominator) < 0.0001) {\n // Avoid division by very small numbers\n return String(entryPrice);\n }\n\n const liquidationPrice =\n entryPrice - (side * marginAvailable * entryPrice) / denominator;\n\n // Ensure liquidation price is non-negative\n return String(Math.max(0, liquidationPrice));\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('calculateLiquidationPrice', {\n asset: params.asset,\n entryPrice: params.entryPrice,\n leverage: params.leverage,\n direction: params.direction,\n }),\n );\n return '0.00';\n }\n }\n\n /**\n * Calculate maintenance margin for a specific asset\n * According to HyperLiquid docs: maintenance_margin = 1 / (2 * max_leverage)\n *\n * @param params\n */\n async calculateMaintenanceMargin(\n params: MaintenanceMarginParams,\n ): Promise<number> {\n const { asset } = params;\n\n // Get asset's max leverage\n const maxLeverage = await this.getMaxLeverage(asset);\n\n // Maintenance margin = 1 / (2 * max_leverage)\n // This varies from 1.25% (for 40x) to 16.7% (for 3x) depending on the asset\n return 1 / (2 * maxLeverage);\n }\n\n /**\n * Get maximum leverage allowed for an asset\n *\n * @param asset\n */\n async getMaxLeverage(asset: string): Promise<number> {\n try {\n // Check cache first\n const cached = this.maxLeverageCache.get(asset);\n const now = Date.now();\n\n if (\n cached &&\n now - cached.timestamp < PERFORMANCE_CONFIG.MaxLeverageCacheDurationMs\n ) {\n return cached.value;\n }\n\n // Read-only operation: only need client initialization, not full ensureReady()\n // (no DEX abstraction, referral, or builder fee needed for metadata)\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(asset);\n\n // Get asset info (uses cache to avoid redundant API calls)\n const meta = await this.getCachedMeta({ dexName });\n\n // Check if meta and universe exist and is valid\n // This should never happen since getCachedMeta validates, but defensive check\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n this.deps.logger.error(\n new Error(\n '[HyperLiquidProvider] Invalid meta response in getMaxLeverage',\n ),\n this.getErrorContext('getMaxLeverage', {\n asset,\n dexName: dexName || 'main',\n note: 'Meta or universe not available, using default max leverage',\n }),\n );\n return PERPS_CONSTANTS.DefaultMaxLeverage;\n }\n\n // asset.name format: \"BTC\" for main DEX, \"xyz:XYZ100\" for HIP-3\n const assetInfo = meta.universe.find((univ) => univ.name === asset);\n if (!assetInfo) {\n this.deps.debugLogger.log(\n `Asset ${asset} not found in universe, using default max leverage`,\n );\n return PERPS_CONSTANTS.DefaultMaxLeverage;\n }\n\n // Cache the result\n this.maxLeverageCache.set(asset, {\n value: assetInfo.maxLeverage,\n timestamp: now,\n });\n\n return assetInfo.maxLeverage;\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('getMaxLeverage', {\n asset,\n }),\n );\n return PERPS_CONSTANTS.DefaultMaxLeverage;\n }\n }\n\n /**\n * Calculate fees based on HyperLiquid's fee structure\n * Returns fee rate as decimal (e.g., 0.00045 for 0.045%)\n *\n * Uses the SDK's userFees API to get actual discounted rates when available,\n * falling back to base rates if the API is unavailable or user not connected.\n *\n * @param params\n */\n async calculateFees(\n params: FeeCalculationParams,\n ): Promise<FeeCalculationResult> {\n const { orderType, isMaker = false, amount, symbol } = params;\n\n // Start with base rates from config\n let feeRate =\n orderType === 'market' || !isMaker ? FEE_RATES.taker : FEE_RATES.maker;\n\n // Parse symbol to detect HIP-3 DEX (e.g., \"xyz:TSLA\" → dex=\"xyz\", parsedSymbol=\"TSLA\")\n const { dex, symbol: parsedSymbol } = parseAssetName(symbol);\n const isHip3Asset = dex !== null;\n\n // Calculate HIP-3 fee multiplier dynamically (handles Growth Mode)\n let hip3Multiplier = 1;\n if (isHip3Asset && dex && parsedSymbol) {\n hip3Multiplier = await this.calculateHip3FeeMultiplier({\n dexName: dex,\n assetSymbol: parsedSymbol,\n });\n const originalRate = feeRate;\n feeRate *= hip3Multiplier;\n\n this.deps.debugLogger.log('HIP-3 Dynamic Fee Multiplier Applied', {\n symbol,\n dex,\n parsedSymbol,\n originalBaseRate: originalRate,\n hip3BaseRate: feeRate,\n hip3Multiplier,\n });\n }\n\n this.deps.debugLogger.log('HyperLiquid Fee Calculation Started', {\n orderType,\n isMaker,\n amount,\n symbol,\n isHip3Asset,\n hip3Multiplier,\n baseFeeRate: feeRate,\n baseTakerRate: FEE_RATES.taker,\n baseMakerRate: FEE_RATES.maker,\n });\n\n // Try to get user-specific rates if wallet is connected\n try {\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n this.deps.debugLogger.log('User Address Retrieved', {\n userAddress,\n network: this.clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n });\n\n // Check cache first\n if (this.isFeeCacheValid(userAddress)) {\n const cached = this.userFeeCache.get(userAddress);\n if (cached) {\n // Market orders always use taker rate, limit orders check isMaker\n let userFeeRate =\n orderType === 'market' || !isMaker\n ? cached.perpsTakerRate\n : cached.perpsMakerRate;\n\n // Apply HIP-3 dynamic multiplier to user-specific rates (includes Growth Mode)\n if (isHip3Asset && hip3Multiplier > 0) {\n userFeeRate *= hip3Multiplier;\n }\n\n feeRate = userFeeRate;\n\n this.deps.debugLogger.log('📦 Using Cached Fee Rates', {\n cacheHit: true,\n perpsTakerRate: cached.perpsTakerRate,\n perpsMakerRate: cached.perpsMakerRate,\n spotTakerRate: cached.spotTakerRate,\n spotMakerRate: cached.spotMakerRate,\n selectedRate: feeRate,\n isHip3Asset,\n hip3Multiplier,\n cacheExpiry: new Date(cached.timestamp + cached.ttl).toISOString(),\n cacheAge: `${Math.round((Date.now() - cached.timestamp) / 1000)}s`,\n });\n }\n } else {\n this.deps.debugLogger.log(\n 'Fetching Fresh Fee Rates from HyperLiquid API',\n {\n cacheHit: false,\n userAddress,\n },\n );\n\n // Fetch fresh rates from SDK\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n const infoClient = this.clientService.getInfoClient();\n const userFees = await infoClient.userFees({\n user: userAddress,\n });\n\n this.deps.debugLogger.log('HyperLiquid userFees API Response', {\n userCrossRate: userFees.userCrossRate,\n userAddRate: userFees.userAddRate,\n activeReferralDiscount: userFees.activeReferralDiscount,\n activeStakingDiscount: userFees.activeStakingDiscount,\n });\n\n // Parse base user rates (these don't include discounts as expected)\n const baseUserTakerRate = parseFloat(userFees.userCrossRate);\n const baseUserMakerRate = parseFloat(userFees.userAddRate);\n const baseUserSpotTakerRate = parseFloat(userFees.userSpotCrossRate);\n const baseUserSpotMakerRate = parseFloat(userFees.userSpotAddRate);\n\n // Apply discounts manually since HyperLiquid API doesn't apply them\n const referralDiscount = parseFloat(\n userFees.activeReferralDiscount || '0',\n );\n const stakingDiscount = parseFloat(\n userFees.activeStakingDiscount?.discount || '0',\n );\n\n // Calculate total discount (referral + staking, but not compounding)\n const totalDiscount = Math.min(referralDiscount + stakingDiscount, 0.4); // Cap at 40%\n\n // Apply discount to rates\n const perpsTakerRate = baseUserTakerRate * (1 - totalDiscount);\n const perpsMakerRate = baseUserMakerRate * (1 - totalDiscount);\n const spotTakerRate = baseUserSpotTakerRate * (1 - totalDiscount);\n const spotMakerRate = baseUserSpotMakerRate * (1 - totalDiscount);\n\n this.deps.debugLogger.log('Fee Discount Calculation', {\n discounts: {\n referral: `${(referralDiscount * 100).toFixed(1)}%`,\n staking: `${(stakingDiscount * 100).toFixed(1)}%`,\n total: `${(totalDiscount * 100).toFixed(1)}%`,\n },\n rates: {\n before: {\n taker: `${(baseUserTakerRate * 100).toFixed(4)}%`,\n maker: `${(baseUserMakerRate * 100).toFixed(4)}%`,\n },\n after: {\n taker: `${(perpsTakerRate * 100).toFixed(4)}%`,\n maker: `${(perpsMakerRate * 100).toFixed(4)}%`,\n },\n },\n });\n\n // Validate all rates are valid numbers before caching\n if (\n isNaN(perpsTakerRate) ||\n isNaN(perpsMakerRate) ||\n isNaN(spotTakerRate) ||\n isNaN(spotMakerRate) ||\n perpsTakerRate < 0 ||\n perpsMakerRate < 0 ||\n spotTakerRate < 0 ||\n spotMakerRate < 0\n ) {\n this.deps.debugLogger.log('Fee Rate Validation Failed', {\n validation: {\n perpsTakerValid: !isNaN(perpsTakerRate) && perpsTakerRate >= 0,\n perpsMakerValid: !isNaN(perpsMakerRate) && perpsMakerRate >= 0,\n spotTakerValid: !isNaN(spotTakerRate) && spotTakerRate >= 0,\n spotMakerValid: !isNaN(spotMakerRate) && spotMakerRate >= 0,\n },\n rawValues: {\n perpsTakerRate,\n perpsMakerRate,\n spotTakerRate,\n spotMakerRate,\n },\n });\n throw new Error('Invalid fee rates received from API');\n }\n\n const rates = {\n perpsTakerRate,\n perpsMakerRate,\n spotTakerRate,\n spotMakerRate,\n timestamp: Date.now(),\n ttl: 5 * 60 * 1000, // 5 minutes\n };\n\n this.userFeeCache.set(userAddress, rates);\n // Market orders always use taker rate, limit orders check isMaker\n let userFeeRate =\n orderType === 'market' || !isMaker\n ? rates.perpsTakerRate\n : rates.perpsMakerRate;\n\n // Apply HIP-3 dynamic multiplier to API-fetched rates (includes Growth Mode)\n if (isHip3Asset && hip3Multiplier > 0) {\n userFeeRate *= hip3Multiplier;\n }\n\n feeRate = userFeeRate;\n\n this.deps.debugLogger.log('Fee Rates Validated and Cached', {\n selectedRate: feeRate,\n selectedRatePercentage: `${(feeRate * 100).toFixed(4)}%`,\n discountApplied: perpsTakerRate < FEE_RATES.taker,\n isHip3Asset,\n hip3Multiplier,\n cacheExpiry: new Date(rates.timestamp + rates.ttl).toISOString(),\n });\n }\n } catch (error) {\n // Silently fall back to base rates\n this.deps.debugLogger.log(\n 'Fee API Call Failed - Falling Back to Base Rates',\n {\n error: error instanceof Error ? error.message : String(error),\n errorType:\n error instanceof Error ? error.constructor.name : typeof error,\n fallbackTakerRate: FEE_RATES.taker,\n fallbackMakerRate: FEE_RATES.maker,\n userAddress: 'unknown',\n },\n );\n }\n\n const parsedAmount = amount ? parseFloat(amount) : 0;\n\n // Protocol base fee (HyperLiquid's fee)\n const protocolFeeRate = feeRate;\n const protocolFeeAmount =\n amount !== undefined\n ? isNaN(parsedAmount)\n ? 0\n : parsedAmount * protocolFeeRate\n : undefined;\n\n // MetaMask builder fee (0.1% = 0.001) with optional reward discount\n let metamaskFeeRate = BUILDER_FEE_CONFIG.MaxFeeDecimal;\n\n // Apply MetaMask reward discount if active\n if (this.userFeeDiscountBips !== undefined) {\n const discount = this.userFeeDiscountBips / BASIS_POINTS_DIVISOR; // Convert basis points to decimal\n metamaskFeeRate = BUILDER_FEE_CONFIG.MaxFeeDecimal * (1 - discount);\n\n this.deps.debugLogger.log('HyperLiquid: Applied MetaMask fee discount', {\n originalRate: BUILDER_FEE_CONFIG.MaxFeeDecimal,\n discountBips: this.userFeeDiscountBips,\n discountPercentage: this.userFeeDiscountBips / 100,\n adjustedRate: metamaskFeeRate,\n discountAmount: BUILDER_FEE_CONFIG.MaxFeeDecimal * discount,\n });\n }\n\n const validAmountForMetamaskFee = isNaN(parsedAmount)\n ? 0\n : parsedAmount * metamaskFeeRate;\n const metamaskFeeAmount =\n amount === undefined ? undefined : validAmountForMetamaskFee;\n\n // Total fees\n const totalFeeRate = protocolFeeRate + metamaskFeeRate;\n const validAmountForTotalFee = isNaN(parsedAmount)\n ? 0\n : parsedAmount * totalFeeRate;\n const totalFeeAmount =\n amount === undefined ? undefined : validAmountForTotalFee;\n\n const result = {\n // Total fees\n feeRate: totalFeeRate,\n feeAmount: totalFeeAmount,\n\n // Protocol fees\n protocolFeeRate,\n protocolFeeAmount,\n\n // MetaMask fees\n metamaskFeeRate,\n metamaskFeeAmount,\n };\n\n this.deps.debugLogger.log('Final Fee Calculation Result', {\n orderType,\n amount,\n fees: {\n protocolRate: `${(protocolFeeRate * 100).toFixed(4)}%`,\n metamaskRate: `${(metamaskFeeRate * 100).toFixed(4)}%`,\n totalRate: `${(totalFeeRate * 100).toFixed(4)}%`,\n totalAmount: totalFeeAmount,\n },\n usingFallbackRates:\n protocolFeeRate === FEE_RATES.taker ||\n protocolFeeRate === FEE_RATES.maker,\n });\n\n return result;\n }\n\n /**\n * Check if the fee cache is valid for a user\n *\n * @param userAddress\n * @private\n */\n private isFeeCacheValid(userAddress: string): boolean {\n const cached = this.userFeeCache.get(userAddress);\n if (!cached) {\n return false;\n }\n return Date.now() - cached.timestamp < cached.ttl;\n }\n\n /**\n * Clear fee cache for a specific user or all users\n *\n * @param userAddress - Optional address to clear cache for\n */\n public clearFeeCache(userAddress?: string): void {\n if (userAddress) {\n this.userFeeCache.delete(userAddress);\n this.deps.debugLogger.log('Cleared fee cache for user', { userAddress });\n } else {\n this.userFeeCache.clear();\n this.deps.debugLogger.log('Cleared all fee cache');\n }\n }\n\n /**\n * Disconnect provider\n */\n async disconnect(): Promise<DisconnectResult> {\n try {\n this.deps.debugLogger.log('HyperLiquid: Disconnecting provider', {\n isTestnet: this.clientService.isTestnetMode(),\n timestamp: new Date().toISOString(),\n });\n\n // Clear subscriptions through subscription service\n this.subscriptionService.clearAll();\n\n // Clear fee cache\n this.clearFeeCache();\n\n // Clear session caches (ensures fresh state on reconnect/account switch)\n this.referralCheckCache.clear();\n this.builderFeeCheckCache.clear();\n this.cachedMetaByDex.clear();\n this.perpDexsCache = { data: null, timestamp: 0 };\n\n // Await pending initialization before clearing to prevent the IIFE from\n // setting clientsInitialized = true after disconnect completes\n const pendingInit = this.initializationPromise;\n const pendingReady = this.ensureReadyPromise;\n\n // Clear references first to prevent new callers from reusing\n this.initializationPromise = null;\n this.ensureReadyPromise = null;\n this.pendingBuilderFeeApprovals.clear();\n\n // Wait for pending operations to complete (ignore errors)\n if (pendingInit) {\n try {\n await pendingInit;\n } catch {\n // Ignore - we're disconnecting anyway\n }\n }\n if (pendingReady) {\n try {\n await pendingReady;\n } catch {\n // Ignore - we're disconnecting anyway\n }\n }\n\n // Reset client initialization flag so wallet adapter will be recreated with new account\n // This fixes account synchronization issue where old account's address persists in wallet adapter\n this.clientsInitialized = false;\n\n // Disconnect client service\n await this.clientService.disconnect();\n\n this.deps.debugLogger.log('HyperLiquid: Provider fully disconnected', {\n timestamp: new Date().toISOString(),\n });\n\n return { success: true };\n } catch (error) {\n return createErrorResult(error, { success: false });\n }\n }\n\n /**\n * Lightweight WebSocket health check using SDK's built-in ready() method\n * Checks if WebSocket connection is open without making expensive API calls\n *\n * @param timeoutMs - Optional timeout in milliseconds (defaults to WEBSOCKET_PING_TIMEOUT_MS)\n * @throws {Error} If WebSocket connection times out or fails\n */\n async ping(timeoutMs?: number): Promise<void> {\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const subscriptionClient = this.clientService.getSubscriptionClient();\n if (!subscriptionClient) {\n throw new Error('Subscription client not initialized');\n }\n\n const timeout = timeoutMs ?? PERPS_CONSTANTS.WebsocketPingTimeoutMs;\n\n this.deps.debugLogger.log(\n `HyperLiquid: WebSocket health check ping starting (timeout: ${timeout}ms)`,\n );\n\n const controller = new AbortController();\n let didTimeout = false;\n\n const timeoutId = setTimeout(() => {\n didTimeout = true;\n controller.abort();\n }, timeout);\n\n try {\n // Use SDK's built-in ready() method which checks socket.readyState === OPEN\n // This is much more efficient than creating a subscription just for health check\n await subscriptionClient.config_.transport.ready(controller.signal);\n\n this.deps.debugLogger.log(\n 'HyperLiquid: WebSocket health check ping succeeded',\n );\n } catch (error) {\n // Check if we timed out first\n if (didTimeout) {\n this.deps.debugLogger.log(\n `HyperLiquid: WebSocket health check ping timed out after ${timeout}ms`,\n );\n throw new Error(PERPS_ERROR_CODES.CONNECTION_TIMEOUT);\n }\n\n // Otherwise throw the actual error\n this.deps.debugLogger.log(\n 'HyperLiquid: WebSocket health check ping failed',\n error,\n );\n throw ensureError(error);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Get the current WebSocket connection state from the client service.\n * Used by the UI to monitor connection health and show notifications.\n *\n * @returns The current WebSocket connection state\n */\n getWebSocketConnectionState(): WebSocketConnectionState {\n return this.clientService.getConnectionState();\n }\n\n /**\n * Subscribe to WebSocket connection state changes.\n * The listener will be called immediately with the current state and whenever the state changes.\n *\n * @param listener - Callback function that receives the new connection state and reconnection attempt\n * @returns Unsubscribe function to remove the listener\n */\n subscribeToConnectionState(\n listener: (\n state: WebSocketConnectionState,\n reconnectionAttempt: number,\n ) => void,\n ): () => void {\n return this.clientService.subscribeToConnectionState(listener);\n }\n\n /**\n * Manually trigger a WebSocket reconnection attempt.\n * Used by the UI retry button when connection is lost.\n */\n async reconnect(): Promise<void> {\n return this.clientService.reconnect();\n }\n\n /**\n * Get list of available HIP-3 builder-deployed DEXs\n *\n * @param _params - Optional parameters (reserved for future filters/pagination)\n * @returns Array of DEX names (empty string '' represents main DEX)\n */\n async getAvailableDexs(_params?: GetAvailableDexsParams): Promise<string[]> {\n try {\n // Read-only operation: only need client initialization\n await this.ensureClientsInitialized();\n this.clientService.ensureInitialized();\n\n const infoClient = this.clientService.getInfoClient();\n const dexs = await infoClient.perpDexs();\n\n // Map DEX objects to names: null -> '' (main DEX), object -> object.name\n return dexs.map((dex) => (dex === null ? '' : dex.name));\n } catch (error) {\n this.deps.logger.error(ensureError(error), {\n context: {\n name: 'HyperLiquidProvider.getAvailableDexs',\n data: { action: 'fetch_available_dexs' },\n },\n });\n throw error;\n }\n }\n\n /**\n * Get block explorer URL for an address or just the base URL\n *\n * @param address - Optional address to append to the base URL\n * @returns Block explorer URL\n */\n getBlockExplorerUrl(address?: string): string {\n const network = this.clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const baseUrl =\n network === 'testnet'\n ? 'https://app.hyperliquid-testnet.xyz'\n : 'https://app.hyperliquid.xyz';\n\n if (address) {\n return `${baseUrl}/explorer/address/${address}`;\n }\n\n return `${baseUrl}/explorer`;\n }\n\n private getBuilderAddress(isTestnet: boolean) {\n return isTestnet\n ? BUILDER_FEE_CONFIG.TestnetBuilder\n : BUILDER_FEE_CONFIG.MainnetBuilder;\n }\n\n private getReferralCode(isTestnet: boolean): string {\n return isTestnet\n ? REFERRAL_CONFIG.TestnetCode\n : REFERRAL_CONFIG.MainnetCode;\n }\n\n /**\n * Ensure user has a MetaMask referral code set\n * Called once during initialization (ensureReady) to set up referral for the session\n * Uses session cache to avoid redundant API calls until disconnect/reconnect\n *\n * Cache semantics: Only caches successful referral sets (never caches \"not set\" state)\n * This allows detection of external referral changes between retries while avoiding redundant checks\n *\n * Note: This is network-specific - testnet and mainnet have separate referral states\n * Note: Non-blocking - failures are logged to Sentry but don't prevent trading\n * Note: Will automatically retry on next session if failed (cache cleared on disconnect)\n */\n private async ensureReferralSet(): Promise<void> {\n try {\n const isTestnet = this.clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const expectedReferralCode = this.getReferralCode(isTestnet);\n const referrerAddress = this.getBuilderAddress(isTestnet);\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n if (userAddress.toLowerCase() === referrerAddress.toLowerCase()) {\n this.deps.debugLogger.log(\n '[ensureReferralSet] User is builder, skipping',\n {\n network,\n },\n );\n return;\n }\n\n // Check session cache first to avoid redundant API calls\n // Cache only stores true (referral confirmed), never false\n const cacheKey = this.getCacheKey(network, userAddress);\n const cached = this.referralCheckCache.get(cacheKey);\n\n if (cached === true) {\n this.deps.debugLogger.log('[ensureReferralSet] Using session cache', {\n network,\n });\n return; // Already has referral set this session, skip\n }\n\n const isReady = await this.isReferralCodeReady();\n if (!isReady) {\n this.deps.debugLogger.log(\n '[ensureReferralSet] Builder referral not ready yet, skipping',\n { network },\n );\n return;\n }\n\n // Check if user already has a referral set on this network\n const hasReferral = await this.checkReferralSet();\n\n if (!hasReferral) {\n this.deps.debugLogger.log(\n '[ensureReferralSet] No referral set - setting MetaMask',\n {\n network,\n referralCode: expectedReferralCode,\n },\n );\n const result = await this.setReferralCode();\n if (result) {\n this.deps.debugLogger.log(\n '[ensureReferralSet] Referral code set successfully',\n {\n network,\n referralCode: expectedReferralCode,\n },\n );\n // Update cache to reflect successful set\n this.referralCheckCache.set(cacheKey, true);\n } else {\n this.deps.debugLogger.log(\n '[ensureReferralSet] Failed to set referral code (will retry next session)',\n { network },\n );\n }\n } else {\n // User already has referral set (possibly from external setup or previous session)\n // Cache success to avoid redundant checks\n this.referralCheckCache.set(cacheKey, true);\n\n this.deps.debugLogger.log(\n '[ensureReferralSet] User already has referral set',\n {\n network,\n },\n );\n }\n } catch (error) {\n // Non-blocking: Log to Sentry but don't throw\n // Will retry automatically on next session (cache cleared on disconnect)\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('ensureReferralSet', {\n note: 'Referral setup failed (non-blocking, will retry next session)',\n }),\n );\n }\n }\n\n /**\n * Check if the referral code is ready to be used\n *\n * @returns Promise resolving to true if referral code is ready\n */\n private async isReferralCodeReady(): Promise<boolean> {\n try {\n const infoClient = this.clientService.getInfoClient();\n const isTestnet = this.clientService.isTestnetMode();\n const code = this.getReferralCode(isTestnet);\n const referrerAddr = this.getBuilderAddress(isTestnet);\n\n const referral = await infoClient.referral({ user: referrerAddr });\n\n const stage = referral.referrerState?.stage;\n\n if (stage === 'ready') {\n const onFile = referral.referrerState?.data?.code || '';\n if (onFile.toUpperCase() !== code.toUpperCase()) {\n throw new Error(\n `Ready for referrals but there is a config code mismatch ${onFile} vs ${code}`,\n );\n }\n return true;\n }\n\n // Not ready yet - log as debugLogger since this is expected during setup phase\n this.deps.debugLogger.log(\n '[isReferralCodeReady] Referral code not ready',\n {\n stage,\n code,\n referrerAddr,\n },\n );\n return false;\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('isReferralCodeReady', {\n code: this.getReferralCode(this.clientService.isTestnetMode()),\n referrerAddress: this.getBuilderAddress(\n this.clientService.isTestnetMode(),\n ),\n }),\n );\n return false;\n }\n }\n\n /**\n * Check if user has a referral code set with HyperLiquid\n *\n * @returns Promise resolving to true if referral is set, false otherwise\n */\n private async checkReferralSet(): Promise<boolean> {\n try {\n const infoClient = this.clientService.getInfoClient();\n const userAddress = await this.walletService.getUserAddressWithDefault();\n\n // Call HyperLiquid API to check if user has a referral set\n const referralData = await infoClient.referral({\n user: userAddress,\n });\n\n this.deps.debugLogger.log('Referral check result:', {\n userAddress,\n referralData,\n });\n\n return Boolean(referralData?.referredBy?.code);\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('checkReferralSet', {\n note: 'Error checking referral status, will retry',\n }),\n );\n // do not throw here, return false as we can try to set it again\n return false;\n }\n }\n\n /**\n * Set MetaMask as the user's referrer on HyperLiquid\n */\n private async setReferralCode(): Promise<boolean> {\n try {\n const exchangeClient = this.clientService.getExchangeClient();\n const referralCode = this.getReferralCode(\n this.clientService.isTestnetMode(),\n );\n\n this.deps.debugLogger.log('[setReferralCode] Setting referral code', {\n code: referralCode,\n network: this.clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n });\n\n // set the referral code\n const result = await exchangeClient.setReferrer({\n code: referralCode,\n });\n\n this.deps.debugLogger.log(\n '[setReferralCode] Referral code set result',\n result,\n );\n\n return result?.status === 'ok';\n } catch (error) {\n this.deps.logger.error(\n ensureError(error),\n this.getErrorContext('setReferralCode', {\n code: this.getReferralCode(this.clientService.isTestnetMode()),\n }),\n );\n // Rethrow to be caught by retry logic in ensureReferralSet\n throw error;\n }\n }\n}\n"]}
|