@metamask-previews/perps-controller 3.0.0-preview-e61cfa5 → 3.1.0-preview-548bdd1d9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/PerpsController-method-action-types.cjs.map +1 -1
  3. package/dist/PerpsController-method-action-types.d.cts +8 -0
  4. package/dist/PerpsController-method-action-types.d.cts.map +1 -1
  5. package/dist/PerpsController-method-action-types.d.mts +8 -0
  6. package/dist/PerpsController-method-action-types.d.mts.map +1 -1
  7. package/dist/PerpsController-method-action-types.mjs.map +1 -1
  8. package/dist/PerpsController.cjs +117 -29
  9. package/dist/PerpsController.cjs.map +1 -1
  10. package/dist/PerpsController.d.cts +14 -2
  11. package/dist/PerpsController.d.cts.map +1 -1
  12. package/dist/PerpsController.d.mts +14 -2
  13. package/dist/PerpsController.d.mts.map +1 -1
  14. package/dist/PerpsController.mjs +118 -30
  15. package/dist/PerpsController.mjs.map +1 -1
  16. package/dist/constants/eventNames.cjs +1 -0
  17. package/dist/constants/eventNames.cjs.map +1 -1
  18. package/dist/constants/eventNames.d.cts +1 -0
  19. package/dist/constants/eventNames.d.cts.map +1 -1
  20. package/dist/constants/eventNames.d.mts +1 -0
  21. package/dist/constants/eventNames.d.mts.map +1 -1
  22. package/dist/constants/eventNames.mjs +1 -0
  23. package/dist/constants/eventNames.mjs.map +1 -1
  24. package/dist/constants/perpsConfig.cjs +46 -1
  25. package/dist/constants/perpsConfig.cjs.map +1 -1
  26. package/dist/constants/perpsConfig.d.cts +35 -0
  27. package/dist/constants/perpsConfig.d.cts.map +1 -1
  28. package/dist/constants/perpsConfig.d.mts +35 -0
  29. package/dist/constants/perpsConfig.d.mts.map +1 -1
  30. package/dist/constants/perpsConfig.mjs +43 -0
  31. package/dist/constants/perpsConfig.mjs.map +1 -1
  32. package/dist/constants/transactionsHistoryConfig.cjs +23 -4
  33. package/dist/constants/transactionsHistoryConfig.cjs.map +1 -1
  34. package/dist/constants/transactionsHistoryConfig.d.cts +23 -4
  35. package/dist/constants/transactionsHistoryConfig.d.cts.map +1 -1
  36. package/dist/constants/transactionsHistoryConfig.d.mts +23 -4
  37. package/dist/constants/transactionsHistoryConfig.d.mts.map +1 -1
  38. package/dist/constants/transactionsHistoryConfig.mjs +23 -4
  39. package/dist/constants/transactionsHistoryConfig.mjs.map +1 -1
  40. package/dist/index.cjs +14 -3
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +3 -1
  43. package/dist/index.d.cts.map +1 -1
  44. package/dist/index.d.mts +3 -1
  45. package/dist/index.d.mts.map +1 -1
  46. package/dist/index.mjs +2 -1
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/providers/HyperLiquidProvider.cjs +83 -27
  49. package/dist/providers/HyperLiquidProvider.cjs.map +1 -1
  50. package/dist/providers/HyperLiquidProvider.d.cts.map +1 -1
  51. package/dist/providers/HyperLiquidProvider.d.mts.map +1 -1
  52. package/dist/providers/HyperLiquidProvider.mjs +83 -27
  53. package/dist/providers/HyperLiquidProvider.mjs.map +1 -1
  54. package/dist/services/HyperLiquidSubscriptionService.cjs +6 -0
  55. package/dist/services/HyperLiquidSubscriptionService.cjs.map +1 -1
  56. package/dist/services/HyperLiquidSubscriptionService.d.cts.map +1 -1
  57. package/dist/services/HyperLiquidSubscriptionService.d.mts.map +1 -1
  58. package/dist/services/HyperLiquidSubscriptionService.mjs +6 -0
  59. package/dist/services/HyperLiquidSubscriptionService.mjs.map +1 -1
  60. package/dist/types/index.cjs.map +1 -1
  61. package/dist/types/index.d.cts +6 -0
  62. package/dist/types/index.d.cts.map +1 -1
  63. package/dist/types/index.d.mts +6 -0
  64. package/dist/types/index.d.mts.map +1 -1
  65. package/dist/types/index.mjs.map +1 -1
  66. package/dist/utils/index.cjs +2 -0
  67. package/dist/utils/index.cjs.map +1 -1
  68. package/dist/utils/index.d.cts +2 -0
  69. package/dist/utils/index.d.cts.map +1 -1
  70. package/dist/utils/index.d.mts +2 -0
  71. package/dist/utils/index.d.mts.map +1 -1
  72. package/dist/utils/index.mjs +2 -0
  73. package/dist/utils/index.mjs.map +1 -1
  74. package/dist/utils/perpsDiskPersistence.cjs +252 -0
  75. package/dist/utils/perpsDiskPersistence.cjs.map +1 -0
  76. package/dist/utils/perpsDiskPersistence.d.cts +108 -0
  77. package/dist/utils/perpsDiskPersistence.d.cts.map +1 -0
  78. package/dist/utils/perpsDiskPersistence.d.mts +108 -0
  79. package/dist/utils/perpsDiskPersistence.d.mts.map +1 -0
  80. package/dist/utils/perpsDiskPersistence.mjs +244 -0
  81. package/dist/utils/perpsDiskPersistence.mjs.map +1 -0
  82. package/dist/utils/perpsFormatters.cjs +498 -0
  83. package/dist/utils/perpsFormatters.cjs.map +1 -0
  84. package/dist/utils/perpsFormatters.d.cts +202 -0
  85. package/dist/utils/perpsFormatters.d.cts.map +1 -0
  86. package/dist/utils/perpsFormatters.d.mts +202 -0
  87. package/dist/utils/perpsFormatters.d.mts.map +1 -0
  88. package/dist/utils/perpsFormatters.mjs +489 -0
  89. package/dist/utils/perpsFormatters.mjs.map +1 -0
  90. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"HyperLiquidProvider.mjs","sourceRoot":"","sources":["../../src/providers/HyperLiquidProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAiB,WAAW,EAAE,wBAAwB;AAE7D,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAGpC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,UAAU,EACV,uBAAuB,EACvB,eAAe,EACf,kBAAkB,EAClB,8BAA8B,EAC9B,mBAAmB,EACnB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,WAAW,EACZ,2CAAuC;AACxC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,YAAY,EACZ,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sourcesContent":["import { CaipAccountId, hasProperty } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport type { CandlePeriod } from '../constants/chartConfig';\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 MAINNET_HIP3_CONFIG,\n REFERRAL_CONFIG,\n SPOT_ASSET_ID_OFFSET,\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} from '../constants/perpsConfig';\nimport { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes';\nimport {\n HyperLiquidClientService,\n WebSocketConnectionState,\n} from '../services/HyperLiquidClientService';\nimport { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService';\nimport { HyperLiquidWalletService } from '../services/HyperLiquidWalletService';\nimport {\n TradingReadinessCache,\n PerpsSigningCache,\n} from '../services/TradingReadinessCache';\nimport type {\n AccountState,\n AssetRoute,\n BatchCancelOrdersParams,\n CancelOrderParams,\n CancelOrderResult,\n CancelOrdersResult,\n CandleData,\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 GetOrFetchFillsParams,\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 ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n TransferBetweenDexsParams,\n TransferBetweenDexsResult,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n RawLedgerUpdate,\n} from '../types';\nimport type {\n SDKOrderParams,\n MetaResponse,\n PerpsAssetCtx,\n FrontendOrder,\n SpotMetaResponse,\n} from '../types/hyperliquid-types';\nimport type { PerpsControllerMessengerBase } from '../types/messenger';\nimport type { ExtendedAssetMeta, ExtendedPerpDex } from '../types/perps-types';\nimport { aggregateAccountStates } from '../utils/accountUtils';\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 {\n createStandaloneInfoClient,\n queryStandaloneClearinghouseStates,\n queryStandaloneOpenOrders,\n} from '../utils/standaloneInfoClient';\n// getStreamManagerInstance removed: use this.#deps.streamManager instead\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 current status.\n * @returns The result of the operation.\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 DexFetchFailureStep = 'metaAndAssetCtxs' | 'allMids';\n\ntype DexFetchResult = {\n dex: string | null;\n meta: MetaResponse | null;\n assetCtxs: PerpsAssetCtx[];\n allMids: Record<string, string>;\n success: boolean;\n failedStep?: DexFetchFailureStep;\n errorMessage?: string;\n};\n\ntype DexQueryResult<TResult> = {\n dex: string | null;\n data: TResult;\n};\n\ntype DexQueryResponse<TResult> = {\n results: DexQueryResult<TResult>[];\n failedDexs: { dex: string | null; error: Error }[];\n};\n\ntype CachedMarketDataSnapshot = {\n data: PerpsMarketData[];\n timestamp: number;\n contributingDexs: string[];\n failedDexs: string[];\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\ntype GetOrFetchPriceParams = {\n symbol: string;\n dexName: string | null;\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 readonly #deps: PerpsPlatformDependencies;\n\n // Service instances\n readonly #clientService: HyperLiquidClientService;\n\n readonly #walletService: HyperLiquidWalletService;\n\n readonly #subscriptionService: HyperLiquidSubscriptionService;\n\n // Asset mapping\n readonly #symbolToAssetId = new Map<string, number>();\n\n // Cache for user fee rates to avoid excessive API calls\n 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 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 readonly #cachedMetaByDex = new Map<string, MetaResponse>();\n\n // Last known-good market list for stale fallback when every enabled DEX fails in one fetch window.\n #cachedMarketDataWithPrices: CachedMarketDataSnapshot | null = null;\n\n // Session cache for spot metadata (contains USDC/USDH token info for HIP-3 collateral checks)\n // Pre-fetched in ensureReadyForTrading() to avoid API failures during order placement\n #cachedSpotMeta: SpotMetaResponse | null = null;\n\n // Cache for perpDexs data (deployerFeeScale for dynamic fee calculation)\n // TTL-based cache - fee scales rarely change\n #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 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 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 #ensureReadyPromise: Promise<void> | null = null;\n\n readonly #pendingBuilderFeeApprovals = new Map<string, Promise<void>>();\n\n // Pre-compiled patterns for fast filtering\n readonly #compiledAllowlistPatterns: CompiledMarketPattern[] = [];\n\n readonly #compiledBlocklistPatterns: CompiledMarketPattern[] = [];\n\n // Fee discount context for MetaMask reward discounts (in basis points)\n #userFeeDiscountBips?: number;\n\n // Feature flag configuration for HIP-3 market filtering\n readonly #hip3Enabled: boolean;\n\n readonly #allowlistMarkets: string[];\n\n readonly #blocklistMarkets: string[];\n\n #useDexAbstraction: boolean;\n\n // Cache for validated DEXs to avoid redundant perpDexs() API calls\n #cachedValidatedDexs: (string | null)[] | null = null;\n\n #cachedAllPerpDexs: ({ name: string } | null)[] | null = null;\n\n // True once DEX discovery has succeeded with real data (not a fallback).\n // When false, #ensureReadyPromise is reset after each init so the next\n // caller retries DEX discovery instead of reusing a degraded mapping.\n #dexDiscoveryComplete = false;\n\n // Pending promise to deduplicate concurrent getValidatedDexs() calls\n #pendingValidatedDexsPromise: Promise<(string | null)[]> | null = null;\n\n // Cache for USDC token ID from spot metadata\n #cachedUsdcTokenId?: string;\n\n // Error mappings from HyperLiquid API errors to standardized PERPS_ERROR_CODES\n 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 #clientsInitialized = false;\n\n // Promise-based lock to prevent race conditions in concurrent initialization\n #initializationPromise: Promise<void> | null = null;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n readonly #builderAddressTestnet?: string;\n\n readonly #builderAddressMainnet?: string;\n\n constructor(options: {\n isTestnet?: boolean;\n hip3Enabled?: boolean;\n allowlistMarkets?: string[];\n blocklistMarkets?: string[];\n useDexAbstraction?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger: PerpsControllerMessengerBase;\n initialAssetMapping?: [string, number][];\n builderAddressTestnet?: string;\n builderAddressMainnet?: string;\n }) {\n this.#deps = options.platformDependencies;\n this.#messenger = options.messenger;\n this.#builderAddressTestnet = options.builderAddressTestnet;\n this.#builderAddressMainnet = options.builderAddressMainnet;\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, {\n isTestnet,\n });\n this.#walletService = new HyperLiquidWalletService(\n this.#deps,\n this.#messenger,\n {\n isTestnet,\n },\n );\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 (invalid patterns are skipped)\n this.#compiledAllowlistPatterns = this.#compilePatternsSafely(\n this.#allowlistMarkets,\n 'allowlist',\n );\n this.#compiledBlocklistPatterns = this.#compilePatternsSafely(\n this.#blocklistMarkets,\n 'blocklist',\n );\n\n // Populate initial asset mapping if provided (used for DI in tests)\n if (options.initialAssetMapping) {\n for (const [symbol, assetId] of options.initialAssetMapping) {\n this.#symbolToAssetId.set(symbol, assetId);\n }\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 * Compile market patterns safely, skipping any that fail validation.\n * Prevents a single bad pattern from crashing the entire constructor.\n *\n * @param patterns - The array of patterns to validate.\n * @param listName - The name of the list for logging context.\n * @returns The result of the operation.\n */\n #compilePatternsSafely(\n patterns: string[],\n listName: string,\n ): CompiledMarketPattern[] {\n const compiled: CompiledMarketPattern[] = [];\n for (const pattern of patterns) {\n try {\n compiled.push({ pattern, matcher: compileMarketPattern(pattern) });\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, `HyperLiquidProvider.compilePatternsSafely`),\n this.#getErrorContext('compilePatternsSafely', { listName, pattern }),\n );\n }\n }\n return compiled;\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 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 (): Promise<void> => {\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 this.#deps.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 * IMPORTANT: Uses global singleton cache to prevent repeated signing requests\n * across provider reconnections (critical for hardware wallets).\n *\n * @private\n */\n async #ensureDexAbstractionEnabled(): Promise<void> {\n if (!this.#useDexAbstraction) {\n return; // Feature disabled\n }\n\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n\n // Check global cache first to avoid repeated signing requests\n // This is CRITICAL for hardware wallets to prevent QR popup spam\n const cachedStatus = TradingReadinessCache.get(network, userAddress);\n if (cachedStatus?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction already attempted (from global cache)',\n {\n user: userAddress,\n network,\n enabled: cachedStatus.enabled,\n note: 'Skipping to prevent repeated signing requests',\n },\n );\n return;\n }\n\n // Check if another provider instance is currently attempting this operation\n // This prevents concurrent signing attempts across providers during reconnection\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'dexAbstraction',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction in-flight, waiting...',\n { network, userAddress },\n );\n await inFlightPromise;\n return; // After waiting, the cache should be set by the other provider\n }\n\n // Set in-flight lock to prevent concurrent attempts\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'dexAbstraction',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock (another provider might have finished)\n const recheckCache = TradingReadinessCache.get(network, userAddress);\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction completed by another provider',\n { network, userAddress },\n );\n completeInFlight();\n return;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n\n // Check if already enabled on-chain (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 on-chain',\n { user: userAddress, network },\n );\n // Cache the enabled status to skip future checks\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n completeInFlight();\n return;\n }\n\n // Enable DEX abstraction (one-time, irreversible, requires signature)\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Enabling DEX abstraction (requires signature)',\n {\n user: userAddress,\n network,\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\n // Cache success to prevent re-attempts on reconnection\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureDexAbstractionEnabled] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache the attempt (even on failure) to prevent repeated signing requests\n // This is CRITICAL for hardware wallets - if user rejects, don't ask again\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction failed, cached to prevent retries',\n {\n user: userAddress,\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureDexAbstractionEnabled',\n ).message,\n },\n );\n\n completeInFlight();\n\n // Don't blindly disable the flag on any error\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureDexAbstractionEnabled'),\n this.#getErrorContext('ensureDexAbstractionEnabled', {\n note: 'Could not enable DEX abstraction (may already be enabled, user rejected, or network error)',\n }),\n );\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 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 (): Promise<void> => {\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, or retry if DEX discovery previously failed\n if (this.#symbolToAssetId.size === 0 || !this.#dexDiscoveryComplete) {\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 // NOTE: Signing operations (DEX abstraction, builder fee, referral) are now DEFERRED\n // They are called on-demand in ensureReadyForTrading() when user attempts to trade\n // This prevents QR popups when just viewing the Perps section (critical for hardware wallets)\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 // or when DEX discovery was degraded so the next caller retries.\n await this.#ensureReadyPromise;\n if (!this.#dexDiscoveryComplete) {\n // DEX discovery failed transiently — reset so next call retries.\n // Trading still works (main DEX mapping is populated), but HIP-3 markets\n // will be re-discovered on the next #ensureReady() call.\n this.#ensureReadyPromise = null;\n }\n this.#deps.debugLogger.log('[ensureReady] Initialization complete');\n }\n\n /**\n * Ensure provider is ready for TRADING operations (signing required)\n *\n * This method performs additional setup that requires user signatures:\n * - DEX abstraction enablement (for HIP-3 auto-transfers)\n * - Builder fee approval (required for orders)\n * - Referral code setup (attribution)\n *\n * These operations are DEFERRED from ensureReady() to avoid QR popup spam\n * when users are just viewing the Perps section (critical for hardware wallets).\n *\n * Call this method before any trading operation (placeOrder, cancelOrder, etc.)\n */\n #tradingSetupPromise: Promise<void> | null = null;\n\n #tradingSetupComplete = false;\n\n async #ensureReadyForTrading(): Promise<void> {\n // First ensure basic initialization is complete\n await this.#ensureReady();\n\n // If trading setup already complete, return immediately\n if (this.#tradingSetupComplete) {\n return;\n }\n\n // If trading setup is in progress, wait for it\n if (this.#tradingSetupPromise) {\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Waiting for in-progress trading setup',\n );\n await this.#tradingSetupPromise;\n return;\n }\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Starting trading setup (may require signatures)',\n );\n\n this.#tradingSetupPromise = (async (): Promise<void> => {\n // Pre-fetch spotMeta for HIP-3 operations (non-blocking if it fails)\n // This ensures token info (USDC/USDH indices) is available during order placement\n if (this.#hip3Enabled) {\n try {\n await this.#getCachedSpotMeta();\n } catch (error) {\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] spotMeta pre-fetch failed, will retry when needed',\n error,\n );\n // Don't throw - spotMeta will be fetched on-demand if needed\n }\n }\n\n // Attempt to enable native balance abstraction\n await this.#ensureDexAbstractionEnabled();\n\n // Set up builder fee approval\n try {\n await this.#ensureBuilderFeeApproval();\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Builder fee approval failed',\n error,\n );\n // Don't throw - let trading continue, will fail with clear error if needed\n }\n\n // Set up referral code\n await this.#ensureReferralSet();\n\n // Only mark complete if keyring was unlocked (signing could actually happen)\n if (this.#walletService.isKeyringUnlocked()) {\n this.#tradingSetupComplete = true;\n }\n })();\n\n try {\n await this.#tradingSetupPromise;\n } finally {\n this.#tradingSetupPromise = null;\n }\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Trading setup complete',\n );\n }\n\n /**\n * Get current price for a symbol using WebSocket cache first, REST API fallback\n * Centralizes the price fetching pattern used across multiple methods\n *\n * @param params - Parameters for fetching price\n * @param params.symbol - The symbol to get price for\n * @param params.dexName - Optional DEX name for REST API fallback\n * @returns The current price as a number\n * @throws Error if no price is available\n */\n async #getOrFetchPrice(params: GetOrFetchPriceParams): Promise<number> {\n const { symbol, dexName } = params;\n\n // OPTIMIZATION: Use WebSocket price cache first (0 weight), fall back to REST (2 weight)\n const cachedPrice = this.#subscriptionService.getCachedPrice(symbol);\n\n if (cachedPrice) {\n const price = parseFloat(cachedPrice);\n // Validate cached price: must be positive and finite\n // Covers zero, negative, NaN, and Infinity in one check\n if (price <= 0 || !isFinite(price)) {\n this.#deps.debugLogger.log(\n 'WebSocket cached price invalid for getOrFetchPrice, falling back to REST',\n { symbol, cachedPrice, parsedPrice: price },\n );\n // Fall through to REST API fallback\n } else {\n this.#deps.debugLogger.log('Using WebSocket cached price', {\n symbol,\n price,\n });\n return price;\n }\n }\n\n // Fallback to REST API if cache miss\n this.#deps.debugLogger.log(\n 'Price cache miss for getOrFetchPrice, falling back to REST allMids',\n { symbol },\n );\n const infoClient = this.#clientService.getInfoClient();\n const mids = await infoClient.allMids(\n dexName ? { dex: dexName } : undefined,\n );\n const price = parseFloat(mids[symbol] || '0');\n\n // Validate REST price: must be positive and finite\n if (price <= 0 || !isFinite(price)) {\n throw new Error(`Invalid price for ${symbol}: ${price}`);\n }\n\n return price;\n }\n\n /**\n * Get fills using WebSocket cache first, falling back to REST API\n * OPTIMIZATION: Uses cached fills when available (0 API weight), only calls REST on cache miss\n *\n * Cache limitation: WebSocket cache is limited to ~100 most recent fills.\n * For historical data (e.g., position-opening fills from months ago), use getOrderFills directly.\n *\n * @param params - Optional filter parameters (startTime, symbol)\n * @returns Array of order fills\n */\n public async getOrFetchFills(\n params?: GetOrFetchFillsParams,\n ): Promise<OrderFill[]> {\n // Check WebSocket cache first (0 API weight)\n const cachedFills = this.#subscriptionService.getFillsCacheIfInitialized();\n\n if (cachedFills !== null) {\n this.#deps.debugLogger.log('Using WebSocket cached fills', {\n count: cachedFills.length,\n params,\n });\n return this.#filterFills(cachedFills, params);\n }\n\n // Fallback to REST API when cache not initialized\n this.#deps.debugLogger.log(\n 'Fills cache miss for getOrFetchFills, falling back to REST',\n { params },\n );\n const restFills = await this.getOrderFills(params);\n // Apply symbol filter to REST results for consistent API behavior\n // Note: getOrderFills doesn't support symbol filtering natively\n return this.#filterFills(restFills, params);\n }\n\n /**\n * Filter fills array by optional startTime and symbol parameters\n *\n * @param fills - Array of fills to filter\n * @param params - Optional filter parameters\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.symbol - The trading pair symbol.\n * @returns Filtered fills array\n */\n #filterFills(\n fills: OrderFill[],\n params?: { startTime?: number; symbol?: string },\n ): OrderFill[] {\n if (!params) {\n return fills;\n }\n\n return fills.filter((fill) => {\n if (params.startTime && fill.timestamp < params.startTime) {\n return false;\n }\n if (params.symbol && fill.symbol !== params.symbol) {\n return false;\n }\n return true;\n });\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 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, 'HyperLiquidProvider.getAllAvailableDexs'),\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 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 * @returns A promise that resolves to the result.\n */\n 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 // debugLogger not logger.error: this is a handled transient failure — the app\n // recovers to main DEX via return [null]. Sending to Sentry as error() is noise.\n this.#deps.debugLogger.log(\n '[fetchValidatedDexsInternal] perpDexs() call failed, falling back to main DEX',\n {\n error: String(error),\n ...this.#getErrorContext('getValidatedDexs.perpDexs'),\n },\n );\n // Do not cache — transient error, allow retry on next call\n return [null];\n }\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 // Do not cache — may be transient, allow retry on next call\n return [null];\n }\n\n // Cache for buildAssetMapping() to avoid duplicate call\n this.#cachedAllPerpDexs = allDexs;\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 } else {\n // Mainnet-specific filtering: Extract allowed DEXs from the allowlist patterns\n // This reduces WebSocket subscription overhead dynamically based on feature flags\n const { AutoDiscoverAll } = MAINNET_HIP3_CONFIG;\n\n if (!AutoDiscoverAll) {\n // Extract unique DEX names from allowlist patterns\n // Patterns like \"xyz:*\", \"xyz:TSLA\", or \"xyz\" all indicate DEX \"xyz\"\n const allowedDexsFromAllowlist = this.#extractDexsFromAllowlist();\n\n if (allowedDexsFromAllowlist.length === 0) {\n // No HIP-3 DEXs in allowlist - main DEX only\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - using main DEX only (no HIP-3 DEXs in allowlist)',\n {\n availableHip3Dexs: availableHip3Dexs.length,\n allowlistMarkets: this.#allowlistMarkets,\n },\n );\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n // Filter to DEXs that are both available AND in the allowlist\n const filteredDexs = availableHip3Dexs.filter((dex) =>\n allowedDexsFromAllowlist.includes(dex),\n );\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - filtered to allowlist DEXs',\n {\n allowedDexsFromAllowlist,\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\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - AUTO_DISCOVER_ALL enabled, using all DEXs',\n { totalDexCount: availableHip3Dexs.length + 1 },\n );\n }\n\n // Fallback: Return all DEXs (when AUTO_DISCOVER_ALL is true)\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 * Extract unique DEX names from allowlist market patterns\n * Patterns can be: \"xyz:*\" (wildcard), \"xyz:TSLA\" (exact), or \"xyz\" (DEX shorthand)\n *\n * @returns Array of unique DEX names from the allowlist\n */\n #extractDexsFromAllowlist(): string[] {\n if (this.#allowlistMarkets.length === 0) {\n return [];\n }\n\n const dexNames = new Set<string>();\n\n for (const pattern of this.#allowlistMarkets) {\n // Pattern formats:\n // - \"xyz:*\" -> DEX \"xyz\" (wildcard)\n // - \"xyz:TSLA\" -> DEX \"xyz\" (exact match)\n // - \"xyz\" -> DEX \"xyz\" (shorthand)\n const colonIndex = pattern.indexOf(':');\n if (colonIndex > 0) {\n // Has colon - extract DEX prefix\n const dex = pattern.substring(0, colonIndex);\n dexNames.add(dex);\n } else if (pattern.length > 0 && !pattern.includes('*')) {\n // No colon and not a wildcard - could be DEX shorthand\n // Only add if it looks like a valid DEX name (lowercase alphanumeric)\n if (/^[a-z][a-z0-9]*$/iu.test(pattern)) {\n dexNames.add(pattern.toLowerCase());\n }\n }\n }\n\n return Array.from(dexNames);\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 - The operation parameters.\n * @param params.dexName - DEX name (null for main DEX).\n * @param params.skipCache - If true, bypass cache and fetch fresh data.\n * @returns MetaResponse with universe data.\n * @throws Error if API returns invalid data\n */\n 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 // Pass dex only for HIP-3 DEXs; omit for main DEX (empty string).\n // Testnet API returns null when dex=\"\" is explicitly sent.\n const meta = await infoClient.meta(dexKey ? { dex: dexKey } : undefined);\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 await this.#backfillAssetMapForDex(dexName, 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 * Backfill the asset ID map for a single DEX from a fresh meta response.\n * Used to repair partial asset mapping when an individual DEX becomes available later.\n *\n * @param dex - DEX name (null for main DEX).\n * @param meta - Meta response containing the DEX universe.\n * @returns True if the mapping was rebuilt for the DEX.\n */\n async #backfillAssetMapForDex(\n dex: string | null,\n meta: MetaResponse,\n ): Promise<boolean> {\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n return false;\n }\n\n if (!this.#cachedAllPerpDexs) {\n try {\n await this.#getValidatedDexs();\n } catch (error) {\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Unable to refresh validated DEXs before rebuilding asset map',\n {\n dex: dex ?? 'main',\n error: ensureError(\n error,\n 'HyperLiquidProvider.backfillAssetMapForDex',\n ).message,\n },\n );\n }\n }\n\n const allPerpDexs = this.#cachedAllPerpDexs ?? [null];\n const perpDexIndex = allPerpDexs.findIndex((entry) => {\n if (dex === null) {\n return entry === null;\n }\n return entry !== null && entry.name === dex;\n });\n\n if (perpDexIndex === -1) {\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Could not find perpDexIndex for DEX',\n { dex: dex ?? 'main' },\n );\n return false;\n }\n\n const { symbolToAssetId } = buildAssetMapping({\n metaUniverse: meta.universe,\n dex,\n perpDexIndex,\n });\n\n symbolToAssetId.forEach((assetId, coin) => {\n this.#symbolToAssetId.set(coin, assetId);\n });\n\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Rebuilt asset mapping for DEX',\n {\n dex: dex ?? 'main',\n dexAssetCount: symbolToAssetId.size,\n totalAssetCount: this.#symbolToAssetId.size,\n },\n );\n\n return symbolToAssetId.size > 0;\n }\n\n /**\n * Resolve an asset ID, repairing the DEX-specific map when meta is available but the map is stale.\n *\n * @param params - Resolution parameters.\n * @param params.symbol - Asset symbol to resolve.\n * @param params.dexName - DEX name (null for main DEX).\n * @param params.meta - Optional pre-fetched meta for the DEX.\n * @returns The asset ID.\n */\n async #getAssetIdWithRepair(params: {\n symbol: string;\n dexName: string | null;\n meta?: MetaResponse;\n }): Promise<number> {\n const { symbol, dexName } = params;\n const existingAssetId = this.#symbolToAssetId.get(symbol);\n\n if (existingAssetId !== undefined) {\n return existingAssetId;\n }\n\n const meta =\n params.meta ?? (await this.#getCachedMeta({ dexName: dexName ?? null }));\n const assetExistsInMeta = meta.universe.some(\n (asset) => asset.name === symbol,\n );\n\n if (assetExistsInMeta) {\n await this.#backfillAssetMapForDex(dexName, meta);\n const repairedAssetId = this.#symbolToAssetId.get(symbol);\n if (repairedAssetId !== undefined) {\n return repairedAssetId;\n }\n }\n\n this.#deps.debugLogger.log('Asset ID lookup failed', {\n requestedCoin: symbol,\n dexName: dexName ?? 'main',\n mapSize: this.#symbolToAssetId.size,\n mapContainsAsset: this.#symbolToAssetId.has(symbol),\n assetExistsInMeta,\n allKeys: Array.from(this.#symbolToAssetId.keys()).slice(0, 20),\n });\n\n throw new Error(`Asset ID not found for ${symbol}`);\n }\n\n /**\n * Fetch spot metadata with session-based caching\n * Contains token info (USDC, USDH indices) needed for HIP-3 collateral checks\n * Pre-fetched in ensureReadyForTrading() to ensure availability during order placement\n *\n * @returns SpotMetaResponse with tokens and universe data\n */\n async #getCachedSpotMeta(): Promise<SpotMetaResponse> {\n if (this.#cachedSpotMeta) {\n this.#deps.debugLogger.log('[getCachedSpotMeta] Using cached spotMeta', {\n tokensCount: this.#cachedSpotMeta.tokens.length,\n universeCount: this.#cachedSpotMeta.universe.length,\n });\n return this.#cachedSpotMeta;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n this.#cachedSpotMeta = spotMeta;\n this.#deps.debugLogger.log(\n '[getCachedSpotMeta] Fetched and cached spotMeta',\n {\n tokensCount: spotMeta.tokens.length,\n universeCount: spotMeta.universe.length,\n },\n );\n\n return spotMeta;\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 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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.assetSymbol - The asset symbol.\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees#fee-formula-for-developers\n * @returns The result of the operation.\n */\n 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(\n error,\n 'HyperLiquidProvider.calculateHip3FeeMultiplier',\n ).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 #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 - The operation parameters.\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 * @returns Array of MarketInfo objects.\n */\n 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 * @returns A promise that resolves to the string result.\n */\n async #getUsdcTokenId(): Promise<string> {\n if (this.#cachedUsdcTokenId) {\n return this.#cachedUsdcTokenId;\n }\n\n const spotMeta = await this.#getCachedSpotMeta();\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 - The DEX identifier (empty string for main DEX).\n * @returns A promise that resolves to the boolean result.\n */\n async #isUsdhCollateralDex(dexName: string): Promise<boolean> {\n const meta = await this.#getCachedMeta({ dexName });\n const spotMeta = await this.#getCachedSpotMeta();\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 * @returns A promise that resolves to the numeric result.\n */\n 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 * @returns A promise that resolves to the numeric result.\n */\n 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 - The amount value.\n * @returns A promise that resolves to the result.\n */\n 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 = ensureError(\n error,\n 'HyperLiquidProvider.transferUSDCToPerps',\n ).message;\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 - The amount value.\n * @returns A promise that resolves to the result.\n */\n async #swapUsdcToUsdh(\n amount: number,\n ): Promise<{ success: boolean; filledSize?: number; error?: string }> {\n const spotMeta = await this.#getCachedSpotMeta();\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 = SPOT_ASSET_ID_OFFSET + 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 infoClient = this.#clientService.getInfoClient();\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) && hasProperty(status, 'error')) {\n return { success: false, error: String(status.error) };\n }\n\n // Note: `in` narrows the HyperLiquid SDK discriminated union to the\n // branch that has `filled`; `hasProperty` only narrows the key and\n // types `status.filled` as `unknown`, which loses access to `.totalSz`.\n /* eslint-disable no-restricted-syntax */\n const filledSize =\n isStatusObject(status) && 'filled' in status\n ? parseFloat(status.filled?.totalSz ?? '0')\n : 0;\n /* eslint-enable no-restricted-syntax */\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 = ensureError(\n error,\n 'HyperLiquidProvider.swapUSDCToUSDH',\n ).message;\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 - The DEX identifier (empty string for main DEX).\n * @param requiredMargin - The required margin amount.\n */\n async #ensureUsdhCollateralForOrder(\n dexName: string,\n requiredMargin: number,\n ): Promise<void> {\n const spotUsdhBalance = await this.#getSpotUsdhBalance();\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Checking USDH collateral',\n {\n dexName,\n requiredMargin,\n spotUsdhBalance,\n },\n );\n\n if (spotUsdhBalance >= requiredMargin) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Sufficient USDH in spot',\n );\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(\n 'HyperLiquidProvider: USDH collateral acquired',\n {\n dexName,\n filledSize: swapResult.filledSize,\n },\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 async #buildAssetMapping(): Promise<void> {\n // Get feature-flag-validated DEXs to map (respects hip3Enabled and enabledDexs)\n let dexsToMap: (string | null)[];\n try {\n dexsToMap = await this.#getValidatedDexs();\n } catch (dexError) {\n // If getValidatedDexs fails, fall back to main DEX only to keep the provider\n // functional. Without this, a transient perpDexs() failure would permanently\n // brick #ensureReady via the cached rejected promise.\n // Do not set #cachedAllPerpDexs or #cachedValidatedDexs here — leave them null\n // so #getValidatedDexs retries on the next call (same as #fetchValidatedDexsInternal).\n this.#deps.debugLogger.log(\n '[buildAssetMapping] getValidatedDexs failed, falling back to main DEX',\n { error: String(dexError) },\n );\n dexsToMap = [null];\n }\n\n // Local fallback only — never write [null] into #cachedAllPerpDexs here.\n // That cache is owned exclusively by #fetchValidatedDexsInternal; writing a\n // fallback here would prevent subsequent callers from retrying perpDexs().\n const allPerpDexs = this.#cachedAllPerpDexs ?? [null];\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 let dexDiscoveryComplete = this.#cachedValidatedDexs !== null;\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 dexDiscoveryComplete = false;\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 dexDiscoveryComplete = false;\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 } else {\n dexDiscoveryComplete = false;\n }\n });\n\n this.#dexDiscoveryComplete = dexDiscoveryComplete;\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 * @example\n * ```typescript\n * const results = await this.#queryUserDataAcrossDexs(\n * { user: userAddress },\n * (p) => infoClient.clearinghouseState(p)\n * );\n * ```\n */\n async #queryUserDataAcrossDexs<\n TParams extends Record<string, unknown>,\n TResult,\n >(\n baseParams: TParams,\n queryFn: (params: TParams & { dex?: string }) => Promise<TResult>,\n ): Promise<DexQueryResponse<TResult>> {\n const enabledDexs = await this.#getValidatedDexs();\n\n const settledResults = await Promise.allSettled(\n enabledDexs.map(async (dex) => {\n const params = dex\n ? ({ ...baseParams, dex } as TParams & { dex: string })\n : (baseParams as TParams & { dex?: string });\n return queryFn(params);\n }),\n );\n\n const results: DexQueryResult<TResult>[] = [];\n const failedDexs: DexQueryResponse<TResult>['failedDexs'] = [];\n\n settledResults.forEach((result, index) => {\n const dex = enabledDexs[index];\n if (result.status === 'fulfilled') {\n results.push({ dex, data: result.value });\n return;\n }\n\n failedDexs.push({\n dex,\n error: ensureError(\n result.reason,\n 'HyperLiquidProvider.queryUserDataAcrossDexs',\n ),\n });\n });\n\n return { results, failedDexs };\n }\n\n /**\n * Map HyperLiquid API errors to standardized PERPS_ERROR_CODES\n *\n * @param error - The error that occurred.\n * @returns The result of the operation.\n */\n #mapError(error: unknown): Error {\n const { message } = ensureError(error, 'HyperLiquidProvider.mapError');\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 ensureError(error, 'HyperLiquidProvider.mapError');\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 * @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 #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 - The operation parameters.\n * @returns The result of the operation.\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 - The operation parameters.\n * @returns The result of the operation.\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 * @returns Current max fee rate or null if not approved\n */\n async #checkBuilderFeeApproval(): Promise<number | null> {\n const infoClient = this.#clientService.getInfoClient();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const builder = this.#getBuilderAddress(\n this.#clientService.isTestnetMode(),\n );\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: Uses GLOBAL cache to persist across provider reconnections\n * This prevents repeated signing requests for hardware wallets.\n *\n * Note: This is network-specific - testnet and mainnet have separate builder fee states\n */\n 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 const cacheKey = this.#getCacheKey(network, userAddress);\n\n // Check GLOBAL cache first to avoid repeated signing requests across reconnections\n // This is CRITICAL for hardware wallets to prevent QR popup spam\n const globalCached = PerpsSigningCache.getBuilderFee(network, userAddress);\n if (globalCached?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Using global cache (prevents QR popup spam)',\n { network, success: globalCached.success },\n );\n if (globalCached.success) {\n this.#builderFeeCheckCache.set(cacheKey, true);\n }\n return;\n }\n\n // Check if another provider instance is currently attempting this operation\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'builderFee',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n return;\n }\n\n // Set global in-flight lock\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'builderFee',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock\n const recheckCache = PerpsSigningCache.getBuilderFee(\n network,\n userAddress,\n );\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Completed by another provider',\n { network },\n );\n completeInFlight();\n return;\n }\n\n const { isApproved, requiredDecimal } =\n await this.#checkBuilderFeeStatus();\n\n if (isApproved) {\n // User already has approval on-chain\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#builderFeeCheckCache.set(cacheKey, true);\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Already approved on-chain',\n { network },\n );\n } else {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval required (will show signing request)',\n { builder: builderAddress, requiredDecimal },\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 // Cache success in BOTH global and instance caches\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#builderFeeCheckCache.set(cacheKey, true);\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval successful',\n {\n builder: builderAddress,\n maxFeeRate,\n },\n );\n }\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache failure to prevent retries\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: false,\n });\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Failed, cached to prevent retries',\n {\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureBuilderFeeApproval',\n ).message,\n },\n );\n\n completeInFlight();\n throw error;\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 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 async #getBalanceForDex(params: { dex: string | null }): 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 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 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 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 - The operation parameters.\n * @param params.symbol - The trading pair symbol.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.positionSize - The position size value.\n * @param params.orderPrice - The order price value.\n * @param params.leverage - The leverage multiplier.\n * @param params.isBuy - Whether this is a buy order.\n * @private\n * @returns The result of the operation.\n */\n 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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.transferInfo - The transfer information.\n * @param params.transferInfo.amount - The amount value.\n * @param params.transferInfo.sourceDex - The source DEX for the transfer.\n * @private\n */\n 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(\n rebalanceError,\n 'HyperLiquidProvider.placeOrder:autoRebalance',\n ),\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(\n balanceCheckError,\n 'HyperLiquidProvider.placeOrder:postOrderBalanceCheck',\n ),\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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.transferInfo - The transfer information.\n * @param params.transferInfo.amount - The amount value.\n * @param params.transferInfo.sourceDex - The source DEX for the transfer.\n * @private\n */\n 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, 'HyperLiquidProvider.placeOrder:rollback'),\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 - The operation parameters.\n * @throws Error if validation fails\n */\n async #validateOrderBeforePlacement(params: OrderParams): 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async #getAssetInfo(params: GetAssetInfoParams): Promise<GetAssetInfoResult> {\n const { symbol, dexName } = params;\n\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 currentPrice = await this.#getOrFetchPrice({\n symbol,\n dexName: dexName ?? null,\n });\n\n return { assetInfo, currentPrice, meta };\n }\n\n /**\n * Prepares asset for trading by updating leverage if specified\n *\n * @param params - The operation parameters.\n */\n 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n 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 // Note: `in` narrows the HyperLiquid SDK discriminated union to the\n // branch that has the property; `hasProperty` types the property as\n // `unknown`, losing downstream access to `.oid`, `.totalSz`, `.avgPx`.\n /* eslint-disable no-restricted-syntax */\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 /* eslint-enable no-restricted-syntax */\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 - The operation parameters.\n * @returns The result of the operation.\n */\n #handleOrderError(params: HandleOrderErrorParams): OrderResult {\n const { error, symbol, orderType, isBuy } = params;\n\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.handleOrderError'),\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 * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\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, meta } = 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 = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName,\n meta,\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 = ensureError(\n error,\n 'HyperLiquidProvider.placeOrder',\n ).message;\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 - The operation parameters.\n * @param params.orderId - The order ID to modify\n * @param params.newOrder - New order parameters (price, size, etc.)\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\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 meta = await this.#getCachedMeta({ 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 = await this.#getOrFetchPrice({\n symbol: params.newOrder.symbol,\n dexName: dexName ?? null,\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 = await this.#getAssetIdWithRepair({\n symbol: params.newOrder.symbol,\n dexName,\n meta,\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, 'HyperLiquidProvider.editOrder'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n const exchangeClient = this.#clientService.getExchangeClient();\n const asset = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName: parseAssetName(params.symbol).dex,\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, 'HyperLiquidProvider.cancelOrder'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n const exchangeClient = this.#clientService.getExchangeClient();\n\n // Map orders to SDK format and validate coins\n const cancelRequests = await Promise.all(\n params.map(async (order) => {\n const asset = await this.#getAssetIdWithRepair({\n symbol: order.symbol,\n dexName: parseAssetName(order.symbol).dex,\n });\n return {\n a: asset,\n o: parseInt(order.orderId, 10),\n };\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 ? undefined\n : (status as { error: string }).error,\n })),\n };\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.cancelOrders'),\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Get all current positions from cache (avoids 429 rate limiting)\n const positions = await this.getPositions();\n\n // Filter positions based on params\n positionsToClose =\n params.closeAll === true ||\n !params.symbols ||\n 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 for order submission\n const exchangeClient = this.#clientService.getExchangeClient();\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 = await this.#getAssetIdWithRepair({\n symbol: position.symbol,\n dexName,\n meta,\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 const currentPrice = await this.#getOrFetchPrice({\n symbol: position.symbol,\n dexName: dexName ?? null,\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) &&\n (hasProperty(stat, 'filled') || hasProperty(stat, 'resting')),\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 (hasProperty(status, 'filled') || hasProperty(status, 'resting'));\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 (hasProperty(status, 'filled') || hasProperty(status, 'resting')),\n error:\n isStatusObject(status) && hasProperty(status, 'error')\n ? String(status.error)\n : undefined,\n })),\n };\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.closePositions'),\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 - The operation parameters.\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 * @returns A promise that resolves to the result.\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 {\n symbol,\n takeProfitPrice,\n stopLossPrice,\n position: livePosition,\n } = params;\n\n // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Use live position (from WebSocket) if available, otherwise fetch via REST\n // Preferring WebSocket data avoids rate limiting issues with the REST API\n let position: Position | undefined = livePosition;\n\n if (position) {\n this.#deps.debugLogger.log('Using live position from WebSocket', {\n symbol: position.symbol,\n size: position.size,\n });\n } else {\n // Fallback: fetch positions via REST API (legacy behavior)\n this.#deps.debugLogger.log(\n 'No live position passed, falling back to REST API fetch',\n );\n let positions: Position[];\n try {\n positions = await this.getPositions({ skipCache: true });\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'),\n this.#getErrorContext('updatePositionTPSL > getPositions', {\n symbol,\n }),\n );\n throw error;\n }\n position = positions.find((pos) => pos.symbol === symbol);\n }\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 // Get clients for API calls (ensureReady already called at method start)\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 // Cancel existing TP/SL orders for this position\n // OPTIMIZATION: Use WebSocket cache first (0 weight), fall back to single-DEX REST (20 weight)\n // Previously: queryUserDataAcrossDexs queried ALL DEXs (20 weight × N DEXs = 40+ weight)\n const assetId = await this.#getAssetIdWithRepair({\n symbol,\n dexName,\n });\n\n let cancelRequests: { a: number; o: number }[] = [];\n\n // Use atomic getter to prevent race condition between check and get\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n\n if (cachedOrders === null) {\n // Fallback: Query only the specific DEX (20 weight instead of 40+)\n this.#deps.debugLogger.log(\n 'WebSocket cache not initialized, falling back to single-DEX REST query',\n { dex: dexName ?? 'main' },\n );\n\n const orders = await infoClient.frontendOpenOrders({\n user: userAddress,\n dex: dexName ?? undefined,\n });\n\n // Filter using raw SDK response properties\n const tpslOrders = orders.filter(\n (order) =>\n order.coin === symbol &&\n order.reduceOnly &&\n order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&\n order.isTrigger &&\n (order.orderType.includes('Take Profit') ||\n order.orderType.includes('Stop')),\n );\n\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: order.oid,\n }));\n } else {\n // WebSocket cache available - use it (no API call, 0 weight)\n this.#deps.debugLogger.log(\n 'Using WebSocket cache for TP/SL orders lookup',\n { cachedOrdersCount: cachedOrders.length },\n );\n\n // Filter using normalized Order type properties\n // Note: Cached orders don't have isPositionTpsl, but we identify TP/SL orders by:\n // - isTrigger === true\n // - reduceOnly === true\n // - detailedOrderType contains 'Take Profit' or 'Stop'\n const tpslOrders = cachedOrders.filter(\n (order) =>\n order.symbol === symbol &&\n order.reduceOnly === true &&\n order.isTrigger === true &&\n order.detailedOrderType &&\n (order.detailedOrderType.includes('Take Profit') ||\n order.detailedOrderType.includes('Stop')),\n );\n\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: parseInt(order.orderId, 10),\n }));\n }\n\n if (cancelRequests.length > 0) {\n this.#deps.debugLogger.log(\n `Canceling ${cancelRequests.length} existing TP/SL orders for ${symbol}`,\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 // assetId already validated above when building cancelRequests\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, 'HyperLiquidProvider.updatePositionTPSL'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async closePosition(params: ClosePositionParams): Promise<OrderResult> {\n try {\n this.#deps.debugLogger.log('Closing position:', params);\n\n // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Use provided position (from WebSocket) or fetch from cache\n // This avoids unnecessary API calls and prevents 429 rate limiting\n let { position } = params;\n if (!position) {\n const positions = await this.getPositions();\n position = positions.find((pos) => pos.symbol === params.symbol);\n }\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, 'HyperLiquidProvider.closePosition'),\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 * @param params.providerId - Optional provider identifier (ignored, always uses HyperLiquid)\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: UpdateMarginParams): 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 (from cache to avoid 429 rate limiting)\n const positions = await this.getPositions();\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 = await this.#getAssetIdWithRepair({\n symbol,\n dexName: parseAssetName(symbol).dex,\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 const safeError = ensureError(error, 'HyperLiquidProvider.updateMargin');\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext('updateMargin', {\n symbol: params.symbol,\n amount: params.amount,\n }),\n );\n return {\n success: false,\n error: safeError.message,\n };\n }\n }\n\n /**\n * Get validated DEXs for standalone mode using a standalone InfoClient.\n * Similar to getValidatedDexs() but doesn't require full initialization.\n * Reuses cachedValidatedDexs to avoid redundant perpDexs() calls.\n *\n * @returns A promise that resolves to the result.\n */\n async #getStandaloneValidatedDexs(): Promise<(string | null)[]> {\n // Return cached result if available\n if (this.#cachedValidatedDexs !== null) {\n return this.#cachedValidatedDexs;\n }\n\n // Kill switch: HIP-3 disabled, return main DEX only\n if (!this.#hip3Enabled) {\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n // Fetch available DEXs via standalone client\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n let allDexs;\n try {\n allDexs = await standaloneInfoClient.perpDexs();\n } catch {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone perpDexs() failed, falling back to main DEX only',\n );\n return [null];\n }\n\n // Validate response\n if (!allDexs || !Array.isArray(allDexs)) {\n return [null];\n }\n\n // Populate #cachedAllPerpDexs so buildAssetMapping can compute perpDexIndex.\n // Without this, getValidatedDexs returns from #cachedValidatedDexs (string names)\n // but #cachedAllPerpDexs (raw objects for index computation) stays null,\n // causing \"Could not find perpDexIndex for DEX xyz\" failures.\n this.#cachedAllPerpDexs = allDexs;\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 // Filter by allowlist patterns (same logic as fetchValidatedDexsInternal)\n const allowedDexsFromAllowlist = this.#extractDexsFromAllowlist();\n if (allowedDexsFromAllowlist.length === 0) {\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n const filteredDexs = availableHip3Dexs.filter((dex) =>\n allowedDexsFromAllowlist.includes(dex),\n );\n\n this.#cachedValidatedDexs = [null, ...filteredDexs];\n return this.#cachedValidatedDexs;\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n try {\n // Path 0: Standalone mode for lightweight position 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 showing positions on token details page\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting positions in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const results = await queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Combine and filter positions from all DEXs\n // Skip TP/SL lookup (would require additional API call)\n const positions = results.flatMap((state) =>\n state.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos)),\n );\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone positions fetched',\n { count: positions.length },\n );\n\n return positions;\n }\n\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 [stateResponse, orderResponse] = 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 const { results: stateResults, failedDexs: failedStateDexs } =\n stateResponse;\n const { results: orderResults, failedDexs: failedOrderDexs } =\n orderResponse;\n\n if (failedStateDexs.length > 0 || failedOrderDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Partial multi-DEX position fetch completed with failures',\n {\n failedStateDexs: failedStateDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n failedOrderDexs: failedOrderDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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:', {\n count: rawFills?.length ?? 0,\n });\n\n // Start fetching historical orders in parallel with fill transformation.\n // The fills API does not return order type, so we cross-reference\n // with historical orders to enable TP/SL pill rendering in activity.\n const historicalOrdersPromise = (\n infoClient.historicalOrders?.({ user: userAddress }) ??\n Promise.resolve(null)\n ).catch((enrichError: unknown) => {\n this.#deps.debugLogger.log(\n 'Warning: failed to enrich fills with order types:',\n enrichError,\n );\n return null;\n });\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 // Enrich fills with detailedOrderType from historical orders\n // Wrapped in its own try/catch so a malformed order never discards fetched fills\n try {\n const rawOrders = await historicalOrdersPromise;\n if (rawOrders) {\n const orderTypeByOid = new Map<string, string>();\n for (const rawOrder of rawOrders) {\n const oid = rawOrder.order?.oid?.toString();\n if (oid && rawOrder.order?.orderType && !orderTypeByOid.has(oid)) {\n orderTypeByOid.set(oid, rawOrder.order.orderType);\n }\n }\n for (const fill of fills) {\n const orderType = orderTypeByOid.get(fill.orderId);\n if (orderType) {\n fill.detailedOrderType = orderType;\n }\n }\n }\n } catch (enrichError) {\n this.#deps.debugLogger.log(\n 'Error enriching fills with order types:',\n enrichError,\n );\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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:', {\n count: rawOrders?.length ?? 0,\n });\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getOpenOrders(params?: GetOrdersParams): Promise<Order[]> {\n try {\n // Path 0: Standalone mode for lightweight open order queries\n // Creates a standalone InfoClient without requiring full initialization\n // No wallet, WebSocket, or account setup needed - just HTTP API call\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting open orders in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const orderResults = await queryStandaloneOpenOrders(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Combine all orders from all DEXs and adapt (without position context in standalone mode)\n const orders = orderResults.flatMap((dexOrders) =>\n dexOrders.map((order) => adaptOrderFromSDK(order, undefined)),\n );\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone open orders fetched',\n { count: orders.length },\n );\n\n return orders;\n }\n\n // Try WebSocket cache first (unless explicitly bypassed)\n // Use atomic getter to prevent race condition between check and get\n if (!params?.skipCache) {\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n if (cachedOrders !== null) {\n this.#deps.debugLogger.log(\n 'Using cached open orders from WebSocket',\n {\n count: cachedOrders.length,\n },\n );\n return cachedOrders;\n }\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 { results: orderResults, failedDexs } =\n await this.#queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.frontendOpenOrders(userParam),\n );\n\n if (failedDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Partial multi-DEX open order fetch completed with failures',\n {\n failedDexs: failedDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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.DEFAULT_FUNDING_HISTORY_DAYS *\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:', {\n count: rawFunding?.length ?? 0,\n });\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 - The operation parameters.\n * @param params.accountId - The CAIP account ID.\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.endTime - End timestamp in milliseconds.\n * @returns The result of the operation.\n */\n async getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]> {\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(\n error,\n 'HyperLiquidProvider.getUserNonFundingLedgerUpdates',\n ),\n this.#getErrorContext('getUserNonFundingLedgerUpdates', params),\n );\n return [];\n }\n }\n\n /**\n * Get user history (deposits, withdrawals, transfers)\n *\n * @param params - The operation parameters.\n * @param params.accountId - The CAIP account ID.\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.endTime - End timestamp in milliseconds.\n * @returns The result of the operation.\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, 'HyperLiquidProvider.getUserHistory'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getAccountState(params?: GetAccountStateParams): Promise<AccountState> {\n try {\n // Path 0: Standalone mode for lightweight account state 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 user has perps funds\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting account state in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const results = await queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Aggregate account states across all DEXs\n const dexAccountStates = results.map((perpsState) =>\n adaptAccountStateFromSDK(perpsState),\n );\n const aggregatedAccountState = aggregateAccountStates(dexAccountStates);\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone account state fetched',\n { totalBalance: aggregatedAccountState.totalBalance },\n );\n\n return aggregatedAccountState;\n }\n\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(\n 'User address for account state:',\n userAddress,\n );\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 // One transient DEX failure should not blank the entire account state.\n const [spotStateResult, perpsStateResult] = await Promise.allSettled([\n infoClient.spotClearinghouseState({ user: userAddress }),\n this.#queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n ]);\n const spotState =\n spotStateResult.status === 'fulfilled' ? spotStateResult.value : null;\n const perpsResponse =\n perpsStateResult.status === 'fulfilled'\n ? perpsStateResult.value\n : {\n results: [],\n failedDexs: [\n {\n dex: null,\n error: ensureError(\n perpsStateResult.reason,\n 'HyperLiquidProvider.getAccountState.perps',\n ),\n },\n ],\n };\n const perpsStateResults = perpsResponse.results;\n const failedPerpsDexs = perpsResponse.failedDexs;\n\n if (spotStateResult.status === 'rejected') {\n this.#deps.debugLogger.log(\n 'Spot state fetch failed during account state aggregation',\n {\n error: ensureError(\n spotStateResult.reason,\n 'HyperLiquidProvider.getAccountState.spot',\n ).message,\n },\n );\n }\n\n if (failedPerpsDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Perps account state completed with partial DEX failures',\n {\n failedDexs: failedPerpsDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\n }\n\n if (perpsStateResults.length === 0) {\n const failedDexNames = failedPerpsDexs.map(({ dex }) => dex ?? 'main');\n const spotErrorMessage =\n spotStateResult.status === 'rejected'\n ? ensureError(\n spotStateResult.reason,\n 'HyperLiquidProvider.getAccountState.spot',\n ).message\n : undefined;\n throw new Error(\n `Failed to fetch account state (failedDexs=[${failedDexNames.join(',')}], spotError=${spotErrorMessage ?? 'none'})`,\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 dexAccountStates = perpsStateResults.map((result) => {\n const dexAccountState = adaptAccountStateFromSDK(result.data);\n this.#deps.debugLogger.log(\n `DEX ${result.dex ?? 'main'} account state:`,\n {\n totalBalance: dexAccountState.totalBalance,\n availableBalance: dexAccountState.availableBalance,\n marginUsed: dexAccountState.marginUsed,\n unrealizedPnl: dexAccountState.unrealizedPnl,\n },\n );\n return dexAccountState;\n });\n const aggregatedAccountState = aggregateAccountStates(dexAccountStates);\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, 'HyperLiquidProvider.getAccountState'),\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 ensureError(error, 'HyperLiquidProvider.getAccountState');\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 * @returns A promise that resolves to the result.\n */\n async getMarkets(params?: GetMarketsParams): Promise<MarketInfo[]> {\n try {\n // Path 0: Standalone 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?.standalone) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting markets in standalone mode',\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, 'HyperLiquidProvider.getMarkets'),\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, 'HyperLiquidProvider.getMarkets'),\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 && hasProperty(dex, 'name')) {\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(\n ` ❌ ${dexName}: error querying`,\n error,\n );\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, 'HyperLiquidProvider.getAvailableHip3Dexs'),\n this.#getErrorContext('getAvailableHip3Dexs'),\n );\n return [];\n }\n }\n\n /**\n * Get allMids for a DEX — uses WS snapshot as primary source, REST as fallback.\n *\n * @param infoClient - The HyperLiquid info client (used only on cold start).\n * @param dexParam - Optional DEX parameter (empty string for main DEX).\n * @returns allMids record.\n */\n async #getAllMids(\n infoClient: ReturnType<\n typeof HyperLiquidClientService.prototype.getInfoClient\n >,\n dexParam?: string,\n ): Promise<Record<string, string>> {\n const wsSnapshot =\n this.#subscriptionService.getLastAllMidsSnapshot?.(dexParam);\n if (wsSnapshot) {\n return wsSnapshot;\n }\n\n this.#deps.debugLogger.log(\n '[getMarketDataWithPrices] No WS allMids snapshot, falling back to REST',\n { dexParam: dexParam ?? 'main' },\n );\n const mids = await infoClient.allMids(\n dexParam ? { dex: dexParam } : undefined,\n );\n return mids ?? {};\n }\n\n async #fetchSingleDexFresh(\n infoClient: ReturnType<\n typeof HyperLiquidClientService.prototype.getInfoClient\n >,\n dex: string | null,\n ): Promise<DexFetchResult> {\n const dexParam = dex ?? '';\n\n let metaAndCtxs: [MetaResponse | null, PerpsAssetCtx[]] | null = null;\n try {\n metaAndCtxs = (await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n )) as [MetaResponse | null, PerpsAssetCtx[]] | null;\n } catch (error) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs',\n errorMessage: ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.metaAndAssetCtxs',\n ).message,\n };\n }\n\n const meta = metaAndCtxs?.[0] ?? null;\n const assetCtxs = metaAndCtxs?.[1] ?? [];\n\n let dexAllMids: Record<string, string> = {};\n let allMidsErrorMessage: string | undefined;\n try {\n dexAllMids = await this.#getAllMids(infoClient, dexParam || undefined);\n } catch (error) {\n allMidsErrorMessage = ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.allMids',\n ).message;\n }\n\n if (meta?.universe) {\n this.#cachedMetaByDex.set(dexParam, meta);\n this.#subscriptionService.setDexMetaCache(dexParam, meta);\n this.#subscriptionService.setDexAssetCtxsCache(dexParam, assetCtxs);\n await this.#backfillAssetMapForDex(dex, meta);\n }\n\n return {\n dex,\n meta,\n assetCtxs,\n allMids: dexAllMids,\n success: Boolean(meta?.universe),\n failedStep: allMidsErrorMessage ? 'allMids' : undefined,\n errorMessage: allMidsErrorMessage,\n };\n }\n\n #mergeDexResultsInto(\n results: DexFetchResult[],\n combinedUniverse: MetaResponse['universe'],\n combinedAssetCtxs: PerpsAssetCtx[],\n combinedAllMids: Record<string, string>,\n ): void {\n results.forEach((result) => {\n if (result.success && result.meta?.universe) {\n const marketsFromDex = result.meta.universe;\n const filteredMarkets =\n result.dex === null\n ? marketsFromDex\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 Object.assign(combinedAllMids, result.allMids);\n }\n });\n }\n\n #cacheFreshMarketDataSnapshot(\n marketData: PerpsMarketData[],\n results: DexFetchResult[],\n ): PerpsMarketData[] {\n const freshMarketData = marketData.map((market) => ({\n ...market,\n isStale: false,\n }));\n this.#cachedMarketDataWithPrices = {\n data: freshMarketData.map((market) => ({ ...market })),\n timestamp: Date.now(),\n contributingDexs: results\n .filter((result) => result.success && result.meta?.universe)\n .map((result) => result.dex ?? 'main'),\n failedDexs: results\n .filter((result) => !result.success)\n .map((result) => result.dex ?? 'main'),\n };\n return freshMarketData;\n }\n\n #getStaleMarketDataSnapshot(): PerpsMarketData[] | null {\n if (!this.#cachedMarketDataWithPrices) {\n return null;\n }\n\n return this.#cachedMarketDataWithPrices.data.map((market) => ({\n ...market,\n isStale: true,\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 * @returns A promise that resolves to the combined market data from all enabled DEXs.\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 // Use HTTP transport for market data fetches — these are one-shot request/response calls\n // that don't benefit from WebSocket. When the WebSocket is in CONNECTING state (after app\n // backgrounding or network transitions), the SDK buffers messages causing timeouts.\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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 // Check the meta cache first to avoid redundant API calls when buildAssetMapping\n // has already populated it; on cache miss, delegate to #fetchSingleDexFresh.\n const dexDataResults = await Promise.all(\n enabledDexs.map(async (dex) => {\n const dexKey = dex ?? '';\n const dexParam = dex ?? '';\n const cachedMeta = this.#cachedMetaByDex.get(dexKey);\n if (!cachedMeta) {\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Cache miss for ${dex ?? 'main'}, fetching`,\n );\n return this.#fetchSingleDexFresh(infoClient, dex);\n }\n\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Using cached meta for ${dex ?? 'main'}`,\n { universeSize: cachedMeta.universe.length },\n );\n\n let metaForDex = cachedMeta;\n let assetCtxs =\n this.#subscriptionService.getDexAssetCtxsCache(dexKey) ?? [];\n let failedStep: DexFetchFailureStep | undefined;\n let errorMessage: string | undefined;\n\n if (assetCtxs.length !== metaForDex.universe.length) {\n try {\n const freshResult = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\n const freshMeta = freshResult?.[0] ?? null;\n const freshAssetCtxs = freshResult?.[1] ?? [];\n\n if (freshAssetCtxs.length !== freshMeta?.universe?.length) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs' as const,\n errorMessage:\n 'metaAndAssetCtxs returned mismatched universe/assetCtxs lengths',\n };\n }\n\n metaForDex = freshMeta;\n assetCtxs = freshAssetCtxs;\n this.#cachedMetaByDex.set(dexKey, freshMeta);\n this.#subscriptionService.setDexMetaCache(dexKey, freshMeta);\n this.#subscriptionService.setDexAssetCtxsCache(dexKey, assetCtxs);\n await this.#backfillAssetMapForDex(dex, freshMeta);\n } catch (error) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs' as const,\n errorMessage: ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.metaAndAssetCtxs',\n ).message,\n };\n }\n }\n\n let dexAllMids: Record<string, string> = {};\n try {\n dexAllMids = await this.#getAllMids(\n infoClient,\n dexParam || undefined,\n );\n } catch (error) {\n failedStep = 'allMids';\n errorMessage = ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.allMids',\n ).message;\n }\n\n return {\n dex,\n meta: metaForDex,\n assetCtxs,\n allMids: dexAllMids,\n success: true,\n failedStep,\n errorMessage,\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 let latestDexResults = dexDataResults;\n\n this.#mergeDexResultsInto(\n dexDataResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n if (combinedUniverse.length === 0) {\n combinedUniverse.length = 0;\n combinedAssetCtxs.length = 0;\n for (const key of Object.keys(combinedAllMids)) {\n delete combinedAllMids[key];\n }\n\n const retryDelayMs = 2000;\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] All DEXs returned empty, retrying in ${retryDelayMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\n const retryResults = await Promise.all(\n enabledDexs.map((dex) => this.#fetchSingleDexFresh(infoClient, dex)),\n );\n\n this.#mergeDexResultsInto(\n retryResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n latestDexResults = retryResults;\n\n if (combinedUniverse.length === 0) {\n const failedDexs = retryResults\n .filter((result) => !result.success)\n .map((result) => result.dex ?? 'main');\n const succeededDexs = retryResults\n .filter((result) => result.success)\n .map((result) => result.dex ?? 'main');\n const failedDetails = retryResults\n .filter((result) => result.errorMessage)\n .map(\n (result) =>\n `${result.dex ?? 'main'}:${result.failedStep ?? 'unknown'}:${\n result.errorMessage\n }`,\n );\n const staleMarketData = this.#getStaleMarketDataSnapshot();\n\n if (staleMarketData) {\n this.#deps.debugLogger.log(\n '[getMarketDataWithPrices] Returning stale cached market data after retry failure',\n {\n failedDexs,\n failedDetails,\n cachedAt:\n this.#cachedMarketDataWithPrices?.timestamp ?? Date.now(),\n },\n );\n return staleMarketData;\n }\n\n const wsState = this.#clientService.getConnectionState();\n throw new Error(\n `Failed to fetch market data - no markets available (enabledDexs=${enabledDexs.length}, failed=[${failedDexs.join(',')}], succeeded=[${succeededDexs.join(',')}], wsState=${wsState}, details=[${failedDetails.join(';')}])`,\n );\n }\n\n this.#deps.debugLogger.log('[getMarketDataWithPrices] Retry succeeded', {\n marketCount: combinedUniverse.length,\n });\n }\n\n const partialFailures = latestDexResults.filter(\n (result) => result.errorMessage,\n );\n if (partialFailures.length > 0) {\n this.#deps.debugLogger.log(\n 'Market data fetch completed with partial per-DEX failures',\n {\n failures: partialFailures.map(\n (result) =>\n `${result.dex ?? 'main'}:${result.failedStep ?? 'unknown'}:${\n result.errorMessage\n }`,\n ),\n },\n );\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: latestDexResults[0]?.meta?.universe?.length ?? 0,\n hip3Markets:\n combinedUniverse.length -\n (latestDexResults[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 const transformedMarketData = transformMarketData(\n {\n universe: combinedUniverse,\n assetCtxs: combinedAssetCtxs,\n allMids: combinedAllMids,\n },\n this.#deps.marketDataFormatters,\n HIP3_ASSET_MARKET_TYPES,\n );\n\n return this.#cacheFreshMarketDataSnapshot(\n transformedMarketData,\n latestDexResults,\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The unused operation parameters.\n * @returns A promise that resolves to the result.\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(\n 'HyperLiquidProvider: INSUFFICIENT BALANCE',\n {\n error: balanceValidation.error,\n requestedAmount: withdrawAmount,\n availableBalance,\n difference: withdrawAmount - availableBalance,\n },\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(\n 'HyperLiquidProvider: WITHDRAW3 API RESPONSE',\n {\n status: result.status,\n response: result,\n timestamp: new Date().toISOString(),\n },\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 safeError = ensureError(\n error,\n 'HyperLiquidProvider.initiateWithdrawal',\n );\n this.#deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL EXCEPTION', {\n error: safeError.message,\n errorType: safeError.name,\n stack: safeError.stack,\n params,\n timestamp: new Date().toISOString(),\n });\n this.#deps.logger.error(\n safeError,\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 * @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(\n 'HyperLiquidProvider: CALLING SEND_ASSET API',\n {\n sourceDex: params.sourceDex || '(main)',\n destinationDex: params.destinationDex || '(main)',\n amount: params.amount,\n },\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 const safeError = ensureError(\n error,\n 'HyperLiquidProvider.transferToSpot',\n );\n this.#deps.debugLogger.log('❌ HyperLiquidProvider: TRANSFER FAILED', {\n error: safeError.message,\n params,\n });\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext('transferBetweenDexs', { ...params }),\n );\n return {\n success: false,\n error: safeError.message,\n };\n }\n }\n\n /**\n * Subscribe to live price updates\n *\n * @param params - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 return undefined;\n })\n .catch((error) => {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.subscribeToPrices'),\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\n */\n subscribeToCandles(params: SubscribeCandlesParams): () => void {\n return this.#clientService.subscribeToCandles(params);\n }\n\n /**\n * Configure live data settings\n *\n * @param config - The configuration object.\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 * @returns A promise that resolves to the result.\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 * @returns A promise that resolves to the result.\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 * @returns A promise that resolves to the result.\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 - maintenanceMarginRatio * side)\n * where maintenanceMarginRatio = 1 / MAINTENANCE_LEVERAGE = 1 / (2 * max_leverage)\n *\n * @param params - The operation parameters.\n * @returns A promise that resolves to the string result.\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, 'HyperLiquidProvider.calculateLiquidationPrice'),\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 - The operation parameters.\n * @returns A promise that resolves to the numeric result.\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 - The asset identifier.\n * @returns A promise that resolves to the numeric result.\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, 'HyperLiquidProvider.getMaxLeverage'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 const safeError = ensureError(\n error,\n 'HyperLiquidProvider.getFeeSchedule',\n );\n this.#deps.debugLogger.log(\n 'Fee API Call Failed - Falling Back to Base Rates',\n {\n error: safeError.message,\n errorType: safeError.name,\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 let protocolFeeAmount: number | undefined;\n if (amount === undefined) {\n protocolFeeAmount = undefined;\n } else if (isNaN(parsedAmount)) {\n protocolFeeAmount = 0;\n } else {\n protocolFeeAmount = parsedAmount * protocolFeeRate;\n }\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 - The user's wallet address.\n * @private\n * @returns True if the condition is met.\n */\n #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 * @returns A promise that resolves to the result.\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 // NOTE: DexAbstractionCache is global and NOT cleared on disconnect\n // to prevent repeated signing requests across reconnections\n this.#cachedMetaByDex.clear();\n this.#cachedSpotMeta = null;\n this.#perpDexsCache = { data: null, timestamp: 0 };\n this.#dexDiscoveryComplete = false;\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 const pendingTradingSetup = this.#tradingSetupPromise;\n\n // Clear references first to prevent new callers from reusing\n this.#initializationPromise = null;\n this.#ensureReadyPromise = null;\n this.#tradingSetupPromise = null;\n this.#tradingSetupComplete = false;\n this.#pendingBuilderFeeApprovals.clear();\n\n // Wait for pending operations to complete (ignore errors)\n // This prevents IIFEs from setting state after disconnect completes\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 if (pendingTradingSetup) {\n try {\n await pendingTradingSetup;\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, 'HyperLiquidProvider.ping');\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 * @returns A promise that resolves when the operation completes.\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(\n ensureError(error, 'HyperLiquidProvider.getAvailableDexs'),\n {\n context: {\n name: 'HyperLiquidProvider.getAvailableDexs',\n data: { action: 'fetch_available_dexs' },\n },\n },\n );\n throw error;\n }\n }\n\n async fetchHistoricalCandles(options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData> {\n this.#clientService.ensureInitialized();\n const result = await this.#clientService.fetchHistoricalCandles(options);\n return (\n result ?? {\n symbol: options.symbol,\n interval: options.interval,\n candles: [],\n }\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 #getBuilderAddress(isTestnet: boolean): string {\n // || intentional: env vars default to '' which must fall through to the hardcoded default\n if (isTestnet) {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this.#builderAddressTestnet || BUILDER_FEE_CONFIG.TestnetBuilder;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this.#builderAddressMainnet || BUILDER_FEE_CONFIG.MainnetBuilder;\n }\n\n #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 GLOBAL cache to persist across provider reconnections\n * This prevents repeated signing requests for hardware wallets.\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 */\n async #ensureReferralSet(): Promise<void> {\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\n let userAddress: string;\n try {\n userAddress = await this.#walletService.getUserAddressWithDefault();\n } catch {\n return; // Can't proceed without address\n }\n\n if (userAddress.toLowerCase() === referrerAddress.toLowerCase()) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] User is builder, skipping',\n { network },\n );\n return;\n }\n\n // Check GLOBAL cache first\n const globalCached = PerpsSigningCache.getReferral(network, userAddress);\n if (globalCached?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Using global cache (prevents QR popup spam)',\n { network, success: globalCached.success },\n );\n return;\n }\n\n // Check if another provider is currently attempting this\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n return;\n }\n\n // Set global in-flight lock\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'referral',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock\n const recheckCache = PerpsSigningCache.getReferral(network, userAddress);\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Completed by another provider',\n { network },\n );\n completeInFlight();\n return;\n }\n\n const isReady = await this.#isReferralCodeReady();\n if (!isReady) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Builder referral not ready, skipping',\n { network },\n );\n completeInFlight();\n return; // Don't cache - retry when ready\n }\n\n // Check if user already has a referral on-chain\n const hasReferral = await this.#checkReferralSet();\n\n if (hasReferral) {\n // Already has referral on-chain\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Already has referral on-chain',\n { network },\n );\n } else {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Setting referral (will show signing request)',\n { network, referralCode: expectedReferralCode },\n );\n const result = await this.#setReferralCode();\n if (result) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Referral set successfully',\n { network },\n );\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: true,\n });\n } else {\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: false,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Failed, cached to prevent retries',\n { network },\n );\n }\n }\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache failure to prevent retries\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: false,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Error, cached to prevent retries',\n {\n network,\n error: ensureError(error, 'HyperLiquidProvider.ensureReferralSet')\n .message,\n },\n );\n completeInFlight();\n\n // Non-blocking: Log to Sentry but don't throw\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureReferralSet'),\n this.#getErrorContext('ensureReferralSet', {\n note: 'Referral setup failed (non-blocking), cached to prevent retries',\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 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, 'HyperLiquidProvider.isReferralCodeReady'),\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 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, 'HyperLiquidProvider.checkReferralSet'),\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 * @returns A promise that resolves to the boolean result.\n */\n 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, 'HyperLiquidProvider.setReferralCode'),\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"]}
1
+ {"version":3,"file":"HyperLiquidProvider.mjs","sourceRoot":"","sources":["../../src/providers/HyperLiquidProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAiB,WAAW,EAAE,wBAAwB;AAE7D,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAGpC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,UAAU,EACV,uBAAuB,EACvB,eAAe,EACf,kBAAkB,EAClB,8BAA8B,EAC9B,mBAAmB,EACnB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,WAAW,EACZ,2CAAuC;AACxC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,EACf,YA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;SACnD,CAAC,CACH,CAAC;QACF,gEAAgE;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,KAAK;IACH,IAAI,CAAC;QACH,MAAM,cAAc,GAAG,uBAAA,IAAI,0CAAe,CAAC,iBAAiB,EAAE,CAAC;QAC/D,MAAM,YAAY,GAAG,uBAAA,IAAI,4EAAiB,MAArB,IAAI,EACvB,uBAAA,IAAI,0CAAe,CAAC,aAAa,EAAE,CACpC,CAAC;QAEF,uBAAA,IAAI,iCAAM,CAAC,WAAW,CAAC,GAAG,CAAC,yCAAyC,EAAE;YACpE,IAAI,EAAE,YAAY;YAClB,OAAO,EAAE,uBAAA,IAAI,0CAAe,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;SACrE,CAAC,CAAC;QAEH,wBAAwB;QACxB,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC;YAC9C,IAAI,EAAE,YAAY;SACnB,CAAC,CAAC;QAEH,uBAAA,IAAI,iCAAM,CAAC,WAAW,CAAC,GAAG,CACxB,4CAA4C,EAC5C,MAAM,CACP,CAAC;QAEF,OAAO,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,uBAAA,IAAI,iCAAM,CAAC,MAAM,CAAC,KAAK,CACrB,WAAW,CAAC,KAAK,EAAE,qCAAqC,CAAC,EACzD,uBAAA,IAAI,4EAAiB,MAArB,IAAI,EAAkB,iBAAiB,EAAE;YACvC,IAAI,EAAE,uBAAA,IAAI,4EAAiB,MAArB,IAAI,EAAkB,uBAAA,IAAI,0CAAe,CAAC,aAAa,EAAE,CAAC;SACjE,CAAC,CACH,CAAC;QACF,2DAA2D;QAC3D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { CaipAccountId, hasProperty } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport type { CandlePeriod } from '../constants/chartConfig';\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 MAINNET_HIP3_CONFIG,\n REFERRAL_CONFIG,\n SPOT_ASSET_ID_OFFSET,\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} from '../constants/perpsConfig';\nimport { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes';\nimport {\n HyperLiquidClientService,\n WebSocketConnectionState,\n} from '../services/HyperLiquidClientService';\nimport { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService';\nimport { HyperLiquidWalletService } from '../services/HyperLiquidWalletService';\nimport {\n TradingReadinessCache,\n PerpsSigningCache,\n} from '../services/TradingReadinessCache';\nimport type {\n AccountState,\n AssetRoute,\n BatchCancelOrdersParams,\n CancelOrderParams,\n CancelOrderResult,\n CancelOrdersResult,\n CandleData,\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 GetOrFetchFillsParams,\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 ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n TransferBetweenDexsParams,\n TransferBetweenDexsResult,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n RawLedgerUpdate,\n} from '../types';\nimport type {\n SDKOrderParams,\n MetaResponse,\n PerpsAssetCtx,\n FrontendOrder,\n SpotMetaResponse,\n} from '../types/hyperliquid-types';\nimport type { PerpsControllerMessengerBase } from '../types/messenger';\nimport type { ExtendedAssetMeta, ExtendedPerpDex } from '../types/perps-types';\nimport { aggregateAccountStates } from '../utils/accountUtils';\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 {\n createStandaloneInfoClient,\n queryStandaloneClearinghouseStates,\n queryStandaloneOpenOrders,\n} from '../utils/standaloneInfoClient';\n// getStreamManagerInstance removed: use this.#deps.streamManager instead\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 current status.\n * @returns The result of the operation.\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 DexFetchFailureStep = 'metaAndAssetCtxs' | 'allMids';\n\ntype DexFetchResult = {\n dex: string | null;\n meta: MetaResponse | null;\n assetCtxs: PerpsAssetCtx[];\n allMids: Record<string, string>;\n success: boolean;\n failedStep?: DexFetchFailureStep;\n errorMessage?: string;\n};\n\ntype DexQueryResult<TResult> = {\n dex: string | null;\n data: TResult;\n};\n\ntype DexQueryResponse<TResult> = {\n results: DexQueryResult<TResult>[];\n failedDexs: { dex: string | null; error: Error }[];\n};\n\ntype CachedMarketDataSnapshot = {\n data: PerpsMarketData[];\n timestamp: number;\n contributingDexs: string[];\n failedDexs: string[];\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\ntype GetOrFetchPriceParams = {\n symbol: string;\n dexName: string | null;\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 readonly #deps: PerpsPlatformDependencies;\n\n // Service instances\n readonly #clientService: HyperLiquidClientService;\n\n readonly #walletService: HyperLiquidWalletService;\n\n readonly #subscriptionService: HyperLiquidSubscriptionService;\n\n // Asset mapping\n readonly #symbolToAssetId = new Map<string, number>();\n\n // Cache for user fee rates to avoid excessive API calls\n 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 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 readonly #cachedMetaByDex = new Map<string, MetaResponse>();\n\n // Last known-good market list for stale fallback when every enabled DEX fails in one fetch window.\n #cachedMarketDataWithPrices: CachedMarketDataSnapshot | null = null;\n\n // Session cache for spot metadata (contains USDC/USDH token info for HIP-3 collateral checks)\n // Pre-fetched in ensureReadyForTrading() to avoid API failures during order placement\n #cachedSpotMeta: SpotMetaResponse | null = null;\n\n // Cache for perpDexs data (deployerFeeScale for dynamic fee calculation)\n // TTL-based cache - fee scales rarely change\n #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 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 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 #ensureReadyPromise: Promise<void> | null = null;\n\n readonly #pendingBuilderFeeApprovals = new Map<string, Promise<void>>();\n\n // Pre-compiled patterns for fast filtering\n readonly #compiledAllowlistPatterns: CompiledMarketPattern[] = [];\n\n readonly #compiledBlocklistPatterns: CompiledMarketPattern[] = [];\n\n // Fee discount context for MetaMask reward discounts (in basis points)\n #userFeeDiscountBips?: number;\n\n // Feature flag configuration for HIP-3 market filtering\n readonly #hip3Enabled: boolean;\n\n readonly #allowlistMarkets: string[];\n\n readonly #blocklistMarkets: string[];\n\n #useDexAbstraction: boolean;\n\n // Cache for validated DEXs to avoid redundant perpDexs() API calls\n #cachedValidatedDexs: (string | null)[] | null = null;\n\n #cachedAllPerpDexs: ({ name: string } | null)[] | null = null;\n\n // True once DEX discovery has succeeded with real data (not a fallback).\n // When false, #ensureReadyPromise is reset after each init so the next\n // caller retries DEX discovery instead of reusing a degraded mapping.\n #dexDiscoveryComplete = false;\n\n // Pending promise to deduplicate concurrent getValidatedDexs() calls\n #pendingValidatedDexsPromise: Promise<(string | null)[]> | null = null;\n\n // Cache for USDC token ID from spot metadata\n #cachedUsdcTokenId?: string;\n\n // Error mappings from HyperLiquid API errors to standardized PERPS_ERROR_CODES\n 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 #clientsInitialized = false;\n\n // Promise-based lock to prevent race conditions in concurrent initialization\n #initializationPromise: Promise<void> | null = null;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n readonly #builderAddressTestnet?: string;\n\n readonly #builderAddressMainnet?: string;\n\n constructor(options: {\n isTestnet?: boolean;\n hip3Enabled?: boolean;\n allowlistMarkets?: string[];\n blocklistMarkets?: string[];\n useDexAbstraction?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger: PerpsControllerMessengerBase;\n initialAssetMapping?: [string, number][];\n builderAddressTestnet?: string;\n builderAddressMainnet?: string;\n }) {\n this.#deps = options.platformDependencies;\n this.#messenger = options.messenger;\n this.#builderAddressTestnet = options.builderAddressTestnet;\n this.#builderAddressMainnet = options.builderAddressMainnet;\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, {\n isTestnet,\n });\n this.#walletService = new HyperLiquidWalletService(\n this.#deps,\n this.#messenger,\n {\n isTestnet,\n },\n );\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 (invalid patterns are skipped)\n this.#compiledAllowlistPatterns = this.#compilePatternsSafely(\n this.#allowlistMarkets,\n 'allowlist',\n );\n this.#compiledBlocklistPatterns = this.#compilePatternsSafely(\n this.#blocklistMarkets,\n 'blocklist',\n );\n\n // Populate initial asset mapping if provided (used for DI in tests)\n if (options.initialAssetMapping) {\n for (const [symbol, assetId] of options.initialAssetMapping) {\n this.#symbolToAssetId.set(symbol, assetId);\n }\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 * Compile market patterns safely, skipping any that fail validation.\n * Prevents a single bad pattern from crashing the entire constructor.\n *\n * @param patterns - The array of patterns to validate.\n * @param listName - The name of the list for logging context.\n * @returns The result of the operation.\n */\n #compilePatternsSafely(\n patterns: string[],\n listName: string,\n ): CompiledMarketPattern[] {\n const compiled: CompiledMarketPattern[] = [];\n for (const pattern of patterns) {\n try {\n compiled.push({ pattern, matcher: compileMarketPattern(pattern) });\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, `HyperLiquidProvider.compilePatternsSafely`),\n this.#getErrorContext('compilePatternsSafely', { listName, pattern }),\n );\n }\n }\n return compiled;\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 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 (): Promise<void> => {\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 this.#deps.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 * IMPORTANT: Uses global singleton cache to prevent repeated signing requests\n * across provider reconnections (critical for hardware wallets).\n *\n * @private\n */\n async #ensureDexAbstractionEnabled(): Promise<void> {\n if (!this.#useDexAbstraction) {\n return; // Feature disabled\n }\n\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n\n // Check global cache first to avoid repeated signing requests\n // This is CRITICAL for hardware wallets to prevent QR popup spam\n const cachedStatus = TradingReadinessCache.get(network, userAddress);\n if (cachedStatus?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction already attempted (from global cache)',\n {\n user: userAddress,\n network,\n enabled: cachedStatus.enabled,\n note: 'Skipping to prevent repeated signing requests',\n },\n );\n return;\n }\n\n // Check if another provider instance is currently attempting this operation\n // This prevents concurrent signing attempts across providers during reconnection\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'dexAbstraction',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction in-flight, waiting...',\n { network, userAddress },\n );\n await inFlightPromise;\n return; // After waiting, the cache should be set by the other provider\n }\n\n // Set in-flight lock to prevent concurrent attempts\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'dexAbstraction',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock (another provider might have finished)\n const recheckCache = TradingReadinessCache.get(network, userAddress);\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction completed by another provider',\n { network, userAddress },\n );\n completeInFlight();\n return;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n\n // Check if already enabled on-chain (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 on-chain',\n { user: userAddress, network },\n );\n // Cache the enabled status to skip future checks\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n completeInFlight();\n return;\n }\n\n // Enable DEX abstraction (one-time, irreversible, requires signature)\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Enabling DEX abstraction (requires signature)',\n {\n user: userAddress,\n network,\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\n // Cache success to prevent re-attempts on reconnection\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureDexAbstractionEnabled] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache the attempt (even on failure) to prevent repeated signing requests\n // This is CRITICAL for hardware wallets - if user rejects, don't ask again\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: DEX abstraction failed, cached to prevent retries',\n {\n user: userAddress,\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureDexAbstractionEnabled',\n ).message,\n },\n );\n\n completeInFlight();\n\n // Don't blindly disable the flag on any error\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureDexAbstractionEnabled'),\n this.#getErrorContext('ensureDexAbstractionEnabled', {\n note: 'Could not enable DEX abstraction (may already be enabled, user rejected, or network error)',\n }),\n );\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 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 (): Promise<void> => {\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, or retry if DEX discovery previously failed\n if (this.#symbolToAssetId.size === 0 || !this.#dexDiscoveryComplete) {\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 // NOTE: Signing operations (DEX abstraction, builder fee, referral) are now DEFERRED\n // They are called on-demand in ensureReadyForTrading() when user attempts to trade\n // This prevents QR popups when just viewing the Perps section (critical for hardware wallets)\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 // or when DEX discovery was degraded so the next caller retries.\n await this.#ensureReadyPromise;\n if (!this.#dexDiscoveryComplete) {\n // DEX discovery failed transiently — reset so next call retries.\n // Trading still works (main DEX mapping is populated), but HIP-3 markets\n // will be re-discovered on the next #ensureReady() call.\n this.#ensureReadyPromise = null;\n }\n this.#deps.debugLogger.log('[ensureReady] Initialization complete');\n }\n\n /**\n * Ensure provider is ready for TRADING operations (signing required)\n *\n * This method performs additional setup that requires user signatures:\n * - DEX abstraction enablement (for HIP-3 auto-transfers)\n * - Builder fee approval (required for orders)\n * - Referral code setup (attribution)\n *\n * These operations are DEFERRED from ensureReady() to avoid QR popup spam\n * when users are just viewing the Perps section (critical for hardware wallets).\n *\n * Call this method before any trading operation (placeOrder, cancelOrder, etc.)\n */\n #tradingSetupPromise: Promise<void> | null = null;\n\n #tradingSetupComplete = false;\n\n async #ensureReadyForTrading(): Promise<void> {\n // First ensure basic initialization is complete\n await this.#ensureReady();\n\n // If trading setup already complete, return immediately\n if (this.#tradingSetupComplete) {\n return;\n }\n\n // If trading setup is in progress, wait for it\n if (this.#tradingSetupPromise) {\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Waiting for in-progress trading setup',\n );\n await this.#tradingSetupPromise;\n return;\n }\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Starting trading setup (may require signatures)',\n );\n\n this.#tradingSetupPromise = (async (): Promise<void> => {\n // Pre-fetch spotMeta for HIP-3 operations (non-blocking if it fails)\n // This ensures token info (USDC/USDH indices) is available during order placement\n if (this.#hip3Enabled) {\n try {\n await this.#getCachedSpotMeta();\n } catch (error) {\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] spotMeta pre-fetch failed, will retry when needed',\n error,\n );\n // Don't throw - spotMeta will be fetched on-demand if needed\n }\n }\n\n // Attempt to enable native balance abstraction\n await this.#ensureDexAbstractionEnabled();\n\n // Set up builder fee approval\n try {\n await this.#ensureBuilderFeeApproval();\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Builder fee approval failed',\n error,\n );\n // Don't throw - let trading continue, will fail with clear error if needed\n }\n\n // Set up referral code\n await this.#ensureReferralSet();\n\n // Only mark complete if keyring was unlocked (signing could actually happen)\n if (this.#walletService.isKeyringUnlocked()) {\n this.#tradingSetupComplete = true;\n }\n })();\n\n try {\n await this.#tradingSetupPromise;\n } finally {\n this.#tradingSetupPromise = null;\n }\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Trading setup complete',\n );\n }\n\n /**\n * Get current price for a symbol using WebSocket cache first, REST API fallback\n * Centralizes the price fetching pattern used across multiple methods\n *\n * @param params - Parameters for fetching price\n * @param params.symbol - The symbol to get price for\n * @param params.dexName - Optional DEX name for REST API fallback\n * @returns The current price as a number\n * @throws Error if no price is available\n */\n async #getOrFetchPrice(params: GetOrFetchPriceParams): Promise<number> {\n const { symbol, dexName } = params;\n\n // OPTIMIZATION: Use WebSocket price cache first (0 weight), fall back to REST (2 weight)\n const cachedPrice = this.#subscriptionService.getCachedPrice(symbol);\n\n if (cachedPrice) {\n const price = parseFloat(cachedPrice);\n // Validate cached price: must be positive and finite\n // Covers zero, negative, NaN, and Infinity in one check\n if (price <= 0 || !isFinite(price)) {\n this.#deps.debugLogger.log(\n 'WebSocket cached price invalid for getOrFetchPrice, falling back to REST',\n { symbol, cachedPrice, parsedPrice: price },\n );\n // Fall through to REST API fallback\n } else {\n this.#deps.debugLogger.log('Using WebSocket cached price', {\n symbol,\n price,\n });\n return price;\n }\n }\n\n // Fallback to REST API if cache miss\n this.#deps.debugLogger.log(\n 'Price cache miss for getOrFetchPrice, falling back to REST allMids',\n { symbol },\n );\n const infoClient = this.#clientService.getInfoClient();\n const mids = await infoClient.allMids(\n dexName ? { dex: dexName } : undefined,\n );\n const price = parseFloat(mids[symbol] || '0');\n\n // Validate REST price: must be positive and finite\n if (price <= 0 || !isFinite(price)) {\n throw new Error(`Invalid price for ${symbol}: ${price}`);\n }\n\n return price;\n }\n\n /**\n * Get fills using WebSocket cache first, falling back to REST API\n * OPTIMIZATION: Uses cached fills when available (0 API weight), only calls REST on cache miss\n *\n * Cache limitation: WebSocket cache is limited to ~100 most recent fills.\n * For historical data (e.g., position-opening fills from months ago), use getOrderFills directly.\n *\n * @param params - Optional filter parameters (startTime, symbol)\n * @returns Array of order fills\n */\n public async getOrFetchFills(\n params?: GetOrFetchFillsParams,\n ): Promise<OrderFill[]> {\n // Check WebSocket cache first (0 API weight)\n const cachedFills = this.#subscriptionService.getFillsCacheIfInitialized();\n\n if (cachedFills !== null) {\n this.#deps.debugLogger.log('Using WebSocket cached fills', {\n count: cachedFills.length,\n params,\n });\n return this.#filterFills(cachedFills, params);\n }\n\n // Fallback to REST API when cache not initialized\n this.#deps.debugLogger.log(\n 'Fills cache miss for getOrFetchFills, falling back to REST',\n { params },\n );\n const restFills = await this.getOrderFills(params);\n // Apply symbol filter to REST results for consistent API behavior\n // Note: getOrderFills doesn't support symbol filtering natively\n return this.#filterFills(restFills, params);\n }\n\n /**\n * Filter fills array by optional startTime and symbol parameters\n *\n * @param fills - Array of fills to filter\n * @param params - Optional filter parameters\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.symbol - The trading pair symbol.\n * @returns Filtered fills array\n */\n #filterFills(\n fills: OrderFill[],\n params?: { startTime?: number; symbol?: string },\n ): OrderFill[] {\n if (!params) {\n return fills;\n }\n\n return fills.filter((fill) => {\n if (params.startTime && fill.timestamp < params.startTime) {\n return false;\n }\n if (params.symbol && fill.symbol !== params.symbol) {\n return false;\n }\n return true;\n });\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 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, 'HyperLiquidProvider.getAllAvailableDexs'),\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 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 * @returns A promise that resolves to the result.\n */\n 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 // debugLogger not logger.error: this is a handled transient failure — the app\n // recovers to main DEX via return [null]. Sending to Sentry as error() is noise.\n this.#deps.debugLogger.log(\n '[fetchValidatedDexsInternal] perpDexs() call failed, falling back to main DEX',\n {\n error: String(error),\n ...this.#getErrorContext('getValidatedDexs.perpDexs'),\n },\n );\n // Do not cache — transient error, allow retry on next call\n return [null];\n }\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 // Do not cache — may be transient, allow retry on next call\n return [null];\n }\n\n // Cache for buildAssetMapping() to avoid duplicate call\n this.#cachedAllPerpDexs = allDexs;\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 } else {\n // Mainnet-specific filtering: Extract allowed DEXs from the allowlist patterns\n // This reduces WebSocket subscription overhead dynamically based on feature flags\n const { AutoDiscoverAll } = MAINNET_HIP3_CONFIG;\n\n if (!AutoDiscoverAll) {\n // Extract unique DEX names from allowlist patterns\n // Patterns like \"xyz:*\", \"xyz:TSLA\", or \"xyz\" all indicate DEX \"xyz\"\n const allowedDexsFromAllowlist = this.#extractDexsFromAllowlist();\n\n if (allowedDexsFromAllowlist.length === 0) {\n // No HIP-3 DEXs in allowlist - main DEX only\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - using main DEX only (no HIP-3 DEXs in allowlist)',\n {\n availableHip3Dexs: availableHip3Dexs.length,\n allowlistMarkets: this.#allowlistMarkets,\n },\n );\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n // Filter to DEXs that are both available AND in the allowlist\n const filteredDexs = availableHip3Dexs.filter((dex) =>\n allowedDexsFromAllowlist.includes(dex),\n );\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - filtered to allowlist DEXs',\n {\n allowedDexsFromAllowlist,\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\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Mainnet - AUTO_DISCOVER_ALL enabled, using all DEXs',\n { totalDexCount: availableHip3Dexs.length + 1 },\n );\n }\n\n // Fallback: Return all DEXs (when AUTO_DISCOVER_ALL is true)\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 * Extract unique DEX names from allowlist market patterns\n * Patterns can be: \"xyz:*\" (wildcard), \"xyz:TSLA\" (exact), or \"xyz\" (DEX shorthand)\n *\n * @returns Array of unique DEX names from the allowlist\n */\n #extractDexsFromAllowlist(): string[] {\n if (this.#allowlistMarkets.length === 0) {\n return [];\n }\n\n const dexNames = new Set<string>();\n\n for (const pattern of this.#allowlistMarkets) {\n // Pattern formats:\n // - \"xyz:*\" -> DEX \"xyz\" (wildcard)\n // - \"xyz:TSLA\" -> DEX \"xyz\" (exact match)\n // - \"xyz\" -> DEX \"xyz\" (shorthand)\n const colonIndex = pattern.indexOf(':');\n if (colonIndex > 0) {\n // Has colon - extract DEX prefix\n const dex = pattern.substring(0, colonIndex);\n dexNames.add(dex);\n } else if (pattern.length > 0 && !pattern.includes('*')) {\n // No colon and not a wildcard - could be DEX shorthand\n // Only add if it looks like a valid DEX name (lowercase alphanumeric)\n if (/^[a-z][a-z0-9]*$/iu.test(pattern)) {\n dexNames.add(pattern.toLowerCase());\n }\n }\n }\n\n return Array.from(dexNames);\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 - The operation parameters.\n * @param params.dexName - DEX name (null for main DEX).\n * @param params.skipCache - If true, bypass cache and fetch fresh data.\n * @returns MetaResponse with universe data.\n * @throws Error if API returns invalid data\n */\n 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 // Pass dex only for HIP-3 DEXs; omit for main DEX (empty string).\n // Testnet API returns null when dex=\"\" is explicitly sent.\n const meta = await infoClient.meta(dexKey ? { dex: dexKey } : undefined);\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 await this.#backfillAssetMapForDex(dexName, 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 * Backfill the asset ID map for a single DEX from a fresh meta response.\n * Used to repair partial asset mapping when an individual DEX becomes available later.\n *\n * @param dex - DEX name (null for main DEX).\n * @param meta - Meta response containing the DEX universe.\n * @returns True if the mapping was rebuilt for the DEX.\n */\n async #backfillAssetMapForDex(\n dex: string | null,\n meta: MetaResponse,\n ): Promise<boolean> {\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n return false;\n }\n\n if (!this.#cachedAllPerpDexs) {\n try {\n await this.#getValidatedDexs();\n } catch (error) {\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Unable to refresh validated DEXs before rebuilding asset map',\n {\n dex: dex ?? 'main',\n error: ensureError(\n error,\n 'HyperLiquidProvider.backfillAssetMapForDex',\n ).message,\n },\n );\n }\n }\n\n const allPerpDexs = this.#cachedAllPerpDexs ?? [null];\n const perpDexIndex = allPerpDexs.findIndex((entry) => {\n if (dex === null) {\n return entry === null;\n }\n return entry !== null && entry.name === dex;\n });\n\n if (perpDexIndex === -1) {\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Could not find perpDexIndex for DEX',\n { dex: dex ?? 'main' },\n );\n return false;\n }\n\n const { symbolToAssetId } = buildAssetMapping({\n metaUniverse: meta.universe,\n dex,\n perpDexIndex,\n });\n\n symbolToAssetId.forEach((assetId, coin) => {\n this.#symbolToAssetId.set(coin, assetId);\n });\n\n this.#deps.debugLogger.log(\n '[backfillAssetMapForDex] Rebuilt asset mapping for DEX',\n {\n dex: dex ?? 'main',\n dexAssetCount: symbolToAssetId.size,\n totalAssetCount: this.#symbolToAssetId.size,\n },\n );\n\n return symbolToAssetId.size > 0;\n }\n\n /**\n * Resolve an asset ID, repairing the DEX-specific map when meta is available but the map is stale.\n *\n * @param params - Resolution parameters.\n * @param params.symbol - Asset symbol to resolve.\n * @param params.dexName - DEX name (null for main DEX).\n * @param params.meta - Optional pre-fetched meta for the DEX.\n * @returns The asset ID.\n */\n async #getAssetIdWithRepair(params: {\n symbol: string;\n dexName: string | null;\n meta?: MetaResponse;\n }): Promise<number> {\n const { symbol, dexName } = params;\n const existingAssetId = this.#symbolToAssetId.get(symbol);\n\n if (existingAssetId !== undefined) {\n return existingAssetId;\n }\n\n const meta =\n params.meta ?? (await this.#getCachedMeta({ dexName: dexName ?? null }));\n const assetExistsInMeta = meta.universe.some(\n (asset) => asset.name === symbol,\n );\n\n if (assetExistsInMeta) {\n await this.#backfillAssetMapForDex(dexName, meta);\n const repairedAssetId = this.#symbolToAssetId.get(symbol);\n if (repairedAssetId !== undefined) {\n return repairedAssetId;\n }\n }\n\n this.#deps.debugLogger.log('Asset ID lookup failed', {\n requestedCoin: symbol,\n dexName: dexName ?? 'main',\n mapSize: this.#symbolToAssetId.size,\n mapContainsAsset: this.#symbolToAssetId.has(symbol),\n assetExistsInMeta,\n allKeys: Array.from(this.#symbolToAssetId.keys()).slice(0, 20),\n });\n\n throw new Error(`Asset ID not found for ${symbol}`);\n }\n\n /**\n * Fetch spot metadata with session-based caching\n * Contains token info (USDC, USDH indices) needed for HIP-3 collateral checks\n * Pre-fetched in ensureReadyForTrading() to ensure availability during order placement\n *\n * @returns SpotMetaResponse with tokens and universe data\n */\n async #getCachedSpotMeta(): Promise<SpotMetaResponse> {\n if (this.#cachedSpotMeta) {\n this.#deps.debugLogger.log('[getCachedSpotMeta] Using cached spotMeta', {\n tokensCount: this.#cachedSpotMeta.tokens.length,\n universeCount: this.#cachedSpotMeta.universe.length,\n });\n return this.#cachedSpotMeta;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n this.#cachedSpotMeta = spotMeta;\n this.#deps.debugLogger.log(\n '[getCachedSpotMeta] Fetched and cached spotMeta',\n {\n tokensCount: spotMeta.tokens.length,\n universeCount: spotMeta.universe.length,\n },\n );\n\n return spotMeta;\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 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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.assetSymbol - The asset symbol.\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees#fee-formula-for-developers\n * @returns The result of the operation.\n */\n 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(\n error,\n 'HyperLiquidProvider.calculateHip3FeeMultiplier',\n ).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 #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 - The operation parameters.\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 * @returns Array of MarketInfo objects.\n */\n 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 * @returns A promise that resolves to the string result.\n */\n async #getUsdcTokenId(): Promise<string> {\n if (this.#cachedUsdcTokenId) {\n return this.#cachedUsdcTokenId;\n }\n\n const spotMeta = await this.#getCachedSpotMeta();\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 - The DEX identifier (empty string for main DEX).\n * @returns A promise that resolves to the boolean result.\n */\n async #isUsdhCollateralDex(dexName: string): Promise<boolean> {\n const meta = await this.#getCachedMeta({ dexName });\n const spotMeta = await this.#getCachedSpotMeta();\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 * @returns A promise that resolves to the numeric result.\n */\n 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 * @returns A promise that resolves to the numeric result.\n */\n 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 - The amount value.\n * @returns A promise that resolves to the result.\n */\n 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 = ensureError(\n error,\n 'HyperLiquidProvider.transferUSDCToPerps',\n ).message;\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 - The amount value.\n * @returns A promise that resolves to the result.\n */\n async #swapUsdcToUsdh(\n amount: number,\n ): Promise<{ success: boolean; filledSize?: number; error?: string }> {\n const spotMeta = await this.#getCachedSpotMeta();\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 = SPOT_ASSET_ID_OFFSET + 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 infoClient = this.#clientService.getInfoClient();\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) && hasProperty(status, 'error')) {\n return { success: false, error: String(status.error) };\n }\n\n // Note: `in` narrows the HyperLiquid SDK discriminated union to the\n // branch that has `filled`; `hasProperty` only narrows the key and\n // types `status.filled` as `unknown`, which loses access to `.totalSz`.\n /* eslint-disable no-restricted-syntax */\n const filledSize =\n isStatusObject(status) && 'filled' in status\n ? parseFloat(status.filled?.totalSz ?? '0')\n : 0;\n /* eslint-enable no-restricted-syntax */\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 = ensureError(\n error,\n 'HyperLiquidProvider.swapUSDCToUSDH',\n ).message;\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 - The DEX identifier (empty string for main DEX).\n * @param requiredMargin - The required margin amount.\n */\n async #ensureUsdhCollateralForOrder(\n dexName: string,\n requiredMargin: number,\n ): Promise<void> {\n const spotUsdhBalance = await this.#getSpotUsdhBalance();\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Checking USDH collateral',\n {\n dexName,\n requiredMargin,\n spotUsdhBalance,\n },\n );\n\n if (spotUsdhBalance >= requiredMargin) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Sufficient USDH in spot',\n );\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(\n 'HyperLiquidProvider: USDH collateral acquired',\n {\n dexName,\n filledSize: swapResult.filledSize,\n },\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 async #buildAssetMapping(): Promise<void> {\n // Get feature-flag-validated DEXs to map (respects hip3Enabled and enabledDexs)\n let dexsToMap: (string | null)[];\n try {\n dexsToMap = await this.#getValidatedDexs();\n } catch (dexError) {\n // If getValidatedDexs fails, fall back to main DEX only to keep the provider\n // functional. Without this, a transient perpDexs() failure would permanently\n // brick #ensureReady via the cached rejected promise.\n // Do not set #cachedAllPerpDexs or #cachedValidatedDexs here — leave them null\n // so #getValidatedDexs retries on the next call (same as #fetchValidatedDexsInternal).\n this.#deps.debugLogger.log(\n '[buildAssetMapping] getValidatedDexs failed, falling back to main DEX',\n { error: String(dexError) },\n );\n dexsToMap = [null];\n }\n\n // Local fallback only — never write [null] into #cachedAllPerpDexs here.\n // That cache is owned exclusively by #fetchValidatedDexsInternal; writing a\n // fallback here would prevent subsequent callers from retrying perpDexs().\n const allPerpDexs = this.#cachedAllPerpDexs ?? [null];\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 let dexDiscoveryComplete = this.#cachedValidatedDexs !== null;\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 dexDiscoveryComplete = false;\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 dexDiscoveryComplete = false;\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 } else {\n dexDiscoveryComplete = false;\n }\n });\n\n this.#dexDiscoveryComplete = dexDiscoveryComplete;\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 * @example\n * ```typescript\n * const results = await this.#queryUserDataAcrossDexs(\n * { user: userAddress },\n * (p) => infoClient.clearinghouseState(p)\n * );\n * ```\n */\n async #queryUserDataAcrossDexs<\n TParams extends Record<string, unknown>,\n TResult,\n >(\n baseParams: TParams,\n queryFn: (params: TParams & { dex?: string }) => Promise<TResult>,\n ): Promise<DexQueryResponse<TResult>> {\n const enabledDexs = await this.#getValidatedDexs();\n\n const settledResults = await Promise.allSettled(\n enabledDexs.map(async (dex) => {\n const params = dex\n ? ({ ...baseParams, dex } as TParams & { dex: string })\n : (baseParams as TParams & { dex?: string });\n return queryFn(params);\n }),\n );\n\n const results: DexQueryResult<TResult>[] = [];\n const failedDexs: DexQueryResponse<TResult>['failedDexs'] = [];\n\n settledResults.forEach((result, index) => {\n const dex = enabledDexs[index];\n if (result.status === 'fulfilled') {\n results.push({ dex, data: result.value });\n return;\n }\n\n failedDexs.push({\n dex,\n error: ensureError(\n result.reason,\n 'HyperLiquidProvider.queryUserDataAcrossDexs',\n ),\n });\n });\n\n return { results, failedDexs };\n }\n\n /**\n * Map HyperLiquid API errors to standardized PERPS_ERROR_CODES\n *\n * @param error - The error that occurred.\n * @returns The result of the operation.\n */\n #mapError(error: unknown): Error {\n const { message } = ensureError(error, 'HyperLiquidProvider.mapError');\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 ensureError(error, 'HyperLiquidProvider.mapError');\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 * @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 #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 - The operation parameters.\n * @returns The result of the operation.\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 - The operation parameters.\n * @returns The result of the operation.\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 * @returns Current max fee rate or null if not approved\n */\n async #checkBuilderFeeApproval(): Promise<number | null> {\n const infoClient = this.#clientService.getInfoClient();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const builder = this.#getBuilderAddress(\n this.#clientService.isTestnetMode(),\n );\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: Uses GLOBAL cache to persist across provider reconnections\n * This prevents repeated signing requests for hardware wallets.\n *\n * Note: This is network-specific - testnet and mainnet have separate builder fee states\n */\n 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 const cacheKey = this.#getCacheKey(network, userAddress);\n\n // Check GLOBAL cache first to avoid repeated signing requests across reconnections\n // This is CRITICAL for hardware wallets to prevent QR popup spam\n const globalCached = PerpsSigningCache.getBuilderFee(network, userAddress);\n if (globalCached?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Using global cache (prevents QR popup spam)',\n { network, success: globalCached.success },\n );\n if (globalCached.success) {\n this.#builderFeeCheckCache.set(cacheKey, true);\n }\n return;\n }\n\n // Check if another provider instance is currently attempting this operation\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'builderFee',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n return;\n }\n\n // Set global in-flight lock\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'builderFee',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock\n const recheckCache = PerpsSigningCache.getBuilderFee(\n network,\n userAddress,\n );\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Completed by another provider',\n { network },\n );\n completeInFlight();\n return;\n }\n\n const { isApproved, requiredDecimal } =\n await this.#checkBuilderFeeStatus();\n\n if (isApproved) {\n // User already has approval on-chain\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#builderFeeCheckCache.set(cacheKey, true);\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Already approved on-chain',\n { network },\n );\n } else {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval required (will show signing request)',\n { builder: builderAddress, requiredDecimal },\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 // Cache success in BOTH global and instance caches\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#builderFeeCheckCache.set(cacheKey, true);\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Approval successful',\n {\n builder: builderAddress,\n maxFeeRate,\n },\n );\n }\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache failure to prevent retries\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: false,\n });\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Failed, cached to prevent retries',\n {\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureBuilderFeeApproval',\n ).message,\n },\n );\n\n completeInFlight();\n throw error;\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 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 async #getBalanceForDex(params: { dex: string | null }): 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 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 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 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 - The operation parameters.\n * @param params.symbol - The trading pair symbol.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.positionSize - The position size value.\n * @param params.orderPrice - The order price value.\n * @param params.leverage - The leverage multiplier.\n * @param params.isBuy - Whether this is a buy order.\n * @private\n * @returns The result of the operation.\n */\n 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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.transferInfo - The transfer information.\n * @param params.transferInfo.amount - The amount value.\n * @param params.transferInfo.sourceDex - The source DEX for the transfer.\n * @private\n */\n 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(\n rebalanceError,\n 'HyperLiquidProvider.placeOrder:autoRebalance',\n ),\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(\n balanceCheckError,\n 'HyperLiquidProvider.placeOrder:postOrderBalanceCheck',\n ),\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 - The operation parameters.\n * @param params.dexName - The DEX identifier (empty string for main DEX).\n * @param params.transferInfo - The transfer information.\n * @param params.transferInfo.amount - The amount value.\n * @param params.transferInfo.sourceDex - The source DEX for the transfer.\n * @private\n */\n 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, 'HyperLiquidProvider.placeOrder:rollback'),\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 - The operation parameters.\n * @throws Error if validation fails\n */\n async #validateOrderBeforePlacement(params: OrderParams): 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async #getAssetInfo(params: GetAssetInfoParams): Promise<GetAssetInfoResult> {\n const { symbol, dexName } = params;\n\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 currentPrice = await this.#getOrFetchPrice({\n symbol,\n dexName: dexName ?? null,\n });\n\n return { assetInfo, currentPrice, meta };\n }\n\n /**\n * Prepares asset for trading by updating leverage if specified\n *\n * @param params - The operation parameters.\n */\n 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n 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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n 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 // Note: `in` narrows the HyperLiquid SDK discriminated union to the\n // branch that has the property; `hasProperty` types the property as\n // `unknown`, losing downstream access to `.oid`, `.totalSz`, `.avgPx`.\n /* eslint-disable no-restricted-syntax */\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 /* eslint-enable no-restricted-syntax */\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 - The operation parameters.\n * @returns The result of the operation.\n */\n #handleOrderError(params: HandleOrderErrorParams): OrderResult {\n const { error, symbol, orderType, isBuy } = params;\n\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.handleOrderError'),\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 * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\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, meta } = 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 = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName,\n meta,\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 = ensureError(\n error,\n 'HyperLiquidProvider.placeOrder',\n ).message;\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 - The operation parameters.\n * @param params.orderId - The order ID to modify\n * @param params.newOrder - New order parameters (price, size, etc.)\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\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 meta = await this.#getCachedMeta({ 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 = await this.#getOrFetchPrice({\n symbol: params.newOrder.symbol,\n dexName: dexName ?? null,\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 = await this.#getAssetIdWithRepair({\n symbol: params.newOrder.symbol,\n dexName,\n meta,\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, 'HyperLiquidProvider.editOrder'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n const exchangeClient = this.#clientService.getExchangeClient();\n const asset = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName: parseAssetName(params.symbol).dex,\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, 'HyperLiquidProvider.cancelOrder'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n const exchangeClient = this.#clientService.getExchangeClient();\n\n // Map orders to SDK format and validate coins\n const cancelRequests = await Promise.all(\n params.map(async (order) => {\n const asset = await this.#getAssetIdWithRepair({\n symbol: order.symbol,\n dexName: parseAssetName(order.symbol).dex,\n });\n return {\n a: asset,\n o: parseInt(order.orderId, 10),\n };\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 ? undefined\n : (status as { error: string }).error,\n })),\n };\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.cancelOrders'),\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 // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Get all current positions from cache (avoids 429 rate limiting)\n const positions = await this.getPositions();\n\n // Filter positions based on params\n positionsToClose =\n params.closeAll === true ||\n !params.symbols ||\n 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 for order submission\n const exchangeClient = this.#clientService.getExchangeClient();\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 = await this.#getAssetIdWithRepair({\n symbol: position.symbol,\n dexName,\n meta,\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 const currentPrice = await this.#getOrFetchPrice({\n symbol: position.symbol,\n dexName: dexName ?? null,\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) &&\n (hasProperty(stat, 'filled') || hasProperty(stat, 'resting')),\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 (hasProperty(status, 'filled') || hasProperty(status, 'resting'));\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 (hasProperty(status, 'filled') || hasProperty(status, 'resting')),\n error:\n isStatusObject(status) && hasProperty(status, 'error')\n ? String(status.error)\n : undefined,\n })),\n };\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.closePositions'),\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 - The operation parameters.\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 * @returns A promise that resolves to the result.\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 {\n symbol,\n takeProfitPrice,\n stopLossPrice,\n position: livePosition,\n } = params;\n\n // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Use live position (from WebSocket) if available, otherwise fetch via REST\n // Preferring WebSocket data avoids rate limiting issues with the REST API\n let position: Position | undefined = livePosition;\n\n if (position) {\n this.#deps.debugLogger.log('Using live position from WebSocket', {\n symbol: position.symbol,\n size: position.size,\n });\n } else {\n // Fallback: fetch positions via REST API (legacy behavior)\n this.#deps.debugLogger.log(\n 'No live position passed, falling back to REST API fetch',\n );\n let positions: Position[];\n try {\n positions = await this.getPositions({ skipCache: true });\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'),\n this.#getErrorContext('updatePositionTPSL > getPositions', {\n symbol,\n }),\n );\n throw error;\n }\n position = positions.find((pos) => pos.symbol === symbol);\n }\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 // Get clients for API calls (ensureReady already called at method start)\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 // Cancel existing TP/SL orders for this position\n // OPTIMIZATION: Use WebSocket cache first (0 weight), fall back to single-DEX REST (20 weight)\n // Previously: queryUserDataAcrossDexs queried ALL DEXs (20 weight × N DEXs = 40+ weight)\n const assetId = await this.#getAssetIdWithRepair({\n symbol,\n dexName,\n });\n\n let cancelRequests: { a: number; o: number }[] = [];\n\n // Use atomic getter to prevent race condition between check and get\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n\n if (cachedOrders === null) {\n // Fallback: Query only the specific DEX (20 weight instead of 40+)\n this.#deps.debugLogger.log(\n 'WebSocket cache not initialized, falling back to single-DEX REST query',\n { dex: dexName ?? 'main' },\n );\n\n const orders = await infoClient.frontendOpenOrders({\n user: userAddress,\n dex: dexName ?? undefined,\n });\n\n // Filter using raw SDK response properties\n const tpslOrders = orders.filter(\n (order) =>\n order.coin === symbol &&\n order.reduceOnly &&\n order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&\n order.isTrigger &&\n (order.orderType.includes('Take Profit') ||\n order.orderType.includes('Stop')),\n );\n\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: order.oid,\n }));\n } else {\n // WebSocket cache available - use it (no API call, 0 weight)\n this.#deps.debugLogger.log(\n 'Using WebSocket cache for TP/SL orders lookup',\n { cachedOrdersCount: cachedOrders.length },\n );\n\n // Filter using normalized Order type properties, matching the REST fallback criteria:\n // - symbol matches\n // - isTrigger === true\n // - reduceOnly === true\n // - isPositionTpsl matches the configured mode (only cancel position-bound TP/SL,\n // not normalTpsl children that belong to pending limit orders)\n // - detailedOrderType contains 'Take Profit' or 'Stop'\n const tpslOrders = cachedOrders.filter(\n (order) =>\n order.symbol === symbol &&\n order.reduceOnly === true &&\n order.isTrigger === true &&\n order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&\n order.detailedOrderType &&\n (order.detailedOrderType.includes('Take Profit') ||\n order.detailedOrderType.includes('Stop')),\n );\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: parseInt(order.orderId, 10),\n }));\n }\n\n if (cancelRequests.length > 0) {\n this.#deps.debugLogger.log(\n `Canceling ${cancelRequests.length} existing TP/SL orders for ${symbol}`,\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 // assetId already validated above when building cancelRequests\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, 'HyperLiquidProvider.updatePositionTPSL'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async closePosition(params: ClosePositionParams): Promise<OrderResult> {\n try {\n this.#deps.debugLogger.log('Closing position:', params);\n\n // Ensure provider is ready for trading (includes signing operations)\n await this.#ensureReadyForTrading();\n\n // Use provided position (from WebSocket) or fetch from cache\n // This avoids unnecessary API calls and prevents 429 rate limiting\n let { position } = params;\n if (!position) {\n const positions = await this.getPositions();\n position = positions.find((pos) => pos.symbol === params.symbol);\n }\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, 'HyperLiquidProvider.closePosition'),\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 * @param params.providerId - Optional provider identifier (ignored, always uses HyperLiquid)\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: UpdateMarginParams): 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 (from cache to avoid 429 rate limiting)\n const positions = await this.getPositions();\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 = await this.#getAssetIdWithRepair({\n symbol,\n dexName: parseAssetName(symbol).dex,\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 const safeError = ensureError(error, 'HyperLiquidProvider.updateMargin');\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext('updateMargin', {\n symbol: params.symbol,\n amount: params.amount,\n }),\n );\n return {\n success: false,\n error: safeError.message,\n };\n }\n }\n\n /**\n * Get validated DEXs for standalone mode using a standalone InfoClient.\n * Similar to getValidatedDexs() but doesn't require full initialization.\n * Reuses cachedValidatedDexs to avoid redundant perpDexs() calls.\n *\n * @returns A promise that resolves to the result.\n */\n async #getStandaloneValidatedDexs(): Promise<(string | null)[]> {\n // Return cached result if available\n if (this.#cachedValidatedDexs !== null) {\n return this.#cachedValidatedDexs;\n }\n\n // Kill switch: HIP-3 disabled, return main DEX only\n if (!this.#hip3Enabled) {\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n // Fetch available DEXs via standalone client\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n let allDexs;\n try {\n allDexs = await standaloneInfoClient.perpDexs();\n } catch {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone perpDexs() failed, falling back to main DEX only',\n );\n return [null];\n }\n\n // Validate response\n if (!allDexs || !Array.isArray(allDexs)) {\n return [null];\n }\n\n // Populate #cachedAllPerpDexs so buildAssetMapping can compute perpDexIndex.\n // Without this, getValidatedDexs returns from #cachedValidatedDexs (string names)\n // but #cachedAllPerpDexs (raw objects for index computation) stays null,\n // causing \"Could not find perpDexIndex for DEX xyz\" failures.\n this.#cachedAllPerpDexs = allDexs;\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 // Filter by allowlist patterns (same logic as fetchValidatedDexsInternal)\n const allowedDexsFromAllowlist = this.#extractDexsFromAllowlist();\n if (allowedDexsFromAllowlist.length === 0) {\n this.#cachedValidatedDexs = [null];\n return this.#cachedValidatedDexs;\n }\n\n const filteredDexs = availableHip3Dexs.filter((dex) =>\n allowedDexsFromAllowlist.includes(dex),\n );\n\n this.#cachedValidatedDexs = [null, ...filteredDexs];\n return this.#cachedValidatedDexs;\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n try {\n // Path 0: Standalone mode for lightweight position 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 showing positions on token details page\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting positions in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const results = await queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Combine and filter positions from all DEXs\n // Skip TP/SL lookup (would require additional API call)\n const positions = results.flatMap((state) =>\n state.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos)),\n );\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone positions fetched',\n { count: positions.length },\n );\n\n return positions;\n }\n\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 [stateResponse, orderResponse] = 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 const { results: stateResults, failedDexs: failedStateDexs } =\n stateResponse;\n const { results: orderResults, failedDexs: failedOrderDexs } =\n orderResponse;\n\n if (failedStateDexs.length > 0 || failedOrderDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Partial multi-DEX position fetch completed with failures',\n {\n failedStateDexs: failedStateDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n failedOrderDexs: failedOrderDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\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 // Only match position-bound TP/SL orders when UsePositionBoundTpsl is enabled,\n // to avoid picking up normalTpsl children from pending limit orders\n const positionOrders = allOrders.filter(\n (order) =>\n order.coin === position.symbol &&\n order.isTrigger &&\n order.reduceOnly &&\n order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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:', {\n count: rawFills?.length ?? 0,\n });\n\n // Start fetching historical orders in parallel with fill transformation.\n // The fills API does not return order type, so we cross-reference\n // with historical orders to enable TP/SL pill rendering in activity.\n const historicalOrdersPromise = (\n infoClient.historicalOrders?.({ user: userAddress }) ??\n Promise.resolve(null)\n ).catch((enrichError: unknown) => {\n this.#deps.debugLogger.log(\n 'Warning: failed to enrich fills with order types:',\n enrichError,\n );\n return null;\n });\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 // Enrich fills with detailedOrderType from historical orders\n // Wrapped in its own try/catch so a malformed order never discards fetched fills\n try {\n const rawOrders = await historicalOrdersPromise;\n if (rawOrders) {\n const orderTypeByOid = new Map<string, string>();\n for (const rawOrder of rawOrders) {\n const oid = rawOrder.order?.oid?.toString();\n if (oid && rawOrder.order?.orderType && !orderTypeByOid.has(oid)) {\n orderTypeByOid.set(oid, rawOrder.order.orderType);\n }\n }\n for (const fill of fills) {\n const orderType = orderTypeByOid.get(fill.orderId);\n if (orderType) {\n fill.detailedOrderType = orderType;\n }\n }\n }\n } catch (enrichError) {\n this.#deps.debugLogger.log(\n 'Error enriching fills with order types:',\n enrichError,\n );\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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:', {\n count: rawOrders?.length ?? 0,\n });\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getOpenOrders(params?: GetOrdersParams): Promise<Order[]> {\n try {\n // Path 0: Standalone mode for lightweight open order queries\n // Creates a standalone InfoClient without requiring full initialization\n // No wallet, WebSocket, or account setup needed - just HTTP API call\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting open orders in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const orderResults = await queryStandaloneOpenOrders(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Combine all orders from all DEXs and adapt (without position context in standalone mode)\n const orders = orderResults.flatMap((dexOrders) =>\n dexOrders.map((order) => adaptOrderFromSDK(order, undefined)),\n );\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone open orders fetched',\n { count: orders.length },\n );\n\n return orders;\n }\n\n // Try WebSocket cache first (unless explicitly bypassed)\n // Use atomic getter to prevent race condition between check and get\n if (!params?.skipCache) {\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n if (cachedOrders !== null) {\n this.#deps.debugLogger.log(\n 'Using cached open orders from WebSocket',\n {\n count: cachedOrders.length,\n },\n );\n return cachedOrders;\n }\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 { results: orderResults, failedDexs } =\n await this.#queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.frontendOpenOrders(userParam),\n );\n\n if (failedDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Partial multi-DEX open order fetch completed with failures',\n {\n failedDexs: failedDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 // On-demand loading: the default window is one 30-day page so the\n // initial fetch costs exactly 1 API call (~24 weight vs 312 previously).\n // When loadMoreFunding in usePerpsTransactionHistory passes explicit\n // startTime/endTime for an older 30-day page the while-loop below still\n // produces exactly 1 chunk. The 365-day max lookback is enforced by the\n // caller.\n //\n // Each chunk is fetched via fetchWindowWithAutoSplit: if a call returns\n // FUNDING_HISTORY_API_LIMIT records the window has hit the API cap and\n // the oldest records would be silently dropped. The function splits the\n // window in half and recurses until every sub-window is under the cap,\n // guaranteeing complete results regardless of position count or activity.\n const finalEndTime = params?.endTime ?? Date.now();\n const pageWindowMs =\n PERPS_TRANSACTIONS_HISTORY_CONSTANTS.FUNDING_HISTORY_PAGE_WINDOW_DAYS *\n 24 *\n 60 *\n 60 *\n 1000;\n const finalStartTime = params?.startTime ?? finalEndTime - pageWindowMs; // Default: most recent 30-day window only\n\n const minSplitWindowMs =\n PERPS_TRANSACTIONS_HISTORY_CONSTANTS.MIN_SPLIT_WINDOW_MS;\n const apiLimit =\n PERPS_TRANSACTIONS_HISTORY_CONSTANTS.FUNDING_HISTORY_API_LIMIT;\n\n // Fetches a single window. If the result hits the API cap the window is\n // split in half and both halves are fetched in parallel, recursively,\n // until every sub-window is under the cap.\n const fetchWindowWithAutoSplit = async (\n windowStart: number,\n windowEnd: number,\n ): Promise<Awaited<ReturnType<typeof infoClient.userFunding>>> => {\n const result = await infoClient.userFunding({\n user: userAddress,\n startTime: windowStart,\n endTime: windowEnd,\n });\n const records = result ?? [];\n if (\n records.length >= apiLimit &&\n windowEnd - windowStart > minSplitWindowMs\n ) {\n const mid = windowStart + Math.floor((windowEnd - windowStart) / 2);\n const [left, right] = await Promise.all([\n fetchWindowWithAutoSplit(windowStart, mid),\n fetchWindowWithAutoSplit(mid, windowEnd),\n ]);\n return [...(left ?? []), ...(right ?? [])];\n }\n return records;\n };\n\n const chunks: { start: number; end: number }[] = [];\n let chunkEnd = finalEndTime;\n while (chunkEnd > finalStartTime) {\n const chunkStart = Math.max(finalStartTime, chunkEnd - pageWindowMs);\n chunks.push({ start: chunkStart, end: chunkEnd });\n chunkEnd = chunkStart;\n }\n\n const pages = await Promise.all(\n chunks.map((chunk) => fetchWindowWithAutoSplit(chunk.start, chunk.end)),\n );\n\n // Deduplicate at chunk boundaries — adjacent windows share their boundary\n // timestamp (chunkEnd of N === chunkStart of N+1) and the API is\n // inclusive on both sides, so a record can appear in both adjacent calls.\n // Funding records share a zero hash, so we key on time + coin instead.\n const seen = new Set<string>();\n const allRaw = pages.flat().filter((record) => {\n const key = `${record.time}-${record.delta.coin}`;\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n allRaw.sort((a, b) => a.time - b.time);\n\n this.#deps.debugLogger.log('User funding received:', {\n count: allRaw.length,\n chunks: chunks.length,\n });\n\n // Transform HyperLiquid funding to abstract Funding type\n const funding: Funding[] = allRaw.map(({ delta, hash, time }) => ({\n symbol: delta.coin,\n amountUsd: delta.usdc,\n rate: delta.fundingRate,\n timestamp: time,\n transactionHash: hash,\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 - The operation parameters.\n * @param params.accountId - The CAIP account ID.\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.endTime - End timestamp in milliseconds.\n * @returns The result of the operation.\n */\n async getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]> {\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(\n error,\n 'HyperLiquidProvider.getUserNonFundingLedgerUpdates',\n ),\n this.#getErrorContext('getUserNonFundingLedgerUpdates', params),\n );\n return [];\n }\n }\n\n /**\n * Get user history (deposits, withdrawals, transfers)\n *\n * @param params - The operation parameters.\n * @param params.accountId - The CAIP account ID.\n * @param params.startTime - Start timestamp in milliseconds.\n * @param params.endTime - End timestamp in milliseconds.\n * @returns The result of the operation.\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, 'HyperLiquidProvider.getUserHistory'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\n */\n async getAccountState(params?: GetAccountStateParams): Promise<AccountState> {\n try {\n // Path 0: Standalone mode for lightweight account state 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 user has perps funds\n if (params?.standalone && params.userAddress) {\n const { userAddress } = params;\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting account state in standalone mode',\n { userAddress },\n );\n\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: this.#clientService.isTestnetMode(),\n });\n const dexs = await this.#getStandaloneValidatedDexs();\n const results = await queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n );\n\n // Aggregate account states across all DEXs\n const dexAccountStates = results.map((perpsState) =>\n adaptAccountStateFromSDK(perpsState),\n );\n const aggregatedAccountState = aggregateAccountStates(dexAccountStates);\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: standalone account state fetched',\n { totalBalance: aggregatedAccountState.totalBalance },\n );\n\n return aggregatedAccountState;\n }\n\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(\n 'User address for account state:',\n userAddress,\n );\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 // One transient DEX failure should not blank the entire account state.\n const [spotStateResult, perpsStateResult] = await Promise.allSettled([\n infoClient.spotClearinghouseState({ user: userAddress }),\n this.#queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n ]);\n const spotState =\n spotStateResult.status === 'fulfilled' ? spotStateResult.value : null;\n const perpsResponse =\n perpsStateResult.status === 'fulfilled'\n ? perpsStateResult.value\n : {\n results: [],\n failedDexs: [\n {\n dex: null,\n error: ensureError(\n perpsStateResult.reason,\n 'HyperLiquidProvider.getAccountState.perps',\n ),\n },\n ],\n };\n const perpsStateResults = perpsResponse.results;\n const failedPerpsDexs = perpsResponse.failedDexs;\n\n if (spotStateResult.status === 'rejected') {\n this.#deps.debugLogger.log(\n 'Spot state fetch failed during account state aggregation',\n {\n error: ensureError(\n spotStateResult.reason,\n 'HyperLiquidProvider.getAccountState.spot',\n ).message,\n },\n );\n }\n\n if (failedPerpsDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Perps account state completed with partial DEX failures',\n {\n failedDexs: failedPerpsDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\n }\n\n if (perpsStateResults.length === 0) {\n const failedDexNames = failedPerpsDexs.map(({ dex }) => dex ?? 'main');\n const spotErrorMessage =\n spotStateResult.status === 'rejected'\n ? ensureError(\n spotStateResult.reason,\n 'HyperLiquidProvider.getAccountState.spot',\n ).message\n : undefined;\n throw new Error(\n `Failed to fetch account state (failedDexs=[${failedDexNames.join(',')}], spotError=${spotErrorMessage ?? 'none'})`,\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 dexAccountStates = perpsStateResults.map((result) => {\n const dexAccountState = adaptAccountStateFromSDK(result.data);\n this.#deps.debugLogger.log(\n `DEX ${result.dex ?? 'main'} account state:`,\n {\n totalBalance: dexAccountState.totalBalance,\n availableBalance: dexAccountState.availableBalance,\n marginUsed: dexAccountState.marginUsed,\n unrealizedPnl: dexAccountState.unrealizedPnl,\n },\n );\n return dexAccountState;\n });\n const aggregatedAccountState = aggregateAccountStates(dexAccountStates);\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, 'HyperLiquidProvider.getAccountState'),\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 ensureError(error, 'HyperLiquidProvider.getAccountState');\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 * @returns A promise that resolves to the result.\n */\n async getMarkets(params?: GetMarketsParams): Promise<MarketInfo[]> {\n try {\n // Path 0: Standalone 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?.standalone) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Getting markets in standalone mode',\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, 'HyperLiquidProvider.getMarkets'),\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, 'HyperLiquidProvider.getMarkets'),\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 && hasProperty(dex, 'name')) {\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(\n ` ❌ ${dexName}: error querying`,\n error,\n );\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, 'HyperLiquidProvider.getAvailableHip3Dexs'),\n this.#getErrorContext('getAvailableHip3Dexs'),\n );\n return [];\n }\n }\n\n /**\n * Get allMids for a DEX — uses WS snapshot as primary source, REST as fallback.\n *\n * @param infoClient - The HyperLiquid info client (used only on cold start).\n * @param dexParam - Optional DEX parameter (empty string for main DEX).\n * @returns allMids record.\n */\n async #getAllMids(\n infoClient: ReturnType<\n typeof HyperLiquidClientService.prototype.getInfoClient\n >,\n dexParam?: string,\n ): Promise<Record<string, string>> {\n const wsSnapshot =\n this.#subscriptionService.getLastAllMidsSnapshot?.(dexParam);\n if (wsSnapshot) {\n return wsSnapshot;\n }\n\n this.#deps.debugLogger.log(\n '[getMarketDataWithPrices] No WS allMids snapshot, falling back to REST',\n { dexParam: dexParam ?? 'main' },\n );\n const mids = await infoClient.allMids(\n dexParam ? { dex: dexParam } : undefined,\n );\n return mids ?? {};\n }\n\n async #fetchSingleDexFresh(\n infoClient: ReturnType<\n typeof HyperLiquidClientService.prototype.getInfoClient\n >,\n dex: string | null,\n ): Promise<DexFetchResult> {\n const dexParam = dex ?? '';\n\n let metaAndCtxs: [MetaResponse | null, PerpsAssetCtx[]] | null = null;\n try {\n metaAndCtxs = (await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n )) as [MetaResponse | null, PerpsAssetCtx[]] | null;\n } catch (error) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs',\n errorMessage: ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.metaAndAssetCtxs',\n ).message,\n };\n }\n\n const meta = metaAndCtxs?.[0] ?? null;\n const assetCtxs = metaAndCtxs?.[1] ?? [];\n\n let dexAllMids: Record<string, string> = {};\n let allMidsErrorMessage: string | undefined;\n try {\n dexAllMids = await this.#getAllMids(infoClient, dexParam || undefined);\n } catch (error) {\n allMidsErrorMessage = ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.allMids',\n ).message;\n }\n\n if (meta?.universe) {\n this.#cachedMetaByDex.set(dexParam, meta);\n this.#subscriptionService.setDexMetaCache(dexParam, meta);\n this.#subscriptionService.setDexAssetCtxsCache(dexParam, assetCtxs);\n await this.#backfillAssetMapForDex(dex, meta);\n }\n\n return {\n dex,\n meta,\n assetCtxs,\n allMids: dexAllMids,\n success: Boolean(meta?.universe),\n failedStep: allMidsErrorMessage ? 'allMids' : undefined,\n errorMessage: allMidsErrorMessage,\n };\n }\n\n #mergeDexResultsInto(\n results: DexFetchResult[],\n combinedUniverse: MetaResponse['universe'],\n combinedAssetCtxs: PerpsAssetCtx[],\n combinedAllMids: Record<string, string>,\n ): void {\n results.forEach((result) => {\n if (result.success && result.meta?.universe) {\n const marketsFromDex = result.meta.universe;\n const filteredMarkets =\n result.dex === null\n ? marketsFromDex\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 Object.assign(combinedAllMids, result.allMids);\n }\n });\n }\n\n #cacheFreshMarketDataSnapshot(\n marketData: PerpsMarketData[],\n results: DexFetchResult[],\n ): PerpsMarketData[] {\n const freshMarketData = marketData.map((market) => ({\n ...market,\n isStale: false,\n }));\n this.#cachedMarketDataWithPrices = {\n data: freshMarketData.map((market) => ({ ...market })),\n timestamp: Date.now(),\n contributingDexs: results\n .filter((result) => result.success && result.meta?.universe)\n .map((result) => result.dex ?? 'main'),\n failedDexs: results\n .filter((result) => !result.success)\n .map((result) => result.dex ?? 'main'),\n };\n return freshMarketData;\n }\n\n #getStaleMarketDataSnapshot(): PerpsMarketData[] | null {\n if (!this.#cachedMarketDataWithPrices) {\n return null;\n }\n\n return this.#cachedMarketDataWithPrices.data.map((market) => ({\n ...market,\n isStale: true,\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 * @returns A promise that resolves to the combined market data from all enabled DEXs.\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 // Use HTTP transport for market data fetches — these are one-shot request/response calls\n // that don't benefit from WebSocket. When the WebSocket is in CONNECTING state (after app\n // backgrounding or network transitions), the SDK buffers messages causing timeouts.\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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 // Check the meta cache first to avoid redundant API calls when buildAssetMapping\n // has already populated it; on cache miss, delegate to #fetchSingleDexFresh.\n const dexDataResults = await Promise.all(\n enabledDexs.map(async (dex) => {\n const dexKey = dex ?? '';\n const dexParam = dex ?? '';\n const cachedMeta = this.#cachedMetaByDex.get(dexKey);\n if (!cachedMeta) {\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Cache miss for ${dex ?? 'main'}, fetching`,\n );\n return this.#fetchSingleDexFresh(infoClient, dex);\n }\n\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Using cached meta for ${dex ?? 'main'}`,\n { universeSize: cachedMeta.universe.length },\n );\n\n let metaForDex = cachedMeta;\n let assetCtxs =\n this.#subscriptionService.getDexAssetCtxsCache(dexKey) ?? [];\n let failedStep: DexFetchFailureStep | undefined;\n let errorMessage: string | undefined;\n\n if (assetCtxs.length !== metaForDex.universe.length) {\n try {\n const freshResult = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\n const freshMeta = freshResult?.[0] ?? null;\n const freshAssetCtxs = freshResult?.[1] ?? [];\n\n if (freshAssetCtxs.length !== freshMeta?.universe?.length) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs' as const,\n errorMessage:\n 'metaAndAssetCtxs returned mismatched universe/assetCtxs lengths',\n };\n }\n\n metaForDex = freshMeta;\n assetCtxs = freshAssetCtxs;\n this.#cachedMetaByDex.set(dexKey, freshMeta);\n this.#subscriptionService.setDexMetaCache(dexKey, freshMeta);\n this.#subscriptionService.setDexAssetCtxsCache(dexKey, assetCtxs);\n await this.#backfillAssetMapForDex(dex, freshMeta);\n } catch (error) {\n return {\n dex,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n failedStep: 'metaAndAssetCtxs' as const,\n errorMessage: ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.metaAndAssetCtxs',\n ).message,\n };\n }\n }\n\n let dexAllMids: Record<string, string> = {};\n try {\n dexAllMids = await this.#getAllMids(\n infoClient,\n dexParam || undefined,\n );\n } catch (error) {\n failedStep = 'allMids';\n errorMessage = ensureError(\n error,\n 'HyperLiquidProvider.getMarketDataWithPrices.allMids',\n ).message;\n }\n\n return {\n dex,\n meta: metaForDex,\n assetCtxs,\n allMids: dexAllMids,\n success: true,\n failedStep,\n errorMessage,\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 let latestDexResults = dexDataResults;\n\n this.#mergeDexResultsInto(\n dexDataResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n if (combinedUniverse.length === 0) {\n combinedUniverse.length = 0;\n combinedAssetCtxs.length = 0;\n for (const key of Object.keys(combinedAllMids)) {\n delete combinedAllMids[key];\n }\n\n const retryDelayMs = 2000;\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] All DEXs returned empty, retrying in ${retryDelayMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\n const retryResults = await Promise.all(\n enabledDexs.map((dex) => this.#fetchSingleDexFresh(infoClient, dex)),\n );\n\n this.#mergeDexResultsInto(\n retryResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n latestDexResults = retryResults;\n\n if (combinedUniverse.length === 0) {\n const failedDexs = retryResults\n .filter((result) => !result.success)\n .map((result) => result.dex ?? 'main');\n const succeededDexs = retryResults\n .filter((result) => result.success)\n .map((result) => result.dex ?? 'main');\n const failedDetails = retryResults\n .filter((result) => result.errorMessage)\n .map(\n (result) =>\n `${result.dex ?? 'main'}:${result.failedStep ?? 'unknown'}:${\n result.errorMessage\n }`,\n );\n const staleMarketData = this.#getStaleMarketDataSnapshot();\n\n if (staleMarketData) {\n this.#deps.debugLogger.log(\n '[getMarketDataWithPrices] Returning stale cached market data after retry failure',\n {\n failedDexs,\n failedDetails,\n cachedAt:\n this.#cachedMarketDataWithPrices?.timestamp ?? Date.now(),\n },\n );\n return staleMarketData;\n }\n\n const wsState = this.#clientService.getConnectionState();\n throw new Error(\n `Failed to fetch market data - no markets available (enabledDexs=${enabledDexs.length}, failed=[${failedDexs.join(',')}], succeeded=[${succeededDexs.join(',')}], wsState=${wsState}, details=[${failedDetails.join(';')}])`,\n );\n }\n\n this.#deps.debugLogger.log('[getMarketDataWithPrices] Retry succeeded', {\n marketCount: combinedUniverse.length,\n });\n }\n\n const partialFailures = latestDexResults.filter(\n (result) => result.errorMessage,\n );\n if (partialFailures.length > 0) {\n this.#deps.debugLogger.log(\n 'Market data fetch completed with partial per-DEX failures',\n {\n failures: partialFailures.map(\n (result) =>\n `${result.dex ?? 'main'}:${result.failedStep ?? 'unknown'}:${\n result.errorMessage\n }`,\n ),\n },\n );\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: latestDexResults[0]?.meta?.universe?.length ?? 0,\n hip3Markets:\n combinedUniverse.length -\n (latestDexResults[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 const transformedMarketData = transformMarketData(\n {\n universe: combinedUniverse,\n assetCtxs: combinedAssetCtxs,\n allMids: combinedAllMids,\n },\n this.#deps.marketDataFormatters,\n HIP3_ASSET_MARKET_TYPES,\n );\n\n return this.#cacheFreshMarketDataSnapshot(\n transformedMarketData,\n latestDexResults,\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 - The unused operation parameters.\n * @returns A promise that resolves to the result.\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(\n 'HyperLiquidProvider: INSUFFICIENT BALANCE',\n {\n error: balanceValidation.error,\n requestedAmount: withdrawAmount,\n availableBalance,\n difference: withdrawAmount - availableBalance,\n },\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(\n 'HyperLiquidProvider: WITHDRAW3 API RESPONSE',\n {\n status: result.status,\n response: result,\n timestamp: new Date().toISOString(),\n },\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 safeError = ensureError(\n error,\n 'HyperLiquidProvider.initiateWithdrawal',\n );\n this.#deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL EXCEPTION', {\n error: safeError.message,\n errorType: safeError.name,\n stack: safeError.stack,\n params,\n timestamp: new Date().toISOString(),\n });\n this.#deps.logger.error(\n safeError,\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 * @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(\n 'HyperLiquidProvider: CALLING SEND_ASSET API',\n {\n sourceDex: params.sourceDex || '(main)',\n destinationDex: params.destinationDex || '(main)',\n amount: params.amount,\n },\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 const safeError = ensureError(\n error,\n 'HyperLiquidProvider.transferToSpot',\n );\n this.#deps.debugLogger.log('❌ HyperLiquidProvider: TRANSFER FAILED', {\n error: safeError.message,\n params,\n });\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext('transferBetweenDexs', { ...params }),\n );\n return {\n success: false,\n error: safeError.message,\n };\n }\n }\n\n /**\n * Subscribe to live price updates\n *\n * @param params - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 return undefined;\n })\n .catch((error) => {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.subscribeToPrices'),\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\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 - The operation parameters.\n * @returns A cleanup function to remove the subscription.\n */\n subscribeToCandles(params: SubscribeCandlesParams): () => void {\n return this.#clientService.subscribeToCandles(params);\n }\n\n /**\n * Configure live data settings\n *\n * @param config - The configuration object.\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 * @returns A promise that resolves to the result.\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 * @returns A promise that resolves to the result.\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 * @returns A promise that resolves to the result.\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 - maintenanceMarginRatio * side)\n * where maintenanceMarginRatio = 1 / MAINTENANCE_LEVERAGE = 1 / (2 * max_leverage)\n *\n * @param params - The operation parameters.\n * @returns A promise that resolves to the string result.\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, 'HyperLiquidProvider.calculateLiquidationPrice'),\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 - The operation parameters.\n * @returns A promise that resolves to the numeric result.\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 - The asset identifier.\n * @returns A promise that resolves to the numeric result.\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, 'HyperLiquidProvider.getMaxLeverage'),\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 - The operation parameters.\n * @returns A promise that resolves to the result.\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 const safeError = ensureError(\n error,\n 'HyperLiquidProvider.getFeeSchedule',\n );\n this.#deps.debugLogger.log(\n 'Fee API Call Failed - Falling Back to Base Rates',\n {\n error: safeError.message,\n errorType: safeError.name,\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 let protocolFeeAmount: number | undefined;\n if (amount === undefined) {\n protocolFeeAmount = undefined;\n } else if (isNaN(parsedAmount)) {\n protocolFeeAmount = 0;\n } else {\n protocolFeeAmount = parsedAmount * protocolFeeRate;\n }\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 - The user's wallet address.\n * @private\n * @returns True if the condition is met.\n */\n #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 * @returns A promise that resolves to the result.\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 // NOTE: DexAbstractionCache is global and NOT cleared on disconnect\n // to prevent repeated signing requests across reconnections\n this.#cachedMetaByDex.clear();\n this.#cachedSpotMeta = null;\n this.#perpDexsCache = { data: null, timestamp: 0 };\n this.#dexDiscoveryComplete = false;\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 const pendingTradingSetup = this.#tradingSetupPromise;\n\n // Clear references first to prevent new callers from reusing\n this.#initializationPromise = null;\n this.#ensureReadyPromise = null;\n this.#tradingSetupPromise = null;\n this.#tradingSetupComplete = false;\n this.#pendingBuilderFeeApprovals.clear();\n\n // Wait for pending operations to complete (ignore errors)\n // This prevents IIFEs from setting state after disconnect completes\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 if (pendingTradingSetup) {\n try {\n await pendingTradingSetup;\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, 'HyperLiquidProvider.ping');\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 * @returns A promise that resolves when the operation completes.\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(\n ensureError(error, 'HyperLiquidProvider.getAvailableDexs'),\n {\n context: {\n name: 'HyperLiquidProvider.getAvailableDexs',\n data: { action: 'fetch_available_dexs' },\n },\n },\n );\n throw error;\n }\n }\n\n async fetchHistoricalCandles(options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData> {\n this.#clientService.ensureInitialized();\n const result = await this.#clientService.fetchHistoricalCandles(options);\n return (\n result ?? {\n symbol: options.symbol,\n interval: options.interval,\n candles: [],\n }\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 #getBuilderAddress(isTestnet: boolean): string {\n // || intentional: env vars default to '' which must fall through to the hardcoded default\n if (isTestnet) {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this.#builderAddressTestnet || BUILDER_FEE_CONFIG.TestnetBuilder;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this.#builderAddressMainnet || BUILDER_FEE_CONFIG.MainnetBuilder;\n }\n\n #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 GLOBAL cache to persist across provider reconnections\n * This prevents repeated signing requests for hardware wallets.\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 */\n async #ensureReferralSet(): Promise<void> {\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\n let userAddress: string;\n try {\n userAddress = await this.#walletService.getUserAddressWithDefault();\n } catch {\n return; // Can't proceed without address\n }\n\n if (userAddress.toLowerCase() === referrerAddress.toLowerCase()) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] User is builder, skipping',\n { network },\n );\n return;\n }\n\n // Check GLOBAL cache first\n const globalCached = PerpsSigningCache.getReferral(network, userAddress);\n if (globalCached?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Using global cache (prevents QR popup spam)',\n { network, success: globalCached.success },\n );\n return;\n }\n\n // Check if another provider is currently attempting this\n const inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\n if (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n return;\n }\n\n // Set global in-flight lock\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'referral',\n network,\n userAddress,\n );\n\n try {\n // Re-check cache after acquiring lock\n const recheckCache = PerpsSigningCache.getReferral(network, userAddress);\n if (recheckCache?.attempted) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Completed by another provider',\n { network },\n );\n completeInFlight();\n return;\n }\n\n const isReady = await this.#isReferralCodeReady();\n if (!isReady) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Builder referral not ready, skipping',\n { network },\n );\n completeInFlight();\n return; // Don't cache - retry when ready\n }\n\n // Check if user already has a referral on-chain\n const hasReferral = await this.#checkReferralSet();\n\n if (hasReferral) {\n // Already has referral on-chain\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Already has referral on-chain',\n { network },\n );\n } else {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Setting referral (will show signing request)',\n { network, referralCode: expectedReferralCode },\n );\n const result = await this.#setReferralCode();\n if (result) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Referral set successfully',\n { network },\n );\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: true,\n });\n } else {\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: false,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Failed, cached to prevent retries',\n { network },\n );\n }\n }\n completeInFlight();\n } catch (error) {\n // If keyring is locked, don't cache so it retries when unlocked\n if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Keyring locked, will retry later',\n );\n completeInFlight();\n return;\n }\n\n // Cache failure to prevent retries\n PerpsSigningCache.setReferral(network, userAddress, {\n attempted: true,\n success: false,\n });\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Error, cached to prevent retries',\n {\n network,\n error: ensureError(error, 'HyperLiquidProvider.ensureReferralSet')\n .message,\n },\n );\n completeInFlight();\n\n // Non-blocking: Log to Sentry but don't throw\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureReferralSet'),\n this.#getErrorContext('ensureReferralSet', {\n note: 'Referral setup failed (non-blocking), cached to prevent retries',\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 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, 'HyperLiquidProvider.isReferralCodeReady'),\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 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, 'HyperLiquidProvider.checkReferralSet'),\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 * @returns A promise that resolves to the boolean result.\n */\n 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, 'HyperLiquidProvider.setReferralCode'),\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"]}