@metamask-previews/perps-controller 20.0.0-preview-4fa35a45a → 20.0.0-preview-92e2f53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/constants/eventNames.d.ts +2 -0
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +1 -0
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/errors.d.ts +50 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +39 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +8 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +11 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +11 -2
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +52 -21
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +10 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/hyperLiquidValidation.d.ts +2 -1
- package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
- package/dist/utils/hyperLiquidValidation.js +14 -1
- package/dist/utils/hyperLiquidValidation.js.map +1 -1
- package/dist/utils/orderCalculations.d.ts.map +1 -1
- package/dist/utils/orderCalculations.js +18 -7
- package/dist/utils/orderCalculations.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HyperLiquidProvider.js","sourceRoot":"","sources":["../../src/providers/HyperLiquidProvider.ts"],"names":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;aACjE,CAAC,CACH,CAAC;YACF,2DAA2D;YAC3D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import { CaipAccountId, hasProperty, isHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport type {\n ExchangeClient,\n InfoClient,\n UserAbstractionResponse,\n} from '@nktkas/hyperliquid';\nimport { HyperliquidError } from '@nktkas/hyperliquid';\nimport { BigNumber } from 'bignumber.js';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport type { CandlePeriod } from '../constants/chartConfig.js';\nimport {\n PERPS_EVENT_PROPERTY,\n PERPS_EVENT_VALUE,\n} from '../constants/eventNames.js';\nimport {\n BASIS_POINTS_DIVISOR,\n BUILDER_FEE_CONFIG,\n canonicalizeHyperLiquidDexes,\n FEE_RATES,\n HYPERLIQUID_ORDER_CAPABILITIES,\n getBridgeInfo,\n getChainId,\n HIP3_ASSET_MARKET_TYPES,\n HIP3_FEE_CONFIG,\n HIP3_MARGIN_CONFIG,\n HYPERLIQUID_ASSET_NAMES,\n HYPERLIQUID_CONFIG,\n HYPERLIQUID_WITHDRAWAL_MINUTES,\n REFERRAL_CONFIG,\n TRADING_DEFAULTS,\n USDC_DECIMALS,\n USDC_SYMBOL,\n} from '../constants/hyperLiquidConfig.js';\nimport { DETAILED_ORDER_TYPES } from '../constants/orderTypes.js';\nimport {\n CHASE_ORDER_CONFIG,\n CHASE_ORDER_STATUS,\n HYPERLIQUID_TWAP_LIMITS,\n ORDER_SLIPPAGE_CONFIG,\n PERFORMANCE_CONFIG,\n PERPS_CONSTANTS,\n PROVIDER_CONFIG,\n SUBSCRIPTION_CLOID_CONFIG,\n TP_SL_CONFIG,\n WITHDRAWAL_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { PerpsErrorCode } from '../perpsErrorCodes.js';\nimport {\n AgentSignerUnavailableError,\n getAgentAccountKey,\n isAgentSignerUnavailableError,\n} from '../services/agentSigner.js';\nimport { hasErrorInCauseChain } from '../services/causeChain.js';\nimport { DexDiscoveryCacheManager } from '../services/DexDiscoveryCacheManager.js';\nimport {\n HyperLiquidClientService,\n WebSocketConnectionState,\n} from '../services/HyperLiquidClientService.js';\nimport type { HyperLiquidWalletParams } from '../services/HyperLiquidClientService.js';\nimport { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService.js';\nimport { HyperLiquidWalletService } from '../services/HyperLiquidWalletService.js';\nimport {\n TradingReadinessCache,\n PerpsSigningCache,\n} from '../services/TradingReadinessCache.js';\nimport type {\n FrontendOrder,\n OrderType as HyperLiquidOrderType,\n OrderProcessingStatus,\n SDKOrderParams,\n MetaResponse,\n PerpsAssetCtx,\n SpotMetaResponse,\n} from '../types/hyperliquid-types.js';\nimport {\n HL_ABSTRACTION_WIRE,\n HL_UNIFIED_ACCOUNT_MODE,\n hyperLiquidModeFoldsSpot,\n} from '../types/hyperliquid-types.js';\nimport { PerpsAnalyticsEvent } from '../types/index.js';\nimport type {\n AccountState,\n AssetRoute,\n BatchCancelOrdersParams,\n CancelOrderParams,\n CancelOrderResult,\n CancelOrdersResult,\n ChaseOrder,\n ChaseOrderMaxDistanceReached,\n ChaseOrderStatus,\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 GetOrderCapabilitiesParams,\n GetMarginModeLockParams,\n GetScalePriceLadderParams,\n GetOrderFillsParams,\n GetOrdersParams,\n GetOrFetchFillsParams,\n GetPositionsParams,\n GetSupportedPathsParams,\n GetUserDataSnapshotParams,\n HistoricalPortfolioResult,\n HyperLiquidCredentials,\n InitializeResult,\n PerpsAgentAccount,\n PerpsAgentSigner,\n PerpsPlatformDependencies,\n PerpsProvider,\n PerpsProviderType,\n PerpsScalePriceLadder,\n LiquidationPriceParams,\n LiveDataConfig,\n MaintenanceMarginParams,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n MarginResult,\n MarketInfo,\n Order,\n OrderFill,\n OrderParams,\n OrderResult,\n ScaleOrderChild,\n PerpsMarketData,\n DirectProviderOrderCapabilities,\n DirectProviderScalePriceLadderUnavailableReason,\n Position,\n PositionTriggerOrder,\n ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribeTwapOrdersParams,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n TransferBetweenDexsParams,\n TransferBetweenDexsResult,\n TwapOrder,\n TwapOrderFill,\n TwapOrderStatus,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n RawLedgerUpdate,\n PerpsReadOptions,\n PerpsUserDataSnapshot,\n PerpsFeeResolution,\n MarginMode,\n MarginModeLockReason,\n PerpsMarginModeLock,\n} from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport type { OrderType, StrategyOrderType } from '../types/perps-types.js';\nimport type {\n ExtendedAssetMeta,\n ExtendedPerpDex,\n} from '../types/perps-types.js';\nimport {\n addSpotBalanceToAccountState,\n aggregateAccountStates,\n} from '../utils/accountUtils.js';\nimport { isValidCapabilitySymbol } from '../utils/capabilitySymbols.js';\nimport {\n PERPS_ERROR_ACTION,\n PERPS_ERROR_COMPONENT,\n PERPS_ERROR_OPERATION,\n createPerpsErrorContext,\n} from '../utils/errorContext.js';\nimport type {\n PerpsErrorTags,\n PerpsLoggerOptions,\n} from '../utils/errorContext.js';\nimport {\n ensureError,\n isHyperLiquidMultiSigRequiredError,\n isHyperLiquidUserNotFoundError,\n isKeyringLockedError,\n} from '../utils/errorUtils.js';\nimport { shouldDeferUnifiedAccountSetup } from '../utils/hyperLiquidAbstraction.js';\nimport {\n adaptAccountStateFromSDK,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n adaptMarketFromSDK,\n adaptOrderFromSDK,\n adaptPositionFromSDK,\n adaptPositionTriggerOrderFromSDK,\n adaptTpslLinkageToGrouping,\n buildAssetMapping,\n buildHyperLiquidFillId,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n HYPERLIQUID_SCALE_CLOID_MARKER,\n parseAssetName,\n readScaleGroupId,\n} from '../utils/hyperLiquidAdapter.js';\nimport {\n previewHyperLiquidIsolatedPositionModify,\n resolveHyperLiquidMarginTiers,\n} from '../utils/hyperLiquidPositionPreview.js';\nimport {\n createErrorResult,\n getMaxOrderValue,\n getSupportedPaths,\n validateAssetSupport,\n validateBalance,\n validateCoinExists,\n validateDepositParams,\n validateOrderParams,\n validateWithdrawalParams,\n} from '../utils/hyperLiquidValidation.js';\nimport type { StrategyOrderValidationParams } from '../utils/hyperLiquidValidation.js';\nimport { generatePerpsId } from '../utils/idUtils.js';\nimport { transformMarketData } from '../utils/marketDataTransform.js';\nimport {\n compileMarketPattern,\n shouldIncludeMarket,\n} from '../utils/marketUtils.js';\nimport type { CompiledMarketPattern } from '../utils/marketUtils.js';\nimport {\n buildOrdersArray,\n calculateFinalPositionSize,\n calculateOrderPriceAndSize,\n computeChaseQuotePrice,\n computeScalePriceLadder,\n floorToSizeDecimals,\n formatPartialTpslSize,\n getPriceTick,\n splitScaleSizes,\n validateOrderPrecision,\n} from '../utils/orderCalculations.js';\nimport {\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isStrategyOrderType,\n isTriggerOrderType,\n resolvePositionTriggerSummaryPrice,\n toSDKTimeInForce,\n} from '../utils/orderTypes.js';\nimport { assertExpectedPosition } from '../utils/positionProtection.js';\nimport {\n createStandaloneInfoClient,\n queryStandaloneClearinghouseStates,\n queryStandaloneOpenOrders,\n} from '../utils/standaloneInfoClient.js';\nimport { parseBoundedNonNegativeDecimal } from '../utils/stringParseUtils.js';\nimport {\n markSubscriptionCloid,\n quantizeBuilderFeeTenthsBps,\n} from '../utils/subscriptionFeeWaiver.js';\n// getStreamManagerInstance removed: use this.#deps.streamManager instead\n\nconst HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE = {\n [DETAILED_ORDER_TYPES.LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.MARKET]: 'market',\n [DETAILED_ORDER_TYPES.STOP_LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.STOP_MARKET]: 'market',\n [DETAILED_ORDER_TYPES.TAKE_PROFIT_LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.TAKE_PROFIT_MARKET]: 'market',\n [DETAILED_ORDER_TYPES.TWAP_SLICE]: 'market',\n [DETAILED_ORDER_TYPES.VAULT_CLOSE]: 'market',\n [DETAILED_ORDER_TYPES.SPOT_DUST_CONVERSION]: 'market',\n} as const satisfies Record<HyperLiquidOrderType, Order['orderType']>;\n\nconst HISTORICAL_ORDER_STATUS_BY_SDK_STATUS = {\n open: 'open',\n filled: 'filled',\n triggered: 'triggered',\n canceled: 'canceled',\n marginCanceled: 'canceled',\n vaultWithdrawalCanceled: 'canceled',\n openInterestCapCanceled: 'canceled',\n selfTradeCanceled: 'canceled',\n reduceOnlyCanceled: 'canceled',\n siblingFilledCanceled: 'canceled',\n delistedCanceled: 'canceled',\n liquidatedCanceled: 'canceled',\n outcomeSettledCanceled: 'canceled',\n scheduledCancel: 'canceled',\n internalCancel: 'canceled',\n reduceOnlyRejected: 'canceled',\n rejected: 'rejected',\n tickRejected: 'rejected',\n minTradeNtlRejected: 'rejected',\n perpMarginRejected: 'rejected',\n badAloPxRejected: 'rejected',\n iocCancelRejected: 'rejected',\n badTriggerPxRejected: 'rejected',\n marketOrderNoLiquidityRejected: 'rejected',\n positionIncreaseAtOpenInterestCapRejected: 'rejected',\n positionFlipAtOpenInterestCapRejected: 'rejected',\n tooAggressiveAtOpenInterestCapRejected: 'rejected',\n openInterestIncreaseRejected: 'rejected',\n insufficientSpotBalanceRejected: 'rejected',\n oracleRejected: 'rejected',\n perpMaxPositionRejected: 'rejected',\n tooManyOpenOrdersRejected: 'rejected',\n} as const satisfies Record<OrderProcessingStatus, Order['status']>;\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/**\n * Allocate an unmarked protection identity without reusing this operation's IDs.\n *\n * @param allocated - IDs already allocated for replacement or restoration.\n * @returns A unique client ID with the subscription layout and no fee flag.\n */\nconst createUnmarkedProtectionCloid = (allocated: Set<string>): Hex => {\n const unmarkedFlags = 0;\n const flags = unmarkedFlags.toString(16).padStart(2, '0');\n const entropy = uuidv4()\n .replace(/-/gu, '')\n .slice(0, SUBSCRIPTION_CLOID_CONFIG.EntropyHexLength);\n const cloid: Hex = `0x${SUBSCRIPTION_CLOID_CONFIG.ProgramId}${flags}${entropy}`;\n if (allocated.has(cloid)) {\n throw new Error('Duplicate TP/SL client order identity');\n }\n allocated.add(cloid);\n return cloid;\n};\n\ntype ScaleBulkOrderResponse = {\n status: 'ok';\n response: {\n type: 'order';\n data: { statuses: unknown[] };\n };\n};\n\ntype ScaleBulkOrderStatus =\n | { kind: 'accepted'; state: 'resting'; orderId: string }\n | {\n kind: 'accepted';\n state: 'filled';\n orderId: string;\n averagePrice: string;\n filledSize: string;\n }\n | { kind: 'accepted'; state: 'waitingForFill' | 'waitingForTrigger' }\n | { kind: 'error'; error: string };\n\n/**\n * Parse every status the HyperLiquid bulk order API can return for a Scale\n * rung. Unknown or malformed statuses are not exchange rejections.\n *\n * @param status - One status from a bulk order response.\n * @returns The classified status, or undefined when it is malformed.\n */\nconst parseScaleBulkOrderStatus = (\n status: unknown,\n): ScaleBulkOrderStatus | undefined => {\n if (status === 'waitingForFill' || status === 'waitingForTrigger') {\n return { kind: 'accepted', state: status };\n }\n\n if (!isStatusObject(status) || Object.keys(status).length !== 1) {\n return undefined;\n }\n\n if (hasProperty(status, 'error')) {\n return typeof status.error === 'string'\n ? { kind: 'error', error: status.error }\n : undefined;\n }\n\n if (hasProperty(status, 'resting')) {\n const order = status.resting;\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0\n ) {\n return {\n kind: 'accepted',\n state: 'resting',\n orderId: order.oid.toString(),\n };\n }\n }\n\n if (hasProperty(status, 'filled')) {\n const order = status.filled;\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0 &&\n typeof order.avgPx === 'string' &&\n new BigNumber(order.avgPx).isFinite() &&\n new BigNumber(order.avgPx).gt(0) &&\n typeof order.totalSz === 'string' &&\n new BigNumber(order.totalSz).isFinite() &&\n new BigNumber(order.totalSz).gt(0)\n ) {\n return {\n kind: 'accepted',\n state: 'filled',\n orderId: order.oid.toString(),\n averagePrice: order.avgPx,\n filledSize: order.totalSz,\n };\n }\n }\n\n return undefined;\n};\n\n/**\n * Recover a structurally valid bulk order response that the pinned SDK wraps\n * in an `ApiRequestError`.\n *\n * @param error - The SDK error thrown by `ExchangeClient.order`.\n * @param expectedStatusCount - Number of Scale rungs submitted.\n * @returns The complete bulk order response, or undefined for any other error.\n */\nconst getScaleBulkOrderResponseFromError = (\n error: unknown,\n expectedStatusCount: number,\n): ScaleBulkOrderResponse | undefined => {\n if (\n !(error instanceof HyperliquidError) ||\n error.name !== 'ApiRequestError' ||\n !hasProperty(error, 'response')\n ) {\n return undefined;\n }\n\n const result = error.response;\n if (!isStatusObject(result) || result.status !== 'ok') {\n return undefined;\n }\n\n const { response } = result;\n if (!isStatusObject(response) || response.type !== 'order') {\n return undefined;\n }\n\n const { data } = response;\n if (!isStatusObject(data)) {\n return undefined;\n }\n\n const { statuses } = data;\n if (!Array.isArray(statuses) || statuses.length !== expectedStatusCount) {\n return undefined;\n }\n\n return result as ScaleBulkOrderResponse;\n};\n\n/**\n * Read a complete cancel response from an SDK `ApiRequestError`.\n *\n * The SDK throws when any cancel entry is an error, including the benign\n * already-gone response that confirms an order is no longer live.\n *\n * @param error - Error thrown by an exchange cancel method.\n * @param expectedStatusCount - Number of cancel requests submitted.\n * @returns The per-request statuses, or undefined for another error shape.\n */\nconst getCancelStatusesFromError = (\n error: unknown,\n expectedStatusCount: number,\n): unknown[] | undefined => {\n if (\n !(error instanceof HyperliquidError) ||\n error.name !== 'ApiRequestError' ||\n !hasProperty(error, 'response')\n ) {\n return undefined;\n }\n\n const result = error.response;\n if (!isStatusObject(result) || result.status !== 'ok') {\n return undefined;\n }\n const { response } = result;\n if (\n !isStatusObject(response) ||\n response.type !== 'cancel' ||\n !isStatusObject(response.data) ||\n !Array.isArray(response.data.statuses) ||\n response.data.statuses.length !== expectedStatusCount\n ) {\n return undefined;\n }\n\n return response.data.statuses;\n};\n\n// The address in HyperLiquid's \"User or API Wallet 0x... does not exist.\"\nconst UNKNOWN_WALLET_ADDRESS_PATTERN = /user or api wallet (0x[0-9a-f]{40})/iu;\n\n// The account in HyperLiquid's \"Must deposit before performing actions.\n// User: 0x...\", which names the main account, not the signer.\nconst MUST_DEPOSIT_USER_PATTERN =\n /must deposit before performing actions\\. user: (0x[0-9a-f]{40})/iu;\n\n// Builder fee approval refusals the venue repeats whoever signs, such as a\n// builder without funds: signing the approval again cannot help.\nconst BUILDER_FEE_REFUSALS = ['builder has insufficient balance'];\n\n// An agent's L1 signature: the account and network it signed for.\ntype AgentSignature = {\n key: string;\n account: PerpsAgentAccount;\n agentAddress: Hex;\n // The provider lifecycle generation of the wallet that made it.\n generation?: number;\n // Whether the venue still lists the agent, asked at most once per\n // signature (see #findRevokedAgent).\n approvalCheck?: Promise<boolean>;\n};\n\n// What a wallet adapter, and so the exchange client signing through it, was\n// created for: its network and provider lifecycle generation. It holds the\n// agent signatures it made that the venue has not answered yet, keyed by\n// getSignatureKey.\ntype WalletBinding = {\n isTestnet: boolean;\n generation: number;\n unansweredSignatures: Map<string, AgentSignature>;\n};\n\n/**\n * The venue answer an SDK error carries.\n *\n * @param error - The caught error.\n * @returns The answer, or undefined.\n */\nfunction getVenueAnswer(error: unknown): unknown {\n return isStatusObject(error) && hasProperty(error, 'response')\n ? error.response\n : undefined;\n}\n\n/**\n * A rejection the venue reported in a status entry, carrying the answer it\n * came in, like the error the SDK throws.\n *\n * @param message - The status entry's error.\n * @param answer - The venue answer with the entry.\n * @returns The error.\n */\nfunction createStatusError(message: string, answer: unknown): Error {\n return Object.assign(new Error(message), { response: answer });\n}\n\n/**\n * The key a signature is recognized by in an exchange request: its r value,\n * which the SDK sends as is.\n *\n * @param signature - The signature, or its r value.\n * @returns The key.\n */\nfunction getSignatureKey(signature: string): string {\n return signature.slice(0, 66).toLowerCase();\n}\n\n/**\n * The venue's refusal of a builder fee approval that signing again cannot\n * fix.\n *\n * @param error - The approval error.\n * @returns The venue's message, or undefined for another error.\n */\nfunction getBuilderFeeRefusal(error: unknown): string | undefined {\n const { message } = ensureError(error, 'HyperLiquidProvider.builderFee');\n const lower = message.toLowerCase();\n return BUILDER_FEE_REFUSALS.some((refusal) => lower.includes(refusal))\n ? message\n : undefined;\n}\n\n/**\n * Exchange messages that mean a cancel was refused because the order is not on\n * the book any more.\n *\n * HyperLiquid answers a cancel it cannot match with \"Order was never placed,\n * already canceled, or filled.\" That is a rejection of the request but a\n * confirmation of what the caller wanted — nothing of that order is resting.\n * Every other rejection (multi-sig, a stale nonce, a rate limit) leaves the\n * order exactly where it was, which is a materially different outcome.\n */\nconst ALREADY_GONE_CANCEL_MARKERS = [\n 'never placed',\n 'already canceled',\n 'already cancelled',\n 'order not found',\n 'twap not found',\n];\n\nconst RETRYABLE_CHASE_PLACEMENT_MARKERS = [\n 'post only order would have immediately matched',\n 'price too far from oracle',\n];\n\nconst CHASE_ORDER_STATUS_RETRY_COUNT = 2;\nconst CHASE_ORDER_STATUS_RETRY_DELAY_MS = 100;\nconst CHASE_ORDER_STATUS_UNAVAILABLE = 'status_unavailable';\n\nclass ChaseOrderStatusUnavailableError extends Error {\n constructor() {\n super('Chase order status unavailable');\n this.name = 'ChaseOrderStatusUnavailableError';\n }\n}\n\nconst isRetryableChasePlacementError = (error: unknown): boolean => {\n const message = ensureError(\n error,\n 'HyperLiquidProvider.startChaseSession',\n ).message.toLowerCase();\n return RETRYABLE_CHASE_PLACEMENT_MARKERS.some((marker) =>\n message.includes(marker),\n );\n};\n\n/**\n * What happened to one order a cancel was asked to remove.\n *\n * `Cancelled` and `Gone` both mean nothing of it is resting, which is all a\n * caller asked for; only `Refused` leaves an order behind.\n */\nconst enum CancelChildOutcome {\n Cancelled = 'cancelled',\n Gone = 'gone',\n Refused = 'refused',\n}\n\nconst enum HyperLiquidTwapLifecycleStatus {\n Activated = 'activated',\n Failed = 'error',\n Finished = 'finished',\n Stopped = 'stopped',\n Terminated = 'terminated',\n WaitingForTrigger = 'waitingForTrigger',\n}\n\nconst enum PerpsTwapLifecycleStatus {\n Active = 'active',\n Canceled = 'canceled',\n Completed = 'completed',\n CompletedUnderfilled = 'completed_underfilled',\n Failed = 'failed',\n}\n\ntype SdkHyperLiquidTwapHistoryEntry = Awaited<\n ReturnType<InfoClient['twapHistory']>\n>[number];\n\ntype HyperLiquidTwapNonFailureLifecycleStatus =\n | `${HyperLiquidTwapLifecycleStatus.Activated}`\n | `${HyperLiquidTwapLifecycleStatus.Finished}`\n | `${HyperLiquidTwapLifecycleStatus.Stopped}`\n | `${HyperLiquidTwapLifecycleStatus.Terminated}`\n | `${HyperLiquidTwapLifecycleStatus.WaitingForTrigger}`;\n\ntype HyperLiquidTwapFailureLifecycleStatus =\n `${HyperLiquidTwapLifecycleStatus.Failed}`;\n\ntype HyperLiquidTwapHistoryEntry = Omit<\n SdkHyperLiquidTwapHistoryEntry,\n 'status'\n> & {\n status:\n | {\n status: HyperLiquidTwapNonFailureLifecycleStatus;\n }\n | {\n status: HyperLiquidTwapFailureLifecycleStatus;\n description: string;\n };\n};\n\ntype HyperLiquidTwapSliceFillEntry = Awaited<\n ReturnType<InfoClient['userTwapSliceFills']>\n>[number];\n\ntype ExchangeCancelRequest = { a: number; o: number };\n\ntype ExchangeCancelByCloidRequest = { asset: number; cloid: Hex };\n\ntype CancelOrderBatchOutcome = {\n remainingOrderIds: number[];\n cancelledOrderIds: number[];\n responseComplete: boolean;\n // KEYRING_LOCKED when the signer could not sign the request. The venue\n // reports it per entry, so entries it did cancel still count as cancelled.\n signerFailure?: Error;\n};\n\ntype OrderPlacementOutcome = {\n orderId: string;\n state: 'resting' | 'filled';\n};\n\ntype TpslOrderPlacementOutcome = {\n orderId?: string;\n state: 'resting' | 'filled' | 'waitingForTrigger' | 'rejected' | 'unknown';\n};\n\ntype RestorableTpslOrder = {\n orderId: number;\n order: SDKOrderParams;\n chargesMetamaskBuilderFee: boolean;\n};\n\ntype TpslProtectionRestorationOutcome = {\n restoredOrderIds: string[];\n success: boolean;\n};\n\ntype BuilderFeeSetupContext = {\n network: 'testnet' | 'mainnet';\n userAddress: string;\n builderAddress: string;\n};\n\n/**\n * Classify one entry of a cancel response.\n *\n * @param status - A single status from the exchange's cancel response.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\nconst classifyCancelStatus = (status: unknown): CancelChildOutcome => {\n if (status === 'success') {\n return CancelChildOutcome.Cancelled;\n }\n\n const message = (\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : ''\n ).toLowerCase();\n\n return ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))\n ? CancelChildOutcome.Gone\n : CancelChildOutcome.Refused;\n};\n\n/**\n * Read the best price on one side of the book, discounting the chase's own\n * order.\n *\n * A chase rests one tick inside the spread, so its own order *is* the best\n * price on its side. Reading the raw book would therefore see the chase's own\n * quote every tick, conclude the touch has not moved, and never re-price —\n * masking exactly the adverse moves the strategy exists to follow. Levels this\n * provider occupies are netted down by what it holds there, and are skipped\n * entirely when nothing else is left on them.\n *\n * \"Own\" means *every* chase this provider is running on that side, not just the\n * one asking. Two chases on the same side each netting only themselves would\n * read the other as the external touch and improve on it, then improve on the\n * improvement — walking each other toward the opposite side of an unchanged\n * market.\n *\n * The sizes must be what the orders still have resting, not what they were\n * placed for: an order netted at its original size subtracts more than it\n * occupies, which can hide external liquidity sharing the level.\n *\n * @param levels - One side of the book, best-first.\n * @param ownByPrice - This provider's own resting size at each price.\n * @returns The best price other participants are showing, or null.\n */\nconst readBestExternalPrice = (\n levels: { px: string; sz: string }[] | undefined,\n ownByPrice: Map<string, number>,\n): number | null => {\n for (const level of levels ?? []) {\n const price = parseFloat(level.px);\n if (!Number.isFinite(price) || price <= 0) {\n continue;\n }\n\n const size = parseFloat(level.sz) - (ownByPrice.get(level.px) ?? 0);\n if (size > 0) {\n return price;\n }\n }\n\n return null;\n};\n\n/**\n * Narrow order params down to their strategy fields.\n *\n * Both validation entry points forward exactly this group, so a field added to\n * `StrategyOrderValidationParams` reaches both of them or neither.\n *\n * @param params - Order parameters.\n * @returns The strategy fields, as validation takes them.\n */\nconst pickStrategyParams = (\n params: OrderParams,\n): StrategyOrderValidationParams => ({\n twapDuration: params.twapDuration,\n twapRandomize: params.twapRandomize,\n scaleMinPrice: params.scaleMinPrice,\n scaleMaxPrice: params.scaleMaxPrice,\n scaleNumOrders: params.scaleNumOrders,\n scaleSkew: params.scaleSkew,\n chaseIntervalMs: params.chaseIntervalMs,\n chaseMaxDurationMs: params.chaseMaxDurationMs,\n chaseMaxRepricings: params.chaseMaxRepricings,\n chaseMaxDistanceBps: params.chaseMaxDistanceBps,\n});\n\n/**\n * Check a strategy placement's notional against the minimum the venue will\n * actually apply to it.\n *\n * The per-order minimum is charged against each order the venue receives, and a\n * strategy placement does not send one order:\n *\n * A `twap` is a single instruction the venue slices itself, so it is bounded by\n * the venue's own documented minimum for a TWAP rather than by the per-order\n * minimum that `validateOrder` has already applied.\n *\n * `scale` is deliberately absent. Its rungs are the orders the venue charges\n * the minimum against, and their sizes come from flooring onto the asset's size\n * grid with the remainder landing on the first rung — none of which is knowable\n * without `szDecimals`, which this check does not have. Every approximation\n * available here is unsound in one direction or the other, and the one that was\n * here rejected ladders whose submitted rungs all cleared the minimum.\n * `#buildScaleLadder` applies the exact per-rung check against the real grid\n * sizes, and it runs before anything is signed, so nothing is lost by leaving\n * the question to it.\n *\n * `chase` is absent too: it rests one order at a time, so the per-order minimum\n * the caller has already been checked against is the right bound.\n *\n * @param params - Notional parameters.\n * @param params.orderType - The order placement type.\n * @param params.orderValueUSD - Total notional of the placement, in USD.\n * @returns Validation result with isValid flag and optional error message.\n */\nconst validateStrategyNotional = (params: {\n orderType?: OrderType;\n orderValueUSD: number;\n}): { isValid: boolean; error?: string } => {\n const { orderType, orderValueUSD } = params;\n\n if (orderType === 'twap') {\n return orderValueUSD < HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd\n ? {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL,\n }\n : { isValid: true };\n }\n\n return { isValid: true };\n};\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: MetaResponse['universe'][number];\n currentPrice: number;\n meta: MetaResponse;\n};\n\ntype PrepareAssetForTradingParams = {\n symbol: string;\n assetId: number;\n leverage?: number;\n marginMode?: OrderParams['marginMode'];\n};\n\ntype Hip3TransferInfo = {\n amount: number;\n sourceDex: string;\n};\n\ntype Hip3TransferContext = {\n dexName: string;\n transferInfo: Hip3TransferInfo;\n};\n\ntype TwapOrderScope = {\n network: 'testnet' | 'mainnet';\n userAddress: string;\n orderId: string;\n};\n\ntype TwapAccountScope = Pick<TwapOrderScope, 'network' | 'userAddress'>;\n\ntype TrackedTwapOrder = {\n symbol: string;\n hip3Transfer?: Hip3TransferContext;\n rebalancePromise?: Promise<boolean>;\n};\n\ntype ChaseTerminalStatus =\n | typeof CHASE_ORDER_STATUS.Filled\n | typeof CHASE_ORDER_STATUS.Canceled\n | typeof CHASE_ORDER_STATUS.Failed;\n\ntype ChaseOrderRemainder = {\n remainingSize: string | null;\n terminalStatus: ChaseTerminalStatus | null;\n};\n\ntype ChaseTerminalResolution = {\n remainingSize: string | null;\n status: ChaseTerminalStatus;\n};\n\ntype ChaseRestingOrder = {\n orderId: string;\n price: string;\n size: string;\n};\n\ntype OrderCapabilitiesMarketCacheEntry = Readonly<{\n markets: MarketInfo[];\n freshAt: number;\n}>;\n\ntype AdaptTwapOrderParams = {\n historyEntry: HyperLiquidTwapHistoryEntry;\n sliceFills: HyperLiquidTwapSliceFillEntry[];\n now: number;\n};\n\ntype ChaseOrderMaxDistanceReachedHandler = (\n event: ChaseOrderMaxDistanceReached,\n) => void;\n\ntype HyperLiquidProviderOptions = {\n isTestnet?: boolean;\n hip3Enabled?: boolean;\n allowlistMarkets?: string[];\n blocklistMarkets?: string[];\n priceDeviationLimit?: number;\n useUnifiedAccount?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger: PerpsControllerMessengerBase;\n initialAssetMapping?: [string, number][];\n builderAddressTestnet?: string;\n builderAddressMainnet?: string;\n subscriptionBuilderAddressTestnet?: string;\n subscriptionBuilderAddressMainnet?: string;\n onChaseOrderMaxDistanceReached?: ChaseOrderMaxDistanceReachedHandler;\n getAgentSigner?: HyperLiquidCredentials['getAgentSigner'];\n // Told when the venue rejects a resolved agent (revoked or expired).\n onAgentRejected?: HyperLiquidCredentials['onAgentRejected'];\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: Hip3TransferInfo | null;\n};\n\ntype SubmitOrderWithRollbackParams = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n isHip3Order: boolean;\n dexName: string | null;\n transferInfo: Hip3TransferInfo | null;\n symbol: string;\n assetId: number;\n chargesMetamaskBuilderFee: boolean;\n builderFeeSetupContext?: BuilderFeeSetupContext;\n};\n\ntype BuilderOrderContext = { b: string; f: number };\n\ntype HandleOrderErrorParams = {\n error: unknown;\n symbol: string;\n orderType: OrderType;\n isBuy: boolean;\n reportFailure: boolean;\n};\n\ntype GetOrFetchPriceParams = {\n symbol: string;\n dexName: string | null;\n};\n\n/**\n * What every strategy placement needs before it can talk to the exchange.\n *\n * The single-order path derives the same values inline; strategy placements\n * share them through `#prepareStrategyPlacement` so the three of them cannot\n * drift apart on validation, readiness, or leverage.\n */\ntype StrategyPlacementContext = {\n assetId: number;\n szDecimals: number;\n formattedSize: string;\n builder?: BuilderOrderContext;\n dexName: string | null;\n network: 'testnet' | 'mainnet';\n transferInfo: Hip3TransferInfo | null;\n userAddress: string;\n /** The validated ladder a scale placement submits; absent for other types. */\n ladder?: ScaleLadder;\n};\n\n/**\n * A scale placement's rungs, exactly as they will be submitted.\n *\n * Built and checked before anything is signed, so the sizes and prices the\n * venue sees are the ones the minimums were applied to.\n */\ntype ScaleLadder = {\n prices: string[];\n sizes: string[];\n};\n\ntype ScaleOrderIdentity = {\n groupId: string;\n clientOrderIds: Hex[];\n};\n\n/**\n * A scale ladder's children, held so the group can be cancelled as one.\n *\n * The group can be rebuilt from open orders because each rung carries the\n * same recoverable group identity in its venue client-order ID.\n */\ntype ScaleOrderGroup = {\n symbol: string;\n orderIds: string[];\n clientOrderIds: Hex[];\n};\n\n/**\n * Create one recoverable identity for a Scale ladder and one venue CLOID per\n * rung. HyperLiquid requires every CLOID to be unique, so the last byte holds\n * the rung index while the preceding 15 bytes identify the shared group.\n *\n * The byte right after the Scale marker is reserved for the subscription flag\n * byte and is always zeroed here. Random entropy in that position would set the\n * `fee_reduction_applied` bit roughly half the time, so an unmarked ladder would\n * decode downstream as a waived one.\n *\n * @param count - Number of ladder rungs.\n * @returns The public group handle and venue client order IDs.\n */\nconst createScaleOrderIdentity = (count: number): ScaleOrderIdentity => {\n const groupKey = `${HYPERLIQUID_SCALE_CLOID_MARKER}00${uuidv4()\n .replace(/-/gu, '')\n .slice(0, 20)}`;\n const clientOrderIds = Array.from({ length: count }, (_, index) => {\n const clientOrderId: Hex = `0x${groupKey}${index\n .toString(16)\n .padStart(2, '0')}`;\n if (!isHexString(clientOrderId)) {\n throw new Error('Failed to create Scale client order ID');\n }\n return clientOrderId;\n });\n return { groupId: `scale:${groupKey}`, clientOrderIds };\n};\n\n/**\n * A running chase: the order currently resting, and the loop re-pricing it.\n */\ntype ChaseSession = {\n symbol: string;\n assetId: number;\n isBuy: boolean;\n szDecimals: number;\n reduceOnly: boolean;\n /** Exchange ID of the order resting right now, or null once it is gone. */\n orderId: string | null;\n /** Previous child ID while a replacement is between cancel and rest. */\n replacingOrderId: string | null;\n /**\n * Size the order resting right now was placed for.\n *\n * Shrinks as the chase re-prices: a child that partially filled before it was\n * cancelled leaves less to chase, and re-placing the original size would\n * execute more than the caller asked for.\n */\n size: string;\n originalSize: string;\n /**\n * Settles when an in-flight replacement has finished resting (or failed).\n * Null while no placement is in flight.\n *\n * `orderId` is null for the whole of that round trip, which is\n * indistinguishable from \"nothing rests\" unless a canceller can tell the two\n * apart — so a cancel joins this before deciding what to cancel.\n */\n pendingReplacement: Promise<void> | null;\n /** Price the resting order sits at. */\n restingPrice: string;\n arrivalPrice: string;\n startedAt: number;\n maxDistanceBps?: number;\n intervalMs: number;\n /** Last live remainder refresh used by client-facing snapshots. */\n lastSnapshotSizeRefreshAt: number;\n /**\n * Builder fee this chase was quoted at, in tenths of a basis point.\n *\n * Captured when the session starts because the rewards discount it reflects\n * is set around the caller's `placeOrder` and cleared as soon as that returns.\n * A chase returns immediately, so every replacement runs after the clear and\n * would otherwise be re-quoted at the undiscounted maximum.\n */\n builder?: BuilderOrderContext;\n /**\n * Whether this chase's orders carry the subscription cloid marking.\n *\n * Captured with {@link builder} and for the same reason: the fee resolution\n * that decides it is live only around the caller's `placeOrder`, and a chase\n * returns immediately, so every replacement runs after it is cleared. Without\n * this a replacement would pay the discounted fee the session captured while\n * shipping an unmarked cloid, and the fill could not be attributed.\n */\n marksSubscriptionCloid?: boolean;\n /** Manual HIP-3 collateral retained while this session has venue exposure. */\n hip3Transfer?: Hip3TransferContext;\n /** Coalesces concurrent terminal cleanup reads for this session. */\n hip3RebalancePromise?: Promise<boolean>;\n /** Remove a canceled session once deferred collateral cleanup succeeds. */\n removeAfterRebalance?: boolean;\n /** Absolute deadline, as a `Date.now()` stamp. */\n deadline: number;\n maxRepricings: number;\n repricings: number;\n /** Cleared when the session stops; null while no tick is pending. */\n timer: ReturnType<typeof setTimeout> | null;\n /** False once the chase has stopped re-pricing, whatever the reason. */\n active: boolean;\n status: ChaseOrderStatus;\n};\n\n/**\n * Collect the order IDs of every TP/SL child carried by a parent order.\n *\n * HyperLiquid lists `normalTpsl` children both nested under their parent and as\n * top-level entries in `frontendOpenOrders`. Those children protect the pending\n * parent order rather than the position, so callers use this set to exclude them.\n *\n * @param orders - Raw frontend open orders for the account.\n * @returns The set of child order IDs.\n */\nfunction collectChildOrderIds(orders: FrontendOrder[]): Set<number> {\n const childOrderIds = new Set<number>();\n\n orders.forEach((order) => {\n order.children?.forEach((child) => {\n childOrderIds.add(child.oid);\n });\n });\n\n return childOrderIds;\n}\n\n/**\n * Group orders by market, so a per-position pass does not rescan every order.\n *\n * @param orders - Raw frontend open orders across all DEXs.\n * @returns Orders keyed by market symbol.\n */\nfunction groupOrdersBySymbol(\n orders: FrontendOrder[],\n): Map<string, FrontendOrder[]> {\n const bySymbol = new Map<string, FrontendOrder[]>();\n\n orders.forEach((order) => {\n const existing = bySymbol.get(order.coin);\n if (existing) {\n existing.push(order);\n } else {\n bySymbol.set(order.coin, [order]);\n }\n });\n\n return bySymbol;\n}\n\n/**\n * Build the trigger-order view of a position: position-bound TP/SL plus\n * standalone (partial) reduce-only triggers on the same market, de-duplicated by\n * order ID and excluding children of pending parent orders.\n *\n * @param params - Collection parameters.\n * @param params.orders - Raw frontend open orders across all DEXs.\n * @param params.position - Position the triggers are attached to.\n * @param params.childOrderIds - Order IDs that belong to a pending parent order.\n * @returns The take profit and stop loss trigger orders for the position.\n */\nfunction collectPositionTriggerOrders(params: {\n orders: FrontendOrder[];\n position: Position;\n childOrderIds: Set<number>;\n}): {\n takeProfitOrders: PositionTriggerOrder[];\n stopLossOrders: PositionTriggerOrder[];\n takeProfitPrice?: string;\n stopLossPrice?: string;\n} {\n const { orders, position, childOrderIds } = params;\n\n const byOrderId = new Map<string, PositionTriggerOrder>();\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n\n orders.forEach((rawOrder) => {\n if (\n rawOrder.isTrigger &&\n rawOrder.reduceOnly &&\n rawOrder.isPositionTpsl === Boolean(TP_SL_CONFIG.UsePositionBoundTpsl)\n ) {\n if (rawOrder.orderType.includes('Take Profit')) {\n takeProfitPrice = rawOrder.triggerPx;\n } else if (rawOrder.orderType.includes('Stop')) {\n stopLossPrice = rawOrder.triggerPx;\n }\n }\n\n rawOrder.children?.forEach((childOrder) => {\n if (\n !childOrder.isTrigger ||\n !childOrder.reduceOnly ||\n childOrder.isPositionTpsl !== Boolean(TP_SL_CONFIG.UsePositionBoundTpsl)\n ) {\n return;\n }\n if (childOrder.orderType.includes('Take Profit')) {\n takeProfitPrice = childOrder.triggerPx;\n } else if (childOrder.orderType.includes('Stop')) {\n stopLossPrice = childOrder.triggerPx;\n }\n });\n\n if (\n rawOrder.coin !== position.symbol ||\n !rawOrder.isTrigger ||\n !rawOrder.reduceOnly ||\n childOrderIds.has(rawOrder.oid)\n ) {\n return;\n }\n\n const triggerOrder = adaptPositionTriggerOrderFromSDK({\n rawOrder,\n positionSize: position.size,\n entryPrice: position.entryPrice,\n });\n\n if (triggerOrder && !byOrderId.has(triggerOrder.orderId)) {\n byOrderId.set(triggerOrder.orderId, triggerOrder);\n }\n });\n\n const triggerOrders = Array.from(byOrderId.values());\n const takeProfitOrders = triggerOrders.filter(\n (order) => order.direction === 'take_profit',\n );\n const stopLossOrders = triggerOrders.filter(\n (order) => order.direction !== 'take_profit',\n );\n\n const takeProfitSummaryPrice = resolvePositionTriggerSummaryPrice({\n triggerOrders: takeProfitOrders,\n scannedPrice: takeProfitPrice,\n });\n const stopLossSummaryPrice = resolvePositionTriggerSummaryPrice({\n triggerOrders: stopLossOrders,\n scannedPrice: stopLossPrice,\n });\n\n return {\n takeProfitOrders,\n stopLossOrders,\n ...(takeProfitSummaryPrice && { takeProfitPrice: takeProfitSummaryPrice }),\n ...(stopLossSummaryPrice && { stopLossPrice: stopLossSummaryPrice }),\n };\n}\n\ntype HyperLiquidOrderFeeContext =\n | Readonly<OrderParams>\n | Readonly<FeeCalculationParams>;\n\ntype HyperLiquidOrderFeePolicy = Readonly<{\n chargesMetamaskBuilderFee: boolean;\n}>;\n\nconst MAX_API_FEE_RATE = 1;\nconst MAX_API_FEE_DISCOUNT = 1;\n\n/**\n * Fee applicability by canonical order type.\n *\n * The configuration type makes this map exhaustive, so a new order type cannot\n * inherit a builder-fee policy accidentally. HyperLiquid's dedicated TWAP\n * action has no builder field. Every other standalone placement uses an order\n * action that can carry one builder context. This policy is deliberately not a\n * constructor or order input. A future backend policy must be resolved inside\n * the provider from its trusted source rather than accepted from a client.\n */\nconst HYPERLIQUID_ORDER_FEE_CONFIG = {\n market: { chargesMetamaskBuilderFee: true },\n limit: { chargesMetamaskBuilderFee: true },\n stop_market: { chargesMetamaskBuilderFee: true },\n stop_limit: { chargesMetamaskBuilderFee: true },\n take_profit_market: { chargesMetamaskBuilderFee: true },\n take_profit_limit: { chargesMetamaskBuilderFee: true },\n twap: { chargesMetamaskBuilderFee: false },\n scale: { chargesMetamaskBuilderFee: true },\n chase: { chargesMetamaskBuilderFee: true },\n} satisfies Record<OrderType, HyperLiquidOrderFeePolicy>;\n\nconst MILLISECONDS_PER_MINUTE = 60_000;\nconst MILLISECONDS_PER_SECOND = 1_000;\n\n/**\n * How long #ensureReady waits before running the unified-account setup again\n * after its lookup failed on the WebSocket transport. A socket that exhausted\n * its reconnect budget rejects every request until reconnect() or reinit, so\n * retrying on every #ensureReady entry only repeats the same failure.\n */\nconst UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS = MILLISECONDS_PER_MINUTE;\n\n/**\n * Fixed messages the SDK gives a `WebSocketRequestError` raised on the client\n * side of the socket. Error frames the server sends back for a request carry\n * the server's own text instead.\n */\nconst WEBSOCKET_CLIENT_FAILURE_MESSAGES = [\n 'WebSocket connection permanently terminated',\n 'WebSocket connection closed',\n 'Request timed out after',\n 'Request aborted',\n 'Unknown error while making a WebSocket request',\n];\n\n/**\n * Whether the WebSocket transport, rather than the venue or the signer, failed\n * the request. The SDK raises `WebSocketRequestError` for client-side failures\n * (closed or terminated socket, timeout, abort), usually with the cause\n * attached, e.g. the `ReconnectingWebSocketError` (`RECONNECTION_LIMIT`,\n * `TERMINATED_BY_USER`) behind a terminated socket. It also uses\n * `WebSocketRequestError` for error frames the server sends back; those are\n * the venue's answer, have no cause and keep the server's text, so they are\n * not transport errors. The fixed messages cover client-side failures that\n * have no cause, including on engines that ignore `Error` `cause`.\n * `HyperLiquidSubscriptionService` keeps its own check for the same SDK errors\n * on the subscription paths.\n *\n * @param error - The caught error.\n * @returns True when the error, or one in its cause chain, is a WebSocket\n * transport error.\n */\nconst isWebSocketTransportError = (error: unknown): boolean =>\n hasErrorInCauseChain(\n error,\n (current) =>\n current.name === 'ReconnectingWebSocketError' ||\n (current.name === 'WebSocketRequestError' &&\n (current.cause !== undefined ||\n WEBSOCKET_CLIENT_FAILURE_MESSAGES.some((message) =>\n current.message.startsWith(message),\n ))),\n );\n\n/**\n * Normalize the TWAP history timestamp documented in seconds while tolerating\n * an already-millisecond value from a future SDK response.\n *\n * @param timestamp - Venue timestamp in seconds or milliseconds.\n * @returns Timestamp in milliseconds.\n */\nconst normalizeTwapHistoryTimestamp = (timestamp: number): number =>\n timestamp < 1_000_000_000_000\n ? timestamp * MILLISECONDS_PER_SECOND\n : timestamp;\n\nconst getTwapOrderScopeKey = (params: TwapOrderScope): string =>\n `${params.network}:${params.userAddress.toLowerCase()}:${params.orderId}`;\n\nconst resolveTwapOrderStatus = (\n historyEntry: HyperLiquidTwapHistoryEntry,\n executedSize: BigNumber,\n totalSize: BigNumber,\n): TwapOrderStatus => {\n switch (historyEntry.status.status) {\n case HyperLiquidTwapLifecycleStatus.Activated:\n case HyperLiquidTwapLifecycleStatus.WaitingForTrigger:\n return PerpsTwapLifecycleStatus.Active;\n case HyperLiquidTwapLifecycleStatus.Finished:\n return executedSize.isLessThan(totalSize)\n ? PerpsTwapLifecycleStatus.CompletedUnderfilled\n : PerpsTwapLifecycleStatus.Completed;\n case HyperLiquidTwapLifecycleStatus.Terminated:\n case HyperLiquidTwapLifecycleStatus.Stopped:\n return PerpsTwapLifecycleStatus.Canceled;\n case HyperLiquidTwapLifecycleStatus.Failed:\n return PerpsTwapLifecycleStatus.Failed;\n default:\n // A new venue status is not proof that a schedule stopped. Keep it\n // non-terminal so collateral cannot be reclaimed from a live TWAP.\n return PerpsTwapLifecycleStatus.Active;\n }\n};\n\n/**\n * Decide whether a newly adapted schedule replaces the one already collapsed\n * under the same order id.\n *\n * The venue reports one lifecycle as several history entries — an activation\n * plus a terminal record — and `lastUpdated` folds in slice fills that every\n * entry sharing a `twapId` receives. A schedule whose final fill completed it\n * therefore derives the same `lastUpdated` on both entries, because that fill\n * outranks each entry's own whole-second timestamp. Ordering on `lastUpdated`\n * alone admits that tie, letting the activation overwrite the terminal record\n * so the schedule reads as live long after it ended. Terminality decides\n * first, and an equal `lastUpdated` keeps the entry already collapsed.\n *\n * @param candidate - Schedule adapted from the current history entry.\n * @param existing - Schedule already collapsed under this order id.\n * @returns True when the candidate replaces the existing schedule.\n */\nconst supersedesCollapsedTwapOrder = (\n candidate: TwapOrder,\n existing: TwapOrder,\n): boolean => {\n const candidateIsTerminal =\n candidate.status !== PerpsTwapLifecycleStatus.Active;\n const existingIsTerminal =\n existing.status !== PerpsTwapLifecycleStatus.Active;\n if (candidateIsTerminal !== existingIsTerminal) {\n return candidateIsTerminal;\n }\n return candidate.lastUpdated > existing.lastUpdated;\n};\n\nconst adaptTwapOrderFill = (\n entry: HyperLiquidTwapSliceFillEntry,\n): TwapOrderFill => ({\n fillId: entry.fill.tid.toString(),\n orderId: entry.fill.oid.toString(),\n side: entry.fill.side === 'B' ? 'buy' : 'sell',\n price: entry.fill.px,\n size: entry.fill.sz,\n fee: entry.fill.fee,\n feeToken: entry.fill.feeToken,\n ...(entry.fill.builderFee === undefined\n ? {}\n : { builderFee: entry.fill.builderFee }),\n timestamp: entry.fill.time,\n transactionHash: entry.fill.hash,\n});\n\nconst normalizeHyperLiquidScalePriceLadder = (params: {\n minPrice: number;\n maxPrice: number;\n count: number;\n szDecimals: number;\n}): string[] => {\n const { szDecimals, ...ladderParams } = params;\n const prices = computeScalePriceLadder(ladderParams).map((price) =>\n formatHyperLiquidPrice({ price, szDecimals }),\n );\n if (new Set(prices).size !== prices.length) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n return prices;\n};\n\n/** Capability lookup result that carries resolved market metadata when ready. */\ntype HyperLiquidOrderCapabilityMarket =\n | Readonly<{ status: 'ready'; market: MarketInfo }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: DirectProviderScalePriceLadderUnavailableReason;\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 = PROVIDER_CONFIG.DefaultProvider;\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 | null, MetaResponse>();\n\n // Fresh filtered markets used only for capability discovery. Each routed\n // DEX owns its freshness window and coalesced refresh.\n readonly #orderCapabilitiesMarketsByDex = new Map<\n string | null,\n OrderCapabilitiesMarketCacheEntry\n >();\n\n readonly #orderCapabilitiesRefreshByDex = new Map<\n string | null,\n Promise<MarketInfo[]>\n >();\n\n // Sticky for this instance. PerpsController discards disconnected providers\n // during initialization; direct callers must call initialize() before reuse.\n #isDisconnected = false;\n\n #disconnectOperationsInFlight = 0;\n\n #disconnectOperationPromise: Promise<DisconnectResult> | null = null;\n\n #lifecycleGeneration = 0;\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 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 // Unified DEX discovery cache — single source of truth for all perpDexs() derivatives.\n // Replaces three separate caches to eliminate desync bugs by construction.\n // All writes go through #dexDiscoveryCache.update(); readers use .state.\n readonly #dexDiscoveryCache: DexDiscoveryCacheManager;\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 #subscriptionBuilderApprovalEpoch = 0;\n\n /** Builder approvals keyed by network, account, and builder address. */\n readonly #approvedBuilderAddresses = new Set<string>();\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 #userFeeResolution?: PerpsFeeResolution;\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 // Legacy rollback switch. MetaMask production supports unified account and\n // portfolio margin. The false branch and its manual HIP-3 transfers remain\n // temporarily for rollback compatibility and will be removed separately.\n #useUnifiedAccount: boolean;\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 // True when the most recent #ensureUnifiedAccountEnabled run ended in a\n // transient state that warrants retry (silent agent-key failure, REST\n // userAbstraction lookup failure, or keyring locked). #ensureReady resets\n // its memoized promise when this is set so the next entry retries the\n // migration instead of returning the cached resolved promise.\n #unifiedAccountSetupNeedsRetry = false;\n\n // Earliest Date.now() at which #ensureReady runs the unified-account setup\n // again after its lookup failed on the WebSocket transport. 0 = no cooldown.\n #unifiedAccountTransportRetryAt = 0;\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 'multi-sig required': PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,\n 'invalid nonce': PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE,\n };\n\n // Scale ladders placed by this provider instance, keyed by group handle, so\n // one cancel can reach every rung. Cleared on disconnect; the rung IDs are\n // also returned to the caller as `OrderResult.childOrderIds`.\n readonly #scaleOrderGroups = new Map<string, ScaleOrderGroup>();\n\n // Prevent a stale open-order cache from recreating a group that this\n // provider lifecycle already canceled successfully.\n readonly #cancelledScaleOrderGroups = new Set<string>();\n\n // Native TWAP IDs and any manual HIP-3 collateral transfer must outlive one\n // provider instance: controller disconnect/reinitialization replaces the\n // provider while the venue schedule keeps running. Each controller messenger\n // owns one registry, so separate controller lifecycles never share handles.\n static readonly #trackedTwapOrdersByMessenger = new WeakMap<\n PerpsControllerMessengerBase,\n Map<string, TrackedTwapOrder>\n >();\n\n readonly #trackedTwapOrders: Map<string, TrackedTwapOrder>;\n\n // Chase sessions running on this provider instance, keyed by session handle.\n // Each owns a pending timer, so disconnect has to stop them.\n readonly #chaseSessions = new Map<string, ChaseSession>();\n\n // In-flight termination is keyed by stable strategy handle so retries share\n // one venue mutation. Completed handles remain idempotent for this provider\n // lifecycle and are cleared on disconnect.\n readonly #chaseTerminations = new Map<string, Promise<CancelOrderResult>>();\n\n // Provider-lifetime tombstones make every later retry idempotent. Disconnect\n // clears them with the rest of the account-scoped Chase registry.\n readonly #terminatedChaseHandles = new Set<string>();\n\n // Chase placements that have reserved a slot against the venue's concurrency\n // cap but have not registered their session yet. Two round trips separate the\n // two, and a reservation is what keeps concurrent placements from both\n // passing the check.\n #chasePlacementsInFlight = 0;\n\n // Allows lifecycle teardown to wait until every placement has either\n // registered a session or retracted its newly-rested child.\n readonly #chasePlacementWaiters = new Set<Promise<void>>();\n\n // Serialize background Chase mutations. Several sessions share one signer and\n // transport, so simultaneous cancel/replace ticks would create avoidable\n // signed traffic and can starve a foreground placement.\n #chaseTickQueue: Promise<void> = Promise.resolve();\n\n // Every strategy captures this before its round trips. A changed generation\n // prevents a late response from registering handles after disconnect.\n #strategyGeneration = 0;\n\n // Reference-counted because suspension and disconnect may overlap. One\n // lifecycle owner finishing must not reopen placement while another still\n // drains or tears down the provider.\n #chasePlacementBlockers = 0;\n\n // Track whether clients have been initialized (lazy initialization)\n #clientsInitialized = false;\n\n readonly #getAgentSigner: HyperLiquidCredentials['getAgentSigner'];\n\n // Incremented by clearAgentSigners so answers pending across a clear are\n // discarded and asked again.\n #agentSignersGeneration = 0;\n\n // The getAgentSigner answer per network and main account (see\n // getAgentAccountKey), pending or non-null, so an agent is only used for its\n // account and network, and the agent it resolved to. An entry is dropped\n // when the venue rejects that agent.\n readonly #agentSigners = new Map<\n string,\n { answer: Promise<PerpsAgentSigner | null>; agent?: PerpsAgentSigner }\n >();\n\n // The account and network each agent last signed an L1 action for, keyed by\n // the lowercased address the venue reports. A rejection is attributed from\n // it rather than from the selected account, which may have changed while\n // the write was in flight; an L1 signature names no user, so one agent acts\n // for one account. Kept across clearAgentSigners, so an agent replaced while\n // its action was in flight is still recognized.\n readonly #agentSignedFor = new Map<string, AgentSignature>();\n\n // The binding of each wallet adapter this provider created.\n readonly #walletBindings = new WeakMap<\n HyperLiquidWalletParams,\n WalletBinding\n >();\n\n // The agent signature of each answered exchange request, keyed by the\n // venue answer. A \"Must deposit\" answer is attributed from it, so only to\n // the agent that signed that request.\n readonly #agentSignatureByAnswer = new WeakMap<object, AgentSignature>();\n\n readonly #onAgentRejected: HyperLiquidProviderOptions['onAgentRejected'];\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 readonly #subscriptionBuilderAddressTestnet?: string;\n\n readonly #subscriptionBuilderAddressMainnet?: string;\n\n readonly #priceDeviationLimit: number;\n\n readonly #onChaseOrderMaxDistanceReached?: ChaseOrderMaxDistanceReachedHandler;\n\n constructor(options: HyperLiquidProviderOptions) {\n this.#deps = options.platformDependencies;\n this.#messenger = options.messenger;\n const trackedTwapOrders =\n HyperLiquidProvider.#trackedTwapOrdersByMessenger.get(this.#messenger) ??\n new Map<string, TrackedTwapOrder>();\n HyperLiquidProvider.#trackedTwapOrdersByMessenger.set(\n this.#messenger,\n trackedTwapOrders,\n );\n this.#trackedTwapOrders = trackedTwapOrders;\n this.#builderAddressTestnet = options.builderAddressTestnet;\n this.#builderAddressMainnet = options.builderAddressMainnet;\n this.#subscriptionBuilderAddressTestnet =\n options.subscriptionBuilderAddressTestnet;\n this.#subscriptionBuilderAddressMainnet =\n options.subscriptionBuilderAddressMainnet;\n this.#getAgentSigner = options.getAgentSigner;\n this.#onAgentRejected = options.onAgentRejected;\n this.#onChaseOrderMaxDistanceReached =\n options.onChaseOrderMaxDistanceReached;\n this.#priceDeviationLimit =\n options.priceDeviationLimit ??\n HYPERLIQUID_CONFIG.OraclePriceDeviationLimit;\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 unified account mode, fallback to programmatic transfer if unsupported\n this.#useUnifiedAccount = options.useUnifiedAccount ?? true;\n\n // Initialize services with injected platform dependencies\n this.#clientService = new HyperLiquidClientService(this.#deps, {\n isTestnet,\n onExchangeRequest: (\n payload: unknown,\n answer: unknown,\n wallet: HyperLiquidWalletParams,\n ): void => this.#matchAgentSignature(payload, answer, wallet),\n });\n this.#dexDiscoveryCache = new DexDiscoveryCacheManager({\n isTestnetMode: (): boolean => this.#clientService.isTestnetMode(),\n debugLogger: this.#deps.debugLogger,\n getAllowlistMarkets: (): string[] => this.#allowlistMarkets,\n });\n this.#walletService = new HyperLiquidWalletService(\n this.#deps,\n this.#messenger,\n { isTestnet },\n );\n this.#subscriptionService = new HyperLiquidSubscriptionService(\n this.#clientService,\n {\n // The subscription service may initialize the SDK clients too, so\n // its wallets are bound like the provider's.\n createWalletAdapter: (): HyperLiquidWalletParams =>\n this.#createWalletAdapter(),\n getUserAddressWithDefault: async (\n accountId?: CaipAccountId,\n ): Promise<Hex> =>\n await this.#walletService.getUserAddressWithDefault(accountId),\n },\n this.#deps,\n this.#hip3Enabled,\n [], // enabledDexs - will be populated after DEX discovery in buildAssetMapping\n this.#allowlistMarkets,\n this.#blocklistMarkets,\n this.#priceDeviationLimit,\n async () => {\n await this.#ensureClientsInitialized();\n const validatedDexs = await this.#getValidatedDexs();\n if (this.#hip3Enabled && !this.#dexDiscoveryCache.state?.validated) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n return validatedDexs.filter((dex): dex is string => dex !== null);\n },\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 * Resolve the provider-owned fee policy for one placement context.\n *\n * The full context is accepted so future policies can vary by market route\n * or other order inputs without changing the provider contract. Runtime\n * callers can still bypass TypeScript, so an unknown order type falls back to\n * the revenue-preserving standard policy and is made observable.\n *\n * @param params - Fee quote or placement context.\n * @returns HyperLiquid's fee policy for this order.\n */\n #resolveOrderFeePolicy(\n params: HyperLiquidOrderFeeContext,\n ): HyperLiquidOrderFeePolicy {\n const fallbackPolicy = Object.prototype.hasOwnProperty.call(\n HYPERLIQUID_ORDER_FEE_CONFIG,\n params.orderType,\n )\n ? HYPERLIQUID_ORDER_FEE_CONFIG[params.orderType]\n : undefined;\n if (fallbackPolicy) {\n return fallbackPolicy;\n }\n\n this.#deps.debugLogger.log(\n 'HyperLiquid: Unknown order type used the safe builder-fee policy',\n { orderType: params.orderType },\n );\n return HYPERLIQUID_ORDER_FEE_CONFIG.market;\n }\n\n /**\n * Return provider-owned standalone trigger, strategy and margin-mode support\n * for a routed market. HyperLiquid advertises its implemented trigger types\n * and strategies uniformly after confirming the routed market exists;\n * margin modes follow the market's metadata.\n *\n * @param params - Required market route context.\n * @returns Supported standalone trigger types, strategies and margin modes.\n */\n async getOrderCapabilities(\n params: GetOrderCapabilitiesParams,\n ): Promise<DirectProviderOrderCapabilities> {\n const result = await this.#getOrderCapabilityMarket(params.symbol);\n if (result.status === 'unavailable') {\n return result;\n }\n const supportedMarginModes: readonly MarginMode[] = Object.freeze(\n this.#isCrossMarginSupported(params.symbol, result.market)\n ? ['isolated', 'cross']\n : ['isolated'],\n );\n return Object.freeze({\n ...HYPERLIQUID_ORDER_CAPABILITIES,\n supportedMarginModes,\n });\n }\n\n /**\n * Whether the venue accepts Cross margin for a market. Both SDK\n * `marginMode` values (strictIsolated and noCross) prohibit Cross, and any\n * future restriction value is treated as unsupported until handled\n * explicitly. HIP-3 collateral transfers still assume isolated margin, so\n * Cross stays unavailable there until that account-mode-aware path is\n * supported.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @param asset - Venue margin metadata for the market.\n * @param asset.onlyIsolated - Whether the market only allows isolated margin.\n * @param asset.marginMode - Venue margin-mode restriction, if any.\n * @returns True when Cross margin orders are accepted.\n */\n #isCrossMarginSupported(\n symbol: string,\n asset: { onlyIsolated?: boolean; marginMode?: string },\n ): boolean {\n const { dex } = parseAssetName(symbol);\n return !asset.onlyIsolated && !asset.marginMode && dex === null;\n }\n\n /**\n * Report the margin mode HyperLiquid currently binds to a market, so\n * clients can match what order placement will accept.\n *\n * @param params - Market and optional provider route.\n * @returns The current lock, or unavailable when it cannot be read.\n */\n async getMarginModeLock(\n params: GetMarginModeLockParams,\n ): Promise<PerpsMarginModeLock> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n await this.#ensureClientsInitialized();\n this.#clientService.ensureInitialized();\n const lock = await this.#readMarginModeLock(params.symbol);\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Margin mode lock read',\n );\n return lock\n ? { status: 'locked', providerId: this.protocolId, ...lock }\n : { status: 'unlocked', providerId: this.protocolId };\n } catch (error) {\n this.#deps.debugLogger.log('HyperLiquid: Margin mode lock unavailable', {\n symbol: params.symbol,\n error: ensureError(error, 'HyperLiquidProvider.getMarginModeLock')\n .message,\n });\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n }\n\n /**\n * Normalize a Scale price ladder with HyperLiquid market precision.\n *\n * @param params - Market, ladder bounds, count, and optional provider route.\n * @returns HyperLiquid-normalized prices or a typed unavailable result.\n * @throws When the ladder count or normalized range is invalid.\n */\n async getScalePriceLadder(\n params: GetScalePriceLadderParams,\n ): Promise<PerpsScalePriceLadder> {\n if (\n params.providerId !== undefined &&\n params.providerId !== this.protocolId\n ) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_not_routable',\n };\n }\n\n const result = await this.#getOrderCapabilityMarket(params.symbol);\n if (result.status === 'unavailable') {\n return result;\n }\n\n const prices = normalizeHyperLiquidScalePriceLadder({\n minPrice: params.minPrice,\n maxPrice: params.maxPrice,\n count: params.count,\n szDecimals: result.market.szDecimals,\n });\n\n return { status: 'ready', providerId: this.protocolId, prices };\n }\n\n /**\n * Resolve fresh market metadata shared by capability and ladder reads.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The resolved market or a typed unavailable result.\n */\n async #getOrderCapabilityMarket(\n symbol: string,\n ): Promise<HyperLiquidOrderCapabilityMarket> {\n if (!isValidCapabilitySymbol(symbol, { allowProviderRoute: true })) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'invalid_symbol',\n };\n }\n if (this.#isDisconnected) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n\n const { dex } = parseAssetName(symbol);\n const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n const market = (await this.#getFreshOrderCapabilityMarkets(dex)).find(\n ({ name }) => name === symbol,\n );\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability read',\n );\n return market\n ? { status: 'ready', market }\n : {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'market_not_found',\n };\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Order capability market unavailable',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.getOrderCapabilityMarket',\n ).message,\n },\n );\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n }\n\n /**\n * Reject provider work that crossed an asynchronous disconnect boundary.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation error.\n */\n #assertProviderLifecycleCurrent(generation: number, operation: string): void {\n if (this.#isDisconnected || generation !== this.#lifecycleGeneration) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Provider operation became stale during disconnect',\n { operation },\n );\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n }\n\n /**\n * Reject cache writes from an old lifecycle or while teardown is active.\n * General reads may lazily rebuild caches after disconnect completes, but a\n * request that crossed the disconnect boundary must not repopulate them.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation log.\n */\n #assertCacheWriteLifecycleCurrent(\n generation: number,\n operation: string,\n ): void {\n if (!this.#isCacheWriteLifecycleCurrent(generation, operation)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n }\n\n /**\n * Check whether fetched data may still populate provider caches.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation log.\n * @returns Whether a cache write is safe.\n */\n #isCacheWriteLifecycleCurrent(\n generation: number,\n operation: string,\n ): boolean {\n if (\n this.#disconnectOperationsInFlight > 0 ||\n generation !== this.#lifecycleGeneration\n ) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Cache write became stale during disconnect',\n { operation },\n );\n return false;\n }\n return true;\n }\n\n /**\n * Return filtered market metadata fresh enough for a capability query.\n * Each DEX shares one refresh across concurrent callers, and a failed\n * refresh remains immediately retryable.\n *\n * @param dex - Routed DEX, or null for the main DEX.\n * @returns Fresh filtered markets for that route.\n */\n async #getFreshOrderCapabilityMarkets(\n dex: string | null,\n ): Promise<MarketInfo[]> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const cachedMarkets = this.#orderCapabilitiesMarketsByDex.get(dex);\n if (\n cachedMarkets &&\n Date.now() - cachedMarkets.freshAt <\n PERFORMANCE_CONFIG.OrderCapabilitiesMetaFreshnessMs\n ) {\n return cachedMarkets.markets;\n }\n\n let refreshPromise = this.#orderCapabilitiesRefreshByDex.get(dex);\n if (!refreshPromise) {\n refreshPromise = (async (): Promise<MarketInfo[]> => {\n const markets = await this.#fetchMarketsForDex({\n dex,\n skipCache: true,\n });\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability metadata refresh',\n );\n\n this.#orderCapabilitiesMarketsByDex.set(dex, {\n markets,\n freshAt: Date.now(),\n });\n return markets;\n })();\n this.#orderCapabilitiesRefreshByDex.set(dex, refreshPromise);\n }\n\n try {\n const markets = await refreshPromise;\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability read',\n );\n return markets;\n } finally {\n if (this.#orderCapabilitiesRefreshByDex.get(dex) === refreshPromise) {\n this.#orderCapabilitiesRefreshByDex.delete(dex);\n }\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.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n\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 if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\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 if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n\n const wallet = this.#createWalletAdapter();\n await this.#clientService.initialize(wallet);\n if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\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 * Create a wallet adapter for the SDK clients, bound to the network and\n * session it is created in: its agents are resolved, and its signatures\n * attributed, for them, even when a queued write signs after a network\n * switch or a disconnect.\n *\n * @returns The wallet adapter.\n */\n #createWalletAdapter(): HyperLiquidWalletParams {\n const binding: WalletBinding = {\n isTestnet: this.#clientService.isTestnetMode(),\n generation: this.#lifecycleGeneration,\n unansweredSignatures: new Map(),\n };\n const wallet = this.#walletService.createWalletAdapter(\n async (mainAddress: Hex): Promise<PerpsAgentSigner | null> =>\n await this.#resolveTrackedAgentSigner(mainAddress, binding),\n );\n this.#walletBindings.set(wallet, binding);\n return wallet;\n }\n\n /**\n * Resolve the agent that signs L1 actions for a main account on a network\n * through `getAgentSigner`. A non-null answer is kept;\n * null and failures are not, so the next L1 action asks again. An answer\n * pending across clearAgentSigners is discarded and asked again.\n *\n * @param mainAddress - The selected main account.\n * @param isTestnet - The network of the wallet adapter that signs.\n * @returns The agent, or null to sign with the main account.\n */\n async #resolveAgentSigner(\n mainAddress: Hex,\n isTestnet: boolean,\n ): Promise<PerpsAgentSigner | null> {\n const account: PerpsAgentAccount = { mainAddress, isTestnet };\n const key = getAgentAccountKey(account);\n const generation = this.#agentSignersGeneration;\n let entry = this.#agentSigners.get(key);\n if (!entry) {\n if (!this.#getAgentSigner) {\n return null;\n }\n let answer: Promise<PerpsAgentSigner | null>;\n try {\n answer = this.#getAgentSigner(account);\n } catch (error) {\n answer = Promise.reject(error);\n }\n entry = { answer };\n this.#agentSigners.set(key, entry);\n }\n\n const pendingEntry = entry;\n // A clear while this answer was pending wins, so it is asked again. Only a\n // clear replaces a pending answer: every other removal happens once it\n // settled, after all its callers resumed.\n const isSuperseded = (): boolean =>\n generation !== this.#agentSignersGeneration;\n\n let agentSigner: PerpsAgentSigner | null;\n try {\n agentSigner = await pendingEntry.answer;\n } catch (error) {\n if (isSuperseded()) {\n return await this.#resolveAgentSigner(mainAddress, isTestnet);\n }\n this.#agentSigners.delete(key);\n this.#deps.debugLogger.log('HyperLiquidProvider: getAgentSigner failed', {\n error: ensureError(error, 'HyperLiquidProvider.resolveAgentSigner')\n .message,\n });\n throw new AgentSignerUnavailableError(error);\n }\n\n if (isSuperseded()) {\n return await this.#resolveAgentSigner(mainAddress, isTestnet);\n }\n if (agentSigner) {\n pendingEntry.agent = agentSigner;\n // The wallet adapter resolves at every L1 signature, so this records\n // the account the agent is about to sign for.\n this.#agentSignedFor.set(agentSigner.address.toLowerCase(), {\n key,\n account,\n agentAddress: agentSigner.address,\n });\n } else {\n this.#agentSigners.delete(key);\n }\n return agentSigner;\n }\n\n /**\n * Map and log a failed exchange write, unless the signer could not sign it\n * (`KEYRING_LOCKED`: a locked keyring, or an unavailable or rejected\n * agent), which the caller retries.\n *\n * @param error - The caught error.\n * @param method - The write that failed.\n * @param extra - Context for the log.\n * @param errorTags - Bounded tags describing the failed write.\n * @returns The mapped error.\n */\n async #reportWriteError(\n error: unknown,\n method: string,\n extra: Record<string, unknown>,\n errorTags: PerpsErrorTags,\n ): Promise<Error> {\n const signerFailure = await this.#handleSignerFailure(error, method, extra);\n if (signerFailure) {\n return signerFailure;\n }\n const mappedError = this.#mapError(error);\n this.#deps.logger.error(\n mappedError,\n await this.#getTradingErrorContext(method, mappedError, extra, errorTags),\n );\n return mappedError;\n }\n\n /**\n * The agent a venue rejection names, with the account and network it last\n * signed for. HyperLiquid answers \"User or API Wallet 0x... does not\n * exist.\" with the signer's address, so for a revoked or expired agent it\n * reads like a wallet with no account. It sometimes answers \"Must deposit\n * before performing actions. User: 0x...\" with the main account instead;\n * that is attributed to the agent that signed the answered request (see\n * #findRevokedAgent).\n *\n * @param error - The caught error.\n * @returns The rejected agent, with its address as the host supplied it\n * and the account it signed for, or undefined.\n */\n async #findRejectedAgent(\n error: unknown,\n ): Promise<AgentSignature | undefined> {\n if (this.#agentSignedFor.size === 0) {\n return undefined;\n }\n const { message } = ensureError(\n error,\n 'HyperLiquidProvider.findRejectedAgent',\n );\n const answer = getVenueAnswer(error);\n const signature = isStatusObject(answer)\n ? this.#agentSignatureByAnswer.get(answer)\n : undefined;\n if (isHyperLiquidUserNotFoundError(error)) {\n const reportedAddress =\n UNKNOWN_WALLET_ADDRESS_PATTERN.exec(message)?.[1]?.toLowerCase();\n if (reportedAddress === undefined) {\n return undefined;\n }\n // The agent that signed the answered request, on its wallet's network.\n // When no signature is linked to the answer (it did not come through\n // an exchange client of this provider), the account the agent last\n // signed an L1 action for.\n if (signature) {\n return signature.agentAddress.toLowerCase() === reportedAddress\n ? signature\n : undefined;\n }\n return this.#agentSignedFor.get(reportedAddress);\n }\n const mainAddress = MUST_DEPOSIT_USER_PATTERN.exec(message)?.[1];\n return mainAddress !== undefined &&\n signature?.account.mainAddress.toLowerCase() === mainAddress.toLowerCase()\n ? await this.#findRevokedAgent(signature)\n : undefined;\n }\n\n /**\n * The agent that signed a request the venue answered with \"Must deposit\n * before performing actions\", if the venue no longer lists it (revoked, or\n * past its `validUntil`). The venue answers an account with no funds the\n * same way, so the agent list decides; it is asked once per signature. A\n * signature made through the wallet of an earlier network or session is\n * not checked.\n *\n * @param signature - The agent signature of the request.\n * @returns The revoked agent, or undefined.\n */\n async #findRevokedAgent(\n signature: AgentSignature,\n ): Promise<AgentSignature | undefined> {\n const isCurrent = (): boolean =>\n signature.generation === this.#lifecycleGeneration &&\n signature.account.isTestnet === this.#clientService.isTestnetMode();\n if (!isCurrent()) {\n return undefined;\n }\n signature.approvalCheck ??= this.#isAgentListed(signature);\n const listed = await signature.approvalCheck;\n return listed || !isCurrent() ? undefined : signature;\n }\n\n /**\n * Resolve the agent for an L1 signature of a wallet adapter, on the\n * adapter's network, and note each signature it makes in the adapter's\n * binding, so the venue's answer to that request is attributed to it.\n *\n * @param mainAddress - The selected main account.\n * @param binding - The binding of the wallet adapter that signs.\n * @returns The agent, or null to sign with the main account.\n */\n async #resolveTrackedAgentSigner(\n mainAddress: Hex,\n binding: WalletBinding,\n ): Promise<PerpsAgentSigner | null> {\n const account: PerpsAgentAccount = {\n mainAddress,\n isTestnet: binding.isTestnet,\n };\n const agent = await this.#resolveAgentSigner(\n mainAddress,\n binding.isTestnet,\n );\n if (!agent) {\n return null;\n }\n return {\n address: agent.address,\n signTypedData: async (payload): Promise<Hex> => {\n const signature = await agent.signTypedData(payload);\n // The SDK refuses any other signature before sending the request,\n // so no answer would come for it.\n if (isHexString(signature) && signature.length === 132) {\n binding.unansweredSignatures.set(getSignatureKey(signature), {\n key: getAgentAccountKey(account),\n account,\n agentAddress: agent.address,\n generation: binding.generation,\n });\n }\n return signature;\n },\n };\n }\n\n /**\n * Link the venue's answer to an exchange request with the agent signature\n * the request carries, if an agent signed it.\n *\n * @param payload - The exchange request.\n * @param answer - The venue's answer, or undefined when there is none.\n * @param wallet - The wallet adapter the request was signed through.\n */\n #matchAgentSignature(\n payload: unknown,\n answer: unknown,\n wallet: HyperLiquidWalletParams,\n ): void {\n const signature =\n isStatusObject(payload) && isStatusObject(payload.signature)\n ? payload.signature.r\n : undefined;\n if (typeof signature !== 'string') {\n return;\n }\n const unansweredSignatures =\n this.#walletBindings.get(wallet)?.unansweredSignatures;\n const key = getSignatureKey(signature);\n const agentSignature = unansweredSignatures?.get(key);\n if (!agentSignature) {\n return;\n }\n unansweredSignatures?.delete(key);\n if (isStatusObject(answer)) {\n this.#agentSignatureByAnswer.set(answer, agentSignature);\n }\n }\n\n /**\n * Whether the venue lists an agent as approved for its main account.\n * `validUntil` is compared with this device's clock.\n *\n * @param agent - The agent and the account it signed for.\n * @param agent.account - The account the agent signed for.\n * @param agent.agentAddress - The agent.\n * @returns False when the agent is missing or expired. True when it is\n * listed, or when the list cannot be read, so the venue's error stands.\n */\n async #isAgentListed({\n account,\n agentAddress,\n }: {\n account: PerpsAgentAccount;\n agentAddress: Hex;\n }): Promise<boolean> {\n try {\n const agents = await this.#clientService\n .getInfoClient({ useHttp: true })\n .extraAgents({ user: account.mainAddress });\n const listed = agents.find(\n ({ address }) => address.toLowerCase() === agentAddress.toLowerCase(),\n );\n return (\n listed !== undefined &&\n (listed.validUntil === null || listed.validUntil > Date.now())\n );\n } catch (error) {\n this.#deps.debugLogger.log('HyperLiquidProvider: extraAgents failed', {\n error: ensureError(error, 'HyperLiquidProvider.isAgentListed').message,\n });\n return true;\n }\n }\n\n /**\n * Handle a venue rejection of an agent: drop it if it is still the\n * resolved one, so the next L1 action asks for one again, and tell the\n * owner of the bindings.\n *\n * @param error - The caught error.\n * @returns True when the error was the rejection of an agent.\n */\n async #evictRejectedAgent(error: unknown): Promise<boolean> {\n const rejected = await this.#findRejectedAgent(error);\n if (!rejected) {\n return false;\n }\n const { account, key, agentAddress } = rejected;\n if (this.#agentSigners.get(key)?.agent?.address === agentAddress) {\n this.#agentSigners.delete(key);\n }\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: agent rejected by the venue, asking again',\n { agent: agentAddress },\n );\n try {\n this.#onAgentRejected?.(account, agentAddress);\n } catch (callbackError) {\n this.#deps.debugLogger.log('HyperLiquidProvider: onAgentRejected threw', {\n error: ensureError(\n callbackError,\n 'HyperLiquidProvider.evictRejectedAgent',\n ).message,\n });\n }\n return true;\n }\n\n /**\n * Whether an exchange write failed because its signer could not sign it:\n * a locked keyring, an unavailable agent, or an agent the venue rejected.\n * It does not evict; the caller that reports the failure classifies it.\n *\n * @param error - The caught error.\n * @returns True for a signer failure.\n */\n async #isSignerFailure(error: unknown): Promise<boolean> {\n return (\n isKeyringLockedError(error) ||\n isAgentSignerUnavailableError(error) ||\n (await this.#findRejectedAgent(error)) !== undefined\n );\n }\n\n /**\n * Classify a failed exchange write whose signer could not sign it, evicting\n * a rejected agent. The next attempt retries.\n *\n * @param error - The caught error.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #classifySignerFailure(error: unknown): Promise<Error | undefined> {\n const rejectedAgent = await this.#evictRejectedAgent(error);\n return rejectedAgent ||\n isKeyringLockedError(error) ||\n isAgentSignerUnavailableError(error)\n ? new Error(PERPS_ERROR_CODES.KEYRING_LOCKED)\n : undefined;\n }\n\n /**\n * Classify a failed write whose signer could not sign it, and note it as\n * retryable instead of reporting it.\n *\n * @param error - The caught error.\n * @param method - The write that failed.\n * @param extra - Context for the debug log.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #handleSignerFailure(\n error: unknown,\n method: string,\n extra: Record<string, unknown>,\n ): Promise<Error | undefined> {\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n this.#logRetryableSignerFailure(method, extra);\n }\n return signerFailure;\n }\n\n /**\n * Note a write that failed because its signer could not sign it; the\n * caller retries it, so it is not reported as an error.\n *\n * @param method - The write that failed.\n * @param extra - Context for the debug log.\n */\n #logRetryableSignerFailure(\n method: string,\n extra: Record<string, unknown>,\n ): void {\n this.#deps.debugLogger.log(\n `[${method}] Signer unavailable, the write can be retried`,\n extra,\n );\n }\n\n /**\n * Decide whether the wallet has a Hyperliquid account.\n *\n * Hyperliquid accounts are created server-side on first USDC deposit.\n * Before that, every user-scoped exchange write rejects with\n * \"User or API Wallet 0x... does not exist.\" — formerly the top source\n * of `feature:perps` Sentry events (Sentry issues METAMASK-MOBILE-4XB5\n * iOS / 4Q4M Android: ~530k events / ~100k users in 14d on 7.75.1).\n *\n * Probes `infoClient.userNonFundingLedgerUpdates` and caches a positive\n * result in `PerpsSigningCache.walletRegistered`. Negative results are NOT\n * cached — the wallet may deposit between checks; the next entry must\n * re-probe. The probe is cheap (~100ms), non-throwing, and returns the\n * full deposit/withdraw history. A non-empty array means the wallet has\n * interacted with Hyperliquid at least once — necessary and sufficient\n * for `agentSetAbstraction` / `setReferrer` to\n * succeed.\n *\n * If the probe itself throws (transient network), returns `true` and does\n * not cache — fail open so one bad probe never traps a real Hyperliquid\n * user in the deferred state.\n *\n * @param userAddress - The wallet address to check.\n * @param network - The network environment (mainnet | testnet).\n * @returns True if the wallet has been observed on Hyperliquid OR if\n * the probe was inconclusive (fail open). False only when the probe\n * succeeded AND returned an empty ledger.\n * @private\n */\n async #isWalletOnHyperliquid(\n userAddress: string,\n network: 'mainnet' | 'testnet',\n ): Promise<boolean> {\n const cached = PerpsSigningCache.getWalletRegistered(network, userAddress);\n if (cached?.registered) {\n return true;\n }\n\n try {\n const infoClient = this.#clientService.getInfoClient();\n const ledger = await infoClient.userNonFundingLedgerUpdates({\n user: userAddress,\n startTime: 0,\n });\n const registered = Array.isArray(ledger) && ledger.length > 0;\n if (registered) {\n PerpsSigningCache.setWalletRegistered(network, userAddress, true);\n }\n return registered;\n } catch (error) {\n // Fail open. A transient probe failure must never prevent a\n // legitimate Hyperliquid user from completing migration / referral\n // setup. The next entry will re-probe.\n this.#deps.debugLogger.log(\n '[isWalletOnHyperliquid] Probe failed, assuming registered',\n {\n network,\n user: userAddress,\n error: ensureError(error, 'HyperLiquidProvider.isWalletOnHyperliquid')\n .message,\n },\n );\n return true;\n }\n }\n\n /**\n * Decide whether the Hyperliquid account is a multi-sig account.\n *\n * Hyperliquid rejects every single-signer exchange write for a converted\n * multi-sig account with `ApiRequestError: Multi-sig required`, so the\n * unified-account migration must not be attempted for those accounts.\n *\n * If the probe throws (transient network), returns `false` — fail open so\n * one bad probe never blocks migration for a normal single-signer account.\n * The `isHyperLiquidMultiSigRequiredError` fallback in the write's catch\n * block remains the safety net.\n *\n * @param userAddress - The wallet address to check.\n * @param infoClient - Optional captured reader for an operation-scoped probe.\n * @returns True only when Hyperliquid reports a multi-sig signer set.\n * @private\n */\n async #isHyperliquidMultiSigAccount(\n userAddress: string,\n infoClient = this.#clientService.getInfoClient(),\n ): Promise<boolean> {\n try {\n const signers = await infoClient.userToMultiSigSigners({\n user: userAddress,\n });\n return signers !== null && signers !== undefined;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[isHyperliquidMultiSigAccount] Probe failed, assuming single-signer',\n {\n user: userAddress,\n error: ensureError(\n error,\n 'HyperLiquidProvider.isHyperliquidMultiSigAccount',\n ).message,\n },\n );\n return false;\n }\n }\n\n /**\n * Attempt to enable HyperLiquid Unified Account mode for HIP-3 orders\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 * @param options - Optional configuration.\n * @param options.allowUserSigning - When true, runs the migration for `default` / `disabled` accounts. Defaults to false so init does not surface a signing prompt; action-time entry points (trading, withdraw) pass true.\n * @private\n */\n async #ensureUnifiedAccountEnabled(options?: {\n allowUserSigning?: boolean;\n }): Promise<void> {\n // Without an agent, the migration is signed by the main wallet, which can\n // prompt (hardware wallets). Init calls with allowUserSigning=false so\n // viewing the Perps section never surfaces a signing dialog. Trading and\n // withdraw entry points pass allowUserSigning=true to drive the migration when\n // the user actually intends to act.\n const allowUserSigning = options?.allowUserSigning ?? false;\n\n // Optimistic reset — set true below only at the failure points that\n // warrant retry (silent agent failure, REST lookup failure, keyring\n // locked). Final-state outcomes (success, prompted-failure cached,\n // already-on-compatible, defer, unknown mode, feature off) leave it\n // false so #ensureReady can keep the memoized promise.\n this.#unifiedAccountSetupNeedsRetry = false;\n\n if (!this.#useUnifiedAccount) {\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 repeated signing prompts\n // while browsing.\n const cachedStatus = TradingReadinessCache.get(network, userAddress);\n if (cachedStatus?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup 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 let inFlightPromise = PerpsSigningCache.isInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n while (inFlightPromise) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup in-flight, waiting...',\n { network, userAddress },\n );\n await inFlightPromise;\n // The other instance may have finished without writing the cache (e.g.\n // an init-time call deferred the migration). If the cache\n // is still empty and we are an action-time caller (allowUserSigning=true),\n // we must run our own attempt — otherwise the trade/withdraw would\n // proceed in the deprecated mode.\n const postWaitCache = TradingReadinessCache.get(network, userAddress);\n if (postWaitCache?.attempted) {\n return;\n }\n // Another waiter may have taken the lock first. The lock is checked\n // and taken with no await in between, so only one waiter gets it.\n inFlightPromise = PerpsSigningCache.isInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n }\n\n // Set in-flight lock to prevent concurrent attempts\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n\n let currentMode: UserAbstractionResponse | undefined;\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: Unified Account setup completed by another provider',\n { network, userAddress },\n );\n completeInFlight();\n return;\n }\n\n // Skip the migration entirely for wallets that have no Hyperliquid\n // account yet. HL creates accounts server-side on first USDC deposit;\n // before that, `agentSetAbstraction` rejects with \"User or API Wallet 0x... does not exist.\" — formerly\n // the top source of `feature:perps` Sentry events on 7.75.1.\n // The probe is cheap, non-throwing, and cached.\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n if (!isRegistered) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Wallet not yet on Hyperliquid, deferring migration',\n { user: userAddress, network },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'no_hl_account',\n });\n // Signal #ensureReady to drop its memoized promise so the next entry\n // re-probes. Without this, the resolved promise would be reused and\n // the wallet would stay permanently deferred until reconnect.\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n\n // Check current abstraction mode on-chain\n currentMode = await infoClient.userAbstraction({\n user: userAddress,\n });\n\n if (\n currentMode === 'unifiedAccount' ||\n currentMode === 'portfolioMargin'\n ) {\n // portfolioMargin is a superset of unifiedAccount — it already supports\n // auto-collateral management for HIP-3 orders and is more capital-efficient.\n // Downgrading portfolio margin users to unifiedAccount would be harmful,\n // so we treat both modes as already-enabled and skip migration.\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Account already in a compatible mode, skipping migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.ALREADY_ENABLED,\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n // Record the resolved mode in the subscription service so the next\n // aggregation folds spot correctly without waiting for #refreshSpotState.\n this.#subscriptionService.setUserAbstractionMode(\n userAddress,\n currentMode,\n );\n completeInFlight();\n return;\n }\n\n // Defer signing-backed transitions until the user attempts an action.\n // Cache is intentionally left untouched so the next entry re-evaluates;\n // the read-only userAbstraction call is cheap and gated by the in-flight\n // lock, preventing concurrent prompts.\n if (shouldDeferUnifiedAccountSetup(currentMode, allowUserSigning)) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Deferring unified account migration to action time',\n { user: userAddress, network, mode: currentMode },\n );\n completeInFlight();\n return;\n }\n\n // Bail on unknown modes BEFORE firing analytics or attempting dispatch.\n // Keeps `migration_required` actionable (only fires for modes we can\n // actually migrate) and avoids re-emitting on every reconnection.\n if (currentMode !== 'default' && currentMode !== 'disabled') {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unknown abstraction mode, skipping Unified Account migration',\n { user: userAddress, network, mode: currentMode },\n );\n completeInFlight();\n return;\n }\n\n // Hyperliquid rejects every single-signer exchange write for a converted\n // multi-sig account with \"ApiRequestError: Multi-sig required\", which\n // surfaced on the Perps tab on every entry (TAT-3214). Probe right\n // before the write so accounts that never reach one (already compatible,\n // deferred, unknown mode) do not pay the extra round trip.\n const isMultiSig = await this.#isHyperliquidMultiSigAccount(userAddress);\n if (isMultiSig) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Multi-sig account, skipping unified account migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'multi_sig_account',\n });\n // Final state: the write can never succeed for this account, so cache\n // it as attempted with unified mode off. Perps keeps working through\n // the programmatic collateral-transfer fallback.\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n completeInFlight();\n return;\n }\n\n // Track which mode users are currently on before we attempt migration.\n // This tells us the distribution of legacy modes across our user base.\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.MIGRATION_REQUIRED,\n });\n\n // Enable Unified Account mode (default / disabled → unifiedAccount).\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Enabling Unified Account mode',\n {\n user: userAddress,\n network,\n previousMode: currentMode,\n note: 'HyperLiquid will auto-manage collateral for HIP-3 orders',\n },\n );\n\n await this.#clientService.getExchangeClient().agentSetAbstraction({\n abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,\n });\n\n this.#deps.debugLogger.log(\n '✅ HyperLiquidProvider: Unified Account enabled successfully',\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.SUCCESS,\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n // Record the post-migration mode in the subscription service so it\n // immediately re-aggregates with fold=true and surfaces the unified\n // balance rather than waiting for the next #refreshSpotState.\n this.#subscriptionService.setUserAbstractionMode(\n userAddress,\n HL_UNIFIED_ACCOUNT_MODE,\n );\n completeInFlight();\n } catch (error) {\n // The signer could not sign (a locked keyring, or an unavailable or\n // rejected agent; HyperLiquid keeps the cause in `cause`): leave the\n // cache empty and retry later.\n if (await this.#classifySignerFailure(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Signer unavailable, will retry later',\n );\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net: a Hyperliquid \"user does not exist\" rejection slipped\n // past the proactive probe (race with deposit confirmation, transient\n // probe failure that failed open, ...). Treat as benign — do NOT\n // forward to Sentry. The walletRegistered cache stores positive\n // observations only, so no demotion is needed; the next entry will\n // re-probe.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Wallet not on Hyperliquid (race/stale-cache), deferring migration',\n { user: userAddress, network, currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'no_hl_account',\n });\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net for the multi-sig probe: the account can be converted\n // between the lookup and the write, and the probe fails open on\n // transient info-API errors. Either way the rejection is a permanent\n // account-shape condition, not a failure worth reporting or retrying.\n if (isHyperLiquidMultiSigRequiredError(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Multi-sig account (race/probe fallback), skipping unified account migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'multi_sig_account',\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n completeInFlight();\n return;\n }\n\n // The WebSocket transport could not carry the lookup, typically a\n // socket that exhausted its reconnect budget (Sentry METAMASK-ZHT9).\n // That is connectivity, not a migration failure: keep it out of Sentry\n // and analytics, keep the retry flag, and have #ensureReady wait out a\n // cooldown instead of repeating the lookup on every entry.\n if (isWebSocketTransportError(error)) {\n this.#unifiedAccountTransportRetryAt =\n Date.now() + UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS;\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] WebSocket transport unavailable, will retry after cooldown',\n {\n user: userAddress,\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureUnifiedAccountEnabled',\n ).message,\n cooldownMs: UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS,\n },\n );\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Agent-path failures and read-only userAbstraction lookup failures\n // are not final: signal #ensureReady to drop its memoized promise and\n // retry on the next entry instead of pinning the user in the\n // deprecated mode for the provider's lifetime.\n this.#unifiedAccountSetupNeedsRetry = true;\n\n const errorMessage = ensureError(\n error,\n 'HyperLiquidProvider.ensureUnifiedAccountEnabled',\n ).message;\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup failed',\n {\n user: userAddress,\n network,\n error: errorMessage,\n },\n );\n\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,\n });\n\n completeInFlight();\n\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureUnifiedAccountEnabled'),\n this.#getErrorContext(\n 'ensureUnifiedAccountEnabled',\n {\n note: 'Could not enable Unified Account (user rejected, or network error)',\n },\n {\n operation: PERPS_ERROR_OPERATION.ConnectionManagement,\n component: PERPS_ERROR_COMPONENT.ConnectionManager,\n action: PERPS_ERROR_ACTION.ConnectionConnection,\n },\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 // Attempt Unified Account migration as early as possible so users aren't\n // blocked when they try to trade. Software wallets can complete the\n // signing-backed migration during initial setup so the first trade sees\n // the unified balance. Hardware wallets remain deferred to action time to\n // avoid repeated signing prompts while browsing.\n // After a WebSocket transport failure, skip it until the cooldown is\n // over. The memoized promise is dropped while the cooldown is active\n // (see below), so a later entry retries. Action-time callers are not\n // gated.\n if (Date.now() >= this.#unifiedAccountTransportRetryAt) {\n await this.#ensureUnifiedAccountEnabled({\n allowUserSigning:\n !this.#walletService.requiresSignatureConfirmation(),\n });\n }\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 try {\n await this.#ensureReadyPromise;\n } catch (error) {\n this.#ensureReadyPromise = null;\n throw error;\n }\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 } else if (\n this.#unifiedAccountSetupNeedsRetry ||\n Date.now() < this.#unifiedAccountTransportRetryAt\n ) {\n // Silent migration / lookup / keyring-locked failure left the cache\n // empty. Without resetting the memoized promise, subsequent\n // #ensureReady calls would skip retry and the user would be stuck\n // in the deprecated mode for the provider's lifetime.\n // A run skipped by the transport cooldown must not be memoized\n // either: the shared flag can read false while an action-time\n // attempt is in flight, and the setup has to run once the cooldown\n // is over.\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 shared setup that may require user signatures:\n * - DEX abstraction enablement (for HIP-3 auto-transfers)\n * - Referral code setup (attribution)\n * - Builder fee approval when the whole action carries a builder context\n *\n * These operations are DEFERRED from ensureReady() to avoid hardware wallet prompt spam\n * when users are just viewing the Perps section (critical for hardware wallets).\n *\n * General trading readiness is independent of builder approval. Native TWAP\n * and cancellations call this with `requiresBuilderFee: false`.\n */\n #tradingSetupPromise: Promise<void> | null = null;\n\n #tradingSetupComplete = false;\n\n // Set when the referral's signer could not sign it, so trading setup is not\n // marked complete and the referral is attempted again.\n #referralSetupNeedsRetry = false;\n\n // Set when the builder's referral code was not ready. It is not the user's\n // to fix, so it does not hold trading setup back: the next\n // `prepareTradingWallet` checks it again, but orders do not.\n #referralAwaitsBuilderCode = false;\n\n readonly #builderFeeSetupPromises = new Map<string, Promise<void>>();\n\n // The venue's refusal of an approval per network, account and builder,\n // when signing again cannot fix it. Kept until disconnect, so the approval\n // is not asked for again.\n readonly #builderFeeRefusals = new Map<string, string>();\n\n /**\n * Approve the standard builder fee once for the current account and network.\n * TWAP never calls this because its native action has no builder field.\n * Without an approval failure code, approval remains non-blocking and the\n * returned context describes attribution only; it does not prove approval.\n * An approval the venue refused for a reason signing again cannot fix is\n * not asked for again until disconnect; it then fails as a failed approval\n * does.\n *\n * @param approvalFailureCode - Operation-specific error to throw when\n * approval is unavailable or fails.\n * @param options - Options.\n * @param options.reportSignerFailure - Throw `KEYRING_LOCKED` when the\n * signer could not sign the approval, even without an approval failure\n * code (the approval is otherwise non-blocking).\n * @param options.reportRefusal - Throw the venue's refusal, even without an\n * approval failure code.\n * @returns The account, network, and configured builder for the action.\n */\n async #ensureBuilderFeeSetup(\n approvalFailureCode?: PerpsErrorCode,\n options: { reportSignerFailure?: boolean; reportRefusal?: boolean } = {},\n ): Promise<BuilderFeeSetupContext> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const isTestnet = this.#clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const cacheKey = this.#getCacheKey(network, userAddress);\n const builderAddress = this.#getBuilderAddress(isTestnet);\n const context: BuilderFeeSetupContext = {\n network,\n userAddress,\n builderAddress,\n };\n const setupKey = this.#getApprovedBuilderKey(\n network,\n userAddress,\n builderAddress,\n );\n if (this.#builderFeeCheckCache.has(cacheKey)) {\n return context;\n }\n\n // An approval the signer could not sign is retryable, not a failure.\n const approvalFailure = (code: PerpsErrorCode): Error =>\n new Error(\n this.#walletService.isMainAccountSignerReady()\n ? code\n : PERPS_ERROR_CODES.KEYRING_LOCKED,\n );\n\n const knownRefusal = this.#builderFeeRefusals.get(setupKey);\n if (knownRefusal) {\n if (approvalFailureCode) {\n throw approvalFailure(approvalFailureCode);\n }\n if (options.reportRefusal) {\n throw new Error(knownRefusal);\n }\n return context;\n }\n\n let pendingApproval = this.#builderFeeSetupPromises.get(setupKey);\n if (!pendingApproval) {\n pendingApproval = this.#ensureBuilderFeeApproval(context);\n this.#builderFeeSetupPromises.set(setupKey, pendingApproval);\n }\n\n try {\n await pendingApproval;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeSetup] Builder fee approval failed',\n error,\n );\n // A signer that could not sign is retryable, not an approval failure.\n if (approvalFailureCode || options.reportSignerFailure) {\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n throw signerFailure;\n }\n }\n const refusal = getBuilderFeeRefusal(error);\n // A refusal that settles after a disconnect belongs to the old session.\n if (refusal && lifecycleGeneration === this.#lifecycleGeneration) {\n this.#builderFeeRefusals.set(setupKey, refusal);\n }\n if (approvalFailureCode) {\n throw approvalFailure(approvalFailureCode);\n }\n if (refusal && options.reportRefusal) {\n throw new Error(refusal);\n }\n } finally {\n if (this.#builderFeeSetupPromises.get(setupKey) === pendingApproval) {\n this.#builderFeeSetupPromises.delete(setupKey);\n }\n }\n\n if (approvalFailureCode && !this.#builderFeeCheckCache.has(cacheKey)) {\n throw approvalFailure(approvalFailureCode);\n }\n\n return context;\n }\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: true;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext>;\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: false;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<undefined>;\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: boolean;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext | undefined>;\n\n async #ensureReadyForTrading(options: {\n requiresBuilderFee: boolean;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n // Run the shared setup again to check a builder referral code that was\n // not ready. Only preparation asks for it; orders do not.\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext | undefined> {\n // First ensure basic initialization is complete\n await this.#ensureReady();\n\n // The migration was deferred during init to avoid a signing prompt on\n // Perps section open. Drive it here, gated by its own cache so\n // already-migrated users are not re-prompted.\n await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });\n\n // Reset right before the check, with no await in between, so a failure\n // above does not leave the setup for an order to run.\n if (options.recheckPendingReferral && this.#referralAwaitsBuilderCode) {\n this.#tradingSetupComplete = false;\n }\n if (!this.#tradingSetupComplete && !this.#tradingSetupPromise) {\n const lifecycleGeneration = this.#lifecycleGeneration;\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Starting shared trading setup',\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 (e.g. USDC token index) 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 // Set up referral code independently from builder-fee applicability.\n await this.#ensureReferralSet();\n\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Trading setup completion',\n );\n\n // Only mark complete if the main-account signer is ready (signing\n // could actually happen) and the referral does not need another\n // attempt.\n if (\n this.#walletService.isMainAccountSignerReady() &&\n !this.#referralSetupNeedsRetry\n ) {\n this.#tradingSetupComplete = true;\n }\n })();\n }\n\n const pendingSetup = this.#tradingSetupPromise;\n if (pendingSetup) {\n try {\n await pendingSetup;\n } finally {\n if (this.#tradingSetupPromise === pendingSetup) {\n this.#tradingSetupPromise = null;\n }\n }\n }\n\n const builderFeeSetupContext = options.requiresBuilderFee\n ? await this.#ensureBuilderFeeSetup(options.builderFeeApprovalFailureCode)\n : undefined;\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Trading setup complete',\n );\n\n return builderFeeSetupContext;\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({ useHttp: true });\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 const lifecycleGeneration = this.#lifecycleGeneration;\n // Use unified state if available\n if (this.#dexDiscoveryCache.state) {\n const availableHip3Dexs: string[] = [];\n this.#dexDiscoveryCache.state.raw.forEach((dex) => {\n if (dex !== null) {\n availableHip3Dexs.push(dex.name);\n }\n });\n return [null, ...availableHip3Dexs];\n }\n\n // Fetch fresh from API and update unified state\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.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX discovery cache write',\n );\n const state = this.#dexDiscoveryCache.update(allDexs);\n const availableHip3Dexs: string[] = [];\n state.raw.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 // Kill switch: HIP-3 disabled, return main DEX only\n // Must check before cache — #getAllAvailableDexs() can populate\n // state.validated without the hip3Enabled gate\n if (!this.#hip3Enabled) {\n return [null];\n }\n\n // Return cached result if available\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\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 const pendingPromise = this.#fetchValidatedDexsInternal();\n this.#pendingValidatedDexsPromise = pendingPromise;\n\n try {\n const result = await pendingPromise;\n return result;\n } finally {\n // A stale request must not clear a newer lifecycle's pending request.\n if (this.#pendingValidatedDexsPromise === pendingPromise) {\n this.#pendingValidatedDexsPromise = null;\n }\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 const state = this.#dexDiscoveryCache.update([null]);\n return state.validated;\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 // Atomically update unified state (raw + validated + timestamp)\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX discovery cache write',\n );\n const state = this.#dexDiscoveryCache.update(allDexs);\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Available DEXs (market filtering applied at data layer)',\n {\n count: state.validated.filter((dex) => dex !== null).length,\n dexNames: state.validated.filter((dex) => dex !== null),\n },\n );\n\n return state.validated;\n }\n\n /**\n * Resolve the complete DEX set for a fail-closed operation.\n *\n * Unlike ordinary discovery, this uses HTTP and never degrades to main-only\n * when HIP-3 discovery fails.\n *\n * @returns The validated DEX set.\n */\n async #getValidatedDexsStrict(): Promise<(string | null)[]> {\n if (!this.#hip3Enabled) {\n return [null];\n }\n\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\n }\n\n const lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n let allDexs;\n try {\n allDexs = await infoClient.perpDexs();\n } catch {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n if (!Array.isArray(allDexs)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Strict DEX discovery cache write',\n );\n return this.#dexDiscoveryCache.update(allDexs).validated;\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 lifecycleGeneration = this.#lifecycleGeneration;\n const { dexName, skipCache } = params;\n const dexDisplayName = dexName ?? 'main';\n\n // Skip cache if requested (forces fresh fetch)\n if (!skipCache) {\n const cached = this.#cachedMetaByDex.get(dexName);\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 meta = await this.#fetchMeta(dexName);\n const cached = await this.#cacheDexMetadataFromRead({\n dex: dexName,\n meta,\n lifecycleGeneration,\n });\n if (cached) {\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\n return meta;\n }\n\n /**\n * Fetch and validate metadata without mutating provider caches.\n *\n * @param dexName - DEX name, or null for the main DEX.\n * @returns Validated metadata for the requested DEX.\n */\n async #fetchMeta(dexName: string | null): Promise<MetaResponse> {\n const dexDisplayName = dexName ?? 'main';\n\n // Bring the SDK clients up first. This is the first client touch on the\n // write path — placeOrder resolves asset info before it ensures trading\n // readiness — so without it a cold start or a post-disconnect action fails\n // with CLIENT_NOT_INITIALIZED instead of waiting for the clients it needs.\n // Idempotent, and a warm cache hit returns above without reaching here.\n await this.#ensureClientsInitialized();\n // Metadata is request/response data, so keep this path available while a\n // failed WebSocket reconnect is retrying.\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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(dexName ? { dex: dexName } : 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 return meta;\n }\n\n /**\n * Write provider metadata caches only within the lifecycle that fetched it.\n *\n * @param params - Metadata and lifecycle context.\n * @param params.dex - DEX name, or null for the main DEX.\n * @param params.meta - Validated DEX metadata.\n * @param params.assetCtxs - Asset contexts shared with subscriptions, if any.\n * @param params.lifecycleGeneration - Lifecycle that produced the metadata.\n */\n #cacheDexMetadata(params: {\n dex: string | null;\n meta: MetaResponse;\n assetCtxs?: PerpsAssetCtx[];\n lifecycleGeneration: number;\n }): void {\n const { dex, meta, assetCtxs, lifecycleGeneration } = params;\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX metadata cache write',\n );\n this.#cachedMetaByDex.set(dex, meta);\n if (assetCtxs) {\n const subscriptionDexKey = dex ?? '';\n this.#subscriptionService.setDexMetaCache(subscriptionDexKey, meta);\n this.#subscriptionService.setDexAssetCtxsCache(\n subscriptionDexKey,\n assetCtxs,\n );\n }\n }\n\n /**\n * Cache metadata fetched for a read without discarding a valid response.\n *\n * @param params - Metadata and lifecycle context.\n * @param params.dex - DEX name, or null for the main DEX.\n * @param params.meta - Validated DEX metadata.\n * @param params.assetCtxs - Asset contexts shared with subscriptions, if any.\n * @param params.lifecycleGeneration - Lifecycle that produced the metadata.\n * @returns Whether the fetched metadata was cached.\n */\n async #cacheDexMetadataFromRead(params: {\n dex: string | null;\n meta: MetaResponse;\n assetCtxs?: PerpsAssetCtx[];\n lifecycleGeneration: number;\n }): Promise<boolean> {\n const { dex, meta, assetCtxs, lifecycleGeneration } = params;\n if (\n !this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX metadata read cache write',\n )\n ) {\n return false;\n }\n\n try {\n this.#cacheDexMetadata({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\n await this.#backfillAssetMapForDex(dex, meta, lifecycleGeneration);\n return true;\n } catch (error) {\n if (\n ensureError(error, 'HyperLiquidProvider.cacheDexMetadataFromRead')\n .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE\n ) {\n return false;\n }\n throw error;\n }\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 * @param lifecycleGeneration - Lifecycle that produced the metadata.\n * @returns True if the mapping was rebuilt for the DEX.\n */\n async #backfillAssetMapForDex(\n dex: string | null,\n meta: MetaResponse,\n lifecycleGeneration: number,\n ): Promise<boolean> {\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset map backfill',\n );\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n return false;\n }\n\n if (!this.#dexDiscoveryCache.state) {\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 this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset map backfill',\n );\n\n const allPerpDexs = this.#dexDiscoveryCache.state?.raw ?? [null];\n const perpDexIndex = allPerpDexs.findIndex((entry) => {\n if (dex === null) {\n return entry === null;\n }\n return 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 lifecycleGeneration = this.#lifecycleGeneration;\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, lifecycleGeneration);\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 (e.g. USDC token index) 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 lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Spot metadata cache write',\n )\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\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 lifecycleGeneration = this.#lifecycleGeneration;\n const now = Date.now();\n\n // Return cached data if still valid (uses unified state timestamp for TTL)\n if (\n this.#dexDiscoveryCache.state &&\n now - this.#dexDiscoveryCache.state.timestamp <\n HIP3_FEE_CONFIG.PerpDexsCacheTtlMs\n ) {\n const raw = this.#dexDiscoveryCache.state.raw as ExtendedPerpDex[];\n this.#deps.debugLogger.log(\n '[getCachedPerpDexs] Using cached perpDexs data',\n {\n age: `${Math.round((now - this.#dexDiscoveryCache.state.timestamp) / 1000)}s`,\n count: raw.length,\n },\n );\n return raw;\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 if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Perp DEX cache write',\n )\n ) {\n // Atomically update unified state (raw + validated + timestamp)\n this.#dexDiscoveryCache.update(perpDexs);\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\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 #getApprovedBuilderKey(\n network: string,\n userAddress: string,\n builderAddress: string,\n ): string {\n return `${this.#getCacheKey(network, userAddress)}:${builderAddress.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 // TAT-3304: Following the USDH sunset, only USDC-collateral HIP-3 DEXs\n // are supported for trading. Gate non-USDC-collateral DEXs out of market\n // discovery entirely (regardless of skipFilters) so their markets can\n // never be surfaced to trade, even via an allowlist entry naming the DEX.\n if (dex !== null && !(await this.#isUsdcCollateralDex(dex))) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Filtering out non-USDC-collateral HIP-3 DEX from market discovery',\n { dex },\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 USDC as its collateral token\n *\n * TAT-3304: Following the USDH sunset, only USDC-collateral DEXs are\n * supported for trading. This gate filters non-USDC-collateral DEXs\n * (e.g. the now-sunset USDH) out of market discovery and blocks order\n * placement, replacing the previous USDH-specific auto-swap path.\n *\n * Fails closed: only returns true when the collateral token index\n * positively resolves to USDC against spot metadata. If the token can't\n * be resolved (e.g. missing/stale spot metadata), the DEX is treated as\n * non-USDC and gated out, since we can't otherwise verify the USDC-only\n * requirement. This only affects HIP-3 DEXs — main-DEX trading (dex ===\n * null) never calls this gate.\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 #isUsdcCollateralDex(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 isUsdc = collateralToken?.name === USDC_SYMBOL;\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Checked DEX collateral type',\n {\n dexName,\n collateralTokenIndex: meta.collateralToken,\n collateralTokenName: collateralToken?.name,\n isUsdc,\n },\n );\n\n return isUsdc;\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 update #dexDiscoveryCache here — leave state 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 #dexDiscoveryCache here.\n // That state is owned exclusively by #dexDiscoveryCache.update(); writing a\n // fallback here would prevent subsequent callers from retrying perpDexs().\n const allPerpDexs = this.#dexDiscoveryCache.state?.raw ?? [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 !this.#hip3Enabled || Boolean(this.#dexDiscoveryCache.state?.validated),\n );\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset mapping rebuild',\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 // Check if already cached (e.g., by getMarketDataWithPrices running in parallel)\n const cachedMeta = this.#cachedMetaByDex.get(dex);\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.#cacheDexMetadata({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\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 this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset mapping rebuild',\n );\n // Build mapping with DEX prefixes for HIP-3 DEXs using the utility function\n this.#symbolToAssetId.clear();\n let dexDiscoveryComplete = this.#dexDiscoveryCache.state !== 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?.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.#userFeeResolution = undefined;\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 * Set the resolved fee and its attribution source for the next operation.\n *\n * @param resolution - Unified fee resolution, or undefined to clear it.\n */\n setUserFeeResolution(resolution: PerpsFeeResolution | undefined): void {\n this.#userFeeResolution = resolution;\n this.#userFeeDiscountBips = resolution?.discountBips;\n\n this.#deps.debugLogger.log('HyperLiquid: Fee resolution context updated', {\n source: resolution?.source,\n discountBips: resolution?.discountBips,\n isActive: resolution !== 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 * @param resolvedDexs - Optional pre-resolved DEX list.\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 resolvedDexs?: (string | null)[],\n ): Promise<DexQueryResponse<TResult>> {\n const enabledDexs = resolvedDexs ?? (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 // \"User or API Wallet 0x... does not exist.\" carries the user's address, so\n // it cannot be matched by the static substring table below. It means the\n // wallet has no Hyperliquid account yet — surface an actionable code the\n // client can translate (\"fund your account\") instead of leaking the raw\n // exchange string to the UI and to failed-trade analytics.\n if (isHyperLiquidUserNotFoundError(error)) {\n return new Error(PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND);\n }\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 * Map a rejection the venue reported in a status entry rather than threw,\n * handling a rejected agent the way a thrown rejection is.\n *\n * @param message - The status entry's error.\n * @param answer - The venue answer with the entry.\n * @returns The mapped error.\n */\n async #mapStatusError(message: string, answer: unknown): Promise<Error> {\n const error = createStatusError(message, answer);\n return (await this.#classifySignerFailure(error)) ?? this.#mapError(error);\n }\n\n /**\n * The signer failure a venue reported in cancel status entries rather than\n * threw. One signature covers the whole request, so it is classified (and\n * reported to the host) once for all its entries.\n *\n * @param statuses - The status entries.\n * @param answer - The venue answer with the entries.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #classifyStatusSignerFailure(\n statuses: unknown[],\n answer: unknown,\n ): Promise<Error | undefined> {\n for (const status of statuses) {\n if (isStatusObject(status) && typeof status.error === 'string') {\n const signerFailure = await this.#classifySignerFailure(\n createStatusError(status.error, answer),\n );\n if (signerFailure) {\n return signerFailure;\n }\n }\n }\n return undefined;\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 * @param errorTags - Optional bounded tags used by error dashboards\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 errorTags?: PerpsErrorTags,\n ): PerpsLoggerOptions {\n return createPerpsErrorContext({\n contextName: 'HyperLiquidProvider',\n method,\n provider: this.protocolId,\n network: this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n errorTags,\n data: extra,\n });\n }\n\n #isMappedAccountModeExchangeError(error: Error): boolean {\n return (\n error.message === PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED ||\n error.message === PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE\n );\n }\n\n async #getTradingErrorContext(\n method: string,\n error: Error,\n extra?: Record<string, unknown>,\n errorTags?: PerpsErrorTags,\n ): Promise<{\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n }> {\n const contextExtra = { ...extra };\n if (this.#isMappedAccountModeExchangeError(error)) {\n try {\n const userAddress =\n await this.#walletService.getUserAddressWithDefault();\n const abstractionMode =\n this.#subscriptionService.getCachedAbstractionMode(userAddress);\n if (abstractionMode) {\n contextExtra[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE] = abstractionMode;\n }\n } catch {\n // Best-effort context enrichment only.\n }\n }\n return this.#getErrorContext(method, contextExtra, errorTags);\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 * @param builder - Builder address to query.\n * @param userAddress - Account whose approval should be queried.\n * @returns Current max fee rate or null if not approved\n */\n async #checkBuilderFeeApproval(\n builder: string,\n userAddress: string,\n ): Promise<number | null> {\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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 * @param params - Builder fee setup context.\n * @param params.network - HyperLiquid network for the approval.\n * @param params.userAddress - Account that owns the approval.\n * @param params.builderAddress - Builder address being approved.\n */\n async #ensureBuilderFeeApproval(\n params: BuilderFeeSetupContext,\n ): Promise<void> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const { network, userAddress, builderAddress } = params;\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\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 repeated signing prompts\n // while browsing.\n const globalCached = PerpsSigningCache.getBuilderFee(network, userAddress);\n if (globalCached?.attempted && globalCached?.success) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Using global cache (prevents hardware wallet prompt spam)',\n { network, success: globalCached.success },\n );\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\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 const completedApproval = PerpsSigningCache.getBuilderFee(\n network,\n userAddress,\n );\n if (completedApproval?.attempted && completedApproval.success) {\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\n }\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 && recheckCache?.success) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Completed by another provider',\n { network },\n );\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\n completeInFlight();\n return;\n }\n\n const { isApproved, requiredDecimal } = await this.#checkBuilderFeeStatus(\n builderAddress,\n userAddress,\n );\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\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 this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\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 builderAddress,\n userAddress,\n );\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 // The approval is already confirmed on-chain. Preserve that fact for\n // the next provider lifecycle even if this instance became stale while\n // the approval request was in flight.\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\n\n // Cache success in the current instance after the lifecycle check.\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\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 (\n ensureError(error, 'HyperLiquidProvider.ensureBuilderFeeApproval')\n .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE\n ) {\n completeInFlight();\n return;\n }\n\n // HyperLiquid wraps wallet signing failures and preserves KEYRING_LOCKED\n // in `cause`, so classify the full chain and leave retry caches empty.\n // The caller reports it as retryable.\n if (isKeyringLockedError(error)) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Keyring locked, will retry later',\n );\n completeInFlight();\n throw error;\n }\n\n // Record failure — will be retried on next trading operation\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: false,\n });\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Failed, will retry on next trading operation',\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 * Approve the dedicated subscription builder outside order submission.\n * Failure is non-blocking: order construction will use the ordinary builder\n * at the standard fee until a later approval succeeds.\n *\n * @deprecated ADR 0064 replaced the dedicated subscription builder with cloid\n * marking on the standard builder, so nothing reads this approval any more —\n * {@link #getBuilderOrderContext} never selects the subscription builder\n * address. The approval machinery is kept intact, unreachable, so the\n * previous design can be restored cheaply if cloid marking does not hold up\n * in shadow mode; remove it, the builder-address config, and\n * {@link #getSubscriptionBuilderAddress} once it does.\n * @returns Whether the builder is approved for the current account.\n */\n async approveSubscriptionBuilderFee(): Promise<boolean> {\n const approvalEpoch = this.#subscriptionBuilderApprovalEpoch;\n await this.#ensureClientsInitialized();\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return false;\n }\n const isTestnet = this.#clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const builderAddress = this.#getSubscriptionBuilderAddress(isTestnet);\n if (!builderAddress) {\n return false;\n }\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const key = this.#getApprovedBuilderKey(\n network,\n userAddress,\n builderAddress,\n );\n if (this.#approvedBuilderAddresses.has(key)) {\n return true;\n }\n\n const pending = this.#pendingBuilderFeeApprovals.get(key);\n if (pending) {\n try {\n await pending;\n return this.#approvedBuilderAddresses.has(key);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Subscription builder approval unavailable',\n error,\n );\n return false;\n }\n }\n\n const approval = (async (): Promise<void> => {\n const currentApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n if (\n currentApproval !== null &&\n currentApproval >= BUILDER_FEE_CONFIG.MaxFeeDecimal\n ) {\n this.#approvedBuilderAddresses.add(key);\n return;\n }\n\n const exchangeClient = this.#clientService.getExchangeClient();\n await exchangeClient.approveBuilderFee({\n builder: builderAddress,\n maxFeeRate: BUILDER_FEE_CONFIG.MaxFeeRate,\n });\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n const afterApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n if (\n afterApproval === null ||\n afterApproval < BUILDER_FEE_CONFIG.MaxFeeDecimal\n ) {\n throw new Error(\n '[HyperLiquidProvider] Subscription builder approval verification failed',\n );\n }\n this.#approvedBuilderAddresses.add(key);\n })();\n this.#pendingBuilderFeeApprovals.set(key, approval);\n\n try {\n await approval;\n return this.#approvedBuilderAddresses.has(key);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Subscription builder approval unavailable',\n error,\n );\n return false;\n } finally {\n if (this.#pendingBuilderFeeApprovals.get(key) === approval) {\n this.#pendingBuilderFeeApprovals.delete(key);\n }\n }\n }\n\n /**\n * Check if builder fee is approved for the current user\n *\n * @param builderAddress - Builder address to query.\n * @param userAddress - Account whose approval should be queried.\n * @returns Object with approval status and current rate\n */\n async #checkBuilderFeeStatus(\n builderAddress: string,\n userAddress: string,\n ): Promise<{\n isApproved: boolean;\n currentRate: number | null;\n requiredDecimal: number;\n }> {\n const currentApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\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.withdrawableBalance);\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.#dexDiscoveryCache.state?.validated?.filter(\n (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 // The signer could not sign the transfer: retryable, not a defect.\n if (result.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n throw new Error(PERPS_ERROR_CODES.KEYRING_LOCKED);\n }\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 // Use the same target-DEX freshness policy as position-management actions;\n // a stale aggregate can over- or under-fund the temporary HIP-3 transfer.\n const positions = await this.#getPositionsForOperation(dexName);\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 spendableBalance >= 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 * @returns Whether the balance check and any required transfer succeeded.\n * @private\n */\n async #handleHip3PostOrderRebalance(\n params: Hip3TransferContext,\n ): Promise<boolean> {\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 spendableBalance: postOrderBalance.toFixed(2),\n desiredBuffer: desiredBuffer.toFixed(2),\n excessAmount: excessAmount.toFixed(2),\n destinationDex: transferInfo.sourceDex,\n },\n );\n\n const transferResult = await this.transferBetweenDexs({\n sourceDex: dexName,\n destinationDex: transferInfo.sourceDex,\n amount: excessAmount.toFixed(USDC_DECIMALS),\n });\n if (!transferResult.success) {\n // The signer could not sign the transfer: retryable, not a defect.\n if (transferResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Auto-rebalance not signed - funds remain on HIP-3 DEX',\n { dex: dexName, excessAmount },\n );\n return false;\n }\n throw new Error(\n transferResult.error ?? PERPS_ERROR_CODES.TRANSFER_FAILED,\n );\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 return true;\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(\n 'placeOrder:autoRebalance',\n {\n dex: dexName,\n excessAmount: excessAmount.toFixed(2),\n note: 'Auto-rebalance failed - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n return false;\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 return true;\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(\n 'placeOrder:postOrderBalanceCheck',\n {\n dex: dexName,\n note: 'Failed to verify post-order balance for auto-rebalance',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n return false;\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: Hip3TransferContext): 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 if (rollbackResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n // The signer could not sign the transfer: retryable, not a defect.\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Rollback not signed - funds remain on HIP-3 DEX',\n { dex: dexName, amount: transferInfo.amount },\n );\n } else {\n this.#deps.logger.error(\n new Error(rollbackResult.error ?? 'Rollback transfer failed'),\n this.#getErrorContext(\n 'placeOrder:rollback',\n {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback failed - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\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(\n 'placeOrder:rollback:exception',\n {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback threw exception - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\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 * Validate an explicit mode before trading setup can sign or change leverage.\n * Mode belongs to the asset, so a new order cannot change an existing book.\n *\n * @param params - Requested order and collateral mode.\n * @param assetInfo - Venue capabilities for the requested market.\n */\n async #validateMarginMode(\n params: OrderParams,\n assetInfo: MetaResponse['universe'][number],\n ): Promise<void> {\n if (params.marginMode === undefined) {\n return;\n }\n if (!Number.isInteger(params.leverage) || (params.leverage ?? 0) < 1) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID);\n }\n if (\n params.marginMode === 'cross' &&\n !this.#isCrossMarginSupported(params.symbol, assetInfo)\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED);\n }\n const lock = await this.#readMarginModeLock(params.symbol);\n if (lock && lock.marginMode !== params.marginMode) {\n throw new Error(\n lock.reason === 'position'\n ? PERPS_ERROR_CODES.ORDER_MARGIN_MODE_POSITION_OPEN\n : PERPS_ERROR_CODES.ORDER_MARGIN_MODE_ORDER_OPEN,\n );\n }\n }\n\n /**\n * Read the margin mode the venue currently binds to an asset. An open\n * position fixes it first; otherwise a resting order or active TWAP fixes\n * the mode reported by the asset's leverage data.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The locked mode and its cause, or null when nothing locks it.\n * @throws When the target DEX positions cannot be read, or when the\n * selected account changes during the read.\n */\n async #readMarginModeLock(\n symbol: string,\n ): Promise<{ marginMode: MarginMode; reason: MarginModeLockReason } | null> {\n const { dex: dexName } = parseAssetName(symbol);\n // Each venue read resolves the selected account on its own. Pin one\n // account for the whole read so positions and orders from different\n // accounts can never be combined.\n const user = await this.#walletService.getUserAddressWithDefault();\n const assertSameAccount = async (): Promise<void> => {\n const current = await this.#walletService.getUserAddressWithDefault();\n if (current.toLowerCase() !== user.toLowerCase()) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n };\n const { answered, positions } = await this.#queryDexPositions(dexName);\n if (!answered) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n await assertSameAccount();\n const position = positions.find((item) => item.symbol === symbol);\n if (position) {\n return { marginMode: position.leverage.type, reason: 'position' };\n }\n const infoClient = this.#clientService.getInfoClient();\n const [orders, twapHistory] = await Promise.all([\n this.#fetchOpenOrders({ dexName }),\n infoClient.twapHistory({ user }),\n ]);\n await assertSameAccount();\n // Native TWAP schedules are absent from frontendOpenOrders before a slice\n // rests or fills. Read history directly: getTwapOrders can rebalance HIP-3\n // collateral, which must not run as part of pre-sign validation.\n const latestTwaps = new Map<\n HyperLiquidTwapHistoryEntry['twapId'],\n HyperLiquidTwapHistoryEntry\n >();\n for (const entry of twapHistory) {\n if (entry.state.coin !== symbol) {\n continue;\n }\n const previous = latestTwaps.get(entry.twapId);\n if (\n !previous ||\n normalizeTwapHistoryTimestamp(entry.time) >=\n normalizeTwapHistoryTimestamp(previous.time)\n ) {\n latestTwaps.set(entry.twapId, entry);\n }\n }\n const hasActiveTwap = [...latestTwaps.values()].some((entry) => {\n switch (entry.status.status) {\n case HyperLiquidTwapLifecycleStatus.Finished:\n case HyperLiquidTwapLifecycleStatus.Stopped:\n case HyperLiquidTwapLifecycleStatus.Terminated:\n case HyperLiquidTwapLifecycleStatus.Failed:\n return false;\n default:\n // Waiting and future venue states are not proof of termination.\n return true;\n }\n });\n if (orders.some((order) => order.coin === symbol) || hasActiveTwap) {\n const asset = await infoClient.activeAssetData({\n user,\n coin: symbol,\n });\n await assertSameAccount();\n return { marginMode: asset.leverage.type, reason: 'open_order' };\n }\n return null;\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 const marginMode =\n params.marginMode ?? (await this.#resolveDefaultMarginMode(symbol));\n\n this.#deps.debugLogger.log('Updating leverage before order:', {\n symbol,\n assetId,\n requestedLeverage: leverage,\n leverageType: marginMode,\n });\n\n const exchangeClient = this.#clientService.getExchangeClient();\n const leverageResult = await exchangeClient.updateLeverage({\n asset: assetId,\n isCross: marginMode === 'cross',\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 * Resolve the margin mode for an order that omits one. HyperLiquid refuses\n * to switch mode while a position is open, so an open position's mode wins\n * over the isolated default (e.g. flipping a Cross position).\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The open position's mode, or isolated when there is none or it\n * cannot be read.\n */\n async #resolveDefaultMarginMode(symbol: string): Promise<MarginMode> {\n const { dex: dexName } = parseAssetName(symbol);\n try {\n const positions = await this.#getPositionsForOperation(dexName ?? '');\n return (\n positions.find((position) => position.symbol === symbol)?.leverage\n .type ?? 'isolated'\n );\n } catch (error) {\n this.#deps.debugLogger.log(\n 'Open position margin mode unavailable: defaulting to isolated',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.resolveDefaultMarginMode',\n ).message,\n },\n );\n return 'isolated';\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 // TAT-3304: Only USDC-collateral HIP-3 DEXs are supported for trading.\n // Following the USDH sunset, reject orders on any non-USDC-collateral\n // DEX here instead of attempting the (now-removed) USDH auto-swap path.\n // Market discovery (#fetchMarketsForDex) already filters such DEXs out,\n // so this is a defense-in-depth check against stale caches or a\n // misconfigured allowlist entry.\n const isUsdcDex = await this.#isUsdcCollateralDex(dexName);\n if (!isUsdcDex) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Rejecting order for non-USDC-collateral DEX',\n {\n dexName,\n symbol,\n },\n );\n\n throw new Error(PERPS_ERROR_CODES.UNSUPPORTED_COLLATERAL);\n }\n\n if (this.#useUnifiedAccount) {\n this.#deps.debugLogger.log('Using Unified Account (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.#useUnifiedAccount = 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 const builder = params.chargesMetamaskBuilderFee\n ? await this.#getBuilderOrderContext(\n params.builderFeeSetupContext ??\n (await this.#ensureBuilderFeeSetup()),\n )\n : undefined;\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: this.#applySubscriptionCloid(orders),\n grouping,\n ...(builder && { builder }),\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 // The main order's `s` is the final normalized size sent to the exchange\n // (post precision rounding, USD recalculation, and $10-minimum retry —\n // the retry recurses through placeOrder so this reflects the last\n // submission). TradingService uses it to classify partial fills. The SDK\n // types `s` as `string | number`, so normalize to the string OrderResult\n // shape while preserving `undefined` when no order was built.\n submittedSize:\n orders[0]?.s === undefined ? undefined : String(orders[0].s),\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 async #handleOrderError(\n params: HandleOrderErrorParams,\n ): Promise<OrderResult> {\n const { error, symbol, orderType, isBuy, reportFailure } = params;\n const signerFailure = await this.#handleSignerFailure(error, 'placeOrder', {\n symbol,\n orderType,\n isBuy,\n });\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n const mappedError = this.#mapError(error);\n const isExpectedAccountState = isHyperLiquidUserNotFoundError(error);\n\n // A wallet with no Hyperliquid account is an expected pre-account state,\n // not an app defect — same policy already applied to every other\n // user-scoped exchange write in this provider. Keep it out of Sentry; the\n // failure is still reported to the caller (and to trade analytics) via the\n // mapped EXCHANGE_ACCOUNT_NOT_FOUND code below.\n if (isExpectedAccountState) {\n this.#deps.debugLogger.log(\n '[handleOrderError] Wallet has no Hyperliquid account, order cannot be placed',\n { symbol, orderType, isBuy },\n );\n } else if (reportFailure) {\n this.#deps.logger.error(\n mappedError,\n await this.#getTradingErrorContext(\n 'placeOrder',\n mappedError,\n {\n symbol,\n orderType,\n isBuy,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n }\n\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 input - Order parameters\n * @param retryCount - Internal retry counter to prevent infinite loops (default: 0)\n * @param reportFailure - Whether this call owns provider-level error reporting.\n * @returns A promise that resolves to the result.\n */\n async placeOrder(\n input: OrderParams,\n retryCount = 0,\n reportFailure = true,\n ): Promise<OrderResult> {\n const deferProviderErrorReport = input.deferProviderErrorReport === true;\n const params = { ...input };\n delete params.deferProviderErrorReport;\n const shouldReportFailure = reportFailure && !deferProviderErrorReport;\n if (params.expectedScaleLadder !== undefined) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE,\n };\n }\n // Hoisted so the retry path in the catch block can use the fetched price\n // even when the caller (e.g. flipPosition) omits currentPrice from params.\n let effectivePrice: number | undefined;\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 triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n tpslLinkage: params.tpslLinkage,\n grouping: params.grouping,\n timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n ...pickStrategyParams(params),\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n // Strategy placements expand into an execution schedule rather than a\n // single order, so they leave the shared path here — before the order\n // array, the HIP-3 transfer, and the atomic single-order submit, none of\n // which describe what a TWAP, a ladder, or a chase does.\n if (isStrategyOrderType(params.orderType)) {\n return await this.#placeStrategyOrder(params, params.orderType);\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 before validation so price-less\n // callers (e.g. flipPosition) can validate against the live fetched price.\n const { assetInfo, currentPrice, meta } = await this.#getAssetInfo({\n symbol: params.symbol,\n dexName,\n });\n\n // A price or partial size that rounds away at the asset precision is\n // caught here, as soon as szDecimals is known and before anything is\n // committed: the signing prompts in #ensureReadyForTrading, the leverage\n // change in #prepareAssetForTrading, and the HIP-3 margin transfer all\n // come later.\n const precision = validateOrderPrecision({\n triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n szDecimals: assetInfo.szDecimals,\n });\n if (!precision.isValid) {\n throw new Error(precision.error);\n }\n\n // Allow override with UI-provided price (optimization to avoid API call).\n 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 // Validate order at provider level (enforces USD validation rules).\n // Pass effectivePrice so price-less market orders (e.g. flipPosition)\n // validate against the live fetched price instead of failing with\n // ORDER_PRICE_REQUIRED.\n await this.#validateOrderBeforePlacement({\n ...params,\n currentPrice: effectivePrice,\n });\n\n // Ensure provider is ready for trading (includes signing operations).\n // Kept after validation so invalid orders never trigger signature prompts\n // (builder-fee approval, DEX abstraction enablement, etc.).\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const builderFeeSetupContext = await this.#ensureReadyForTrading({\n requiresBuilderFee: chargesMetamaskBuilderFee,\n });\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 // Normalize the deprecated decimal `slippage` to bps once so both the\n // price-staleness check and the limit-price calc see the same value.\n const normalizedMaxSlippageBps =\n params.maxSlippageBps ??\n (typeof params.slippage === 'number'\n ? Math.round(params.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n\n const { finalPositionSize } = calculateFinalPositionSize({\n usdAmount: params.usdAmount,\n size: params.size,\n currentPrice: effectivePrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: normalizedMaxSlippageBps,\n szDecimals: assetInfo.szDecimals,\n leverage: params.leverage,\n reduceOnly: params.reduceOnly,\n });\n\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 triggerPrice: params.triggerPrice,\n maxSlippageBps: normalizedMaxSlippageBps,\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 marginMode: params.marginMode,\n });\n\n // 6. Handle HIP-3 balance management (if applicable)\n const isHip3Order = dexName !== null;\n let transferInfo: Hip3TransferInfo | 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 timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n szDecimals: assetInfo.szDecimals,\n // The provider-agnostic linkage wins; `grouping` is the deprecated\n // HyperLiquid-shaped spelling kept for existing callers.\n grouping: params.tpslLinkage\n ? adaptTpslLinkageToGrouping(params.tpslLinkage)\n : 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 chargesMetamaskBuilderFee,\n builderFeeSetupContext,\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 // Reduce-only orders are excluded. The retry works by growing the order\n // 1.5%, which a close cannot do: a full close already submits the whole\n // position, and a partial close is capped at the size the caller asked to\n // close, so the retry would either be rejected as \"Reduce only order would\n // increase position\" or resubmit an identical order. Surfacing the\n // minimum-value error names the real problem instead.\n //\n // Strategy placements are excluded for the same reason in a different\n // shape: the minimum applies to each TWAP slice and each ladder rung, not\n // to the total, so growing the total by 1.5% does not clear it.\n if (\n isMinimumOrderError &&\n retryCount === 0 &&\n !params.reduceOnly &&\n !isStrategyOrderType(params.orderType)\n ) {\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 (effectivePrice) {\n // Size-based order: calculate USD from size and adjust.\n // Use the hoisted effectivePrice (fetched live price) so callers that\n // omit currentPrice (e.g. flipPosition) can still recover from the\n // $10-minimum edge case.\n const sizeValue = parseFloat(params.size);\n const estimatedUsd = sizeValue * effectivePrice;\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 await this.#handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n reportFailure: shouldReportFailure,\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 shouldReportFailure,\n );\n }\n\n return await this.#handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n reportFailure: shouldReportFailure,\n });\n }\n }\n\n /**\n * Dispatch a strategy placement to the handler that owns it.\n *\n * @param params - Order parameters, already validated.\n * @param orderType - The strategy type, narrowed by the caller.\n * @returns A promise that resolves to the result.\n */\n async #placeStrategyOrder(\n params: OrderParams,\n orderType: StrategyOrderType,\n ): Promise<OrderResult> {\n // Captured before the shared preamble, not after it: that preamble awaits\n // asset info, validation, trading readiness and a leverage update, and a\n // disconnect during any of them has to be seen before or after submission.\n const generation = this.#strategyGeneration;\n\n if (orderType !== 'chase') {\n const context = await this.#prepareStrategyPlacement(params);\n return await this.#submitPreparedStrategy(params, context, async () => {\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n return orderType === 'twap'\n ? await this.#placeTwapOrder(params, context, generation)\n : await this.#placeScaleOrder(params, context, generation);\n });\n }\n\n if (this.#chasePlacementBlockers > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n // The chase slot is claimed before the preamble, not after it: the preamble\n // completes the signing setup and can change the asset's leverage, and a\n // request that is going to be refused for exceeding the venue's cap must\n // not cost either. Reserved in the same synchronous step it is checked, so\n // concurrent placements cannot both see room during the round trips that\n // follow.\n const activeChases = [...this.#chaseSessions.values()].filter(\n (session) => session.active,\n ).length;\n if (\n activeChases + this.#chasePlacementsInFlight >=\n CHASE_ORDER_CONFIG.MaxActiveSessions\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_LIMIT_REACHED);\n }\n this.#chasePlacementsInFlight += 1;\n this.#pauseChaseTicksForPlacement();\n\n let settlePlacement: (() => void) | undefined;\n const placementWaiter = new Promise<void>((resolve) => {\n settlePlacement = resolve;\n });\n this.#chasePlacementWaiters.add(placementWaiter);\n\n try {\n await this.#chaseTickQueue;\n const context = await this.#prepareStrategyPlacement(params);\n return await this.#submitPreparedStrategy(\n params,\n context,\n async () => await this.#startChaseSession(params, context, generation),\n );\n } finally {\n settlePlacement?.();\n this.#chasePlacementWaiters.delete(placementWaiter);\n this.#chasePlacementsInFlight -= 1;\n if (this.#chasePlacementsInFlight === 0) {\n this.#resumeChaseTicksAfterPlacement();\n }\n }\n }\n\n /**\n * Submit a prepared strategy and settle any manual HIP-3 collateral move.\n *\n * Scale and Chase leave regular orders or fills on the venue, so the normal\n * HIP-3 post-order balance check can return any unreserved excess. Native\n * TWAP executes future slices, so its transferred collateral stays on the\n * routed DEX until cancellation confirms the schedule has stopped.\n *\n * @param params - Strategy order parameters.\n * @param context - Prepared placement and HIP-3 transfer context.\n * @param submit - Venue submission.\n * @returns The strategy placement result.\n */\n async #submitPreparedStrategy(\n params: OrderParams,\n context: StrategyPlacementContext,\n submit: () => Promise<OrderResult>,\n ): Promise<OrderResult> {\n const { dexName, network, transferInfo, userAddress } = context;\n let result: OrderResult;\n\n try {\n result = await submit();\n } catch (error) {\n if (dexName && transferInfo) {\n await this.#handleHip3OrderRollback({ dexName, transferInfo });\n }\n throw error;\n }\n\n const resultFilledSize = new BigNumber(result.filledSize ?? 0);\n const hasVenueExposure =\n result.success === true ||\n result.orderId !== undefined ||\n (result.childOrderIds?.length ?? 0) > 0 ||\n (resultFilledSize.isFinite() && resultFilledSize.gt(0));\n if (dexName && transferInfo && !hasVenueExposure) {\n await this.#handleHip3OrderRollback({ dexName, transferInfo });\n return result;\n }\n\n if (params.orderType === 'twap' && result.orderId) {\n this.#trackedTwapOrders.set(\n getTwapOrderScopeKey({\n network,\n userAddress,\n orderId: result.orderId,\n }),\n {\n symbol: params.symbol,\n ...(dexName && transferInfo\n ? { hip3Transfer: { dexName, transferInfo } }\n : {}),\n },\n );\n return result;\n }\n\n if (\n params.orderType === 'chase' &&\n result.success &&\n result.orderId &&\n dexName &&\n transferInfo\n ) {\n const session = this.#chaseSessions.get(result.orderId);\n if (session) {\n session.hip3Transfer = { dexName, transferInfo };\n return result;\n }\n }\n\n if (params.orderType === 'chase' && hasVenueExposure) {\n // A stale placement can fail after its child rests and the best-effort\n // retraction is refused. With no session left to own that child, keep\n // manual HIP-3 collateral on its DEX until the caller cancels the\n // reported exchange ID.\n return result;\n }\n\n if (dexName && transferInfo) {\n await this.#handleHip3PostOrderRebalance({ dexName, transferInfo });\n }\n\n return result;\n }\n\n /**\n * Run the shared preamble every strategy placement needs.\n *\n * Mirrors the single-order path's own preamble — validate against a live\n * price, complete the signing setup, resolve the asset ID, apply leverage —\n * so a strategy order is held to the same rules as an ordinary one.\n *\n * @param params - Order parameters.\n * @returns The asset and sizing context the strategy handlers submit with.\n */\n async #prepareStrategyPlacement(\n params: OrderParams,\n ): Promise<StrategyPlacementContext> {\n const { dex: dexName } = parseAssetName(params.symbol);\n\n const { assetInfo, currentPrice, meta } = await this.#getAssetInfo({\n symbol: params.symbol,\n dexName,\n });\n\n const effectivePrice =\n params.currentPrice && params.currentPrice > 0\n ? params.currentPrice\n : currentPrice;\n\n await this.#validateOrderBeforePlacement({\n ...params,\n currentPrice: effectivePrice,\n });\n\n const normalizedMaxSlippageBps =\n params.maxSlippageBps ??\n (typeof params.slippage === 'number'\n ? Math.round(params.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n\n const { finalPositionSize } = calculateFinalPositionSize({\n usdAmount: params.usdAmount,\n size: params.size,\n currentPrice: effectivePrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: normalizedMaxSlippageBps,\n szDecimals: assetInfo.szDecimals,\n leverage: params.leverage,\n reduceOnly: params.reduceOnly,\n });\n\n const formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals: assetInfo.szDecimals,\n });\n\n // Everything below is checked here, before anything is signed: it needs\n // `szDecimals`, which only arrives with the asset info above, and these are\n // caller mistakes that must not cost a leverage change or a signing prompt\n // first.\n const ladder =\n params.orderType === 'scale'\n ? this.#buildScaleLadder({\n params,\n szDecimals: assetInfo.szDecimals,\n finalPositionSize,\n })\n : undefined;\n\n // `validateOrder` applied the venue minimum to the notional the caller\n // asked for; this applies it to the size actually being submitted. The two\n // differ whenever sizing floors onto the grid rather than rounding up to\n // meet the requested USD — which is exactly what a reduce-only order does,\n // since the venue rejects a close larger than the position. A boundary\n // amount can therefore clear the check the caller sees and still arrive\n // under the minimum the venue charges against what it receives.\n if (params.orderType === 'twap' || params.orderType === 'chase') {\n const submittedNotional = parseFloat(formattedSize) * effectivePrice;\n const minimumNotional =\n params.orderType === 'twap'\n ? HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd\n : this.#getMinimumOrderSize();\n\n if (submittedNotional < minimumNotional) {\n throw new Error(\n params.orderType === 'twap'\n ? PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL\n : PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n );\n }\n }\n\n // Kept after validation so an invalid strategy order never triggers the\n // signature prompts in trading setup — same ordering as `placeOrder`.\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const builderFeeSetupContext = chargesMetamaskBuilderFee\n ? await this.#ensureReadyForTrading({ requiresBuilderFee: true })\n : await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName,\n meta,\n });\n\n await this.#prepareAssetForTrading({\n symbol: params.symbol,\n assetId,\n leverage: params.leverage,\n marginMode: params.marginMode,\n });\n\n const builder = builderFeeSetupContext\n ? await this.#getBuilderOrderContext(builderFeeSetupContext)\n : undefined;\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const userAddress =\n builderFeeSetupContext?.userAddress ??\n (await this.#walletService.getUserAddressWithDefault());\n\n let transferInfo: Hip3TransferInfo | null = null;\n if (dexName) {\n const orderPrice =\n ladder === undefined\n ? effectivePrice\n : Math.max(...ladder.prices.map(Number.parseFloat));\n const hip3Result = await this.#handleHip3PreOrder({\n dexName,\n symbol: params.symbol,\n orderPrice,\n positionSize: parseFloat(formattedSize),\n leverage: params.leverage ?? assetInfo.maxLeverage ?? 1,\n isBuy: params.isBuy,\n maxLeverage: assetInfo.maxLeverage,\n });\n transferInfo = hip3Result.transferInfo;\n }\n\n return {\n assetId,\n szDecimals: assetInfo.szDecimals,\n formattedSize,\n ladder,\n builder,\n dexName,\n network,\n transferInfo,\n userAddress,\n };\n }\n\n /**\n * The venue's minimum value for a single order, in USD.\n *\n * @returns The minimum for the network this provider is pointed at.\n */\n #getMinimumOrderSize(): number {\n return this.#clientService.isTestnetMode()\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n }\n\n /**\n * Build a scale placement's rungs and check them as the venue will see them.\n *\n * Three things can only be decided once the asset's precision is known, and\n * all of them are decided here rather than after the order is on its way:\n *\n * - **Prices collapse.** Two distinct rung prices can round onto the same\n * venue-formatted price, which would submit several orders at one price\n * instead of a ladder spanning the requested range.\n * - **Slices are not the average.** `splitScaleSizes` floors onto the size\n * grid, and a `scaleSkew` weights the rungs along the ladder on top of that,\n * so no rung carries the average slice the pre-network check in\n * `validateOrder` approximates with.\n * - **The cheapest rung decides.** Each rung is an independent order, so the\n * venue applies its per-order minimum to the smallest slice at the lowest\n * price, not to the ladder's total.\n *\n * @param options - Ladder inputs.\n * @param options.params - Order parameters.\n * @param options.szDecimals - The asset's size and price precision.\n * @param options.finalPositionSize - Total size to spread across the rungs.\n * @returns The rungs, exactly as they will be submitted.\n */\n #buildScaleLadder(options: {\n params: OrderParams;\n szDecimals: number;\n finalPositionSize: number;\n }): ScaleLadder {\n const { params, szDecimals, finalPositionSize } = options;\n const { scaleMinPrice, scaleMaxPrice, scaleNumOrders } = params;\n if (scaleMinPrice === undefined || scaleMaxPrice === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);\n }\n if (scaleNumOrders === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);\n }\n\n const prices = normalizeHyperLiquidScalePriceLadder({\n minPrice: parseFloat(scaleMinPrice),\n maxPrice: parseFloat(scaleMaxPrice),\n count: scaleNumOrders,\n szDecimals,\n });\n\n // Throws ORDER_SCALE_SIZE_TOO_SMALL when a rung would round to nothing,\n // which a skew weighted far enough from even can do on its own.\n const sizes = splitScaleSizes({\n totalSize: finalPositionSize,\n count: scaleNumOrders,\n szDecimals,\n skew: params.scaleSkew,\n });\n\n const minimumOrderSize = this.#getMinimumOrderSize();\n const cheapestRungNotional = Math.min(\n ...sizes.map(\n (size, index) => parseFloat(size) * parseFloat(prices[index]),\n ),\n );\n if (cheapestRungNotional < minimumOrderSize) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL);\n }\n\n return { prices, sizes };\n }\n\n /**\n * Submit a TWAP through HyperLiquid's dedicated TWAP action.\n *\n * A TWAP is not an order on the book, so it does not go through the `order`\n * action, carries no builder fee, and comes back identified by a `twapId`\n * rather than an `oid`. That ID is the handle `cancelOrder` needs.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before preparation.\n * @returns A promise that resolves to the result.\n */\n async #placeTwapOrder(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, formattedSize } = context;\n const durationMinutes = params.twapDuration;\n if (durationMinutes === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED);\n }\n if (\n !Number.isSafeInteger(durationMinutes) ||\n durationMinutes < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||\n durationMinutes > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID);\n }\n const exchangeClient = this.#clientService.getExchangeClient();\n\n this.#deps.debugLogger.log('Submitting TWAP order', {\n symbol: params.symbol,\n assetId,\n size: formattedSize,\n durationMinutes,\n randomize: params.twapRandomize ?? false,\n });\n\n const result = await exchangeClient.twapOrder({\n twap: {\n a: assetId,\n b: params.isBuy,\n s: formattedSize,\n r: params.reduceOnly ?? false,\n m: durationMinutes,\n t: params.twapRandomize ?? false,\n },\n });\n\n if (result.status !== 'ok') {\n throw new Error(`TWAP order failed: ${JSON.stringify(result)}`);\n }\n\n const status: unknown = result.response?.data?.status;\n if (!isStatusObject(status)) {\n throw new Error('TWAP order rejected');\n }\n\n const rawError =\n typeof status.error === 'string' ? status.error : 'TWAP order rejected';\n const { running } = status;\n if (\n !isStatusObject(running) ||\n typeof running.twapId !== 'number' ||\n !Number.isSafeInteger(running.twapId) ||\n running.twapId < 0\n ) {\n throw new Error(rawError);\n }\n\n const orderId = running.twapId.toString();\n if (generation !== this.#strategyGeneration) {\n let remainsLive = true;\n try {\n const cancelResult = await exchangeClient.twapCancel({\n a: assetId,\n t: running.twapId,\n });\n const cancelStatus: unknown = cancelResult.response?.data?.status;\n // A rejected agent is dropped and reported; the TWAP stays live.\n if (\n isStatusObject(cancelStatus) &&\n typeof cancelStatus.error === 'string'\n ) {\n await this.#evictRejectedAgent(\n createStatusError(cancelStatus.error, cancelResult),\n );\n }\n remainsLive =\n classifyCancelStatus(cancelStatus) === CancelChildOutcome.Refused;\n } catch (error) {\n // A rejected agent is dropped and reported; the TWAP stays live.\n await this.#evictRejectedAgent(error);\n this.#deps.debugLogger.log(\n 'Stale TWAP placement could not be retracted',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.placeTwapOrder.retract',\n ).message,\n orderId,\n },\n );\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE),\n {\n success: false,\n submittedSize: formattedSize,\n ...(remainsLive && { orderId }),\n },\n );\n }\n\n return {\n success: true,\n orderId,\n submittedSize: formattedSize,\n };\n }\n\n /**\n * Fan a scale placement out into one batch of resting limit orders.\n *\n * The whole ladder goes in a single `order` action, which is one round trip\n * and one signature rather than one per rung. It is **not** atomic: an `na`\n * grouping evaluates each entry independently. Accepted rungs remain live and\n * are returned to the caller when another rung is rejected.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before preparation.\n * @returns A promise that resolves to the result.\n */\n async #placeScaleOrder(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, formattedSize, ladder, builder } = context;\n // Built and validated in `#prepareStrategyPlacement`, before anything was\n // signed, so what is submitted here is exactly what the minimums were\n // applied to.\n if (!ladder) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);\n }\n const { prices, sizes } = ladder;\n const count = prices.length;\n const { clientOrderIds: ladderClientOrderIds } =\n createScaleOrderIdentity(count);\n\n // Marked here rather than at submission so the ids recorded for\n // cancel-by-cloid are exactly the ids the venue received. Marking keeps the\n // Scale group marker and the rung index, so the group stays recoverable.\n const orders: SDKOrderParams[] = this.#applySubscriptionCloid(\n prices.map((price, index) => ({\n a: assetId,\n b: params.isBuy,\n p: price,\n s: sizes[index],\n r: params.reduceOnly ?? false,\n t: { limit: { tif: 'Gtc' as const } },\n c: ladderClientOrderIds[index],\n })),\n // These ids were generated a few lines above, so they are ours to stamp.\n new Set(ladderClientOrderIds),\n );\n const clientOrderIds: Hex[] = orders.map((order, index) =>\n order.c === undefined ? ladderClientOrderIds[index] : (order.c as Hex),\n );\n // Derived from the submitted ids, not from the pre-marking identity: the\n // group is recovered from open orders by reading their cloids, so tracking\n // it under any other key would register the same ladder twice.\n const groupId =\n readScaleGroupId(clientOrderIds[0]) ??\n `scale:${clientOrderIds[0].slice(2, -2)}`;\n\n this.#deps.debugLogger.log('Submitting scale ladder', {\n symbol: params.symbol,\n assetId,\n count,\n prices: orders.map((order) => order.p),\n sizes,\n });\n\n const exchangeClient = this.#clientService.getExchangeClient();\n let result: ScaleBulkOrderResponse;\n let thrownBulkOrderError: HyperliquidError | undefined;\n try {\n result = await exchangeClient.order({\n orders,\n grouping: 'na',\n ...(builder && { builder }),\n });\n } catch (error) {\n const bulkResponse = getScaleBulkOrderResponseFromError(error, count);\n if (!bulkResponse) {\n throw error;\n }\n result = bulkResponse;\n thrownBulkOrderError = error as HyperliquidError;\n }\n\n const rawStatuses = result.response?.data?.statuses;\n const statuses = Array.isArray(rawStatuses) ? rawStatuses : [];\n const outcomes = Array.from({ length: count }, (_unused, index) =>\n parseScaleBulkOrderStatus(statuses[index]),\n );\n const acceptedCount = outcomes.filter(\n (outcome) => outcome?.kind === 'accepted',\n ).length;\n const everyStatusClassified = outcomes.every(\n (outcome) => outcome !== undefined,\n );\n const rejectedCount = outcomes.filter(\n (outcome) => outcome?.kind === 'error',\n ).length;\n const acceptedRungs = outcomes.flatMap((outcome, index) =>\n outcome?.kind === 'accepted'\n ? [\n {\n outcome,\n price: prices[index],\n size: sizes[index],\n },\n ]\n : [],\n );\n const restingChildOrderIds = acceptedRungs.flatMap((rung) =>\n rung.outcome.state === 'resting' ? [rung.outcome.orderId] : [],\n );\n // Waiting rungs have no exchange order ID and cannot be recovered after\n // the in-memory Scale group registry is cleared on disconnect.\n const hasWaitingRungs = acceptedRungs.some(\n (rung) =>\n rung.outcome.state === 'waitingForFill' ||\n rung.outcome.state === 'waitingForTrigger',\n );\n const cleanupClientOrderIds = outcomes.flatMap((outcome, index) =>\n outcome?.kind === 'error' || outcome?.state === 'resting'\n ? []\n : [clientOrderIds[index]],\n );\n const acceptedChildren: ScaleOrderChild[] = acceptedRungs.map(\n ({ outcome }) =>\n outcome.state === 'resting' || outcome.state === 'filled'\n ? { orderId: outcome.orderId, state: outcome.state }\n : { state: outcome.state },\n );\n const acceptedSize = acceptedRungs.reduce(\n (total, rung) => total.plus(rung.size),\n new BigNumber(0),\n );\n const acceptedNotional = acceptedRungs.reduce(\n (total, rung) => total.plus(new BigNumber(rung.size).times(rung.price)),\n new BigNumber(0),\n );\n const filledRungs = acceptedRungs.flatMap((rung) =>\n rung.outcome.state === 'filled'\n ? [{ ...rung, outcome: rung.outcome }]\n : [],\n );\n const filledSize = filledRungs.reduce(\n (total, rung) => total.plus(rung.outcome.filledSize),\n new BigNumber(0),\n );\n const executedNotional = filledRungs.reduce(\n (total, rung) =>\n total.plus(\n new BigNumber(rung.outcome.filledSize).times(\n rung.outcome.averagePrice,\n ),\n ),\n new BigNumber(0),\n );\n const acceptedResult = {\n childOrderIds: restingChildOrderIds,\n submittedSize: formattedSize,\n acceptedSize: acceptedSize.toFixed(),\n ...(acceptedSize.gt(0) && {\n weightedAverageLimitPrice: acceptedNotional\n .dividedBy(acceptedSize)\n .toFixed(),\n }),\n acceptedChildren,\n ...(filledSize.gt(0) && {\n filledSize: filledSize.toFixed(),\n averagePrice: executedNotional.dividedBy(filledSize).toFixed(),\n }),\n } satisfies Partial<OrderResult>;\n const buildAcceptedResult = (): OrderResult => ({\n success: true,\n orderId: groupId,\n ...acceptedResult,\n });\n const cancelNonRejectedOrders = async (): Promise<{\n orderIds: string[];\n clientOrderIds: Hex[];\n }> => {\n const [orderIds, pendingClientOrderIds] = await Promise.all([\n this.#cancelOrderRequests(\n exchangeClient,\n restingChildOrderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n })),\n ),\n this.#cancelOrderCloidRequests(\n exchangeClient,\n cleanupClientOrderIds.map((clientOrderId) => ({\n asset: assetId,\n cloid: clientOrderId,\n })),\n ),\n ]);\n return {\n orderIds: orderIds.map(String),\n clientOrderIds: pendingClientOrderIds,\n };\n };\n\n if (thrownBulkOrderError !== undefined) {\n const isRecoverablePartial =\n everyStatusClassified && acceptedCount > 0 && rejectedCount > 0;\n if (!isRecoverablePartial) {\n if (!everyStatusClassified) {\n await cancelNonRejectedOrders();\n }\n throw thrownBulkOrderError;\n }\n }\n\n if (generation !== this.#strategyGeneration) {\n const remaining = await cancelNonRejectedOrders();\n if (\n remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n ...remaining,\n });\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE),\n {\n success: false,\n ...acceptedResult,\n ...(remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ? { orderId: groupId }\n : {}),\n childOrderIds: remaining.orderIds,\n },\n );\n }\n\n if (\n result.status !== 'ok' ||\n statuses.length !== count ||\n acceptedCount !== count ||\n hasWaitingRungs\n ) {\n this.#deps.debugLogger.log('Scale ladder was not fully accepted', {\n accepted: acceptedCount,\n filled: filledRungs.length,\n resting: restingChildOrderIds.length,\n requested: count,\n statuses,\n });\n const isValidPartial =\n result.status === 'ok' &&\n statuses.length === count &&\n everyStatusClassified &&\n !hasWaitingRungs &&\n acceptedCount > 0 &&\n rejectedCount > 0;\n if (isValidPartial) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n orderIds: restingChildOrderIds,\n clientOrderIds: [],\n });\n return buildAcceptedResult();\n }\n const remaining = await cancelNonRejectedOrders();\n if (\n remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n ...remaining,\n });\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n {\n success: false,\n orderId: groupId,\n ...acceptedResult,\n childOrderIds: remaining.orderIds,\n },\n );\n }\n\n if (acceptedCount > 0) {\n return createErrorResult(new Error(PERPS_ERROR_CODES.ORDER_REJECTED), {\n success: false,\n ...acceptedResult,\n childOrderIds: [],\n });\n }\n\n throw new Error(PERPS_ERROR_CODES.ORDER_REJECTED);\n }\n\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n orderIds: restingChildOrderIds,\n clientOrderIds: [],\n });\n return buildAcceptedResult();\n }\n\n /**\n * Place a chase's first order and register the session that follows it.\n *\n * Split from the routing above so the concurrency reservation there wraps\n * every await in one `try`/`finally`.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before any await.\n * @returns A promise that resolves to the result.\n */\n async #startChaseSession(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, szDecimals, formattedSize, builder } = context;\n // Captured now, alongside the builder fee and for the same reason: the fee\n // resolution behind it is cleared when the caller's `placeOrder` returns,\n // which for a chase is before any replacement runs.\n const marksSubscriptionCloid = this.#isSubscriptionFeeSource();\n\n // The preamble is several round trips long. A disconnect during it has\n // already torn down everything this session would run on, so the chase\n // stops here rather than reading the book and putting a fresh order on it\n // for a provider that no longer exists.\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n\n let quotePrice = await this.#getChaseQuotePrice({\n symbol: params.symbol,\n isBuy: params.isBuy,\n szDecimals,\n });\n if (\n quotePrice === CHASE_ORDER_STATUS_UNAVAILABLE ||\n typeof quotePrice !== 'string'\n ) {\n // A first placement has no child whose terminal state could be read.\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n // The book read is a round trip of its own, so the check above does not\n // cover it. Re-checked here, immediately before the only statement that\n // signs anything: every await on this path is now followed by a refusal\n // before the next one, leaving one window that cannot be closed from here\n // — a disconnect arriving while the submission itself is in flight, which\n // the check after it handles.\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n\n // Held onto rather than looked up again after the submission returns.\n // `disconnect` drops the service's client reference synchronously, so a\n // retraction that asked for a client after the fact would be refused one\n // and leave the order resting under the account that placed it. This\n // instance signed the order and can still cancel it as that account.\n const placingClient = this.#clientService.getExchangeClient();\n\n let orderId: string | undefined;\n for (\n let attempt = 1;\n attempt <= CHASE_ORDER_CONFIG.InitialPlacementAttempts;\n attempt += 1\n ) {\n try {\n orderId = await this.#restChaseOrder({\n assetId,\n isBuy: params.isBuy,\n price: quotePrice,\n size: formattedSize,\n reduceOnly: params.reduceOnly ?? false,\n builder,\n marksSubscriptionCloid,\n exchangeClient: placingClient,\n });\n break;\n } catch (error) {\n if (\n attempt === CHASE_ORDER_CONFIG.InitialPlacementAttempts ||\n !isRetryableChasePlacementError(error)\n ) {\n throw error;\n }\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n const refreshedQuote = await this.#getChaseQuotePrice({\n symbol: params.symbol,\n isBuy: params.isBuy,\n szDecimals,\n });\n if (\n refreshedQuote === CHASE_ORDER_STATUS_UNAVAILABLE ||\n typeof refreshedQuote !== 'string'\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n quotePrice = refreshedQuote;\n }\n }\n if (!orderId) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n const intervalMs =\n params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;\n const sessionId = generatePerpsId('chase');\n const session: ChaseSession = {\n symbol: params.symbol,\n assetId,\n isBuy: params.isBuy,\n size: formattedSize,\n originalSize: formattedSize,\n szDecimals,\n reduceOnly: params.reduceOnly ?? false,\n orderId,\n replacingOrderId: null,\n pendingReplacement: null,\n restingPrice: quotePrice,\n arrivalPrice: quotePrice,\n startedAt: Date.now(),\n maxDistanceBps: params.chaseMaxDistanceBps,\n intervalMs,\n lastSnapshotSizeRefreshAt: 0,\n builder,\n marksSubscriptionCloid,\n deadline:\n params.chaseMaxDurationMs === undefined\n ? Number.POSITIVE_INFINITY\n : Date.now() + params.chaseMaxDurationMs,\n maxRepricings: params.chaseMaxRepricings ?? Number.POSITIVE_INFINITY,\n repricings: 0,\n timer: null,\n active: true,\n status: CHASE_ORDER_STATUS.Active,\n };\n // A disconnect landed while the submission was in flight — the one window\n // the checks above cannot close. The order rested, but no strategy is\n // running behind it and no handle names it, so this placement is reported\n // as a failure. That makes the resting order an orphan: the caller is told\n // the chase failed, nothing refreshes the caches a successful placement\n // would have invalidated, and the exchange id is only usable for as long as\n // the provider stays pointed at the account that placed it — a disconnect\n // is usually followed by an account or network switch, after which handing\n // the id back is no remedy at all. So it is cancelled here, through the\n // client that signed it — the account switch cannot reach that instance —\n // and the failure is then true of the venue as well as of this provider.\n // Best-effort still: the transport underneath that client may already be\n // closing, so a cancel that does not land falls back to reporting the id.\n if (generation !== this.#strategyGeneration) {\n this.#deps.debugLogger.log('Chase placement outlived its provider', {\n orderId,\n restingPrice: quotePrice,\n });\n\n const outcome = await this.#retractOrphanedChaseOrder(\n session,\n placingClient,\n );\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED),\n {\n success: false,\n // Reported only when the retraction did not take. Naming an order\n // that is no longer on the book would send the caller to cancel\n // something already gone; naming one that still rests is the only\n // route left to it.\n ...(outcome === CancelChildOutcome.Refused\n ? { childOrderIds: [orderId] }\n : {}),\n submittedSize: formattedSize,\n },\n );\n }\n\n this.#chaseSessions.set(sessionId, session);\n this.#scheduleChaseTick(sessionId);\n\n this.#deps.debugLogger.log('Chase session started', {\n sessionId,\n symbol: params.symbol,\n orderId,\n restingPrice: quotePrice,\n intervalMs,\n });\n\n return {\n success: true,\n orderId: sessionId,\n childOrderIds: [orderId],\n submittedSize: formattedSize,\n };\n }\n\n /**\n * Read the price a chase must rest at: the best bid for a buy, the best ask\n * for a sell.\n *\n * The touch, not the mid: a post-only order priced at the mid would either\n * cross or be rejected, and a chase that never rests at the front of the\n * queue is not chasing anything.\n *\n * @param params - The lookup parameters.\n * @param params.symbol - Market to read.\n * @param params.isBuy - Which side the chase rests on.\n * @param params.szDecimals - Asset size precision, for price formatting.\n * @param params.own - The chase's own resting order, excluded from the book.\n * @param params.own.orderId - Exchange ID of that order.\n * @param params.own.price - Price that order rests at.\n * @param params.own.size - Size it was last placed for.\n * @returns The formatted price, a terminal child result, or the status\n * unavailable sentinel when the child may still be live.\n */\n async #getChaseQuotePrice(params: {\n symbol: string;\n isBuy: boolean;\n szDecimals: number;\n /** The chase's own resting order, excluded from the book it reads. */\n own?: { orderId: string; price: string; size: string };\n }): Promise<\n string | ChaseTerminalResolution | typeof CHASE_ORDER_STATUS_UNAVAILABLE\n > {\n const { symbol, isBuy, szDecimals, own } = params;\n\n const book = await this.#clientService.getInfoClient().l2Book({\n coin: symbol,\n });\n\n // `levels` is [bids, asks], each best-first.\n const ownSide = book?.levels?.[isBuy ? 0 : 1];\n const netting = await this.#resolveOwnRestingSizes({\n symbol,\n isBuy,\n callerOrderId: own?.orderId,\n ownSide,\n });\n if (\n netting === CHASE_ORDER_STATUS_UNAVAILABLE ||\n !(netting instanceof Map)\n ) {\n return netting;\n }\n\n const bestBid = readBestExternalPrice(book?.levels?.[0], netting);\n const bestAsk = readBestExternalPrice(book?.levels?.[1], netting);\n\n if (bestBid === null || bestAsk === null) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n return computeChaseQuotePrice({ bestBid, bestAsk, isBuy, szDecimals });\n }\n\n /**\n * Rest one post-only order for a chase and return its exchange ID.\n *\n * @param params - The placement parameters.\n * @param params.assetId - Resolved asset ID.\n * @param params.isBuy - Order side.\n * @param params.price - Formatted limit price.\n * @param params.size - Formatted size.\n * @param params.reduceOnly - Whether the order may only reduce a position.\n * @param params.builder - Builder context captured when the session started.\n * @param params.marksSubscriptionCloid - Whether to mark the cloid, captured\n * when the session started. Passed explicitly rather than read live: a\n * replacement runs long after the fee resolution behind it was cleared.\n * @param params.exchangeClient - Client to submit through. Passed in rather\n * than looked up here so a first placement can keep the instance it signed\n * with, which is the only one that can take the order back once `disconnect`\n * has dropped the service's reference.\n * @returns The resting order's exchange ID.\n */\n async #restChaseOrder(params: {\n assetId: number;\n isBuy: boolean;\n price: string;\n size: string;\n reduceOnly: boolean;\n builder?: BuilderOrderContext;\n marksSubscriptionCloid?: boolean;\n exchangeClient: ExchangeClient;\n }): Promise<string> {\n const result = await params.exchangeClient.order({\n orders: this.#applySubscriptionCloid(\n [\n {\n a: params.assetId,\n b: params.isBuy,\n p: params.price,\n s: params.size,\n r: params.reduceOnly,\n // Post-only: a chase adds liquidity at the touch. Crossing would\n // end the chase on its first tick at a worse price than resting.\n t: { limit: { tif: 'Alo' as const } },\n },\n ],\n undefined,\n params.marksSubscriptionCloid,\n ),\n grouping: 'na',\n ...(params.builder && { builder: params.builder }),\n });\n\n if (result.status !== 'ok') {\n throw new Error(`Chase order failed: ${JSON.stringify(result)}`);\n }\n\n const orderId = this.#readOrderIdFromStatus(\n result.response?.data?.statuses?.[0],\n );\n if (!orderId) {\n throw new Error(\n `Chase order rejected: ${JSON.stringify(result.response?.data)}`,\n );\n }\n\n return orderId;\n }\n\n /**\n * Schedule the next tick of a chase session.\n *\n * @param sessionId - Session to advance.\n */\n #scheduleChaseTick(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active || session.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n session.timer = null;\n this.#chaseTickQueue = this.#chaseTickQueue\n .then(() => this.#runChaseTick(sessionId))\n .catch(async (error: unknown) => {\n // A rejected agent is dropped so the next tick asks for another.\n await this.#evictRejectedAgent(error);\n // Resolve the shared queue after every failure. Otherwise one\n // rejected tick prevents all later ticks and teardown from running.\n this.#deps.debugLogger.log('Chase tick failed', {\n sessionId,\n error: ensureError(error, 'HyperLiquidProvider.chaseTick').message,\n });\n this.#recoverFailedChaseTick(sessionId);\n });\n }, session.intervalMs);\n\n // Node keeps the process alive for a pending timer; a background chase is\n // not a reason to hold an exiting process open. React Native's timers have\n // no `unref`, hence the guard.\n timer.unref?.();\n session.timer = timer;\n }\n\n /** Pause scheduled background work while a foreground Chase is submitted. */\n #pauseChaseTicksForPlacement(): void {\n for (const session of this.#chaseSessions.values()) {\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n }\n }\n\n /** Restart the polling cadence after all foreground placements settle. */\n #resumeChaseTicksAfterPlacement(): void {\n for (const [sessionId, session] of this.#chaseSessions) {\n if (session.active && !session.timer) {\n this.#scheduleChaseTick(sessionId);\n }\n }\n }\n\n /**\n * Decide what a session does after one of its ticks threw.\n *\n * Two outcomes, told apart by whether the session still owns a resting order:\n *\n * - It does — the failure was a book read or a refused cancel, and the order\n * is untouched. The chase keeps going; the deadline check at the top of the\n * next tick ends it if the window has since closed. Letting a transient\n * error end the chase would strand a live order under a session that still\n * claimed to be re-pricing it.\n * - It does not — the tick cancelled the order and then failed to rest its\n * replacement, so nothing is on the book. There is nothing left to chase and\n * nothing left to cancel, so the session ends here. Leaving it `active` would\n * report a live chase with no timer, and every later cancel would try to\n * cancel the dead order and keep the handle forever.\n *\n * @param sessionId - Session whose tick failed.\n */\n #recoverFailedChaseTick(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active) {\n return;\n }\n\n if (session.orderId === null) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase ended with nothing resting', {\n sessionId,\n });\n this.#rebalanceChaseSession(session).catch((error: unknown) => {\n this.#deps.debugLogger.log('Chase collateral cleanup failed', {\n sessionId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.recoverFailedChaseTick',\n ).message,\n });\n });\n return;\n }\n\n this.#scheduleChaseTick(sessionId);\n }\n\n /**\n * Advance one chase session: re-price if the touch has moved, stop if the\n * window has closed.\n *\n * @param sessionId - Session to advance.\n */\n async #runChaseTick(sessionId: string): Promise<void> {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active) {\n return;\n }\n\n // Give a new Chase placement priority over background cancel/replace\n // traffic. With several active sessions, their signed mutations can\n // otherwise overlap the placement preamble and trip the SDK transport's\n // circuit breaker before the new order reaches the venue. Deferring one\n // polling interval leaves every existing child resting as a valid ALO and\n // preserves the venue's five-session limit without increasing request\n // churn.\n if (this.#chasePlacementsInFlight > 0) {\n this.#scheduleChaseTick(sessionId);\n return;\n }\n\n if (Date.now() >= session.deadline) {\n // The window closed. The last order stays resting as an ordinary limit\n // order and the session stays registered, so cancelling by its handle\n // still reaches that order.\n session.active = false;\n session.status = CHASE_ORDER_STATUS.DurationReached;\n this.#deps.debugLogger.log('Chase session window closed', { sessionId });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n const rawQuotePrice = await this.#getChaseQuotePrice({\n symbol: session.symbol,\n isBuy: session.isBuy,\n szDecimals: session.szDecimals,\n own: session.orderId\n ? {\n orderId: session.orderId,\n price: session.restingPrice,\n size: session.size,\n }\n : undefined,\n });\n\n if (typeof rawQuotePrice !== 'string') {\n // The order left the book without the loop seeing it. Preserve the venue\n // status so an external cancellation is not reported as a fill.\n session.orderId = null;\n session.active = false;\n session.status = rawQuotePrice.status;\n session.size = rawQuotePrice.remainingSize ?? '0';\n this.#deps.debugLogger.log('Chase order ended between ticks', {\n sessionId,\n status: session.status,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n if (rawQuotePrice === CHASE_ORDER_STATUS_UNAVAILABLE) {\n // The child may still be live. Leave it untouched and retry on the next\n // normal interval instead of permanently stranding the Chase after one\n // short status outage.\n this.#deps.debugLogger.log('Chase order status unavailable', {\n sessionId,\n orderId: session.orderId,\n });\n this.#scheduleChaseTick(sessionId);\n return;\n }\n\n const arrivalPrice = Number.parseFloat(session.arrivalPrice);\n const rawQuote = Number.parseFloat(rawQuotePrice);\n const adverseDistanceFromArrival = session.isBuy\n ? (rawQuote - arrivalPrice) / arrivalPrice\n : (arrivalPrice - rawQuote) / arrivalPrice;\n const boundaryDirection = session.isBuy ? 1 : -1;\n const maxDistanceRatio =\n session.maxDistanceBps === undefined\n ? undefined\n : session.maxDistanceBps / BASIS_POINTS_DIVISOR;\n const boundaryPrice =\n maxDistanceRatio === undefined\n ? undefined\n : arrivalPrice * (1 + boundaryDirection * maxDistanceRatio);\n let reachedMaxDistance =\n boundaryPrice !== undefined &&\n maxDistanceRatio !== undefined &&\n adverseDistanceFromArrival >= maxDistanceRatio;\n let quotePrice = rawQuotePrice;\n if (reachedMaxDistance && boundaryPrice !== undefined) {\n quotePrice = formatHyperLiquidPrice({\n price: boundaryPrice,\n szDecimals: session.szDecimals,\n });\n const formattedBoundary = Number.parseFloat(quotePrice);\n const overshootsBoundary = session.isBuy\n ? formattedBoundary > boundaryPrice\n : formattedBoundary < boundaryPrice;\n if (overshootsBoundary) {\n const tick = getPriceTick({\n price: boundaryPrice,\n szDecimals: session.szDecimals,\n });\n quotePrice = formatHyperLiquidPrice({\n price: session.isBuy\n ? formattedBoundary - tick\n : formattedBoundary + tick,\n szDecimals: session.szDecimals,\n });\n }\n }\n\n // The book read is a round trip, and a cancel arriving during it stops the\n // session. Without this re-check the tick would cancel and re-place the very\n // order the caller just asked to be rid of.\n if (!session.active) {\n return;\n }\n\n if (quotePrice !== session.restingPrice && session.orderId) {\n const outcome = await this.#cancelChaseChild(session);\n\n // The cancel is a second round trip, and this is the window where a\n // caller's `cancelOrder` does the most damage: it would cancel the order\n // this tick has already cancelled, report the cancel incomplete, and then\n // this tick would rest a replacement the caller has no idea exists.\n // Stopping here leaves nothing on the book.\n if (!session.active) {\n // A refused cancel leaves the child resting. Preserve its ID so the\n // caller that stopped this session can report an incomplete cancel and\n // retry it instead of orphaning the order.\n if (outcome !== CancelChildOutcome.Refused) {\n session.orderId = null;\n }\n return;\n }\n\n if (outcome === CancelChildOutcome.Refused) {\n // The exchange kept the order, so it is still resting at the old price.\n // Placing the replacement anyway would double the position. Leave it\n // alone and try again on the next tick, which is why this falls through\n // to the reschedule below rather than ending the session.\n this.#deps.debugLogger.log('Chase reprice cancel refused', {\n sessionId,\n orderId: session.orderId,\n });\n reachedMaxDistance = false;\n } else if (outcome === CancelChildOutcome.Gone) {\n // The order left the book between ticks: it filled, or something else\n // cancelled it. There is nothing left to chase.\n const goneOrderId = session.orderId;\n session.orderId = null;\n session.active = false;\n let remainder: ChaseOrderRemainder;\n try {\n remainder = await this.#readOrderRemainder(\n goneOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n } catch (error) {\n session.status = CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase order status unavailable', {\n sessionId,\n orderId: goneOrderId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.chaseGoneOrderStatus',\n ).message,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n session.status = remainder.terminalStatus ?? CHASE_ORDER_STATUS.Failed;\n if (remainder.remainingSize !== null) {\n session.size = remainder.remainingSize;\n }\n this.#deps.debugLogger.log('Chase order no longer resting', {\n sessionId,\n status: session.status,\n remainingSize: session.size,\n });\n await this.#rebalanceChaseSession(session);\n return;\n } else {\n // The cancel is confirmed, so the session owns nothing from here on.\n // Recorded before the read rather than after it: a read that rejects\n // would otherwise leave the session naming an order that is already off\n // the book, and recovery would reschedule a chase with nothing resting.\n const cancelledOrderId = session.orderId;\n session.replacingOrderId = cancelledOrderId;\n session.orderId = null;\n\n // No further fills can reach a cancelled order, so what it did not fill\n // is now fixed. Sampling before the cancel would have left a window in\n // which a fill lands and is then re-placed.\n let remainder: ChaseOrderRemainder;\n try {\n remainder = await this.#readOrderRemainder(\n cancelledOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n } catch (error) {\n session.replacingOrderId = null;\n throw error;\n }\n\n // Another round trip, another window for a cancel to land. By now the\n // old order is already off the book, so a cancel that arrived during it\n // found nothing to cancel and reported success — resting a replacement\n // after that would put an order on the book the caller believes is gone\n // and has no handle for.\n if (!session.active || !this.#chaseSessions.has(sessionId)) {\n session.replacingOrderId = null;\n this.#deps.debugLogger.log('Chase cancelled mid-reprice', {\n sessionId,\n });\n return;\n }\n\n if (\n remainder.remainingSize === null ||\n (remainder.terminalStatus !== null &&\n remainder.terminalStatus !== CHASE_ORDER_STATUS.Canceled)\n ) {\n // Nothing is left to chase. Preserve whether the venue actually\n // confirmed a fill rather than labelling every zero remainder filled.\n session.replacingOrderId = null;\n session.active = false;\n session.size = remainder.remainingSize ?? '0';\n session.status =\n remainder.terminalStatus ?? CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase order has no remainder', {\n sessionId,\n status: session.status,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n const remaining = remainder.remainingSize;\n\n // Published *before* the placement starts, not from the promise it\n // returns: the window opens the moment `#restChaseOrder` is entered, so\n // deriving the marker from its return value would leave the synchronous\n // prefix of that call unguarded. A cancel arriving anywhere inside the\n // round trip now waits for the replacement to land instead of reading\n // the null `orderId` as \"nothing rests\", reporting success, and dropping\n // the handle while this call is still putting an order on the book.\n let settleReplacement: (() => void) | undefined;\n session.pendingReplacement = new Promise<void>((resolve) => {\n settleReplacement = resolve;\n });\n\n try {\n session.orderId = await this.#restChaseOrder({\n assetId: session.assetId,\n isBuy: session.isBuy,\n price: quotePrice,\n size: remaining,\n reduceOnly: session.reduceOnly,\n builder: session.builder,\n marksSubscriptionCloid: session.marksSubscriptionCloid,\n // A running session is on a live provider, so the current client is\n // the right one; only the first placement has a teardown to survive.\n exchangeClient: this.#clientService.getExchangeClient(),\n });\n session.size = remaining;\n } finally {\n // Cleared before the waiters wake, so they see the settled session.\n session.replacingOrderId = null;\n session.pendingReplacement = null;\n settleReplacement?.();\n }\n session.restingPrice = quotePrice;\n session.repricings += 1;\n\n this.#deps.debugLogger.log('Chase re-priced', {\n sessionId,\n orderId: session.orderId,\n restingPrice: quotePrice,\n size: session.size,\n repricings: session.repricings,\n });\n\n // A cancel that arrived during the round trip is now waiting on this\n // session; it cancels the order just recorded above. A `disconnect`\n // deregisters the session instead, and deliberately leaves resting\n // orders alone — logged with its ID so it stays traceable.\n if (!this.#chaseSessions.has(sessionId)) {\n this.#deps.debugLogger.log('Chase replacement outlived its session', {\n sessionId,\n orderId: session.orderId,\n });\n return;\n }\n if (!session.active) {\n return;\n }\n }\n }\n\n if (reachedMaxDistance && session.maxDistanceBps !== undefined) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.MaxDistanceReached;\n this.#deps.debugLogger.log('Chase max distance reached', {\n sessionId,\n restingPrice: session.restingPrice,\n maxDistanceBps: session.maxDistanceBps,\n });\n this.#onChaseOrderMaxDistanceReached?.({\n handle: sessionId,\n symbol: session.symbol,\n side: session.isBuy ? 'buy' : 'sell',\n restingOrderId: session.orderId,\n restingPrice: session.restingPrice,\n maxDistanceBps: session.maxDistanceBps,\n timestamp: Date.now(),\n providerId: PROVIDER_CONFIG.DefaultProvider,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n if (session.repricings >= session.maxRepricings) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.RepricingLimitReached;\n this.#deps.debugLogger.log('Chase repricing cap reached', { sessionId });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n this.#scheduleChaseTick(sessionId);\n }\n\n /**\n * Resolve how much of the chase's own order is really sitting on its level.\n *\n * The session tracks what its order was last *placed* for, which overstates\n * the order once it partially fills. Over-subtracting only matters when it\n * would net the level away entirely — while the level still shows more size\n * than the order could possibly hold, the level has external liquidity either\n * way and the stale figure is good enough.\n *\n * So the live size is fetched only in the ambiguous case, which keeps the\n * common tick to a single book read rather than doubling the request rate\n * against the venue for every chase on every interval.\n *\n * @param params - Netting parameters.\n * @param params.symbol - Market being quoted.\n * @param params.isBuy - Side being quoted.\n * @param params.callerOrderId - The asking session's order, if it has one.\n * @param params.ownSide - The side of the book those orders rest on.\n * @returns Our resting size at each price, the asking child's terminal\n * result, or the unavailable sentinel.\n */\n async #resolveOwnRestingSizes(params: {\n symbol: string;\n isBuy: boolean;\n callerOrderId?: string;\n ownSide?: { px: string; sz: string }[];\n }): Promise<\n | Map<string, number>\n | ChaseTerminalResolution\n | typeof CHASE_ORDER_STATUS_UNAVAILABLE\n > {\n const { symbol, isBuy, callerOrderId, ownSide } = params;\n\n // Every chase this provider is running on this side, the caller included.\n const ourOrders: ChaseRestingOrder[] = [];\n for (const session of this.#chaseSessions.values()) {\n if (\n session.orderId !== null &&\n session.symbol === symbol &&\n session.isBuy === isBuy\n ) {\n ourOrders.push({\n orderId: session.orderId,\n price: session.restingPrice,\n size: session.size,\n });\n }\n }\n\n if (ourOrders.length === 0) {\n return new Map();\n }\n\n const recorded = new Map<string, number>();\n for (const order of ourOrders) {\n recorded.set(\n order.price,\n (recorded.get(order.price) ?? 0) + parseFloat(order.size),\n );\n }\n\n // A level holding more than we possibly could has external size regardless,\n // so the recorded figures cannot change the answer there and are left as\n // they are. Elsewhere the recorded sizes may overstate what is really\n // resting — an order partially fills without the loop seeing it — and only\n // then is a lookup worth a round trip.\n const ambiguous = ourOrders.filter((order) => {\n const level = ownSide?.find((entry) => entry.px === order.price);\n return !level || parseFloat(level.sz) <= (recorded.get(order.price) ?? 0);\n });\n\n let callerTerminalResult: ChaseTerminalResolution | null = null;\n let callerStatusUnavailable = false;\n const resolutions = await Promise.allSettled(\n ambiguous.map((order) =>\n this.#readOrderRemainder(order.orderId, CHASE_ORDER_STATUS_RETRY_COUNT),\n ),\n );\n resolutions.forEach((resolution, index) => {\n const order = ambiguous[index];\n if (resolution.status === 'fulfilled') {\n const { remainingSize: live, terminalStatus } = resolution.value;\n const delta =\n (live === null ? 0 : parseFloat(live)) - parseFloat(order.size);\n recorded.set(\n order.price,\n Math.max(0, (recorded.get(order.price) ?? 0) + delta),\n );\n if (terminalStatus !== null && order.orderId === callerOrderId) {\n callerTerminalResult = {\n remainingSize: live,\n status: terminalStatus,\n };\n }\n } else {\n const { reason: error } = resolution;\n if (\n error instanceof ChaseOrderStatusUnavailableError &&\n order.orderId === callerOrderId\n ) {\n callerStatusUnavailable = true;\n } else {\n // A failed lookup must not stop the chase. Keeping the recorded size\n // can only over-subtract, which quotes a level deeper rather than\n // leaving the order stranded at a stale price.\n this.#deps.debugLogger.log('Chase own-size lookup failed', {\n orderId: order.orderId,\n error: ensureError(error, 'HyperLiquidProvider.chaseOwnSize')\n .message,\n });\n }\n }\n });\n\n if (callerStatusUnavailable) {\n return CHASE_ORDER_STATUS_UNAVAILABLE;\n }\n return callerTerminalResult ?? recorded;\n }\n\n /**\n * Read what a chase's just-cancelled order left unfilled.\n *\n * A chase re-prices by cancelling and re-placing, and the order it cancels\n * may have partially filled first; re-placing the session's original size\n * would execute more than the caller asked for.\n *\n * Read *after* the cancel on purpose. The order's status endpoint answers for\n * an order that is no longer on the book, and once the cancel has landed no\n * further fills can reach it — so the unfilled size it reports is final.\n * Sampling the open-order book beforehand would instead leave a one-round-trip\n * window in which a fill lands and is then re-placed on top.\n *\n * @param orderId - Exchange ID of the order that was just cancelled.\n * @param unknownStatusRetries - Remaining retries for a transient unknown ID.\n * @returns The unfilled size and exact terminal status, when present.\n */\n async #readOrderRemainder(\n orderId: string,\n unknownStatusRetries = 0,\n ): Promise<ChaseOrderRemainder> {\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const status = await this.#clientService.getInfoClient().orderStatus({\n user: userAddress,\n oid: parseInt(orderId, 10),\n });\n\n if (status.status !== 'order') {\n // unknownOid can be transient while the order-status index catches up.\n // Treating it as a fill would drop the only handle to a live order.\n if (unknownStatusRetries > 0) {\n await new Promise((resolve) =>\n setTimeout(resolve, CHASE_ORDER_STATUS_RETRY_DELAY_MS),\n );\n return await this.#readOrderRemainder(\n orderId,\n unknownStatusRetries - 1,\n );\n }\n throw new ChaseOrderStatusUnavailableError();\n }\n\n const remaining = String(status.order.order.sz);\n const remainingSize = parseFloat(remaining) > 0 ? remaining : null;\n switch (status.order.status) {\n case 'open':\n case 'triggered':\n return { remainingSize, terminalStatus: null };\n case 'filled':\n return {\n remainingSize: null,\n terminalStatus: CHASE_ORDER_STATUS.Filled,\n };\n case 'canceled':\n return remainingSize === null\n ? {\n remainingSize: null,\n terminalStatus: CHASE_ORDER_STATUS.Filled,\n }\n : {\n remainingSize,\n terminalStatus: CHASE_ORDER_STATUS.Canceled,\n };\n default:\n return {\n remainingSize,\n terminalStatus: CHASE_ORDER_STATUS.Failed,\n };\n }\n }\n\n /**\n * Cancel the order a chase session currently has resting.\n *\n * @param session - The session whose child to cancel.\n * @param placingClient - Client to cancel through. Omitted by every cancel on\n * a live provider, which wants the current one; an abandoned placement passes\n * the client it signed with, the only one still able to reach its order.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\n async #cancelChaseChild(\n session: ChaseSession,\n placingClient?: ExchangeClient,\n ): Promise<CancelChildOutcome> {\n if (!session.orderId) {\n return CancelChildOutcome.Gone;\n }\n\n // Looked up only once there is something to cancel, so a session with\n // nothing resting still answers on a provider whose client is already gone.\n const exchangeClient =\n placingClient ?? this.#clientService.getExchangeClient();\n let result;\n try {\n result = await exchangeClient.cancel({\n cancels: [{ a: session.assetId, o: parseInt(session.orderId, 10) }],\n });\n } catch (error) {\n const message = ensureError(\n error,\n 'HyperLiquidProvider.cancelChaseChild',\n ).message.toLowerCase();\n if (\n ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))\n ) {\n return CancelChildOutcome.Gone;\n }\n throw error;\n }\n\n const status: unknown = result.response?.data?.statuses?.[0];\n const signerFailure = await this.#classifyStatusSignerFailure(\n [status],\n result,\n );\n if (signerFailure) {\n throw signerFailure;\n }\n return classifyCancelStatus(status);\n }\n\n /**\n * Take back the order of a chase that was abandoned before it registered.\n *\n * Best-effort by construction: the provider is already being torn down, so a\n * cancel that fails outright is reported rather than retried or thrown. The\n * caller reports the placement as a failure either way — the outcome only\n * decides whether an exchange id is worth handing back with it.\n *\n * @param session - The unregistered session holding the resting order.\n * @param placingClient - The client the order was signed with. The service's\n * own reference is already cleared by the time this runs, so asking it for a\n * client here would fail before a cancel was ever sent.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\n async #retractOrphanedChaseOrder(\n session: ChaseSession,\n placingClient: ExchangeClient,\n ): Promise<CancelChildOutcome> {\n try {\n const outcome = await this.#cancelChaseChild(session, placingClient);\n this.#deps.debugLogger.log('Retracted abandoned chase order', {\n orderId: session.orderId,\n outcome,\n });\n return outcome;\n } catch (error) {\n // A rejected agent is dropped and reported; the order stays resting.\n await this.#evictRejectedAgent(error);\n this.#deps.debugLogger.log('Could not retract abandoned chase order', {\n orderId: session.orderId,\n error: ensureError(error, 'HyperLiquidProvider.startChaseSession')\n .message,\n });\n return CancelChildOutcome.Refused;\n }\n }\n\n /**\n * Stop a chase session's re-pricing loop.\n *\n * @param sessionId - Session to stop.\n */\n #stopChaseSession(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session) {\n return;\n }\n\n const wasActive = session.active;\n session.active = false;\n if (wasActive) {\n session.status = CHASE_ORDER_STATUS.TerminationPending;\n }\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n }\n\n /**\n * Rebalance one Chase session at most once at a time. Failed cleanup keeps\n * the transfer context so a later lifecycle read or cancel can retry it.\n *\n * @param session - Chase session whose manual HIP-3 transfer is complete.\n * @returns Whether no collateral cleanup remains for the session.\n */\n async #rebalanceChaseSession(session: ChaseSession): Promise<boolean> {\n const { hip3Transfer } = session;\n if (!hip3Transfer) {\n return true;\n }\n if (\n session.orderId !== null ||\n session.replacingOrderId !== null ||\n session.pendingReplacement !== null\n ) {\n return false;\n }\n\n let rebalancePromise = session.hip3RebalancePromise;\n if (!rebalancePromise) {\n rebalancePromise = this.#handleHip3PostOrderRebalance(hip3Transfer);\n session.hip3RebalancePromise = rebalancePromise;\n }\n\n try {\n const success = await rebalancePromise;\n if (success && session.hip3Transfer === hip3Transfer) {\n delete session.hip3Transfer;\n }\n return success;\n } finally {\n if (session.hip3RebalancePromise === rebalancePromise) {\n delete session.hip3RebalancePromise;\n }\n }\n }\n\n /**\n * Adapt one venue TWAP history record and its slice fills to the shared\n * controller contract.\n *\n * @param params - Venue history, fills, and read time.\n * @returns A TWAP lifecycle record, or null when the venue supplied no ID.\n */\n #adaptTwapOrder(params: AdaptTwapOrderParams): TwapOrder | null {\n const { historyEntry, now } = params;\n const { state, twapId } = historyEntry;\n if (twapId === undefined || !Number.isSafeInteger(twapId) || twapId < 0) {\n return null;\n }\n\n const totalSize = new BigNumber(state.sz);\n const executedSize = new BigNumber(state.executedSz);\n const executedNotional = new BigNumber(state.executedNtl);\n if (\n !totalSize.isFinite() ||\n !executedSize.isFinite() ||\n !executedNotional.isFinite() ||\n !Number.isFinite(state.timestamp) ||\n !Number.isFinite(historyEntry.time) ||\n !Number.isFinite(state.minutes)\n ) {\n return null;\n }\n let boundedExecutedSize = executedSize;\n if (executedSize.isLessThan(0)) {\n boundedExecutedSize = new BigNumber(0);\n } else if (executedSize.isGreaterThan(totalSize)) {\n boundedExecutedSize = totalSize;\n }\n const rawRemainingSize = totalSize.minus(boundedExecutedSize);\n const remainingSize = rawRemainingSize.isGreaterThan(0)\n ? rawRemainingSize\n : new BigNumber(0);\n const status = resolveTwapOrderStatus(\n historyEntry,\n boundedExecutedSize,\n totalSize,\n );\n const fills = params.sliceFills\n .map(adaptTwapOrderFill)\n .sort((left, right) => left.timestamp - right.timestamp);\n const startedAt = state.timestamp;\n const historyUpdatedAt = normalizeTwapHistoryTimestamp(historyEntry.time);\n const lastUpdated = Math.max(\n startedAt,\n historyUpdatedAt,\n ...fills.map((fill) => fill.timestamp),\n );\n const durationMilliseconds = state.minutes * MILLISECONDS_PER_MINUTE;\n const elapsedTimeMilliseconds = Math.min(\n durationMilliseconds,\n Math.max(\n 0,\n (status === PerpsTwapLifecycleStatus.Active ? now : lastUpdated) -\n startedAt,\n ),\n );\n const fillProgressBps = totalSize.isGreaterThan(0)\n ? boundedExecutedSize\n .dividedBy(totalSize)\n .multipliedBy(BASIS_POINTS_DIVISOR)\n .integerValue(BigNumber.ROUND_FLOOR)\n .toNumber()\n : 0;\n const timeProgressBps =\n durationMilliseconds > 0\n ? Math.floor(\n (elapsedTimeMilliseconds / durationMilliseconds) *\n BASIS_POINTS_DIVISOR,\n )\n : 0;\n\n return {\n orderId: twapId.toString(),\n symbol: state.coin,\n side: state.side === 'B' ? 'buy' : 'sell',\n size: state.sz,\n executedSize: boundedExecutedSize.toString(),\n remainingSize: remainingSize.toFixed(),\n executedNotional: state.executedNtl,\n ...(executedSize.isGreaterThan(0) && {\n averagePrice: executedNotional.dividedBy(executedSize).toFixed(),\n }),\n fillProgressBps,\n timeProgressBps,\n elapsedTimeMilliseconds,\n durationMinutes: state.minutes,\n randomize: state.randomize,\n reduceOnly: state.reduceOnly,\n status,\n startedAt,\n lastUpdated,\n ...(historyEntry.status.status ===\n HyperLiquidTwapLifecycleStatus.Failed && {\n error: historyEntry.status.description,\n }),\n fills,\n };\n }\n\n /**\n * Rebalance one tracked TWAP at most once at a time. A failed transfer keeps\n * the tracking entry so the next lifecycle read or cancel can retry it.\n *\n * @param trackingKey - Account-scoped TWAP tracking key.\n * @returns Whether no cleanup remains for the entry.\n */\n async #rebalanceTrackedTwapOrder(trackingKey: string): Promise<boolean> {\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n if (!trackedOrder) {\n return true;\n }\n if (!trackedOrder.hip3Transfer) {\n if (this.#trackedTwapOrders.get(trackingKey) === trackedOrder) {\n this.#trackedTwapOrders.delete(trackingKey);\n }\n return true;\n }\n\n let { rebalancePromise } = trackedOrder;\n if (!rebalancePromise) {\n rebalancePromise = this.#handleHip3PostOrderRebalance(\n trackedOrder.hip3Transfer,\n );\n trackedOrder.rebalancePromise = rebalancePromise;\n }\n\n try {\n const success = await rebalancePromise;\n if (\n success &&\n this.#trackedTwapOrders.get(trackingKey) === trackedOrder\n ) {\n this.#trackedTwapOrders.delete(trackingKey);\n }\n return success;\n } finally {\n if (\n this.#trackedTwapOrders.get(trackingKey) === trackedOrder &&\n trackedOrder.rebalancePromise === rebalancePromise\n ) {\n delete trackedOrder.rebalancePromise;\n }\n }\n }\n\n /**\n * Return manually moved HIP-3 collateral after a TWAP reaches a terminal\n * venue state. The scoped registry survives reconnects so an active schedule\n * cannot lose its eventual cleanup path.\n *\n * @param orders - Current and historical TWAP lifecycle records.\n * @param scope - Current account and network identity.\n */\n async #rebalanceTerminalHip3Twaps(\n orders: TwapOrder[],\n scope: TwapAccountScope,\n ): Promise<void> {\n for (const order of orders) {\n if (order.status === PerpsTwapLifecycleStatus.Active) {\n continue;\n }\n\n const trackingKey = getTwapOrderScopeKey({\n ...scope,\n orderId: order.orderId,\n });\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n if (trackedOrder?.symbol !== order.symbol) {\n continue;\n }\n\n await this.#rebalanceTrackedTwapOrder(trackingKey);\n }\n }\n\n /**\n * Read native TWAP schedules and their slice fills from the venue.\n *\n * @returns Current and terminal TWAP lifecycle records, newest first.\n */\n async getTwapOrders(): Promise<TwapOrder[]> {\n await this.#ensureClientsInitialized();\n this.#clientService.ensureInitialized();\n\n const lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const [history, sliceFills] = await Promise.all([\n infoClient.twapHistory({ user: userAddress }),\n infoClient.userTwapSliceFills({ user: userAddress }),\n ]);\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'TWAP lifecycle read',\n );\n\n const fillsByTwapId = new Map<number, HyperLiquidTwapSliceFillEntry[]>();\n for (const sliceFill of sliceFills) {\n const existing = fillsByTwapId.get(sliceFill.twapId) ?? [];\n existing.push(sliceFill);\n fillsByTwapId.set(sliceFill.twapId, existing);\n }\n\n const now = Date.now();\n const ordersById = new Map<string, TwapOrder>();\n for (const historyEntry of history) {\n const order = this.#adaptTwapOrder({\n historyEntry,\n sliceFills:\n historyEntry.twapId === undefined\n ? []\n : (fillsByTwapId.get(historyEntry.twapId) ?? []),\n now,\n });\n if (!order) {\n continue;\n }\n\n const existing = ordersById.get(order.orderId);\n if (!existing || supersedesCollapsedTwapOrder(order, existing)) {\n ordersById.set(order.orderId, order);\n }\n }\n\n const orders = [...ordersById.values()].sort(\n (left, right) => right.startedAt - left.startedAt,\n );\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n await this.#rebalanceTerminalHip3Twaps(orders, {\n network,\n userAddress,\n });\n return orders;\n }\n\n /**\n * Return stable client-facing snapshots for every Chase session retained by\n * this provider instance. A read may refresh the current child order's\n * remaining size from the venue, throttled to the Chase interval.\n *\n * @returns Current Chase session snapshots.\n */\n async getChaseOrders(): Promise<ChaseOrder[]> {\n return await Promise.all(\n [...this.#chaseSessions.entries()].map(async ([handle, session]) => {\n const now = Date.now();\n let snapshotRemainingSize = session.size;\n if (\n session.orderId !== null &&\n session.pendingReplacement === null &&\n now - session.lastSnapshotSizeRefreshAt >= session.intervalMs\n ) {\n session.lastSnapshotSizeRefreshAt = now;\n const snapshotOrderId = session.orderId;\n try {\n const liveRemainder = await this.#readOrderRemainder(\n snapshotOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n if (\n session.orderId === snapshotOrderId &&\n session.pendingReplacement === null\n ) {\n if (liveRemainder.terminalStatus === null) {\n if (liveRemainder.remainingSize !== null) {\n session.size = liveRemainder.remainingSize;\n snapshotRemainingSize = liveRemainder.remainingSize;\n }\n } else {\n session.orderId = null;\n session.size = liveRemainder.remainingSize ?? '0';\n session.active = false;\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n session.status = liveRemainder.terminalStatus;\n snapshotRemainingSize = session.size;\n }\n }\n } catch (error) {\n this.#deps.debugLogger.log('Chase snapshot size refresh failed', {\n orderId: snapshotOrderId,\n error: ensureError(error, 'HyperLiquidProvider.getChaseOrders')\n .message,\n });\n }\n }\n\n if (!session.active && session.hip3Transfer) {\n const rebalanced = await this.#rebalanceChaseSession(session);\n if (rebalanced && session.removeAfterRebalance) {\n this.#chaseSessions.delete(handle);\n }\n }\n\n const arrival = Number.parseFloat(session.arrivalPrice);\n const resting = Number.parseFloat(session.restingPrice);\n const adverseDistance = session.isBuy\n ? resting - arrival\n : arrival - resting;\n const measuredDistance =\n Number.isFinite(arrival) &&\n arrival > 0 &&\n Number.isFinite(adverseDistance)\n ? Math.round(\n (Math.max(0, adverseDistance) / arrival) * BASIS_POINTS_DIVISOR,\n )\n : 0;\n return {\n handle,\n symbol: session.symbol,\n side: session.isBuy ? 'buy' : 'sell',\n originalSize: session.originalSize,\n remainingSize: snapshotRemainingSize,\n arrivalPrice: session.arrivalPrice,\n restingPrice: session.restingPrice,\n restingOrderId: session.orderId,\n distanceChasedBps: measuredDistance,\n ...(session.maxDistanceBps === undefined\n ? {}\n : { maxDistanceBps: session.maxDistanceBps }),\n repricings: session.repricings,\n startedAt: session.startedAt,\n status: session.status,\n };\n }),\n );\n }\n\n /**\n * Stop all active Chase loops while deliberately leaving their current\n * post-only children resting. Used when a client moves to the background.\n *\n * @returns Snapshots after every in-flight replacement has settled.\n */\n async suspendChaseOrders(): Promise<ChaseOrder[]> {\n this.#chasePlacementBlockers += 1;\n try {\n await Promise.all([...this.#chasePlacementWaiters]);\n // Clear timers without deactivating sessions, then let any tick already\n // admitted to the shared queue finish its cancel/replace. Stopping first\n // can strand a session between children: the old order is cancelled, the\n // tick observes `active === false`, and suspension reports a resting\n // Chase that no longer owns an exchange order.\n this.#pauseChaseTicksForPlacement();\n await this.#chaseTickQueue;\n\n for (const [sessionId, session] of this.#chaseSessions.entries()) {\n if (!session.active) {\n continue;\n }\n this.#stopChaseSession(sessionId);\n session.status = CHASE_ORDER_STATUS.Backgrounded;\n }\n return await this.getChaseOrders();\n } finally {\n this.#chasePlacementBlockers -= 1;\n }\n }\n\n /**\n * Cancel a strategy placement by its handle.\n *\n * @param params - Cancellation parameters.\n * @returns A promise that resolves to the result.\n */\n async #cancelStrategyOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n try {\n this.#deps.debugLogger.log('Canceling strategy order:', params);\n\n if (params.orderType === 'twap') {\n return await this.#cancelTwapOrder(params);\n }\n if (params.orderType === 'scale') {\n return await this.#cancelScaleOrder(params);\n }\n return await this.#cancelChaseOrder(params);\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrder',\n {\n orderId: params.orderId,\n coin: params.symbol,\n orderType: params.orderType,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n return createErrorResult(mappedError, {\n success: false,\n orderId: params.orderId,\n });\n }\n }\n\n /**\n * Cancel a running TWAP through the venue's TWAP cancel action.\n *\n * A TWAP never rested on the book, so the ordinary `cancel` action has no\n * order ID to match and would reject it.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the TWAP ID.\n * @returns A promise that resolves to the result.\n */\n async #cancelTwapOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n await this.#ensureReady();\n\n const coinValidation = validateCoinExists(\n params.symbol,\n this.#symbolToAssetId,\n );\n if (!coinValidation.isValid) {\n throw new Error(coinValidation.error);\n }\n\n const twapId = Number(params.orderId);\n if (!/^\\d+$/u.test(params.orderId) || !Number.isSafeInteger(twapId)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const trackingKey = getTwapOrderScopeKey({\n network,\n userAddress,\n orderId: params.orderId,\n });\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n let ownershipAuthenticated = trackedOrder !== undefined;\n if (trackedOrder) {\n if (trackedOrder.symbol !== params.symbol) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n } else {\n let venueOrders: TwapOrder[] | null = null;\n try {\n venueOrders = await this.getTwapOrders();\n } catch (error) {\n // History is an ownership check, not the cancellation transport. A\n // transient read failure must not make a live TWAP impossible to stop.\n this.#deps.debugLogger.log(\n 'TWAP history unavailable before cancellation',\n {\n orderId: params.orderId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.cancelTwapOrderHistory',\n ).message,\n },\n );\n }\n const venueOrder = venueOrders?.find(\n (order) => order.orderId === params.orderId,\n );\n if (venueOrders !== null && venueOrder?.symbol !== params.symbol) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n ownershipAuthenticated = venueOrder !== undefined;\n }\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName: parseAssetName(params.symbol).dex,\n });\n\n const result = await this.#clientService.getExchangeClient().twapCancel({\n a: assetId,\n t: twapId,\n });\n\n const status = result.response?.data?.status;\n const cancelOutcome = classifyCancelStatus(status);\n if (cancelOutcome === CancelChildOutcome.Gone && !ownershipAuthenticated) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n if (cancelOutcome !== CancelChildOutcome.Refused) {\n await this.#rebalanceTrackedTwapOrder(trackingKey);\n return { success: true, orderId: params.orderId };\n }\n\n const rawError =\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : 'TWAP cancellation failed';\n return createErrorResult(await this.#mapStatusError(rawError, result), {\n success: false,\n orderId: params.orderId,\n });\n }\n\n /**\n * Cancel every child of a scale ladder in one batch.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the group handle.\n * @returns A promise that resolves to the result.\n */\n async #cancelScaleOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n const group = this.#scaleOrderGroups.get(params.orderId);\n if (!group) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: group.symbol,\n dexName: parseAssetName(group.symbol).dex,\n });\n const exchangeClient = this.#clientService.getExchangeClient();\n const cancelRequests = group.orderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n }));\n const cancelByCloidRequests = group.clientOrderIds.map((clientOrderId) => ({\n asset: assetId,\n cloid: clientOrderId,\n }));\n const [orderCancellation, cloidCancellation] = await Promise.all([\n this.#cancelOrderRequestBatch(exchangeClient, cancelRequests),\n this.#cancelOrderCloidRequestBatch(exchangeClient, cancelByCloidRequests),\n ]);\n const remaining = orderCancellation.remainingOrderIds.map(String);\n const { remainingClientOrderIds } = cloidCancellation;\n\n /*\n * A rung that filled or was cancelled individually comes back as a\n * rejection, but nothing of it is resting. The shared cancellation helper\n * distinguishes that result from a refusal while retaining every child\n * after a malformed or non-ok batch response.\n */\n if (remaining.length === 0 && remainingClientOrderIds.length === 0) {\n this.#cancelledScaleOrderGroups.add(params.orderId);\n this.#scaleOrderGroups.delete(params.orderId);\n return { success: true, orderId: params.orderId };\n }\n\n // A rung the exchange refused to cancel may still be resting. Keeping the\n // handle registered against what is left means the caller can retry the\n // same cancel rather than being told the ladder is gone when it is not.\n this.#scaleOrderGroups.set(params.orderId, {\n symbol: group.symbol,\n orderIds: remaining,\n clientOrderIds: remainingClientOrderIds,\n });\n // The signer could not sign a cancel: retryable, not a defect.\n const signerFailure =\n orderCancellation.signerFailure ?? cloidCancellation.signerFailure;\n if (signerFailure) {\n this.#logRetryableSignerFailure('cancelOrder', {\n orderId: params.orderId,\n orderType: params.orderType,\n });\n return createErrorResult(signerFailure, {\n success: false,\n orderId: params.orderId,\n });\n }\n this.#deps.debugLogger.log('Scale group cancel left children resting', {\n groupId: params.orderId,\n remainingOrderIds: remaining.length,\n remainingClientOrderIds: remainingClientOrderIds.length,\n total: group.orderIds.length + group.clientOrderIds.length,\n });\n\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n { success: false, orderId: params.orderId },\n );\n }\n\n /**\n * Stop a chase session and cancel whatever it still has resting.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the session handle.\n * @returns A promise that resolves to the result.\n */\n async #cancelChaseOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n if (this.#terminatedChaseHandles.has(params.orderId)) {\n return { success: true, orderId: params.orderId };\n }\n const existingTermination = this.#chaseTerminations.get(params.orderId);\n if (existingTermination) {\n return await existingTermination;\n }\n\n const termination = this.#performChaseTermination(params);\n this.#chaseTerminations.set(params.orderId, termination);\n try {\n const result = await termination;\n if (result.success) {\n this.#terminatedChaseHandles.add(params.orderId);\n }\n return result;\n } finally {\n this.#chaseTerminations.delete(params.orderId);\n }\n }\n\n /**\n * Own one Chase termination after concurrent callers have been deduplicated.\n *\n * @param params - Cancellation parameters with a stable Chase handle.\n * @returns The single underlying termination result.\n */\n async #performChaseTermination(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n const session = this.#chaseSessions.get(params.orderId);\n if (!session) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n // Stopped first: a tick that fired between here and the cancel below would\n // otherwise re-place the very order being cancelled.\n this.#stopChaseSession(params.orderId);\n\n // A replacement already in flight cannot be called off, so the cancel waits\n // for it and then cancels whatever it rested. Deciding without waiting would\n // read the session's null `orderId` as \"nothing rests\" and report a clean\n // cancellation over an order that was about to appear on the book.\n if (session.pendingReplacement) {\n await session.pendingReplacement;\n }\n\n // Nothing rests: the order filled, something else cancelled it, or a\n // replacement failed to go up. Either way the session ends cleanly.\n if (session.orderId === null) {\n session.removeAfterRebalance = true;\n if (await this.#rebalanceChaseSession(session)) {\n this.#chaseSessions.delete(params.orderId);\n }\n return { success: true, orderId: params.orderId };\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n // Only a refusal leaves an order behind. A child that had already filled or\n // been cancelled is reported as a rejection too, but nothing of it is\n // resting — treating that as a failure would pin the handle open forever on\n // a chase that is entirely finished.\n const cancelOutcome = await this.#cancelChaseChild(session);\n\n if (cancelOutcome === CancelChildOutcome.Refused) {\n // The order is still resting. The session stays registered — stopped, but\n // still cancellable — so the caller can retry with the same handle.\n this.#deps.debugLogger.log('Chase cancel left its order resting', {\n sessionId: params.orderId,\n orderId: session.orderId,\n });\n await this.#rebalanceChaseSession(session);\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n { success: false, orderId: params.orderId },\n );\n }\n\n session.orderId = null;\n session.status = CHASE_ORDER_STATUS.Canceled;\n session.removeAfterRebalance = true;\n if (await this.#rebalanceChaseSession(session)) {\n this.#chaseSessions.delete(params.orderId);\n }\n return { success: true, orderId: params.orderId };\n }\n\n /**\n * Cancel a batch and retain every order that may still be live.\n *\n * A malformed, truncated, or rejected response cannot prove which requests\n * reached the venue, so every requested ID remains recoverable for a retry.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel requests.\n * @param onError - Optional operation-specific failure classifier.\n * @returns Order IDs that may still be resting.\n */\n async #cancelOrderRequests(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelRequest[],\n onError?: (error: unknown) => void | Promise<void>,\n ): Promise<number[]> {\n return (\n await this.#cancelOrderRequestBatch(exchangeClient, requests, onError)\n ).remainingOrderIds;\n }\n\n /**\n * Cancel pending orders by client order ID and retain every request that may\n * still be live.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel-by-CLOID requests.\n * @returns Client order IDs that may still be resting.\n */\n async #cancelOrderCloidRequests(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelByCloidRequest[],\n ): Promise<Hex[]> {\n return (await this.#cancelOrderCloidRequestBatch(exchangeClient, requests))\n .remainingClientOrderIds;\n }\n\n /**\n * Cancel pending orders by client order ID, reporting a signer that could\n * not sign the cancel.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel-by-CLOID requests.\n * @returns Client order IDs that may still be resting, and the signer\n * failure when the signer could not sign the request.\n */\n async #cancelOrderCloidRequestBatch(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelByCloidRequest[],\n ): Promise<{ remainingClientOrderIds: Hex[]; signerFailure?: Error }> {\n if (requests.length === 0) {\n return { remainingClientOrderIds: [] };\n }\n\n const classifyStatuses = async (\n statuses: unknown[],\n answer: unknown,\n ): Promise<{ remainingClientOrderIds: Hex[]; signerFailure?: Error }> => {\n // A signer failure is classified (and reported) once for the request;\n // entries the venue cancelled are not resting either way.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n return {\n remainingClientOrderIds: requests.flatMap((request, index) =>\n classifyCancelStatus(statuses[index]) === CancelChildOutcome.Refused\n ? [request.cloid]\n : [],\n ),\n ...(signerFailure && { signerFailure }),\n };\n };\n\n try {\n const result = await exchangeClient.cancelByCloid({\n cancels: requests,\n });\n const statuses = result.response?.data?.statuses ?? [];\n if (result.status !== 'ok' || statuses.length !== requests.length) {\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n };\n }\n\n return await classifyStatuses(statuses, result);\n } catch (error) {\n // The SDK throws when any entry failed, with every entry's status.\n const statuses = getCancelStatusesFromError(error, requests.length);\n if (statuses) {\n return await classifyStatuses(statuses, getVenueAnswer(error));\n }\n // The signer could not sign, so nothing was cancelled.\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n signerFailure,\n };\n }\n this.#deps.debugLogger.log('Order cancellation by CLOID failed', {\n error: ensureError(\n error,\n 'HyperLiquidProvider.cancelOrderCloidRequests',\n ).message,\n clientOrderIds: requests.map((request) => request.cloid),\n });\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n };\n }\n }\n\n /**\n * Cancel a batch while distinguishing confirmed cancellations from orders\n * that were already gone. Replacement rollback may only restore the former.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel requests.\n * @param onError - Optional operation-specific failure classifier.\n * @returns IDs that may still rest and IDs this call confirmed it cancelled.\n */\n async #cancelOrderRequestBatch(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelRequest[],\n onError?: (error: unknown) => void | Promise<void>,\n ): Promise<CancelOrderBatchOutcome> {\n if (requests.length === 0) {\n return {\n remainingOrderIds: [],\n cancelledOrderIds: [],\n responseComplete: true,\n };\n }\n\n const classifyStatuses = async (\n statuses: unknown[],\n answer: unknown,\n ): Promise<CancelOrderBatchOutcome> => {\n // A signer failure is classified (and reported) once for the request;\n // entries the venue cancelled still count as cancelled.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n const remainingOrderIds: number[] = [];\n const cancelledOrderIds: number[] = [];\n requests.forEach((request, index) => {\n const outcome = classifyCancelStatus(statuses[index]);\n if (outcome === CancelChildOutcome.Refused) {\n remainingOrderIds.push(request.o);\n } else if (outcome === CancelChildOutcome.Cancelled) {\n cancelledOrderIds.push(request.o);\n }\n });\n return {\n remainingOrderIds,\n cancelledOrderIds,\n responseComplete: true,\n ...(signerFailure && { signerFailure }),\n };\n };\n\n try {\n const result = await exchangeClient.cancel({ cancels: requests });\n const statuses = result.response?.data?.statuses ?? [];\n if (result.status !== 'ok' || statuses.length !== requests.length) {\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n };\n }\n\n return await classifyStatuses(statuses, result);\n } catch (error) {\n await onError?.(error);\n // The SDK throws when any entry failed, with every entry's status.\n const statuses = getCancelStatusesFromError(error, requests.length);\n if (statuses) {\n return await classifyStatuses(statuses, getVenueAnswer(error));\n }\n // The signer could not sign, so nothing was cancelled.\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n signerFailure,\n };\n }\n this.#deps.debugLogger.log('Order cancellation batch failed', {\n error: ensureError(error, 'HyperLiquidProvider.cancelOrderRequests')\n .message,\n orderIds: requests.map((request) => request.o),\n });\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n };\n }\n }\n\n /**\n * Read an order ID out of one `order` action status entry.\n *\n * @param status - A single status from the exchange response.\n * @returns The order ID, or undefined when the entry rested nothing.\n */\n #readOrderPlacementOutcome(\n status: unknown,\n ): OrderPlacementOutcome | undefined {\n if (!isStatusObject(status)) {\n return undefined;\n }\n\n for (const state of ['resting', 'filled'] as const) {\n if (!hasProperty(status, state)) {\n continue;\n }\n const order = status[state];\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0\n ) {\n return { orderId: order.oid.toString(), state };\n }\n }\n return undefined;\n }\n\n /**\n * Classify one TP/SL placement response.\n *\n * HyperLiquid acknowledges a resting trigger with the bare\n * `waitingForTrigger` string, which is successful but carries no order ID.\n * Other placement paths still require a resting or filled ID.\n *\n * @param status - A single status from the exchange response.\n * @returns The TP/SL-specific placement outcome.\n */\n #readTpslOrderPlacementOutcome(status: unknown): TpslOrderPlacementOutcome {\n const placement = this.#readOrderPlacementOutcome(status);\n if (placement) {\n return placement;\n }\n if (status === 'waitingForTrigger') {\n return { state: 'waitingForTrigger' };\n }\n if (isStatusObject(status) && hasProperty(status, 'error')) {\n return { state: 'rejected' };\n }\n return { state: 'unknown' };\n }\n\n /**\n * Preserve the raw statuses carried by the SDK's bulk rejection.\n *\n * @param error - SDK exchange error.\n * @returns Exact reported statuses, or undefined for no authoritative batch.\n */\n #readProtectionErrorStatuses(error: unknown): unknown[] | undefined {\n const response =\n error instanceof Error && hasProperty(error, 'response')\n ? error.response\n : undefined;\n return isStatusObject(response) &&\n isStatusObject(response.response) &&\n response.response.type === 'order' &&\n isStatusObject(response.response.data) &&\n Array.isArray(response.response.data.statuses)\n ? response.response.data.statuses\n : undefined;\n }\n\n /**\n * Distinguish a venue rejection from ambiguous transport failure.\n *\n * @param error - SDK exchange error.\n * @returns Whether the venue authoritatively rejected the entire action.\n */\n #isDefinitiveProtectionRejection(error: unknown): boolean {\n const response =\n error instanceof Error && hasProperty(error, 'response')\n ? error.response\n : undefined;\n return (\n isStatusObject(response) &&\n response.status === 'err' &&\n typeof response.response === 'string'\n );\n }\n\n /**\n * Apply both signer invalidation and account-shape classification to writes.\n *\n * @param error - Failed protection write.\n * @returns Actionable error retaining the venue message when unmapped.\n */\n async #classifyProtectionWriteError(error: unknown): Promise<Error> {\n return (\n (await this.#classifySignerFailure(error)) ??\n (isHyperLiquidMultiSigRequiredError(error)\n ? new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)\n : ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'))\n );\n }\n\n /**\n * Correlate protection outcomes only by final signed cloid and market.\n * Unknown/truncated acknowledgements never acquire ownership from book shape.\n *\n * @param params - Captured request identities and scoped status reader.\n * @param params.outcomes - Classified SDK statuses, possibly truncated.\n * @param params.orders - Exact signed orders, including final cloids.\n * @param params.userAddress - Captured submitting account.\n * @param params.infoClient - Captured venue reader.\n * @param params.assertScope - Account/network/lifecycle fence.\n * @param params.symbol - Requested venue market.\n * @returns Ordered outcomes with exact identities where resolved.\n */\n async #reconcileTpslOrderPlacementOutcomes(params: {\n outcomes: TpslOrderPlacementOutcome[];\n orders: SDKOrderParams[];\n userAddress: Hex;\n infoClient: InfoClient;\n assertScope: () => Promise<void>;\n symbol: string;\n }): Promise<TpslOrderPlacementOutcome[]> {\n const correlated: TpslOrderPlacementOutcome[] = [];\n for (const [index, order] of params.orders.entries()) {\n const outcome = params.outcomes[index] ?? { state: 'unknown' as const };\n if (outcome.state === 'rejected' || outcome.orderId !== undefined) {\n correlated.push(outcome);\n continue;\n }\n let resolved = outcome;\n if (order.c !== undefined) {\n await params.assertScope();\n try {\n const status = await params.infoClient.orderStatus({\n user: params.userAddress,\n oid: order.c,\n });\n await params.assertScope();\n if (status.status === 'order') {\n const row = status.order.order;\n if (\n row.coin === params.symbol &&\n row.cloid?.toLowerCase() === order.c.toLowerCase() &&\n Number.isSafeInteger(row.oid) &&\n row.oid > 0\n ) {\n let state: TpslOrderPlacementOutcome['state'] = 'unknown';\n if (status.order.status === 'filled') {\n state = 'filled';\n } else if (status.order.status === 'open') {\n state = 'resting';\n } else if (\n hasProperty(\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS,\n status.order.status,\n )\n ) {\n const terminal =\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS[status.order.status];\n if (terminal === 'canceled' || terminal === 'rejected') {\n state = 'rejected';\n }\n }\n resolved = { orderId: String(row.oid), state };\n }\n }\n } catch {\n await params.assertScope();\n }\n }\n correlated.push(resolved);\n }\n const ids = correlated.flatMap((outcome) =>\n outcome.orderId ? [outcome.orderId] : [],\n );\n return correlated.map((outcome) =>\n outcome.orderId && ids.filter((id) => id === outcome.orderId).length > 1\n ? { state: 'unknown' }\n : outcome,\n );\n }\n\n /**\n * Read a valid order ID from a resting or filled placement status.\n *\n * @param status - A single status from the exchange response.\n * @returns The order ID, or undefined when the status has no valid ID.\n */\n #readOrderIdFromStatus(status: unknown): string | undefined {\n return this.#readOrderPlacementOutcome(status)?.orderId;\n }\n\n /**\n * The builder fee this account pays, after any rewards discount.\n *\n * @returns The fee in tenths of a basis point.\n */\n #getDiscountedBuilderFee(): number {\n if (this.#userFeeDiscountBips === undefined) {\n return BUILDER_FEE_CONFIG.MaxFeeTenthsBps;\n }\n // Shared with the preview so a quoted rate is the rate the venue charges.\n return quantizeBuilderFeeTenthsBps(this.#userFeeDiscountBips);\n }\n\n /**\n * Resolve the builder payload for the current operation.\n *\n * ADR 0064 removed the dedicated subscription builder: every source — the\n * subscription waiver included — now pays through the standard builder at the\n * resolved fee, and the subscription attribution rides on the order's cloid\n * instead (see {@link #applySubscriptionCloid}). That drops the per-user\n * builder approval the ADR rejected, and lets a partial waiver charge a real\n * blended fee, which a dedicated 0-bips builder could not express.\n *\n * @param setupContext - Account, network, and builder approved for the order.\n * @returns HyperLiquid builder address and fee payload.\n */\n async #getBuilderOrderContext(\n setupContext: BuilderFeeSetupContext,\n ): Promise<{ b: string; f: number }> {\n return {\n b: setupContext.builderAddress,\n f: this.#getDiscountedBuilderFee(),\n };\n }\n\n /**\n * Whether the operation in flight actually carries a subscription reduction.\n *\n * Winning the comparison is not sufficient. A nearly-spent allowance produces\n * a blend that approaches the full fee without reaching it, so it still wins\n * on `<=` — but its discount rounds to zero bips and\n * {@link #getDiscountedBuilderFee} then charges the undiscounted fee. Marking\n * such an order would tell the fill fan-out a waiver applied when the user\n * paid full price. The marking therefore follows the charged fee, not the\n * winning source.\n *\n * @returns True when the resolved source is `subscription` and it reduced the fee.\n */\n #isSubscriptionFeeSource(): boolean {\n return (\n this.#userFeeResolution?.source === 'subscription' &&\n this.#getDiscountedBuilderFee() < BUILDER_FEE_CONFIG.MaxFeeTenthsBps\n );\n }\n\n /**\n * Mark an order's cloid for the subscription program when it won the fee.\n *\n * This is the single place a cloid becomes subscription-attributed. Every\n * placement path — primary submit, scale ladder, TP/SL (attached and\n * standalone), batch close, modify/replace, and chase — routes its orders\n * through here, so no path can silently ship an unmarked order while the\n * waiver is being charged, and no other fee source can produce a marked one.\n *\n * A cloid this package generated keeps its trailing entropy, so the Scale\n * ladder's per-rung index and its cancel-by-cloid recovery survive marking.\n * A caller's `OrderParams.clientOrderId` is never rewritten, so those orders\n * go unattributed — which is why `isGenerated` is passed explicitly rather\n * than inferred from the id's leading bytes: a caller is free to supply one\n * that happens to begin with a reserved marker.\n *\n * @param orders - The SDK order payloads about to be submitted.\n * @param generatedCloids - Cloids this package generated for these orders and\n * may therefore re-stamp. Scale ladders and position TP/SL supply these;\n * other paths have no cloid or carry the caller's own.\n * @param marksSubscriptionCloid - Overrides the live fee resolution for a\n * chase replacement, which runs after that resolution has been cleared.\n * @returns The same payloads, with cloids marked when subscription won.\n */\n #applySubscriptionCloid(\n orders: SDKOrderParams[],\n generatedCloids?: ReadonlySet<string>,\n marksSubscriptionCloid?: boolean,\n ): SDKOrderParams[] {\n // A chase replacement decides from the session, because the live resolution\n // was cleared when the caller's `placeOrder` returned. Everything else\n // decides from the resolution in flight.\n const marks = marksSubscriptionCloid ?? this.#isSubscriptionFeeSource();\n if (!marks) {\n // Any other source leaves the id exactly as the caller built it.\n // Position TP/SL already reserves the subscription layout with flag00;\n // the program marker alone never implies a fee reduction.\n return orders;\n }\n\n return orders.map((order) => ({\n ...order,\n c: markSubscriptionCloid({\n clientOrderId: order.c ?? undefined,\n isGenerated:\n order.c !== undefined && Boolean(generatedCloids?.has(order.c)),\n entropy: uuidv4().replace(/-/gu, ''),\n }),\n }));\n }\n\n /**\n * Read the account's currently resting orders.\n *\n * @param params - The lookup parameters.\n * @param params.dexName - DEX to query, or null for the main DEX.\n * @returns The raw open orders.\n */\n async #fetchOpenOrders(params: {\n dexName: string | null;\n }): Promise<FrontendOrder[]> {\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n return await this.#clientService.getInfoClient().frontendOpenOrders({\n user: userAddress,\n dex: params.dexName ?? undefined,\n });\n }\n\n /**\n * Resolve the order id that a `modify` rested the replacement under.\n *\n * HyperLiquid does not edit an order in place: it cancels the target and\n * rests a replacement under a NEW oid, which the SDK's modify response does\n * not carry. The submitted oid therefore names an order that no longer\n * exists, so the only honest source of identity is a post-modify read.\n *\n * An id is returned only when exactly one newly-rested order carries the\n * attributes just submitted. Everything else leaves it absent: a market edit\n * that filled rather than rested, a read that has not caught up yet, or two\n * equally plausible candidates. Novelty is judged against the pre-edit\n * snapshot rather than attributes alone, because an order that was already\n * resting can share a market, side and size with the replacement.\n *\n * @param params - The resolution parameters.\n * @param params.previousOrders - Orders resting immediately before the edit.\n * @param params.dexName - DEX to query, or null for the main DEX.\n * @param params.symbol - Market the edit was submitted against.\n * @param params.isBuy - Direction submitted.\n * @param params.size - Formatted size submitted.\n * @returns The replacement order id, or undefined when it cannot be resolved unambiguously.\n */\n async #resolveReplacementOrderId(params: {\n previousOrders: FrontendOrder[];\n dexName: string | null;\n symbol: string;\n isBuy: boolean;\n size: string;\n }): Promise<string | undefined> {\n try {\n const previousOrderIds = new Set(\n params.previousOrders.map((order) => order.oid.toString()),\n );\n const ordersAfterEdit = await this.#fetchOpenOrders({\n dexName: params.dexName,\n });\n const submittedSize = parseFloat(params.size);\n const candidates = ordersAfterEdit.filter(\n (order) =>\n !previousOrderIds.has(order.oid.toString()) &&\n order.coin === params.symbol &&\n (order.side === 'B') === params.isBuy &&\n parseFloat(order.sz) === submittedSize,\n );\n\n return candidates.length === 1 ? candidates[0].oid.toString() : undefined;\n } catch (error) {\n // The modify was accepted; only the identity lookup failed. Reporting a\n // failed edit here would misstate an order that really was changed.\n this.#deps.debugLogger.log(\n 'Could not resolve the replacement order id after modify:',\n error,\n );\n return undefined;\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 // `modify` rebuilds an order as a plain limit/market order, so a trigger\n // on either side of the edit would be silently dropped. Reject a resting\n // trigger order as well as an edit *into* one; cancel and re-place instead.\n if (isTriggerOrderType(params.newOrder.orderType)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\n };\n }\n\n // A strategy placement is not a single resting order, so there is nothing\n // for `modify` to rewrite: it would submit the edit as an ordinary\n // FrontendMarket modification and quietly drop the TWAP schedule, the\n // ladder, or the chase loop the caller asked for. Cancel by the strategy\n // handle and place again.\n if (isStrategyOrderType(params.newOrder.orderType)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_STRATEGY_UNSUPPORTED,\n };\n }\n\n // The WebSocket order cache is the cheap source for the resting order's\n // placement type, but it may be cold or stale.\n const cachedRestingOrder = this.#subscriptionService\n .getOrdersCacheIfInitialized()\n ?.find((order) => order.orderId === params.orderId.toString());\n if (cachedRestingOrder?.isTrigger === true) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\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 triggerPrice: params.newOrder.triggerPrice,\n takeProfitPrice: params.newOrder.takeProfitPrice,\n stopLossPrice: params.newOrder.stopLossPrice,\n takeProfitSize: params.newOrder.takeProfitSize,\n stopLossSize: params.newOrder.stopLossSize,\n tpslLinkage: params.newOrder.tpslLinkage,\n grouping: params.newOrder.grouping,\n timeInForce: params.newOrder.timeInForce,\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(params.newOrder.symbol);\n\n // Initialization only — clients and the asset mapping. The signing half\n // of readiness is deferred until after the checks below, so a refused\n // edit never prompts for a signature or writes an approval.\n await this.#ensureReady();\n\n // What is resting before the edit serves two purposes, and they carry\n // different weight. Verifying the target is REQUIRED when the cache could\n // not do it — an unverified edit can rebuild a protective stop as a plain\n // order — so that read must fail closed. Providing a baseline for the\n // optional orderId resolution is not: when the cache already confirmed the\n // order, a failed read must not sink a modify that would otherwise\n // succeed, exactly as the post-modify lookup does not.\n let ordersBeforeEdit: FrontendOrder[] | undefined;\n\n if (cachedRestingOrder === undefined) {\n ordersBeforeEdit = await this.#fetchOpenOrders({ dexName });\n const restingOrder = ordersBeforeEdit.find(\n (order) => order.oid.toString() === params.orderId.toString(),\n );\n\n if (!restingOrder) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_ORDER_UNVERIFIABLE,\n };\n }\n\n if (restingOrder.isTrigger) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\n };\n }\n } else {\n try {\n ordersBeforeEdit = await this.#fetchOpenOrders({ dexName });\n } catch (error) {\n // Only the optional identity baseline is lost. Without it novelty\n // cannot be judged, so the id is omitted below rather than guessed.\n this.#deps.debugLogger.log(\n 'Could not read the pre-edit orders baseline:',\n error,\n );\n }\n }\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 helper as placeOrder so the\n // slippage rules stay in one place (bps → decimal, market-only, default).\n // Accept the deprecated decimal `slippage` field too, normalizing to bps.\n const normalizedMaxSlippageBps =\n params.newOrder.maxSlippageBps ??\n (typeof params.newOrder.slippage === 'number'\n ? Math.round(params.newOrder.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n // calculateOrderPriceAndSize formats with formatHyperLiquidSize, which\n // rounds half-up. On a reduce-only edit that can submit a size above the\n // one requested, which HyperLiquid rejects with \"Reduce only order would\n // increase position\", so floor onto the size grid first. An opening edit\n // keeps its existing rounding: it has no position ceiling to breach.\n const requestedSize = parseFloat(params.newOrder.size);\n const sizeForSubmission =\n params.newOrder.reduceOnly === true\n ? floorToSizeDecimals(requestedSize, assetInfo.szDecimals)\n : requestedSize;\n\n // Refuse non-numeric and non-positive sizes before formatting or submit.\n if (!(sizeForSubmission > 0)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE,\n };\n }\n\n const { formattedSize, formattedPrice } = calculateOrderPriceAndSize({\n orderType: params.newOrder.orderType,\n isBuy: params.newOrder.isBuy,\n finalPositionSize: sizeForSubmission,\n currentPrice,\n limitPrice: params.newOrder.price,\n maxSlippageBps: normalizedMaxSlippageBps,\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 // A limit order honours the caller's time in force; validation above has\n // already rejected one on any other order shape.\n t:\n params.newOrder.orderType === 'limit'\n ? { limit: { tif: toSDKTimeInForce(params.newOrder.timeInForce) } }\n : { limit: { tif: 'FrontendMarket' } }, // True market order\n c: params.newOrder.clientOrderId\n ? params.newOrder.clientOrderId\n : undefined,\n };\n\n // Every refusal is behind us, so shared trading readiness can run now.\n // HyperLiquid's modify action has no builder field and must not request a\n // builder-fee approval.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // Submit modification via SDK. The cloid is deliberately left unmarked:\n // `modify` carries no builder field, as the readiness call above records,\n // so no MetaMask fee is charged on this action and marking it would tell\n // the fill fan-out a reduction applied to an order that paid nothing.\n // The replacement inherits the resting order's own attribution.\n const exchangeClient = this.#clientService.getExchangeClient();\n const result = await exchangeClient.modify({\n oid:\n typeof params.orderId === 'string' ? params.orderId : 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 // `params.orderId` is the order that was just REPLACED, so returning it\n // as OrderResult.orderId (documented as the exchange order ID) names an\n // order the venue has already cancelled. Report the replacement when it\n // can be resolved unambiguously, and otherwise omit the optional id\n // rather than fabricate identity.\n const replacementOrderId =\n ordersBeforeEdit === undefined\n ? undefined\n : await this.#resolveReplacementOrderId({\n previousOrders: ordersBeforeEdit,\n dexName,\n symbol: params.newOrder.symbol,\n isBuy: params.newOrder.isBuy,\n size: formattedSize,\n });\n\n return {\n success: true,\n ...(replacementOrderId === undefined\n ? {}\n : { orderId: replacementOrderId }),\n };\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'editOrder',\n {\n orderId: params.orderId,\n },\n );\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.editOrder'),\n this.#getErrorContext(\n 'editOrder',\n {\n orderId: params.orderId,\n coin: params.newOrder.symbol,\n orderType: params.newOrder.orderType,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.EditOrder,\n },\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 // A strategy handle is not an exchange order ID, so it cannot go through\n // the single-order cancel below. Callers that omit `orderType` — every\n // existing one — keep the behaviour they have today.\n if (params.orderType && isStrategyOrderType(params.orderType)) {\n return await this.#cancelStrategyOrder(params);\n }\n\n // Resolve ownership before the first await. A reprice can change the child\n // ID while an ordinary cancel is in flight; cancelling through the stable\n // session handle stops the loop, joins any replacement, and removes the\n // current child instead of leaving a replacement chasing behind the user.\n const owningChase = [...this.#chaseSessions.entries()].find(\n ([, session]) =>\n session.orderId === params.orderId ||\n session.replacingOrderId === params.orderId,\n );\n try {\n if (owningChase) {\n this.#stopChaseSession(owningChase[0]);\n await this.#chaseTickQueue;\n const result = await this.#cancelChaseOrder({\n ...params,\n orderId: owningChase[0],\n orderType: 'chase',\n });\n return { ...result, orderId: params.orderId };\n }\n\n this.#deps.debugLogger.log('Canceling order:', params);\n\n // Hydrate the asset map before coin validation so a cold start (e.g.\n // service-worker restart with an empty prefetch map) can self-heal\n // without signature prompts on invalid cancels. Trading setup (builder\n // referral and unified-account setup runs only after validation passes,\n // matching placeOrder / editOrder. Cancel has no builder field.\n await this.#ensureReady();\n\n const coinValidation = validateCoinExists(\n params.symbol,\n this.#symbolToAssetId,\n );\n if (!coinValidation.isValid) {\n throw new Error(coinValidation.error);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\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 status: unknown = result.response?.data?.statuses?.[0];\n if (status === 'success') {\n return {\n success: true,\n orderId: params.orderId,\n };\n }\n\n // HyperLiquid usually rejects a cancel without throwing: the status entry\n // carries the raw exchange string (e.g. \"multi-sig required\"). Map it the\n // same way as a thrown rejection so callers get a standardized code\n // instead of a generic message.\n const rawError =\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : 'Order cancellation failed';\n\n return createErrorResult(await this.#mapStatusError(rawError, result), {\n success: false,\n orderId: params.orderId,\n });\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrder',\n {\n orderId: params.orderId,\n coin: params.symbol,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n return createErrorResult(mappedError, {\n success: false,\n orderId: params.orderId,\n });\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 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 const results: CancelOrdersResult['results'] = params.map((order) => ({\n orderId: order.orderId,\n symbol: order.symbol,\n success: false,\n error: PERPS_ERROR_CODES.BATCH_CANCEL_FAILED,\n }));\n\n // Resolve Chase ownership before the first await. A queued reprice may\n // replace the child ID, but the stable session handle still reaches it.\n const chaseSessions = [...this.#chaseSessions.entries()];\n const chaseRoutes = params.flatMap((order, index) => {\n const owner = chaseSessions.find(\n ([, session]) =>\n session.orderId === order.orderId ||\n session.replacingOrderId === order.orderId,\n );\n return owner ? [{ handle: owner[0], index, order }] : [];\n });\n const chaseIndexes = new Set(chaseRoutes.map(({ index }) => index));\n\n try {\n for (const handle of new Set(chaseRoutes.map((route) => route.handle))) {\n this.#stopChaseSession(handle);\n }\n if (chaseRoutes.length > 0) {\n await this.#chaseTickQueue;\n }\n for (const { handle, index, order } of chaseRoutes) {\n const result = await this.#cancelStrategyOrder({\n orderId: handle,\n symbol: order.symbol,\n orderType: 'chase',\n });\n results[index] = {\n orderId: order.orderId,\n symbol: order.symbol,\n success: result.success,\n ...(result.error === undefined ? {} : { error: result.error }),\n };\n }\n\n const ordinaryOrders = params.flatMap((order, index) =>\n chaseIndexes.has(index) ? [] : [{ index, order }],\n );\n if (ordinaryOrders.length > 0) {\n // Cancellation carries no builder context, so it must not prompt for a\n // fee approval that the action cannot use.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n const exchangeClient = this.#clientService.getExchangeClient();\n const cancelRequests = await Promise.all(\n ordinaryOrders.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 let statuses: unknown[] | undefined;\n let answer: unknown;\n try {\n const result = await exchangeClient.cancel({\n cancels: cancelRequests,\n });\n answer = result;\n const returnedStatuses = result.response?.data?.statuses ?? [];\n statuses =\n result.status === 'ok' &&\n returnedStatuses.length === ordinaryOrders.length\n ? returnedStatuses\n : undefined;\n } catch (error) {\n // The SDK throws when any entry failed, with every entry's status.\n answer = getVenueAnswer(error);\n statuses = getCancelStatusesFromError(error, ordinaryOrders.length);\n if (!statuses) {\n throw error;\n }\n }\n\n if (statuses) {\n // One signature covers the batch, so a signer failure is classified\n // (and reported to the host) once. Each entry keeps its own result.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n for (const [\n statusIndex,\n { index, order },\n ] of ordinaryOrders.entries()) {\n const status: unknown = statuses[statusIndex];\n const success = status === 'success';\n const statusError =\n isStatusObject(status) && typeof status.error === 'string'\n ? createStatusError(status.error, answer)\n : undefined;\n let error: string = PERPS_ERROR_CODES.BATCH_CANCEL_FAILED;\n if (statusError) {\n error =\n signerFailure && (await this.#isSignerFailure(statusError))\n ? signerFailure.message\n : this.#mapError(statusError).message;\n }\n results[index] = {\n orderId: order.orderId,\n symbol: order.symbol,\n success,\n ...(success ? {} : { error }),\n };\n }\n }\n }\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrders',\n {\n orderCount: params.length,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n for (const result of results) {\n if (\n !result.success &&\n result.error === PERPS_ERROR_CODES.BATCH_CANCEL_FAILED\n ) {\n result.error =\n error instanceof Error\n ? mappedError.message\n : PERPS_ERROR_CODES.BATCH_CANCEL_FAILED;\n }\n }\n }\n\n const successCount = results.filter(({ success }) => success).length;\n return {\n success: successCount > 0,\n successCount,\n failureCount: results.length - successCount,\n results,\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 const unavailableResults: ClosePositionsResult['results'] = [];\n\n try {\n // Batch preparation needs trading readiness but not builder approval yet.\n // The provider-owned market policy is resolved from the positions below.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // Selected symbols only need the DEXes they belong to. Loading every\n // market group would refuse a BTC close when an unrelated HIP-3 DEX\n // cannot be read. closeAll / empty symbols still need a complete\n // snapshot so a missed DEX cannot be reported as \"nothing to close\".\n // Per-DEX loads are independent: a requested xyz outage must not\n // abort a BTC close in the same symbols list.\n const requestedSymbols =\n params.closeAll === true ||\n params.symbols === undefined ||\n params.symbols.length === 0\n ? undefined\n : params.symbols;\n let positions: Position[];\n if (requestedSymbols === undefined) {\n positions = await this.#getPositionsForOperation();\n } else {\n const dexNames = [\n ...new Set(\n requestedSymbols.map((symbol) => parseAssetName(symbol).dex ?? ''),\n ),\n ];\n const settled = await Promise.allSettled(\n dexNames.map((dexName) => this.#getPositionsForOperation(dexName)),\n );\n positions = [];\n settled.forEach((outcome, index) => {\n if (outcome.status === 'fulfilled') {\n positions.push(...outcome.value);\n return;\n }\n const message =\n outcome.reason instanceof Error\n ? outcome.reason.message\n : String(outcome.reason);\n if (message !== PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE) {\n throw outcome.reason;\n }\n const failedDex = dexNames[index];\n for (const symbol of requestedSymbols) {\n if ((parseAssetName(symbol).dex ?? '') === failedDex) {\n unavailableResults.push({\n symbol,\n success: false,\n error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,\n });\n }\n }\n });\n }\n\n positionsToClose =\n requestedSymbols === undefined\n ? positions\n : positions.filter((pos) => requestedSymbols.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 if (unavailableResults.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: 0,\n results: [],\n };\n }\n return {\n success: false,\n successCount: 0,\n failureCount: unavailableResults.length,\n error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,\n results: unavailableResults,\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 // Freed-margin transfer for each submitted order, or null when that order\n // needs none. One entry per order rather than one per HIP-3 position: a\n // compacted list read with the response-status index credits the wrong\n // order in a mixed main-DEX/HIP-3 batch.\n const orderedHip3Transfers: ({\n sourceDex: string;\n freedMargin: number;\n } | null)[] = [];\n\n // Build orders array, plus the positions each order closes so response\n // statuses stay index-aligned when a position is skipped below\n const orders: SDKOrderParams[] = [];\n const feePolicyContexts: OrderParams[] = [];\n const orderedPositions: Position[] = [];\n // Positions no order could be built for. Reported as failures so a caller\n // cannot read \"closed everything\" from a result that left one open.\n const skippedResults: ClosePositionsResult['results'] = [];\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 // formatHyperLiquidSize() below rounds half-up, so floor onto the size\n // grid first: a reduce-only order rounded above the position is rejected\n // with \"Reduce only order would increase position\".\n const flooredCloseSize = floorToSizeDecimals(\n closeSize,\n assetInfo.szDecimals,\n );\n\n // A dust position worth less than one size increment floors to 0, which\n // would submit a zero-size order. Skip it rather than sending an order\n // the exchange must reject; the remaining positions still close, and the\n // skip is reported as a failure below.\n if (flooredCloseSize <= 0) {\n this.#deps.debugLogger.log(\n 'Skipping position smaller than one size increment',\n { coin: position.symbol, size: position.size },\n );\n skippedResults.push({\n symbol: position.symbol,\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE,\n });\n continue;\n }\n\n // Track this order's HIP-3 transfer, if it needs one (a full position\n // close frees all of its margin). Pushed below alongside the order so the\n // two stay index-aligned.\n const hip3Transfer =\n isHip3Position && dexName && !this.#useUnifiedAccount\n ? { sourceDex: dexName, freedMargin: totalMarginUsed }\n : null;\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 const formattedSize = formatHyperLiquidSize({\n size: flooredCloseSize,\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 feePolicyContexts.push({\n symbol: position.symbol,\n isBuy,\n size: formattedSize,\n orderType: 'market',\n reduceOnly: true,\n });\n orderedPositions.push(position);\n orderedHip3Transfers.push(hip3Transfer);\n }\n\n // Every position was smaller than one size increment. Return their\n // failures rather than an empty result, which would be indistinguishable\n // from \"no positions matched\".\n if (orders.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: skippedResults.length + unavailableResults.length,\n results: [...skippedResults, ...unavailableResults],\n };\n }\n\n // HyperLiquid accepts one builder context for the whole close batch.\n // Resolve every position context and charge the batch when any included\n // policy charges, preserving deterministic behavior for future policies\n // that vary by market or route.\n const chargesMetamaskBuilderFee = feePolicyContexts.some(\n (context) =>\n this.#resolveOrderFeePolicy(context).chargesMetamaskBuilderFee,\n );\n const builder = chargesMetamaskBuilderFee\n ? await this.#getBuilderOrderContext(\n await this.#ensureReadyForTrading({ requiresBuilderFee: true }),\n )\n : undefined;\n\n // Single batch API call\n const result = await exchangeClient.order({\n orders: this.#applySubscriptionCloid(orders),\n grouping: 'na',\n ...(builder && { builder }),\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 =\n statuses.length -\n successCount +\n skippedResults.length +\n unavailableResults.length;\n\n // Handle HIP-3 margin transfers for successful closes\n if (!this.#useUnifiedAccount) {\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 const transfer = orderedHip3Transfers[i];\n\n if (isSuccess && transfer) {\n const { sourceDex, freedMargin } = transfer;\n this.#deps.debugLogger.log(\n 'Position closed successfully, initiating manual auto-transfer back',\n { symbol: orderedPositions[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 // Index submitted and skipped outcomes by symbol so `results` can keep the\n // order of the requested positions: consumers may correlate them by index.\n const submittedResults = new Map(\n statuses.map((status, index) => [\n orderedPositions[index].symbol,\n {\n symbol: orderedPositions[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 );\n const skippedBySymbol = new Map(\n skippedResults.map((skipped) => [skipped.symbol, skipped]),\n );\n\n return {\n success: successCount > 0,\n successCount,\n failureCount,\n results: [\n ...positionsToClose.flatMap((position) => {\n const outcome =\n submittedResults.get(position.symbol) ??\n skippedBySymbol.get(position.symbol);\n return outcome ? [outcome] : [];\n }),\n ...unavailableResults,\n ],\n };\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'closePositions',\n {\n positionCount: positionsToClose.length,\n },\n );\n const safeError =\n signerFailure ??\n ensureError(error, 'HyperLiquidProvider.closePositions');\n if (!signerFailure) {\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext(\n 'closePositions',\n {\n positionCount: positionsToClose.length,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.ClosePosition,\n },\n ),\n );\n }\n // Return all selected positions as failed, including unavailable DEXes.\n return {\n success: false,\n successCount: 0,\n failureCount: positionsToClose.length + unavailableResults.length,\n error:\n error instanceof Error\n ? safeError.message\n : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,\n results: [\n ...positionsToClose.map((position) => ({\n symbol: position.symbol,\n success: false,\n error:\n error instanceof Error\n ? safeError.message\n : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,\n })),\n ...unavailableResults,\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 * Partial TP/SL: when `takeProfitSize` or `stopLossSize` is supplied, the\n * orders cannot use 'positionTpsl' (which always covers the whole position and\n * requires size 0). They are submitted as standalone reduce-only trigger orders\n * with 'na' grouping and explicit sizes instead.\n *\n * Note that the pre-cancel sweep clears every standalone reduce-only trigger\n * on the symbol — whether this update is partial or whole-position — not only\n * the ones this method placed. A trigger the caller placed independently\n * through `placeOrder` (for example a manual reduce-only stop) is therefore\n * cancelled too. Only TP/SL children of another pending order are protected.\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 * @param params.takeProfitSize - Partial TP size (undefined for the whole position)\n * @param params.stopLossSize - Partial SL size (undefined for the whole position)\n * @returns A promise that resolves to the result.\n */\n async updatePositionTPSL(\n params: UpdatePositionTPSLParams,\n ): Promise<OrderResult> {\n const expectedPosition =\n params.expectedPosition === undefined\n ? undefined\n : { ...params.expectedPosition };\n try {\n if (\n params.partialPairLinkage !== undefined &&\n (params.partialPairLinkage !== 'independent' ||\n !params.takeProfitPrice ||\n !params.stopLossPrice ||\n (params.takeProfitSize === undefined &&\n params.stopLossSize === undefined))\n ) {\n throw new Error(\n 'Hyperliquid partial pair linkage requires an independently sized TP/SL pair',\n );\n }\n\n const lifecycle = this.#lifecycleGeneration;\n const isTestnet = this.#clientService.isTestnetMode();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const assertScope = async (): Promise<void> => {\n const current = await this.#walletService.getUserAddressWithDefault();\n this.#assertProviderLifecycleCurrent(lifecycle, 'updatePositionTPSL');\n if (\n current.toLowerCase() !== userAddress.toLowerCase() ||\n this.#clientService.isTestnetMode() !== isTestnet\n ) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n };\n await assertScope();\n this.#deps.debugLogger.log('Updating position TP/SL:', params);\n\n const {\n symbol,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n position: livePosition,\n } = params;\n\n const isPartialTpsl =\n takeProfitSize !== undefined || stopLossSize !== undefined;\n\n // Basic initialization only. The trading setup that can prompt a hardware\n // wallet and write the referral / builder-fee approvals is deferred until\n // every validation below has passed, so a rejected update leaves nothing\n // behind.\n await this.#ensureReady();\n\n // A caller snapshot is only a hint. Use the current-connection DEX slice\n // when available, otherwise query that DEX over HTTP. If neither source\n // answers, fail closed: trusting the snapshot would recreate the stale\n // side/size reduce-only rejection this method is meant to prevent.\n const currentPositions = await this.#getPositionsForOperation(\n parseAssetName(symbol).dex ?? '',\n { revalidateMissingSymbol: symbol },\n );\n const position = currentPositions.find((pos) => pos.symbol === symbol);\n\n if (\n livePosition &&\n position &&\n parseFloat(position.size) !== parseFloat(livePosition.size)\n ) {\n this.#deps.debugLogger.log(\n 'Stale TP/SL position snapshot: using current position',\n {\n symbol,\n snapshotSize: livePosition.size,\n liveSize: position.size,\n },\n );\n }\n\n await assertScope();\n assertExpectedPosition(expectedPosition, position);\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\n }\n\n const positionSize = Math.abs(parseFloat(position.size));\n const isLong = parseFloat(position.size) > 0;\n\n // Partial TP/SL sizes must be positive, paired with their price, and no\n // larger than the position they close.\n const tpslSizeValidation = validateOrderParams({\n coin: symbol,\n size: positionSize.toString(),\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n });\n if (!tpslSizeValidation.isValid) {\n return {\n success: false,\n error: tpslSizeValidation.error,\n };\n }\n\n // Get clients for API calls (#ensureReady already called at method start).\n // Holding the exchange client reference is not itself a write; it is only\n // used below, after the trading setup has run.\n const infoClient = this.#clientService.getInfoClient();\n await assertScope();\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(symbol);\n\n // Asset info is resolved before the pre-cancel sweep so a partial size\n // that rounds away at the asset precision is rejected while the\n // position's existing triggers are still in place. Rejecting it after the\n // sweep would leave the position unprotected with nothing put back.\n const meta = await this.#getCachedMeta({ dexName });\n\n // Check if meta is an error response (string) or doesn't have universe property\n if (\n !meta ||\n typeof meta === 'string' ||\n !meta.universe ||\n !Array.isArray(meta.universe)\n ) {\n this.#deps.debugLogger.log(\n 'Failed to fetch metadata for asset mapping',\n {\n meta,\n dex: dexName ?? 'main',\n },\n );\n throw new Error(\n `Failed to fetch market metadata for DEX ${dexName ?? 'main'}`,\n );\n }\n\n // asset.name format: \"BTC\" for main DEX, \"xyz:XYZ100\" for HIP-3\n const assetInfo = meta.universe.find((asset) => asset.name === symbol);\n if (!assetInfo) {\n throw new Error(\n `Asset ${symbol} not found in ${dexName ?? 'main'} DEX universe`,\n );\n }\n\n const precision = validateOrderPrecision({\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals: assetInfo.szDecimals,\n });\n if (!precision.isValid) {\n return {\n success: false,\n error: precision.error,\n };\n }\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol,\n dexName,\n });\n\n // Keep whole-position trigger formatting fail-safe too. Venue positions\n // are normally grid-aligned, but flooring guarantees a reduce-only child\n // never exceeds the position if an upstream value is not.\n const fullSize =\n TP_SL_CONFIG.UsePositionBoundTpsl && !isPartialTpsl\n ? '0'\n : formatHyperLiquidSize({\n size: floorToSizeDecimals(positionSize, assetInfo.szDecimals),\n szDecimals: assetInfo.szDecimals,\n });\n\n // Partial TP/SL orders carry their own size; the rest cover the position.\n // A partial size that rounds away at the asset precision is rejected\n // rather than sent as '0', which the exchange reads as whole-position.\n const resolveTpslSize = (tpslSize?: string): string =>\n tpslSize === undefined\n ? fullSize\n : formatPartialTpslSize({\n size: parseFloat(tpslSize),\n szDecimals: assetInfo.szDecimals,\n });\n\n // HyperLiquid accepts one builder context for the whole TP/SL action.\n // Position TP/SL has no parent policy to inherit, so resolve every\n // included trigger and charge the batch when any child policy charges.\n const feePolicyContexts = [\n ...(takeProfitPrice\n ? [\n {\n symbol,\n isBuy: !isLong,\n size: resolveTpslSize(takeProfitSize),\n orderType: 'take_profit_limit',\n price: takeProfitPrice,\n triggerPrice: takeProfitPrice,\n reduceOnly: true,\n } satisfies OrderParams,\n ]\n : []),\n ...(stopLossPrice\n ? [\n {\n symbol,\n isBuy: !isLong,\n size: resolveTpslSize(stopLossSize),\n orderType: 'stop_market',\n triggerPrice: stopLossPrice,\n reduceOnly: true,\n } satisfies OrderParams,\n ]\n : []),\n ];\n const replacementChargesMetamaskBuilderFee = feePolicyContexts.some(\n (feePolicyContext) =>\n this.#resolveOrderFeePolicy(feePolicyContext)\n .chargesMetamaskBuilderFee,\n );\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 let cancelRequests: ExchangeCancelRequest[] = [];\n const restorablePositionTpslOrders: RestorableTpslOrder[] = [];\n const restorableStandaloneTpslOrders: RestorableTpslOrder[] = [];\n\n // Every replacement must cancel first so old and new reduce-only triggers\n // cannot execute together. Retain the exact trigger definitions so a\n // definitively failed replacement can restore confirmed cancellations.\n const captureRestorableTpslOrders = (tpslOrders: Order[]): void => {\n if (!takeProfitPrice && !stopLossPrice) {\n return;\n }\n\n tpslOrders.forEach((order) => {\n const orderId = Number(order.orderId);\n const orderType = order.triggerOrderType;\n const triggerPrice = order.triggerPrice ?? order.price;\n if (!Number.isSafeInteger(orderId) || !orderType || !triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n\n const size = order.isPositionTpsl ? '0' : order.remainingSize;\n const isBuy = order.side === 'buy';\n const feePolicyContext = {\n symbol,\n isBuy,\n size,\n orderType,\n triggerPrice,\n reduceOnly: true,\n ...(isLimitExecutionOrderType(orderType) && {\n price: order.price,\n }),\n } satisfies OrderParams;\n const restorableOrder = {\n orderId,\n order: {\n a: assetId,\n b: isBuy,\n p: order.price,\n s: size,\n r: true,\n t: {\n trigger: {\n isMarket: !isLimitExecutionOrderType(orderType),\n triggerPx: triggerPrice,\n tpsl: getTriggerDirection(orderType) === 'stop' ? 'sl' : 'tp',\n },\n },\n },\n chargesMetamaskBuilderFee:\n this.#resolveOrderFeePolicy(feePolicyContext)\n .chargesMetamaskBuilderFee,\n } satisfies RestorableTpslOrder;\n\n if (order.isPositionTpsl) {\n restorablePositionTpslOrders.push(restorableOrder);\n } else {\n restorableStandaloneTpslOrders.push(restorableOrder);\n }\n });\n };\n\n // Use atomic getter to prevent race condition between check and get\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n\n // Replacing TP/SL has to consider standalone ('na' grouping) triggers —\n // left by a partial update or placed independently — which are not\n // position-bound. Telling those apart from a pending order's normalTpsl\n // child requires the parent/child relationship, which only the REST\n // payload carries. The cache path is therefore only safe when the cache\n // shows no such trigger on this market: a partial update always places\n // standalone triggers, and a whole-position update must still clear any\n // standalone leftovers instead of letting them fire beside the new\n // position-bound orders.\n const cacheShowsStandaloneTriggers = Boolean(\n cachedOrders?.some(\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 );\n\n if (\n cachedOrders === null ||\n isPartialTpsl ||\n cacheShowsStandaloneTriggers\n ) {\n // Fallback: Query only the specific DEX (20 weight instead of 40+)\n this.#deps.debugLogger.log(\n cachedOrders === null\n ? 'WebSocket cache not initialized, falling back to single-DEX REST query'\n : 'TP/SL update needs parent/child order context: using single-DEX REST query',\n { dex: dexName ?? 'main', isPartialTpsl },\n );\n\n const openOrders = await infoClient.frontendOpenOrders({\n user: userAddress,\n dex: dexName ?? undefined,\n });\n\n // Orders that belong to a pending parent order (normalTpsl children) are\n // also listed at the top level, so collect their IDs to exclude them:\n // they protect that pending order, not this position.\n const childOrderIds = collectChildOrderIds(openOrders);\n\n // Filter using raw SDK response properties\n const tpslOrders = openOrders.filter(\n (order) =>\n order.coin === symbol &&\n order.reduceOnly &&\n // Position-bound TP/SL always qualifies, and so do standalone\n // triggers on this market (they belong to the position too, whether\n // this update is partial or whole) — but never another order's\n // TP/SL children.\n (order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) ||\n !childOrderIds.has(order.oid)) &&\n order.isTrigger &&\n (order.orderType.includes('Take Profit') ||\n order.orderType.includes('Stop')),\n );\n\n captureRestorableTpslOrders(\n tpslOrders.map((order) => adaptOrderFromSDK(order, position)),\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 captureRestorableTpslOrders(tpslOrders);\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: parseInt(order.orderId, 10),\n }));\n }\n\n // Build orders array for TP/SL\n const orders: SDKOrderParams[] = [];\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: resolveTpslSize(takeProfitSize),\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: resolveTpslSize(stopLossSize),\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 const generatedCloids = new Set<string>();\n for (const order of orders) {\n order.c = createUnmarkedProtectionCloid(generatedCloids);\n }\n const assertCurrentPosition = async (): Promise<void> => {\n await assertScope();\n if (expectedPosition) {\n const state = await infoClient.clearinghouseState({\n user: userAddress,\n ...(dexName ? { dex: dexName } : {}),\n });\n await assertScope();\n const current = state.assetPositions.find(\n (entry) => entry.position.coin === symbol,\n );\n assertExpectedPosition(\n expectedPosition,\n current\n ? {\n size: current.position.szi,\n entryPrice: current.position.entryPx ?? '',\n }\n : undefined,\n );\n }\n };\n await assertCurrentPosition();\n // These operation-local reads run inside the SDK signing semaphore.\n // The extra round trips deliberately serialize with the signed write,\n // preventing stale account-shape/position dispatch after wallet prompts.\n const assertWritableScope = async (): Promise<void> => {\n await assertScope();\n const isMultiSig = await this.#isHyperliquidMultiSigAccount(\n userAddress,\n infoClient,\n );\n await assertScope();\n if (isMultiSig) {\n throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);\n }\n };\n let cancelGuardFailure: unknown;\n const exchangeClient = this.#clientService.getExchangeClient(async () => {\n try {\n await assertWritableScope();\n await assertCurrentPosition();\n } catch (error) {\n cancelGuardFailure = error;\n throw error;\n }\n });\n const recoveryExchangeClient =\n this.#clientService.getExchangeClient(assertWritableScope);\n let replacementMayHaveDispatched = false;\n const replacementExchangeClient = this.#clientService.getExchangeClient(\n async () => {\n await assertWritableScope();\n await assertCurrentPosition();\n replacementMayHaveDispatched = true;\n },\n );\n\n const rollbackRequiresBuilderFee = [\n ...restorablePositionTpslOrders,\n ...restorableStandaloneTpslOrders,\n ].some((order) => order.chargesMetamaskBuilderFee);\n const requiresBuilderFee =\n replacementChargesMetamaskBuilderFee || rollbackRequiresBuilderFee;\n\n // Approval and builder-context resolution both finish before the\n // pre-cancel. A failure here therefore leaves the old protection intact.\n const builderFeeSetupContext = requiresBuilderFee\n ? await this.#ensureReadyForTrading({\n requiresBuilderFee: true,\n builderFeeApprovalFailureCode: PERPS_ERROR_CODES.TPSL_UPDATE_FAILED,\n })\n : await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n const builderOrderContext = builderFeeSetupContext\n ? await this.#getBuilderOrderContext(builderFeeSetupContext)\n : undefined;\n\n const sentOrders = this.#applySubscriptionCloid(orders, generatedCloids);\n if (\n new Set(sentOrders.map((order) => order.c)).size !== sentOrders.length\n ) {\n throw new Error('Duplicate final TP/SL client order identity');\n }\n\n const restoreCancelledProtection = async (\n cancelledOrderIds: Set<number>,\n ): Promise<TpslProtectionRestorationOutcome> => {\n const restoredOrderIds: string[] = [];\n let success = true;\n const protectionGroups: {\n grouping: 'positionTpsl' | 'na';\n entries: RestorableTpslOrder[];\n }[] = [\n {\n grouping: 'positionTpsl',\n entries: restorablePositionTpslOrders,\n },\n {\n grouping: 'na',\n entries: restorableStandaloneTpslOrders,\n },\n ];\n for (const protection of protectionGroups) {\n const entries = protection.entries.filter((entry) =>\n cancelledOrderIds.has(entry.orderId),\n );\n if (entries.length === 0) {\n continue;\n }\n\n const restorationOrders = entries.map((entry) => ({\n ...entry.order,\n c: createUnmarkedProtectionCloid(generatedCloids),\n }));\n const sentRestorationOrders = this.#applySubscriptionCloid(\n restorationOrders,\n new Set(restorationOrders.map((order) => order.c)),\n );\n let statuses: unknown[];\n let restorationFailure: Error | undefined;\n try {\n // Restore the exact pre-call reduce-only intent. Scope and account\n // shape are still probed after signing, but the requested new\n // protection's position precondition does not apply to rollback.\n await assertScope();\n const result = await recoveryExchangeClient.order({\n orders: sentRestorationOrders,\n grouping: protection.grouping,\n ...(entries.some((entry) => entry.chargesMetamaskBuilderFee) &&\n builderOrderContext && { builder: builderOrderContext }),\n });\n statuses = result.response?.data?.statuses ?? [];\n } catch (error) {\n const failure = await this.#classifyProtectionWriteError(error);\n restorationFailure = failure;\n statuses =\n this.#readProtectionErrorStatuses(error) ??\n (this.#isDefinitiveProtectionRejection(error)\n ? entries.map(() => ({ error: failure.message }))\n : []);\n this.#deps.debugLogger.log(\n 'Protection restoration requires reconciliation',\n { symbol, error: failure.message },\n );\n }\n await assertScope();\n const outcomes = await this.#reconcileTpslOrderPlacementOutcomes({\n outcomes: statuses\n .slice(0, entries.length)\n .map((status) => this.#readTpslOrderPlacementOutcome(status)),\n orders: sentRestorationOrders,\n userAddress,\n infoClient,\n assertScope,\n symbol,\n });\n await assertScope();\n restoredOrderIds.push(\n ...outcomes.flatMap((outcome) =>\n outcome.orderId ? [outcome.orderId] : [],\n ),\n );\n if (\n outcomes.some(\n (outcome) =>\n outcome.state === 'rejected' || outcome.state === 'unknown',\n )\n ) {\n success = false;\n const signerFailure =\n restorationFailure &&\n (await this.#isSignerFailure(restorationFailure));\n await assertScope();\n if (!signerFailure) {\n this.#deps.logger.error(\n restorationFailure ??\n new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST),\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol,\n stage: 'restoration',\n protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,\n childOrderIds: restoredOrderIds,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n }\n }\n }\n await assertScope();\n return { restoredOrderIds, success };\n };\n\n const createProtectionLostResult = (\n survivingOrderIds: string[],\n ): OrderResult =>\n createErrorResult(new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), {\n success: false,\n childOrderIds: [...new Set(survivingOrderIds)],\n });\n\n // Cancel before placing for both position-bound and standalone partial\n // triggers. A place-first partial update leaves both trigger sets live\n // during the cancellation round trip and can reduce more than requested.\n await assertCurrentPosition();\n const oldCancellation = await this.#cancelOrderRequestBatch(\n exchangeClient,\n cancelRequests,\n async (error) => {\n if (cancelGuardFailure !== undefined) {\n throw await this.#classifyProtectionWriteError(cancelGuardFailure);\n }\n if (isHyperLiquidMultiSigRequiredError(error)) {\n throw await this.#classifyProtectionWriteError(error);\n }\n },\n );\n // The signer could not sign the cancel. With nothing cancelled the old\n // protection is still in place, and a clear keeps only what it could\n // not cancel, so the caller retries. A replacement that cancelled part\n // of the old protection restores it below.\n if (\n oldCancellation.signerFailure &&\n (orders.length === 0 || oldCancellation.cancelledOrderIds.length === 0)\n ) {\n this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });\n return createErrorResult(oldCancellation.signerFailure, {\n success: false,\n });\n }\n\n await assertScope();\n\n // Clearing has no replacement batch to preserve. A partial cancellation\n // is reported so the caller can retry the same clear operation.\n if (orders.length === 0) {\n if (oldCancellation.remainingOrderIds.length > 0) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n this.#deps.debugLogger.log(\n 'No new TP/SL orders to place - existing ones cancelled',\n );\n return {\n success: true,\n childOrderIds: [],\n // No orderId since we only cancelled orders, didn't place new ones\n };\n }\n\n const confirmedCancelledOldOrderIds = new Set<number>();\n if (!oldCancellation.responseComplete) {\n const requestedOrderIds = new Set(\n cancelRequests.map((request) => request.o),\n );\n let possiblyLiveOrderIds = Array.from(requestedOrderIds, String);\n try {\n const liveOrders = await this.#fetchOpenOrders({ dexName });\n possiblyLiveOrderIds = liveOrders\n .filter((order) => requestedOrderIds.has(order.oid))\n .map((order) => String(order.oid));\n } catch (error) {\n this.#deps.debugLogger.log(\n 'Could not reconcile TP/SL protection after an incomplete cancel',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.updatePositionTPSL.reconcileProtection',\n ).message,\n },\n );\n }\n await assertScope();\n return createProtectionLostResult(possiblyLiveOrderIds);\n }\n oldCancellation.cancelledOrderIds.forEach((orderId) =>\n confirmedCancelledOldOrderIds.add(orderId),\n );\n if (oldCancellation.remainingOrderIds.length > 0) {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult([\n ...oldCancellation.remainingOrderIds.map(String),\n ...restoration.restoredOrderIds,\n ]);\n }\n const survivingOrderIds = [\n ...new Set([\n ...oldCancellation.remainingOrderIds.map(String),\n ...restoration.restoredOrderIds,\n ]),\n ];\n if (oldCancellation.signerFailure) {\n this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });\n return createErrorResult(oldCancellation.signerFailure, {\n success: false,\n childOrderIds: survivingOrderIds,\n });\n }\n const updateError = new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n this.#deps.logger.error(\n updateError,\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol: params.symbol,\n hasTakeProfit: params.takeProfitPrice !== undefined,\n hasStopLoss: params.stopLossPrice !== undefined,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n return createErrorResult(updateError, {\n success: false,\n childOrderIds: survivingOrderIds,\n });\n }\n\n let placementStatuses: unknown[];\n let placementFailure: Error | undefined;\n let responseAccepted = false;\n try {\n // Old protection may already be cancelled. A failed position read\n // belongs to recovery, which reports loss if safe restoration is\n // impossible instead of returning a pre-mutation refresh error.\n await assertCurrentPosition();\n const result = await replacementExchangeClient.order({\n orders: sentOrders,\n grouping: isPartialTpsl ? 'na' : 'positionTpsl',\n ...(replacementChargesMetamaskBuilderFee &&\n builderOrderContext && { builder: builderOrderContext }),\n });\n placementStatuses = result.response?.data?.statuses ?? [];\n responseAccepted = result.status === 'ok';\n } catch (error) {\n // Drop and report a rejected agent before restoration signs.\n placementFailure = await this.#classifyProtectionWriteError(error);\n await assertScope();\n const statuses = this.#readProtectionErrorStatuses(error);\n if (statuses !== undefined) {\n placementStatuses = statuses;\n } else if (\n replacementMayHaveDispatched &&\n !this.#isDefinitiveProtectionRejection(error)\n ) {\n // Arbitrary transport/HTTP failures do not prove non-processing.\n placementStatuses = [];\n } else {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult(restoration.restoredOrderIds);\n }\n return createErrorResult(placementFailure, {\n success: false,\n ...(restoration.restoredOrderIds.length > 0\n ? { childOrderIds: restoration.restoredOrderIds }\n : {}),\n });\n }\n }\n\n await assertScope();\n const initialPlacementOutcomes = placementStatuses\n .slice(0, orders.length)\n .map((status) => this.#readTpslOrderPlacementOutcome(status));\n const placementAccepted =\n responseAccepted &&\n placementStatuses.length === orders.length &&\n initialPlacementOutcomes.every(\n (outcome) =>\n outcome.state === 'resting' ||\n outcome.state === 'filled' ||\n outcome.state === 'waitingForTrigger',\n );\n\n if (placementAccepted) {\n // Only response-correlated IDs form a receipt. A waitingForTrigger\n // acknowledgement without an ID cannot be attributed from book changes.\n const childOrderIds: string[] = [];\n let identitiesValid = true;\n for (const [index, outcome] of initialPlacementOutcomes.entries()) {\n const cloid = sentOrders[index]?.c;\n let { orderId } = outcome;\n if (cloid === undefined) {\n identitiesValid = false;\n continue;\n }\n // One exact-ID lookup verifies immediate correlation. An unknown\n // index is uncertainty, not a reason to repeat the same read in a tight loop.\n await assertScope();\n try {\n const status = await infoClient.orderStatus({\n user: userAddress,\n oid: cloid,\n });\n await assertScope();\n if (status.status === 'order') {\n const row = status.order.order;\n if (\n row.coin !== symbol ||\n row.cloid?.toLowerCase() !== cloid.toLowerCase() ||\n !Number.isSafeInteger(row.oid) ||\n row.oid <= 0 ||\n (orderId !== undefined && orderId !== String(row.oid))\n ) {\n identitiesValid = false;\n } else {\n orderId = String(row.oid);\n }\n }\n } catch {\n // Read failure cannot invent an ID; stale scopes cannot return receipts.\n await assertScope();\n }\n if (orderId !== undefined) {\n childOrderIds.push(orderId);\n }\n }\n const completeReceipt =\n identitiesValid &&\n childOrderIds.length === orders.length &&\n childOrderIds.every((id) => Number(id) > 0) &&\n new Set(childOrderIds).size === childOrderIds.length;\n return {\n success: true,\n orderId: 'TP/SL orders placed',\n ...(completeReceipt ? { childOrderIds } : {}),\n };\n }\n\n const placementOutcomes = await this.#reconcileTpslOrderPlacementOutcomes(\n {\n outcomes: initialPlacementOutcomes,\n orders: sentOrders,\n userAddress,\n infoClient,\n assertScope,\n symbol,\n },\n );\n await assertScope();\n const restingReplacementOrderIds = placementOutcomes.flatMap((outcome) =>\n (outcome.state === 'resting' ||\n outcome.state === 'waitingForTrigger') &&\n outcome.orderId\n ? [outcome.orderId]\n : [],\n );\n const filledReplacementOrderIds = placementOutcomes.flatMap((outcome) =>\n outcome.state === 'filled' && outcome.orderId ? [outcome.orderId] : [],\n );\n const inFlightOrderIds = placementOutcomes.flatMap((outcome) =>\n outcome.state === 'unknown' && outcome.orderId ? [outcome.orderId] : [],\n );\n const hasUnresolvedWaitingTrigger = placementOutcomes.some(\n (outcome) =>\n (outcome.state === 'waitingForTrigger' ||\n outcome.state === 'unknown') &&\n outcome.orderId === undefined,\n );\n await assertScope();\n let cleanupFailure: Error | undefined;\n const remainingReplacementIds = await this.#cancelOrderRequests(\n recoveryExchangeClient,\n restingReplacementOrderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n })),\n async (error) => {\n if (\n isHyperLiquidMultiSigRequiredError(error) ||\n (error instanceof Error &&\n error.message === PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)\n ) {\n // Old protection has already changed. Classification must not\n // throw away this batch's still-live replacement identities.\n cleanupFailure = await this.#classifyProtectionWriteError(error);\n }\n },\n );\n await assertScope();\n const recoverableOrderIds = [\n ...filledReplacementOrderIds,\n ...inFlightOrderIds,\n ...remainingReplacementIds.map(String),\n ];\n if (cleanupFailure && recoverableOrderIds.length > 0) {\n this.#deps.logger.error(\n cleanupFailure,\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol,\n stage: 'cleanup',\n protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,\n childOrderIds: recoverableOrderIds,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n return createProtectionLostResult(recoverableOrderIds);\n }\n if (hasUnresolvedWaitingTrigger) {\n return createProtectionLostResult(recoverableOrderIds);\n }\n if (recoverableOrderIds.length === 0) {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult(restoration.restoredOrderIds);\n }\n return createErrorResult(\n placementFailure ?? new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED),\n {\n success: false,\n ...(restoration.restoredOrderIds.length > 0\n ? { childOrderIds: restoration.restoredOrderIds }\n : {}),\n },\n );\n }\n // A filled replacement may have changed or closed the position, while\n // an uncancelled replacement may still protect it. Restoring the old\n // whole-position triggers in either case risks stale or duplicate\n // protection, so return those IDs for caller reconciliation instead.\n if (!isPartialTpsl) {\n return createProtectionLostResult(recoverableOrderIds);\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED),\n {\n success: false,\n childOrderIds: recoverableOrderIds,\n },\n );\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'updatePositionTPSL',\n { symbol: params.symbol },\n );\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'),\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol: params.symbol,\n hasTakeProfit: params.takeProfitPrice !== undefined,\n hasStopLoss: params.stopLossPrice !== undefined,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\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 // The delegated placeOrder call resolves the builder-fee policy for the\n // concrete close order after validation.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // A caller snapshot is never authoritative for a reduce-only close. Use\n // the current DEX slice or its HTTP fallback, and fail closed if neither\n // answers. This keeps the size and side on one freshness contract across\n // snapshot and snapshot-less callers.\n const currentPositions = await this.#getPositionsForOperation(\n parseAssetName(params.symbol).dex ?? '',\n );\n const position = currentPositions.find(\n (pos) => pos.symbol === params.symbol,\n );\n\n if (\n params.position &&\n position &&\n parseFloat(position.size) !== parseFloat(params.position.size)\n ) {\n this.#deps.debugLogger.log(\n 'Stale close position snapshot: using current position',\n {\n coin: params.symbol,\n snapshotSize: params.position.size,\n liveSize: position.size,\n },\n );\n }\n\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\n }\n\n const positionSize = parseFloat(position.size);\n const isBuy = positionSize < 0;\n const absPositionSize = Math.abs(positionSize);\n // Only an omitted (or empty) size means \"close 100%\". A supplied size must\n // be a positive number: silently promoting '0' or 'abc' to a full close\n // would liquidate the whole position on a caller-side formatting slip.\n // A supplied size is clamped to the live position size, because\n // HyperLiquid rejects reduce-only orders that exceed the position and the\n // caller computed its size from a snapshot that may already be too large.\n const hasRequestedSize = params.size !== undefined && params.size !== '';\n let closeSizeNumber = absPositionSize;\n\n if (hasRequestedSize) {\n const requestedSize = parseFloat(params.size as string);\n\n if (!Number.isFinite(requestedSize) || requestedSize <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n closeSizeNumber = Math.min(requestedSize, absPositionSize);\n }\n\n const closeSize = closeSizeNumber.toString();\n\n // Capture position details BEFORE closing for freed margin calculation\n const totalMarginUsed = parseFloat(position.marginUsed);\n const totalPositionSize = absPositionSize;\n const closeSizeNum = closeSizeNumber;\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 USD/minimum validation if not provided. A full\n // close skips *that* validation because it submits the exact live size —\n // but not the price-staleness guard: calculateFinalPositionSize checks\n // priceAtCalculation against the live price for every close that supplies\n // it, using the price placeOrder fetches when none is passed here.\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 // True when the order closes 100% of the position: either no size was\n // provided, or the requested size covers (or was clamped to) the whole\n // position.\n const isFullClose = closeSizeNum >= absPositionSize;\n\n // Execute position close with consistent slippage handling\n const result = await this.placeOrder(\n {\n symbol: params.symbol,\n isBuy,\n size: closeSize,\n orderType: params.orderType ?? 'market',\n price: params.price,\n reduceOnly: true,\n isFullClose,\n // Pass through price and slippage parameters for consistent validation\n currentPrice,\n // A close of the whole position must submit exactly the live position\n // size. Forwarding usdAmount would make placeOrder recompute the size as\n // usdAmount / currentPrice — discarding the clamp above, since usdAmount\n // is the source of truth there — and submit more than the position\n // holds, which is rejected with \"Reduce only order would increase\n // position\". Genuine partial closes keep usdAmount so their size stays\n // USD-accurate.\n usdAmount: isFullClose ? undefined : params.usdAmount,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n },\n 0,\n false,\n );\n\n // Return freed margin using native abstraction or programmatic transfer\n if (\n result.success &&\n isHip3Position &&\n hip3Dex &&\n !this.#useUnifiedAccount\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.#useUnifiedAccount\n ) {\n this.#deps.debugLogger.log(\n 'Position closed - Unified Account 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 const safeError = ensureError(error, 'HyperLiquidProvider.closePosition');\n this.#deps.debugLogger.log('[closePosition] Close failed', {\n error: safeError.message,\n coin: params.symbol,\n orderType: params.orderType,\n });\n return createErrorResult(safeError, { 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 // Use the target DEX's current slice or one targeted HTTP read before\n // deriving the position side.\n const positions = await this.#getPositionsForOperation(\n parseAssetName(symbol).dex ?? '',\n );\n const position = positions.find((pos) => pos.symbol === symbol);\n\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\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 // Guard: confirm spendableBalance can cover margin addition.\n // spendableBalance is already mode-aware (includes free spot in Unified,\n // excludes it in Standard), so no extra spot fetch needed.\n if (amountFloat > 0) {\n const accountState = await this.getAccountState();\n const spendable = parseFloat(accountState.spendableBalance);\n\n if (spendable < amountFloat) {\n throw new Error(\n `Insufficient balance for margin addition: need ${amountFloat}, available ${spendable.toFixed(2)}`,\n );\n }\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 signerFailure = await this.#handleSignerFailure(\n error,\n 'updateMargin',\n {\n symbol: params.symbol,\n },\n );\n if (signerFailure) {\n return { success: false, error: signerFailure.message };\n }\n const safeError = ensureError(error, 'HyperLiquidProvider.updateMargin');\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext(\n 'updateMargin',\n {\n symbol: params.symbol,\n amount: params.amount,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.UpdateMargin,\n },\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 (unified state)\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\n }\n\n // Kill switch: HIP-3 disabled, return main DEX only\n if (!this.#hip3Enabled) {\n const state = this.#dexDiscoveryCache.update([null]);\n return state.validated;\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 // Do not cache — transient error, allow retry on next call\n return [null];\n }\n\n // Validate response\n if (!allDexs || !Array.isArray(allDexs)) {\n // Do not cache — may be transient, allow retry on next call\n return [null];\n }\n\n // Atomically update unified state (raw + validated + timestamp).\n // buildAssetMapping uses state.raw for perpDexIndex computation.\n const state = this.#dexDiscoveryCache.update(allDexs);\n return state.validated;\n }\n\n /**\n * Fetch a complete standalone user-data bundle.\n *\n * Each DEX clearinghouse response is shared by position and account-state\n * mapping. Any required request failure rejects the entire bundle.\n *\n * @param params - User and captured controller identity.\n * @returns The complete user-data snapshot.\n */\n async getUserDataSnapshot(\n params: GetUserDataSnapshotParams,\n ): Promise<PerpsUserDataSnapshot> {\n const { identity, userAddress } = params;\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const snapshotStartedAt = this.#deps.performance.now();\n const measure = async <Result>(\n stage: string,\n request: () => Promise<Result>,\n dex?: string | null,\n ): Promise<Result> => {\n const startedAt = this.#deps.performance.now();\n const dexDetail = dex === undefined ? {} : { dex: dex ?? 'main' };\n try {\n const result = await request();\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage,\n durationMs: Math.round(this.#deps.performance.now() - startedAt),\n success: true,\n ...dexDetail,\n });\n return result;\n } catch (error) {\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage,\n durationMs: Math.round(this.#deps.performance.now() - startedAt),\n success: false,\n ...dexDetail,\n });\n throw error;\n }\n };\n\n if (identity.provider !== 'hyperliquid' || identity.network !== network) {\n throw new Error('User data snapshot identity does not match provider');\n }\n\n const requestedDexes = identity.dexes;\n const canonicalDexes = canonicalizeHyperLiquidDexes(requestedDexes);\n const hasValidDexIdentity =\n requestedDexes.length > 0 &&\n new Set(requestedDexes).size === requestedDexes.length &&\n requestedDexes.every(\n (dex) => dex === 'main' || /^[a-z0-9][a-z0-9-]*$/u.test(dex),\n ) &&\n requestedDexes.length === canonicalDexes.length &&\n requestedDexes.every((dex, index) => dex === canonicalDexes[index]);\n if (!hasValidDexIdentity) {\n throw new Error('User data snapshot DEX identity is invalid');\n }\n const dexs = requestedDexes.map((dex) => (dex === 'main' ? null : dex));\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: network === 'testnet',\n });\n const buildUserParams = (\n dex: string | null,\n ): { user: string; dex?: string } => ({\n user: userAddress,\n ...(dex ? { dex } : {}),\n });\n\n const [clearinghouseStates, openOrdersByDex, spotState, abstractionMode] =\n await Promise.all([\n Promise.all(\n dexs.map((dex) =>\n measure(\n 'clearinghouse_state',\n () =>\n standaloneInfoClient.clearinghouseState(buildUserParams(dex)),\n dex,\n ),\n ),\n ),\n Promise.all(\n dexs.map((dex) =>\n measure(\n 'frontend_open_orders',\n () =>\n standaloneInfoClient.frontendOpenOrders(buildUserParams(dex)),\n dex,\n ),\n ),\n ),\n measure('spot_clearinghouse_state', () =>\n standaloneInfoClient.spotClearinghouseState({ user: userAddress }),\n ),\n measure('user_abstraction', () =>\n standaloneInfoClient.userAbstraction({ user: userAddress }),\n ),\n ]);\n\n const rawOrders = openOrdersByDex.flat();\n const childOrderIds = collectChildOrderIds(rawOrders);\n const ordersBySymbol = groupOrdersBySymbol(rawOrders);\n const positions = clearinghouseStates.flatMap((state) =>\n state.assetPositions\n .filter(({ position }) => position.szi !== '0')\n .map((assetPosition) => {\n const position = adaptPositionFromSDK(assetPosition);\n const {\n takeProfitOrders,\n stopLossOrders,\n takeProfitPrice,\n stopLossPrice,\n } = collectPositionTriggerOrders({\n orders: ordersBySymbol.get(position.symbol) ?? [],\n position,\n childOrderIds,\n });\n return {\n ...position,\n takeProfitCount: takeProfitOrders.length,\n stopLossCount: stopLossOrders.length,\n takeProfitOrders,\n stopLossOrders,\n ...(takeProfitPrice && { takeProfitPrice }),\n ...(stopLossPrice && { stopLossPrice }),\n };\n }),\n );\n const positionsBySymbol = new Map(\n positions.map((position) => [position.symbol, position]),\n );\n const orders = rawOrders.map((order) =>\n adaptOrderFromSDK(order, positionsBySymbol.get(order.coin)),\n );\n const dexAccountStates = clearinghouseStates.map((state) =>\n adaptAccountStateFromSDK(state),\n );\n const accountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n spotState,\n { foldIntoCollateral: hyperLiquidModeFoldsSpot(abstractionMode) },\n );\n\n accountState.subAccountBreakdown = Object.fromEntries(\n dexAccountStates.map((dexAccountState, index) => {\n return [\n dexs[index] ?? '',\n {\n spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\n totalBalance: dexAccountState.totalBalance,\n },\n ];\n }),\n );\n\n const snapshot = {\n positions,\n orders,\n accountState,\n identity: {\n ...identity,\n address: userAddress,\n },\n };\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage: 'complete',\n durationMs: Math.round(this.#deps.performance.now() - snapshotStartedAt),\n success: true,\n dexCount: dexs.length,\n });\n return snapshot;\n }\n\n /**\n * Read positions without mixing sources whose relative recency is unknown.\n *\n * A symbol-specific caller can use its current-connection DEX slice directly.\n * The current-epoch slice wins before any REST request because it is the\n * provider's live subscription source for that exact DEX. A caller may opt\n * into one targeted REST revalidation when a required symbol is absent, which\n * covers the post-fill window before the next WebSocket position update. If\n * the target DEX has not published, the caller uses REST instead of a stale\n * aggregate.\n *\n * A whole-list caller uses one shallow-copied WebSocket snapshot only when\n * every configured DEX is current. Otherwise it falls back to REST. No path\n * mixes sources of unknown relative recency. WebSocket positions include\n * TP/SL decoration; REST positions do not.\n *\n * @param targetDex - DEX for a single-symbol lookup, or undefined for a full\n * position list.\n * @param options - Optional lookup behavior for a symbol-specific operation.\n * @param options.revalidateMissingSymbol - Query the target DEX over REST when\n * its current WebSocket slice does not contain this symbol.\n * @returns Positions from one provenance-safe cache/REST path.\n */\n async #getPositionsForOperation(\n targetDex?: string,\n options: { revalidateMissingSymbol?: string } = {},\n ): Promise<Position[]> {\n if (targetDex !== undefined) {\n const targetPositions =\n this.#subscriptionService.getCachedPositionsForDex(targetDex);\n if (targetPositions === null) {\n this.#deps.debugLogger.log(\n 'Target DEX position cache unavailable: fetching REST positions',\n { dex: targetDex || 'main' },\n );\n } else {\n const { revalidateMissingSymbol } = options;\n const shouldRevalidate =\n revalidateMissingSymbol !== undefined &&\n targetPositions.find(\n (position) => position.symbol === revalidateMissingSymbol,\n ) === undefined;\n if (shouldRevalidate) {\n this.#deps.debugLogger.log(\n 'Target symbol missing from position cache: revalidating REST positions',\n {\n dex: targetDex || 'main',\n symbol: revalidateMissingSymbol,\n },\n );\n } else {\n return [...targetPositions];\n }\n }\n\n const { answered, positions } = await this.#queryDexPositions(\n targetDex || null,\n );\n if (!answered) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n return positions;\n }\n\n const cachedPositions =\n this.#subscriptionService.getFreshPositionsForAllDexs();\n if (cachedPositions !== null) {\n return cachedPositions;\n }\n\n this.#deps.debugLogger.log(\n 'Position caches incomplete: fetching full REST positions',\n );\n return this.#queryAllDexPositionsStrict();\n }\n\n /**\n * Query every enabled DEX over HTTP and reject a partial snapshot.\n *\n * A batch action cannot treat the successful subset as complete: doing so\n * could close one DEX and report success while another live position was\n * never checked.\n *\n * @returns A complete position list across all enabled DEXs.\n * @throws `PROVIDER_NOT_AVAILABLE` when any expected DEX fails.\n */\n async #queryAllDexPositionsStrict(): Promise<Position[]> {\n await this.#ensureClientsInitialized();\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const enabledDexs = await this.#getValidatedDexsStrict();\n\n const { results, failedDexs } = await this.#queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.clearinghouseState(userParam),\n enabledDexs,\n );\n\n if (failedDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Complete REST position snapshot unavailable',\n {\n failedDexs: failedDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n if (results.some(({ data }) => !Array.isArray(data.assetPositions))) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n return results.flatMap(({ data }) =>\n data.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos)),\n );\n }\n\n /**\n * Query one DEX's positions directly, preserving whether that DEX answered.\n *\n * `getPositions()` fans out across every enabled DEX, flattens the subset that\n * answered and converts any thrown error into an empty array, so its result\n * cannot distinguish \"this DEX answered and holds no positions\" from \"this\n * DEX's request failed or it was never queried\". Symbol operations need that\n * distinction: the first means the position is closed, while the second must\n * fail with `PROVIDER_NOT_AVAILABLE`.\n *\n * TP/SL enrichment is skipped because callers only read size, side, and margin.\n *\n * @param dexName - DEX identifier, or null for the main DEX.\n * @returns Whether the DEX answered, and the positions it reported.\n */\n async #queryDexPositions(\n dexName: string | null,\n ): Promise<{ answered: boolean; positions: Position[] }> {\n try {\n await this.#ensureClientsInitialized();\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const state = await infoClient.clearinghouseState(\n dexName ? { user: userAddress, dex: dexName } : { user: userAddress },\n );\n if (!Array.isArray(state.assetPositions)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n const positions = state.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos));\n\n this.#deps.debugLogger.log('Target DEX position query answered', {\n dex: dexName ?? 'main',\n count: positions.length,\n });\n\n return { answered: true, positions };\n } catch (error) {\n const safeError = ensureError(\n error,\n 'HyperLiquidProvider.queryDexPositions',\n );\n this.#deps.debugLogger.log('Target DEX position query failed', {\n dex: dexName ?? 'main',\n error: safeError.message,\n });\n\n return { answered: false, positions: [] };\n }\n }\n\n /**\n * Get current positions with TP/SL prices\n *\n * Note on TP/SL orders:\n * - normalTpsl: TP/SL tied to parent order, only placed after parent fills\n * - positionTpsl: TP/SL tied to position, placed immediately\n *\n * This means TP/SL prices may not appear immediately after placing an order\n * with TP/SL. They will only show up once the parent order is filled and\n * the child TP/SL orders are actually placed on the order book.\n *\n * @param params - 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 // TP/SL children of pending parent orders are listed at the top level too;\n // they belong to that order, not to a position.\n const allOrdersChildIds = collectChildOrderIds(allOrders);\n\n // Grouped once here rather than rescanned per position, mirroring the\n // positionsBySymbol map on the WebSocket path.\n const ordersBySymbol = groupOrdersBySymbol(allOrders);\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 // Trigger orders attached to this position: position-bound TP/SL plus\n // standalone ('na' grouping) partial TP/SL. A pending order's\n // normalTpsl children are excluded — they are also listed at the top\n // level, but they protect that order, not this position (same rule as\n // the positionOrders filter above).\n const { takeProfitOrders, stopLossOrders } =\n collectPositionTriggerOrders({\n orders: ordersBySymbol.get(position.symbol) ?? [],\n position,\n childOrderIds: allOrdersChildIds,\n });\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((childOrder) => {\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: resolvePositionTriggerSummaryPrice({\n triggerOrders: takeProfitOrders,\n scannedPrice: takeProfitPrice,\n }),\n stopLossPrice: resolvePositionTriggerSummaryPrice({\n triggerOrders: stopLossOrders,\n scannedPrice: stopLossPrice,\n }),\n takeProfitCount: takeProfitOrders.length,\n stopLossCount: stopLossOrders.length,\n takeProfitOrders,\n stopLossOrders,\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 * @param options - Optional cache-control modifiers for this read.\n * @returns A promise that resolves to the result.\n */\n async getOrderFills(\n params?: GetOrderFillsParams,\n options?: PerpsReadOptions,\n ): 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 // Routed through the client-service coalesce so the enrichment sidecar\n // rides the same cache as an explicit getOrders call, preventing a\n // second REST fire under rapid market switching.\n const historicalOrdersPromise = this.#clientService\n .fetchHistoricalOrders(userAddress, {\n forceRefresh: options?.forceRefresh,\n })\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 const fillId = buildHyperLiquidFillId(fill);\n acc.push({\n orderId: fill.oid?.toString() || '',\n // Two partial fills of one order can share oid, time, sz and px,\n // so the execution id is the only field that tells them apart\n // downstream. Omitted when a non-conforming payload lacks tid.\n ...(fillId === undefined ? {} : { fillId }),\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 * @param options - Optional cache-control modifiers for this read.\n * @returns A promise that resolves to the result.\n */\n async getOrders(\n params?: GetOrdersParams,\n options?: PerpsReadOptions,\n ): 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 userAddress = await this.#walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n const rawOrders = await this.#clientService.fetchHistoricalOrders(\n userAddress,\n { forceRefresh: options?.forceRefresh },\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\n // Statuses newer than the SDK types stay visible as queued.\n const normalizedStatus: Order['status'] = hasProperty(\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS,\n status,\n )\n ? HISTORICAL_ORDER_STATUS_BY_SDK_STATUS[status]\n : 'queued';\n\n const adaptedOrder = adaptOrderFromSDK(order, undefined);\n // limitPx is also populated as a slippage cap for market orders, so the\n // exchange's detailed type is the reliable execution-mode source.\n const historicalOrderType = hasProperty(\n HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE,\n order.orderType,\n )\n ? HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE[order.orderType]\n : 'market';\n\n return {\n ...adaptedOrder,\n orderType: historicalOrderType,\n remainingSize: parseFloat(order.sz).toString(),\n status: normalizedStatus,\n timestamp: statusTimestamp,\n lastUpdated: statusTimestamp,\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 * Rebuild Scale cancellation handles from the group identity persisted on\n * open venue orders.\n *\n * @param orders - Current normalized open orders.\n */\n #restoreScaleOrderGroups(orders: Order[]): void {\n const recovered = new Map<string, ScaleOrderGroup>();\n for (const order of orders) {\n if (!order.strategyGroupId) {\n continue;\n }\n const group = recovered.get(order.strategyGroupId) ?? {\n symbol: order.symbol,\n orderIds: [],\n clientOrderIds: [],\n };\n group.orderIds.push(order.orderId);\n recovered.set(order.strategyGroupId, group);\n }\n\n for (const [groupId, group] of recovered) {\n if (this.#cancelledScaleOrderGroups.has(groupId)) {\n continue;\n }\n const existingGroup = this.#scaleOrderGroups.get(groupId);\n if (!existingGroup) {\n this.#scaleOrderGroups.set(groupId, group);\n continue;\n }\n if (existingGroup.symbol === group.symbol) {\n existingGroup.orderIds = [\n ...new Set([...existingGroup.orderIds, ...group.orderIds]),\n ];\n } else {\n this.#deps.debugLogger.log(\n 'Scale group symbol mismatch during recovery',\n {\n groupId,\n existingSymbol: existingGroup.symbol,\n recoveredSymbol: group.symbol,\n },\n );\n }\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 this.#restoreScaleOrderGroups(cachedOrders);\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 this.#restoreScaleOrderGroups(orders);\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 * @param _options - Cache-control modifiers (unused — funding has no\n * provider-internal cache; coalescing happens at MarketDataService).\n * @returns A promise that resolves to the result.\n */\n async getFunding(\n params?: GetFundingParams,\n _options?: PerpsReadOptions,\n ): 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 * Resolve the provider's currently active CAIP account identifier.\n * Used by the MarketDataService REST coalesce layer so cached payloads\n * are keyed by the actual resolved address rather than a shared\n * \"default\" sentinel — prevents one account's data from being served\n * after an account switch within the coalesce TTL window.\n *\n * @returns CAIP account id for the currently selected HyperLiquid account.\n */\n async getCurrentAccountId(): Promise<CaipAccountId> {\n return this.#walletService.getCurrentAccountId();\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 [\n standaloneSpotStateResult,\n standalonePerpsResults,\n standaloneAbstractionResult,\n ] = await Promise.all([\n standaloneInfoClient\n .spotClearinghouseState({ user: userAddress })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log(\n 'Standalone spot state fetch failed — falling back to perps-only totals',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.getAccountState.standalone.spot',\n ).message,\n },\n );\n return null;\n }),\n queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n ),\n standaloneInfoClient\n .userAbstraction({ user: userAddress })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log(\n 'Standalone userAbstraction fetch failed; spot fold disabled until the mode resolves',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.getAccountState.standalone.abstraction',\n ).message,\n },\n );\n return null;\n }),\n ]);\n\n // Aggregate account states across all DEXs, then apply spot-backed\n // adjustments so streamed/standalone/full paths report the same totals.\n const dexAccountStates = standalonePerpsResults.map((perpsState) =>\n adaptAccountStateFromSDK(perpsState),\n );\n const aggregatedAccountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n standaloneSpotStateResult,\n {\n foldIntoCollateral: hyperLiquidModeFoldsSpot(\n standaloneAbstractionResult,\n ),\n },\n );\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, Perps states across DEXs, and the HL abstraction\n // mode (Unified / Standard / Portfolio / DEX-abstraction). Mode decides\n // whether spot USDC is perps collateral — see addSpotBalanceToAccountState.\n // One transient DEX failure should not blank the entire account state.\n const [spotStateResult, perpsStateResult, abstractionResult] =\n await Promise.allSettled([\n infoClient.spotClearinghouseState({ user: userAddress }),\n this.#queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n infoClient.userAbstraction({ user: userAddress }),\n ]);\n const spotState =\n spotStateResult.status === 'fulfilled' ? spotStateResult.value : null;\n const abstractionMode =\n abstractionResult.status === 'fulfilled'\n ? abstractionResult.value\n : null;\n if (abstractionResult.status === 'rejected') {\n this.#deps.debugLogger.log(\n 'User abstraction fetch failed; spot fold disabled until the mode resolves',\n {\n error: ensureError(\n abstractionResult.reason,\n 'HyperLiquidProvider.getAccountState.abstraction',\n ).message,\n },\n );\n }\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 spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\n marginUsed: dexAccountState.marginUsed,\n unrealizedPnl: dexAccountState.unrealizedPnl,\n },\n );\n return dexAccountState;\n });\n const aggregatedAccountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n spotState,\n { foldIntoCollateral: hyperLiquidModeFoldsSpot(abstractionMode) },\n );\n\n // Build per-sub-account breakdown (HIP-3 DEXs map to sub-accounts)\n const subAccountBreakdown: Record<\n string,\n {\n spendableBalance: string;\n withdrawableBalance: string;\n totalBalance: string;\n }\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 spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\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 lifecycleGeneration: number,\n ): Promise<DexFetchResult> {\n const dexParam = dex ?? '';\n let metaAndCtxs: [MetaResponse | null, PerpsAssetCtx[]] | null = null;\n try {\n metaAndCtxs = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\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 await this.#cacheDexMetadataFromRead({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\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 /**\n * Filter out successful HIP-3 DexFetchResults whose collateral token is\n * not USDC, so getMarketDataWithPrices enforces the same USDC-only policy\n * as market discovery (#fetchMarketsForDex) and order placement\n * (#handleHip3PreOrder) — otherwise a non-USDC HIP-3 market could appear\n * in overview data (and the cached stale snapshot derived from it) while\n * order placement rejects it (TAT-3304).\n *\n * Main-DEX results (dex === null) and already-failed results pass through\n * unchanged. #isUsdcCollateralDex fails closed, and on an unexpected\n * error checking it (e.g. a spotMeta fetch failure) this also fails\n * closed by dropping the DEX's result, rather than failing the whole\n * method and losing main-DEX overview data.\n *\n * @param results - The DEX fetch results to filter.\n * @returns A promise that resolves to the filtered results.\n */\n async #excludeNonUsdcCollateralResults(\n results: DexFetchResult[],\n ): Promise<DexFetchResult[]> {\n return Promise.all(\n results.map(async (result) => {\n if (result.dex === null || !result.success) {\n return result;\n }\n\n let isUsdcDex: boolean;\n try {\n isUsdcDex = await this.#isUsdcCollateralDex(result.dex);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Failed to check collateral type for HIP-3 DEX; excluding from market data',\n {\n dex: result.dex,\n error: ensureError(\n error,\n 'HyperLiquidProvider.excludeNonUsdcCollateralResults',\n ).message,\n },\n );\n isUsdcDex = false;\n }\n\n if (isUsdcDex) {\n return result;\n }\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Excluding non-USDC-collateral HIP-3 DEX from market data',\n { dex: result.dex },\n );\n\n return {\n ...result,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n };\n }),\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 filteredMarketsWithContexts = marketsFromDex\n .map((market, index) => ({\n market,\n assetCtx: result.assetCtxs[index],\n }))\n .filter(\n ({ market }) =>\n result.dex === null ||\n shouldIncludeMarket(\n market.name,\n result.dex,\n this.#hip3Enabled,\n this.#compiledAllowlistPatterns,\n this.#compiledBlocklistPatterns,\n ),\n );\n\n combinedUniverse.push(\n ...filteredMarketsWithContexts.map(({ market }) => market),\n );\n combinedAssetCtxs.push(\n ...filteredMarketsWithContexts.map(({ assetCtx }) => assetCtx),\n );\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 dexParam = dex ?? '';\n const cachedMeta = this.#cachedMetaByDex.get(dex);\n if (!cachedMeta) {\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Cache miss for ${dex ?? 'main'}, fetching`,\n );\n return this.#fetchSingleDexFresh(\n infoClient,\n dex,\n lifecycleGeneration,\n );\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(dexParam) ?? [];\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 await this.#cacheDexMetadataFromRead({\n dex,\n meta: freshMeta,\n assetCtxs,\n lifecycleGeneration,\n });\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 // TAT-3304: Exclude non-USDC-collateral HIP-3 DEXs before merging, so\n // getMarketDataWithPrices (and the stale snapshot #cacheFreshMarketDataSnapshot\n // derives from it) enforces the same USDC-only policy as market discovery\n // and order placement.\n const usdcFilteredDexDataResults =\n await this.#excludeNonUsdcCollateralResults(dexDataResults);\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 = usdcFilteredDexDataResults;\n\n this.#mergeDexResultsInto(\n usdcFilteredDexDataResults,\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) =>\n this.#fetchSingleDexFresh(infoClient, dex, lifecycleGeneration),\n ),\n );\n const usdcFilteredRetryResults =\n await this.#excludeNonUsdcCollateralResults(retryResults);\n\n this.#mergeDexResultsInto(\n usdcFilteredRetryResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n latestDexResults = usdcFilteredRetryResults;\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 // Keep this diagnostic bounded. Logging every price stalls React Native\n // DevTools and other CDP clients when thousands of spot keys are present.\n const allMidEntries = Object.entries(combinedAllMids);\n const hip3Entries = allMidEntries.filter(([key]) => key.includes(':'));\n this.#deps.debugLogger.log('Combined allMids price data:', {\n totalKeys: allMidEntries.length,\n hip3Keys: hip3Entries.length,\n keySample: allMidEntries.slice(0, 5).map(([key]) => key),\n hip3KeySample: hip3Entries.slice(0, 5).map(([key]) => key),\n samplePrices: Object.fromEntries(allMidEntries.slice(0, 5)),\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 HYPERLIQUID_ASSET_NAMES,\n );\n if (\n !this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Market data cache write',\n )\n ) {\n return transformedMarketData;\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 if (params.expectedScaleLadder !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE,\n };\n }\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 triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n tpslLinkage: params.tpslLinkage,\n grouping: params.grouping,\n timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n ...pickStrategyParams(params),\n });\n if (!basicValidation.isValid) {\n return basicValidation;\n }\n\n if (params.marginMode !== undefined) {\n if (params.marginMode !== 'cross' && params.marginMode !== 'isolated') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_INVALID,\n };\n }\n const { dex: dexName } = parseAssetName(params.symbol);\n const meta = await this.#getCachedMeta({ dexName });\n const assetInfo = meta.universe.find(\n (asset) => asset.name === params.symbol,\n );\n if (!assetInfo) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n await this.#validateMarginMode(params, assetInfo);\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-executing orders without currentPrice, use limit price as\n // fallback (plain limit, stop_limit, take_profit_limit)\n if (\n !priceForValidation &&\n params.price &&\n isLimitExecutionOrderType(params.orderType)\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 // Market-executing trigger orders (stop_market, take_profit_market)\n // have no limit price; the trigger price is the best notional estimate.\n if (\n !priceForValidation &&\n params.triggerPrice &&\n isTriggerOrderType(params.orderType)\n ) {\n priceForValidation = parseFloat(params.triggerPrice);\n this.#deps.debugLogger.log(\n 'Using trigger price for order validation (trigger order):',\n {\n size,\n triggerPrice: priceForValidation,\n orderType: params.orderType,\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 // A strategy placement's total clearing the per-order minimum does not\n // mean the orders it expands into will.\n const strategyMinimum = validateStrategyNotional({\n orderType: params.orderType,\n orderValueUSD,\n });\n if (!strategyMinimum.isValid) {\n return strategyMinimum;\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 await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });\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 withdrawableBalance = parseFloat(accountState.withdrawableBalance);\n this.#deps.debugLogger.log('HyperLiquidProvider: ACCOUNT BALANCE', {\n withdrawableBalance,\n spendableBalance: accountState.spendableBalance,\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 withdrawableBalance,\n sufficientBalance: withdrawAmount <= withdrawableBalance,\n });\n\n // Validate against withdrawableBalance — the mode-aware cap.\n // No spot sweep: withdrawableBalance already reflects what withdraw3\n // can pull. In Unified mode HL handles cross-wallet internally; in\n // Standard mode spot is not withdrawable via perps.\n const balanceValidation = validateBalance(\n withdrawAmount,\n withdrawableBalance,\n );\n if (!balanceValidation.isValid) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: INSUFFICIENT BALANCE',\n {\n error: balanceValidation.error,\n requestedAmount: withdrawAmount,\n withdrawableBalance,\n difference: withdrawAmount - withdrawableBalance,\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 signerFailure = await this.#handleSignerFailure(error, 'withdraw', {\n assetId: params.assetId,\n });\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\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(\n 'withdraw',\n {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n },\n {\n operation: PERPS_ERROR_OPERATION.FinancialOperations,\n action: PERPS_ERROR_ACTION.FinancialWithdrawal,\n },\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 signerFailure = await this.#handleSignerFailure(\n error,\n 'transferBetweenDexs',\n { sourceDex: params.sourceDex, destinationDex: params.destinationDex },\n );\n if (signerFailure) {\n return { success: false, error: signerFailure.message };\n }\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;\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;\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 * Stream TWAP lifecycle updates from the venue's own push channel.\n *\n * The venue streams schedule state without slice fills, so each pushed\n * schedule carries an empty `fills` array. A subscriber that renders fill\n * history should keep what a prior `getTwapOrders()` read supplied rather\n * than replacing it from the stream.\n *\n * @param params - Subscription parameters including callback and account ID.\n * @returns A cleanup function to unsubscribe from TWAP updates.\n */\n subscribeToTwapOrders(params: SubscribeTwapOrdersParams): () => void {\n return this.#subscriptionService.subscribeToTwapOrders({\n ...params,\n adapt: (history) => {\n const now = Date.now();\n const ordersById = new Map<string, TwapOrder>();\n for (const historyEntry of history) {\n const order = this.#adaptTwapOrder({\n historyEntry,\n sliceFills: [],\n now,\n });\n if (!order) {\n continue;\n }\n const existing = ordersById.get(order.orderId);\n if (!existing || supersedesCollapsedTwapOrder(order, existing)) {\n ordersById.set(order.orderId, order);\n }\n }\n const orders = [...ordersById.values()].sort(\n (left, right) => right.startedAt - left.startedAt,\n );\n\n // A streamed terminal schedule must reclaim HIP-3 collateral the same\n // way a polled read does, or a consumer that replaced polling with\n // this subscription strands manually transferred collateral. The\n // listener is synchronous, so this runs detached and logs its own\n // failures rather than rejecting into the stream.\n this.#rebalanceStreamedTerminalTwaps(orders, params.accountId);\n\n return orders;\n },\n });\n }\n\n /**\n * Reclaim HIP-3 collateral for terminal schedules seen on the TWAP stream.\n *\n * `getTwapOrders()` does this on every read; without the same call here a\n * consumer that replaced polling with the subscription would strand\n * manually transferred collateral. Detached on purpose: the stream listener\n * is synchronous and must not reject.\n *\n * @param orders - Schedules from the latest stream push.\n * @param accountId - Optional CAIP account ID the subscription is scoped to.\n */\n #rebalanceStreamedTerminalTwaps(\n orders: TwapOrder[],\n accountId?: CaipAccountId,\n ): void {\n if (orders.every((order) => order.status === 'active')) {\n return;\n }\n\n // Resolve the address from the push's own scope before detaching. Left\n // inside the microtask it would resolve at run time, so an account switch\n // racing a terminal push would key the reclaim to the newly selected\n // account and silently skip the schedule it was meant to settle.\n const userAddressPromise =\n this.#walletService.getUserAddressWithDefault(accountId);\n // Capture the network with the address, not after awaiting it: a network\n // toggle while resolution is pending would key the reclaim to the opposite\n // network and skip the terminal schedule.\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n\n (async (): Promise<void> => {\n const userAddress = await userAddressPromise;\n await this.#rebalanceTerminalHip3Twaps(orders, {\n network,\n userAddress,\n });\n })().catch((error) => {\n this.#deps.debugLogger.log('TWAP stream HIP-3 rebalance failed', {\n error: ensureError(error, 'HyperLiquidProvider.subscribeToTwapOrders')\n .message,\n });\n });\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 webData3 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 const disconnectResult = await this.disconnect();\n if (!disconnectResult.success) {\n // The network did not change. Keep the provider eligible for lazy\n // recovery instead of leaving this aborted toggle permanently sticky.\n this.#isDisconnected = false;\n throw new Error(\n disconnectResult.error ??\n 'Failed to disconnect before network toggle',\n );\n }\n\n // Update all services\n this.#clientService.setTestnetMode(newIsTestnet);\n // Invalidate reads that started after disconnect completed but before\n // the clients switched networks.\n this.#lifecycleGeneration += 1;\n this.#walletService.setTestnetMode(newIsTestnet);\n\n const initializeResult = await this.initialize();\n if (!initializeResult.success) {\n // The network switch is already committed. Leave the provider eligible\n // for lazy initialization so the next operation can retry the failed\n // client setup instead of remaining permanently disconnected.\n this.#isDisconnected = false;\n throw new Error(\n initializeResult.error ?? 'Failed to initialize after network toggle',\n );\n }\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 const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n // Ensure clients are initialized (lazy initialization)\n await this.#ensureClientsInitialized();\n if (\n this.#disconnectOperationsInFlight > 0 ||\n lifecycleGeneration !== this.#lifecycleGeneration\n ) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n this.#isDisconnected = false;\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 * Forget every agent resolved through `getAgentSigner`, so the next L1\n * action asks again; an answer still pending is discarded too.\n */\n clearAgentSigners(): void {\n this.#agentSignersGeneration += 1;\n this.#agentSigners.clear();\n }\n\n /**\n * Run the deferred account migration, builder fee and referral setup ahead\n * of the first order. Results are cached, so an already-ready account signs\n * nothing. A referral whose MetaMask code is not ready yet is checked again\n * by the next call rather than by orders.\n *\n * @returns The readiness result described on\n * `PerpsController.prepareTradingWallet`.\n */\n async prepareTradingWallet(): Promise<ReadyToTradeResult> {\n // Nothing can be signed, so run no setup (and log nothing) until it can.\n if (!this.#walletService.isMainAccountSignerReady()) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n try {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n // The result is only for the provider and account it started with.\n const assertPreparationCurrent = async (): Promise<void> => {\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Trading wallet preparation',\n );\n // A deselected account changed too.\n const currentAddress = await this.#walletService\n .getUserAddressWithDefault()\n .catch(() => undefined);\n if (currentAddress?.toLowerCase() !== userAddress.toLowerCase()) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n };\n await this.#ensureReadyForTrading({\n requiresBuilderFee: false,\n recheckPendingReferral: true,\n });\n const network = this.#clientService.isTestnetMode()\n ? 'testnet'\n : 'mainnet';\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n await assertPreparationCurrent();\n // The venue rejects every write from a wallet with no HyperLiquid account\n // yet, so it is not asked to sign a builder fee approval either.\n if (!isRegistered) {\n return {\n ready: false,\n error: this.#walletService.isMainAccountSignerReady()\n ? PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND\n : PERPS_ERROR_CODES.KEYRING_LOCKED,\n };\n }\n await this.#ensureBuilderFeeSetup(undefined, {\n reportSignerFailure: true,\n reportRefusal: true,\n });\n // The builder fee setup ends quietly when the provider disconnects.\n await assertPreparationCurrent();\n if (!this.#walletService.isMainAccountSignerReady()) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n const ready =\n this.#tradingSetupComplete &&\n !this.#unifiedAccountSetupNeedsRetry &&\n this.#builderFeeCheckCache.has(this.#getCacheKey(network, userAddress));\n return { ready };\n } catch (error) {\n // A step failed because the signer could not sign it (or locked while\n // it ran): retryable, not logged.\n if (\n isKeyringLockedError(error) ||\n !this.#walletService.isMainAccountSignerReady()\n ) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n const caughtError = ensureError(\n error,\n 'HyperLiquidProvider.prepareTradingWallet',\n );\n if (caughtError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] Provider replaced during preparation',\n );\n } else if (\n caughtError.message === PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED\n ) {\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] No account selected',\n );\n } else if (getBuilderFeeRefusal(caughtError)) {\n // Signing again cannot fix it, and orders are not blocked by it.\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] Builder fee approval refused',\n { error: caughtError.message },\n );\n } else {\n this.#deps.logger.error(\n caughtError,\n this.#getErrorContext('prepareTradingWallet'),\n );\n }\n return { ready: false, error: caughtError.message };\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 * Project the isolated position that would remain after a proposed order.\n *\n * Fetches the asset's margin table from cached meta so liquidation uses the\n * maintenance tier at the resulting liquidation notional. Cross-margin\n * positions return unsupported without a table lookup.\n *\n * @param params - Live position plus the proposed order.\n * @returns Discriminated preview; margin and liquidation are independently available.\n */\n async previewPositionModify(\n params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult> {\n if (params.position.leverage.type === 'cross') {\n return { status: 'unsupported', reason: 'cross_margin' };\n }\n\n const { dex: dexName } = parseAssetName(params.position.symbol);\n let marginTiers = null;\n\n try {\n const meta = await this.#getCachedMeta({ dexName });\n const assetInfo = meta.universe.find(\n (universeItem) => universeItem.name === params.position.symbol,\n );\n marginTiers = resolveHyperLiquidMarginTiers({\n marginTableId: assetInfo?.marginTableId,\n maxLeverage: assetInfo?.maxLeverage ?? params.position.maxLeverage,\n marginTables: meta.marginTables,\n });\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: margin table unavailable for position preview',\n {\n symbol: params.position.symbol,\n error,\n },\n );\n }\n\n return previewHyperLiquidIsolatedPositionModify({\n ...params,\n marginTiers,\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Maximum leverage cache write',\n )\n ) {\n this.#maxLeverageCache.set(asset, {\n value: assetInfo.maxLeverage,\n timestamp: now,\n });\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 lifecycleGeneration = this.#lifecycleGeneration;\n const { orderType, isMaker = false, amount, symbol } = params;\n const numericAmount =\n amount === undefined ? undefined : Number.parseFloat(amount);\n const parsedAmount =\n numericAmount === undefined ||\n (Number.isFinite(numericAmount) && numericAmount >= 0)\n ? numericAmount\n : 0;\n\n // Every placement is charged as its execution kind: a stop_market fills as a\n // market order (taker), a stop_limit as a limit order, a scale ladder as the\n // resting limit orders it fans out into, and a TWAP as the marketable\n // suborders it crosses the book with.\n const isMarketExecution = getTriggerExecution(orderType) === 'market';\n\n // A chase is post-only by construction, so it can only ever fill as a maker.\n // Quoting it at the taker rate would overstate the fee whatever the caller\n // passes for `isMaker`.\n const chargesMakerRate =\n orderType === 'chase' || (!isMarketExecution && isMaker);\n\n // Start with base rates from config\n let feeRate = chargesMakerRate ? FEE_RATES.maker : FEE_RATES.taker;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee cache read',\n );\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 // Same maker/taker decision as the base rates above, including the\n // post-only chase case — re-deriving it here would quote a chase at\n // the taker rate whenever the caller passed isMaker: false.\n let userFeeRate = chargesMakerRate\n ? cached.perpsMakerRate\n : cached.perpsTakerRate;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee fetch',\n );\n await this.#ensureClientsInitialized();\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee fetch',\n );\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 = parseBoundedNonNegativeDecimal(\n userFees.userCrossRate,\n MAX_API_FEE_RATE,\n );\n const baseUserMakerRate = parseBoundedNonNegativeDecimal(\n userFees.userAddRate,\n MAX_API_FEE_RATE,\n );\n const baseUserSpotTakerRate = parseBoundedNonNegativeDecimal(\n userFees.userSpotCrossRate,\n MAX_API_FEE_RATE,\n );\n const baseUserSpotMakerRate = parseBoundedNonNegativeDecimal(\n userFees.userSpotAddRate,\n MAX_API_FEE_RATE,\n );\n\n // Apply discounts manually since HyperLiquid API doesn't apply them\n const referralDiscount = parseBoundedNonNegativeDecimal(\n userFees.activeReferralDiscount || '0',\n MAX_API_FEE_DISCOUNT,\n );\n const stakingDiscount = parseBoundedNonNegativeDecimal(\n userFees.activeStakingDiscount?.discount || '0',\n MAX_API_FEE_DISCOUNT,\n );\n\n if (\n baseUserTakerRate === null ||\n baseUserMakerRate === null ||\n baseUserSpotTakerRate === null ||\n baseUserSpotMakerRate === null ||\n referralDiscount === null ||\n stakingDiscount === null\n ) {\n throw new Error('Invalid fee rates received from API');\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 !Number.isFinite(perpsTakerRate) ||\n !Number.isFinite(perpsMakerRate) ||\n !Number.isFinite(spotTakerRate) ||\n !Number.isFinite(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:\n Number.isFinite(perpsTakerRate) && perpsTakerRate >= 0,\n perpsMakerValid:\n Number.isFinite(perpsMakerRate) && perpsMakerRate >= 0,\n spotTakerValid:\n Number.isFinite(spotTakerRate) && spotTakerRate >= 0,\n spotMakerValid:\n Number.isFinite(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.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee cache write',\n );\n this.#userFeeCache.set(userAddress, rates);\n // Same maker/taker decision as the base rates above, chase included.\n let userFeeRate = chargesMakerRate\n ? rates.perpsMakerRate\n : rates.perpsTakerRate;\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 if (safeError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {\n throw safeError;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Fee calculation',\n );\n\n // Protocol base fee (HyperLiquid's fee)\n const protocolFeeRate = feeRate;\n const protocolFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * protocolFeeRate;\n\n // The provider policy, not the client, owns whether this placement can\n // carry a builder fee. The dedicated TWAP action has no builder field.\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const baseMetamaskFeeRate = chargesMetamaskBuilderFee\n ? BUILDER_FEE_CONFIG.MaxFeeDecimal\n : 0;\n const metamaskFeeDiscount =\n this.#userFeeDiscountBips === undefined\n ? 0\n : this.#userFeeDiscountBips / BASIS_POINTS_DIVISOR;\n const metamaskFeeRate = baseMetamaskFeeRate * (1 - metamaskFeeDiscount);\n\n if (chargesMetamaskBuilderFee && this.#userFeeDiscountBips !== undefined) {\n this.#deps.debugLogger.log('HyperLiquid: Applied MetaMask fee discount', {\n originalRate: baseMetamaskFeeRate,\n discountBips: this.#userFeeDiscountBips,\n discountPercentage: this.#userFeeDiscountBips / 100,\n adjustedRate: metamaskFeeRate,\n discountAmount: baseMetamaskFeeRate * metamaskFeeDiscount,\n });\n }\n\n const metamaskFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * metamaskFeeRate;\n\n // Total fees\n const totalFeeRate = protocolFeeRate + metamaskFeeRate;\n const totalFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * totalFeeRate;\n if (\n !Number.isFinite(protocolFeeRate) ||\n protocolFeeRate < 0 ||\n !Number.isFinite(metamaskFeeRate) ||\n metamaskFeeRate < 0 ||\n !Number.isFinite(totalFeeRate) ||\n totalFeeRate < 0 ||\n (protocolFeeAmount !== undefined &&\n !Number.isFinite(protocolFeeAmount)) ||\n (metamaskFeeAmount !== undefined &&\n !Number.isFinite(metamaskFeeAmount)) ||\n (totalFeeAmount !== undefined && !Number.isFinite(totalFeeAmount))\n ) {\n throw new Error('Invalid fee calculation result');\n }\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 chargesMetamaskBuilderFee,\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 * Escape hatch for agentic validation flows and test harnesses that drive\n * HL mutations directly. NOT part of the PerpsProvider interface.\n * Production code paths must go through the provider's own methods.\n *\n * @returns A promise resolving to the underlying HyperLiquid SDK\n * ExchangeClient. Promise shape matches the existing agentic flows\n * (hl-provision-fixture) that chain `.then` on the result.\n */\n public async getExchangeClient(): Promise<ExchangeClient> {\n // Initialized here so the client signs through this provider's wallet.\n await this.#ensureClientsInitialized();\n return this.#clientService.getExchangeClient();\n }\n\n /**\n * Disconnect provider\n *\n * @returns A promise that resolves to the result.\n */\n async disconnect(): Promise<DisconnectResult> {\n if (this.#disconnectOperationPromise) {\n return this.#disconnectOperationPromise;\n }\n\n const operation = this.#performDisconnect();\n this.#disconnectOperationPromise = operation;\n try {\n return await operation;\n } finally {\n if (this.#disconnectOperationPromise === operation) {\n this.#disconnectOperationPromise = null;\n }\n }\n }\n\n /**\n * Perform one provider teardown shared by every concurrent caller.\n *\n * @returns A promise that resolves to the result.\n */\n async #performDisconnect(): Promise<DisconnectResult> {\n this.#chasePlacementBlockers += 1;\n this.#strategyGeneration += 1;\n this.#disconnectOperationsInFlight += 1;\n this.#isDisconnected = true;\n this.#lifecycleGeneration += 1;\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 // Stop every chase loop: each holds a pending timer, and re-pricing after\n // a disconnect would sign orders against a client that is being torn down.\n // Orders already resting are deliberately left alone — disconnecting is\n // not a request to cancel the user's positions or orders.\n // Invalidate placements first, then drain every mutation before clearing\n // the registry and tearing down the clients they use.\n for (const [sessionId, session] of this.#chaseSessions.entries()) {\n if (session.active) {\n this.#stopChaseSession(sessionId);\n }\n }\n await Promise.all([...this.#chasePlacementWaiters]);\n await this.#chaseTickQueue;\n await Promise.allSettled([...this.#chaseTerminations.values()]);\n await Promise.all(\n [...this.#chaseSessions.values()].map(\n async (session) => await this.#rebalanceChaseSession(session),\n ),\n );\n this.#chaseSessions.clear();\n this.#chaseTerminations.clear();\n this.#terminatedChaseHandles.clear();\n this.#scaleOrderGroups.clear();\n this.#cancelledScaleOrderGroups.clear();\n\n // Clear session caches. Capability and fee reads use the lifecycle\n // generation above to discard any old response that resolves later.\n this.clearFeeCache();\n this.#referralCheckCache.clear();\n this.#builderFeeCheckCache.clear();\n this.#builderFeeRefusals.clear();\n this.#subscriptionBuilderApprovalEpoch += 1;\n this.#approvedBuilderAddresses.clear();\n this.#userFeeResolution = undefined;\n this.#userFeeDiscountBips = undefined;\n // UnifiedAccountCache stays global to avoid repeated signing requests.\n this.#cachedMetaByDex.clear();\n this.#pendingValidatedDexsPromise = null;\n this.#orderCapabilitiesMarketsByDex.clear();\n this.#orderCapabilitiesRefreshByDex.clear();\n this.#cachedSpotMeta = null;\n this.#dexDiscoveryCache.reset();\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 const pendingBuilderFeeSetups = [\n ...this.#builderFeeSetupPromises.values(),\n ];\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.#builderFeeSetupPromises.clear();\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 for (const pendingBuilderFeeSetup of pendingBuilderFeeSetups) {\n try {\n await pendingBuilderFeeSetup;\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 // Only after the pending setups above settled: a lookup that failed on\n // the transport while they were awaited must not carry its cooldown\n // into the next session.\n this.#unifiedAccountTransportRetryAt = 0;\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 } finally {\n this.#chasePlacementBlockers -= 1;\n this.#disconnectOperationsInFlight -= 1;\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 await this.#clientService.reconnect();\n // The socket was rebuilt: the unified-account setup can run again now.\n this.#unifiedAccountTransportRetryAt = 0;\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 /**\n * The dedicated subscription builder address for this network, if configured.\n *\n * @deprecated Only {@link approveSubscriptionBuilderFee} still reads this;\n * order construction no longer does. See that method for the removal plan.\n * @param isTestnet - Whether the provider is in testnet mode.\n * @returns The configured address, or undefined.\n */\n #getSubscriptionBuilderAddress(isTestnet: boolean): string | undefined {\n return isTestnet\n ? this.#subscriptionBuilderAddressTestnet\n : this.#subscriptionBuilderAddressMainnet;\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 this.#referralSetupNeedsRetry = false;\n this.#referralAwaitsBuilderCode = false;\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 // Skip the referral write for unfunded wallets — same proactive gate\n // as `#ensureUnifiedAccountEnabled`. `exchangeClient.setReferrer`\n // rejects with \"User or API Wallet 0x... does not exist.\" for wallets\n // that have not yet deposited.\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n if (!isRegistered) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Wallet not yet on Hyperliquid, deferring referral setup',\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 hardware wallet prompt spam)',\n { network, success: globalCached.success },\n );\n return;\n }\n\n // Wait while another provider attempts it. That attempt may end without\n // caching a result (its signer could not sign), so take the lock once it\n // is free and re-check the cache under it. The lock is checked and taken\n // with no await in between, so only one of several waiters gets it.\n let inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\n while (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\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 codeStatus = await this.#getReferralCodeStatus();\n if (codeStatus !== 'ready') {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Builder referral not ready, skipping',\n { network, codeStatus },\n );\n // Don't cache. A failed lookup (already logged) waits for the next\n // setup; a code that is not ready yet, for the next preparation.\n this.#referralAwaitsBuilderCode = codeStatus === 'pending';\n completeInFlight();\n return;\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 // The signer could not sign (a locked keyring, or an unavailable or\n // rejected agent; HyperLiquid keeps the cause in `cause`): leave the\n // cache empty and attempt the referral again at the next setup.\n if (await this.#classifySignerFailure(error)) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Signer unavailable, will retry later',\n );\n this.#referralSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net: wallet looked registered but the SDK still rejects with\n // \"User or API Wallet 0x... does not exist.\" Do not forward to Sentry.\n // The walletRegistered cache stores positive observations only, so no\n // demotion is needed; the next entry will re-probe.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Wallet not on Hyperliquid (race/stale-cache), deferring referral',\n { network, user: userAddress },\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 whether the builder's referral code can be used.\n *\n * @returns `ready`, `pending` while the builder's code is not ready yet, or\n * `failed` when the lookup failed or the code on file does not match (logged).\n */\n async #getReferralCodeStatus(): Promise<'ready' | 'pending' | 'failed'> {\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 'ready';\n }\n\n // Not ready yet - log as debugLogger since this is expected during setup phase\n this.#deps.debugLogger.log(\n '[getReferralCodeStatus] Referral code not ready',\n {\n stage,\n code,\n referrerAddr,\n },\n );\n return 'pending';\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.getReferralCodeStatus'),\n this.#getErrorContext('getReferralCodeStatus', {\n code: this.#getReferralCode(this.#clientService.isTestnetMode()),\n referrerAddress: this.#getBuilderAddress(\n this.#clientService.isTestnetMode(),\n ),\n }),\n );\n return 'failed';\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 // Benign for unfunded wallets — downgrade to debug log, do not Sentry.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[checkReferralSet] Wallet not on Hyperliquid yet, treating as no referral',\n {\n error: ensureError(error, 'HyperLiquidProvider.checkReferralSet')\n .message,\n },\n );\n return false;\n }\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 // Retryable (a locked keyring, an unavailable agent, or one the venue\n // rejected): `#ensureReferralSet` retries at the next entry, so it is\n // not an error to report.\n if (await this.#isSignerFailure(error)) {\n throw error;\n }\n // Benign for unfunded wallets — downgrade and rethrow so the outer\n // `#ensureReferralSet` catch self-heals the walletRegistered gate\n // without forwarding to Sentry.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[setReferralCode] Wallet not on Hyperliquid yet, skipping referral write',\n {\n error: ensureError(error, 'HyperLiquidProvider.setReferralCode')\n .message,\n },\n );\n throw error;\n }\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.js","sourceRoot":"","sources":["../../src/providers/HyperLiquidProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAO1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,qB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W,CAAC,KAAK,EAAE,qCAAqC,CAAC,EACzD,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,EAAE;gBACvC,IAAI,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;aACjE,CAAC,CACH,CAAC;YACF,2DAA2D;YAC3D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import { CaipAccountId, hasProperty, isHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport type {\n ExchangeClient,\n InfoClient,\n UserAbstractionResponse,\n} from '@nktkas/hyperliquid';\nimport { HyperliquidError } from '@nktkas/hyperliquid';\nimport { BigNumber } from 'bignumber.js';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport type { CandlePeriod } from '../constants/chartConfig.js';\nimport {\n PERPS_EVENT_PROPERTY,\n PERPS_EVENT_VALUE,\n} from '../constants/eventNames.js';\nimport {\n BASIS_POINTS_DIVISOR,\n BUILDER_FEE_CONFIG,\n canonicalizeHyperLiquidDexes,\n FEE_RATES,\n HYPERLIQUID_ORDER_CAPABILITIES,\n getBridgeInfo,\n getChainId,\n HIP3_ASSET_MARKET_TYPES,\n HIP3_FEE_CONFIG,\n HIP3_MARGIN_CONFIG,\n HYPERLIQUID_ASSET_NAMES,\n HYPERLIQUID_CONFIG,\n HYPERLIQUID_WITHDRAWAL_MINUTES,\n REFERRAL_CONFIG,\n TRADING_DEFAULTS,\n USDC_DECIMALS,\n USDC_SYMBOL,\n} from '../constants/hyperLiquidConfig.js';\nimport { DETAILED_ORDER_TYPES } from '../constants/orderTypes.js';\nimport {\n CHASE_ORDER_CONFIG,\n CHASE_ORDER_STATUS,\n HYPERLIQUID_TWAP_LIMITS,\n ORDER_SLIPPAGE_CONFIG,\n PERFORMANCE_CONFIG,\n PERPS_CONSTANTS,\n PROVIDER_CONFIG,\n SUBSCRIPTION_CLOID_CONFIG,\n TP_SL_CONFIG,\n WITHDRAWAL_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig.js';\nimport { PerpsControllerError } from '../errors.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { PerpsErrorCode } from '../perpsErrorCodes.js';\nimport {\n AgentSignerUnavailableError,\n getAgentAccountKey,\n isAgentSignerUnavailableError,\n} from '../services/agentSigner.js';\nimport { hasErrorInCauseChain } from '../services/causeChain.js';\nimport { DexDiscoveryCacheManager } from '../services/DexDiscoveryCacheManager.js';\nimport {\n HyperLiquidClientService,\n WebSocketConnectionState,\n} from '../services/HyperLiquidClientService.js';\nimport type { HyperLiquidWalletParams } from '../services/HyperLiquidClientService.js';\nimport { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService.js';\nimport { HyperLiquidWalletService } from '../services/HyperLiquidWalletService.js';\nimport {\n TradingReadinessCache,\n PerpsSigningCache,\n} from '../services/TradingReadinessCache.js';\nimport type {\n FrontendOrder,\n OrderType as HyperLiquidOrderType,\n OrderProcessingStatus,\n SDKOrderParams,\n MetaResponse,\n PerpsAssetCtx,\n SpotMetaResponse,\n} from '../types/hyperliquid-types.js';\nimport {\n HL_ABSTRACTION_WIRE,\n HL_UNIFIED_ACCOUNT_MODE,\n hyperLiquidModeFoldsSpot,\n} from '../types/hyperliquid-types.js';\nimport { PerpsAnalyticsEvent } from '../types/index.js';\nimport type {\n AccountState,\n AssetRoute,\n BatchCancelOrdersParams,\n CancelOrderParams,\n CancelOrderResult,\n CancelOrdersResult,\n ChaseOrder,\n ChaseOrderMaxDistanceReached,\n ChaseOrderStatus,\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 GetOrderCapabilitiesParams,\n GetMarginModeLockParams,\n GetScalePriceLadderParams,\n GetOrderFillsParams,\n GetOrdersParams,\n GetOrFetchFillsParams,\n GetPositionsParams,\n GetSupportedPathsParams,\n GetUserDataSnapshotParams,\n HistoricalPortfolioResult,\n HyperLiquidCredentials,\n InitializeResult,\n PerpsAgentAccount,\n PerpsAgentSigner,\n PerpsPlatformDependencies,\n PerpsProvider,\n PerpsProviderType,\n PerpsScalePriceLadder,\n LiquidationPriceParams,\n LiveDataConfig,\n MaintenanceMarginParams,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n MarginResult,\n MarketInfo,\n Order,\n OrderFill,\n OrderParams,\n OrderResult,\n ScaleOrderChild,\n PerpsMarketData,\n DirectProviderOrderCapabilities,\n DirectProviderScalePriceLadderUnavailableReason,\n Position,\n PositionTriggerOrder,\n ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribeTwapOrdersParams,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n TransferBetweenDexsParams,\n TransferBetweenDexsResult,\n TwapOrder,\n TwapOrderFill,\n TwapOrderStatus,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n RawLedgerUpdate,\n PerpsReadOptions,\n PerpsUserDataSnapshot,\n PerpsFeeResolution,\n MarginMode,\n MarginModeLockReason,\n PerpsMarginModeLock,\n} from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport type { OrderType, StrategyOrderType } from '../types/perps-types.js';\nimport type {\n ExtendedAssetMeta,\n ExtendedPerpDex,\n} from '../types/perps-types.js';\nimport {\n addSpotBalanceToAccountState,\n aggregateAccountStates,\n} from '../utils/accountUtils.js';\nimport { isValidCapabilitySymbol } from '../utils/capabilitySymbols.js';\nimport {\n PERPS_ERROR_ACTION,\n PERPS_ERROR_COMPONENT,\n PERPS_ERROR_OPERATION,\n createPerpsErrorContext,\n} from '../utils/errorContext.js';\nimport type {\n PerpsErrorTags,\n PerpsLoggerOptions,\n} from '../utils/errorContext.js';\nimport {\n ensureError,\n isHyperLiquidMultiSigRequiredError,\n isHyperLiquidUserNotFoundError,\n isKeyringLockedError,\n} from '../utils/errorUtils.js';\nimport { shouldDeferUnifiedAccountSetup } from '../utils/hyperLiquidAbstraction.js';\nimport {\n adaptAccountStateFromSDK,\n adaptHyperLiquidLedgerUpdateToUserHistoryItem,\n adaptMarketFromSDK,\n adaptOrderFromSDK,\n adaptPositionFromSDK,\n adaptPositionTriggerOrderFromSDK,\n adaptTpslLinkageToGrouping,\n buildAssetMapping,\n buildHyperLiquidFillId,\n formatHyperLiquidPrice,\n formatHyperLiquidSize,\n HYPERLIQUID_SCALE_CLOID_MARKER,\n parseAssetName,\n readScaleGroupId,\n} from '../utils/hyperLiquidAdapter.js';\nimport {\n previewHyperLiquidIsolatedPositionModify,\n resolveHyperLiquidMarginTiers,\n} from '../utils/hyperLiquidPositionPreview.js';\nimport {\n createErrorResult,\n getMaxOrderValue,\n getSupportedPaths,\n validateAssetSupport,\n validateBalance,\n validateCoinExists,\n validateDepositParams,\n validateOrderParams,\n validateWithdrawalParams,\n} from '../utils/hyperLiquidValidation.js';\nimport type { StrategyOrderValidationParams } from '../utils/hyperLiquidValidation.js';\nimport { generatePerpsId } from '../utils/idUtils.js';\nimport { transformMarketData } from '../utils/marketDataTransform.js';\nimport {\n compileMarketPattern,\n shouldIncludeMarket,\n} from '../utils/marketUtils.js';\nimport type { CompiledMarketPattern } from '../utils/marketUtils.js';\nimport {\n buildOrdersArray,\n calculateFinalPositionSize,\n calculateOrderPriceAndSize,\n computeChaseQuotePrice,\n computeScalePriceLadder,\n floorToSizeDecimals,\n formatPartialTpslSize,\n getPriceTick,\n splitScaleSizes,\n validateOrderPrecision,\n} from '../utils/orderCalculations.js';\nimport {\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isStrategyOrderType,\n isTriggerOrderType,\n resolvePositionTriggerSummaryPrice,\n toSDKTimeInForce,\n} from '../utils/orderTypes.js';\nimport { assertExpectedPosition } from '../utils/positionProtection.js';\nimport {\n createStandaloneInfoClient,\n queryStandaloneClearinghouseStates,\n queryStandaloneOpenOrders,\n} from '../utils/standaloneInfoClient.js';\nimport { parseBoundedNonNegativeDecimal } from '../utils/stringParseUtils.js';\nimport {\n markSubscriptionCloid,\n quantizeBuilderFeeTenthsBps,\n} from '../utils/subscriptionFeeWaiver.js';\n// getStreamManagerInstance removed: use this.#deps.streamManager instead\n\nconst HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE = {\n [DETAILED_ORDER_TYPES.LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.MARKET]: 'market',\n [DETAILED_ORDER_TYPES.STOP_LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.STOP_MARKET]: 'market',\n [DETAILED_ORDER_TYPES.TAKE_PROFIT_LIMIT]: 'limit',\n [DETAILED_ORDER_TYPES.TAKE_PROFIT_MARKET]: 'market',\n [DETAILED_ORDER_TYPES.TWAP_SLICE]: 'market',\n [DETAILED_ORDER_TYPES.VAULT_CLOSE]: 'market',\n [DETAILED_ORDER_TYPES.SPOT_DUST_CONVERSION]: 'market',\n} as const satisfies Record<HyperLiquidOrderType, Order['orderType']>;\n\nconst HISTORICAL_ORDER_STATUS_BY_SDK_STATUS = {\n open: 'open',\n filled: 'filled',\n triggered: 'triggered',\n canceled: 'canceled',\n marginCanceled: 'canceled',\n vaultWithdrawalCanceled: 'canceled',\n openInterestCapCanceled: 'canceled',\n selfTradeCanceled: 'canceled',\n reduceOnlyCanceled: 'canceled',\n siblingFilledCanceled: 'canceled',\n delistedCanceled: 'canceled',\n liquidatedCanceled: 'canceled',\n outcomeSettledCanceled: 'canceled',\n scheduledCancel: 'canceled',\n internalCancel: 'canceled',\n reduceOnlyRejected: 'canceled',\n rejected: 'rejected',\n tickRejected: 'rejected',\n minTradeNtlRejected: 'rejected',\n perpMarginRejected: 'rejected',\n badAloPxRejected: 'rejected',\n iocCancelRejected: 'rejected',\n badTriggerPxRejected: 'rejected',\n marketOrderNoLiquidityRejected: 'rejected',\n positionIncreaseAtOpenInterestCapRejected: 'rejected',\n positionFlipAtOpenInterestCapRejected: 'rejected',\n tooAggressiveAtOpenInterestCapRejected: 'rejected',\n openInterestIncreaseRejected: 'rejected',\n insufficientSpotBalanceRejected: 'rejected',\n oracleRejected: 'rejected',\n perpMaxPositionRejected: 'rejected',\n tooManyOpenOrdersRejected: 'rejected',\n} as const satisfies Record<OrderProcessingStatus, Order['status']>;\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/**\n * Allocate an unmarked protection identity without reusing this operation's IDs.\n *\n * @param allocated - IDs already allocated for replacement or restoration.\n * @returns A unique client ID with the subscription layout and no fee flag.\n */\nconst createUnmarkedProtectionCloid = (allocated: Set<string>): Hex => {\n const unmarkedFlags = 0;\n const flags = unmarkedFlags.toString(16).padStart(2, '0');\n const entropy = uuidv4()\n .replace(/-/gu, '')\n .slice(0, SUBSCRIPTION_CLOID_CONFIG.EntropyHexLength);\n const cloid: Hex = `0x${SUBSCRIPTION_CLOID_CONFIG.ProgramId}${flags}${entropy}`;\n if (allocated.has(cloid)) {\n throw new Error('Duplicate TP/SL client order identity');\n }\n allocated.add(cloid);\n return cloid;\n};\n\ntype ScaleBulkOrderResponse = {\n status: 'ok';\n response: {\n type: 'order';\n data: { statuses: unknown[] };\n };\n};\n\ntype ScaleBulkOrderStatus =\n | { kind: 'accepted'; state: 'resting'; orderId: string }\n | {\n kind: 'accepted';\n state: 'filled';\n orderId: string;\n averagePrice: string;\n filledSize: string;\n }\n | { kind: 'accepted'; state: 'waitingForFill' | 'waitingForTrigger' }\n | { kind: 'error'; error: string };\n\n/**\n * Parse every status the HyperLiquid bulk order API can return for a Scale\n * rung. Unknown or malformed statuses are not exchange rejections.\n *\n * @param status - One status from a bulk order response.\n * @returns The classified status, or undefined when it is malformed.\n */\nconst parseScaleBulkOrderStatus = (\n status: unknown,\n): ScaleBulkOrderStatus | undefined => {\n if (status === 'waitingForFill' || status === 'waitingForTrigger') {\n return { kind: 'accepted', state: status };\n }\n\n if (!isStatusObject(status) || Object.keys(status).length !== 1) {\n return undefined;\n }\n\n if (hasProperty(status, 'error')) {\n return typeof status.error === 'string'\n ? { kind: 'error', error: status.error }\n : undefined;\n }\n\n if (hasProperty(status, 'resting')) {\n const order = status.resting;\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0\n ) {\n return {\n kind: 'accepted',\n state: 'resting',\n orderId: order.oid.toString(),\n };\n }\n }\n\n if (hasProperty(status, 'filled')) {\n const order = status.filled;\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0 &&\n typeof order.avgPx === 'string' &&\n new BigNumber(order.avgPx).isFinite() &&\n new BigNumber(order.avgPx).gt(0) &&\n typeof order.totalSz === 'string' &&\n new BigNumber(order.totalSz).isFinite() &&\n new BigNumber(order.totalSz).gt(0)\n ) {\n return {\n kind: 'accepted',\n state: 'filled',\n orderId: order.oid.toString(),\n averagePrice: order.avgPx,\n filledSize: order.totalSz,\n };\n }\n }\n\n return undefined;\n};\n\n/**\n * Recover a structurally valid bulk order response that the pinned SDK wraps\n * in an `ApiRequestError`.\n *\n * @param error - The SDK error thrown by `ExchangeClient.order`.\n * @param expectedStatusCount - Number of Scale rungs submitted.\n * @returns The complete bulk order response, or undefined for any other error.\n */\nconst getScaleBulkOrderResponseFromError = (\n error: unknown,\n expectedStatusCount: number,\n): ScaleBulkOrderResponse | undefined => {\n if (\n !(error instanceof HyperliquidError) ||\n error.name !== 'ApiRequestError' ||\n !hasProperty(error, 'response')\n ) {\n return undefined;\n }\n\n const result = error.response;\n if (!isStatusObject(result) || result.status !== 'ok') {\n return undefined;\n }\n\n const { response } = result;\n if (!isStatusObject(response) || response.type !== 'order') {\n return undefined;\n }\n\n const { data } = response;\n if (!isStatusObject(data)) {\n return undefined;\n }\n\n const { statuses } = data;\n if (!Array.isArray(statuses) || statuses.length !== expectedStatusCount) {\n return undefined;\n }\n\n return result as ScaleBulkOrderResponse;\n};\n\n/**\n * Read a complete cancel response from an SDK `ApiRequestError`.\n *\n * The SDK throws when any cancel entry is an error, including the benign\n * already-gone response that confirms an order is no longer live.\n *\n * @param error - Error thrown by an exchange cancel method.\n * @param expectedStatusCount - Number of cancel requests submitted.\n * @returns The per-request statuses, or undefined for another error shape.\n */\nconst getCancelStatusesFromError = (\n error: unknown,\n expectedStatusCount: number,\n): unknown[] | undefined => {\n if (\n !(error instanceof HyperliquidError) ||\n error.name !== 'ApiRequestError' ||\n !hasProperty(error, 'response')\n ) {\n return undefined;\n }\n\n const result = error.response;\n if (!isStatusObject(result) || result.status !== 'ok') {\n return undefined;\n }\n const { response } = result;\n if (\n !isStatusObject(response) ||\n response.type !== 'cancel' ||\n !isStatusObject(response.data) ||\n !Array.isArray(response.data.statuses) ||\n response.data.statuses.length !== expectedStatusCount\n ) {\n return undefined;\n }\n\n return response.data.statuses;\n};\n\n// The address in HyperLiquid's \"User or API Wallet 0x... does not exist.\"\nconst UNKNOWN_WALLET_ADDRESS_PATTERN = /user or api wallet (0x[0-9a-f]{40})/iu;\n\n// The account in HyperLiquid's \"Must deposit before performing actions.\n// User: 0x...\", which names the main account, not the signer.\nconst MUST_DEPOSIT_USER_PATTERN =\n /must deposit before performing actions\\. user: (0x[0-9a-f]{40})/iu;\n\n// Builder fee approval refusals the venue repeats whoever signs, such as a\n// builder without funds: signing the approval again cannot help.\nconst BUILDER_FEE_REFUSALS = ['builder has insufficient balance'];\n\n// An agent's L1 signature: the account and network it signed for.\ntype AgentSignature = {\n key: string;\n account: PerpsAgentAccount;\n agentAddress: Hex;\n // The provider lifecycle generation of the wallet that made it.\n generation?: number;\n // Whether the venue still lists the agent, asked at most once per\n // signature (see #findRevokedAgent).\n approvalCheck?: Promise<boolean>;\n};\n\n// What a wallet adapter, and so the exchange client signing through it, was\n// created for: its network and provider lifecycle generation. It holds the\n// agent signatures it made that the venue has not answered yet, keyed by\n// getSignatureKey.\ntype WalletBinding = {\n isTestnet: boolean;\n generation: number;\n unansweredSignatures: Map<string, AgentSignature>;\n};\n\n/**\n * The venue answer an SDK error carries.\n *\n * @param error - The caught error.\n * @returns The answer, or undefined.\n */\nfunction getVenueAnswer(error: unknown): unknown {\n return isStatusObject(error) && hasProperty(error, 'response')\n ? error.response\n : undefined;\n}\n\n/**\n * A rejection the venue reported in a status entry, carrying the answer it\n * came in, like the error the SDK throws.\n *\n * @param message - The status entry's error.\n * @param answer - The venue answer with the entry.\n * @returns The error.\n */\nfunction createStatusError(message: string, answer: unknown): Error {\n return Object.assign(new Error(message), { response: answer });\n}\n\n/**\n * The key a signature is recognized by in an exchange request: its r value,\n * which the SDK sends as is.\n *\n * @param signature - The signature, or its r value.\n * @returns The key.\n */\nfunction getSignatureKey(signature: string): string {\n return signature.slice(0, 66).toLowerCase();\n}\n\n/**\n * The venue's refusal of a builder fee approval that signing again cannot\n * fix.\n *\n * @param error - The approval error.\n * @returns The venue's message, or undefined for another error.\n */\nfunction getBuilderFeeRefusal(error: unknown): string | undefined {\n const { message } = ensureError(error, 'HyperLiquidProvider.builderFee');\n const lower = message.toLowerCase();\n return BUILDER_FEE_REFUSALS.some((refusal) => lower.includes(refusal))\n ? message\n : undefined;\n}\n\n/**\n * Exchange messages that mean a cancel was refused because the order is not on\n * the book any more.\n *\n * HyperLiquid answers a cancel it cannot match with \"Order was never placed,\n * already canceled, or filled.\" That is a rejection of the request but a\n * confirmation of what the caller wanted — nothing of that order is resting.\n * Every other rejection (multi-sig, a stale nonce, a rate limit) leaves the\n * order exactly where it was, which is a materially different outcome.\n */\nconst ALREADY_GONE_CANCEL_MARKERS = [\n 'never placed',\n 'already canceled',\n 'already cancelled',\n 'order not found',\n 'twap not found',\n];\n\nconst RETRYABLE_CHASE_PLACEMENT_MARKERS = [\n 'post only order would have immediately matched',\n 'price too far from oracle',\n];\n\nconst CHASE_ORDER_STATUS_RETRY_COUNT = 2;\nconst CHASE_ORDER_STATUS_RETRY_DELAY_MS = 100;\nconst CHASE_ORDER_STATUS_UNAVAILABLE = 'status_unavailable';\n\nclass ChaseOrderStatusUnavailableError extends Error {\n constructor() {\n super('Chase order status unavailable');\n this.name = 'ChaseOrderStatusUnavailableError';\n }\n}\n\nconst isRetryableChasePlacementError = (error: unknown): boolean => {\n const message = ensureError(\n error,\n 'HyperLiquidProvider.startChaseSession',\n ).message.toLowerCase();\n return RETRYABLE_CHASE_PLACEMENT_MARKERS.some((marker) =>\n message.includes(marker),\n );\n};\n\n/**\n * What happened to one order a cancel was asked to remove.\n *\n * `Cancelled` and `Gone` both mean nothing of it is resting, which is all a\n * caller asked for; only `Refused` leaves an order behind.\n */\nconst enum CancelChildOutcome {\n Cancelled = 'cancelled',\n Gone = 'gone',\n Refused = 'refused',\n}\n\nconst enum HyperLiquidTwapLifecycleStatus {\n Activated = 'activated',\n Failed = 'error',\n Finished = 'finished',\n Stopped = 'stopped',\n Terminated = 'terminated',\n WaitingForTrigger = 'waitingForTrigger',\n}\n\nconst enum PerpsTwapLifecycleStatus {\n Active = 'active',\n Canceled = 'canceled',\n Completed = 'completed',\n CompletedUnderfilled = 'completed_underfilled',\n Failed = 'failed',\n}\n\ntype SdkHyperLiquidTwapHistoryEntry = Awaited<\n ReturnType<InfoClient['twapHistory']>\n>[number];\n\ntype HyperLiquidTwapNonFailureLifecycleStatus =\n | `${HyperLiquidTwapLifecycleStatus.Activated}`\n | `${HyperLiquidTwapLifecycleStatus.Finished}`\n | `${HyperLiquidTwapLifecycleStatus.Stopped}`\n | `${HyperLiquidTwapLifecycleStatus.Terminated}`\n | `${HyperLiquidTwapLifecycleStatus.WaitingForTrigger}`;\n\ntype HyperLiquidTwapFailureLifecycleStatus =\n `${HyperLiquidTwapLifecycleStatus.Failed}`;\n\ntype HyperLiquidTwapHistoryEntry = Omit<\n SdkHyperLiquidTwapHistoryEntry,\n 'status'\n> & {\n status:\n | {\n status: HyperLiquidTwapNonFailureLifecycleStatus;\n }\n | {\n status: HyperLiquidTwapFailureLifecycleStatus;\n description: string;\n };\n};\n\ntype HyperLiquidTwapSliceFillEntry = Awaited<\n ReturnType<InfoClient['userTwapSliceFills']>\n>[number];\n\ntype ExchangeCancelRequest = { a: number; o: number };\n\ntype ExchangeCancelByCloidRequest = { asset: number; cloid: Hex };\n\ntype CancelOrderBatchOutcome = {\n remainingOrderIds: number[];\n cancelledOrderIds: number[];\n responseComplete: boolean;\n // KEYRING_LOCKED when the signer could not sign the request. The venue\n // reports it per entry, so entries it did cancel still count as cancelled.\n signerFailure?: Error;\n};\n\ntype OrderPlacementOutcome = {\n orderId: string;\n state: 'resting' | 'filled';\n};\n\ntype TpslOrderPlacementOutcome = {\n orderId?: string;\n state: 'resting' | 'filled' | 'waitingForTrigger' | 'rejected' | 'unknown';\n};\n\ntype RestorableTpslOrder = {\n orderId: number;\n order: SDKOrderParams;\n chargesMetamaskBuilderFee: boolean;\n};\n\ntype TpslProtectionRestorationOutcome = {\n restoredOrderIds: string[];\n success: boolean;\n};\n\ntype BuilderFeeSetupContext = {\n network: 'testnet' | 'mainnet';\n userAddress: string;\n builderAddress: string;\n};\n\n/**\n * Classify one entry of a cancel response.\n *\n * @param status - A single status from the exchange's cancel response.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\nconst classifyCancelStatus = (status: unknown): CancelChildOutcome => {\n if (status === 'success') {\n return CancelChildOutcome.Cancelled;\n }\n\n const message = (\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : ''\n ).toLowerCase();\n\n return ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))\n ? CancelChildOutcome.Gone\n : CancelChildOutcome.Refused;\n};\n\n/**\n * Read the best price on one side of the book, discounting the chase's own\n * order.\n *\n * A chase rests one tick inside the spread, so its own order *is* the best\n * price on its side. Reading the raw book would therefore see the chase's own\n * quote every tick, conclude the touch has not moved, and never re-price —\n * masking exactly the adverse moves the strategy exists to follow. Levels this\n * provider occupies are netted down by what it holds there, and are skipped\n * entirely when nothing else is left on them.\n *\n * \"Own\" means *every* chase this provider is running on that side, not just the\n * one asking. Two chases on the same side each netting only themselves would\n * read the other as the external touch and improve on it, then improve on the\n * improvement — walking each other toward the opposite side of an unchanged\n * market.\n *\n * The sizes must be what the orders still have resting, not what they were\n * placed for: an order netted at its original size subtracts more than it\n * occupies, which can hide external liquidity sharing the level.\n *\n * @param levels - One side of the book, best-first.\n * @param ownByPrice - This provider's own resting size at each price.\n * @returns The best price other participants are showing, or null.\n */\nconst readBestExternalPrice = (\n levels: { px: string; sz: string }[] | undefined,\n ownByPrice: Map<string, number>,\n): number | null => {\n for (const level of levels ?? []) {\n const price = parseFloat(level.px);\n if (!Number.isFinite(price) || price <= 0) {\n continue;\n }\n\n const size = parseFloat(level.sz) - (ownByPrice.get(level.px) ?? 0);\n if (size > 0) {\n return price;\n }\n }\n\n return null;\n};\n\n/**\n * Narrow order params down to their strategy fields.\n *\n * Both validation entry points forward exactly this group, so a field added to\n * `StrategyOrderValidationParams` reaches both of them or neither.\n *\n * @param params - Order parameters.\n * @returns The strategy fields, as validation takes them.\n */\nconst pickStrategyParams = (\n params: OrderParams,\n): StrategyOrderValidationParams => ({\n twapDuration: params.twapDuration,\n twapRandomize: params.twapRandomize,\n scaleMinPrice: params.scaleMinPrice,\n scaleMaxPrice: params.scaleMaxPrice,\n scaleNumOrders: params.scaleNumOrders,\n scaleSkew: params.scaleSkew,\n chaseIntervalMs: params.chaseIntervalMs,\n chaseMaxDurationMs: params.chaseMaxDurationMs,\n chaseMaxRepricings: params.chaseMaxRepricings,\n chaseMaxDistanceBps: params.chaseMaxDistanceBps,\n});\n\n/**\n * Check a strategy placement's notional against the minimum the venue will\n * actually apply to it.\n *\n * The per-order minimum is charged against each order the venue receives, and a\n * strategy placement does not send one order:\n *\n * A `twap` is a single instruction the venue slices itself, so it is bounded by\n * the venue's own documented minimum for a TWAP rather than by the per-order\n * minimum that `validateOrder` has already applied.\n *\n * `scale` is deliberately absent. Its rungs are the orders the venue charges\n * the minimum against, and their sizes come from flooring onto the asset's size\n * grid with the remainder landing on the first rung — none of which is knowable\n * without `szDecimals`, which this check does not have. Every approximation\n * available here is unsound in one direction or the other, and the one that was\n * here rejected ladders whose submitted rungs all cleared the minimum.\n * `#buildScaleLadder` applies the exact per-rung check against the real grid\n * sizes, and it runs before anything is signed, so nothing is lost by leaving\n * the question to it.\n *\n * `chase` is absent too: it rests one order at a time, so the per-order minimum\n * the caller has already been checked against is the right bound.\n *\n * @param params - Notional parameters.\n * @param params.orderType - The order placement type.\n * @param params.orderValueUSD - Total notional of the placement, in USD.\n * @returns Validation result with isValid flag and optional error message.\n */\nconst validateStrategyNotional = (params: {\n orderType?: OrderType;\n orderValueUSD: number;\n}): { isValid: boolean; error?: string } => {\n const { orderType, orderValueUSD } = params;\n\n if (orderType === 'twap') {\n return orderValueUSD < HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd\n ? {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL,\n }\n : { isValid: true };\n }\n\n return { isValid: true };\n};\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: MetaResponse['universe'][number];\n currentPrice: number;\n meta: MetaResponse;\n};\n\ntype PrepareAssetForTradingParams = {\n symbol: string;\n assetId: number;\n leverage?: number;\n marginMode?: OrderParams['marginMode'];\n};\n\ntype Hip3TransferInfo = {\n amount: number;\n sourceDex: string;\n};\n\ntype Hip3TransferContext = {\n dexName: string;\n transferInfo: Hip3TransferInfo;\n};\n\ntype TwapOrderScope = {\n network: 'testnet' | 'mainnet';\n userAddress: string;\n orderId: string;\n};\n\ntype TwapAccountScope = Pick<TwapOrderScope, 'network' | 'userAddress'>;\n\ntype TrackedTwapOrder = {\n symbol: string;\n hip3Transfer?: Hip3TransferContext;\n rebalancePromise?: Promise<boolean>;\n};\n\ntype ChaseTerminalStatus =\n | typeof CHASE_ORDER_STATUS.Filled\n | typeof CHASE_ORDER_STATUS.Canceled\n | typeof CHASE_ORDER_STATUS.Failed;\n\ntype ChaseOrderRemainder = {\n remainingSize: string | null;\n terminalStatus: ChaseTerminalStatus | null;\n};\n\ntype ChaseTerminalResolution = {\n remainingSize: string | null;\n status: ChaseTerminalStatus;\n};\n\ntype ChaseRestingOrder = {\n orderId: string;\n price: string;\n size: string;\n};\n\ntype OrderCapabilitiesMarketCacheEntry = Readonly<{\n markets: MarketInfo[];\n freshAt: number;\n}>;\n\ntype AdaptTwapOrderParams = {\n historyEntry: HyperLiquidTwapHistoryEntry;\n sliceFills: HyperLiquidTwapSliceFillEntry[];\n now: number;\n};\n\ntype ChaseOrderMaxDistanceReachedHandler = (\n event: ChaseOrderMaxDistanceReached,\n) => void;\n\ntype HyperLiquidProviderOptions = {\n isTestnet?: boolean;\n hip3Enabled?: boolean;\n allowlistMarkets?: string[];\n blocklistMarkets?: string[];\n priceDeviationLimit?: number;\n useUnifiedAccount?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger: PerpsControllerMessengerBase;\n initialAssetMapping?: [string, number][];\n builderAddressTestnet?: string;\n builderAddressMainnet?: string;\n subscriptionBuilderAddressTestnet?: string;\n subscriptionBuilderAddressMainnet?: string;\n onChaseOrderMaxDistanceReached?: ChaseOrderMaxDistanceReachedHandler;\n getAgentSigner?: HyperLiquidCredentials['getAgentSigner'];\n // Told when the venue rejects a resolved agent (revoked or expired).\n onAgentRejected?: HyperLiquidCredentials['onAgentRejected'];\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: Hip3TransferInfo | null;\n};\n\ntype SubmitOrderWithRollbackParams = {\n orders: SDKOrderParams[];\n grouping: 'na' | 'normalTpsl' | 'positionTpsl';\n isHip3Order: boolean;\n dexName: string | null;\n transferInfo: Hip3TransferInfo | null;\n symbol: string;\n assetId: number;\n chargesMetamaskBuilderFee: boolean;\n builderFeeSetupContext?: BuilderFeeSetupContext;\n};\n\ntype BuilderOrderContext = { b: string; f: number };\n\ntype HandleOrderErrorParams = {\n error: unknown;\n symbol: string;\n orderType: OrderType;\n isBuy: boolean;\n reportFailure: boolean;\n};\n\ntype GetOrFetchPriceParams = {\n symbol: string;\n dexName: string | null;\n};\n\n/**\n * What every strategy placement needs before it can talk to the exchange.\n *\n * The single-order path derives the same values inline; strategy placements\n * share them through `#prepareStrategyPlacement` so the three of them cannot\n * drift apart on validation, readiness, or leverage.\n */\ntype StrategyPlacementContext = {\n assetId: number;\n szDecimals: number;\n formattedSize: string;\n builder?: BuilderOrderContext;\n dexName: string | null;\n network: 'testnet' | 'mainnet';\n transferInfo: Hip3TransferInfo | null;\n userAddress: string;\n /** The validated ladder a scale placement submits; absent for other types. */\n ladder?: ScaleLadder;\n};\n\n/**\n * A scale placement's rungs, exactly as they will be submitted.\n *\n * Built and checked before anything is signed, so the sizes and prices the\n * venue sees are the ones the minimums were applied to.\n */\ntype ScaleLadder = {\n prices: string[];\n sizes: string[];\n};\n\ntype ScaleOrderIdentity = {\n groupId: string;\n clientOrderIds: Hex[];\n};\n\n/**\n * A scale ladder's children, held so the group can be cancelled as one.\n *\n * The group can be rebuilt from open orders because each rung carries the\n * same recoverable group identity in its venue client-order ID.\n */\ntype ScaleOrderGroup = {\n symbol: string;\n orderIds: string[];\n clientOrderIds: Hex[];\n};\n\n/**\n * Create one recoverable identity for a Scale ladder and one venue CLOID per\n * rung. HyperLiquid requires every CLOID to be unique, so the last byte holds\n * the rung index while the preceding 15 bytes identify the shared group.\n *\n * The byte right after the Scale marker is reserved for the subscription flag\n * byte and is always zeroed here. Random entropy in that position would set the\n * `fee_reduction_applied` bit roughly half the time, so an unmarked ladder would\n * decode downstream as a waived one.\n *\n * @param count - Number of ladder rungs.\n * @returns The public group handle and venue client order IDs.\n */\nconst createScaleOrderIdentity = (count: number): ScaleOrderIdentity => {\n const groupKey = `${HYPERLIQUID_SCALE_CLOID_MARKER}00${uuidv4()\n .replace(/-/gu, '')\n .slice(0, 20)}`;\n const clientOrderIds = Array.from({ length: count }, (_, index) => {\n const clientOrderId: Hex = `0x${groupKey}${index\n .toString(16)\n .padStart(2, '0')}`;\n if (!isHexString(clientOrderId)) {\n throw new Error('Failed to create Scale client order ID');\n }\n return clientOrderId;\n });\n return { groupId: `scale:${groupKey}`, clientOrderIds };\n};\n\n/**\n * A running chase: the order currently resting, and the loop re-pricing it.\n */\ntype ChaseSession = {\n symbol: string;\n assetId: number;\n isBuy: boolean;\n szDecimals: number;\n reduceOnly: boolean;\n /** Exchange ID of the order resting right now, or null once it is gone. */\n orderId: string | null;\n /** Previous child ID while a replacement is between cancel and rest. */\n replacingOrderId: string | null;\n /**\n * Size the order resting right now was placed for.\n *\n * Shrinks as the chase re-prices: a child that partially filled before it was\n * cancelled leaves less to chase, and re-placing the original size would\n * execute more than the caller asked for.\n */\n size: string;\n originalSize: string;\n /**\n * Settles when an in-flight replacement has finished resting (or failed).\n * Null while no placement is in flight.\n *\n * `orderId` is null for the whole of that round trip, which is\n * indistinguishable from \"nothing rests\" unless a canceller can tell the two\n * apart — so a cancel joins this before deciding what to cancel.\n */\n pendingReplacement: Promise<void> | null;\n /** Price the resting order sits at. */\n restingPrice: string;\n arrivalPrice: string;\n startedAt: number;\n maxDistanceBps?: number;\n intervalMs: number;\n /** Last live remainder refresh used by client-facing snapshots. */\n lastSnapshotSizeRefreshAt: number;\n /**\n * Builder fee this chase was quoted at, in tenths of a basis point.\n *\n * Captured when the session starts because the rewards discount it reflects\n * is set around the caller's `placeOrder` and cleared as soon as that returns.\n * A chase returns immediately, so every replacement runs after the clear and\n * would otherwise be re-quoted at the undiscounted maximum.\n */\n builder?: BuilderOrderContext;\n /**\n * Whether this chase's orders carry the subscription cloid marking.\n *\n * Captured with {@link builder} and for the same reason: the fee resolution\n * that decides it is live only around the caller's `placeOrder`, and a chase\n * returns immediately, so every replacement runs after it is cleared. Without\n * this a replacement would pay the discounted fee the session captured while\n * shipping an unmarked cloid, and the fill could not be attributed.\n */\n marksSubscriptionCloid?: boolean;\n /** Manual HIP-3 collateral retained while this session has venue exposure. */\n hip3Transfer?: Hip3TransferContext;\n /** Coalesces concurrent terminal cleanup reads for this session. */\n hip3RebalancePromise?: Promise<boolean>;\n /** Remove a canceled session once deferred collateral cleanup succeeds. */\n removeAfterRebalance?: boolean;\n /** Absolute deadline, as a `Date.now()` stamp. */\n deadline: number;\n maxRepricings: number;\n repricings: number;\n /** Cleared when the session stops; null while no tick is pending. */\n timer: ReturnType<typeof setTimeout> | null;\n /** False once the chase has stopped re-pricing, whatever the reason. */\n active: boolean;\n status: ChaseOrderStatus;\n};\n\n/**\n * Collect the order IDs of every TP/SL child carried by a parent order.\n *\n * HyperLiquid lists `normalTpsl` children both nested under their parent and as\n * top-level entries in `frontendOpenOrders`. Those children protect the pending\n * parent order rather than the position, so callers use this set to exclude them.\n *\n * @param orders - Raw frontend open orders for the account.\n * @returns The set of child order IDs.\n */\nfunction collectChildOrderIds(orders: FrontendOrder[]): Set<number> {\n const childOrderIds = new Set<number>();\n\n orders.forEach((order) => {\n order.children?.forEach((child) => {\n childOrderIds.add(child.oid);\n });\n });\n\n return childOrderIds;\n}\n\n/**\n * Group orders by market, so a per-position pass does not rescan every order.\n *\n * @param orders - Raw frontend open orders across all DEXs.\n * @returns Orders keyed by market symbol.\n */\nfunction groupOrdersBySymbol(\n orders: FrontendOrder[],\n): Map<string, FrontendOrder[]> {\n const bySymbol = new Map<string, FrontendOrder[]>();\n\n orders.forEach((order) => {\n const existing = bySymbol.get(order.coin);\n if (existing) {\n existing.push(order);\n } else {\n bySymbol.set(order.coin, [order]);\n }\n });\n\n return bySymbol;\n}\n\n/**\n * Build the trigger-order view of a position: position-bound TP/SL plus\n * standalone (partial) reduce-only triggers on the same market, de-duplicated by\n * order ID and excluding children of pending parent orders.\n *\n * @param params - Collection parameters.\n * @param params.orders - Raw frontend open orders across all DEXs.\n * @param params.position - Position the triggers are attached to.\n * @param params.childOrderIds - Order IDs that belong to a pending parent order.\n * @returns The take profit and stop loss trigger orders for the position.\n */\nfunction collectPositionTriggerOrders(params: {\n orders: FrontendOrder[];\n position: Position;\n childOrderIds: Set<number>;\n}): {\n takeProfitOrders: PositionTriggerOrder[];\n stopLossOrders: PositionTriggerOrder[];\n takeProfitPrice?: string;\n stopLossPrice?: string;\n} {\n const { orders, position, childOrderIds } = params;\n\n const byOrderId = new Map<string, PositionTriggerOrder>();\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n\n orders.forEach((rawOrder) => {\n if (\n rawOrder.isTrigger &&\n rawOrder.reduceOnly &&\n rawOrder.isPositionTpsl === Boolean(TP_SL_CONFIG.UsePositionBoundTpsl)\n ) {\n if (rawOrder.orderType.includes('Take Profit')) {\n takeProfitPrice = rawOrder.triggerPx;\n } else if (rawOrder.orderType.includes('Stop')) {\n stopLossPrice = rawOrder.triggerPx;\n }\n }\n\n rawOrder.children?.forEach((childOrder) => {\n if (\n !childOrder.isTrigger ||\n !childOrder.reduceOnly ||\n childOrder.isPositionTpsl !== Boolean(TP_SL_CONFIG.UsePositionBoundTpsl)\n ) {\n return;\n }\n if (childOrder.orderType.includes('Take Profit')) {\n takeProfitPrice = childOrder.triggerPx;\n } else if (childOrder.orderType.includes('Stop')) {\n stopLossPrice = childOrder.triggerPx;\n }\n });\n\n if (\n rawOrder.coin !== position.symbol ||\n !rawOrder.isTrigger ||\n !rawOrder.reduceOnly ||\n childOrderIds.has(rawOrder.oid)\n ) {\n return;\n }\n\n const triggerOrder = adaptPositionTriggerOrderFromSDK({\n rawOrder,\n positionSize: position.size,\n entryPrice: position.entryPrice,\n });\n\n if (triggerOrder && !byOrderId.has(triggerOrder.orderId)) {\n byOrderId.set(triggerOrder.orderId, triggerOrder);\n }\n });\n\n const triggerOrders = Array.from(byOrderId.values());\n const takeProfitOrders = triggerOrders.filter(\n (order) => order.direction === 'take_profit',\n );\n const stopLossOrders = triggerOrders.filter(\n (order) => order.direction !== 'take_profit',\n );\n\n const takeProfitSummaryPrice = resolvePositionTriggerSummaryPrice({\n triggerOrders: takeProfitOrders,\n scannedPrice: takeProfitPrice,\n });\n const stopLossSummaryPrice = resolvePositionTriggerSummaryPrice({\n triggerOrders: stopLossOrders,\n scannedPrice: stopLossPrice,\n });\n\n return {\n takeProfitOrders,\n stopLossOrders,\n ...(takeProfitSummaryPrice && { takeProfitPrice: takeProfitSummaryPrice }),\n ...(stopLossSummaryPrice && { stopLossPrice: stopLossSummaryPrice }),\n };\n}\n\ntype HyperLiquidOrderFeeContext =\n | Readonly<OrderParams>\n | Readonly<FeeCalculationParams>;\n\ntype HyperLiquidOrderFeePolicy = Readonly<{\n chargesMetamaskBuilderFee: boolean;\n}>;\n\nconst MAX_API_FEE_RATE = 1;\nconst MAX_API_FEE_DISCOUNT = 1;\n\n/**\n * Fee applicability by canonical order type.\n *\n * The configuration type makes this map exhaustive, so a new order type cannot\n * inherit a builder-fee policy accidentally. HyperLiquid's dedicated TWAP\n * action has no builder field. Every other standalone placement uses an order\n * action that can carry one builder context. This policy is deliberately not a\n * constructor or order input. A future backend policy must be resolved inside\n * the provider from its trusted source rather than accepted from a client.\n */\nconst HYPERLIQUID_ORDER_FEE_CONFIG = {\n market: { chargesMetamaskBuilderFee: true },\n limit: { chargesMetamaskBuilderFee: true },\n stop_market: { chargesMetamaskBuilderFee: true },\n stop_limit: { chargesMetamaskBuilderFee: true },\n take_profit_market: { chargesMetamaskBuilderFee: true },\n take_profit_limit: { chargesMetamaskBuilderFee: true },\n twap: { chargesMetamaskBuilderFee: false },\n scale: { chargesMetamaskBuilderFee: true },\n chase: { chargesMetamaskBuilderFee: true },\n} satisfies Record<OrderType, HyperLiquidOrderFeePolicy>;\n\nconst MILLISECONDS_PER_MINUTE = 60_000;\nconst MILLISECONDS_PER_SECOND = 1_000;\n\n/**\n * How long #ensureReady waits before running the unified-account setup again\n * after its lookup failed on the WebSocket transport. A socket that exhausted\n * its reconnect budget rejects every request until reconnect() or reinit, so\n * retrying on every #ensureReady entry only repeats the same failure.\n */\nconst UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS = MILLISECONDS_PER_MINUTE;\n\n/**\n * Fixed messages the SDK gives a `WebSocketRequestError` raised on the client\n * side of the socket. Error frames the server sends back for a request carry\n * the server's own text instead.\n */\nconst WEBSOCKET_CLIENT_FAILURE_MESSAGES = [\n 'WebSocket connection permanently terminated',\n 'WebSocket connection closed',\n 'Request timed out after',\n 'Request aborted',\n 'Unknown error while making a WebSocket request',\n];\n\n/**\n * Whether the WebSocket transport, rather than the venue or the signer, failed\n * the request. The SDK raises `WebSocketRequestError` for client-side failures\n * (closed or terminated socket, timeout, abort), usually with the cause\n * attached, e.g. the `ReconnectingWebSocketError` (`RECONNECTION_LIMIT`,\n * `TERMINATED_BY_USER`) behind a terminated socket. It also uses\n * `WebSocketRequestError` for error frames the server sends back; those are\n * the venue's answer, have no cause and keep the server's text, so they are\n * not transport errors. The fixed messages cover client-side failures that\n * have no cause, including on engines that ignore `Error` `cause`.\n * `HyperLiquidSubscriptionService` keeps its own check for the same SDK errors\n * on the subscription paths.\n *\n * @param error - The caught error.\n * @returns True when the error, or one in its cause chain, is a WebSocket\n * transport error.\n */\nconst isWebSocketTransportError = (error: unknown): boolean =>\n hasErrorInCauseChain(\n error,\n (current) =>\n current.name === 'ReconnectingWebSocketError' ||\n (current.name === 'WebSocketRequestError' &&\n (current.cause !== undefined ||\n WEBSOCKET_CLIENT_FAILURE_MESSAGES.some((message) =>\n current.message.startsWith(message),\n ))),\n );\n\n/**\n * Normalize the TWAP history timestamp documented in seconds while tolerating\n * an already-millisecond value from a future SDK response.\n *\n * @param timestamp - Venue timestamp in seconds or milliseconds.\n * @returns Timestamp in milliseconds.\n */\nconst normalizeTwapHistoryTimestamp = (timestamp: number): number =>\n timestamp < 1_000_000_000_000\n ? timestamp * MILLISECONDS_PER_SECOND\n : timestamp;\n\nconst getTwapOrderScopeKey = (params: TwapOrderScope): string =>\n `${params.network}:${params.userAddress.toLowerCase()}:${params.orderId}`;\n\nconst resolveTwapOrderStatus = (\n historyEntry: HyperLiquidTwapHistoryEntry,\n executedSize: BigNumber,\n totalSize: BigNumber,\n): TwapOrderStatus => {\n switch (historyEntry.status.status) {\n case HyperLiquidTwapLifecycleStatus.Activated:\n case HyperLiquidTwapLifecycleStatus.WaitingForTrigger:\n return PerpsTwapLifecycleStatus.Active;\n case HyperLiquidTwapLifecycleStatus.Finished:\n return executedSize.isLessThan(totalSize)\n ? PerpsTwapLifecycleStatus.CompletedUnderfilled\n : PerpsTwapLifecycleStatus.Completed;\n case HyperLiquidTwapLifecycleStatus.Terminated:\n case HyperLiquidTwapLifecycleStatus.Stopped:\n return PerpsTwapLifecycleStatus.Canceled;\n case HyperLiquidTwapLifecycleStatus.Failed:\n return PerpsTwapLifecycleStatus.Failed;\n default:\n // A new venue status is not proof that a schedule stopped. Keep it\n // non-terminal so collateral cannot be reclaimed from a live TWAP.\n return PerpsTwapLifecycleStatus.Active;\n }\n};\n\n/**\n * Decide whether a newly adapted schedule replaces the one already collapsed\n * under the same order id.\n *\n * The venue reports one lifecycle as several history entries — an activation\n * plus a terminal record — and `lastUpdated` folds in slice fills that every\n * entry sharing a `twapId` receives. A schedule whose final fill completed it\n * therefore derives the same `lastUpdated` on both entries, because that fill\n * outranks each entry's own whole-second timestamp. Ordering on `lastUpdated`\n * alone admits that tie, letting the activation overwrite the terminal record\n * so the schedule reads as live long after it ended. Terminality decides\n * first, and an equal `lastUpdated` keeps the entry already collapsed.\n *\n * @param candidate - Schedule adapted from the current history entry.\n * @param existing - Schedule already collapsed under this order id.\n * @returns True when the candidate replaces the existing schedule.\n */\nconst supersedesCollapsedTwapOrder = (\n candidate: TwapOrder,\n existing: TwapOrder,\n): boolean => {\n const candidateIsTerminal =\n candidate.status !== PerpsTwapLifecycleStatus.Active;\n const existingIsTerminal =\n existing.status !== PerpsTwapLifecycleStatus.Active;\n if (candidateIsTerminal !== existingIsTerminal) {\n return candidateIsTerminal;\n }\n return candidate.lastUpdated > existing.lastUpdated;\n};\n\nconst adaptTwapOrderFill = (\n entry: HyperLiquidTwapSliceFillEntry,\n): TwapOrderFill => ({\n fillId: entry.fill.tid.toString(),\n orderId: entry.fill.oid.toString(),\n side: entry.fill.side === 'B' ? 'buy' : 'sell',\n price: entry.fill.px,\n size: entry.fill.sz,\n fee: entry.fill.fee,\n feeToken: entry.fill.feeToken,\n ...(entry.fill.builderFee === undefined\n ? {}\n : { builderFee: entry.fill.builderFee }),\n timestamp: entry.fill.time,\n transactionHash: entry.fill.hash,\n});\n\nconst normalizeHyperLiquidScalePriceLadder = (params: {\n minPrice: number;\n maxPrice: number;\n count: number;\n szDecimals: number;\n}): string[] => {\n const { szDecimals, ...ladderParams } = params;\n const prices = computeScalePriceLadder(ladderParams).map((price) =>\n formatHyperLiquidPrice({ price, szDecimals }),\n );\n if (new Set(prices).size !== prices.length) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n return prices;\n};\n\n/** Capability lookup result that carries resolved market metadata when ready. */\ntype HyperLiquidOrderCapabilityMarket =\n | Readonly<{ status: 'ready'; market: MarketInfo }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: DirectProviderScalePriceLadderUnavailableReason;\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 = PROVIDER_CONFIG.DefaultProvider;\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 | null, MetaResponse>();\n\n // Fresh filtered markets used only for capability discovery. Each routed\n // DEX owns its freshness window and coalesced refresh.\n readonly #orderCapabilitiesMarketsByDex = new Map<\n string | null,\n OrderCapabilitiesMarketCacheEntry\n >();\n\n readonly #orderCapabilitiesRefreshByDex = new Map<\n string | null,\n Promise<MarketInfo[]>\n >();\n\n // Sticky for this instance. PerpsController discards disconnected providers\n // during initialization; direct callers must call initialize() before reuse.\n #isDisconnected = false;\n\n #disconnectOperationsInFlight = 0;\n\n #disconnectOperationPromise: Promise<DisconnectResult> | null = null;\n\n #lifecycleGeneration = 0;\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 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 // Unified DEX discovery cache — single source of truth for all perpDexs() derivatives.\n // Replaces three separate caches to eliminate desync bugs by construction.\n // All writes go through #dexDiscoveryCache.update(); readers use .state.\n readonly #dexDiscoveryCache: DexDiscoveryCacheManager;\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 #subscriptionBuilderApprovalEpoch = 0;\n\n /** Builder approvals keyed by network, account, and builder address. */\n readonly #approvedBuilderAddresses = new Set<string>();\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 #userFeeResolution?: PerpsFeeResolution;\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 // Legacy rollback switch. MetaMask production supports unified account and\n // portfolio margin. The false branch and its manual HIP-3 transfers remain\n // temporarily for rollback compatibility and will be removed separately.\n #useUnifiedAccount: boolean;\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 // True when the most recent #ensureUnifiedAccountEnabled run ended in a\n // transient state that warrants retry (silent agent-key failure, REST\n // userAbstraction lookup failure, or keyring locked). #ensureReady resets\n // its memoized promise when this is set so the next entry retries the\n // migration instead of returning the cached resolved promise.\n #unifiedAccountSetupNeedsRetry = false;\n\n // Earliest Date.now() at which #ensureReady runs the unified-account setup\n // again after its lookup failed on the WebSocket transport. 0 = no cooldown.\n #unifiedAccountTransportRetryAt = 0;\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 'multi-sig required': PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,\n 'invalid nonce': PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE,\n };\n\n // Scale ladders placed by this provider instance, keyed by group handle, so\n // one cancel can reach every rung. Cleared on disconnect; the rung IDs are\n // also returned to the caller as `OrderResult.childOrderIds`.\n readonly #scaleOrderGroups = new Map<string, ScaleOrderGroup>();\n\n // Prevent a stale open-order cache from recreating a group that this\n // provider lifecycle already canceled successfully.\n readonly #cancelledScaleOrderGroups = new Set<string>();\n\n // Native TWAP IDs and any manual HIP-3 collateral transfer must outlive one\n // provider instance: controller disconnect/reinitialization replaces the\n // provider while the venue schedule keeps running. Each controller messenger\n // owns one registry, so separate controller lifecycles never share handles.\n static readonly #trackedTwapOrdersByMessenger = new WeakMap<\n PerpsControllerMessengerBase,\n Map<string, TrackedTwapOrder>\n >();\n\n readonly #trackedTwapOrders: Map<string, TrackedTwapOrder>;\n\n // Chase sessions running on this provider instance, keyed by session handle.\n // Each owns a pending timer, so disconnect has to stop them.\n readonly #chaseSessions = new Map<string, ChaseSession>();\n\n // In-flight termination is keyed by stable strategy handle so retries share\n // one venue mutation. Completed handles remain idempotent for this provider\n // lifecycle and are cleared on disconnect.\n readonly #chaseTerminations = new Map<string, Promise<CancelOrderResult>>();\n\n // Provider-lifetime tombstones make every later retry idempotent. Disconnect\n // clears them with the rest of the account-scoped Chase registry.\n readonly #terminatedChaseHandles = new Set<string>();\n\n // Chase placements that have reserved a slot against the venue's concurrency\n // cap but have not registered their session yet. Two round trips separate the\n // two, and a reservation is what keeps concurrent placements from both\n // passing the check.\n #chasePlacementsInFlight = 0;\n\n // Allows lifecycle teardown to wait until every placement has either\n // registered a session or retracted its newly-rested child.\n readonly #chasePlacementWaiters = new Set<Promise<void>>();\n\n // Serialize background Chase mutations. Several sessions share one signer and\n // transport, so simultaneous cancel/replace ticks would create avoidable\n // signed traffic and can starve a foreground placement.\n #chaseTickQueue: Promise<void> = Promise.resolve();\n\n // Every strategy captures this before its round trips. A changed generation\n // prevents a late response from registering handles after disconnect.\n #strategyGeneration = 0;\n\n // Reference-counted because suspension and disconnect may overlap. One\n // lifecycle owner finishing must not reopen placement while another still\n // drains or tears down the provider.\n #chasePlacementBlockers = 0;\n\n // Track whether clients have been initialized (lazy initialization)\n #clientsInitialized = false;\n\n readonly #getAgentSigner: HyperLiquidCredentials['getAgentSigner'];\n\n // Incremented by clearAgentSigners so answers pending across a clear are\n // discarded and asked again.\n #agentSignersGeneration = 0;\n\n // The getAgentSigner answer per network and main account (see\n // getAgentAccountKey), pending or non-null, so an agent is only used for its\n // account and network, and the agent it resolved to. An entry is dropped\n // when the venue rejects that agent.\n readonly #agentSigners = new Map<\n string,\n { answer: Promise<PerpsAgentSigner | null>; agent?: PerpsAgentSigner }\n >();\n\n // The account and network each agent last signed an L1 action for, keyed by\n // the lowercased address the venue reports. A rejection is attributed from\n // it rather than from the selected account, which may have changed while\n // the write was in flight; an L1 signature names no user, so one agent acts\n // for one account. Kept across clearAgentSigners, so an agent replaced while\n // its action was in flight is still recognized.\n readonly #agentSignedFor = new Map<string, AgentSignature>();\n\n // The binding of each wallet adapter this provider created.\n readonly #walletBindings = new WeakMap<\n HyperLiquidWalletParams,\n WalletBinding\n >();\n\n // The agent signature of each answered exchange request, keyed by the\n // venue answer. A \"Must deposit\" answer is attributed from it, so only to\n // the agent that signed that request.\n readonly #agentSignatureByAnswer = new WeakMap<object, AgentSignature>();\n\n readonly #onAgentRejected: HyperLiquidProviderOptions['onAgentRejected'];\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 readonly #subscriptionBuilderAddressTestnet?: string;\n\n readonly #subscriptionBuilderAddressMainnet?: string;\n\n readonly #priceDeviationLimit: number;\n\n readonly #onChaseOrderMaxDistanceReached?: ChaseOrderMaxDistanceReachedHandler;\n\n constructor(options: HyperLiquidProviderOptions) {\n this.#deps = options.platformDependencies;\n this.#messenger = options.messenger;\n const trackedTwapOrders =\n HyperLiquidProvider.#trackedTwapOrdersByMessenger.get(this.#messenger) ??\n new Map<string, TrackedTwapOrder>();\n HyperLiquidProvider.#trackedTwapOrdersByMessenger.set(\n this.#messenger,\n trackedTwapOrders,\n );\n this.#trackedTwapOrders = trackedTwapOrders;\n this.#builderAddressTestnet = options.builderAddressTestnet;\n this.#builderAddressMainnet = options.builderAddressMainnet;\n this.#subscriptionBuilderAddressTestnet =\n options.subscriptionBuilderAddressTestnet;\n this.#subscriptionBuilderAddressMainnet =\n options.subscriptionBuilderAddressMainnet;\n this.#getAgentSigner = options.getAgentSigner;\n this.#onAgentRejected = options.onAgentRejected;\n this.#onChaseOrderMaxDistanceReached =\n options.onChaseOrderMaxDistanceReached;\n this.#priceDeviationLimit =\n options.priceDeviationLimit ??\n HYPERLIQUID_CONFIG.OraclePriceDeviationLimit;\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 unified account mode, fallback to programmatic transfer if unsupported\n this.#useUnifiedAccount = options.useUnifiedAccount ?? true;\n\n // Initialize services with injected platform dependencies\n this.#clientService = new HyperLiquidClientService(this.#deps, {\n isTestnet,\n onExchangeRequest: (\n payload: unknown,\n answer: unknown,\n wallet: HyperLiquidWalletParams,\n ): void => this.#matchAgentSignature(payload, answer, wallet),\n });\n this.#dexDiscoveryCache = new DexDiscoveryCacheManager({\n isTestnetMode: (): boolean => this.#clientService.isTestnetMode(),\n debugLogger: this.#deps.debugLogger,\n getAllowlistMarkets: (): string[] => this.#allowlistMarkets,\n });\n this.#walletService = new HyperLiquidWalletService(\n this.#deps,\n this.#messenger,\n { isTestnet },\n );\n this.#subscriptionService = new HyperLiquidSubscriptionService(\n this.#clientService,\n {\n // The subscription service may initialize the SDK clients too, so\n // its wallets are bound like the provider's.\n createWalletAdapter: (): HyperLiquidWalletParams =>\n this.#createWalletAdapter(),\n getUserAddressWithDefault: async (\n accountId?: CaipAccountId,\n ): Promise<Hex> =>\n await this.#walletService.getUserAddressWithDefault(accountId),\n },\n this.#deps,\n this.#hip3Enabled,\n [], // enabledDexs - will be populated after DEX discovery in buildAssetMapping\n this.#allowlistMarkets,\n this.#blocklistMarkets,\n this.#priceDeviationLimit,\n async () => {\n await this.#ensureClientsInitialized();\n const validatedDexs = await this.#getValidatedDexs();\n if (this.#hip3Enabled && !this.#dexDiscoveryCache.state?.validated) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n return validatedDexs.filter((dex): dex is string => dex !== null);\n },\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 * Resolve the provider-owned fee policy for one placement context.\n *\n * The full context is accepted so future policies can vary by market route\n * or other order inputs without changing the provider contract. Runtime\n * callers can still bypass TypeScript, so an unknown order type falls back to\n * the revenue-preserving standard policy and is made observable.\n *\n * @param params - Fee quote or placement context.\n * @returns HyperLiquid's fee policy for this order.\n */\n #resolveOrderFeePolicy(\n params: HyperLiquidOrderFeeContext,\n ): HyperLiquidOrderFeePolicy {\n const fallbackPolicy = Object.prototype.hasOwnProperty.call(\n HYPERLIQUID_ORDER_FEE_CONFIG,\n params.orderType,\n )\n ? HYPERLIQUID_ORDER_FEE_CONFIG[params.orderType]\n : undefined;\n if (fallbackPolicy) {\n return fallbackPolicy;\n }\n\n this.#deps.debugLogger.log(\n 'HyperLiquid: Unknown order type used the safe builder-fee policy',\n { orderType: params.orderType },\n );\n return HYPERLIQUID_ORDER_FEE_CONFIG.market;\n }\n\n /**\n * Return provider-owned standalone trigger, strategy and margin-mode support\n * for a routed market. HyperLiquid advertises its implemented trigger types\n * and strategies uniformly after confirming the routed market exists;\n * margin modes follow the market's metadata.\n *\n * @param params - Required market route context.\n * @returns Supported standalone trigger types, strategies and margin modes.\n */\n async getOrderCapabilities(\n params: GetOrderCapabilitiesParams,\n ): Promise<DirectProviderOrderCapabilities> {\n const result = await this.#getOrderCapabilityMarket(params.symbol);\n if (result.status === 'unavailable') {\n return result;\n }\n const supportedMarginModes: readonly MarginMode[] = Object.freeze(\n this.#isCrossMarginSupported(params.symbol, result.market)\n ? ['isolated', 'cross']\n : ['isolated'],\n );\n return Object.freeze({\n ...HYPERLIQUID_ORDER_CAPABILITIES,\n supportedMarginModes,\n });\n }\n\n /**\n * Whether the venue accepts Cross margin for a market. Both SDK\n * `marginMode` values (strictIsolated and noCross) prohibit Cross, and any\n * future restriction value is treated as unsupported until handled\n * explicitly. HIP-3 collateral transfers still assume isolated margin, so\n * Cross stays unavailable there until that account-mode-aware path is\n * supported.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @param asset - Venue margin metadata for the market.\n * @param asset.onlyIsolated - Whether the market only allows isolated margin.\n * @param asset.marginMode - Venue margin-mode restriction, if any.\n * @returns True when Cross margin orders are accepted.\n */\n #isCrossMarginSupported(\n symbol: string,\n asset: { onlyIsolated?: boolean; marginMode?: string },\n ): boolean {\n const { dex } = parseAssetName(symbol);\n return !asset.onlyIsolated && !asset.marginMode && dex === null;\n }\n\n /**\n * Report the margin mode HyperLiquid currently binds to a market, so\n * clients can match what order placement will accept.\n *\n * @param params - Market and optional provider route.\n * @returns The current lock, or unavailable when it cannot be read.\n */\n async getMarginModeLock(\n params: GetMarginModeLockParams,\n ): Promise<PerpsMarginModeLock> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n await this.#ensureClientsInitialized();\n this.#clientService.ensureInitialized();\n const lock = await this.#readMarginModeLock(params.symbol);\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Margin mode lock read',\n );\n return lock\n ? { status: 'locked', providerId: this.protocolId, ...lock }\n : { status: 'unlocked', providerId: this.protocolId };\n } catch (error) {\n this.#deps.debugLogger.log('HyperLiquid: Margin mode lock unavailable', {\n symbol: params.symbol,\n error: ensureError(error, 'HyperLiquidProvider.getMarginModeLock')\n .message,\n });\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n }\n\n /**\n * Normalize a Scale price ladder with HyperLiquid market precision.\n *\n * @param params - Market, ladder bounds, count, and optional provider route.\n * @returns HyperLiquid-normalized prices or a typed unavailable result.\n * @throws When the ladder count or normalized range is invalid.\n */\n async getScalePriceLadder(\n params: GetScalePriceLadderParams,\n ): Promise<PerpsScalePriceLadder> {\n if (\n params.providerId !== undefined &&\n params.providerId !== this.protocolId\n ) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_not_routable',\n };\n }\n\n const result = await this.#getOrderCapabilityMarket(params.symbol);\n if (result.status === 'unavailable') {\n return result;\n }\n\n const prices = normalizeHyperLiquidScalePriceLadder({\n minPrice: params.minPrice,\n maxPrice: params.maxPrice,\n count: params.count,\n szDecimals: result.market.szDecimals,\n });\n\n return { status: 'ready', providerId: this.protocolId, prices };\n }\n\n /**\n * Resolve fresh market metadata shared by capability and ladder reads.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The resolved market or a typed unavailable result.\n */\n async #getOrderCapabilityMarket(\n symbol: string,\n ): Promise<HyperLiquidOrderCapabilityMarket> {\n if (!isValidCapabilitySymbol(symbol, { allowProviderRoute: true })) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'invalid_symbol',\n };\n }\n if (this.#isDisconnected) {\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n\n const { dex } = parseAssetName(symbol);\n const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n const market = (await this.#getFreshOrderCapabilityMarkets(dex)).find(\n ({ name }) => name === symbol,\n );\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability read',\n );\n return market\n ? { status: 'ready', market }\n : {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'market_not_found',\n };\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Order capability market unavailable',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.getOrderCapabilityMarket',\n ).message,\n },\n );\n return {\n status: 'unavailable',\n providerId: this.protocolId,\n reason: 'provider_unavailable',\n };\n }\n }\n\n /**\n * Reject provider work that crossed an asynchronous disconnect boundary.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation error.\n */\n #assertProviderLifecycleCurrent(generation: number, operation: string): void {\n if (this.#isDisconnected || generation !== this.#lifecycleGeneration) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Provider operation became stale during disconnect',\n { operation },\n );\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n }\n\n /**\n * Reject cache writes from an old lifecycle or while teardown is active.\n * General reads may lazily rebuild caches after disconnect completes, but a\n * request that crossed the disconnect boundary must not repopulate them.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation log.\n */\n #assertCacheWriteLifecycleCurrent(\n generation: number,\n operation: string,\n ): void {\n if (!this.#isCacheWriteLifecycleCurrent(generation, operation)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n }\n\n /**\n * Check whether fetched data may still populate provider caches.\n *\n * @param generation - Provider lifecycle generation captured before work.\n * @param operation - Operation name included in the cancellation log.\n * @returns Whether a cache write is safe.\n */\n #isCacheWriteLifecycleCurrent(\n generation: number,\n operation: string,\n ): boolean {\n if (\n this.#disconnectOperationsInFlight > 0 ||\n generation !== this.#lifecycleGeneration\n ) {\n this.#deps.debugLogger.log(\n 'HyperLiquid: Cache write became stale during disconnect',\n { operation },\n );\n return false;\n }\n return true;\n }\n\n /**\n * Return filtered market metadata fresh enough for a capability query.\n * Each DEX shares one refresh across concurrent callers, and a failed\n * refresh remains immediately retryable.\n *\n * @param dex - Routed DEX, or null for the main DEX.\n * @returns Fresh filtered markets for that route.\n */\n async #getFreshOrderCapabilityMarkets(\n dex: string | null,\n ): Promise<MarketInfo[]> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const cachedMarkets = this.#orderCapabilitiesMarketsByDex.get(dex);\n if (\n cachedMarkets &&\n Date.now() - cachedMarkets.freshAt <\n PERFORMANCE_CONFIG.OrderCapabilitiesMetaFreshnessMs\n ) {\n return cachedMarkets.markets;\n }\n\n let refreshPromise = this.#orderCapabilitiesRefreshByDex.get(dex);\n if (!refreshPromise) {\n refreshPromise = (async (): Promise<MarketInfo[]> => {\n const markets = await this.#fetchMarketsForDex({\n dex,\n skipCache: true,\n });\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability metadata refresh',\n );\n\n this.#orderCapabilitiesMarketsByDex.set(dex, {\n markets,\n freshAt: Date.now(),\n });\n return markets;\n })();\n this.#orderCapabilitiesRefreshByDex.set(dex, refreshPromise);\n }\n\n try {\n const markets = await refreshPromise;\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Order capability read',\n );\n return markets;\n } finally {\n if (this.#orderCapabilitiesRefreshByDex.get(dex) === refreshPromise) {\n this.#orderCapabilitiesRefreshByDex.delete(dex);\n }\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.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n\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 if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\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 if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n\n const wallet = this.#createWalletAdapter();\n await this.#clientService.initialize(wallet);\n if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\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 * Create a wallet adapter for the SDK clients, bound to the network and\n * session it is created in: its agents are resolved, and its signatures\n * attributed, for them, even when a queued write signs after a network\n * switch or a disconnect.\n *\n * @returns The wallet adapter.\n */\n #createWalletAdapter(): HyperLiquidWalletParams {\n const binding: WalletBinding = {\n isTestnet: this.#clientService.isTestnetMode(),\n generation: this.#lifecycleGeneration,\n unansweredSignatures: new Map(),\n };\n const wallet = this.#walletService.createWalletAdapter(\n async (mainAddress: Hex): Promise<PerpsAgentSigner | null> =>\n await this.#resolveTrackedAgentSigner(mainAddress, binding),\n );\n this.#walletBindings.set(wallet, binding);\n return wallet;\n }\n\n /**\n * Resolve the agent that signs L1 actions for a main account on a network\n * through `getAgentSigner`. A non-null answer is kept;\n * null and failures are not, so the next L1 action asks again. An answer\n * pending across clearAgentSigners is discarded and asked again.\n *\n * @param mainAddress - The selected main account.\n * @param isTestnet - The network of the wallet adapter that signs.\n * @returns The agent, or null to sign with the main account.\n */\n async #resolveAgentSigner(\n mainAddress: Hex,\n isTestnet: boolean,\n ): Promise<PerpsAgentSigner | null> {\n const account: PerpsAgentAccount = { mainAddress, isTestnet };\n const key = getAgentAccountKey(account);\n const generation = this.#agentSignersGeneration;\n let entry = this.#agentSigners.get(key);\n if (!entry) {\n if (!this.#getAgentSigner) {\n return null;\n }\n let answer: Promise<PerpsAgentSigner | null>;\n try {\n answer = this.#getAgentSigner(account);\n } catch (error) {\n answer = Promise.reject(error);\n }\n entry = { answer };\n this.#agentSigners.set(key, entry);\n }\n\n const pendingEntry = entry;\n // A clear while this answer was pending wins, so it is asked again. Only a\n // clear replaces a pending answer: every other removal happens once it\n // settled, after all its callers resumed.\n const isSuperseded = (): boolean =>\n generation !== this.#agentSignersGeneration;\n\n let agentSigner: PerpsAgentSigner | null;\n try {\n agentSigner = await pendingEntry.answer;\n } catch (error) {\n if (isSuperseded()) {\n return await this.#resolveAgentSigner(mainAddress, isTestnet);\n }\n this.#agentSigners.delete(key);\n this.#deps.debugLogger.log('HyperLiquidProvider: getAgentSigner failed', {\n error: ensureError(error, 'HyperLiquidProvider.resolveAgentSigner')\n .message,\n });\n throw new AgentSignerUnavailableError(error);\n }\n\n if (isSuperseded()) {\n return await this.#resolveAgentSigner(mainAddress, isTestnet);\n }\n if (agentSigner) {\n pendingEntry.agent = agentSigner;\n // The wallet adapter resolves at every L1 signature, so this records\n // the account the agent is about to sign for.\n this.#agentSignedFor.set(agentSigner.address.toLowerCase(), {\n key,\n account,\n agentAddress: agentSigner.address,\n });\n } else {\n this.#agentSigners.delete(key);\n }\n return agentSigner;\n }\n\n /**\n * Map and log a failed exchange write, unless the signer could not sign it\n * (`KEYRING_LOCKED`: a locked keyring, or an unavailable or rejected\n * agent), which the caller retries.\n *\n * @param error - The caught error.\n * @param method - The write that failed.\n * @param extra - Context for the log.\n * @param errorTags - Bounded tags describing the failed write.\n * @returns The mapped error.\n */\n async #reportWriteError(\n error: unknown,\n method: string,\n extra: Record<string, unknown>,\n errorTags: PerpsErrorTags,\n ): Promise<Error> {\n const signerFailure = await this.#handleSignerFailure(error, method, extra);\n if (signerFailure) {\n return signerFailure;\n }\n const mappedError = this.#mapError(error);\n this.#deps.logger.error(\n mappedError,\n await this.#getTradingErrorContext(method, mappedError, extra, errorTags),\n );\n return mappedError;\n }\n\n /**\n * The agent a venue rejection names, with the account and network it last\n * signed for. HyperLiquid answers \"User or API Wallet 0x... does not\n * exist.\" with the signer's address, so for a revoked or expired agent it\n * reads like a wallet with no account. It sometimes answers \"Must deposit\n * before performing actions. User: 0x...\" with the main account instead;\n * that is attributed to the agent that signed the answered request (see\n * #findRevokedAgent).\n *\n * @param error - The caught error.\n * @returns The rejected agent, with its address as the host supplied it\n * and the account it signed for, or undefined.\n */\n async #findRejectedAgent(\n error: unknown,\n ): Promise<AgentSignature | undefined> {\n if (this.#agentSignedFor.size === 0) {\n return undefined;\n }\n const { message } = ensureError(\n error,\n 'HyperLiquidProvider.findRejectedAgent',\n );\n const answer = getVenueAnswer(error);\n const signature = isStatusObject(answer)\n ? this.#agentSignatureByAnswer.get(answer)\n : undefined;\n if (isHyperLiquidUserNotFoundError(error)) {\n const reportedAddress =\n UNKNOWN_WALLET_ADDRESS_PATTERN.exec(message)?.[1]?.toLowerCase();\n if (reportedAddress === undefined) {\n return undefined;\n }\n // The agent that signed the answered request, on its wallet's network.\n // When no signature is linked to the answer (it did not come through\n // an exchange client of this provider), the account the agent last\n // signed an L1 action for.\n if (signature) {\n return signature.agentAddress.toLowerCase() === reportedAddress\n ? signature\n : undefined;\n }\n return this.#agentSignedFor.get(reportedAddress);\n }\n const mainAddress = MUST_DEPOSIT_USER_PATTERN.exec(message)?.[1];\n return mainAddress !== undefined &&\n signature?.account.mainAddress.toLowerCase() === mainAddress.toLowerCase()\n ? await this.#findRevokedAgent(signature)\n : undefined;\n }\n\n /**\n * The agent that signed a request the venue answered with \"Must deposit\n * before performing actions\", if the venue no longer lists it (revoked, or\n * past its `validUntil`). The venue answers an account with no funds the\n * same way, so the agent list decides; it is asked once per signature. A\n * signature made through the wallet of an earlier network or session is\n * not checked.\n *\n * @param signature - The agent signature of the request.\n * @returns The revoked agent, or undefined.\n */\n async #findRevokedAgent(\n signature: AgentSignature,\n ): Promise<AgentSignature | undefined> {\n const isCurrent = (): boolean =>\n signature.generation === this.#lifecycleGeneration &&\n signature.account.isTestnet === this.#clientService.isTestnetMode();\n if (!isCurrent()) {\n return undefined;\n }\n signature.approvalCheck ??= this.#isAgentListed(signature);\n const listed = await signature.approvalCheck;\n return listed || !isCurrent() ? undefined : signature;\n }\n\n /**\n * Resolve the agent for an L1 signature of a wallet adapter, on the\n * adapter's network, and note each signature it makes in the adapter's\n * binding, so the venue's answer to that request is attributed to it.\n *\n * @param mainAddress - The selected main account.\n * @param binding - The binding of the wallet adapter that signs.\n * @returns The agent, or null to sign with the main account.\n */\n async #resolveTrackedAgentSigner(\n mainAddress: Hex,\n binding: WalletBinding,\n ): Promise<PerpsAgentSigner | null> {\n const account: PerpsAgentAccount = {\n mainAddress,\n isTestnet: binding.isTestnet,\n };\n const agent = await this.#resolveAgentSigner(\n mainAddress,\n binding.isTestnet,\n );\n if (!agent) {\n return null;\n }\n return {\n address: agent.address,\n signTypedData: async (payload): Promise<Hex> => {\n const signature = await agent.signTypedData(payload);\n // The SDK refuses any other signature before sending the request,\n // so no answer would come for it.\n if (isHexString(signature) && signature.length === 132) {\n binding.unansweredSignatures.set(getSignatureKey(signature), {\n key: getAgentAccountKey(account),\n account,\n agentAddress: agent.address,\n generation: binding.generation,\n });\n }\n return signature;\n },\n };\n }\n\n /**\n * Link the venue's answer to an exchange request with the agent signature\n * the request carries, if an agent signed it.\n *\n * @param payload - The exchange request.\n * @param answer - The venue's answer, or undefined when there is none.\n * @param wallet - The wallet adapter the request was signed through.\n */\n #matchAgentSignature(\n payload: unknown,\n answer: unknown,\n wallet: HyperLiquidWalletParams,\n ): void {\n const signature =\n isStatusObject(payload) && isStatusObject(payload.signature)\n ? payload.signature.r\n : undefined;\n if (typeof signature !== 'string') {\n return;\n }\n const unansweredSignatures =\n this.#walletBindings.get(wallet)?.unansweredSignatures;\n const key = getSignatureKey(signature);\n const agentSignature = unansweredSignatures?.get(key);\n if (!agentSignature) {\n return;\n }\n unansweredSignatures?.delete(key);\n if (isStatusObject(answer)) {\n this.#agentSignatureByAnswer.set(answer, agentSignature);\n }\n }\n\n /**\n * Whether the venue lists an agent as approved for its main account.\n * `validUntil` is compared with this device's clock.\n *\n * @param agent - The agent and the account it signed for.\n * @param agent.account - The account the agent signed for.\n * @param agent.agentAddress - The agent.\n * @returns False when the agent is missing or expired. True when it is\n * listed, or when the list cannot be read, so the venue's error stands.\n */\n async #isAgentListed({\n account,\n agentAddress,\n }: {\n account: PerpsAgentAccount;\n agentAddress: Hex;\n }): Promise<boolean> {\n try {\n const agents = await this.#clientService\n .getInfoClient({ useHttp: true })\n .extraAgents({ user: account.mainAddress });\n const listed = agents.find(\n ({ address }) => address.toLowerCase() === agentAddress.toLowerCase(),\n );\n return (\n listed !== undefined &&\n (listed.validUntil === null || listed.validUntil > Date.now())\n );\n } catch (error) {\n this.#deps.debugLogger.log('HyperLiquidProvider: extraAgents failed', {\n error: ensureError(error, 'HyperLiquidProvider.isAgentListed').message,\n });\n return true;\n }\n }\n\n /**\n * Handle a venue rejection of an agent: drop it if it is still the\n * resolved one, so the next L1 action asks for one again, and tell the\n * owner of the bindings.\n *\n * @param error - The caught error.\n * @returns True when the error was the rejection of an agent.\n */\n async #evictRejectedAgent(error: unknown): Promise<boolean> {\n const rejected = await this.#findRejectedAgent(error);\n if (!rejected) {\n return false;\n }\n const { account, key, agentAddress } = rejected;\n if (this.#agentSigners.get(key)?.agent?.address === agentAddress) {\n this.#agentSigners.delete(key);\n }\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: agent rejected by the venue, asking again',\n { agent: agentAddress },\n );\n try {\n this.#onAgentRejected?.(account, agentAddress);\n } catch (callbackError) {\n this.#deps.debugLogger.log('HyperLiquidProvider: onAgentRejected threw', {\n error: ensureError(\n callbackError,\n 'HyperLiquidProvider.evictRejectedAgent',\n ).message,\n });\n }\n return true;\n }\n\n /**\n * Whether an exchange write failed because its signer could not sign it:\n * a locked keyring, an unavailable agent, or an agent the venue rejected.\n * It does not evict; the caller that reports the failure classifies it.\n *\n * @param error - The caught error.\n * @returns True for a signer failure.\n */\n async #isSignerFailure(error: unknown): Promise<boolean> {\n return (\n isKeyringLockedError(error) ||\n isAgentSignerUnavailableError(error) ||\n (await this.#findRejectedAgent(error)) !== undefined\n );\n }\n\n /**\n * Classify a failed exchange write whose signer could not sign it, evicting\n * a rejected agent. The next attempt retries.\n *\n * @param error - The caught error.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #classifySignerFailure(error: unknown): Promise<Error | undefined> {\n const rejectedAgent = await this.#evictRejectedAgent(error);\n return rejectedAgent ||\n isKeyringLockedError(error) ||\n isAgentSignerUnavailableError(error)\n ? new Error(PERPS_ERROR_CODES.KEYRING_LOCKED)\n : undefined;\n }\n\n /**\n * Classify a failed write whose signer could not sign it, and note it as\n * retryable instead of reporting it.\n *\n * @param error - The caught error.\n * @param method - The write that failed.\n * @param extra - Context for the debug log.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #handleSignerFailure(\n error: unknown,\n method: string,\n extra: Record<string, unknown>,\n ): Promise<Error | undefined> {\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n this.#logRetryableSignerFailure(method, extra);\n }\n return signerFailure;\n }\n\n /**\n * Note a write that failed because its signer could not sign it; the\n * caller retries it, so it is not reported as an error.\n *\n * @param method - The write that failed.\n * @param extra - Context for the debug log.\n */\n #logRetryableSignerFailure(\n method: string,\n extra: Record<string, unknown>,\n ): void {\n this.#deps.debugLogger.log(\n `[${method}] Signer unavailable, the write can be retried`,\n extra,\n );\n }\n\n /**\n * Decide whether the wallet has a Hyperliquid account.\n *\n * Hyperliquid accounts are created server-side on first USDC deposit.\n * Before that, every user-scoped exchange write rejects with\n * \"User or API Wallet 0x... does not exist.\" — formerly the top source\n * of `feature:perps` Sentry events (Sentry issues METAMASK-MOBILE-4XB5\n * iOS / 4Q4M Android: ~530k events / ~100k users in 14d on 7.75.1).\n *\n * Probes `infoClient.userNonFundingLedgerUpdates` and caches a positive\n * result in `PerpsSigningCache.walletRegistered`. Negative results are NOT\n * cached — the wallet may deposit between checks; the next entry must\n * re-probe. The probe is cheap (~100ms), non-throwing, and returns the\n * full deposit/withdraw history. A non-empty array means the wallet has\n * interacted with Hyperliquid at least once — necessary and sufficient\n * for `agentSetAbstraction` / `setReferrer` to\n * succeed.\n *\n * If the probe itself throws (transient network), returns `true` and does\n * not cache — fail open so one bad probe never traps a real Hyperliquid\n * user in the deferred state.\n *\n * @param userAddress - The wallet address to check.\n * @param network - The network environment (mainnet | testnet).\n * @returns True if the wallet has been observed on Hyperliquid OR if\n * the probe was inconclusive (fail open). False only when the probe\n * succeeded AND returned an empty ledger.\n * @private\n */\n async #isWalletOnHyperliquid(\n userAddress: string,\n network: 'mainnet' | 'testnet',\n ): Promise<boolean> {\n const cached = PerpsSigningCache.getWalletRegistered(network, userAddress);\n if (cached?.registered) {\n return true;\n }\n\n try {\n const infoClient = this.#clientService.getInfoClient();\n const ledger = await infoClient.userNonFundingLedgerUpdates({\n user: userAddress,\n startTime: 0,\n });\n const registered = Array.isArray(ledger) && ledger.length > 0;\n if (registered) {\n PerpsSigningCache.setWalletRegistered(network, userAddress, true);\n }\n return registered;\n } catch (error) {\n // Fail open. A transient probe failure must never prevent a\n // legitimate Hyperliquid user from completing migration / referral\n // setup. The next entry will re-probe.\n this.#deps.debugLogger.log(\n '[isWalletOnHyperliquid] Probe failed, assuming registered',\n {\n network,\n user: userAddress,\n error: ensureError(error, 'HyperLiquidProvider.isWalletOnHyperliquid')\n .message,\n },\n );\n return true;\n }\n }\n\n /**\n * Decide whether the Hyperliquid account is a multi-sig account.\n *\n * Hyperliquid rejects every single-signer exchange write for a converted\n * multi-sig account with `ApiRequestError: Multi-sig required`, so the\n * unified-account migration must not be attempted for those accounts.\n *\n * If the probe throws (transient network), returns `false` — fail open so\n * one bad probe never blocks migration for a normal single-signer account.\n * The `isHyperLiquidMultiSigRequiredError` fallback in the write's catch\n * block remains the safety net.\n *\n * @param userAddress - The wallet address to check.\n * @param infoClient - Optional captured reader for an operation-scoped probe.\n * @returns True only when Hyperliquid reports a multi-sig signer set.\n * @private\n */\n async #isHyperliquidMultiSigAccount(\n userAddress: string,\n infoClient = this.#clientService.getInfoClient(),\n ): Promise<boolean> {\n try {\n const signers = await infoClient.userToMultiSigSigners({\n user: userAddress,\n });\n return signers !== null && signers !== undefined;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[isHyperliquidMultiSigAccount] Probe failed, assuming single-signer',\n {\n user: userAddress,\n error: ensureError(\n error,\n 'HyperLiquidProvider.isHyperliquidMultiSigAccount',\n ).message,\n },\n );\n return false;\n }\n }\n\n /**\n * Attempt to enable HyperLiquid Unified Account mode for HIP-3 orders\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 * @param options - Optional configuration.\n * @param options.allowUserSigning - When true, runs the migration for `default` / `disabled` accounts. Defaults to false so init does not surface a signing prompt; action-time entry points (trading, withdraw) pass true.\n * @private\n */\n async #ensureUnifiedAccountEnabled(options?: {\n allowUserSigning?: boolean;\n }): Promise<void> {\n // Without an agent, the migration is signed by the main wallet, which can\n // prompt (hardware wallets). Init calls with allowUserSigning=false so\n // viewing the Perps section never surfaces a signing dialog. Trading and\n // withdraw entry points pass allowUserSigning=true to drive the migration when\n // the user actually intends to act.\n const allowUserSigning = options?.allowUserSigning ?? false;\n\n // Optimistic reset — set true below only at the failure points that\n // warrant retry (silent agent failure, REST lookup failure, keyring\n // locked). Final-state outcomes (success, prompted-failure cached,\n // already-on-compatible, defer, unknown mode, feature off) leave it\n // false so #ensureReady can keep the memoized promise.\n this.#unifiedAccountSetupNeedsRetry = false;\n\n if (!this.#useUnifiedAccount) {\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 repeated signing prompts\n // while browsing.\n const cachedStatus = TradingReadinessCache.get(network, userAddress);\n if (cachedStatus?.attempted) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup 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 let inFlightPromise = PerpsSigningCache.isInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n while (inFlightPromise) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup in-flight, waiting...',\n { network, userAddress },\n );\n await inFlightPromise;\n // The other instance may have finished without writing the cache (e.g.\n // an init-time call deferred the migration). If the cache\n // is still empty and we are an action-time caller (allowUserSigning=true),\n // we must run our own attempt — otherwise the trade/withdraw would\n // proceed in the deprecated mode.\n const postWaitCache = TradingReadinessCache.get(network, userAddress);\n if (postWaitCache?.attempted) {\n return;\n }\n // Another waiter may have taken the lock first. The lock is checked\n // and taken with no await in between, so only one waiter gets it.\n inFlightPromise = PerpsSigningCache.isInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n }\n\n // Set in-flight lock to prevent concurrent attempts\n const completeInFlight = PerpsSigningCache.setInFlight(\n 'unifiedAccount',\n network,\n userAddress,\n );\n\n let currentMode: UserAbstractionResponse | undefined;\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: Unified Account setup completed by another provider',\n { network, userAddress },\n );\n completeInFlight();\n return;\n }\n\n // Skip the migration entirely for wallets that have no Hyperliquid\n // account yet. HL creates accounts server-side on first USDC deposit;\n // before that, `agentSetAbstraction` rejects with \"User or API Wallet 0x... does not exist.\" — formerly\n // the top source of `feature:perps` Sentry events on 7.75.1.\n // The probe is cheap, non-throwing, and cached.\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n if (!isRegistered) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Wallet not yet on Hyperliquid, deferring migration',\n { user: userAddress, network },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'no_hl_account',\n });\n // Signal #ensureReady to drop its memoized promise so the next entry\n // re-probes. Without this, the resolved promise would be reused and\n // the wallet would stay permanently deferred until reconnect.\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n const infoClient = this.#clientService.getInfoClient();\n\n // Check current abstraction mode on-chain\n currentMode = await infoClient.userAbstraction({\n user: userAddress,\n });\n\n if (\n currentMode === 'unifiedAccount' ||\n currentMode === 'portfolioMargin'\n ) {\n // portfolioMargin is a superset of unifiedAccount — it already supports\n // auto-collateral management for HIP-3 orders and is more capital-efficient.\n // Downgrading portfolio margin users to unifiedAccount would be harmful,\n // so we treat both modes as already-enabled and skip migration.\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Account already in a compatible mode, skipping migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.ALREADY_ENABLED,\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n // Record the resolved mode in the subscription service so the next\n // aggregation folds spot correctly without waiting for #refreshSpotState.\n this.#subscriptionService.setUserAbstractionMode(\n userAddress,\n currentMode,\n );\n completeInFlight();\n return;\n }\n\n // Defer signing-backed transitions until the user attempts an action.\n // Cache is intentionally left untouched so the next entry re-evaluates;\n // the read-only userAbstraction call is cheap and gated by the in-flight\n // lock, preventing concurrent prompts.\n if (shouldDeferUnifiedAccountSetup(currentMode, allowUserSigning)) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Deferring unified account migration to action time',\n { user: userAddress, network, mode: currentMode },\n );\n completeInFlight();\n return;\n }\n\n // Bail on unknown modes BEFORE firing analytics or attempting dispatch.\n // Keeps `migration_required` actionable (only fires for modes we can\n // actually migrate) and avoids re-emitting on every reconnection.\n if (currentMode !== 'default' && currentMode !== 'disabled') {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unknown abstraction mode, skipping Unified Account migration',\n { user: userAddress, network, mode: currentMode },\n );\n completeInFlight();\n return;\n }\n\n // Hyperliquid rejects every single-signer exchange write for a converted\n // multi-sig account with \"ApiRequestError: Multi-sig required\", which\n // surfaced on the Perps tab on every entry (TAT-3214). Probe right\n // before the write so accounts that never reach one (already compatible,\n // deferred, unknown mode) do not pay the extra round trip.\n const isMultiSig = await this.#isHyperliquidMultiSigAccount(userAddress);\n if (isMultiSig) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Multi-sig account, skipping unified account migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'multi_sig_account',\n });\n // Final state: the write can never succeed for this account, so cache\n // it as attempted with unified mode off. Perps keeps working through\n // the programmatic collateral-transfer fallback.\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n completeInFlight();\n return;\n }\n\n // Track which mode users are currently on before we attempt migration.\n // This tells us the distribution of legacy modes across our user base.\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.MIGRATION_REQUIRED,\n });\n\n // Enable Unified Account mode (default / disabled → unifiedAccount).\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Enabling Unified Account mode',\n {\n user: userAddress,\n network,\n previousMode: currentMode,\n note: 'HyperLiquid will auto-manage collateral for HIP-3 orders',\n },\n );\n\n await this.#clientService.getExchangeClient().agentSetAbstraction({\n abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,\n });\n\n this.#deps.debugLogger.log(\n '✅ HyperLiquidProvider: Unified Account enabled successfully',\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.SUCCESS,\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: true,\n });\n // Record the post-migration mode in the subscription service so it\n // immediately re-aggregates with fold=true and surfaces the unified\n // balance rather than waiting for the next #refreshSpotState.\n this.#subscriptionService.setUserAbstractionMode(\n userAddress,\n HL_UNIFIED_ACCOUNT_MODE,\n );\n completeInFlight();\n } catch (error) {\n // The signer could not sign (a locked keyring, or an unavailable or\n // rejected agent; HyperLiquid keeps the cause in `cause`): leave the\n // cache empty and retry later.\n if (await this.#classifySignerFailure(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Signer unavailable, will retry later',\n );\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net: a Hyperliquid \"user does not exist\" rejection slipped\n // past the proactive probe (race with deposit confirmation, transient\n // probe failure that failed open, ...). Treat as benign — do NOT\n // forward to Sentry. The walletRegistered cache stores positive\n // observations only, so no demotion is needed; the next entry will\n // re-probe.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Wallet not on Hyperliquid (race/stale-cache), deferring migration',\n { user: userAddress, network, currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'no_hl_account',\n });\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net for the multi-sig probe: the account can be converted\n // between the lookup and the write, and the probe fails open on\n // transient info-API errors. Either way the rejection is a permanent\n // account-shape condition, not a failure worth reporting or retrying.\n if (isHyperLiquidMultiSigRequiredError(error)) {\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] Multi-sig account (race/probe fallback), skipping unified account migration',\n { user: userAddress, network, mode: currentMode },\n );\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]:\n PERPS_EVENT_VALUE.STATUS.NOT_APPLICABLE,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: 'multi_sig_account',\n });\n TradingReadinessCache.set(network, userAddress, {\n attempted: true,\n enabled: false,\n });\n completeInFlight();\n return;\n }\n\n // The WebSocket transport could not carry the lookup, typically a\n // socket that exhausted its reconnect budget (Sentry METAMASK-ZHT9).\n // That is connectivity, not a migration failure: keep it out of Sentry\n // and analytics, keep the retry flag, and have #ensureReady wait out a\n // cooldown instead of repeating the lookup on every entry.\n if (isWebSocketTransportError(error)) {\n this.#unifiedAccountTransportRetryAt =\n Date.now() + UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS;\n this.#deps.debugLogger.log(\n '[ensureUnifiedAccountEnabled] WebSocket transport unavailable, will retry after cooldown',\n {\n user: userAddress,\n network,\n error: ensureError(\n error,\n 'HyperLiquidProvider.ensureUnifiedAccountEnabled',\n ).message,\n cooldownMs: UNIFIED_ACCOUNT_TRANSPORT_RETRY_COOLDOWN_MS,\n },\n );\n this.#unifiedAccountSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Agent-path failures and read-only userAbstraction lookup failures\n // are not final: signal #ensureReady to drop its memoized promise and\n // retry on the next entry instead of pinning the user in the\n // deprecated mode for the provider's lifetime.\n this.#unifiedAccountSetupNeedsRetry = true;\n\n const errorMessage = ensureError(\n error,\n 'HyperLiquidProvider.ensureUnifiedAccountEnabled',\n ).message;\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Unified Account setup failed',\n {\n user: userAddress,\n network,\n error: errorMessage,\n },\n );\n\n this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {\n ...(currentMode && {\n [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,\n [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,\n }),\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,\n });\n\n completeInFlight();\n\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.ensureUnifiedAccountEnabled'),\n this.#getErrorContext(\n 'ensureUnifiedAccountEnabled',\n {\n note: 'Could not enable Unified Account (user rejected, or network error)',\n },\n {\n operation: PERPS_ERROR_OPERATION.ConnectionManagement,\n component: PERPS_ERROR_COMPONENT.ConnectionManager,\n action: PERPS_ERROR_ACTION.ConnectionConnection,\n },\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 // Attempt Unified Account migration as early as possible so users aren't\n // blocked when they try to trade. Software wallets can complete the\n // signing-backed migration during initial setup so the first trade sees\n // the unified balance. Hardware wallets remain deferred to action time to\n // avoid repeated signing prompts while browsing.\n // After a WebSocket transport failure, skip it until the cooldown is\n // over. The memoized promise is dropped while the cooldown is active\n // (see below), so a later entry retries. Action-time callers are not\n // gated.\n if (Date.now() >= this.#unifiedAccountTransportRetryAt) {\n await this.#ensureUnifiedAccountEnabled({\n allowUserSigning:\n !this.#walletService.requiresSignatureConfirmation(),\n });\n }\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 try {\n await this.#ensureReadyPromise;\n } catch (error) {\n this.#ensureReadyPromise = null;\n throw error;\n }\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 } else if (\n this.#unifiedAccountSetupNeedsRetry ||\n Date.now() < this.#unifiedAccountTransportRetryAt\n ) {\n // Silent migration / lookup / keyring-locked failure left the cache\n // empty. Without resetting the memoized promise, subsequent\n // #ensureReady calls would skip retry and the user would be stuck\n // in the deprecated mode for the provider's lifetime.\n // A run skipped by the transport cooldown must not be memoized\n // either: the shared flag can read false while an action-time\n // attempt is in flight, and the setup has to run once the cooldown\n // is over.\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 shared setup that may require user signatures:\n * - DEX abstraction enablement (for HIP-3 auto-transfers)\n * - Referral code setup (attribution)\n * - Builder fee approval when the whole action carries a builder context\n *\n * These operations are DEFERRED from ensureReady() to avoid hardware wallet prompt spam\n * when users are just viewing the Perps section (critical for hardware wallets).\n *\n * General trading readiness is independent of builder approval. Native TWAP\n * and cancellations call this with `requiresBuilderFee: false`.\n */\n #tradingSetupPromise: Promise<void> | null = null;\n\n #tradingSetupComplete = false;\n\n // Set when the referral's signer could not sign it, so trading setup is not\n // marked complete and the referral is attempted again.\n #referralSetupNeedsRetry = false;\n\n // Set when the builder's referral code was not ready. It is not the user's\n // to fix, so it does not hold trading setup back: the next\n // `prepareTradingWallet` checks it again, but orders do not.\n #referralAwaitsBuilderCode = false;\n\n readonly #builderFeeSetupPromises = new Map<string, Promise<void>>();\n\n // The venue's refusal of an approval per network, account and builder,\n // when signing again cannot fix it. Kept until disconnect, so the approval\n // is not asked for again.\n readonly #builderFeeRefusals = new Map<string, string>();\n\n /**\n * Approve the standard builder fee once for the current account and network.\n * TWAP never calls this because its native action has no builder field.\n * Without an approval failure code, approval remains non-blocking and the\n * returned context describes attribution only; it does not prove approval.\n * An approval the venue refused for a reason signing again cannot fix is\n * not asked for again until disconnect; it then fails as a failed approval\n * does.\n *\n * @param approvalFailureCode - Operation-specific error to throw when\n * approval is unavailable or fails.\n * @param options - Options.\n * @param options.reportSignerFailure - Throw `KEYRING_LOCKED` when the\n * signer could not sign the approval, even without an approval failure\n * code (the approval is otherwise non-blocking).\n * @param options.reportRefusal - Throw the venue's refusal, even without an\n * approval failure code.\n * @returns The account, network, and configured builder for the action.\n */\n async #ensureBuilderFeeSetup(\n approvalFailureCode?: PerpsErrorCode,\n options: { reportSignerFailure?: boolean; reportRefusal?: boolean } = {},\n ): Promise<BuilderFeeSetupContext> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const isTestnet = this.#clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const cacheKey = this.#getCacheKey(network, userAddress);\n const builderAddress = this.#getBuilderAddress(isTestnet);\n const context: BuilderFeeSetupContext = {\n network,\n userAddress,\n builderAddress,\n };\n const setupKey = this.#getApprovedBuilderKey(\n network,\n userAddress,\n builderAddress,\n );\n if (this.#builderFeeCheckCache.has(cacheKey)) {\n return context;\n }\n\n // An approval the signer could not sign is retryable, not a failure.\n const approvalFailure = (code: PerpsErrorCode): Error =>\n new Error(\n this.#walletService.isMainAccountSignerReady()\n ? code\n : PERPS_ERROR_CODES.KEYRING_LOCKED,\n );\n\n const knownRefusal = this.#builderFeeRefusals.get(setupKey);\n if (knownRefusal) {\n if (approvalFailureCode) {\n throw approvalFailure(approvalFailureCode);\n }\n if (options.reportRefusal) {\n throw new Error(knownRefusal);\n }\n return context;\n }\n\n let pendingApproval = this.#builderFeeSetupPromises.get(setupKey);\n if (!pendingApproval) {\n pendingApproval = this.#ensureBuilderFeeApproval(context);\n this.#builderFeeSetupPromises.set(setupKey, pendingApproval);\n }\n\n try {\n await pendingApproval;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeSetup] Builder fee approval failed',\n error,\n );\n // A signer that could not sign is retryable, not an approval failure.\n if (approvalFailureCode || options.reportSignerFailure) {\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n throw signerFailure;\n }\n }\n const refusal = getBuilderFeeRefusal(error);\n // A refusal that settles after a disconnect belongs to the old session.\n if (refusal && lifecycleGeneration === this.#lifecycleGeneration) {\n this.#builderFeeRefusals.set(setupKey, refusal);\n }\n if (approvalFailureCode) {\n throw approvalFailure(approvalFailureCode);\n }\n if (refusal && options.reportRefusal) {\n throw new Error(refusal);\n }\n } finally {\n if (this.#builderFeeSetupPromises.get(setupKey) === pendingApproval) {\n this.#builderFeeSetupPromises.delete(setupKey);\n }\n }\n\n if (approvalFailureCode && !this.#builderFeeCheckCache.has(cacheKey)) {\n throw approvalFailure(approvalFailureCode);\n }\n\n return context;\n }\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: true;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext>;\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: false;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<undefined>;\n\n #ensureReadyForTrading(options: {\n requiresBuilderFee: boolean;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext | undefined>;\n\n async #ensureReadyForTrading(options: {\n requiresBuilderFee: boolean;\n builderFeeApprovalFailureCode?: PerpsErrorCode;\n // Run the shared setup again to check a builder referral code that was\n // not ready. Only preparation asks for it; orders do not.\n recheckPendingReferral?: boolean;\n }): Promise<BuilderFeeSetupContext | undefined> {\n // First ensure basic initialization is complete\n await this.#ensureReady();\n\n // The migration was deferred during init to avoid a signing prompt on\n // Perps section open. Drive it here, gated by its own cache so\n // already-migrated users are not re-prompted.\n await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });\n\n // Reset right before the check, with no await in between, so a failure\n // above does not leave the setup for an order to run.\n if (options.recheckPendingReferral && this.#referralAwaitsBuilderCode) {\n this.#tradingSetupComplete = false;\n }\n if (!this.#tradingSetupComplete && !this.#tradingSetupPromise) {\n const lifecycleGeneration = this.#lifecycleGeneration;\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Starting shared trading setup',\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 (e.g. USDC token index) 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 // Set up referral code independently from builder-fee applicability.\n await this.#ensureReferralSet();\n\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Trading setup completion',\n );\n\n // Only mark complete if the main-account signer is ready (signing\n // could actually happen) and the referral does not need another\n // attempt.\n if (\n this.#walletService.isMainAccountSignerReady() &&\n !this.#referralSetupNeedsRetry\n ) {\n this.#tradingSetupComplete = true;\n }\n })();\n }\n\n const pendingSetup = this.#tradingSetupPromise;\n if (pendingSetup) {\n try {\n await pendingSetup;\n } finally {\n if (this.#tradingSetupPromise === pendingSetup) {\n this.#tradingSetupPromise = null;\n }\n }\n }\n\n const builderFeeSetupContext = options.requiresBuilderFee\n ? await this.#ensureBuilderFeeSetup(options.builderFeeApprovalFailureCode)\n : undefined;\n\n this.#deps.debugLogger.log(\n '[ensureReadyForTrading] Trading setup complete',\n );\n\n return builderFeeSetupContext;\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({ useHttp: true });\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 const lifecycleGeneration = this.#lifecycleGeneration;\n // Use unified state if available\n if (this.#dexDiscoveryCache.state) {\n const availableHip3Dexs: string[] = [];\n this.#dexDiscoveryCache.state.raw.forEach((dex) => {\n if (dex !== null) {\n availableHip3Dexs.push(dex.name);\n }\n });\n return [null, ...availableHip3Dexs];\n }\n\n // Fetch fresh from API and update unified state\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.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX discovery cache write',\n );\n const state = this.#dexDiscoveryCache.update(allDexs);\n const availableHip3Dexs: string[] = [];\n state.raw.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 // Kill switch: HIP-3 disabled, return main DEX only\n // Must check before cache — #getAllAvailableDexs() can populate\n // state.validated without the hip3Enabled gate\n if (!this.#hip3Enabled) {\n return [null];\n }\n\n // Return cached result if available\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\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 const pendingPromise = this.#fetchValidatedDexsInternal();\n this.#pendingValidatedDexsPromise = pendingPromise;\n\n try {\n const result = await pendingPromise;\n return result;\n } finally {\n // A stale request must not clear a newer lifecycle's pending request.\n if (this.#pendingValidatedDexsPromise === pendingPromise) {\n this.#pendingValidatedDexsPromise = null;\n }\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 const state = this.#dexDiscoveryCache.update([null]);\n return state.validated;\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 // Atomically update unified state (raw + validated + timestamp)\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX discovery cache write',\n );\n const state = this.#dexDiscoveryCache.update(allDexs);\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Available DEXs (market filtering applied at data layer)',\n {\n count: state.validated.filter((dex) => dex !== null).length,\n dexNames: state.validated.filter((dex) => dex !== null),\n },\n );\n\n return state.validated;\n }\n\n /**\n * Resolve the complete DEX set for a fail-closed operation.\n *\n * Unlike ordinary discovery, this uses HTTP and never degrades to main-only\n * when HIP-3 discovery fails.\n *\n * @returns The validated DEX set.\n */\n async #getValidatedDexsStrict(): Promise<(string | null)[]> {\n if (!this.#hip3Enabled) {\n return [null];\n }\n\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\n }\n\n const lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n let allDexs;\n try {\n allDexs = await infoClient.perpDexs();\n } catch {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n if (!Array.isArray(allDexs)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Strict DEX discovery cache write',\n );\n return this.#dexDiscoveryCache.update(allDexs).validated;\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 lifecycleGeneration = this.#lifecycleGeneration;\n const { dexName, skipCache } = params;\n const dexDisplayName = dexName ?? 'main';\n\n // Skip cache if requested (forces fresh fetch)\n if (!skipCache) {\n const cached = this.#cachedMetaByDex.get(dexName);\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 meta = await this.#fetchMeta(dexName);\n const cached = await this.#cacheDexMetadataFromRead({\n dex: dexName,\n meta,\n lifecycleGeneration,\n });\n if (cached) {\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\n return meta;\n }\n\n /**\n * Fetch and validate metadata without mutating provider caches.\n *\n * @param dexName - DEX name, or null for the main DEX.\n * @returns Validated metadata for the requested DEX.\n */\n async #fetchMeta(dexName: string | null): Promise<MetaResponse> {\n const dexDisplayName = dexName ?? 'main';\n\n // Bring the SDK clients up first. This is the first client touch on the\n // write path — placeOrder resolves asset info before it ensures trading\n // readiness — so without it a cold start or a post-disconnect action fails\n // with CLIENT_NOT_INITIALIZED instead of waiting for the clients it needs.\n // Idempotent, and a warm cache hit returns above without reaching here.\n await this.#ensureClientsInitialized();\n // Metadata is request/response data, so keep this path available while a\n // failed WebSocket reconnect is retrying.\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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(dexName ? { dex: dexName } : 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 return meta;\n }\n\n /**\n * Write provider metadata caches only within the lifecycle that fetched it.\n *\n * @param params - Metadata and lifecycle context.\n * @param params.dex - DEX name, or null for the main DEX.\n * @param params.meta - Validated DEX metadata.\n * @param params.assetCtxs - Asset contexts shared with subscriptions, if any.\n * @param params.lifecycleGeneration - Lifecycle that produced the metadata.\n */\n #cacheDexMetadata(params: {\n dex: string | null;\n meta: MetaResponse;\n assetCtxs?: PerpsAssetCtx[];\n lifecycleGeneration: number;\n }): void {\n const { dex, meta, assetCtxs, lifecycleGeneration } = params;\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX metadata cache write',\n );\n this.#cachedMetaByDex.set(dex, meta);\n if (assetCtxs) {\n const subscriptionDexKey = dex ?? '';\n this.#subscriptionService.setDexMetaCache(subscriptionDexKey, meta);\n this.#subscriptionService.setDexAssetCtxsCache(\n subscriptionDexKey,\n assetCtxs,\n );\n }\n }\n\n /**\n * Cache metadata fetched for a read without discarding a valid response.\n *\n * @param params - Metadata and lifecycle context.\n * @param params.dex - DEX name, or null for the main DEX.\n * @param params.meta - Validated DEX metadata.\n * @param params.assetCtxs - Asset contexts shared with subscriptions, if any.\n * @param params.lifecycleGeneration - Lifecycle that produced the metadata.\n * @returns Whether the fetched metadata was cached.\n */\n async #cacheDexMetadataFromRead(params: {\n dex: string | null;\n meta: MetaResponse;\n assetCtxs?: PerpsAssetCtx[];\n lifecycleGeneration: number;\n }): Promise<boolean> {\n const { dex, meta, assetCtxs, lifecycleGeneration } = params;\n if (\n !this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'DEX metadata read cache write',\n )\n ) {\n return false;\n }\n\n try {\n this.#cacheDexMetadata({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\n await this.#backfillAssetMapForDex(dex, meta, lifecycleGeneration);\n return true;\n } catch (error) {\n if (\n ensureError(error, 'HyperLiquidProvider.cacheDexMetadataFromRead')\n .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE\n ) {\n return false;\n }\n throw error;\n }\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 * @param lifecycleGeneration - Lifecycle that produced the metadata.\n * @returns True if the mapping was rebuilt for the DEX.\n */\n async #backfillAssetMapForDex(\n dex: string | null,\n meta: MetaResponse,\n lifecycleGeneration: number,\n ): Promise<boolean> {\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset map backfill',\n );\n if (!meta?.universe || !Array.isArray(meta.universe)) {\n return false;\n }\n\n if (!this.#dexDiscoveryCache.state) {\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 this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset map backfill',\n );\n\n const allPerpDexs = this.#dexDiscoveryCache.state?.raw ?? [null];\n const perpDexIndex = allPerpDexs.findIndex((entry) => {\n if (dex === null) {\n return entry === null;\n }\n return 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 lifecycleGeneration = this.#lifecycleGeneration;\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, lifecycleGeneration);\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 (e.g. USDC token index) 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 lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient();\n const spotMeta = await infoClient.spotMeta();\n\n if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Spot metadata cache write',\n )\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\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 lifecycleGeneration = this.#lifecycleGeneration;\n const now = Date.now();\n\n // Return cached data if still valid (uses unified state timestamp for TTL)\n if (\n this.#dexDiscoveryCache.state &&\n now - this.#dexDiscoveryCache.state.timestamp <\n HIP3_FEE_CONFIG.PerpDexsCacheTtlMs\n ) {\n const raw = this.#dexDiscoveryCache.state.raw as ExtendedPerpDex[];\n this.#deps.debugLogger.log(\n '[getCachedPerpDexs] Using cached perpDexs data',\n {\n age: `${Math.round((now - this.#dexDiscoveryCache.state.timestamp) / 1000)}s`,\n count: raw.length,\n },\n );\n return raw;\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 if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Perp DEX cache write',\n )\n ) {\n // Atomically update unified state (raw + validated + timestamp)\n this.#dexDiscoveryCache.update(perpDexs);\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\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 #getApprovedBuilderKey(\n network: string,\n userAddress: string,\n builderAddress: string,\n ): string {\n return `${this.#getCacheKey(network, userAddress)}:${builderAddress.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 // TAT-3304: Following the USDH sunset, only USDC-collateral HIP-3 DEXs\n // are supported for trading. Gate non-USDC-collateral DEXs out of market\n // discovery entirely (regardless of skipFilters) so their markets can\n // never be surfaced to trade, even via an allowlist entry naming the DEX.\n if (dex !== null && !(await this.#isUsdcCollateralDex(dex))) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Filtering out non-USDC-collateral HIP-3 DEX from market discovery',\n { dex },\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 USDC as its collateral token\n *\n * TAT-3304: Following the USDH sunset, only USDC-collateral DEXs are\n * supported for trading. This gate filters non-USDC-collateral DEXs\n * (e.g. the now-sunset USDH) out of market discovery and blocks order\n * placement, replacing the previous USDH-specific auto-swap path.\n *\n * Fails closed: only returns true when the collateral token index\n * positively resolves to USDC against spot metadata. If the token can't\n * be resolved (e.g. missing/stale spot metadata), the DEX is treated as\n * non-USDC and gated out, since we can't otherwise verify the USDC-only\n * requirement. This only affects HIP-3 DEXs — main-DEX trading (dex ===\n * null) never calls this gate.\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 #isUsdcCollateralDex(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 isUsdc = collateralToken?.name === USDC_SYMBOL;\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Checked DEX collateral type',\n {\n dexName,\n collateralTokenIndex: meta.collateralToken,\n collateralTokenName: collateralToken?.name,\n isUsdc,\n },\n );\n\n return isUsdc;\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 update #dexDiscoveryCache here — leave state 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 #dexDiscoveryCache here.\n // That state is owned exclusively by #dexDiscoveryCache.update(); writing a\n // fallback here would prevent subsequent callers from retrying perpDexs().\n const allPerpDexs = this.#dexDiscoveryCache.state?.raw ?? [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 !this.#hip3Enabled || Boolean(this.#dexDiscoveryCache.state?.validated),\n );\n this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset mapping rebuild',\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 // Check if already cached (e.g., by getMarketDataWithPrices running in parallel)\n const cachedMeta = this.#cachedMetaByDex.get(dex);\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.#cacheDexMetadata({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\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 this.#assertCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Asset mapping rebuild',\n );\n // Build mapping with DEX prefixes for HIP-3 DEXs using the utility function\n this.#symbolToAssetId.clear();\n let dexDiscoveryComplete = this.#dexDiscoveryCache.state !== 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?.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.#userFeeResolution = undefined;\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 * Set the resolved fee and its attribution source for the next operation.\n *\n * @param resolution - Unified fee resolution, or undefined to clear it.\n */\n setUserFeeResolution(resolution: PerpsFeeResolution | undefined): void {\n this.#userFeeResolution = resolution;\n this.#userFeeDiscountBips = resolution?.discountBips;\n\n this.#deps.debugLogger.log('HyperLiquid: Fee resolution context updated', {\n source: resolution?.source,\n discountBips: resolution?.discountBips,\n isActive: resolution !== 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 * @param resolvedDexs - Optional pre-resolved DEX list.\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 resolvedDexs?: (string | null)[],\n ): Promise<DexQueryResponse<TResult>> {\n const enabledDexs = resolvedDexs ?? (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 // \"User or API Wallet 0x... does not exist.\" carries the user's address, so\n // it cannot be matched by the static substring table below. It means the\n // wallet has no Hyperliquid account yet — surface an actionable code the\n // client can translate (\"fund your account\") instead of leaking the raw\n // exchange string to the UI and to failed-trade analytics.\n if (isHyperLiquidUserNotFoundError(error)) {\n return new PerpsControllerError(\n PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND,\n PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND,\n );\n }\n\n for (const [pattern, code] of Object.entries(this.#errorMappings)) {\n if (message.toLowerCase().includes(pattern.toLowerCase())) {\n return new PerpsControllerError(code, 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 * Map a rejection the venue reported in a status entry rather than threw,\n * handling a rejected agent the way a thrown rejection is.\n *\n * @param message - The status entry's error.\n * @param answer - The venue answer with the entry.\n * @returns The mapped error.\n */\n async #mapStatusError(message: string, answer: unknown): Promise<Error> {\n const error = createStatusError(message, answer);\n return (await this.#classifySignerFailure(error)) ?? this.#mapError(error);\n }\n\n /**\n * The signer failure a venue reported in cancel status entries rather than\n * threw. One signature covers the whole request, so it is classified (and\n * reported to the host) once for all its entries.\n *\n * @param statuses - The status entries.\n * @param answer - The venue answer with the entries.\n * @returns `KEYRING_LOCKED` for a signer failure, else undefined.\n */\n async #classifyStatusSignerFailure(\n statuses: unknown[],\n answer: unknown,\n ): Promise<Error | undefined> {\n for (const status of statuses) {\n if (isStatusObject(status) && typeof status.error === 'string') {\n const signerFailure = await this.#classifySignerFailure(\n createStatusError(status.error, answer),\n );\n if (signerFailure) {\n return signerFailure;\n }\n }\n }\n return undefined;\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 * @param errorTags - Optional bounded tags used by error dashboards\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 errorTags?: PerpsErrorTags,\n ): PerpsLoggerOptions {\n return createPerpsErrorContext({\n contextName: 'HyperLiquidProvider',\n method,\n provider: this.protocolId,\n network: this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet',\n errorTags,\n data: extra,\n });\n }\n\n #isMappedAccountModeExchangeError(error: Error): boolean {\n return (\n error.message === PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED ||\n error.message === PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE\n );\n }\n\n async #getTradingErrorContext(\n method: string,\n error: Error,\n extra?: Record<string, unknown>,\n errorTags?: PerpsErrorTags,\n ): Promise<{\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n }> {\n const contextExtra = { ...extra };\n if (this.#isMappedAccountModeExchangeError(error)) {\n try {\n const userAddress =\n await this.#walletService.getUserAddressWithDefault();\n const abstractionMode =\n this.#subscriptionService.getCachedAbstractionMode(userAddress);\n if (abstractionMode) {\n contextExtra[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE] = abstractionMode;\n }\n } catch {\n // Best-effort context enrichment only.\n }\n }\n return this.#getErrorContext(method, contextExtra, errorTags);\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 * @param builder - Builder address to query.\n * @param userAddress - Account whose approval should be queried.\n * @returns Current max fee rate or null if not approved\n */\n async #checkBuilderFeeApproval(\n builder: string,\n userAddress: string,\n ): Promise<number | null> {\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\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 * @param params - Builder fee setup context.\n * @param params.network - HyperLiquid network for the approval.\n * @param params.userAddress - Account that owns the approval.\n * @param params.builderAddress - Builder address being approved.\n */\n async #ensureBuilderFeeApproval(\n params: BuilderFeeSetupContext,\n ): Promise<void> {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const { network, userAddress, builderAddress } = params;\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\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 repeated signing prompts\n // while browsing.\n const globalCached = PerpsSigningCache.getBuilderFee(network, userAddress);\n if (globalCached?.attempted && globalCached?.success) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Using global cache (prevents hardware wallet prompt spam)',\n { network, success: globalCached.success },\n );\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\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 const completedApproval = PerpsSigningCache.getBuilderFee(\n network,\n userAddress,\n );\n if (completedApproval?.attempted && completedApproval.success) {\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\n }\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 && recheckCache?.success) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Completed by another provider',\n { network },\n );\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\n completeInFlight();\n return;\n }\n\n const { isApproved, requiredDecimal } = await this.#checkBuilderFeeStatus(\n builderAddress,\n userAddress,\n );\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\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 this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\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 builderAddress,\n userAddress,\n );\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 // The approval is already confirmed on-chain. Preserve that fact for\n // the next provider lifecycle even if this instance became stale while\n // the approval request was in flight.\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: true,\n });\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Builder fee approval',\n );\n\n // Cache success in the current instance after the lifecycle check.\n this.#builderFeeCheckCache.set(cacheKey, true);\n this.#approvedBuilderAddresses.add(\n this.#getApprovedBuilderKey(network, userAddress, builderAddress),\n );\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 (\n ensureError(error, 'HyperLiquidProvider.ensureBuilderFeeApproval')\n .message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE\n ) {\n completeInFlight();\n return;\n }\n\n // HyperLiquid wraps wallet signing failures and preserves KEYRING_LOCKED\n // in `cause`, so classify the full chain and leave retry caches empty.\n // The caller reports it as retryable.\n if (isKeyringLockedError(error)) {\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Keyring locked, will retry later',\n );\n completeInFlight();\n throw error;\n }\n\n // Record failure — will be retried on next trading operation\n PerpsSigningCache.setBuilderFee(network, userAddress, {\n attempted: true,\n success: false,\n });\n\n this.#deps.debugLogger.log(\n '[ensureBuilderFeeApproval] Failed, will retry on next trading operation',\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 * Approve the dedicated subscription builder outside order submission.\n * Failure is non-blocking: order construction will use the ordinary builder\n * at the standard fee until a later approval succeeds.\n *\n * @deprecated ADR 0064 replaced the dedicated subscription builder with cloid\n * marking on the standard builder, so nothing reads this approval any more —\n * {@link #getBuilderOrderContext} never selects the subscription builder\n * address. The approval machinery is kept intact, unreachable, so the\n * previous design can be restored cheaply if cloid marking does not hold up\n * in shadow mode; remove it, the builder-address config, and\n * {@link #getSubscriptionBuilderAddress} once it does.\n * @returns Whether the builder is approved for the current account.\n */\n async approveSubscriptionBuilderFee(): Promise<boolean> {\n const approvalEpoch = this.#subscriptionBuilderApprovalEpoch;\n await this.#ensureClientsInitialized();\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return false;\n }\n const isTestnet = this.#clientService.isTestnetMode();\n const network = isTestnet ? 'testnet' : 'mainnet';\n const builderAddress = this.#getSubscriptionBuilderAddress(isTestnet);\n if (!builderAddress) {\n return false;\n }\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const key = this.#getApprovedBuilderKey(\n network,\n userAddress,\n builderAddress,\n );\n if (this.#approvedBuilderAddresses.has(key)) {\n return true;\n }\n\n const pending = this.#pendingBuilderFeeApprovals.get(key);\n if (pending) {\n try {\n await pending;\n return this.#approvedBuilderAddresses.has(key);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Subscription builder approval unavailable',\n error,\n );\n return false;\n }\n }\n\n const approval = (async (): Promise<void> => {\n const currentApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n if (\n currentApproval !== null &&\n currentApproval >= BUILDER_FEE_CONFIG.MaxFeeDecimal\n ) {\n this.#approvedBuilderAddresses.add(key);\n return;\n }\n\n const exchangeClient = this.#clientService.getExchangeClient();\n await exchangeClient.approveBuilderFee({\n builder: builderAddress,\n maxFeeRate: BUILDER_FEE_CONFIG.MaxFeeRate,\n });\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n const afterApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\n if (approvalEpoch !== this.#subscriptionBuilderApprovalEpoch) {\n return;\n }\n if (\n afterApproval === null ||\n afterApproval < BUILDER_FEE_CONFIG.MaxFeeDecimal\n ) {\n throw new Error(\n '[HyperLiquidProvider] Subscription builder approval verification failed',\n );\n }\n this.#approvedBuilderAddresses.add(key);\n })();\n this.#pendingBuilderFeeApprovals.set(key, approval);\n\n try {\n await approval;\n return this.#approvedBuilderAddresses.has(key);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Subscription builder approval unavailable',\n error,\n );\n return false;\n } finally {\n if (this.#pendingBuilderFeeApprovals.get(key) === approval) {\n this.#pendingBuilderFeeApprovals.delete(key);\n }\n }\n }\n\n /**\n * Check if builder fee is approved for the current user\n *\n * @param builderAddress - Builder address to query.\n * @param userAddress - Account whose approval should be queried.\n * @returns Object with approval status and current rate\n */\n async #checkBuilderFeeStatus(\n builderAddress: string,\n userAddress: string,\n ): Promise<{\n isApproved: boolean;\n currentRate: number | null;\n requiredDecimal: number;\n }> {\n const currentApproval = await this.#checkBuilderFeeApproval(\n builderAddress,\n userAddress,\n );\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.withdrawableBalance);\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.#dexDiscoveryCache.state?.validated?.filter(\n (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 // The signer could not sign the transfer: retryable, not a defect.\n if (result.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n throw new Error(PERPS_ERROR_CODES.KEYRING_LOCKED);\n }\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 // Use the same target-DEX freshness policy as position-management actions;\n // a stale aggregate can over- or under-fund the temporary HIP-3 transfer.\n const positions = await this.#getPositionsForOperation(dexName);\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 spendableBalance >= 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 * @returns Whether the balance check and any required transfer succeeded.\n * @private\n */\n async #handleHip3PostOrderRebalance(\n params: Hip3TransferContext,\n ): Promise<boolean> {\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 spendableBalance: postOrderBalance.toFixed(2),\n desiredBuffer: desiredBuffer.toFixed(2),\n excessAmount: excessAmount.toFixed(2),\n destinationDex: transferInfo.sourceDex,\n },\n );\n\n const transferResult = await this.transferBetweenDexs({\n sourceDex: dexName,\n destinationDex: transferInfo.sourceDex,\n amount: excessAmount.toFixed(USDC_DECIMALS),\n });\n if (!transferResult.success) {\n // The signer could not sign the transfer: retryable, not a defect.\n if (transferResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Auto-rebalance not signed - funds remain on HIP-3 DEX',\n { dex: dexName, excessAmount },\n );\n return false;\n }\n throw new Error(\n transferResult.error ?? PERPS_ERROR_CODES.TRANSFER_FAILED,\n );\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 return true;\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(\n 'placeOrder:autoRebalance',\n {\n dex: dexName,\n excessAmount: excessAmount.toFixed(2),\n note: 'Auto-rebalance failed - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n return false;\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 return true;\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(\n 'placeOrder:postOrderBalanceCheck',\n {\n dex: dexName,\n note: 'Failed to verify post-order balance for auto-rebalance',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n return false;\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: Hip3TransferContext): 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 if (rollbackResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {\n // The signer could not sign the transfer: retryable, not a defect.\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Rollback not signed - funds remain on HIP-3 DEX',\n { dex: dexName, amount: transferInfo.amount },\n );\n } else {\n this.#deps.logger.error(\n new Error(rollbackResult.error ?? 'Rollback transfer failed'),\n this.#getErrorContext(\n 'placeOrder:rollback',\n {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback failed - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\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(\n 'placeOrder:rollback:exception',\n {\n dex: dexName,\n amount: transferInfo.amount.toFixed(USDC_DECIMALS),\n note: 'Rollback threw exception - funds remain on HIP-3 DEX',\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\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 * Validate an explicit mode before trading setup can sign or change leverage.\n * Mode belongs to the asset, so a new order cannot change an existing book.\n *\n * @param params - Requested order and collateral mode.\n * @param assetInfo - Venue capabilities for the requested market.\n */\n async #validateMarginMode(\n params: OrderParams,\n assetInfo: MetaResponse['universe'][number],\n ): Promise<void> {\n if (params.marginMode === undefined) {\n return;\n }\n if (!Number.isInteger(params.leverage) || (params.leverage ?? 0) < 1) {\n throw new Error(PERPS_ERROR_CODES.ORDER_LEVERAGE_INVALID);\n }\n if (\n params.marginMode === 'cross' &&\n !this.#isCrossMarginSupported(params.symbol, assetInfo)\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED);\n }\n const lock = await this.#readMarginModeLock(params.symbol);\n if (lock && lock.marginMode !== params.marginMode) {\n throw new Error(\n lock.reason === 'position'\n ? PERPS_ERROR_CODES.ORDER_MARGIN_MODE_POSITION_OPEN\n : PERPS_ERROR_CODES.ORDER_MARGIN_MODE_ORDER_OPEN,\n );\n }\n }\n\n /**\n * Read the margin mode the venue currently binds to an asset. An open\n * position fixes it first; otherwise a resting order or active TWAP fixes\n * the mode reported by the asset's leverage data.\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The locked mode and its cause, or null when nothing locks it.\n * @throws When the target DEX positions cannot be read, or when the\n * selected account changes during the read.\n */\n async #readMarginModeLock(\n symbol: string,\n ): Promise<{ marginMode: MarginMode; reason: MarginModeLockReason } | null> {\n const { dex: dexName } = parseAssetName(symbol);\n // Each venue read resolves the selected account on its own. Pin one\n // account for the whole read so positions and orders from different\n // accounts can never be combined.\n const user = await this.#walletService.getUserAddressWithDefault();\n const assertSameAccount = async (): Promise<void> => {\n const current = await this.#walletService.getUserAddressWithDefault();\n if (current.toLowerCase() !== user.toLowerCase()) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n };\n const { answered, positions } = await this.#queryDexPositions(dexName);\n if (!answered) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n await assertSameAccount();\n const position = positions.find((item) => item.symbol === symbol);\n if (position) {\n return { marginMode: position.leverage.type, reason: 'position' };\n }\n const infoClient = this.#clientService.getInfoClient();\n const [orders, twapHistory] = await Promise.all([\n this.#fetchOpenOrders({ dexName }),\n infoClient.twapHistory({ user }),\n ]);\n await assertSameAccount();\n // Native TWAP schedules are absent from frontendOpenOrders before a slice\n // rests or fills. Read history directly: getTwapOrders can rebalance HIP-3\n // collateral, which must not run as part of pre-sign validation.\n const latestTwaps = new Map<\n HyperLiquidTwapHistoryEntry['twapId'],\n HyperLiquidTwapHistoryEntry\n >();\n for (const entry of twapHistory) {\n if (entry.state.coin !== symbol) {\n continue;\n }\n const previous = latestTwaps.get(entry.twapId);\n if (\n !previous ||\n normalizeTwapHistoryTimestamp(entry.time) >=\n normalizeTwapHistoryTimestamp(previous.time)\n ) {\n latestTwaps.set(entry.twapId, entry);\n }\n }\n const hasActiveTwap = [...latestTwaps.values()].some((entry) => {\n switch (entry.status.status) {\n case HyperLiquidTwapLifecycleStatus.Finished:\n case HyperLiquidTwapLifecycleStatus.Stopped:\n case HyperLiquidTwapLifecycleStatus.Terminated:\n case HyperLiquidTwapLifecycleStatus.Failed:\n return false;\n default:\n // Waiting and future venue states are not proof of termination.\n return true;\n }\n });\n if (orders.some((order) => order.coin === symbol) || hasActiveTwap) {\n const asset = await infoClient.activeAssetData({\n user,\n coin: symbol,\n });\n await assertSameAccount();\n return { marginMode: asset.leverage.type, reason: 'open_order' };\n }\n return null;\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 const marginMode =\n params.marginMode ?? (await this.#resolveDefaultMarginMode(symbol));\n\n this.#deps.debugLogger.log('Updating leverage before order:', {\n symbol,\n assetId,\n requestedLeverage: leverage,\n leverageType: marginMode,\n });\n\n const exchangeClient = this.#clientService.getExchangeClient();\n const leverageResult = await exchangeClient.updateLeverage({\n asset: assetId,\n isCross: marginMode === 'cross',\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 * Resolve the margin mode for an order that omits one. HyperLiquid refuses\n * to switch mode while a position is open, so an open position's mode wins\n * over the isolated default (e.g. flipping a Cross position).\n *\n * @param symbol - Market symbol, including its DEX route when applicable.\n * @returns The open position's mode, or isolated when there is none or it\n * cannot be read.\n */\n async #resolveDefaultMarginMode(symbol: string): Promise<MarginMode> {\n const { dex: dexName } = parseAssetName(symbol);\n try {\n const positions = await this.#getPositionsForOperation(dexName ?? '');\n return (\n positions.find((position) => position.symbol === symbol)?.leverage\n .type ?? 'isolated'\n );\n } catch (error) {\n this.#deps.debugLogger.log(\n 'Open position margin mode unavailable: defaulting to isolated',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.resolveDefaultMarginMode',\n ).message,\n },\n );\n return 'isolated';\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 // TAT-3304: Only USDC-collateral HIP-3 DEXs are supported for trading.\n // Following the USDH sunset, reject orders on any non-USDC-collateral\n // DEX here instead of attempting the (now-removed) USDH auto-swap path.\n // Market discovery (#fetchMarketsForDex) already filters such DEXs out,\n // so this is a defense-in-depth check against stale caches or a\n // misconfigured allowlist entry.\n const isUsdcDex = await this.#isUsdcCollateralDex(dexName);\n if (!isUsdcDex) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Rejecting order for non-USDC-collateral DEX',\n {\n dexName,\n symbol,\n },\n );\n\n throw new Error(PERPS_ERROR_CODES.UNSUPPORTED_COLLATERAL);\n }\n\n if (this.#useUnifiedAccount) {\n this.#deps.debugLogger.log('Using Unified Account (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.#useUnifiedAccount = 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 const builder = params.chargesMetamaskBuilderFee\n ? await this.#getBuilderOrderContext(\n params.builderFeeSetupContext ??\n (await this.#ensureBuilderFeeSetup()),\n )\n : undefined;\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: this.#applySubscriptionCloid(orders),\n grouping,\n ...(builder && { builder }),\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 // The main order's `s` is the final normalized size sent to the exchange\n // (post precision rounding, USD recalculation, and $10-minimum retry —\n // the retry recurses through placeOrder so this reflects the last\n // submission). TradingService uses it to classify partial fills. The SDK\n // types `s` as `string | number`, so normalize to the string OrderResult\n // shape while preserving `undefined` when no order was built.\n submittedSize:\n orders[0]?.s === undefined ? undefined : String(orders[0].s),\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 async #handleOrderError(\n params: HandleOrderErrorParams,\n ): Promise<OrderResult> {\n const { error, symbol, orderType, isBuy, reportFailure } = params;\n const signerFailure = await this.#handleSignerFailure(error, 'placeOrder', {\n symbol,\n orderType,\n isBuy,\n });\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n const mappedError = this.#mapError(error);\n const isExpectedAccountState = isHyperLiquidUserNotFoundError(error);\n\n // A wallet with no Hyperliquid account is an expected pre-account state,\n // not an app defect — same policy already applied to every other\n // user-scoped exchange write in this provider. Keep it out of Sentry; the\n // failure is still reported to the caller (and to trade analytics) via the\n // mapped EXCHANGE_ACCOUNT_NOT_FOUND code below.\n if (isExpectedAccountState) {\n this.#deps.debugLogger.log(\n '[handleOrderError] Wallet has no Hyperliquid account, order cannot be placed',\n { symbol, orderType, isBuy },\n );\n } else if (reportFailure) {\n this.#deps.logger.error(\n mappedError,\n await this.#getTradingErrorContext(\n 'placeOrder',\n mappedError,\n {\n symbol,\n orderType,\n isBuy,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.PlaceOrder,\n },\n ),\n );\n }\n\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 input - Order parameters\n * @param retryCount - Internal retry counter to prevent infinite loops (default: 0)\n * @param reportFailure - Whether this call owns provider-level error reporting.\n * @returns A promise that resolves to the result.\n */\n async placeOrder(\n input: OrderParams,\n retryCount = 0,\n reportFailure = true,\n ): Promise<OrderResult> {\n const deferProviderErrorReport = input.deferProviderErrorReport === true;\n const params = { ...input };\n delete params.deferProviderErrorReport;\n const shouldReportFailure = reportFailure && !deferProviderErrorReport;\n if (params.expectedScaleLadder !== undefined) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE,\n };\n }\n // Hoisted so the retry path in the catch block can use the fetched price\n // even when the caller (e.g. flipPosition) omits currentPrice from params.\n let effectivePrice: number | undefined;\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 triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n tpslLinkage: params.tpslLinkage,\n grouping: params.grouping,\n timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n ...pickStrategyParams(params),\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n // Strategy placements expand into an execution schedule rather than a\n // single order, so they leave the shared path here — before the order\n // array, the HIP-3 transfer, and the atomic single-order submit, none of\n // which describe what a TWAP, a ladder, or a chase does.\n if (isStrategyOrderType(params.orderType)) {\n return await this.#placeStrategyOrder(params, params.orderType);\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 before validation so price-less\n // callers (e.g. flipPosition) can validate against the live fetched price.\n const { assetInfo, currentPrice, meta } = await this.#getAssetInfo({\n symbol: params.symbol,\n dexName,\n });\n\n // A price or partial size that rounds away at the asset precision is\n // caught here, as soon as szDecimals is known and before anything is\n // committed: the signing prompts in #ensureReadyForTrading, the leverage\n // change in #prepareAssetForTrading, and the HIP-3 margin transfer all\n // come later.\n const precision = validateOrderPrecision({\n triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n szDecimals: assetInfo.szDecimals,\n });\n if (!precision.isValid) {\n throw new Error(precision.error);\n }\n\n // Allow override with UI-provided price (optimization to avoid API call).\n 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 // Validate order at provider level (enforces USD validation rules).\n // Pass effectivePrice so price-less market orders (e.g. flipPosition)\n // validate against the live fetched price instead of failing with\n // ORDER_PRICE_REQUIRED.\n await this.#validateOrderBeforePlacement({\n ...params,\n currentPrice: effectivePrice,\n });\n\n // Ensure provider is ready for trading (includes signing operations).\n // Kept after validation so invalid orders never trigger signature prompts\n // (builder-fee approval, DEX abstraction enablement, etc.).\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const builderFeeSetupContext = await this.#ensureReadyForTrading({\n requiresBuilderFee: chargesMetamaskBuilderFee,\n });\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 // Normalize the deprecated decimal `slippage` to bps once so both the\n // price-staleness check and the limit-price calc see the same value.\n const normalizedMaxSlippageBps =\n params.maxSlippageBps ??\n (typeof params.slippage === 'number'\n ? Math.round(params.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n\n const { finalPositionSize } = calculateFinalPositionSize({\n usdAmount: params.usdAmount,\n size: params.size,\n currentPrice: effectivePrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: normalizedMaxSlippageBps,\n szDecimals: assetInfo.szDecimals,\n leverage: params.leverage,\n reduceOnly: params.reduceOnly,\n });\n\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 triggerPrice: params.triggerPrice,\n maxSlippageBps: normalizedMaxSlippageBps,\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 marginMode: params.marginMode,\n });\n\n // 6. Handle HIP-3 balance management (if applicable)\n const isHip3Order = dexName !== null;\n let transferInfo: Hip3TransferInfo | 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 timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n szDecimals: assetInfo.szDecimals,\n // The provider-agnostic linkage wins; `grouping` is the deprecated\n // HyperLiquid-shaped spelling kept for existing callers.\n grouping: params.tpslLinkage\n ? adaptTpslLinkageToGrouping(params.tpslLinkage)\n : 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 chargesMetamaskBuilderFee,\n builderFeeSetupContext,\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 // Reduce-only orders are excluded. The retry works by growing the order\n // 1.5%, which a close cannot do: a full close already submits the whole\n // position, and a partial close is capped at the size the caller asked to\n // close, so the retry would either be rejected as \"Reduce only order would\n // increase position\" or resubmit an identical order. Surfacing the\n // minimum-value error names the real problem instead.\n //\n // Strategy placements are excluded for the same reason in a different\n // shape: the minimum applies to each TWAP slice and each ladder rung, not\n // to the total, so growing the total by 1.5% does not clear it.\n if (\n isMinimumOrderError &&\n retryCount === 0 &&\n !params.reduceOnly &&\n !isStrategyOrderType(params.orderType)\n ) {\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 (effectivePrice) {\n // Size-based order: calculate USD from size and adjust.\n // Use the hoisted effectivePrice (fetched live price) so callers that\n // omit currentPrice (e.g. flipPosition) can still recover from the\n // $10-minimum edge case.\n const sizeValue = parseFloat(params.size);\n const estimatedUsd = sizeValue * effectivePrice;\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 await this.#handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n reportFailure: shouldReportFailure,\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 // This USD amount was derived from the effective price solely to\n // grow an exact-size order past the venue minimum. Preserve the\n // original exact-size semantics instead of applying its unrelated\n // calculation snapshot to the retry. Genuine USD-sized orders keep\n // their snapshot guard.\n priceAtCalculation: params.usdAmount\n ? params.priceAtCalculation\n : undefined,\n },\n 1, // Retry count = 1, prevents further retries\n shouldReportFailure,\n );\n }\n\n return await this.#handleOrderError({\n error,\n symbol: params.symbol,\n orderType: params.orderType,\n isBuy: params.isBuy,\n reportFailure: shouldReportFailure,\n });\n }\n }\n\n /**\n * Dispatch a strategy placement to the handler that owns it.\n *\n * @param params - Order parameters, already validated.\n * @param orderType - The strategy type, narrowed by the caller.\n * @returns A promise that resolves to the result.\n */\n async #placeStrategyOrder(\n params: OrderParams,\n orderType: StrategyOrderType,\n ): Promise<OrderResult> {\n // Captured before the shared preamble, not after it: that preamble awaits\n // asset info, validation, trading readiness and a leverage update, and a\n // disconnect during any of them has to be seen before or after submission.\n const generation = this.#strategyGeneration;\n\n if (orderType !== 'chase') {\n const context = await this.#prepareStrategyPlacement(params);\n return await this.#submitPreparedStrategy(params, context, async () => {\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n return orderType === 'twap'\n ? await this.#placeTwapOrder(params, context, generation)\n : await this.#placeScaleOrder(params, context, generation);\n });\n }\n\n if (this.#chasePlacementBlockers > 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n // The chase slot is claimed before the preamble, not after it: the preamble\n // completes the signing setup and can change the asset's leverage, and a\n // request that is going to be refused for exceeding the venue's cap must\n // not cost either. Reserved in the same synchronous step it is checked, so\n // concurrent placements cannot both see room during the round trips that\n // follow.\n const activeChases = [...this.#chaseSessions.values()].filter(\n (session) => session.active,\n ).length;\n if (\n activeChases + this.#chasePlacementsInFlight >=\n CHASE_ORDER_CONFIG.MaxActiveSessions\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_LIMIT_REACHED);\n }\n this.#chasePlacementsInFlight += 1;\n this.#pauseChaseTicksForPlacement();\n\n let settlePlacement: (() => void) | undefined;\n const placementWaiter = new Promise<void>((resolve) => {\n settlePlacement = resolve;\n });\n this.#chasePlacementWaiters.add(placementWaiter);\n\n try {\n await this.#chaseTickQueue;\n const context = await this.#prepareStrategyPlacement(params);\n return await this.#submitPreparedStrategy(\n params,\n context,\n async () => await this.#startChaseSession(params, context, generation),\n );\n } finally {\n settlePlacement?.();\n this.#chasePlacementWaiters.delete(placementWaiter);\n this.#chasePlacementsInFlight -= 1;\n if (this.#chasePlacementsInFlight === 0) {\n this.#resumeChaseTicksAfterPlacement();\n }\n }\n }\n\n /**\n * Submit a prepared strategy and settle any manual HIP-3 collateral move.\n *\n * Scale and Chase leave regular orders or fills on the venue, so the normal\n * HIP-3 post-order balance check can return any unreserved excess. Native\n * TWAP executes future slices, so its transferred collateral stays on the\n * routed DEX until cancellation confirms the schedule has stopped.\n *\n * @param params - Strategy order parameters.\n * @param context - Prepared placement and HIP-3 transfer context.\n * @param submit - Venue submission.\n * @returns The strategy placement result.\n */\n async #submitPreparedStrategy(\n params: OrderParams,\n context: StrategyPlacementContext,\n submit: () => Promise<OrderResult>,\n ): Promise<OrderResult> {\n const { dexName, network, transferInfo, userAddress } = context;\n let result: OrderResult;\n\n try {\n result = await submit();\n } catch (error) {\n if (dexName && transferInfo) {\n await this.#handleHip3OrderRollback({ dexName, transferInfo });\n }\n throw error;\n }\n\n const resultFilledSize = new BigNumber(result.filledSize ?? 0);\n const hasVenueExposure =\n result.success === true ||\n result.orderId !== undefined ||\n (result.childOrderIds?.length ?? 0) > 0 ||\n (resultFilledSize.isFinite() && resultFilledSize.gt(0));\n if (dexName && transferInfo && !hasVenueExposure) {\n await this.#handleHip3OrderRollback({ dexName, transferInfo });\n return result;\n }\n\n if (params.orderType === 'twap' && result.orderId) {\n this.#trackedTwapOrders.set(\n getTwapOrderScopeKey({\n network,\n userAddress,\n orderId: result.orderId,\n }),\n {\n symbol: params.symbol,\n ...(dexName && transferInfo\n ? { hip3Transfer: { dexName, transferInfo } }\n : {}),\n },\n );\n return result;\n }\n\n if (\n params.orderType === 'chase' &&\n result.success &&\n result.orderId &&\n dexName &&\n transferInfo\n ) {\n const session = this.#chaseSessions.get(result.orderId);\n if (session) {\n session.hip3Transfer = { dexName, transferInfo };\n return result;\n }\n }\n\n if (params.orderType === 'chase' && hasVenueExposure) {\n // A stale placement can fail after its child rests and the best-effort\n // retraction is refused. With no session left to own that child, keep\n // manual HIP-3 collateral on its DEX until the caller cancels the\n // reported exchange ID.\n return result;\n }\n\n if (dexName && transferInfo) {\n await this.#handleHip3PostOrderRebalance({ dexName, transferInfo });\n }\n\n return result;\n }\n\n /**\n * Run the shared preamble every strategy placement needs.\n *\n * Mirrors the single-order path's own preamble — validate against a live\n * price, complete the signing setup, resolve the asset ID, apply leverage —\n * so a strategy order is held to the same rules as an ordinary one.\n *\n * @param params - Order parameters.\n * @returns The asset and sizing context the strategy handlers submit with.\n */\n async #prepareStrategyPlacement(\n params: OrderParams,\n ): Promise<StrategyPlacementContext> {\n const { dex: dexName } = parseAssetName(params.symbol);\n\n const { assetInfo, currentPrice, meta } = await this.#getAssetInfo({\n symbol: params.symbol,\n dexName,\n });\n\n const effectivePrice =\n params.currentPrice && params.currentPrice > 0\n ? params.currentPrice\n : currentPrice;\n\n await this.#validateOrderBeforePlacement({\n ...params,\n currentPrice: effectivePrice,\n });\n\n const normalizedMaxSlippageBps =\n params.maxSlippageBps ??\n (typeof params.slippage === 'number'\n ? Math.round(params.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n\n const { finalPositionSize } = calculateFinalPositionSize({\n usdAmount: params.usdAmount,\n size: params.size,\n currentPrice: effectivePrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: normalizedMaxSlippageBps,\n szDecimals: assetInfo.szDecimals,\n leverage: params.leverage,\n reduceOnly: params.reduceOnly,\n });\n\n const formattedSize = formatHyperLiquidSize({\n size: finalPositionSize,\n szDecimals: assetInfo.szDecimals,\n });\n\n // Everything below is checked here, before anything is signed: it needs\n // `szDecimals`, which only arrives with the asset info above, and these are\n // caller mistakes that must not cost a leverage change or a signing prompt\n // first.\n const ladder =\n params.orderType === 'scale'\n ? this.#buildScaleLadder({\n params,\n szDecimals: assetInfo.szDecimals,\n finalPositionSize,\n })\n : undefined;\n\n // `validateOrder` applied the venue minimum to the notional the caller\n // asked for; this applies it to the size actually being submitted. The two\n // differ whenever sizing floors onto the grid rather than rounding up to\n // meet the requested USD — which is exactly what a reduce-only order does,\n // since the venue rejects a close larger than the position. A boundary\n // amount can therefore clear the check the caller sees and still arrive\n // under the minimum the venue charges against what it receives.\n if (params.orderType === 'twap' || params.orderType === 'chase') {\n const submittedNotional = parseFloat(formattedSize) * effectivePrice;\n const minimumNotional =\n params.orderType === 'twap'\n ? HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd\n : this.#getMinimumOrderSize();\n\n if (submittedNotional < minimumNotional) {\n throw new Error(\n params.orderType === 'twap'\n ? PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL\n : PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n );\n }\n }\n\n // Kept after validation so an invalid strategy order never triggers the\n // signature prompts in trading setup — same ordering as `placeOrder`.\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const builderFeeSetupContext = chargesMetamaskBuilderFee\n ? await this.#ensureReadyForTrading({ requiresBuilderFee: true })\n : await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName,\n meta,\n });\n\n await this.#prepareAssetForTrading({\n symbol: params.symbol,\n assetId,\n leverage: params.leverage,\n marginMode: params.marginMode,\n });\n\n const builder = builderFeeSetupContext\n ? await this.#getBuilderOrderContext(builderFeeSetupContext)\n : undefined;\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const userAddress =\n builderFeeSetupContext?.userAddress ??\n (await this.#walletService.getUserAddressWithDefault());\n\n let transferInfo: Hip3TransferInfo | null = null;\n if (dexName) {\n const orderPrice =\n ladder === undefined\n ? effectivePrice\n : Math.max(...ladder.prices.map(Number.parseFloat));\n const hip3Result = await this.#handleHip3PreOrder({\n dexName,\n symbol: params.symbol,\n orderPrice,\n positionSize: parseFloat(formattedSize),\n leverage: params.leverage ?? assetInfo.maxLeverage ?? 1,\n isBuy: params.isBuy,\n maxLeverage: assetInfo.maxLeverage,\n });\n transferInfo = hip3Result.transferInfo;\n }\n\n return {\n assetId,\n szDecimals: assetInfo.szDecimals,\n formattedSize,\n ladder,\n builder,\n dexName,\n network,\n transferInfo,\n userAddress,\n };\n }\n\n /**\n * The venue's minimum value for a single order, in USD.\n *\n * @returns The minimum for the network this provider is pointed at.\n */\n #getMinimumOrderSize(): number {\n return this.#clientService.isTestnetMode()\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n }\n\n /**\n * Build a scale placement's rungs and check them as the venue will see them.\n *\n * Three things can only be decided once the asset's precision is known, and\n * all of them are decided here rather than after the order is on its way:\n *\n * - **Prices collapse.** Two distinct rung prices can round onto the same\n * venue-formatted price, which would submit several orders at one price\n * instead of a ladder spanning the requested range.\n * - **Slices are not the average.** `splitScaleSizes` floors onto the size\n * grid, and a `scaleSkew` weights the rungs along the ladder on top of that,\n * so no rung carries the average slice the pre-network check in\n * `validateOrder` approximates with.\n * - **The cheapest rung decides.** Each rung is an independent order, so the\n * venue applies its per-order minimum to the smallest slice at the lowest\n * price, not to the ladder's total.\n *\n * @param options - Ladder inputs.\n * @param options.params - Order parameters.\n * @param options.szDecimals - The asset's size and price precision.\n * @param options.finalPositionSize - Total size to spread across the rungs.\n * @returns The rungs, exactly as they will be submitted.\n */\n #buildScaleLadder(options: {\n params: OrderParams;\n szDecimals: number;\n finalPositionSize: number;\n }): ScaleLadder {\n const { params, szDecimals, finalPositionSize } = options;\n const { scaleMinPrice, scaleMaxPrice, scaleNumOrders } = params;\n if (scaleMinPrice === undefined || scaleMaxPrice === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);\n }\n if (scaleNumOrders === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);\n }\n\n const prices = normalizeHyperLiquidScalePriceLadder({\n minPrice: parseFloat(scaleMinPrice),\n maxPrice: parseFloat(scaleMaxPrice),\n count: scaleNumOrders,\n szDecimals,\n });\n\n // Throws ORDER_SCALE_SIZE_TOO_SMALL when a rung would round to nothing,\n // which a skew weighted far enough from even can do on its own.\n const sizes = splitScaleSizes({\n totalSize: finalPositionSize,\n count: scaleNumOrders,\n szDecimals,\n skew: params.scaleSkew,\n });\n\n const minimumOrderSize = this.#getMinimumOrderSize();\n const cheapestRungNotional = Math.min(\n ...sizes.map(\n (size, index) => parseFloat(size) * parseFloat(prices[index]),\n ),\n );\n if (cheapestRungNotional < minimumOrderSize) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL);\n }\n\n return { prices, sizes };\n }\n\n /**\n * Submit a TWAP through HyperLiquid's dedicated TWAP action.\n *\n * A TWAP is not an order on the book, so it does not go through the `order`\n * action, carries no builder fee, and comes back identified by a `twapId`\n * rather than an `oid`. That ID is the handle `cancelOrder` needs.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before preparation.\n * @returns A promise that resolves to the result.\n */\n async #placeTwapOrder(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, formattedSize } = context;\n const durationMinutes = params.twapDuration;\n if (durationMinutes === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED);\n }\n if (\n !Number.isSafeInteger(durationMinutes) ||\n durationMinutes < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||\n durationMinutes > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID);\n }\n const exchangeClient = this.#clientService.getExchangeClient();\n\n this.#deps.debugLogger.log('Submitting TWAP order', {\n symbol: params.symbol,\n assetId,\n size: formattedSize,\n durationMinutes,\n randomize: params.twapRandomize ?? false,\n });\n\n const result = await exchangeClient.twapOrder({\n twap: {\n a: assetId,\n b: params.isBuy,\n s: formattedSize,\n r: params.reduceOnly ?? false,\n m: durationMinutes,\n t: params.twapRandomize ?? false,\n },\n });\n\n if (result.status !== 'ok') {\n throw new Error(`TWAP order failed: ${JSON.stringify(result)}`);\n }\n\n const status: unknown = result.response?.data?.status;\n if (!isStatusObject(status)) {\n throw new Error('TWAP order rejected');\n }\n\n const rawError =\n typeof status.error === 'string' ? status.error : 'TWAP order rejected';\n const { running } = status;\n if (\n !isStatusObject(running) ||\n typeof running.twapId !== 'number' ||\n !Number.isSafeInteger(running.twapId) ||\n running.twapId < 0\n ) {\n throw new Error(rawError);\n }\n\n const orderId = running.twapId.toString();\n if (generation !== this.#strategyGeneration) {\n let remainsLive = true;\n try {\n const cancelResult = await exchangeClient.twapCancel({\n a: assetId,\n t: running.twapId,\n });\n const cancelStatus: unknown = cancelResult.response?.data?.status;\n // A rejected agent is dropped and reported; the TWAP stays live.\n if (\n isStatusObject(cancelStatus) &&\n typeof cancelStatus.error === 'string'\n ) {\n await this.#evictRejectedAgent(\n createStatusError(cancelStatus.error, cancelResult),\n );\n }\n remainsLive =\n classifyCancelStatus(cancelStatus) === CancelChildOutcome.Refused;\n } catch (error) {\n // A rejected agent is dropped and reported; the TWAP stays live.\n await this.#evictRejectedAgent(error);\n this.#deps.debugLogger.log(\n 'Stale TWAP placement could not be retracted',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.placeTwapOrder.retract',\n ).message,\n orderId,\n },\n );\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE),\n {\n success: false,\n submittedSize: formattedSize,\n ...(remainsLive && { orderId }),\n },\n );\n }\n\n return {\n success: true,\n orderId,\n submittedSize: formattedSize,\n };\n }\n\n /**\n * Fan a scale placement out into one batch of resting limit orders.\n *\n * The whole ladder goes in a single `order` action, which is one round trip\n * and one signature rather than one per rung. It is **not** atomic: an `na`\n * grouping evaluates each entry independently. Accepted rungs remain live and\n * are returned to the caller when another rung is rejected.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before preparation.\n * @returns A promise that resolves to the result.\n */\n async #placeScaleOrder(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, formattedSize, ladder, builder } = context;\n // Built and validated in `#prepareStrategyPlacement`, before anything was\n // signed, so what is submitted here is exactly what the minimums were\n // applied to.\n if (!ladder) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);\n }\n const { prices, sizes } = ladder;\n const count = prices.length;\n const { clientOrderIds: ladderClientOrderIds } =\n createScaleOrderIdentity(count);\n\n // Marked here rather than at submission so the ids recorded for\n // cancel-by-cloid are exactly the ids the venue received. Marking keeps the\n // Scale group marker and the rung index, so the group stays recoverable.\n const orders: SDKOrderParams[] = this.#applySubscriptionCloid(\n prices.map((price, index) => ({\n a: assetId,\n b: params.isBuy,\n p: price,\n s: sizes[index],\n r: params.reduceOnly ?? false,\n t: { limit: { tif: 'Gtc' as const } },\n c: ladderClientOrderIds[index],\n })),\n // These ids were generated a few lines above, so they are ours to stamp.\n new Set(ladderClientOrderIds),\n );\n const clientOrderIds: Hex[] = orders.map((order, index) =>\n order.c === undefined ? ladderClientOrderIds[index] : (order.c as Hex),\n );\n // Derived from the submitted ids, not from the pre-marking identity: the\n // group is recovered from open orders by reading their cloids, so tracking\n // it under any other key would register the same ladder twice.\n const groupId =\n readScaleGroupId(clientOrderIds[0]) ??\n `scale:${clientOrderIds[0].slice(2, -2)}`;\n\n this.#deps.debugLogger.log('Submitting scale ladder', {\n symbol: params.symbol,\n assetId,\n count,\n prices: orders.map((order) => order.p),\n sizes,\n });\n\n const exchangeClient = this.#clientService.getExchangeClient();\n let result: ScaleBulkOrderResponse;\n let thrownBulkOrderError: HyperliquidError | undefined;\n try {\n result = await exchangeClient.order({\n orders,\n grouping: 'na',\n ...(builder && { builder }),\n });\n } catch (error) {\n const bulkResponse = getScaleBulkOrderResponseFromError(error, count);\n if (!bulkResponse) {\n throw error;\n }\n result = bulkResponse;\n thrownBulkOrderError = error as HyperliquidError;\n }\n\n const rawStatuses = result.response?.data?.statuses;\n const statuses = Array.isArray(rawStatuses) ? rawStatuses : [];\n const outcomes = Array.from({ length: count }, (_unused, index) =>\n parseScaleBulkOrderStatus(statuses[index]),\n );\n const acceptedCount = outcomes.filter(\n (outcome) => outcome?.kind === 'accepted',\n ).length;\n const everyStatusClassified = outcomes.every(\n (outcome) => outcome !== undefined,\n );\n const rejectedCount = outcomes.filter(\n (outcome) => outcome?.kind === 'error',\n ).length;\n const acceptedRungs = outcomes.flatMap((outcome, index) =>\n outcome?.kind === 'accepted'\n ? [\n {\n outcome,\n price: prices[index],\n size: sizes[index],\n },\n ]\n : [],\n );\n const restingChildOrderIds = acceptedRungs.flatMap((rung) =>\n rung.outcome.state === 'resting' ? [rung.outcome.orderId] : [],\n );\n // Waiting rungs have no exchange order ID and cannot be recovered after\n // the in-memory Scale group registry is cleared on disconnect.\n const hasWaitingRungs = acceptedRungs.some(\n (rung) =>\n rung.outcome.state === 'waitingForFill' ||\n rung.outcome.state === 'waitingForTrigger',\n );\n const cleanupClientOrderIds = outcomes.flatMap((outcome, index) =>\n outcome?.kind === 'error' || outcome?.state === 'resting'\n ? []\n : [clientOrderIds[index]],\n );\n const acceptedChildren: ScaleOrderChild[] = acceptedRungs.map(\n ({ outcome }) =>\n outcome.state === 'resting' || outcome.state === 'filled'\n ? { orderId: outcome.orderId, state: outcome.state }\n : { state: outcome.state },\n );\n const acceptedSize = acceptedRungs.reduce(\n (total, rung) => total.plus(rung.size),\n new BigNumber(0),\n );\n const acceptedNotional = acceptedRungs.reduce(\n (total, rung) => total.plus(new BigNumber(rung.size).times(rung.price)),\n new BigNumber(0),\n );\n const filledRungs = acceptedRungs.flatMap((rung) =>\n rung.outcome.state === 'filled'\n ? [{ ...rung, outcome: rung.outcome }]\n : [],\n );\n const filledSize = filledRungs.reduce(\n (total, rung) => total.plus(rung.outcome.filledSize),\n new BigNumber(0),\n );\n const executedNotional = filledRungs.reduce(\n (total, rung) =>\n total.plus(\n new BigNumber(rung.outcome.filledSize).times(\n rung.outcome.averagePrice,\n ),\n ),\n new BigNumber(0),\n );\n const acceptedResult = {\n childOrderIds: restingChildOrderIds,\n submittedSize: formattedSize,\n acceptedSize: acceptedSize.toFixed(),\n ...(acceptedSize.gt(0) && {\n weightedAverageLimitPrice: acceptedNotional\n .dividedBy(acceptedSize)\n .toFixed(),\n }),\n acceptedChildren,\n ...(filledSize.gt(0) && {\n filledSize: filledSize.toFixed(),\n averagePrice: executedNotional.dividedBy(filledSize).toFixed(),\n }),\n } satisfies Partial<OrderResult>;\n const buildAcceptedResult = (): OrderResult => ({\n success: true,\n orderId: groupId,\n ...acceptedResult,\n });\n const cancelNonRejectedOrders = async (): Promise<{\n orderIds: string[];\n clientOrderIds: Hex[];\n }> => {\n const [orderIds, pendingClientOrderIds] = await Promise.all([\n this.#cancelOrderRequests(\n exchangeClient,\n restingChildOrderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n })),\n ),\n this.#cancelOrderCloidRequests(\n exchangeClient,\n cleanupClientOrderIds.map((clientOrderId) => ({\n asset: assetId,\n cloid: clientOrderId,\n })),\n ),\n ]);\n return {\n orderIds: orderIds.map(String),\n clientOrderIds: pendingClientOrderIds,\n };\n };\n\n if (thrownBulkOrderError !== undefined) {\n const isRecoverablePartial =\n everyStatusClassified && acceptedCount > 0 && rejectedCount > 0;\n if (!isRecoverablePartial) {\n if (!everyStatusClassified) {\n await cancelNonRejectedOrders();\n }\n throw thrownBulkOrderError;\n }\n }\n\n if (generation !== this.#strategyGeneration) {\n const remaining = await cancelNonRejectedOrders();\n if (\n remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n ...remaining,\n });\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE),\n {\n success: false,\n ...acceptedResult,\n ...(remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ? { orderId: groupId }\n : {}),\n childOrderIds: remaining.orderIds,\n },\n );\n }\n\n if (\n result.status !== 'ok' ||\n statuses.length !== count ||\n acceptedCount !== count ||\n hasWaitingRungs\n ) {\n this.#deps.debugLogger.log('Scale ladder was not fully accepted', {\n accepted: acceptedCount,\n filled: filledRungs.length,\n resting: restingChildOrderIds.length,\n requested: count,\n statuses,\n });\n const isValidPartial =\n result.status === 'ok' &&\n statuses.length === count &&\n everyStatusClassified &&\n !hasWaitingRungs &&\n acceptedCount > 0 &&\n rejectedCount > 0;\n if (isValidPartial) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n orderIds: restingChildOrderIds,\n clientOrderIds: [],\n });\n return buildAcceptedResult();\n }\n const remaining = await cancelNonRejectedOrders();\n if (\n remaining.orderIds.length > 0 ||\n remaining.clientOrderIds.length > 0\n ) {\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n ...remaining,\n });\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n {\n success: false,\n orderId: groupId,\n ...acceptedResult,\n childOrderIds: remaining.orderIds,\n },\n );\n }\n\n if (acceptedCount > 0) {\n return createErrorResult(new Error(PERPS_ERROR_CODES.ORDER_REJECTED), {\n success: false,\n ...acceptedResult,\n childOrderIds: [],\n });\n }\n\n throw new Error(PERPS_ERROR_CODES.ORDER_REJECTED);\n }\n\n this.#scaleOrderGroups.set(groupId, {\n symbol: params.symbol,\n orderIds: restingChildOrderIds,\n clientOrderIds: [],\n });\n return buildAcceptedResult();\n }\n\n /**\n * Place a chase's first order and register the session that follows it.\n *\n * Split from the routing above so the concurrency reservation there wraps\n * every await in one `try`/`finally`.\n *\n * @param params - Order parameters.\n * @param context - Prepared asset and sizing context.\n * @param generation - Teardown generation captured before any await.\n * @returns A promise that resolves to the result.\n */\n async #startChaseSession(\n params: OrderParams,\n context: StrategyPlacementContext,\n generation: number,\n ): Promise<OrderResult> {\n const { assetId, szDecimals, formattedSize, builder } = context;\n // Captured now, alongside the builder fee and for the same reason: the fee\n // resolution behind it is cleared when the caller's `placeOrder` returns,\n // which for a chase is before any replacement runs.\n const marksSubscriptionCloid = this.#isSubscriptionFeeSource();\n\n // The preamble is several round trips long. A disconnect during it has\n // already torn down everything this session would run on, so the chase\n // stops here rather than reading the book and putting a fresh order on it\n // for a provider that no longer exists.\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n\n let quotePrice = await this.#getChaseQuotePrice({\n symbol: params.symbol,\n isBuy: params.isBuy,\n szDecimals,\n });\n if (\n quotePrice === CHASE_ORDER_STATUS_UNAVAILABLE ||\n typeof quotePrice !== 'string'\n ) {\n // A first placement has no child whose terminal state could be read.\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n // The book read is a round trip of its own, so the check above does not\n // cover it. Re-checked here, immediately before the only statement that\n // signs anything: every await on this path is now followed by a refusal\n // before the next one, leaving one window that cannot be closed from here\n // — a disconnect arriving while the submission itself is in flight, which\n // the check after it handles.\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n\n // Held onto rather than looked up again after the submission returns.\n // `disconnect` drops the service's client reference synchronously, so a\n // retraction that asked for a client after the fact would be refused one\n // and leave the order resting under the account that placed it. This\n // instance signed the order and can still cancel it as that account.\n const placingClient = this.#clientService.getExchangeClient();\n\n let orderId: string | undefined;\n for (\n let attempt = 1;\n attempt <= CHASE_ORDER_CONFIG.InitialPlacementAttempts;\n attempt += 1\n ) {\n try {\n orderId = await this.#restChaseOrder({\n assetId,\n isBuy: params.isBuy,\n price: quotePrice,\n size: formattedSize,\n reduceOnly: params.reduceOnly ?? false,\n builder,\n marksSubscriptionCloid,\n exchangeClient: placingClient,\n });\n break;\n } catch (error) {\n if (\n attempt === CHASE_ORDER_CONFIG.InitialPlacementAttempts ||\n !isRetryableChasePlacementError(error)\n ) {\n throw error;\n }\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n const refreshedQuote = await this.#getChaseQuotePrice({\n symbol: params.symbol,\n isBuy: params.isBuy,\n szDecimals,\n });\n if (\n refreshedQuote === CHASE_ORDER_STATUS_UNAVAILABLE ||\n typeof refreshedQuote !== 'string'\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n if (generation !== this.#strategyGeneration) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED);\n }\n quotePrice = refreshedQuote;\n }\n }\n if (!orderId) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n const intervalMs =\n params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;\n const sessionId = generatePerpsId('chase');\n const session: ChaseSession = {\n symbol: params.symbol,\n assetId,\n isBuy: params.isBuy,\n size: formattedSize,\n originalSize: formattedSize,\n szDecimals,\n reduceOnly: params.reduceOnly ?? false,\n orderId,\n replacingOrderId: null,\n pendingReplacement: null,\n restingPrice: quotePrice,\n arrivalPrice: quotePrice,\n startedAt: Date.now(),\n maxDistanceBps: params.chaseMaxDistanceBps,\n intervalMs,\n lastSnapshotSizeRefreshAt: 0,\n builder,\n marksSubscriptionCloid,\n deadline:\n params.chaseMaxDurationMs === undefined\n ? Number.POSITIVE_INFINITY\n : Date.now() + params.chaseMaxDurationMs,\n maxRepricings: params.chaseMaxRepricings ?? Number.POSITIVE_INFINITY,\n repricings: 0,\n timer: null,\n active: true,\n status: CHASE_ORDER_STATUS.Active,\n };\n // A disconnect landed while the submission was in flight — the one window\n // the checks above cannot close. The order rested, but no strategy is\n // running behind it and no handle names it, so this placement is reported\n // as a failure. That makes the resting order an orphan: the caller is told\n // the chase failed, nothing refreshes the caches a successful placement\n // would have invalidated, and the exchange id is only usable for as long as\n // the provider stays pointed at the account that placed it — a disconnect\n // is usually followed by an account or network switch, after which handing\n // the id back is no remedy at all. So it is cancelled here, through the\n // client that signed it — the account switch cannot reach that instance —\n // and the failure is then true of the venue as well as of this provider.\n // Best-effort still: the transport underneath that client may already be\n // closing, so a cancel that does not land falls back to reporting the id.\n if (generation !== this.#strategyGeneration) {\n this.#deps.debugLogger.log('Chase placement outlived its provider', {\n orderId,\n restingPrice: quotePrice,\n });\n\n const outcome = await this.#retractOrphanedChaseOrder(\n session,\n placingClient,\n );\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_CHASE_ABANDONED),\n {\n success: false,\n // Reported only when the retraction did not take. Naming an order\n // that is no longer on the book would send the caller to cancel\n // something already gone; naming one that still rests is the only\n // route left to it.\n ...(outcome === CancelChildOutcome.Refused\n ? { childOrderIds: [orderId] }\n : {}),\n submittedSize: formattedSize,\n },\n );\n }\n\n this.#chaseSessions.set(sessionId, session);\n this.#scheduleChaseTick(sessionId);\n\n this.#deps.debugLogger.log('Chase session started', {\n sessionId,\n symbol: params.symbol,\n orderId,\n restingPrice: quotePrice,\n intervalMs,\n });\n\n return {\n success: true,\n orderId: sessionId,\n childOrderIds: [orderId],\n submittedSize: formattedSize,\n };\n }\n\n /**\n * Read the price a chase must rest at: the best bid for a buy, the best ask\n * for a sell.\n *\n * The touch, not the mid: a post-only order priced at the mid would either\n * cross or be rejected, and a chase that never rests at the front of the\n * queue is not chasing anything.\n *\n * @param params - The lookup parameters.\n * @param params.symbol - Market to read.\n * @param params.isBuy - Which side the chase rests on.\n * @param params.szDecimals - Asset size precision, for price formatting.\n * @param params.own - The chase's own resting order, excluded from the book.\n * @param params.own.orderId - Exchange ID of that order.\n * @param params.own.price - Price that order rests at.\n * @param params.own.size - Size it was last placed for.\n * @returns The formatted price, a terminal child result, or the status\n * unavailable sentinel when the child may still be live.\n */\n async #getChaseQuotePrice(params: {\n symbol: string;\n isBuy: boolean;\n szDecimals: number;\n /** The chase's own resting order, excluded from the book it reads. */\n own?: { orderId: string; price: string; size: string };\n }): Promise<\n string | ChaseTerminalResolution | typeof CHASE_ORDER_STATUS_UNAVAILABLE\n > {\n const { symbol, isBuy, szDecimals, own } = params;\n\n const book = await this.#clientService.getInfoClient().l2Book({\n coin: symbol,\n });\n\n // `levels` is [bids, asks], each best-first.\n const ownSide = book?.levels?.[isBuy ? 0 : 1];\n const netting = await this.#resolveOwnRestingSizes({\n symbol,\n isBuy,\n callerOrderId: own?.orderId,\n ownSide,\n });\n if (\n netting === CHASE_ORDER_STATUS_UNAVAILABLE ||\n !(netting instanceof Map)\n ) {\n return netting;\n }\n\n const bestBid = readBestExternalPrice(book?.levels?.[0], netting);\n const bestAsk = readBestExternalPrice(book?.levels?.[1], netting);\n\n if (bestBid === null || bestAsk === null) {\n throw new Error(PERPS_ERROR_CODES.ORDER_CHASE_TOUCH_UNAVAILABLE);\n }\n\n return computeChaseQuotePrice({ bestBid, bestAsk, isBuy, szDecimals });\n }\n\n /**\n * Rest one post-only order for a chase and return its exchange ID.\n *\n * @param params - The placement parameters.\n * @param params.assetId - Resolved asset ID.\n * @param params.isBuy - Order side.\n * @param params.price - Formatted limit price.\n * @param params.size - Formatted size.\n * @param params.reduceOnly - Whether the order may only reduce a position.\n * @param params.builder - Builder context captured when the session started.\n * @param params.marksSubscriptionCloid - Whether to mark the cloid, captured\n * when the session started. Passed explicitly rather than read live: a\n * replacement runs long after the fee resolution behind it was cleared.\n * @param params.exchangeClient - Client to submit through. Passed in rather\n * than looked up here so a first placement can keep the instance it signed\n * with, which is the only one that can take the order back once `disconnect`\n * has dropped the service's reference.\n * @returns The resting order's exchange ID.\n */\n async #restChaseOrder(params: {\n assetId: number;\n isBuy: boolean;\n price: string;\n size: string;\n reduceOnly: boolean;\n builder?: BuilderOrderContext;\n marksSubscriptionCloid?: boolean;\n exchangeClient: ExchangeClient;\n }): Promise<string> {\n const result = await params.exchangeClient.order({\n orders: this.#applySubscriptionCloid(\n [\n {\n a: params.assetId,\n b: params.isBuy,\n p: params.price,\n s: params.size,\n r: params.reduceOnly,\n // Post-only: a chase adds liquidity at the touch. Crossing would\n // end the chase on its first tick at a worse price than resting.\n t: { limit: { tif: 'Alo' as const } },\n },\n ],\n undefined,\n params.marksSubscriptionCloid,\n ),\n grouping: 'na',\n ...(params.builder && { builder: params.builder }),\n });\n\n if (result.status !== 'ok') {\n throw new Error(`Chase order failed: ${JSON.stringify(result)}`);\n }\n\n const orderId = this.#readOrderIdFromStatus(\n result.response?.data?.statuses?.[0],\n );\n if (!orderId) {\n throw new Error(\n `Chase order rejected: ${JSON.stringify(result.response?.data)}`,\n );\n }\n\n return orderId;\n }\n\n /**\n * Schedule the next tick of a chase session.\n *\n * @param sessionId - Session to advance.\n */\n #scheduleChaseTick(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active || session.timer !== null) {\n return;\n }\n\n const timer = setTimeout(() => {\n session.timer = null;\n this.#chaseTickQueue = this.#chaseTickQueue\n .then(() => this.#runChaseTick(sessionId))\n .catch(async (error: unknown) => {\n // A rejected agent is dropped so the next tick asks for another.\n await this.#evictRejectedAgent(error);\n // Resolve the shared queue after every failure. Otherwise one\n // rejected tick prevents all later ticks and teardown from running.\n this.#deps.debugLogger.log('Chase tick failed', {\n sessionId,\n error: ensureError(error, 'HyperLiquidProvider.chaseTick').message,\n });\n this.#recoverFailedChaseTick(sessionId);\n });\n }, session.intervalMs);\n\n // Node keeps the process alive for a pending timer; a background chase is\n // not a reason to hold an exiting process open. React Native's timers have\n // no `unref`, hence the guard.\n timer.unref?.();\n session.timer = timer;\n }\n\n /** Pause scheduled background work while a foreground Chase is submitted. */\n #pauseChaseTicksForPlacement(): void {\n for (const session of this.#chaseSessions.values()) {\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n }\n }\n\n /** Restart the polling cadence after all foreground placements settle. */\n #resumeChaseTicksAfterPlacement(): void {\n for (const [sessionId, session] of this.#chaseSessions) {\n if (session.active && !session.timer) {\n this.#scheduleChaseTick(sessionId);\n }\n }\n }\n\n /**\n * Decide what a session does after one of its ticks threw.\n *\n * Two outcomes, told apart by whether the session still owns a resting order:\n *\n * - It does — the failure was a book read or a refused cancel, and the order\n * is untouched. The chase keeps going; the deadline check at the top of the\n * next tick ends it if the window has since closed. Letting a transient\n * error end the chase would strand a live order under a session that still\n * claimed to be re-pricing it.\n * - It does not — the tick cancelled the order and then failed to rest its\n * replacement, so nothing is on the book. There is nothing left to chase and\n * nothing left to cancel, so the session ends here. Leaving it `active` would\n * report a live chase with no timer, and every later cancel would try to\n * cancel the dead order and keep the handle forever.\n *\n * @param sessionId - Session whose tick failed.\n */\n #recoverFailedChaseTick(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active) {\n return;\n }\n\n if (session.orderId === null) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase ended with nothing resting', {\n sessionId,\n });\n this.#rebalanceChaseSession(session).catch((error: unknown) => {\n this.#deps.debugLogger.log('Chase collateral cleanup failed', {\n sessionId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.recoverFailedChaseTick',\n ).message,\n });\n });\n return;\n }\n\n this.#scheduleChaseTick(sessionId);\n }\n\n /**\n * Advance one chase session: re-price if the touch has moved, stop if the\n * window has closed.\n *\n * @param sessionId - Session to advance.\n */\n async #runChaseTick(sessionId: string): Promise<void> {\n const session = this.#chaseSessions.get(sessionId);\n if (!session?.active) {\n return;\n }\n\n // Give a new Chase placement priority over background cancel/replace\n // traffic. With several active sessions, their signed mutations can\n // otherwise overlap the placement preamble and trip the SDK transport's\n // circuit breaker before the new order reaches the venue. Deferring one\n // polling interval leaves every existing child resting as a valid ALO and\n // preserves the venue's five-session limit without increasing request\n // churn.\n if (this.#chasePlacementsInFlight > 0) {\n this.#scheduleChaseTick(sessionId);\n return;\n }\n\n if (Date.now() >= session.deadline) {\n // The window closed. The last order stays resting as an ordinary limit\n // order and the session stays registered, so cancelling by its handle\n // still reaches that order.\n session.active = false;\n session.status = CHASE_ORDER_STATUS.DurationReached;\n this.#deps.debugLogger.log('Chase session window closed', { sessionId });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n const rawQuotePrice = await this.#getChaseQuotePrice({\n symbol: session.symbol,\n isBuy: session.isBuy,\n szDecimals: session.szDecimals,\n own: session.orderId\n ? {\n orderId: session.orderId,\n price: session.restingPrice,\n size: session.size,\n }\n : undefined,\n });\n\n if (typeof rawQuotePrice !== 'string') {\n // The order left the book without the loop seeing it. Preserve the venue\n // status so an external cancellation is not reported as a fill.\n session.orderId = null;\n session.active = false;\n session.status = rawQuotePrice.status;\n session.size = rawQuotePrice.remainingSize ?? '0';\n this.#deps.debugLogger.log('Chase order ended between ticks', {\n sessionId,\n status: session.status,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n if (rawQuotePrice === CHASE_ORDER_STATUS_UNAVAILABLE) {\n // The child may still be live. Leave it untouched and retry on the next\n // normal interval instead of permanently stranding the Chase after one\n // short status outage.\n this.#deps.debugLogger.log('Chase order status unavailable', {\n sessionId,\n orderId: session.orderId,\n });\n this.#scheduleChaseTick(sessionId);\n return;\n }\n\n const arrivalPrice = Number.parseFloat(session.arrivalPrice);\n const rawQuote = Number.parseFloat(rawQuotePrice);\n const adverseDistanceFromArrival = session.isBuy\n ? (rawQuote - arrivalPrice) / arrivalPrice\n : (arrivalPrice - rawQuote) / arrivalPrice;\n const boundaryDirection = session.isBuy ? 1 : -1;\n const maxDistanceRatio =\n session.maxDistanceBps === undefined\n ? undefined\n : session.maxDistanceBps / BASIS_POINTS_DIVISOR;\n const boundaryPrice =\n maxDistanceRatio === undefined\n ? undefined\n : arrivalPrice * (1 + boundaryDirection * maxDistanceRatio);\n let reachedMaxDistance =\n boundaryPrice !== undefined &&\n maxDistanceRatio !== undefined &&\n adverseDistanceFromArrival >= maxDistanceRatio;\n let quotePrice = rawQuotePrice;\n if (reachedMaxDistance && boundaryPrice !== undefined) {\n quotePrice = formatHyperLiquidPrice({\n price: boundaryPrice,\n szDecimals: session.szDecimals,\n });\n const formattedBoundary = Number.parseFloat(quotePrice);\n const overshootsBoundary = session.isBuy\n ? formattedBoundary > boundaryPrice\n : formattedBoundary < boundaryPrice;\n if (overshootsBoundary) {\n const tick = getPriceTick({\n price: boundaryPrice,\n szDecimals: session.szDecimals,\n });\n quotePrice = formatHyperLiquidPrice({\n price: session.isBuy\n ? formattedBoundary - tick\n : formattedBoundary + tick,\n szDecimals: session.szDecimals,\n });\n }\n }\n\n // The book read is a round trip, and a cancel arriving during it stops the\n // session. Without this re-check the tick would cancel and re-place the very\n // order the caller just asked to be rid of.\n if (!session.active) {\n return;\n }\n\n if (quotePrice !== session.restingPrice && session.orderId) {\n const outcome = await this.#cancelChaseChild(session);\n\n // The cancel is a second round trip, and this is the window where a\n // caller's `cancelOrder` does the most damage: it would cancel the order\n // this tick has already cancelled, report the cancel incomplete, and then\n // this tick would rest a replacement the caller has no idea exists.\n // Stopping here leaves nothing on the book.\n if (!session.active) {\n // A refused cancel leaves the child resting. Preserve its ID so the\n // caller that stopped this session can report an incomplete cancel and\n // retry it instead of orphaning the order.\n if (outcome !== CancelChildOutcome.Refused) {\n session.orderId = null;\n }\n return;\n }\n\n if (outcome === CancelChildOutcome.Refused) {\n // The exchange kept the order, so it is still resting at the old price.\n // Placing the replacement anyway would double the position. Leave it\n // alone and try again on the next tick, which is why this falls through\n // to the reschedule below rather than ending the session.\n this.#deps.debugLogger.log('Chase reprice cancel refused', {\n sessionId,\n orderId: session.orderId,\n });\n reachedMaxDistance = false;\n } else if (outcome === CancelChildOutcome.Gone) {\n // The order left the book between ticks: it filled, or something else\n // cancelled it. There is nothing left to chase.\n const goneOrderId = session.orderId;\n session.orderId = null;\n session.active = false;\n let remainder: ChaseOrderRemainder;\n try {\n remainder = await this.#readOrderRemainder(\n goneOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n } catch (error) {\n session.status = CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase order status unavailable', {\n sessionId,\n orderId: goneOrderId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.chaseGoneOrderStatus',\n ).message,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n session.status = remainder.terminalStatus ?? CHASE_ORDER_STATUS.Failed;\n if (remainder.remainingSize !== null) {\n session.size = remainder.remainingSize;\n }\n this.#deps.debugLogger.log('Chase order no longer resting', {\n sessionId,\n status: session.status,\n remainingSize: session.size,\n });\n await this.#rebalanceChaseSession(session);\n return;\n } else {\n // The cancel is confirmed, so the session owns nothing from here on.\n // Recorded before the read rather than after it: a read that rejects\n // would otherwise leave the session naming an order that is already off\n // the book, and recovery would reschedule a chase with nothing resting.\n const cancelledOrderId = session.orderId;\n session.replacingOrderId = cancelledOrderId;\n session.orderId = null;\n\n // No further fills can reach a cancelled order, so what it did not fill\n // is now fixed. Sampling before the cancel would have left a window in\n // which a fill lands and is then re-placed.\n let remainder: ChaseOrderRemainder;\n try {\n remainder = await this.#readOrderRemainder(\n cancelledOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n } catch (error) {\n session.replacingOrderId = null;\n throw error;\n }\n\n // Another round trip, another window for a cancel to land. By now the\n // old order is already off the book, so a cancel that arrived during it\n // found nothing to cancel and reported success — resting a replacement\n // after that would put an order on the book the caller believes is gone\n // and has no handle for.\n if (!session.active || !this.#chaseSessions.has(sessionId)) {\n session.replacingOrderId = null;\n this.#deps.debugLogger.log('Chase cancelled mid-reprice', {\n sessionId,\n });\n return;\n }\n\n if (\n remainder.remainingSize === null ||\n (remainder.terminalStatus !== null &&\n remainder.terminalStatus !== CHASE_ORDER_STATUS.Canceled)\n ) {\n // Nothing is left to chase. Preserve whether the venue actually\n // confirmed a fill rather than labelling every zero remainder filled.\n session.replacingOrderId = null;\n session.active = false;\n session.size = remainder.remainingSize ?? '0';\n session.status =\n remainder.terminalStatus ?? CHASE_ORDER_STATUS.Failed;\n this.#deps.debugLogger.log('Chase order has no remainder', {\n sessionId,\n status: session.status,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n const remaining = remainder.remainingSize;\n\n // Published *before* the placement starts, not from the promise it\n // returns: the window opens the moment `#restChaseOrder` is entered, so\n // deriving the marker from its return value would leave the synchronous\n // prefix of that call unguarded. A cancel arriving anywhere inside the\n // round trip now waits for the replacement to land instead of reading\n // the null `orderId` as \"nothing rests\", reporting success, and dropping\n // the handle while this call is still putting an order on the book.\n let settleReplacement: (() => void) | undefined;\n session.pendingReplacement = new Promise<void>((resolve) => {\n settleReplacement = resolve;\n });\n\n try {\n session.orderId = await this.#restChaseOrder({\n assetId: session.assetId,\n isBuy: session.isBuy,\n price: quotePrice,\n size: remaining,\n reduceOnly: session.reduceOnly,\n builder: session.builder,\n marksSubscriptionCloid: session.marksSubscriptionCloid,\n // A running session is on a live provider, so the current client is\n // the right one; only the first placement has a teardown to survive.\n exchangeClient: this.#clientService.getExchangeClient(),\n });\n session.size = remaining;\n } finally {\n // Cleared before the waiters wake, so they see the settled session.\n session.replacingOrderId = null;\n session.pendingReplacement = null;\n settleReplacement?.();\n }\n session.restingPrice = quotePrice;\n session.repricings += 1;\n\n this.#deps.debugLogger.log('Chase re-priced', {\n sessionId,\n orderId: session.orderId,\n restingPrice: quotePrice,\n size: session.size,\n repricings: session.repricings,\n });\n\n // A cancel that arrived during the round trip is now waiting on this\n // session; it cancels the order just recorded above. A `disconnect`\n // deregisters the session instead, and deliberately leaves resting\n // orders alone — logged with its ID so it stays traceable.\n if (!this.#chaseSessions.has(sessionId)) {\n this.#deps.debugLogger.log('Chase replacement outlived its session', {\n sessionId,\n orderId: session.orderId,\n });\n return;\n }\n if (!session.active) {\n return;\n }\n }\n }\n\n if (reachedMaxDistance && session.maxDistanceBps !== undefined) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.MaxDistanceReached;\n this.#deps.debugLogger.log('Chase max distance reached', {\n sessionId,\n restingPrice: session.restingPrice,\n maxDistanceBps: session.maxDistanceBps,\n });\n this.#onChaseOrderMaxDistanceReached?.({\n handle: sessionId,\n symbol: session.symbol,\n side: session.isBuy ? 'buy' : 'sell',\n restingOrderId: session.orderId,\n restingPrice: session.restingPrice,\n maxDistanceBps: session.maxDistanceBps,\n timestamp: Date.now(),\n providerId: PROVIDER_CONFIG.DefaultProvider,\n });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n if (session.repricings >= session.maxRepricings) {\n session.active = false;\n session.status = CHASE_ORDER_STATUS.RepricingLimitReached;\n this.#deps.debugLogger.log('Chase repricing cap reached', { sessionId });\n await this.#rebalanceChaseSession(session);\n return;\n }\n\n this.#scheduleChaseTick(sessionId);\n }\n\n /**\n * Resolve how much of the chase's own order is really sitting on its level.\n *\n * The session tracks what its order was last *placed* for, which overstates\n * the order once it partially fills. Over-subtracting only matters when it\n * would net the level away entirely — while the level still shows more size\n * than the order could possibly hold, the level has external liquidity either\n * way and the stale figure is good enough.\n *\n * So the live size is fetched only in the ambiguous case, which keeps the\n * common tick to a single book read rather than doubling the request rate\n * against the venue for every chase on every interval.\n *\n * @param params - Netting parameters.\n * @param params.symbol - Market being quoted.\n * @param params.isBuy - Side being quoted.\n * @param params.callerOrderId - The asking session's order, if it has one.\n * @param params.ownSide - The side of the book those orders rest on.\n * @returns Our resting size at each price, the asking child's terminal\n * result, or the unavailable sentinel.\n */\n async #resolveOwnRestingSizes(params: {\n symbol: string;\n isBuy: boolean;\n callerOrderId?: string;\n ownSide?: { px: string; sz: string }[];\n }): Promise<\n | Map<string, number>\n | ChaseTerminalResolution\n | typeof CHASE_ORDER_STATUS_UNAVAILABLE\n > {\n const { symbol, isBuy, callerOrderId, ownSide } = params;\n\n // Every chase this provider is running on this side, the caller included.\n const ourOrders: ChaseRestingOrder[] = [];\n for (const session of this.#chaseSessions.values()) {\n if (\n session.orderId !== null &&\n session.symbol === symbol &&\n session.isBuy === isBuy\n ) {\n ourOrders.push({\n orderId: session.orderId,\n price: session.restingPrice,\n size: session.size,\n });\n }\n }\n\n if (ourOrders.length === 0) {\n return new Map();\n }\n\n const recorded = new Map<string, number>();\n for (const order of ourOrders) {\n recorded.set(\n order.price,\n (recorded.get(order.price) ?? 0) + parseFloat(order.size),\n );\n }\n\n // A level holding more than we possibly could has external size regardless,\n // so the recorded figures cannot change the answer there and are left as\n // they are. Elsewhere the recorded sizes may overstate what is really\n // resting — an order partially fills without the loop seeing it — and only\n // then is a lookup worth a round trip.\n const ambiguous = ourOrders.filter((order) => {\n const level = ownSide?.find((entry) => entry.px === order.price);\n return !level || parseFloat(level.sz) <= (recorded.get(order.price) ?? 0);\n });\n\n let callerTerminalResult: ChaseTerminalResolution | null = null;\n let callerStatusUnavailable = false;\n const resolutions = await Promise.allSettled(\n ambiguous.map((order) =>\n this.#readOrderRemainder(order.orderId, CHASE_ORDER_STATUS_RETRY_COUNT),\n ),\n );\n resolutions.forEach((resolution, index) => {\n const order = ambiguous[index];\n if (resolution.status === 'fulfilled') {\n const { remainingSize: live, terminalStatus } = resolution.value;\n const delta =\n (live === null ? 0 : parseFloat(live)) - parseFloat(order.size);\n recorded.set(\n order.price,\n Math.max(0, (recorded.get(order.price) ?? 0) + delta),\n );\n if (terminalStatus !== null && order.orderId === callerOrderId) {\n callerTerminalResult = {\n remainingSize: live,\n status: terminalStatus,\n };\n }\n } else {\n const { reason: error } = resolution;\n if (\n error instanceof ChaseOrderStatusUnavailableError &&\n order.orderId === callerOrderId\n ) {\n callerStatusUnavailable = true;\n } else {\n // A failed lookup must not stop the chase. Keeping the recorded size\n // can only over-subtract, which quotes a level deeper rather than\n // leaving the order stranded at a stale price.\n this.#deps.debugLogger.log('Chase own-size lookup failed', {\n orderId: order.orderId,\n error: ensureError(error, 'HyperLiquidProvider.chaseOwnSize')\n .message,\n });\n }\n }\n });\n\n if (callerStatusUnavailable) {\n return CHASE_ORDER_STATUS_UNAVAILABLE;\n }\n return callerTerminalResult ?? recorded;\n }\n\n /**\n * Read what a chase's just-cancelled order left unfilled.\n *\n * A chase re-prices by cancelling and re-placing, and the order it cancels\n * may have partially filled first; re-placing the session's original size\n * would execute more than the caller asked for.\n *\n * Read *after* the cancel on purpose. The order's status endpoint answers for\n * an order that is no longer on the book, and once the cancel has landed no\n * further fills can reach it — so the unfilled size it reports is final.\n * Sampling the open-order book beforehand would instead leave a one-round-trip\n * window in which a fill lands and is then re-placed on top.\n *\n * @param orderId - Exchange ID of the order that was just cancelled.\n * @param unknownStatusRetries - Remaining retries for a transient unknown ID.\n * @returns The unfilled size and exact terminal status, when present.\n */\n async #readOrderRemainder(\n orderId: string,\n unknownStatusRetries = 0,\n ): Promise<ChaseOrderRemainder> {\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const status = await this.#clientService.getInfoClient().orderStatus({\n user: userAddress,\n oid: parseInt(orderId, 10),\n });\n\n if (status.status !== 'order') {\n // unknownOid can be transient while the order-status index catches up.\n // Treating it as a fill would drop the only handle to a live order.\n if (unknownStatusRetries > 0) {\n await new Promise((resolve) =>\n setTimeout(resolve, CHASE_ORDER_STATUS_RETRY_DELAY_MS),\n );\n return await this.#readOrderRemainder(\n orderId,\n unknownStatusRetries - 1,\n );\n }\n throw new ChaseOrderStatusUnavailableError();\n }\n\n const remaining = String(status.order.order.sz);\n const remainingSize = parseFloat(remaining) > 0 ? remaining : null;\n switch (status.order.status) {\n case 'open':\n case 'triggered':\n return { remainingSize, terminalStatus: null };\n case 'filled':\n return {\n remainingSize: null,\n terminalStatus: CHASE_ORDER_STATUS.Filled,\n };\n case 'canceled':\n return remainingSize === null\n ? {\n remainingSize: null,\n terminalStatus: CHASE_ORDER_STATUS.Filled,\n }\n : {\n remainingSize,\n terminalStatus: CHASE_ORDER_STATUS.Canceled,\n };\n default:\n return {\n remainingSize,\n terminalStatus: CHASE_ORDER_STATUS.Failed,\n };\n }\n }\n\n /**\n * Cancel the order a chase session currently has resting.\n *\n * @param session - The session whose child to cancel.\n * @param placingClient - Client to cancel through. Omitted by every cancel on\n * a live provider, which wants the current one; an abandoned placement passes\n * the client it signed with, the only one still able to reach its order.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\n async #cancelChaseChild(\n session: ChaseSession,\n placingClient?: ExchangeClient,\n ): Promise<CancelChildOutcome> {\n if (!session.orderId) {\n return CancelChildOutcome.Gone;\n }\n\n // Looked up only once there is something to cancel, so a session with\n // nothing resting still answers on a provider whose client is already gone.\n const exchangeClient =\n placingClient ?? this.#clientService.getExchangeClient();\n let result;\n try {\n result = await exchangeClient.cancel({\n cancels: [{ a: session.assetId, o: parseInt(session.orderId, 10) }],\n });\n } catch (error) {\n const message = ensureError(\n error,\n 'HyperLiquidProvider.cancelChaseChild',\n ).message.toLowerCase();\n if (\n ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))\n ) {\n return CancelChildOutcome.Gone;\n }\n throw error;\n }\n\n const status: unknown = result.response?.data?.statuses?.[0];\n const signerFailure = await this.#classifyStatusSignerFailure(\n [status],\n result,\n );\n if (signerFailure) {\n throw signerFailure;\n }\n return classifyCancelStatus(status);\n }\n\n /**\n * Take back the order of a chase that was abandoned before it registered.\n *\n * Best-effort by construction: the provider is already being torn down, so a\n * cancel that fails outright is reported rather than retried or thrown. The\n * caller reports the placement as a failure either way — the outcome only\n * decides whether an exchange id is worth handing back with it.\n *\n * @param session - The unregistered session holding the resting order.\n * @param placingClient - The client the order was signed with. The service's\n * own reference is already cleared by the time this runs, so asking it for a\n * client here would fail before a cancel was ever sent.\n * @returns Whether the order was cancelled, was already gone, or still rests.\n */\n async #retractOrphanedChaseOrder(\n session: ChaseSession,\n placingClient: ExchangeClient,\n ): Promise<CancelChildOutcome> {\n try {\n const outcome = await this.#cancelChaseChild(session, placingClient);\n this.#deps.debugLogger.log('Retracted abandoned chase order', {\n orderId: session.orderId,\n outcome,\n });\n return outcome;\n } catch (error) {\n // A rejected agent is dropped and reported; the order stays resting.\n await this.#evictRejectedAgent(error);\n this.#deps.debugLogger.log('Could not retract abandoned chase order', {\n orderId: session.orderId,\n error: ensureError(error, 'HyperLiquidProvider.startChaseSession')\n .message,\n });\n return CancelChildOutcome.Refused;\n }\n }\n\n /**\n * Stop a chase session's re-pricing loop.\n *\n * @param sessionId - Session to stop.\n */\n #stopChaseSession(sessionId: string): void {\n const session = this.#chaseSessions.get(sessionId);\n if (!session) {\n return;\n }\n\n const wasActive = session.active;\n session.active = false;\n if (wasActive) {\n session.status = CHASE_ORDER_STATUS.TerminationPending;\n }\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n }\n\n /**\n * Rebalance one Chase session at most once at a time. Failed cleanup keeps\n * the transfer context so a later lifecycle read or cancel can retry it.\n *\n * @param session - Chase session whose manual HIP-3 transfer is complete.\n * @returns Whether no collateral cleanup remains for the session.\n */\n async #rebalanceChaseSession(session: ChaseSession): Promise<boolean> {\n const { hip3Transfer } = session;\n if (!hip3Transfer) {\n return true;\n }\n if (\n session.orderId !== null ||\n session.replacingOrderId !== null ||\n session.pendingReplacement !== null\n ) {\n return false;\n }\n\n let rebalancePromise = session.hip3RebalancePromise;\n if (!rebalancePromise) {\n rebalancePromise = this.#handleHip3PostOrderRebalance(hip3Transfer);\n session.hip3RebalancePromise = rebalancePromise;\n }\n\n try {\n const success = await rebalancePromise;\n if (success && session.hip3Transfer === hip3Transfer) {\n delete session.hip3Transfer;\n }\n return success;\n } finally {\n if (session.hip3RebalancePromise === rebalancePromise) {\n delete session.hip3RebalancePromise;\n }\n }\n }\n\n /**\n * Adapt one venue TWAP history record and its slice fills to the shared\n * controller contract.\n *\n * @param params - Venue history, fills, and read time.\n * @returns A TWAP lifecycle record, or null when the venue supplied no ID.\n */\n #adaptTwapOrder(params: AdaptTwapOrderParams): TwapOrder | null {\n const { historyEntry, now } = params;\n const { state, twapId } = historyEntry;\n if (twapId === undefined || !Number.isSafeInteger(twapId) || twapId < 0) {\n return null;\n }\n\n const totalSize = new BigNumber(state.sz);\n const executedSize = new BigNumber(state.executedSz);\n const executedNotional = new BigNumber(state.executedNtl);\n if (\n !totalSize.isFinite() ||\n !executedSize.isFinite() ||\n !executedNotional.isFinite() ||\n !Number.isFinite(state.timestamp) ||\n !Number.isFinite(historyEntry.time) ||\n !Number.isFinite(state.minutes)\n ) {\n return null;\n }\n let boundedExecutedSize = executedSize;\n if (executedSize.isLessThan(0)) {\n boundedExecutedSize = new BigNumber(0);\n } else if (executedSize.isGreaterThan(totalSize)) {\n boundedExecutedSize = totalSize;\n }\n const rawRemainingSize = totalSize.minus(boundedExecutedSize);\n const remainingSize = rawRemainingSize.isGreaterThan(0)\n ? rawRemainingSize\n : new BigNumber(0);\n const status = resolveTwapOrderStatus(\n historyEntry,\n boundedExecutedSize,\n totalSize,\n );\n const fills = params.sliceFills\n .map(adaptTwapOrderFill)\n .sort((left, right) => left.timestamp - right.timestamp);\n const startedAt = state.timestamp;\n const historyUpdatedAt = normalizeTwapHistoryTimestamp(historyEntry.time);\n const lastUpdated = Math.max(\n startedAt,\n historyUpdatedAt,\n ...fills.map((fill) => fill.timestamp),\n );\n const durationMilliseconds = state.minutes * MILLISECONDS_PER_MINUTE;\n const elapsedTimeMilliseconds = Math.min(\n durationMilliseconds,\n Math.max(\n 0,\n (status === PerpsTwapLifecycleStatus.Active ? now : lastUpdated) -\n startedAt,\n ),\n );\n const fillProgressBps = totalSize.isGreaterThan(0)\n ? boundedExecutedSize\n .dividedBy(totalSize)\n .multipliedBy(BASIS_POINTS_DIVISOR)\n .integerValue(BigNumber.ROUND_FLOOR)\n .toNumber()\n : 0;\n const timeProgressBps =\n durationMilliseconds > 0\n ? Math.floor(\n (elapsedTimeMilliseconds / durationMilliseconds) *\n BASIS_POINTS_DIVISOR,\n )\n : 0;\n\n return {\n orderId: twapId.toString(),\n symbol: state.coin,\n side: state.side === 'B' ? 'buy' : 'sell',\n size: state.sz,\n executedSize: boundedExecutedSize.toString(),\n remainingSize: remainingSize.toFixed(),\n executedNotional: state.executedNtl,\n ...(executedSize.isGreaterThan(0) && {\n averagePrice: executedNotional.dividedBy(executedSize).toFixed(),\n }),\n fillProgressBps,\n timeProgressBps,\n elapsedTimeMilliseconds,\n durationMinutes: state.minutes,\n randomize: state.randomize,\n reduceOnly: state.reduceOnly,\n status,\n startedAt,\n lastUpdated,\n ...(historyEntry.status.status ===\n HyperLiquidTwapLifecycleStatus.Failed && {\n error: historyEntry.status.description,\n }),\n fills,\n };\n }\n\n /**\n * Rebalance one tracked TWAP at most once at a time. A failed transfer keeps\n * the tracking entry so the next lifecycle read or cancel can retry it.\n *\n * @param trackingKey - Account-scoped TWAP tracking key.\n * @returns Whether no cleanup remains for the entry.\n */\n async #rebalanceTrackedTwapOrder(trackingKey: string): Promise<boolean> {\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n if (!trackedOrder) {\n return true;\n }\n if (!trackedOrder.hip3Transfer) {\n if (this.#trackedTwapOrders.get(trackingKey) === trackedOrder) {\n this.#trackedTwapOrders.delete(trackingKey);\n }\n return true;\n }\n\n let { rebalancePromise } = trackedOrder;\n if (!rebalancePromise) {\n rebalancePromise = this.#handleHip3PostOrderRebalance(\n trackedOrder.hip3Transfer,\n );\n trackedOrder.rebalancePromise = rebalancePromise;\n }\n\n try {\n const success = await rebalancePromise;\n if (\n success &&\n this.#trackedTwapOrders.get(trackingKey) === trackedOrder\n ) {\n this.#trackedTwapOrders.delete(trackingKey);\n }\n return success;\n } finally {\n if (\n this.#trackedTwapOrders.get(trackingKey) === trackedOrder &&\n trackedOrder.rebalancePromise === rebalancePromise\n ) {\n delete trackedOrder.rebalancePromise;\n }\n }\n }\n\n /**\n * Return manually moved HIP-3 collateral after a TWAP reaches a terminal\n * venue state. The scoped registry survives reconnects so an active schedule\n * cannot lose its eventual cleanup path.\n *\n * @param orders - Current and historical TWAP lifecycle records.\n * @param scope - Current account and network identity.\n */\n async #rebalanceTerminalHip3Twaps(\n orders: TwapOrder[],\n scope: TwapAccountScope,\n ): Promise<void> {\n for (const order of orders) {\n if (order.status === PerpsTwapLifecycleStatus.Active) {\n continue;\n }\n\n const trackingKey = getTwapOrderScopeKey({\n ...scope,\n orderId: order.orderId,\n });\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n if (trackedOrder?.symbol !== order.symbol) {\n continue;\n }\n\n await this.#rebalanceTrackedTwapOrder(trackingKey);\n }\n }\n\n /**\n * Read native TWAP schedules and their slice fills from the venue.\n *\n * @returns Current and terminal TWAP lifecycle records, newest first.\n */\n async getTwapOrders(): Promise<TwapOrder[]> {\n await this.#ensureClientsInitialized();\n this.#clientService.ensureInitialized();\n\n const lifecycleGeneration = this.#lifecycleGeneration;\n const infoClient = this.#clientService.getInfoClient();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const [history, sliceFills] = await Promise.all([\n infoClient.twapHistory({ user: userAddress }),\n infoClient.userTwapSliceFills({ user: userAddress }),\n ]);\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'TWAP lifecycle read',\n );\n\n const fillsByTwapId = new Map<number, HyperLiquidTwapSliceFillEntry[]>();\n for (const sliceFill of sliceFills) {\n const existing = fillsByTwapId.get(sliceFill.twapId) ?? [];\n existing.push(sliceFill);\n fillsByTwapId.set(sliceFill.twapId, existing);\n }\n\n const now = Date.now();\n const ordersById = new Map<string, TwapOrder>();\n for (const historyEntry of history) {\n const order = this.#adaptTwapOrder({\n historyEntry,\n sliceFills:\n historyEntry.twapId === undefined\n ? []\n : (fillsByTwapId.get(historyEntry.twapId) ?? []),\n now,\n });\n if (!order) {\n continue;\n }\n\n const existing = ordersById.get(order.orderId);\n if (!existing || supersedesCollapsedTwapOrder(order, existing)) {\n ordersById.set(order.orderId, order);\n }\n }\n\n const orders = [...ordersById.values()].sort(\n (left, right) => right.startedAt - left.startedAt,\n );\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n await this.#rebalanceTerminalHip3Twaps(orders, {\n network,\n userAddress,\n });\n return orders;\n }\n\n /**\n * Return stable client-facing snapshots for every Chase session retained by\n * this provider instance. A read may refresh the current child order's\n * remaining size from the venue, throttled to the Chase interval.\n *\n * @returns Current Chase session snapshots.\n */\n async getChaseOrders(): Promise<ChaseOrder[]> {\n return await Promise.all(\n [...this.#chaseSessions.entries()].map(async ([handle, session]) => {\n const now = Date.now();\n let snapshotRemainingSize = session.size;\n if (\n session.orderId !== null &&\n session.pendingReplacement === null &&\n now - session.lastSnapshotSizeRefreshAt >= session.intervalMs\n ) {\n session.lastSnapshotSizeRefreshAt = now;\n const snapshotOrderId = session.orderId;\n try {\n const liveRemainder = await this.#readOrderRemainder(\n snapshotOrderId,\n CHASE_ORDER_STATUS_RETRY_COUNT,\n );\n if (\n session.orderId === snapshotOrderId &&\n session.pendingReplacement === null\n ) {\n if (liveRemainder.terminalStatus === null) {\n if (liveRemainder.remainingSize !== null) {\n session.size = liveRemainder.remainingSize;\n snapshotRemainingSize = liveRemainder.remainingSize;\n }\n } else {\n session.orderId = null;\n session.size = liveRemainder.remainingSize ?? '0';\n session.active = false;\n if (session.timer) {\n clearTimeout(session.timer);\n session.timer = null;\n }\n session.status = liveRemainder.terminalStatus;\n snapshotRemainingSize = session.size;\n }\n }\n } catch (error) {\n this.#deps.debugLogger.log('Chase snapshot size refresh failed', {\n orderId: snapshotOrderId,\n error: ensureError(error, 'HyperLiquidProvider.getChaseOrders')\n .message,\n });\n }\n }\n\n if (!session.active && session.hip3Transfer) {\n const rebalanced = await this.#rebalanceChaseSession(session);\n if (rebalanced && session.removeAfterRebalance) {\n this.#chaseSessions.delete(handle);\n }\n }\n\n const arrival = Number.parseFloat(session.arrivalPrice);\n const resting = Number.parseFloat(session.restingPrice);\n const adverseDistance = session.isBuy\n ? resting - arrival\n : arrival - resting;\n const measuredDistance =\n Number.isFinite(arrival) &&\n arrival > 0 &&\n Number.isFinite(adverseDistance)\n ? Math.round(\n (Math.max(0, adverseDistance) / arrival) * BASIS_POINTS_DIVISOR,\n )\n : 0;\n return {\n handle,\n symbol: session.symbol,\n side: session.isBuy ? 'buy' : 'sell',\n originalSize: session.originalSize,\n remainingSize: snapshotRemainingSize,\n arrivalPrice: session.arrivalPrice,\n restingPrice: session.restingPrice,\n restingOrderId: session.orderId,\n distanceChasedBps: measuredDistance,\n ...(session.maxDistanceBps === undefined\n ? {}\n : { maxDistanceBps: session.maxDistanceBps }),\n repricings: session.repricings,\n startedAt: session.startedAt,\n status: session.status,\n };\n }),\n );\n }\n\n /**\n * Stop all active Chase loops while deliberately leaving their current\n * post-only children resting. Used when a client moves to the background.\n *\n * @returns Snapshots after every in-flight replacement has settled.\n */\n async suspendChaseOrders(): Promise<ChaseOrder[]> {\n this.#chasePlacementBlockers += 1;\n try {\n await Promise.all([...this.#chasePlacementWaiters]);\n // Clear timers without deactivating sessions, then let any tick already\n // admitted to the shared queue finish its cancel/replace. Stopping first\n // can strand a session between children: the old order is cancelled, the\n // tick observes `active === false`, and suspension reports a resting\n // Chase that no longer owns an exchange order.\n this.#pauseChaseTicksForPlacement();\n await this.#chaseTickQueue;\n\n for (const [sessionId, session] of this.#chaseSessions.entries()) {\n if (!session.active) {\n continue;\n }\n this.#stopChaseSession(sessionId);\n session.status = CHASE_ORDER_STATUS.Backgrounded;\n }\n return await this.getChaseOrders();\n } finally {\n this.#chasePlacementBlockers -= 1;\n }\n }\n\n /**\n * Cancel a strategy placement by its handle.\n *\n * @param params - Cancellation parameters.\n * @returns A promise that resolves to the result.\n */\n async #cancelStrategyOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n try {\n this.#deps.debugLogger.log('Canceling strategy order:', params);\n\n if (params.orderType === 'twap') {\n return await this.#cancelTwapOrder(params);\n }\n if (params.orderType === 'scale') {\n return await this.#cancelScaleOrder(params);\n }\n return await this.#cancelChaseOrder(params);\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrder',\n {\n orderId: params.orderId,\n coin: params.symbol,\n orderType: params.orderType,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n return createErrorResult(mappedError, {\n success: false,\n orderId: params.orderId,\n });\n }\n }\n\n /**\n * Cancel a running TWAP through the venue's TWAP cancel action.\n *\n * A TWAP never rested on the book, so the ordinary `cancel` action has no\n * order ID to match and would reject it.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the TWAP ID.\n * @returns A promise that resolves to the result.\n */\n async #cancelTwapOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n await this.#ensureReady();\n\n const coinValidation = validateCoinExists(\n params.symbol,\n this.#symbolToAssetId,\n );\n if (!coinValidation.isValid) {\n throw new Error(coinValidation.error);\n }\n\n const twapId = Number(params.orderId);\n if (!/^\\d+$/u.test(params.orderId) || !Number.isSafeInteger(twapId)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const trackingKey = getTwapOrderScopeKey({\n network,\n userAddress,\n orderId: params.orderId,\n });\n const trackedOrder = this.#trackedTwapOrders.get(trackingKey);\n let ownershipAuthenticated = trackedOrder !== undefined;\n if (trackedOrder) {\n if (trackedOrder.symbol !== params.symbol) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n } else {\n let venueOrders: TwapOrder[] | null = null;\n try {\n venueOrders = await this.getTwapOrders();\n } catch (error) {\n // History is an ownership check, not the cancellation transport. A\n // transient read failure must not make a live TWAP impossible to stop.\n this.#deps.debugLogger.log(\n 'TWAP history unavailable before cancellation',\n {\n orderId: params.orderId,\n error: ensureError(\n error,\n 'HyperLiquidProvider.cancelTwapOrderHistory',\n ).message,\n },\n );\n }\n const venueOrder = venueOrders?.find(\n (order) => order.orderId === params.orderId,\n );\n if (venueOrders !== null && venueOrder?.symbol !== params.symbol) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n ownershipAuthenticated = venueOrder !== undefined;\n }\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: params.symbol,\n dexName: parseAssetName(params.symbol).dex,\n });\n\n const result = await this.#clientService.getExchangeClient().twapCancel({\n a: assetId,\n t: twapId,\n });\n\n const status = result.response?.data?.status;\n const cancelOutcome = classifyCancelStatus(status);\n if (cancelOutcome === CancelChildOutcome.Gone && !ownershipAuthenticated) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n if (cancelOutcome !== CancelChildOutcome.Refused) {\n await this.#rebalanceTrackedTwapOrder(trackingKey);\n return { success: true, orderId: params.orderId };\n }\n\n const rawError =\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : 'TWAP cancellation failed';\n return createErrorResult(await this.#mapStatusError(rawError, result), {\n success: false,\n orderId: params.orderId,\n });\n }\n\n /**\n * Cancel every child of a scale ladder in one batch.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the group handle.\n * @returns A promise that resolves to the result.\n */\n async #cancelScaleOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n const group = this.#scaleOrderGroups.get(params.orderId);\n if (!group) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol: group.symbol,\n dexName: parseAssetName(group.symbol).dex,\n });\n const exchangeClient = this.#clientService.getExchangeClient();\n const cancelRequests = group.orderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n }));\n const cancelByCloidRequests = group.clientOrderIds.map((clientOrderId) => ({\n asset: assetId,\n cloid: clientOrderId,\n }));\n const [orderCancellation, cloidCancellation] = await Promise.all([\n this.#cancelOrderRequestBatch(exchangeClient, cancelRequests),\n this.#cancelOrderCloidRequestBatch(exchangeClient, cancelByCloidRequests),\n ]);\n const remaining = orderCancellation.remainingOrderIds.map(String);\n const { remainingClientOrderIds } = cloidCancellation;\n\n /*\n * A rung that filled or was cancelled individually comes back as a\n * rejection, but nothing of it is resting. The shared cancellation helper\n * distinguishes that result from a refusal while retaining every child\n * after a malformed or non-ok batch response.\n */\n if (remaining.length === 0 && remainingClientOrderIds.length === 0) {\n this.#cancelledScaleOrderGroups.add(params.orderId);\n this.#scaleOrderGroups.delete(params.orderId);\n return { success: true, orderId: params.orderId };\n }\n\n // A rung the exchange refused to cancel may still be resting. Keeping the\n // handle registered against what is left means the caller can retry the\n // same cancel rather than being told the ladder is gone when it is not.\n this.#scaleOrderGroups.set(params.orderId, {\n symbol: group.symbol,\n orderIds: remaining,\n clientOrderIds: remainingClientOrderIds,\n });\n // The signer could not sign a cancel: retryable, not a defect.\n const signerFailure =\n orderCancellation.signerFailure ?? cloidCancellation.signerFailure;\n if (signerFailure) {\n this.#logRetryableSignerFailure('cancelOrder', {\n orderId: params.orderId,\n orderType: params.orderType,\n });\n return createErrorResult(signerFailure, {\n success: false,\n orderId: params.orderId,\n });\n }\n this.#deps.debugLogger.log('Scale group cancel left children resting', {\n groupId: params.orderId,\n remainingOrderIds: remaining.length,\n remainingClientOrderIds: remainingClientOrderIds.length,\n total: group.orderIds.length + group.clientOrderIds.length,\n });\n\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n { success: false, orderId: params.orderId },\n );\n }\n\n /**\n * Stop a chase session and cancel whatever it still has resting.\n *\n * @param params - Cancellation parameters, with `orderId` carrying the session handle.\n * @returns A promise that resolves to the result.\n */\n async #cancelChaseOrder(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n if (this.#terminatedChaseHandles.has(params.orderId)) {\n return { success: true, orderId: params.orderId };\n }\n const existingTermination = this.#chaseTerminations.get(params.orderId);\n if (existingTermination) {\n return await existingTermination;\n }\n\n const termination = this.#performChaseTermination(params);\n this.#chaseTerminations.set(params.orderId, termination);\n try {\n const result = await termination;\n if (result.success) {\n this.#terminatedChaseHandles.add(params.orderId);\n }\n return result;\n } finally {\n this.#chaseTerminations.delete(params.orderId);\n }\n }\n\n /**\n * Own one Chase termination after concurrent callers have been deduplicated.\n *\n * @param params - Cancellation parameters with a stable Chase handle.\n * @returns The single underlying termination result.\n */\n async #performChaseTermination(\n params: CancelOrderParams,\n ): Promise<CancelOrderResult> {\n const session = this.#chaseSessions.get(params.orderId);\n if (!session) {\n throw new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_HANDLE_UNKNOWN);\n }\n\n // Stopped first: a tick that fired between here and the cancel below would\n // otherwise re-place the very order being cancelled.\n this.#stopChaseSession(params.orderId);\n\n // A replacement already in flight cannot be called off, so the cancel waits\n // for it and then cancels whatever it rested. Deciding without waiting would\n // read the session's null `orderId` as \"nothing rests\" and report a clean\n // cancellation over an order that was about to appear on the book.\n if (session.pendingReplacement) {\n await session.pendingReplacement;\n }\n\n // Nothing rests: the order filled, something else cancelled it, or a\n // replacement failed to go up. Either way the session ends cleanly.\n if (session.orderId === null) {\n session.removeAfterRebalance = true;\n if (await this.#rebalanceChaseSession(session)) {\n this.#chaseSessions.delete(params.orderId);\n }\n return { success: true, orderId: params.orderId };\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n // Only a refusal leaves an order behind. A child that had already filled or\n // been cancelled is reported as a rejection too, but nothing of it is\n // resting — treating that as a failure would pin the handle open forever on\n // a chase that is entirely finished.\n const cancelOutcome = await this.#cancelChaseChild(session);\n\n if (cancelOutcome === CancelChildOutcome.Refused) {\n // The order is still resting. The session stays registered — stopped, but\n // still cancellable — so the caller can retry with the same handle.\n this.#deps.debugLogger.log('Chase cancel left its order resting', {\n sessionId: params.orderId,\n orderId: session.orderId,\n });\n await this.#rebalanceChaseSession(session);\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.ORDER_STRATEGY_CANCEL_INCOMPLETE),\n { success: false, orderId: params.orderId },\n );\n }\n\n session.orderId = null;\n session.status = CHASE_ORDER_STATUS.Canceled;\n session.removeAfterRebalance = true;\n if (await this.#rebalanceChaseSession(session)) {\n this.#chaseSessions.delete(params.orderId);\n }\n return { success: true, orderId: params.orderId };\n }\n\n /**\n * Cancel a batch and retain every order that may still be live.\n *\n * A malformed, truncated, or rejected response cannot prove which requests\n * reached the venue, so every requested ID remains recoverable for a retry.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel requests.\n * @param onError - Optional operation-specific failure classifier.\n * @returns Order IDs that may still be resting.\n */\n async #cancelOrderRequests(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelRequest[],\n onError?: (error: unknown) => void | Promise<void>,\n ): Promise<number[]> {\n return (\n await this.#cancelOrderRequestBatch(exchangeClient, requests, onError)\n ).remainingOrderIds;\n }\n\n /**\n * Cancel pending orders by client order ID and retain every request that may\n * still be live.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel-by-CLOID requests.\n * @returns Client order IDs that may still be resting.\n */\n async #cancelOrderCloidRequests(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelByCloidRequest[],\n ): Promise<Hex[]> {\n return (await this.#cancelOrderCloidRequestBatch(exchangeClient, requests))\n .remainingClientOrderIds;\n }\n\n /**\n * Cancel pending orders by client order ID, reporting a signer that could\n * not sign the cancel.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel-by-CLOID requests.\n * @returns Client order IDs that may still be resting, and the signer\n * failure when the signer could not sign the request.\n */\n async #cancelOrderCloidRequestBatch(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelByCloidRequest[],\n ): Promise<{ remainingClientOrderIds: Hex[]; signerFailure?: Error }> {\n if (requests.length === 0) {\n return { remainingClientOrderIds: [] };\n }\n\n const classifyStatuses = async (\n statuses: unknown[],\n answer: unknown,\n ): Promise<{ remainingClientOrderIds: Hex[]; signerFailure?: Error }> => {\n // A signer failure is classified (and reported) once for the request;\n // entries the venue cancelled are not resting either way.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n return {\n remainingClientOrderIds: requests.flatMap((request, index) =>\n classifyCancelStatus(statuses[index]) === CancelChildOutcome.Refused\n ? [request.cloid]\n : [],\n ),\n ...(signerFailure && { signerFailure }),\n };\n };\n\n try {\n const result = await exchangeClient.cancelByCloid({\n cancels: requests,\n });\n const statuses = result.response?.data?.statuses ?? [];\n if (result.status !== 'ok' || statuses.length !== requests.length) {\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n };\n }\n\n return await classifyStatuses(statuses, result);\n } catch (error) {\n // The SDK throws when any entry failed, with every entry's status.\n const statuses = getCancelStatusesFromError(error, requests.length);\n if (statuses) {\n return await classifyStatuses(statuses, getVenueAnswer(error));\n }\n // The signer could not sign, so nothing was cancelled.\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n signerFailure,\n };\n }\n this.#deps.debugLogger.log('Order cancellation by CLOID failed', {\n error: ensureError(\n error,\n 'HyperLiquidProvider.cancelOrderCloidRequests',\n ).message,\n clientOrderIds: requests.map((request) => request.cloid),\n });\n return {\n remainingClientOrderIds: requests.map((request) => request.cloid),\n };\n }\n }\n\n /**\n * Cancel a batch while distinguishing confirmed cancellations from orders\n * that were already gone. Replacement rollback may only restore the former.\n *\n * @param exchangeClient - Client that owns the orders.\n * @param requests - Venue cancel requests.\n * @param onError - Optional operation-specific failure classifier.\n * @returns IDs that may still rest and IDs this call confirmed it cancelled.\n */\n async #cancelOrderRequestBatch(\n exchangeClient: ExchangeClient,\n requests: ExchangeCancelRequest[],\n onError?: (error: unknown) => void | Promise<void>,\n ): Promise<CancelOrderBatchOutcome> {\n if (requests.length === 0) {\n return {\n remainingOrderIds: [],\n cancelledOrderIds: [],\n responseComplete: true,\n };\n }\n\n const classifyStatuses = async (\n statuses: unknown[],\n answer: unknown,\n ): Promise<CancelOrderBatchOutcome> => {\n // A signer failure is classified (and reported) once for the request;\n // entries the venue cancelled still count as cancelled.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n const remainingOrderIds: number[] = [];\n const cancelledOrderIds: number[] = [];\n requests.forEach((request, index) => {\n const outcome = classifyCancelStatus(statuses[index]);\n if (outcome === CancelChildOutcome.Refused) {\n remainingOrderIds.push(request.o);\n } else if (outcome === CancelChildOutcome.Cancelled) {\n cancelledOrderIds.push(request.o);\n }\n });\n return {\n remainingOrderIds,\n cancelledOrderIds,\n responseComplete: true,\n ...(signerFailure && { signerFailure }),\n };\n };\n\n try {\n const result = await exchangeClient.cancel({ cancels: requests });\n const statuses = result.response?.data?.statuses ?? [];\n if (result.status !== 'ok' || statuses.length !== requests.length) {\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n };\n }\n\n return await classifyStatuses(statuses, result);\n } catch (error) {\n await onError?.(error);\n // The SDK throws when any entry failed, with every entry's status.\n const statuses = getCancelStatusesFromError(error, requests.length);\n if (statuses) {\n return await classifyStatuses(statuses, getVenueAnswer(error));\n }\n // The signer could not sign, so nothing was cancelled.\n const signerFailure = await this.#classifySignerFailure(error);\n if (signerFailure) {\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n signerFailure,\n };\n }\n this.#deps.debugLogger.log('Order cancellation batch failed', {\n error: ensureError(error, 'HyperLiquidProvider.cancelOrderRequests')\n .message,\n orderIds: requests.map((request) => request.o),\n });\n return {\n remainingOrderIds: requests.map((request) => request.o),\n cancelledOrderIds: [],\n responseComplete: false,\n };\n }\n }\n\n /**\n * Read an order ID out of one `order` action status entry.\n *\n * @param status - A single status from the exchange response.\n * @returns The order ID, or undefined when the entry rested nothing.\n */\n #readOrderPlacementOutcome(\n status: unknown,\n ): OrderPlacementOutcome | undefined {\n if (!isStatusObject(status)) {\n return undefined;\n }\n\n for (const state of ['resting', 'filled'] as const) {\n if (!hasProperty(status, state)) {\n continue;\n }\n const order = status[state];\n if (\n isStatusObject(order) &&\n typeof order.oid === 'number' &&\n Number.isSafeInteger(order.oid) &&\n order.oid >= 0\n ) {\n return { orderId: order.oid.toString(), state };\n }\n }\n return undefined;\n }\n\n /**\n * Classify one TP/SL placement response.\n *\n * HyperLiquid acknowledges a resting trigger with the bare\n * `waitingForTrigger` string, which is successful but carries no order ID.\n * Other placement paths still require a resting or filled ID.\n *\n * @param status - A single status from the exchange response.\n * @returns The TP/SL-specific placement outcome.\n */\n #readTpslOrderPlacementOutcome(status: unknown): TpslOrderPlacementOutcome {\n const placement = this.#readOrderPlacementOutcome(status);\n if (placement) {\n return placement;\n }\n if (status === 'waitingForTrigger') {\n return { state: 'waitingForTrigger' };\n }\n if (isStatusObject(status) && hasProperty(status, 'error')) {\n return { state: 'rejected' };\n }\n return { state: 'unknown' };\n }\n\n /**\n * Preserve the raw statuses carried by the SDK's bulk rejection.\n *\n * @param error - SDK exchange error.\n * @returns Exact reported statuses, or undefined for no authoritative batch.\n */\n #readProtectionErrorStatuses(error: unknown): unknown[] | undefined {\n const response =\n error instanceof Error && hasProperty(error, 'response')\n ? error.response\n : undefined;\n return isStatusObject(response) &&\n isStatusObject(response.response) &&\n response.response.type === 'order' &&\n isStatusObject(response.response.data) &&\n Array.isArray(response.response.data.statuses)\n ? response.response.data.statuses\n : undefined;\n }\n\n /**\n * Distinguish a venue rejection from ambiguous transport failure.\n *\n * @param error - SDK exchange error.\n * @returns Whether the venue authoritatively rejected the entire action.\n */\n #isDefinitiveProtectionRejection(error: unknown): boolean {\n const response =\n error instanceof Error && hasProperty(error, 'response')\n ? error.response\n : undefined;\n return (\n isStatusObject(response) &&\n response.status === 'err' &&\n typeof response.response === 'string'\n );\n }\n\n /**\n * Apply both signer invalidation and account-shape classification to writes.\n *\n * @param error - Failed protection write.\n * @returns Actionable error retaining the venue message when unmapped.\n */\n async #classifyProtectionWriteError(error: unknown): Promise<Error> {\n return (\n (await this.#classifySignerFailure(error)) ??\n (isHyperLiquidMultiSigRequiredError(error)\n ? new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)\n : ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'))\n );\n }\n\n /**\n * Correlate protection outcomes only by final signed cloid and market.\n * Unknown/truncated acknowledgements never acquire ownership from book shape.\n *\n * @param params - Captured request identities and scoped status reader.\n * @param params.outcomes - Classified SDK statuses, possibly truncated.\n * @param params.orders - Exact signed orders, including final cloids.\n * @param params.userAddress - Captured submitting account.\n * @param params.infoClient - Captured venue reader.\n * @param params.assertScope - Account/network/lifecycle fence.\n * @param params.symbol - Requested venue market.\n * @returns Ordered outcomes with exact identities where resolved.\n */\n async #reconcileTpslOrderPlacementOutcomes(params: {\n outcomes: TpslOrderPlacementOutcome[];\n orders: SDKOrderParams[];\n userAddress: Hex;\n infoClient: InfoClient;\n assertScope: () => Promise<void>;\n symbol: string;\n }): Promise<TpslOrderPlacementOutcome[]> {\n const correlated: TpslOrderPlacementOutcome[] = [];\n for (const [index, order] of params.orders.entries()) {\n const outcome = params.outcomes[index] ?? { state: 'unknown' as const };\n if (outcome.state === 'rejected' || outcome.orderId !== undefined) {\n correlated.push(outcome);\n continue;\n }\n let resolved = outcome;\n if (order.c !== undefined) {\n await params.assertScope();\n try {\n const status = await params.infoClient.orderStatus({\n user: params.userAddress,\n oid: order.c,\n });\n await params.assertScope();\n if (status.status === 'order') {\n const row = status.order.order;\n if (\n row.coin === params.symbol &&\n row.cloid?.toLowerCase() === order.c.toLowerCase() &&\n Number.isSafeInteger(row.oid) &&\n row.oid > 0\n ) {\n let state: TpslOrderPlacementOutcome['state'] = 'unknown';\n if (status.order.status === 'filled') {\n state = 'filled';\n } else if (status.order.status === 'open') {\n state = 'resting';\n } else if (\n hasProperty(\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS,\n status.order.status,\n )\n ) {\n const terminal =\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS[status.order.status];\n if (terminal === 'canceled' || terminal === 'rejected') {\n state = 'rejected';\n }\n }\n resolved = { orderId: String(row.oid), state };\n }\n }\n } catch {\n await params.assertScope();\n }\n }\n correlated.push(resolved);\n }\n const ids = correlated.flatMap((outcome) =>\n outcome.orderId ? [outcome.orderId] : [],\n );\n return correlated.map((outcome) =>\n outcome.orderId && ids.filter((id) => id === outcome.orderId).length > 1\n ? { state: 'unknown' }\n : outcome,\n );\n }\n\n /**\n * Read a valid order ID from a resting or filled placement status.\n *\n * @param status - A single status from the exchange response.\n * @returns The order ID, or undefined when the status has no valid ID.\n */\n #readOrderIdFromStatus(status: unknown): string | undefined {\n return this.#readOrderPlacementOutcome(status)?.orderId;\n }\n\n /**\n * The builder fee this account pays, after any rewards discount.\n *\n * @returns The fee in tenths of a basis point.\n */\n #getDiscountedBuilderFee(): number {\n if (this.#userFeeDiscountBips === undefined) {\n return BUILDER_FEE_CONFIG.MaxFeeTenthsBps;\n }\n // Shared with the preview so a quoted rate is the rate the venue charges.\n return quantizeBuilderFeeTenthsBps(this.#userFeeDiscountBips);\n }\n\n /**\n * Resolve the builder payload for the current operation.\n *\n * ADR 0064 removed the dedicated subscription builder: every source — the\n * subscription waiver included — now pays through the standard builder at the\n * resolved fee, and the subscription attribution rides on the order's cloid\n * instead (see {@link #applySubscriptionCloid}). That drops the per-user\n * builder approval the ADR rejected, and lets a partial waiver charge a real\n * blended fee, which a dedicated 0-bips builder could not express.\n *\n * @param setupContext - Account, network, and builder approved for the order.\n * @returns HyperLiquid builder address and fee payload.\n */\n async #getBuilderOrderContext(\n setupContext: BuilderFeeSetupContext,\n ): Promise<{ b: string; f: number }> {\n return {\n b: setupContext.builderAddress,\n f: this.#getDiscountedBuilderFee(),\n };\n }\n\n /**\n * Whether the operation in flight actually carries a subscription reduction.\n *\n * Winning the comparison is not sufficient. A nearly-spent allowance produces\n * a blend that approaches the full fee without reaching it, so it still wins\n * on `<=` — but its discount rounds to zero bips and\n * {@link #getDiscountedBuilderFee} then charges the undiscounted fee. Marking\n * such an order would tell the fill fan-out a waiver applied when the user\n * paid full price. The marking therefore follows the charged fee, not the\n * winning source.\n *\n * @returns True when the resolved source is `subscription` and it reduced the fee.\n */\n #isSubscriptionFeeSource(): boolean {\n return (\n this.#userFeeResolution?.source === 'subscription' &&\n this.#getDiscountedBuilderFee() < BUILDER_FEE_CONFIG.MaxFeeTenthsBps\n );\n }\n\n /**\n * Mark an order's cloid for the subscription program when it won the fee.\n *\n * This is the single place a cloid becomes subscription-attributed. Every\n * placement path — primary submit, scale ladder, TP/SL (attached and\n * standalone), batch close, modify/replace, and chase — routes its orders\n * through here, so no path can silently ship an unmarked order while the\n * waiver is being charged, and no other fee source can produce a marked one.\n *\n * A cloid this package generated keeps its trailing entropy, so the Scale\n * ladder's per-rung index and its cancel-by-cloid recovery survive marking.\n * A caller's `OrderParams.clientOrderId` is never rewritten, so those orders\n * go unattributed — which is why `isGenerated` is passed explicitly rather\n * than inferred from the id's leading bytes: a caller is free to supply one\n * that happens to begin with a reserved marker.\n *\n * @param orders - The SDK order payloads about to be submitted.\n * @param generatedCloids - Cloids this package generated for these orders and\n * may therefore re-stamp. Scale ladders and position TP/SL supply these;\n * other paths have no cloid or carry the caller's own.\n * @param marksSubscriptionCloid - Overrides the live fee resolution for a\n * chase replacement, which runs after that resolution has been cleared.\n * @returns The same payloads, with cloids marked when subscription won.\n */\n #applySubscriptionCloid(\n orders: SDKOrderParams[],\n generatedCloids?: ReadonlySet<string>,\n marksSubscriptionCloid?: boolean,\n ): SDKOrderParams[] {\n // A chase replacement decides from the session, because the live resolution\n // was cleared when the caller's `placeOrder` returned. Everything else\n // decides from the resolution in flight.\n const marks = marksSubscriptionCloid ?? this.#isSubscriptionFeeSource();\n if (!marks) {\n // Any other source leaves the id exactly as the caller built it.\n // Position TP/SL already reserves the subscription layout with flag00;\n // the program marker alone never implies a fee reduction.\n return orders;\n }\n\n return orders.map((order) => ({\n ...order,\n c: markSubscriptionCloid({\n clientOrderId: order.c ?? undefined,\n isGenerated:\n order.c !== undefined && Boolean(generatedCloids?.has(order.c)),\n entropy: uuidv4().replace(/-/gu, ''),\n }),\n }));\n }\n\n /**\n * Read the account's currently resting orders.\n *\n * @param params - The lookup parameters.\n * @param params.dexName - DEX to query, or null for the main DEX.\n * @returns The raw open orders.\n */\n async #fetchOpenOrders(params: {\n dexName: string | null;\n }): Promise<FrontendOrder[]> {\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n return await this.#clientService.getInfoClient().frontendOpenOrders({\n user: userAddress,\n dex: params.dexName ?? undefined,\n });\n }\n\n /**\n * Resolve the order id that a `modify` rested the replacement under.\n *\n * HyperLiquid does not edit an order in place: it cancels the target and\n * rests a replacement under a NEW oid, which the SDK's modify response does\n * not carry. The submitted oid therefore names an order that no longer\n * exists, so the only honest source of identity is a post-modify read.\n *\n * An id is returned only when exactly one newly-rested order carries the\n * attributes just submitted. Everything else leaves it absent: a market edit\n * that filled rather than rested, a read that has not caught up yet, or two\n * equally plausible candidates. Novelty is judged against the pre-edit\n * snapshot rather than attributes alone, because an order that was already\n * resting can share a market, side and size with the replacement.\n *\n * @param params - The resolution parameters.\n * @param params.previousOrders - Orders resting immediately before the edit.\n * @param params.dexName - DEX to query, or null for the main DEX.\n * @param params.symbol - Market the edit was submitted against.\n * @param params.isBuy - Direction submitted.\n * @param params.size - Formatted size submitted.\n * @returns The replacement order id, or undefined when it cannot be resolved unambiguously.\n */\n async #resolveReplacementOrderId(params: {\n previousOrders: FrontendOrder[];\n dexName: string | null;\n symbol: string;\n isBuy: boolean;\n size: string;\n }): Promise<string | undefined> {\n try {\n const previousOrderIds = new Set(\n params.previousOrders.map((order) => order.oid.toString()),\n );\n const ordersAfterEdit = await this.#fetchOpenOrders({\n dexName: params.dexName,\n });\n const submittedSize = parseFloat(params.size);\n const candidates = ordersAfterEdit.filter(\n (order) =>\n !previousOrderIds.has(order.oid.toString()) &&\n order.coin === params.symbol &&\n (order.side === 'B') === params.isBuy &&\n parseFloat(order.sz) === submittedSize,\n );\n\n return candidates.length === 1 ? candidates[0].oid.toString() : undefined;\n } catch (error) {\n // The modify was accepted; only the identity lookup failed. Reporting a\n // failed edit here would misstate an order that really was changed.\n this.#deps.debugLogger.log(\n 'Could not resolve the replacement order id after modify:',\n error,\n );\n return undefined;\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 // `modify` rebuilds an order as a plain limit/market order, so a trigger\n // on either side of the edit would be silently dropped. Reject a resting\n // trigger order as well as an edit *into* one; cancel and re-place instead.\n if (isTriggerOrderType(params.newOrder.orderType)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\n };\n }\n\n // A strategy placement is not a single resting order, so there is nothing\n // for `modify` to rewrite: it would submit the edit as an ordinary\n // FrontendMarket modification and quietly drop the TWAP schedule, the\n // ladder, or the chase loop the caller asked for. Cancel by the strategy\n // handle and place again.\n if (isStrategyOrderType(params.newOrder.orderType)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_STRATEGY_UNSUPPORTED,\n };\n }\n\n // The WebSocket order cache is the cheap source for the resting order's\n // placement type, but it may be cold or stale.\n const cachedRestingOrder = this.#subscriptionService\n .getOrdersCacheIfInitialized()\n ?.find((order) => order.orderId === params.orderId.toString());\n if (cachedRestingOrder?.isTrigger === true) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\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 triggerPrice: params.newOrder.triggerPrice,\n takeProfitPrice: params.newOrder.takeProfitPrice,\n stopLossPrice: params.newOrder.stopLossPrice,\n takeProfitSize: params.newOrder.takeProfitSize,\n stopLossSize: params.newOrder.stopLossSize,\n tpslLinkage: params.newOrder.tpslLinkage,\n grouping: params.newOrder.grouping,\n timeInForce: params.newOrder.timeInForce,\n });\n if (!validation.isValid) {\n throw new Error(validation.error);\n }\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(params.newOrder.symbol);\n\n // Initialization only — clients and the asset mapping. The signing half\n // of readiness is deferred until after the checks below, so a refused\n // edit never prompts for a signature or writes an approval.\n await this.#ensureReady();\n\n // What is resting before the edit serves two purposes, and they carry\n // different weight. Verifying the target is REQUIRED when the cache could\n // not do it — an unverified edit can rebuild a protective stop as a plain\n // order — so that read must fail closed. Providing a baseline for the\n // optional orderId resolution is not: when the cache already confirmed the\n // order, a failed read must not sink a modify that would otherwise\n // succeed, exactly as the post-modify lookup does not.\n let ordersBeforeEdit: FrontendOrder[] | undefined;\n\n if (cachedRestingOrder === undefined) {\n ordersBeforeEdit = await this.#fetchOpenOrders({ dexName });\n const restingOrder = ordersBeforeEdit.find(\n (order) => order.oid.toString() === params.orderId.toString(),\n );\n\n if (!restingOrder) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_ORDER_UNVERIFIABLE,\n };\n }\n\n if (restingOrder.isTrigger) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_EDIT_TRIGGER_UNSUPPORTED,\n };\n }\n } else {\n try {\n ordersBeforeEdit = await this.#fetchOpenOrders({ dexName });\n } catch (error) {\n // Only the optional identity baseline is lost. Without it novelty\n // cannot be judged, so the id is omitted below rather than guessed.\n this.#deps.debugLogger.log(\n 'Could not read the pre-edit orders baseline:',\n error,\n );\n }\n }\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 helper as placeOrder so the\n // slippage rules stay in one place (bps → decimal, market-only, default).\n // Accept the deprecated decimal `slippage` field too, normalizing to bps.\n const normalizedMaxSlippageBps =\n params.newOrder.maxSlippageBps ??\n (typeof params.newOrder.slippage === 'number'\n ? Math.round(params.newOrder.slippage * BASIS_POINTS_DIVISOR)\n : undefined);\n // calculateOrderPriceAndSize formats with formatHyperLiquidSize, which\n // rounds half-up. On a reduce-only edit that can submit a size above the\n // one requested, which HyperLiquid rejects with \"Reduce only order would\n // increase position\", so floor onto the size grid first. An opening edit\n // keeps its existing rounding: it has no position ceiling to breach.\n const requestedSize = parseFloat(params.newOrder.size);\n const sizeForSubmission =\n params.newOrder.reduceOnly === true\n ? floorToSizeDecimals(requestedSize, assetInfo.szDecimals)\n : requestedSize;\n\n // Refuse non-numeric and non-positive sizes before formatting or submit.\n if (!(sizeForSubmission > 0)) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE,\n };\n }\n\n const { formattedSize, formattedPrice } = calculateOrderPriceAndSize({\n orderType: params.newOrder.orderType,\n isBuy: params.newOrder.isBuy,\n finalPositionSize: sizeForSubmission,\n currentPrice,\n limitPrice: params.newOrder.price,\n maxSlippageBps: normalizedMaxSlippageBps,\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 // A limit order honours the caller's time in force; validation above has\n // already rejected one on any other order shape.\n t:\n params.newOrder.orderType === 'limit'\n ? { limit: { tif: toSDKTimeInForce(params.newOrder.timeInForce) } }\n : { limit: { tif: 'FrontendMarket' } }, // True market order\n c: params.newOrder.clientOrderId\n ? params.newOrder.clientOrderId\n : undefined,\n };\n\n // Every refusal is behind us, so shared trading readiness can run now.\n // HyperLiquid's modify action has no builder field and must not request a\n // builder-fee approval.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // Submit modification via SDK. The cloid is deliberately left unmarked:\n // `modify` carries no builder field, as the readiness call above records,\n // so no MetaMask fee is charged on this action and marking it would tell\n // the fill fan-out a reduction applied to an order that paid nothing.\n // The replacement inherits the resting order's own attribution.\n const exchangeClient = this.#clientService.getExchangeClient();\n const result = await exchangeClient.modify({\n oid:\n typeof params.orderId === 'string' ? params.orderId : 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 // `params.orderId` is the order that was just REPLACED, so returning it\n // as OrderResult.orderId (documented as the exchange order ID) names an\n // order the venue has already cancelled. Report the replacement when it\n // can be resolved unambiguously, and otherwise omit the optional id\n // rather than fabricate identity.\n const replacementOrderId =\n ordersBeforeEdit === undefined\n ? undefined\n : await this.#resolveReplacementOrderId({\n previousOrders: ordersBeforeEdit,\n dexName,\n symbol: params.newOrder.symbol,\n isBuy: params.newOrder.isBuy,\n size: formattedSize,\n });\n\n return {\n success: true,\n ...(replacementOrderId === undefined\n ? {}\n : { orderId: replacementOrderId }),\n };\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'editOrder',\n {\n orderId: params.orderId,\n },\n );\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.editOrder'),\n this.#getErrorContext(\n 'editOrder',\n {\n orderId: params.orderId,\n coin: params.newOrder.symbol,\n orderType: params.newOrder.orderType,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.EditOrder,\n },\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 // A strategy handle is not an exchange order ID, so it cannot go through\n // the single-order cancel below. Callers that omit `orderType` — every\n // existing one — keep the behaviour they have today.\n if (params.orderType && isStrategyOrderType(params.orderType)) {\n return await this.#cancelStrategyOrder(params);\n }\n\n // Resolve ownership before the first await. A reprice can change the child\n // ID while an ordinary cancel is in flight; cancelling through the stable\n // session handle stops the loop, joins any replacement, and removes the\n // current child instead of leaving a replacement chasing behind the user.\n const owningChase = [...this.#chaseSessions.entries()].find(\n ([, session]) =>\n session.orderId === params.orderId ||\n session.replacingOrderId === params.orderId,\n );\n try {\n if (owningChase) {\n this.#stopChaseSession(owningChase[0]);\n await this.#chaseTickQueue;\n const result = await this.#cancelChaseOrder({\n ...params,\n orderId: owningChase[0],\n orderType: 'chase',\n });\n return { ...result, orderId: params.orderId };\n }\n\n this.#deps.debugLogger.log('Canceling order:', params);\n\n // Hydrate the asset map before coin validation so a cold start (e.g.\n // service-worker restart with an empty prefetch map) can self-heal\n // without signature prompts on invalid cancels. Trading setup (builder\n // referral and unified-account setup runs only after validation passes,\n // matching placeOrder / editOrder. Cancel has no builder field.\n await this.#ensureReady();\n\n const coinValidation = validateCoinExists(\n params.symbol,\n this.#symbolToAssetId,\n );\n if (!coinValidation.isValid) {\n throw new Error(coinValidation.error);\n }\n\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\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 status: unknown = result.response?.data?.statuses?.[0];\n if (status === 'success') {\n return {\n success: true,\n orderId: params.orderId,\n };\n }\n\n // HyperLiquid usually rejects a cancel without throwing: the status entry\n // carries the raw exchange string (e.g. \"multi-sig required\"). Map it the\n // same way as a thrown rejection so callers get a standardized code\n // instead of a generic message.\n const rawError =\n isStatusObject(status) && typeof status.error === 'string'\n ? status.error\n : 'Order cancellation failed';\n\n return createErrorResult(await this.#mapStatusError(rawError, result), {\n success: false,\n orderId: params.orderId,\n });\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrder',\n {\n orderId: params.orderId,\n coin: params.symbol,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n return createErrorResult(mappedError, {\n success: false,\n orderId: params.orderId,\n });\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 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 const results: CancelOrdersResult['results'] = params.map((order) => ({\n orderId: order.orderId,\n symbol: order.symbol,\n success: false,\n error: PERPS_ERROR_CODES.BATCH_CANCEL_FAILED,\n }));\n\n // Resolve Chase ownership before the first await. A queued reprice may\n // replace the child ID, but the stable session handle still reaches it.\n const chaseSessions = [...this.#chaseSessions.entries()];\n const chaseRoutes = params.flatMap((order, index) => {\n const owner = chaseSessions.find(\n ([, session]) =>\n session.orderId === order.orderId ||\n session.replacingOrderId === order.orderId,\n );\n return owner ? [{ handle: owner[0], index, order }] : [];\n });\n const chaseIndexes = new Set(chaseRoutes.map(({ index }) => index));\n\n try {\n for (const handle of new Set(chaseRoutes.map((route) => route.handle))) {\n this.#stopChaseSession(handle);\n }\n if (chaseRoutes.length > 0) {\n await this.#chaseTickQueue;\n }\n for (const { handle, index, order } of chaseRoutes) {\n const result = await this.#cancelStrategyOrder({\n orderId: handle,\n symbol: order.symbol,\n orderType: 'chase',\n });\n results[index] = {\n orderId: order.orderId,\n symbol: order.symbol,\n success: result.success,\n ...(result.error === undefined ? {} : { error: result.error }),\n };\n }\n\n const ordinaryOrders = params.flatMap((order, index) =>\n chaseIndexes.has(index) ? [] : [{ index, order }],\n );\n if (ordinaryOrders.length > 0) {\n // Cancellation carries no builder context, so it must not prompt for a\n // fee approval that the action cannot use.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n const exchangeClient = this.#clientService.getExchangeClient();\n const cancelRequests = await Promise.all(\n ordinaryOrders.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 let statuses: unknown[] | undefined;\n let answer: unknown;\n try {\n const result = await exchangeClient.cancel({\n cancels: cancelRequests,\n });\n answer = result;\n const returnedStatuses = result.response?.data?.statuses ?? [];\n statuses =\n result.status === 'ok' &&\n returnedStatuses.length === ordinaryOrders.length\n ? returnedStatuses\n : undefined;\n } catch (error) {\n // The SDK throws when any entry failed, with every entry's status.\n answer = getVenueAnswer(error);\n statuses = getCancelStatusesFromError(error, ordinaryOrders.length);\n if (!statuses) {\n throw error;\n }\n }\n\n if (statuses) {\n // One signature covers the batch, so a signer failure is classified\n // (and reported to the host) once. Each entry keeps its own result.\n const signerFailure = await this.#classifyStatusSignerFailure(\n statuses,\n answer,\n );\n for (const [\n statusIndex,\n { index, order },\n ] of ordinaryOrders.entries()) {\n const status: unknown = statuses[statusIndex];\n const success = status === 'success';\n const statusError =\n isStatusObject(status) && typeof status.error === 'string'\n ? createStatusError(status.error, answer)\n : undefined;\n let error: string = PERPS_ERROR_CODES.BATCH_CANCEL_FAILED;\n if (statusError) {\n error =\n signerFailure && (await this.#isSignerFailure(statusError))\n ? signerFailure.message\n : this.#mapError(statusError).message;\n }\n results[index] = {\n orderId: order.orderId,\n symbol: order.symbol,\n success,\n ...(success ? {} : { error }),\n };\n }\n }\n }\n } catch (error) {\n const mappedError = await this.#reportWriteError(\n error,\n 'cancelOrders',\n {\n orderCount: params.length,\n },\n {\n operation: PERPS_ERROR_OPERATION.OrderManagement,\n action: PERPS_ERROR_ACTION.CancelOrder,\n },\n );\n for (const result of results) {\n if (\n !result.success &&\n result.error === PERPS_ERROR_CODES.BATCH_CANCEL_FAILED\n ) {\n result.error =\n error instanceof Error\n ? mappedError.message\n : PERPS_ERROR_CODES.BATCH_CANCEL_FAILED;\n }\n }\n }\n\n const successCount = results.filter(({ success }) => success).length;\n return {\n success: successCount > 0,\n successCount,\n failureCount: results.length - successCount,\n results,\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 const unavailableResults: ClosePositionsResult['results'] = [];\n\n try {\n // Batch preparation needs trading readiness but not builder approval yet.\n // The provider-owned market policy is resolved from the positions below.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // Selected symbols only need the DEXes they belong to. Loading every\n // market group would refuse a BTC close when an unrelated HIP-3 DEX\n // cannot be read. closeAll / empty symbols still need a complete\n // snapshot so a missed DEX cannot be reported as \"nothing to close\".\n // Per-DEX loads are independent: a requested xyz outage must not\n // abort a BTC close in the same symbols list.\n const requestedSymbols =\n params.closeAll === true ||\n params.symbols === undefined ||\n params.symbols.length === 0\n ? undefined\n : params.symbols;\n let positions: Position[];\n if (requestedSymbols === undefined) {\n positions = await this.#getPositionsForOperation();\n } else {\n const dexNames = [\n ...new Set(\n requestedSymbols.map((symbol) => parseAssetName(symbol).dex ?? ''),\n ),\n ];\n const settled = await Promise.allSettled(\n dexNames.map((dexName) => this.#getPositionsForOperation(dexName)),\n );\n positions = [];\n settled.forEach((outcome, index) => {\n if (outcome.status === 'fulfilled') {\n positions.push(...outcome.value);\n return;\n }\n const message =\n outcome.reason instanceof Error\n ? outcome.reason.message\n : String(outcome.reason);\n if (message !== PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE) {\n throw outcome.reason;\n }\n const failedDex = dexNames[index];\n for (const symbol of requestedSymbols) {\n if ((parseAssetName(symbol).dex ?? '') === failedDex) {\n unavailableResults.push({\n symbol,\n success: false,\n error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,\n });\n }\n }\n });\n }\n\n positionsToClose =\n requestedSymbols === undefined\n ? positions\n : positions.filter((pos) => requestedSymbols.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 if (unavailableResults.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: 0,\n results: [],\n };\n }\n return {\n success: false,\n successCount: 0,\n failureCount: unavailableResults.length,\n error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,\n results: unavailableResults,\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 // Freed-margin transfer for each submitted order, or null when that order\n // needs none. One entry per order rather than one per HIP-3 position: a\n // compacted list read with the response-status index credits the wrong\n // order in a mixed main-DEX/HIP-3 batch.\n const orderedHip3Transfers: ({\n sourceDex: string;\n freedMargin: number;\n } | null)[] = [];\n\n // Build orders array, plus the positions each order closes so response\n // statuses stay index-aligned when a position is skipped below\n const orders: SDKOrderParams[] = [];\n const feePolicyContexts: OrderParams[] = [];\n const orderedPositions: Position[] = [];\n // Positions no order could be built for. Reported as failures so a caller\n // cannot read \"closed everything\" from a result that left one open.\n const skippedResults: ClosePositionsResult['results'] = [];\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 // formatHyperLiquidSize() below rounds half-up, so floor onto the size\n // grid first: a reduce-only order rounded above the position is rejected\n // with \"Reduce only order would increase position\".\n const flooredCloseSize = floorToSizeDecimals(\n closeSize,\n assetInfo.szDecimals,\n );\n\n // A dust position worth less than one size increment floors to 0, which\n // would submit a zero-size order. Skip it rather than sending an order\n // the exchange must reject; the remaining positions still close, and the\n // skip is reported as a failure below.\n if (flooredCloseSize <= 0) {\n this.#deps.debugLogger.log(\n 'Skipping position smaller than one size increment',\n { coin: position.symbol, size: position.size },\n );\n skippedResults.push({\n symbol: position.symbol,\n success: false,\n error: PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE,\n });\n continue;\n }\n\n // Track this order's HIP-3 transfer, if it needs one (a full position\n // close frees all of its margin). Pushed below alongside the order so the\n // two stay index-aligned.\n const hip3Transfer =\n isHip3Position && dexName && !this.#useUnifiedAccount\n ? { sourceDex: dexName, freedMargin: totalMarginUsed }\n : null;\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 const formattedSize = formatHyperLiquidSize({\n size: flooredCloseSize,\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 feePolicyContexts.push({\n symbol: position.symbol,\n isBuy,\n size: formattedSize,\n orderType: 'market',\n reduceOnly: true,\n });\n orderedPositions.push(position);\n orderedHip3Transfers.push(hip3Transfer);\n }\n\n // Every position was smaller than one size increment. Return their\n // failures rather than an empty result, which would be indistinguishable\n // from \"no positions matched\".\n if (orders.length === 0) {\n return {\n success: false,\n successCount: 0,\n failureCount: skippedResults.length + unavailableResults.length,\n results: [...skippedResults, ...unavailableResults],\n };\n }\n\n // HyperLiquid accepts one builder context for the whole close batch.\n // Resolve every position context and charge the batch when any included\n // policy charges, preserving deterministic behavior for future policies\n // that vary by market or route.\n const chargesMetamaskBuilderFee = feePolicyContexts.some(\n (context) =>\n this.#resolveOrderFeePolicy(context).chargesMetamaskBuilderFee,\n );\n const builder = chargesMetamaskBuilderFee\n ? await this.#getBuilderOrderContext(\n await this.#ensureReadyForTrading({ requiresBuilderFee: true }),\n )\n : undefined;\n\n // Single batch API call\n const result = await exchangeClient.order({\n orders: this.#applySubscriptionCloid(orders),\n grouping: 'na',\n ...(builder && { builder }),\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 =\n statuses.length -\n successCount +\n skippedResults.length +\n unavailableResults.length;\n\n // Handle HIP-3 margin transfers for successful closes\n if (!this.#useUnifiedAccount) {\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 const transfer = orderedHip3Transfers[i];\n\n if (isSuccess && transfer) {\n const { sourceDex, freedMargin } = transfer;\n this.#deps.debugLogger.log(\n 'Position closed successfully, initiating manual auto-transfer back',\n { symbol: orderedPositions[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 // Index submitted and skipped outcomes by symbol so `results` can keep the\n // order of the requested positions: consumers may correlate them by index.\n const submittedResults = new Map(\n statuses.map((status, index) => [\n orderedPositions[index].symbol,\n {\n symbol: orderedPositions[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 );\n const skippedBySymbol = new Map(\n skippedResults.map((skipped) => [skipped.symbol, skipped]),\n );\n\n return {\n success: successCount > 0,\n successCount,\n failureCount,\n results: [\n ...positionsToClose.flatMap((position) => {\n const outcome =\n submittedResults.get(position.symbol) ??\n skippedBySymbol.get(position.symbol);\n return outcome ? [outcome] : [];\n }),\n ...unavailableResults,\n ],\n };\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'closePositions',\n {\n positionCount: positionsToClose.length,\n },\n );\n const safeError =\n signerFailure ??\n ensureError(error, 'HyperLiquidProvider.closePositions');\n if (!signerFailure) {\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext(\n 'closePositions',\n {\n positionCount: positionsToClose.length,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.ClosePosition,\n },\n ),\n );\n }\n // Return all selected positions as failed, including unavailable DEXes.\n return {\n success: false,\n successCount: 0,\n failureCount: positionsToClose.length + unavailableResults.length,\n error:\n error instanceof Error\n ? safeError.message\n : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,\n results: [\n ...positionsToClose.map((position) => ({\n symbol: position.symbol,\n success: false,\n error:\n error instanceof Error\n ? safeError.message\n : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,\n })),\n ...unavailableResults,\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 * Partial TP/SL: when `takeProfitSize` or `stopLossSize` is supplied, the\n * orders cannot use 'positionTpsl' (which always covers the whole position and\n * requires size 0). They are submitted as standalone reduce-only trigger orders\n * with 'na' grouping and explicit sizes instead.\n *\n * Note that the pre-cancel sweep clears every standalone reduce-only trigger\n * on the symbol — whether this update is partial or whole-position — not only\n * the ones this method placed. A trigger the caller placed independently\n * through `placeOrder` (for example a manual reduce-only stop) is therefore\n * cancelled too. Only TP/SL children of another pending order are protected.\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 * @param params.takeProfitSize - Partial TP size (undefined for the whole position)\n * @param params.stopLossSize - Partial SL size (undefined for the whole position)\n * @returns A promise that resolves to the result.\n */\n async updatePositionTPSL(\n params: UpdatePositionTPSLParams,\n ): Promise<OrderResult> {\n const expectedPosition =\n params.expectedPosition === undefined\n ? undefined\n : { ...params.expectedPosition };\n try {\n if (\n params.partialPairLinkage !== undefined &&\n (params.partialPairLinkage !== 'independent' ||\n !params.takeProfitPrice ||\n !params.stopLossPrice ||\n (params.takeProfitSize === undefined &&\n params.stopLossSize === undefined))\n ) {\n throw new Error(\n 'Hyperliquid partial pair linkage requires an independently sized TP/SL pair',\n );\n }\n\n const lifecycle = this.#lifecycleGeneration;\n const isTestnet = this.#clientService.isTestnetMode();\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const assertScope = async (): Promise<void> => {\n const current = await this.#walletService.getUserAddressWithDefault();\n this.#assertProviderLifecycleCurrent(lifecycle, 'updatePositionTPSL');\n if (\n current.toLowerCase() !== userAddress.toLowerCase() ||\n this.#clientService.isTestnetMode() !== isTestnet\n ) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n };\n await assertScope();\n this.#deps.debugLogger.log('Updating position TP/SL:', params);\n\n const {\n symbol,\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n position: livePosition,\n } = params;\n\n const isPartialTpsl =\n takeProfitSize !== undefined || stopLossSize !== undefined;\n\n // Basic initialization only. The trading setup that can prompt a hardware\n // wallet and write the referral / builder-fee approvals is deferred until\n // every validation below has passed, so a rejected update leaves nothing\n // behind.\n await this.#ensureReady();\n\n // A caller snapshot is only a hint. Use the current-connection DEX slice\n // when available, otherwise query that DEX over HTTP. If neither source\n // answers, fail closed: trusting the snapshot would recreate the stale\n // side/size reduce-only rejection this method is meant to prevent.\n const currentPositions = await this.#getPositionsForOperation(\n parseAssetName(symbol).dex ?? '',\n { revalidateMissingSymbol: symbol },\n );\n const position = currentPositions.find((pos) => pos.symbol === symbol);\n\n if (\n livePosition &&\n position &&\n parseFloat(position.size) !== parseFloat(livePosition.size)\n ) {\n this.#deps.debugLogger.log(\n 'Stale TP/SL position snapshot: using current position',\n {\n symbol,\n snapshotSize: livePosition.size,\n liveSize: position.size,\n },\n );\n }\n\n await assertScope();\n assertExpectedPosition(expectedPosition, position);\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\n }\n\n const positionSize = Math.abs(parseFloat(position.size));\n const isLong = parseFloat(position.size) > 0;\n\n // Partial TP/SL sizes must be positive, paired with their price, and no\n // larger than the position they close.\n const tpslSizeValidation = validateOrderParams({\n coin: symbol,\n size: positionSize.toString(),\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n });\n if (!tpslSizeValidation.isValid) {\n return {\n success: false,\n error: tpslSizeValidation.error,\n };\n }\n\n // Get clients for API calls (#ensureReady already called at method start).\n // Holding the exchange client reference is not itself a write; it is only\n // used below, after the trading setup has run.\n const infoClient = this.#clientService.getInfoClient();\n await assertScope();\n\n // Extract DEX name for API calls (main DEX = null)\n const { dex: dexName } = parseAssetName(symbol);\n\n // Asset info is resolved before the pre-cancel sweep so a partial size\n // that rounds away at the asset precision is rejected while the\n // position's existing triggers are still in place. Rejecting it after the\n // sweep would leave the position unprotected with nothing put back.\n const meta = await this.#getCachedMeta({ dexName });\n\n // Check if meta is an error response (string) or doesn't have universe property\n if (\n !meta ||\n typeof meta === 'string' ||\n !meta.universe ||\n !Array.isArray(meta.universe)\n ) {\n this.#deps.debugLogger.log(\n 'Failed to fetch metadata for asset mapping',\n {\n meta,\n dex: dexName ?? 'main',\n },\n );\n throw new Error(\n `Failed to fetch market metadata for DEX ${dexName ?? 'main'}`,\n );\n }\n\n // asset.name format: \"BTC\" for main DEX, \"xyz:XYZ100\" for HIP-3\n const assetInfo = meta.universe.find((asset) => asset.name === symbol);\n if (!assetInfo) {\n throw new Error(\n `Asset ${symbol} not found in ${dexName ?? 'main'} DEX universe`,\n );\n }\n\n const precision = validateOrderPrecision({\n takeProfitPrice,\n stopLossPrice,\n takeProfitSize,\n stopLossSize,\n szDecimals: assetInfo.szDecimals,\n });\n if (!precision.isValid) {\n return {\n success: false,\n error: precision.error,\n };\n }\n\n const assetId = await this.#getAssetIdWithRepair({\n symbol,\n dexName,\n });\n\n // Keep whole-position trigger formatting fail-safe too. Venue positions\n // are normally grid-aligned, but flooring guarantees a reduce-only child\n // never exceeds the position if an upstream value is not.\n const fullSize =\n TP_SL_CONFIG.UsePositionBoundTpsl && !isPartialTpsl\n ? '0'\n : formatHyperLiquidSize({\n size: floorToSizeDecimals(positionSize, assetInfo.szDecimals),\n szDecimals: assetInfo.szDecimals,\n });\n\n // Partial TP/SL orders carry their own size; the rest cover the position.\n // A partial size that rounds away at the asset precision is rejected\n // rather than sent as '0', which the exchange reads as whole-position.\n const resolveTpslSize = (tpslSize?: string): string =>\n tpslSize === undefined\n ? fullSize\n : formatPartialTpslSize({\n size: parseFloat(tpslSize),\n szDecimals: assetInfo.szDecimals,\n });\n\n // HyperLiquid accepts one builder context for the whole TP/SL action.\n // Position TP/SL has no parent policy to inherit, so resolve every\n // included trigger and charge the batch when any child policy charges.\n const feePolicyContexts = [\n ...(takeProfitPrice\n ? [\n {\n symbol,\n isBuy: !isLong,\n size: resolveTpslSize(takeProfitSize),\n orderType: 'take_profit_limit',\n price: takeProfitPrice,\n triggerPrice: takeProfitPrice,\n reduceOnly: true,\n } satisfies OrderParams,\n ]\n : []),\n ...(stopLossPrice\n ? [\n {\n symbol,\n isBuy: !isLong,\n size: resolveTpslSize(stopLossSize),\n orderType: 'stop_market',\n triggerPrice: stopLossPrice,\n reduceOnly: true,\n } satisfies OrderParams,\n ]\n : []),\n ];\n const replacementChargesMetamaskBuilderFee = feePolicyContexts.some(\n (feePolicyContext) =>\n this.#resolveOrderFeePolicy(feePolicyContext)\n .chargesMetamaskBuilderFee,\n );\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 let cancelRequests: ExchangeCancelRequest[] = [];\n const restorablePositionTpslOrders: RestorableTpslOrder[] = [];\n const restorableStandaloneTpslOrders: RestorableTpslOrder[] = [];\n\n // Every replacement must cancel first so old and new reduce-only triggers\n // cannot execute together. Retain the exact trigger definitions so a\n // definitively failed replacement can restore confirmed cancellations.\n const captureRestorableTpslOrders = (tpslOrders: Order[]): void => {\n if (!takeProfitPrice && !stopLossPrice) {\n return;\n }\n\n tpslOrders.forEach((order) => {\n const orderId = Number(order.orderId);\n const orderType = order.triggerOrderType;\n const triggerPrice = order.triggerPrice ?? order.price;\n if (!Number.isSafeInteger(orderId) || !orderType || !triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n\n const size = order.isPositionTpsl ? '0' : order.remainingSize;\n const isBuy = order.side === 'buy';\n const feePolicyContext = {\n symbol,\n isBuy,\n size,\n orderType,\n triggerPrice,\n reduceOnly: true,\n ...(isLimitExecutionOrderType(orderType) && {\n price: order.price,\n }),\n } satisfies OrderParams;\n const restorableOrder = {\n orderId,\n order: {\n a: assetId,\n b: isBuy,\n p: order.price,\n s: size,\n r: true,\n t: {\n trigger: {\n isMarket: !isLimitExecutionOrderType(orderType),\n triggerPx: triggerPrice,\n tpsl: getTriggerDirection(orderType) === 'stop' ? 'sl' : 'tp',\n },\n },\n },\n chargesMetamaskBuilderFee:\n this.#resolveOrderFeePolicy(feePolicyContext)\n .chargesMetamaskBuilderFee,\n } satisfies RestorableTpslOrder;\n\n if (order.isPositionTpsl) {\n restorablePositionTpslOrders.push(restorableOrder);\n } else {\n restorableStandaloneTpslOrders.push(restorableOrder);\n }\n });\n };\n\n // Use atomic getter to prevent race condition between check and get\n const cachedOrders =\n this.#subscriptionService.getOrdersCacheIfInitialized();\n\n // Replacing TP/SL has to consider standalone ('na' grouping) triggers —\n // left by a partial update or placed independently — which are not\n // position-bound. Telling those apart from a pending order's normalTpsl\n // child requires the parent/child relationship, which only the REST\n // payload carries. The cache path is therefore only safe when the cache\n // shows no such trigger on this market: a partial update always places\n // standalone triggers, and a whole-position update must still clear any\n // standalone leftovers instead of letting them fire beside the new\n // position-bound orders.\n const cacheShowsStandaloneTriggers = Boolean(\n cachedOrders?.some(\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 );\n\n if (\n cachedOrders === null ||\n isPartialTpsl ||\n cacheShowsStandaloneTriggers\n ) {\n // Fallback: Query only the specific DEX (20 weight instead of 40+)\n this.#deps.debugLogger.log(\n cachedOrders === null\n ? 'WebSocket cache not initialized, falling back to single-DEX REST query'\n : 'TP/SL update needs parent/child order context: using single-DEX REST query',\n { dex: dexName ?? 'main', isPartialTpsl },\n );\n\n const openOrders = await infoClient.frontendOpenOrders({\n user: userAddress,\n dex: dexName ?? undefined,\n });\n\n // Orders that belong to a pending parent order (normalTpsl children) are\n // also listed at the top level, so collect their IDs to exclude them:\n // they protect that pending order, not this position.\n const childOrderIds = collectChildOrderIds(openOrders);\n\n // Filter using raw SDK response properties\n const tpslOrders = openOrders.filter(\n (order) =>\n order.coin === symbol &&\n order.reduceOnly &&\n // Position-bound TP/SL always qualifies, and so do standalone\n // triggers on this market (they belong to the position too, whether\n // this update is partial or whole) — but never another order's\n // TP/SL children.\n (order.isPositionTpsl ===\n Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) ||\n !childOrderIds.has(order.oid)) &&\n order.isTrigger &&\n (order.orderType.includes('Take Profit') ||\n order.orderType.includes('Stop')),\n );\n\n captureRestorableTpslOrders(\n tpslOrders.map((order) => adaptOrderFromSDK(order, position)),\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 captureRestorableTpslOrders(tpslOrders);\n cancelRequests = tpslOrders.map((order) => ({\n a: assetId,\n o: parseInt(order.orderId, 10),\n }));\n }\n\n // Build orders array for TP/SL\n const orders: SDKOrderParams[] = [];\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: resolveTpslSize(takeProfitSize),\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: resolveTpslSize(stopLossSize),\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 const generatedCloids = new Set<string>();\n for (const order of orders) {\n order.c = createUnmarkedProtectionCloid(generatedCloids);\n }\n const assertCurrentPosition = async (): Promise<void> => {\n await assertScope();\n if (expectedPosition) {\n const state = await infoClient.clearinghouseState({\n user: userAddress,\n ...(dexName ? { dex: dexName } : {}),\n });\n await assertScope();\n const current = state.assetPositions.find(\n (entry) => entry.position.coin === symbol,\n );\n assertExpectedPosition(\n expectedPosition,\n current\n ? {\n size: current.position.szi,\n entryPrice: current.position.entryPx ?? '',\n }\n : undefined,\n );\n }\n };\n await assertCurrentPosition();\n // These operation-local reads run inside the SDK signing semaphore.\n // The extra round trips deliberately serialize with the signed write,\n // preventing stale account-shape/position dispatch after wallet prompts.\n const assertWritableScope = async (): Promise<void> => {\n await assertScope();\n const isMultiSig = await this.#isHyperliquidMultiSigAccount(\n userAddress,\n infoClient,\n );\n await assertScope();\n if (isMultiSig) {\n throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);\n }\n };\n let cancelGuardFailure: unknown;\n const exchangeClient = this.#clientService.getExchangeClient(async () => {\n try {\n await assertWritableScope();\n await assertCurrentPosition();\n } catch (error) {\n cancelGuardFailure = error;\n throw error;\n }\n });\n const recoveryExchangeClient =\n this.#clientService.getExchangeClient(assertWritableScope);\n let replacementMayHaveDispatched = false;\n const replacementExchangeClient = this.#clientService.getExchangeClient(\n async () => {\n await assertWritableScope();\n await assertCurrentPosition();\n replacementMayHaveDispatched = true;\n },\n );\n\n const rollbackRequiresBuilderFee = [\n ...restorablePositionTpslOrders,\n ...restorableStandaloneTpslOrders,\n ].some((order) => order.chargesMetamaskBuilderFee);\n const requiresBuilderFee =\n replacementChargesMetamaskBuilderFee || rollbackRequiresBuilderFee;\n\n // Approval and builder-context resolution both finish before the\n // pre-cancel. A failure here therefore leaves the old protection intact.\n const builderFeeSetupContext = requiresBuilderFee\n ? await this.#ensureReadyForTrading({\n requiresBuilderFee: true,\n builderFeeApprovalFailureCode: PERPS_ERROR_CODES.TPSL_UPDATE_FAILED,\n })\n : await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n const builderOrderContext = builderFeeSetupContext\n ? await this.#getBuilderOrderContext(builderFeeSetupContext)\n : undefined;\n\n const sentOrders = this.#applySubscriptionCloid(orders, generatedCloids);\n if (\n new Set(sentOrders.map((order) => order.c)).size !== sentOrders.length\n ) {\n throw new Error('Duplicate final TP/SL client order identity');\n }\n\n const restoreCancelledProtection = async (\n cancelledOrderIds: Set<number>,\n ): Promise<TpslProtectionRestorationOutcome> => {\n const restoredOrderIds: string[] = [];\n let success = true;\n const protectionGroups: {\n grouping: 'positionTpsl' | 'na';\n entries: RestorableTpslOrder[];\n }[] = [\n {\n grouping: 'positionTpsl',\n entries: restorablePositionTpslOrders,\n },\n {\n grouping: 'na',\n entries: restorableStandaloneTpslOrders,\n },\n ];\n for (const protection of protectionGroups) {\n const entries = protection.entries.filter((entry) =>\n cancelledOrderIds.has(entry.orderId),\n );\n if (entries.length === 0) {\n continue;\n }\n\n const restorationOrders = entries.map((entry) => ({\n ...entry.order,\n c: createUnmarkedProtectionCloid(generatedCloids),\n }));\n const sentRestorationOrders = this.#applySubscriptionCloid(\n restorationOrders,\n new Set(restorationOrders.map((order) => order.c)),\n );\n let statuses: unknown[];\n let restorationFailure: Error | undefined;\n try {\n // Restore the exact pre-call reduce-only intent. Scope and account\n // shape are still probed after signing, but the requested new\n // protection's position precondition does not apply to rollback.\n await assertScope();\n const result = await recoveryExchangeClient.order({\n orders: sentRestorationOrders,\n grouping: protection.grouping,\n ...(entries.some((entry) => entry.chargesMetamaskBuilderFee) &&\n builderOrderContext && { builder: builderOrderContext }),\n });\n statuses = result.response?.data?.statuses ?? [];\n } catch (error) {\n const failure = await this.#classifyProtectionWriteError(error);\n restorationFailure = failure;\n statuses =\n this.#readProtectionErrorStatuses(error) ??\n (this.#isDefinitiveProtectionRejection(error)\n ? entries.map(() => ({ error: failure.message }))\n : []);\n this.#deps.debugLogger.log(\n 'Protection restoration requires reconciliation',\n { symbol, error: failure.message },\n );\n }\n await assertScope();\n const outcomes = await this.#reconcileTpslOrderPlacementOutcomes({\n outcomes: statuses\n .slice(0, entries.length)\n .map((status) => this.#readTpslOrderPlacementOutcome(status)),\n orders: sentRestorationOrders,\n userAddress,\n infoClient,\n assertScope,\n symbol,\n });\n await assertScope();\n restoredOrderIds.push(\n ...outcomes.flatMap((outcome) =>\n outcome.orderId ? [outcome.orderId] : [],\n ),\n );\n if (\n outcomes.some(\n (outcome) =>\n outcome.state === 'rejected' || outcome.state === 'unknown',\n )\n ) {\n success = false;\n const signerFailure =\n restorationFailure &&\n (await this.#isSignerFailure(restorationFailure));\n await assertScope();\n if (!signerFailure) {\n this.#deps.logger.error(\n restorationFailure ??\n new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST),\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol,\n stage: 'restoration',\n protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,\n childOrderIds: restoredOrderIds,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n }\n }\n }\n await assertScope();\n return { restoredOrderIds, success };\n };\n\n const createProtectionLostResult = (\n survivingOrderIds: string[],\n ): OrderResult =>\n createErrorResult(new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), {\n success: false,\n childOrderIds: [...new Set(survivingOrderIds)],\n });\n\n // Cancel before placing for both position-bound and standalone partial\n // triggers. A place-first partial update leaves both trigger sets live\n // during the cancellation round trip and can reduce more than requested.\n await assertCurrentPosition();\n const oldCancellation = await this.#cancelOrderRequestBatch(\n exchangeClient,\n cancelRequests,\n async (error) => {\n if (cancelGuardFailure !== undefined) {\n throw await this.#classifyProtectionWriteError(cancelGuardFailure);\n }\n if (isHyperLiquidMultiSigRequiredError(error)) {\n throw await this.#classifyProtectionWriteError(error);\n }\n },\n );\n // The signer could not sign the cancel. With nothing cancelled the old\n // protection is still in place, and a clear keeps only what it could\n // not cancel, so the caller retries. A replacement that cancelled part\n // of the old protection restores it below.\n if (\n oldCancellation.signerFailure &&\n (orders.length === 0 || oldCancellation.cancelledOrderIds.length === 0)\n ) {\n this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });\n return createErrorResult(oldCancellation.signerFailure, {\n success: false,\n });\n }\n\n await assertScope();\n\n // Clearing has no replacement batch to preserve. A partial cancellation\n // is reported so the caller can retry the same clear operation.\n if (orders.length === 0) {\n if (oldCancellation.remainingOrderIds.length > 0) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n this.#deps.debugLogger.log(\n 'No new TP/SL orders to place - existing ones cancelled',\n );\n return {\n success: true,\n childOrderIds: [],\n // No orderId since we only cancelled orders, didn't place new ones\n };\n }\n\n const confirmedCancelledOldOrderIds = new Set<number>();\n if (!oldCancellation.responseComplete) {\n const requestedOrderIds = new Set(\n cancelRequests.map((request) => request.o),\n );\n let possiblyLiveOrderIds = Array.from(requestedOrderIds, String);\n try {\n const liveOrders = await this.#fetchOpenOrders({ dexName });\n possiblyLiveOrderIds = liveOrders\n .filter((order) => requestedOrderIds.has(order.oid))\n .map((order) => String(order.oid));\n } catch (error) {\n this.#deps.debugLogger.log(\n 'Could not reconcile TP/SL protection after an incomplete cancel',\n {\n symbol,\n error: ensureError(\n error,\n 'HyperLiquidProvider.updatePositionTPSL.reconcileProtection',\n ).message,\n },\n );\n }\n await assertScope();\n return createProtectionLostResult(possiblyLiveOrderIds);\n }\n oldCancellation.cancelledOrderIds.forEach((orderId) =>\n confirmedCancelledOldOrderIds.add(orderId),\n );\n if (oldCancellation.remainingOrderIds.length > 0) {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult([\n ...oldCancellation.remainingOrderIds.map(String),\n ...restoration.restoredOrderIds,\n ]);\n }\n const survivingOrderIds = [\n ...new Set([\n ...oldCancellation.remainingOrderIds.map(String),\n ...restoration.restoredOrderIds,\n ]),\n ];\n if (oldCancellation.signerFailure) {\n this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });\n return createErrorResult(oldCancellation.signerFailure, {\n success: false,\n childOrderIds: survivingOrderIds,\n });\n }\n const updateError = new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n this.#deps.logger.error(\n updateError,\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol: params.symbol,\n hasTakeProfit: params.takeProfitPrice !== undefined,\n hasStopLoss: params.stopLossPrice !== undefined,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n return createErrorResult(updateError, {\n success: false,\n childOrderIds: survivingOrderIds,\n });\n }\n\n let placementStatuses: unknown[];\n let placementFailure: Error | undefined;\n let responseAccepted = false;\n try {\n // Old protection may already be cancelled. A failed position read\n // belongs to recovery, which reports loss if safe restoration is\n // impossible instead of returning a pre-mutation refresh error.\n await assertCurrentPosition();\n const result = await replacementExchangeClient.order({\n orders: sentOrders,\n grouping: isPartialTpsl ? 'na' : 'positionTpsl',\n ...(replacementChargesMetamaskBuilderFee &&\n builderOrderContext && { builder: builderOrderContext }),\n });\n placementStatuses = result.response?.data?.statuses ?? [];\n responseAccepted = result.status === 'ok';\n } catch (error) {\n // Drop and report a rejected agent before restoration signs.\n placementFailure = await this.#classifyProtectionWriteError(error);\n await assertScope();\n const statuses = this.#readProtectionErrorStatuses(error);\n if (statuses !== undefined) {\n placementStatuses = statuses;\n } else if (\n replacementMayHaveDispatched &&\n !this.#isDefinitiveProtectionRejection(error)\n ) {\n // Arbitrary transport/HTTP failures do not prove non-processing.\n placementStatuses = [];\n } else {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult(restoration.restoredOrderIds);\n }\n return createErrorResult(placementFailure, {\n success: false,\n ...(restoration.restoredOrderIds.length > 0\n ? { childOrderIds: restoration.restoredOrderIds }\n : {}),\n });\n }\n }\n\n await assertScope();\n const initialPlacementOutcomes = placementStatuses\n .slice(0, orders.length)\n .map((status) => this.#readTpslOrderPlacementOutcome(status));\n const placementAccepted =\n responseAccepted &&\n placementStatuses.length === orders.length &&\n initialPlacementOutcomes.every(\n (outcome) =>\n outcome.state === 'resting' ||\n outcome.state === 'filled' ||\n outcome.state === 'waitingForTrigger',\n );\n\n if (placementAccepted) {\n // Only response-correlated IDs form a receipt. A waitingForTrigger\n // acknowledgement without an ID cannot be attributed from book changes.\n const childOrderIds: string[] = [];\n let identitiesValid = true;\n for (const [index, outcome] of initialPlacementOutcomes.entries()) {\n const cloid = sentOrders[index]?.c;\n let { orderId } = outcome;\n if (cloid === undefined) {\n identitiesValid = false;\n continue;\n }\n // One exact-ID lookup verifies immediate correlation. An unknown\n // index is uncertainty, not a reason to repeat the same read in a tight loop.\n await assertScope();\n try {\n const status = await infoClient.orderStatus({\n user: userAddress,\n oid: cloid,\n });\n await assertScope();\n if (status.status === 'order') {\n const row = status.order.order;\n if (\n row.coin !== symbol ||\n row.cloid?.toLowerCase() !== cloid.toLowerCase() ||\n !Number.isSafeInteger(row.oid) ||\n row.oid <= 0 ||\n (orderId !== undefined && orderId !== String(row.oid))\n ) {\n identitiesValid = false;\n } else {\n orderId = String(row.oid);\n }\n }\n } catch {\n // Read failure cannot invent an ID; stale scopes cannot return receipts.\n await assertScope();\n }\n if (orderId !== undefined) {\n childOrderIds.push(orderId);\n }\n }\n const completeReceipt =\n identitiesValid &&\n childOrderIds.length === orders.length &&\n childOrderIds.every((id) => Number(id) > 0) &&\n new Set(childOrderIds).size === childOrderIds.length;\n return {\n success: true,\n orderId: 'TP/SL orders placed',\n ...(completeReceipt ? { childOrderIds } : {}),\n };\n }\n\n const placementOutcomes = await this.#reconcileTpslOrderPlacementOutcomes(\n {\n outcomes: initialPlacementOutcomes,\n orders: sentOrders,\n userAddress,\n infoClient,\n assertScope,\n symbol,\n },\n );\n await assertScope();\n const restingReplacementOrderIds = placementOutcomes.flatMap((outcome) =>\n (outcome.state === 'resting' ||\n outcome.state === 'waitingForTrigger') &&\n outcome.orderId\n ? [outcome.orderId]\n : [],\n );\n const filledReplacementOrderIds = placementOutcomes.flatMap((outcome) =>\n outcome.state === 'filled' && outcome.orderId ? [outcome.orderId] : [],\n );\n const inFlightOrderIds = placementOutcomes.flatMap((outcome) =>\n outcome.state === 'unknown' && outcome.orderId ? [outcome.orderId] : [],\n );\n const hasUnresolvedWaitingTrigger = placementOutcomes.some(\n (outcome) =>\n (outcome.state === 'waitingForTrigger' ||\n outcome.state === 'unknown') &&\n outcome.orderId === undefined,\n );\n await assertScope();\n let cleanupFailure: Error | undefined;\n const remainingReplacementIds = await this.#cancelOrderRequests(\n recoveryExchangeClient,\n restingReplacementOrderIds.map((orderId) => ({\n a: assetId,\n o: Number(orderId),\n })),\n async (error) => {\n if (\n isHyperLiquidMultiSigRequiredError(error) ||\n (error instanceof Error &&\n error.message === PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)\n ) {\n // Old protection has already changed. Classification must not\n // throw away this batch's still-live replacement identities.\n cleanupFailure = await this.#classifyProtectionWriteError(error);\n }\n },\n );\n await assertScope();\n const recoverableOrderIds = [\n ...filledReplacementOrderIds,\n ...inFlightOrderIds,\n ...remainingReplacementIds.map(String),\n ];\n if (cleanupFailure && recoverableOrderIds.length > 0) {\n this.#deps.logger.error(\n cleanupFailure,\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol,\n stage: 'cleanup',\n protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,\n childOrderIds: recoverableOrderIds,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\n ),\n );\n return createProtectionLostResult(recoverableOrderIds);\n }\n if (hasUnresolvedWaitingTrigger) {\n return createProtectionLostResult(recoverableOrderIds);\n }\n if (recoverableOrderIds.length === 0) {\n const restoration = await restoreCancelledProtection(\n confirmedCancelledOldOrderIds,\n );\n if (!restoration.success) {\n return createProtectionLostResult(restoration.restoredOrderIds);\n }\n return createErrorResult(\n placementFailure ?? new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED),\n {\n success: false,\n ...(restoration.restoredOrderIds.length > 0\n ? { childOrderIds: restoration.restoredOrderIds }\n : {}),\n },\n );\n }\n // A filled replacement may have changed or closed the position, while\n // an uncancelled replacement may still protect it. Restoring the old\n // whole-position triggers in either case risks stale or duplicate\n // protection, so return those IDs for caller reconciliation instead.\n if (!isPartialTpsl) {\n return createProtectionLostResult(recoverableOrderIds);\n }\n return createErrorResult(\n new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED),\n {\n success: false,\n childOrderIds: recoverableOrderIds,\n },\n );\n } catch (error) {\n const signerFailure = await this.#handleSignerFailure(\n error,\n 'updatePositionTPSL',\n { symbol: params.symbol },\n );\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'),\n this.#getErrorContext(\n 'updatePositionTPSL',\n {\n symbol: params.symbol,\n hasTakeProfit: params.takeProfitPrice !== undefined,\n hasStopLoss: params.stopLossPrice !== undefined,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.PositionTpslUpdate,\n },\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 // The delegated placeOrder call resolves the builder-fee policy for the\n // concrete close order after validation.\n await this.#ensureReadyForTrading({ requiresBuilderFee: false });\n\n // A caller snapshot is never authoritative for a reduce-only close. Use\n // the current DEX slice or its HTTP fallback, and fail closed if neither\n // answers. This keeps the size and side on one freshness contract across\n // snapshot and snapshot-less callers.\n const currentPositions = await this.#getPositionsForOperation(\n parseAssetName(params.symbol).dex ?? '',\n );\n const position = currentPositions.find(\n (pos) => pos.symbol === params.symbol,\n );\n\n if (\n params.position &&\n position &&\n parseFloat(position.size) !== parseFloat(params.position.size)\n ) {\n this.#deps.debugLogger.log(\n 'Stale close position snapshot: using current position',\n {\n coin: params.symbol,\n snapshotSize: params.position.size,\n liveSize: position.size,\n },\n );\n }\n\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\n }\n\n const positionSize = parseFloat(position.size);\n const isBuy = positionSize < 0;\n const absPositionSize = Math.abs(positionSize);\n // Only an omitted (or empty) size means \"close 100%\". A supplied size must\n // be a positive number: silently promoting '0' or 'abc' to a full close\n // would liquidate the whole position on a caller-side formatting slip.\n // A supplied size is clamped to the live position size, because\n // HyperLiquid rejects reduce-only orders that exceed the position and the\n // caller computed its size from a snapshot that may already be too large.\n const hasRequestedSize = params.size !== undefined && params.size !== '';\n let closeSizeNumber = absPositionSize;\n\n if (hasRequestedSize) {\n const requestedSize = parseFloat(params.size as string);\n\n if (!Number.isFinite(requestedSize) || requestedSize <= 0) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n\n closeSizeNumber = Math.min(requestedSize, absPositionSize);\n }\n\n const closeSize = closeSizeNumber.toString();\n\n // Capture position details BEFORE closing for freed margin calculation\n const totalMarginUsed = parseFloat(position.marginUsed);\n const totalPositionSize = absPositionSize;\n const closeSizeNum = closeSizeNumber;\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 USD/minimum validation if not provided. A full\n // close skips *that* validation because it submits the exact live size —\n // but not the price-staleness guard: calculateFinalPositionSize checks\n // priceAtCalculation against the live price for every close that supplies\n // it, using the price placeOrder fetches when none is passed here.\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 // True when the order closes 100% of the position: either no size was\n // provided, or the requested size covers (or was clamped to) the whole\n // position.\n const isFullClose = closeSizeNum >= absPositionSize;\n\n // Execute position close with consistent slippage handling\n const result = await this.placeOrder(\n {\n symbol: params.symbol,\n isBuy,\n size: closeSize,\n orderType: params.orderType ?? 'market',\n price: params.price,\n reduceOnly: true,\n isFullClose,\n // Pass through price and slippage parameters for consistent validation\n currentPrice,\n // A close of the whole position must submit exactly the live position\n // size. Forwarding usdAmount would make placeOrder recompute the size as\n // usdAmount / currentPrice — discarding the clamp above, since usdAmount\n // is the source of truth there — and submit more than the position\n // holds, which is rejected with \"Reduce only order would increase\n // position\". Genuine partial closes keep usdAmount so their size stays\n // USD-accurate.\n usdAmount: isFullClose ? undefined : params.usdAmount,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n },\n 0,\n false,\n );\n\n // Return freed margin using native abstraction or programmatic transfer\n if (\n result.success &&\n isHip3Position &&\n hip3Dex &&\n !this.#useUnifiedAccount\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.#useUnifiedAccount\n ) {\n this.#deps.debugLogger.log(\n 'Position closed - Unified Account 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 const safeError = ensureError(error, 'HyperLiquidProvider.closePosition');\n this.#deps.debugLogger.log('[closePosition] Close failed', {\n error: safeError.message,\n coin: params.symbol,\n orderType: params.orderType,\n });\n return createErrorResult(safeError, { 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 // Use the target DEX's current slice or one targeted HTTP read before\n // deriving the position side.\n const positions = await this.#getPositionsForOperation(\n parseAssetName(symbol).dex ?? '',\n );\n const position = positions.find((pos) => pos.symbol === symbol);\n\n if (!position) {\n throw new Error(PERPS_ERROR_CODES.POSITION_NOT_FOUND);\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 // Guard: confirm spendableBalance can cover margin addition.\n // spendableBalance is already mode-aware (includes free spot in Unified,\n // excludes it in Standard), so no extra spot fetch needed.\n if (amountFloat > 0) {\n const accountState = await this.getAccountState();\n const spendable = parseFloat(accountState.spendableBalance);\n\n if (spendable < amountFloat) {\n throw new Error(\n `Insufficient balance for margin addition: need ${amountFloat}, available ${spendable.toFixed(2)}`,\n );\n }\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 signerFailure = await this.#handleSignerFailure(\n error,\n 'updateMargin',\n {\n symbol: params.symbol,\n },\n );\n if (signerFailure) {\n return { success: false, error: signerFailure.message };\n }\n const safeError = ensureError(error, 'HyperLiquidProvider.updateMargin');\n this.#deps.logger.error(\n safeError,\n this.#getErrorContext(\n 'updateMargin',\n {\n symbol: params.symbol,\n amount: params.amount,\n },\n {\n operation: PERPS_ERROR_OPERATION.PositionManagement,\n action: PERPS_ERROR_ACTION.UpdateMargin,\n },\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 (unified state)\n if (this.#dexDiscoveryCache.state?.validated) {\n return this.#dexDiscoveryCache.state.validated;\n }\n\n // Kill switch: HIP-3 disabled, return main DEX only\n if (!this.#hip3Enabled) {\n const state = this.#dexDiscoveryCache.update([null]);\n return state.validated;\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 // Do not cache — transient error, allow retry on next call\n return [null];\n }\n\n // Validate response\n if (!allDexs || !Array.isArray(allDexs)) {\n // Do not cache — may be transient, allow retry on next call\n return [null];\n }\n\n // Atomically update unified state (raw + validated + timestamp).\n // buildAssetMapping uses state.raw for perpDexIndex computation.\n const state = this.#dexDiscoveryCache.update(allDexs);\n return state.validated;\n }\n\n /**\n * Fetch a complete standalone user-data bundle.\n *\n * Each DEX clearinghouse response is shared by position and account-state\n * mapping. Any required request failure rejects the entire bundle.\n *\n * @param params - User and captured controller identity.\n * @returns The complete user-data snapshot.\n */\n async getUserDataSnapshot(\n params: GetUserDataSnapshotParams,\n ): Promise<PerpsUserDataSnapshot> {\n const { identity, userAddress } = params;\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n const snapshotStartedAt = this.#deps.performance.now();\n const measure = async <Result>(\n stage: string,\n request: () => Promise<Result>,\n dex?: string | null,\n ): Promise<Result> => {\n const startedAt = this.#deps.performance.now();\n const dexDetail = dex === undefined ? {} : { dex: dex ?? 'main' };\n try {\n const result = await request();\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage,\n durationMs: Math.round(this.#deps.performance.now() - startedAt),\n success: true,\n ...dexDetail,\n });\n return result;\n } catch (error) {\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage,\n durationMs: Math.round(this.#deps.performance.now() - startedAt),\n success: false,\n ...dexDetail,\n });\n throw error;\n }\n };\n\n if (identity.provider !== 'hyperliquid' || identity.network !== network) {\n throw new Error('User data snapshot identity does not match provider');\n }\n\n const requestedDexes = identity.dexes;\n const canonicalDexes = canonicalizeHyperLiquidDexes(requestedDexes);\n const hasValidDexIdentity =\n requestedDexes.length > 0 &&\n new Set(requestedDexes).size === requestedDexes.length &&\n requestedDexes.every(\n (dex) => dex === 'main' || /^[a-z0-9][a-z0-9-]*$/u.test(dex),\n ) &&\n requestedDexes.length === canonicalDexes.length &&\n requestedDexes.every((dex, index) => dex === canonicalDexes[index]);\n if (!hasValidDexIdentity) {\n throw new Error('User data snapshot DEX identity is invalid');\n }\n const dexs = requestedDexes.map((dex) => (dex === 'main' ? null : dex));\n const standaloneInfoClient = createStandaloneInfoClient({\n isTestnet: network === 'testnet',\n });\n const buildUserParams = (\n dex: string | null,\n ): { user: string; dex?: string } => ({\n user: userAddress,\n ...(dex ? { dex } : {}),\n });\n\n const [clearinghouseStates, openOrdersByDex, spotState, abstractionMode] =\n await Promise.all([\n Promise.all(\n dexs.map((dex) =>\n measure(\n 'clearinghouse_state',\n () =>\n standaloneInfoClient.clearinghouseState(buildUserParams(dex)),\n dex,\n ),\n ),\n ),\n Promise.all(\n dexs.map((dex) =>\n measure(\n 'frontend_open_orders',\n () =>\n standaloneInfoClient.frontendOpenOrders(buildUserParams(dex)),\n dex,\n ),\n ),\n ),\n measure('spot_clearinghouse_state', () =>\n standaloneInfoClient.spotClearinghouseState({ user: userAddress }),\n ),\n measure('user_abstraction', () =>\n standaloneInfoClient.userAbstraction({ user: userAddress }),\n ),\n ]);\n\n const rawOrders = openOrdersByDex.flat();\n const childOrderIds = collectChildOrderIds(rawOrders);\n const ordersBySymbol = groupOrdersBySymbol(rawOrders);\n const positions = clearinghouseStates.flatMap((state) =>\n state.assetPositions\n .filter(({ position }) => position.szi !== '0')\n .map((assetPosition) => {\n const position = adaptPositionFromSDK(assetPosition);\n const {\n takeProfitOrders,\n stopLossOrders,\n takeProfitPrice,\n stopLossPrice,\n } = collectPositionTriggerOrders({\n orders: ordersBySymbol.get(position.symbol) ?? [],\n position,\n childOrderIds,\n });\n return {\n ...position,\n takeProfitCount: takeProfitOrders.length,\n stopLossCount: stopLossOrders.length,\n takeProfitOrders,\n stopLossOrders,\n ...(takeProfitPrice && { takeProfitPrice }),\n ...(stopLossPrice && { stopLossPrice }),\n };\n }),\n );\n const positionsBySymbol = new Map(\n positions.map((position) => [position.symbol, position]),\n );\n const orders = rawOrders.map((order) =>\n adaptOrderFromSDK(order, positionsBySymbol.get(order.coin)),\n );\n const dexAccountStates = clearinghouseStates.map((state) =>\n adaptAccountStateFromSDK(state),\n );\n const accountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n spotState,\n { foldIntoCollateral: hyperLiquidModeFoldsSpot(abstractionMode) },\n );\n\n accountState.subAccountBreakdown = Object.fromEntries(\n dexAccountStates.map((dexAccountState, index) => {\n return [\n dexs[index] ?? '',\n {\n spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\n totalBalance: dexAccountState.totalBalance,\n },\n ];\n }),\n );\n\n const snapshot = {\n positions,\n orders,\n accountState,\n identity: {\n ...identity,\n address: userAddress,\n },\n };\n this.#deps.debugLogger.log('[PerpsUserSnapshot]', {\n stage: 'complete',\n durationMs: Math.round(this.#deps.performance.now() - snapshotStartedAt),\n success: true,\n dexCount: dexs.length,\n });\n return snapshot;\n }\n\n /**\n * Read positions without mixing sources whose relative recency is unknown.\n *\n * A symbol-specific caller can use its current-connection DEX slice directly.\n * The current-epoch slice wins before any REST request because it is the\n * provider's live subscription source for that exact DEX. A caller may opt\n * into one targeted REST revalidation when a required symbol is absent, which\n * covers the post-fill window before the next WebSocket position update. If\n * the target DEX has not published, the caller uses REST instead of a stale\n * aggregate.\n *\n * A whole-list caller uses one shallow-copied WebSocket snapshot only when\n * every configured DEX is current. Otherwise it falls back to REST. No path\n * mixes sources of unknown relative recency. WebSocket positions include\n * TP/SL decoration; REST positions do not.\n *\n * @param targetDex - DEX for a single-symbol lookup, or undefined for a full\n * position list.\n * @param options - Optional lookup behavior for a symbol-specific operation.\n * @param options.revalidateMissingSymbol - Query the target DEX over REST when\n * its current WebSocket slice does not contain this symbol.\n * @returns Positions from one provenance-safe cache/REST path.\n */\n async #getPositionsForOperation(\n targetDex?: string,\n options: { revalidateMissingSymbol?: string } = {},\n ): Promise<Position[]> {\n if (targetDex !== undefined) {\n const targetPositions =\n this.#subscriptionService.getCachedPositionsForDex(targetDex);\n if (targetPositions === null) {\n this.#deps.debugLogger.log(\n 'Target DEX position cache unavailable: fetching REST positions',\n { dex: targetDex || 'main' },\n );\n } else {\n const { revalidateMissingSymbol } = options;\n const shouldRevalidate =\n revalidateMissingSymbol !== undefined &&\n targetPositions.find(\n (position) => position.symbol === revalidateMissingSymbol,\n ) === undefined;\n if (shouldRevalidate) {\n this.#deps.debugLogger.log(\n 'Target symbol missing from position cache: revalidating REST positions',\n {\n dex: targetDex || 'main',\n symbol: revalidateMissingSymbol,\n },\n );\n } else {\n return [...targetPositions];\n }\n }\n\n const { answered, positions } = await this.#queryDexPositions(\n targetDex || null,\n );\n if (!answered) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n return positions;\n }\n\n const cachedPositions =\n this.#subscriptionService.getFreshPositionsForAllDexs();\n if (cachedPositions !== null) {\n return cachedPositions;\n }\n\n this.#deps.debugLogger.log(\n 'Position caches incomplete: fetching full REST positions',\n );\n return this.#queryAllDexPositionsStrict();\n }\n\n /**\n * Query every enabled DEX over HTTP and reject a partial snapshot.\n *\n * A batch action cannot treat the successful subset as complete: doing so\n * could close one DEX and report success while another live position was\n * never checked.\n *\n * @returns A complete position list across all enabled DEXs.\n * @throws `PROVIDER_NOT_AVAILABLE` when any expected DEX fails.\n */\n async #queryAllDexPositionsStrict(): Promise<Position[]> {\n await this.#ensureClientsInitialized();\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const enabledDexs = await this.#getValidatedDexsStrict();\n\n const { results, failedDexs } = await this.#queryUserDataAcrossDexs(\n { user: userAddress },\n (userParam) => infoClient.clearinghouseState(userParam),\n enabledDexs,\n );\n\n if (failedDexs.length > 0) {\n this.#deps.debugLogger.log(\n 'Complete REST position snapshot unavailable',\n {\n failedDexs: failedDexs.map(\n ({ dex, error }) => `${dex ?? 'main'}:${error.message}`,\n ),\n },\n );\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n if (results.some(({ data }) => !Array.isArray(data.assetPositions))) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n\n return results.flatMap(({ data }) =>\n data.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos)),\n );\n }\n\n /**\n * Query one DEX's positions directly, preserving whether that DEX answered.\n *\n * `getPositions()` fans out across every enabled DEX, flattens the subset that\n * answered and converts any thrown error into an empty array, so its result\n * cannot distinguish \"this DEX answered and holds no positions\" from \"this\n * DEX's request failed or it was never queried\". Symbol operations need that\n * distinction: the first means the position is closed, while the second must\n * fail with `PROVIDER_NOT_AVAILABLE`.\n *\n * TP/SL enrichment is skipped because callers only read size, side, and margin.\n *\n * @param dexName - DEX identifier, or null for the main DEX.\n * @returns Whether the DEX answered, and the positions it reported.\n */\n async #queryDexPositions(\n dexName: string | null,\n ): Promise<{ answered: boolean; positions: Position[] }> {\n try {\n await this.#ensureClientsInitialized();\n const infoClient = this.#clientService.getInfoClient({ useHttp: true });\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n const state = await infoClient.clearinghouseState(\n dexName ? { user: userAddress, dex: dexName } : { user: userAddress },\n );\n if (!Array.isArray(state.assetPositions)) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);\n }\n const positions = state.assetPositions\n .filter((assetPos) => assetPos.position.szi !== '0')\n .map((assetPos) => adaptPositionFromSDK(assetPos));\n\n this.#deps.debugLogger.log('Target DEX position query answered', {\n dex: dexName ?? 'main',\n count: positions.length,\n });\n\n return { answered: true, positions };\n } catch (error) {\n const safeError = ensureError(\n error,\n 'HyperLiquidProvider.queryDexPositions',\n );\n this.#deps.debugLogger.log('Target DEX position query failed', {\n dex: dexName ?? 'main',\n error: safeError.message,\n });\n\n return { answered: false, positions: [] };\n }\n }\n\n /**\n * Get current positions with TP/SL prices\n *\n * Note on TP/SL orders:\n * - normalTpsl: TP/SL tied to parent order, only placed after parent fills\n * - positionTpsl: TP/SL tied to position, placed immediately\n *\n * This means TP/SL prices may not appear immediately after placing an order\n * with TP/SL. They will only show up once the parent order is filled and\n * the child TP/SL orders are actually placed on the order book.\n *\n * @param params - 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 // TP/SL children of pending parent orders are listed at the top level too;\n // they belong to that order, not to a position.\n const allOrdersChildIds = collectChildOrderIds(allOrders);\n\n // Grouped once here rather than rescanned per position, mirroring the\n // positionsBySymbol map on the WebSocket path.\n const ordersBySymbol = groupOrdersBySymbol(allOrders);\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 // Trigger orders attached to this position: position-bound TP/SL plus\n // standalone ('na' grouping) partial TP/SL. A pending order's\n // normalTpsl children are excluded — they are also listed at the top\n // level, but they protect that order, not this position (same rule as\n // the positionOrders filter above).\n const { takeProfitOrders, stopLossOrders } =\n collectPositionTriggerOrders({\n orders: ordersBySymbol.get(position.symbol) ?? [],\n position,\n childOrderIds: allOrdersChildIds,\n });\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((childOrder) => {\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: resolvePositionTriggerSummaryPrice({\n triggerOrders: takeProfitOrders,\n scannedPrice: takeProfitPrice,\n }),\n stopLossPrice: resolvePositionTriggerSummaryPrice({\n triggerOrders: stopLossOrders,\n scannedPrice: stopLossPrice,\n }),\n takeProfitCount: takeProfitOrders.length,\n stopLossCount: stopLossOrders.length,\n takeProfitOrders,\n stopLossOrders,\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 * @param options - Optional cache-control modifiers for this read.\n * @returns A promise that resolves to the result.\n */\n async getOrderFills(\n params?: GetOrderFillsParams,\n options?: PerpsReadOptions,\n ): 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 // Routed through the client-service coalesce so the enrichment sidecar\n // rides the same cache as an explicit getOrders call, preventing a\n // second REST fire under rapid market switching.\n const historicalOrdersPromise = this.#clientService\n .fetchHistoricalOrders(userAddress, {\n forceRefresh: options?.forceRefresh,\n })\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 const fillId = buildHyperLiquidFillId(fill);\n acc.push({\n orderId: fill.oid?.toString() || '',\n // Two partial fills of one order can share oid, time, sz and px,\n // so the execution id is the only field that tells them apart\n // downstream. Omitted when a non-conforming payload lacks tid.\n ...(fillId === undefined ? {} : { fillId }),\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 * @param options - Optional cache-control modifiers for this read.\n * @returns A promise that resolves to the result.\n */\n async getOrders(\n params?: GetOrdersParams,\n options?: PerpsReadOptions,\n ): 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 userAddress = await this.#walletService.getUserAddressWithDefault(\n params?.accountId,\n );\n\n const rawOrders = await this.#clientService.fetchHistoricalOrders(\n userAddress,\n { forceRefresh: options?.forceRefresh },\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\n // Statuses newer than the SDK types stay visible as queued.\n const normalizedStatus: Order['status'] = hasProperty(\n HISTORICAL_ORDER_STATUS_BY_SDK_STATUS,\n status,\n )\n ? HISTORICAL_ORDER_STATUS_BY_SDK_STATUS[status]\n : 'queued';\n\n const adaptedOrder = adaptOrderFromSDK(order, undefined);\n // limitPx is also populated as a slippage cap for market orders, so the\n // exchange's detailed type is the reliable execution-mode source.\n const historicalOrderType = hasProperty(\n HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE,\n order.orderType,\n )\n ? HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE[order.orderType]\n : 'market';\n\n return {\n ...adaptedOrder,\n orderType: historicalOrderType,\n remainingSize: parseFloat(order.sz).toString(),\n status: normalizedStatus,\n timestamp: statusTimestamp,\n lastUpdated: statusTimestamp,\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 * Rebuild Scale cancellation handles from the group identity persisted on\n * open venue orders.\n *\n * @param orders - Current normalized open orders.\n */\n #restoreScaleOrderGroups(orders: Order[]): void {\n const recovered = new Map<string, ScaleOrderGroup>();\n for (const order of orders) {\n if (!order.strategyGroupId) {\n continue;\n }\n const group = recovered.get(order.strategyGroupId) ?? {\n symbol: order.symbol,\n orderIds: [],\n clientOrderIds: [],\n };\n group.orderIds.push(order.orderId);\n recovered.set(order.strategyGroupId, group);\n }\n\n for (const [groupId, group] of recovered) {\n if (this.#cancelledScaleOrderGroups.has(groupId)) {\n continue;\n }\n const existingGroup = this.#scaleOrderGroups.get(groupId);\n if (!existingGroup) {\n this.#scaleOrderGroups.set(groupId, group);\n continue;\n }\n if (existingGroup.symbol === group.symbol) {\n existingGroup.orderIds = [\n ...new Set([...existingGroup.orderIds, ...group.orderIds]),\n ];\n } else {\n this.#deps.debugLogger.log(\n 'Scale group symbol mismatch during recovery',\n {\n groupId,\n existingSymbol: existingGroup.symbol,\n recoveredSymbol: group.symbol,\n },\n );\n }\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 this.#restoreScaleOrderGroups(cachedOrders);\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 this.#restoreScaleOrderGroups(orders);\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 * @param _options - Cache-control modifiers (unused — funding has no\n * provider-internal cache; coalescing happens at MarketDataService).\n * @returns A promise that resolves to the result.\n */\n async getFunding(\n params?: GetFundingParams,\n _options?: PerpsReadOptions,\n ): 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 * Resolve the provider's currently active CAIP account identifier.\n * Used by the MarketDataService REST coalesce layer so cached payloads\n * are keyed by the actual resolved address rather than a shared\n * \"default\" sentinel — prevents one account's data from being served\n * after an account switch within the coalesce TTL window.\n *\n * @returns CAIP account id for the currently selected HyperLiquid account.\n */\n async getCurrentAccountId(): Promise<CaipAccountId> {\n return this.#walletService.getCurrentAccountId();\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 [\n standaloneSpotStateResult,\n standalonePerpsResults,\n standaloneAbstractionResult,\n ] = await Promise.all([\n standaloneInfoClient\n .spotClearinghouseState({ user: userAddress })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log(\n 'Standalone spot state fetch failed — falling back to perps-only totals',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.getAccountState.standalone.spot',\n ).message,\n },\n );\n return null;\n }),\n queryStandaloneClearinghouseStates(\n standaloneInfoClient,\n userAddress,\n dexs,\n ),\n standaloneInfoClient\n .userAbstraction({ user: userAddress })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log(\n 'Standalone userAbstraction fetch failed; spot fold disabled until the mode resolves',\n {\n error: ensureError(\n error,\n 'HyperLiquidProvider.getAccountState.standalone.abstraction',\n ).message,\n },\n );\n return null;\n }),\n ]);\n\n // Aggregate account states across all DEXs, then apply spot-backed\n // adjustments so streamed/standalone/full paths report the same totals.\n const dexAccountStates = standalonePerpsResults.map((perpsState) =>\n adaptAccountStateFromSDK(perpsState),\n );\n const aggregatedAccountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n standaloneSpotStateResult,\n {\n foldIntoCollateral: hyperLiquidModeFoldsSpot(\n standaloneAbstractionResult,\n ),\n },\n );\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, Perps states across DEXs, and the HL abstraction\n // mode (Unified / Standard / Portfolio / DEX-abstraction). Mode decides\n // whether spot USDC is perps collateral — see addSpotBalanceToAccountState.\n // One transient DEX failure should not blank the entire account state.\n const [spotStateResult, perpsStateResult, abstractionResult] =\n await Promise.allSettled([\n infoClient.spotClearinghouseState({ user: userAddress }),\n this.#queryUserDataAcrossDexs({ user: userAddress }, (userParam) =>\n infoClient.clearinghouseState(userParam),\n ),\n infoClient.userAbstraction({ user: userAddress }),\n ]);\n const spotState =\n spotStateResult.status === 'fulfilled' ? spotStateResult.value : null;\n const abstractionMode =\n abstractionResult.status === 'fulfilled'\n ? abstractionResult.value\n : null;\n if (abstractionResult.status === 'rejected') {\n this.#deps.debugLogger.log(\n 'User abstraction fetch failed; spot fold disabled until the mode resolves',\n {\n error: ensureError(\n abstractionResult.reason,\n 'HyperLiquidProvider.getAccountState.abstraction',\n ).message,\n },\n );\n }\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 spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\n marginUsed: dexAccountState.marginUsed,\n unrealizedPnl: dexAccountState.unrealizedPnl,\n },\n );\n return dexAccountState;\n });\n const aggregatedAccountState = addSpotBalanceToAccountState(\n aggregateAccountStates(dexAccountStates),\n spotState,\n { foldIntoCollateral: hyperLiquidModeFoldsSpot(abstractionMode) },\n );\n\n // Build per-sub-account breakdown (HIP-3 DEXs map to sub-accounts)\n const subAccountBreakdown: Record<\n string,\n {\n spendableBalance: string;\n withdrawableBalance: string;\n totalBalance: string;\n }\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 spendableBalance: dexAccountState.spendableBalance,\n withdrawableBalance: dexAccountState.withdrawableBalance,\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 lifecycleGeneration: number,\n ): Promise<DexFetchResult> {\n const dexParam = dex ?? '';\n let metaAndCtxs: [MetaResponse | null, PerpsAssetCtx[]] | null = null;\n try {\n metaAndCtxs = await infoClient.metaAndAssetCtxs(\n dexParam ? { dex: dexParam } : undefined,\n );\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 await this.#cacheDexMetadataFromRead({\n dex,\n meta,\n assetCtxs,\n lifecycleGeneration,\n });\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 /**\n * Filter out successful HIP-3 DexFetchResults whose collateral token is\n * not USDC, so getMarketDataWithPrices enforces the same USDC-only policy\n * as market discovery (#fetchMarketsForDex) and order placement\n * (#handleHip3PreOrder) — otherwise a non-USDC HIP-3 market could appear\n * in overview data (and the cached stale snapshot derived from it) while\n * order placement rejects it (TAT-3304).\n *\n * Main-DEX results (dex === null) and already-failed results pass through\n * unchanged. #isUsdcCollateralDex fails closed, and on an unexpected\n * error checking it (e.g. a spotMeta fetch failure) this also fails\n * closed by dropping the DEX's result, rather than failing the whole\n * method and losing main-DEX overview data.\n *\n * @param results - The DEX fetch results to filter.\n * @returns A promise that resolves to the filtered results.\n */\n async #excludeNonUsdcCollateralResults(\n results: DexFetchResult[],\n ): Promise<DexFetchResult[]> {\n return Promise.all(\n results.map(async (result) => {\n if (result.dex === null || !result.success) {\n return result;\n }\n\n let isUsdcDex: boolean;\n try {\n isUsdcDex = await this.#isUsdcCollateralDex(result.dex);\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Failed to check collateral type for HIP-3 DEX; excluding from market data',\n {\n dex: result.dex,\n error: ensureError(\n error,\n 'HyperLiquidProvider.excludeNonUsdcCollateralResults',\n ).message,\n },\n );\n isUsdcDex = false;\n }\n\n if (isUsdcDex) {\n return result;\n }\n\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: Excluding non-USDC-collateral HIP-3 DEX from market data',\n { dex: result.dex },\n );\n\n return {\n ...result,\n meta: null,\n assetCtxs: [],\n allMids: {},\n success: false,\n };\n }),\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 filteredMarketsWithContexts = marketsFromDex\n .map((market, index) => ({\n market,\n assetCtx: result.assetCtxs[index],\n }))\n .filter(\n ({ market }) =>\n result.dex === null ||\n shouldIncludeMarket(\n market.name,\n result.dex,\n this.#hip3Enabled,\n this.#compiledAllowlistPatterns,\n this.#compiledBlocklistPatterns,\n ),\n );\n\n combinedUniverse.push(\n ...filteredMarketsWithContexts.map(({ market }) => market),\n );\n combinedAssetCtxs.push(\n ...filteredMarketsWithContexts.map(({ assetCtx }) => assetCtx),\n );\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 dexParam = dex ?? '';\n const cachedMeta = this.#cachedMetaByDex.get(dex);\n if (!cachedMeta) {\n this.#deps.debugLogger.log(\n `[getMarketDataWithPrices] Cache miss for ${dex ?? 'main'}, fetching`,\n );\n return this.#fetchSingleDexFresh(\n infoClient,\n dex,\n lifecycleGeneration,\n );\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(dexParam) ?? [];\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 await this.#cacheDexMetadataFromRead({\n dex,\n meta: freshMeta,\n assetCtxs,\n lifecycleGeneration,\n });\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 // TAT-3304: Exclude non-USDC-collateral HIP-3 DEXs before merging, so\n // getMarketDataWithPrices (and the stale snapshot #cacheFreshMarketDataSnapshot\n // derives from it) enforces the same USDC-only policy as market discovery\n // and order placement.\n const usdcFilteredDexDataResults =\n await this.#excludeNonUsdcCollateralResults(dexDataResults);\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 = usdcFilteredDexDataResults;\n\n this.#mergeDexResultsInto(\n usdcFilteredDexDataResults,\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) =>\n this.#fetchSingleDexFresh(infoClient, dex, lifecycleGeneration),\n ),\n );\n const usdcFilteredRetryResults =\n await this.#excludeNonUsdcCollateralResults(retryResults);\n\n this.#mergeDexResultsInto(\n usdcFilteredRetryResults,\n combinedUniverse,\n combinedAssetCtxs,\n combinedAllMids,\n );\n\n latestDexResults = usdcFilteredRetryResults;\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 // Keep this diagnostic bounded. Logging every price stalls React Native\n // DevTools and other CDP clients when thousands of spot keys are present.\n const allMidEntries = Object.entries(combinedAllMids);\n const hip3Entries = allMidEntries.filter(([key]) => key.includes(':'));\n this.#deps.debugLogger.log('Combined allMids price data:', {\n totalKeys: allMidEntries.length,\n hip3Keys: hip3Entries.length,\n keySample: allMidEntries.slice(0, 5).map(([key]) => key),\n hip3KeySample: hip3Entries.slice(0, 5).map(([key]) => key),\n samplePrices: Object.fromEntries(allMidEntries.slice(0, 5)),\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 HYPERLIQUID_ASSET_NAMES,\n );\n if (\n !this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Market data cache write',\n )\n ) {\n return transformedMarketData;\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 if (params.expectedScaleLadder !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE,\n };\n }\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 triggerPrice: params.triggerPrice,\n takeProfitPrice: params.takeProfitPrice,\n stopLossPrice: params.stopLossPrice,\n takeProfitSize: params.takeProfitSize,\n stopLossSize: params.stopLossSize,\n tpslLinkage: params.tpslLinkage,\n grouping: params.grouping,\n timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n ...pickStrategyParams(params),\n });\n if (!basicValidation.isValid) {\n return basicValidation;\n }\n\n if (params.marginMode !== undefined) {\n if (params.marginMode !== 'cross' && params.marginMode !== 'isolated') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_INVALID,\n };\n }\n const { dex: dexName } = parseAssetName(params.symbol);\n const meta = await this.#getCachedMeta({ dexName });\n const assetInfo = meta.universe.find(\n (asset) => asset.name === params.symbol,\n );\n if (!assetInfo) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n await this.#validateMarginMode(params, assetInfo);\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-executing orders without currentPrice, use limit price as\n // fallback (plain limit, stop_limit, take_profit_limit)\n if (\n !priceForValidation &&\n params.price &&\n isLimitExecutionOrderType(params.orderType)\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 // Market-executing trigger orders (stop_market, take_profit_market)\n // have no limit price; the trigger price is the best notional estimate.\n if (\n !priceForValidation &&\n params.triggerPrice &&\n isTriggerOrderType(params.orderType)\n ) {\n priceForValidation = parseFloat(params.triggerPrice);\n this.#deps.debugLogger.log(\n 'Using trigger price for order validation (trigger order):',\n {\n size,\n triggerPrice: priceForValidation,\n orderType: params.orderType,\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 // A strategy placement's total clearing the per-order minimum does not\n // mean the orders it expands into will.\n const strategyMinimum = validateStrategyNotional({\n orderType: params.orderType,\n orderValueUSD,\n });\n if (!strategyMinimum.isValid) {\n return strategyMinimum;\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 await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });\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 withdrawableBalance = parseFloat(accountState.withdrawableBalance);\n this.#deps.debugLogger.log('HyperLiquidProvider: ACCOUNT BALANCE', {\n withdrawableBalance,\n spendableBalance: accountState.spendableBalance,\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 withdrawableBalance,\n sufficientBalance: withdrawAmount <= withdrawableBalance,\n });\n\n // Validate against withdrawableBalance — the mode-aware cap.\n // No spot sweep: withdrawableBalance already reflects what withdraw3\n // can pull. In Unified mode HL handles cross-wallet internally; in\n // Standard mode spot is not withdrawable via perps.\n const balanceValidation = validateBalance(\n withdrawAmount,\n withdrawableBalance,\n );\n if (!balanceValidation.isValid) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: INSUFFICIENT BALANCE',\n {\n error: balanceValidation.error,\n requestedAmount: withdrawAmount,\n withdrawableBalance,\n difference: withdrawAmount - withdrawableBalance,\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 signerFailure = await this.#handleSignerFailure(error, 'withdraw', {\n assetId: params.assetId,\n });\n if (signerFailure) {\n return createErrorResult(signerFailure, { success: false });\n }\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(\n 'withdraw',\n {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n },\n {\n operation: PERPS_ERROR_OPERATION.FinancialOperations,\n action: PERPS_ERROR_ACTION.FinancialWithdrawal,\n },\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 signerFailure = await this.#handleSignerFailure(\n error,\n 'transferBetweenDexs',\n { sourceDex: params.sourceDex, destinationDex: params.destinationDex },\n );\n if (signerFailure) {\n return { success: false, error: signerFailure.message };\n }\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;\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;\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 * Stream TWAP lifecycle updates from the venue's own push channel.\n *\n * The venue streams schedule state without slice fills, so each pushed\n * schedule carries an empty `fills` array. A subscriber that renders fill\n * history should keep what a prior `getTwapOrders()` read supplied rather\n * than replacing it from the stream.\n *\n * @param params - Subscription parameters including callback and account ID.\n * @returns A cleanup function to unsubscribe from TWAP updates.\n */\n subscribeToTwapOrders(params: SubscribeTwapOrdersParams): () => void {\n return this.#subscriptionService.subscribeToTwapOrders({\n ...params,\n adapt: (history) => {\n const now = Date.now();\n const ordersById = new Map<string, TwapOrder>();\n for (const historyEntry of history) {\n const order = this.#adaptTwapOrder({\n historyEntry,\n sliceFills: [],\n now,\n });\n if (!order) {\n continue;\n }\n const existing = ordersById.get(order.orderId);\n if (!existing || supersedesCollapsedTwapOrder(order, existing)) {\n ordersById.set(order.orderId, order);\n }\n }\n const orders = [...ordersById.values()].sort(\n (left, right) => right.startedAt - left.startedAt,\n );\n\n // A streamed terminal schedule must reclaim HIP-3 collateral the same\n // way a polled read does, or a consumer that replaced polling with\n // this subscription strands manually transferred collateral. The\n // listener is synchronous, so this runs detached and logs its own\n // failures rather than rejecting into the stream.\n this.#rebalanceStreamedTerminalTwaps(orders, params.accountId);\n\n return orders;\n },\n });\n }\n\n /**\n * Reclaim HIP-3 collateral for terminal schedules seen on the TWAP stream.\n *\n * `getTwapOrders()` does this on every read; without the same call here a\n * consumer that replaced polling with the subscription would strand\n * manually transferred collateral. Detached on purpose: the stream listener\n * is synchronous and must not reject.\n *\n * @param orders - Schedules from the latest stream push.\n * @param accountId - Optional CAIP account ID the subscription is scoped to.\n */\n #rebalanceStreamedTerminalTwaps(\n orders: TwapOrder[],\n accountId?: CaipAccountId,\n ): void {\n if (orders.every((order) => order.status === 'active')) {\n return;\n }\n\n // Resolve the address from the push's own scope before detaching. Left\n // inside the microtask it would resolve at run time, so an account switch\n // racing a terminal push would key the reclaim to the newly selected\n // account and silently skip the schedule it was meant to settle.\n const userAddressPromise =\n this.#walletService.getUserAddressWithDefault(accountId);\n // Capture the network with the address, not after awaiting it: a network\n // toggle while resolution is pending would key the reclaim to the opposite\n // network and skip the terminal schedule.\n const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';\n\n (async (): Promise<void> => {\n const userAddress = await userAddressPromise;\n await this.#rebalanceTerminalHip3Twaps(orders, {\n network,\n userAddress,\n });\n })().catch((error) => {\n this.#deps.debugLogger.log('TWAP stream HIP-3 rebalance failed', {\n error: ensureError(error, 'HyperLiquidProvider.subscribeToTwapOrders')\n .message,\n });\n });\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 webData3 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 const disconnectResult = await this.disconnect();\n if (!disconnectResult.success) {\n // The network did not change. Keep the provider eligible for lazy\n // recovery instead of leaving this aborted toggle permanently sticky.\n this.#isDisconnected = false;\n throw new Error(\n disconnectResult.error ??\n 'Failed to disconnect before network toggle',\n );\n }\n\n // Update all services\n this.#clientService.setTestnetMode(newIsTestnet);\n // Invalidate reads that started after disconnect completed but before\n // the clients switched networks.\n this.#lifecycleGeneration += 1;\n this.#walletService.setTestnetMode(newIsTestnet);\n\n const initializeResult = await this.initialize();\n if (!initializeResult.success) {\n // The network switch is already committed. Leave the provider eligible\n // for lazy initialization so the next operation can retry the failed\n // client setup instead of remaining permanently disconnected.\n this.#isDisconnected = false;\n throw new Error(\n initializeResult.error ?? 'Failed to initialize after network toggle',\n );\n }\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 const lifecycleGeneration = this.#lifecycleGeneration;\n try {\n if (this.#disconnectOperationsInFlight > 0) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n // Ensure clients are initialized (lazy initialization)\n await this.#ensureClientsInitialized();\n if (\n this.#disconnectOperationsInFlight > 0 ||\n lifecycleGeneration !== this.#lifecycleGeneration\n ) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n this.#isDisconnected = false;\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 * Forget every agent resolved through `getAgentSigner`, so the next L1\n * action asks again; an answer still pending is discarded too.\n */\n clearAgentSigners(): void {\n this.#agentSignersGeneration += 1;\n this.#agentSigners.clear();\n }\n\n /**\n * Run the deferred account migration, builder fee and referral setup ahead\n * of the first order. Results are cached, so an already-ready account signs\n * nothing. A referral whose MetaMask code is not ready yet is checked again\n * by the next call rather than by orders.\n *\n * @returns The readiness result described on\n * `PerpsController.prepareTradingWallet`.\n */\n async prepareTradingWallet(): Promise<ReadyToTradeResult> {\n // Nothing can be signed, so run no setup (and log nothing) until it can.\n if (!this.#walletService.isMainAccountSignerReady()) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n try {\n const lifecycleGeneration = this.#lifecycleGeneration;\n const userAddress = await this.#walletService.getUserAddressWithDefault();\n // The result is only for the provider and account it started with.\n const assertPreparationCurrent = async (): Promise<void> => {\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Trading wallet preparation',\n );\n // A deselected account changed too.\n const currentAddress = await this.#walletService\n .getUserAddressWithDefault()\n .catch(() => undefined);\n if (currentAddress?.toLowerCase() !== userAddress.toLowerCase()) {\n throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);\n }\n };\n await this.#ensureReadyForTrading({\n requiresBuilderFee: false,\n recheckPendingReferral: true,\n });\n const network = this.#clientService.isTestnetMode()\n ? 'testnet'\n : 'mainnet';\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n await assertPreparationCurrent();\n // The venue rejects every write from a wallet with no HyperLiquid account\n // yet, so it is not asked to sign a builder fee approval either.\n if (!isRegistered) {\n return {\n ready: false,\n error: this.#walletService.isMainAccountSignerReady()\n ? PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND\n : PERPS_ERROR_CODES.KEYRING_LOCKED,\n };\n }\n await this.#ensureBuilderFeeSetup(undefined, {\n reportSignerFailure: true,\n reportRefusal: true,\n });\n // The builder fee setup ends quietly when the provider disconnects.\n await assertPreparationCurrent();\n if (!this.#walletService.isMainAccountSignerReady()) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n const ready =\n this.#tradingSetupComplete &&\n !this.#unifiedAccountSetupNeedsRetry &&\n this.#builderFeeCheckCache.has(this.#getCacheKey(network, userAddress));\n return { ready };\n } catch (error) {\n // A step failed because the signer could not sign it (or locked while\n // it ran): retryable, not logged.\n if (\n isKeyringLockedError(error) ||\n !this.#walletService.isMainAccountSignerReady()\n ) {\n return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };\n }\n const caughtError = ensureError(\n error,\n 'HyperLiquidProvider.prepareTradingWallet',\n );\n if (caughtError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] Provider replaced during preparation',\n );\n } else if (\n caughtError.message === PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED\n ) {\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] No account selected',\n );\n } else if (getBuilderFeeRefusal(caughtError)) {\n // Signing again cannot fix it, and orders are not blocked by it.\n this.#deps.debugLogger.log(\n '[prepareTradingWallet] Builder fee approval refused',\n { error: caughtError.message },\n );\n } else {\n this.#deps.logger.error(\n caughtError,\n this.#getErrorContext('prepareTradingWallet'),\n );\n }\n return { ready: false, error: caughtError.message };\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 * Project the isolated position that would remain after a proposed order.\n *\n * Fetches the asset's margin table from cached meta so liquidation uses the\n * maintenance tier at the resulting liquidation notional. Cross-margin\n * positions return unsupported without a table lookup.\n *\n * @param params - Live position plus the proposed order.\n * @returns Discriminated preview; margin and liquidation are independently available.\n */\n async previewPositionModify(\n params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult> {\n if (params.position.leverage.type === 'cross') {\n return { status: 'unsupported', reason: 'cross_margin' };\n }\n\n const { dex: dexName } = parseAssetName(params.position.symbol);\n let marginTiers = null;\n\n try {\n const meta = await this.#getCachedMeta({ dexName });\n const assetInfo = meta.universe.find(\n (universeItem) => universeItem.name === params.position.symbol,\n );\n marginTiers = resolveHyperLiquidMarginTiers({\n marginTableId: assetInfo?.marginTableId,\n maxLeverage: assetInfo?.maxLeverage ?? params.position.maxLeverage,\n marginTables: meta.marginTables,\n });\n } catch (error) {\n this.#deps.debugLogger.log(\n 'HyperLiquidProvider: margin table unavailable for position preview',\n {\n symbol: params.position.symbol,\n error,\n },\n );\n }\n\n return previewHyperLiquidIsolatedPositionModify({\n ...params,\n marginTiers,\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 const lifecycleGeneration = this.#lifecycleGeneration;\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 if (\n this.#isCacheWriteLifecycleCurrent(\n lifecycleGeneration,\n 'Maximum leverage cache write',\n )\n ) {\n this.#maxLeverageCache.set(asset, {\n value: assetInfo.maxLeverage,\n timestamp: now,\n });\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 lifecycleGeneration = this.#lifecycleGeneration;\n const { orderType, isMaker = false, amount, symbol } = params;\n const numericAmount =\n amount === undefined ? undefined : Number.parseFloat(amount);\n const parsedAmount =\n numericAmount === undefined ||\n (Number.isFinite(numericAmount) && numericAmount >= 0)\n ? numericAmount\n : 0;\n\n // Every placement is charged as its execution kind: a stop_market fills as a\n // market order (taker), a stop_limit as a limit order, a scale ladder as the\n // resting limit orders it fans out into, and a TWAP as the marketable\n // suborders it crosses the book with.\n const isMarketExecution = getTriggerExecution(orderType) === 'market';\n\n // A chase is post-only by construction, so it can only ever fill as a maker.\n // Quoting it at the taker rate would overstate the fee whatever the caller\n // passes for `isMaker`.\n const chargesMakerRate =\n orderType === 'chase' || (!isMarketExecution && isMaker);\n\n // Start with base rates from config\n let feeRate = chargesMakerRate ? FEE_RATES.maker : FEE_RATES.taker;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee cache read',\n );\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 // Same maker/taker decision as the base rates above, including the\n // post-only chase case — re-deriving it here would quote a chase at\n // the taker rate whenever the caller passed isMaker: false.\n let userFeeRate = chargesMakerRate\n ? cached.perpsMakerRate\n : cached.perpsTakerRate;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee fetch',\n );\n await this.#ensureClientsInitialized();\n this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee fetch',\n );\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 = parseBoundedNonNegativeDecimal(\n userFees.userCrossRate,\n MAX_API_FEE_RATE,\n );\n const baseUserMakerRate = parseBoundedNonNegativeDecimal(\n userFees.userAddRate,\n MAX_API_FEE_RATE,\n );\n const baseUserSpotTakerRate = parseBoundedNonNegativeDecimal(\n userFees.userSpotCrossRate,\n MAX_API_FEE_RATE,\n );\n const baseUserSpotMakerRate = parseBoundedNonNegativeDecimal(\n userFees.userSpotAddRate,\n MAX_API_FEE_RATE,\n );\n\n // Apply discounts manually since HyperLiquid API doesn't apply them\n const referralDiscount = parseBoundedNonNegativeDecimal(\n userFees.activeReferralDiscount || '0',\n MAX_API_FEE_DISCOUNT,\n );\n const stakingDiscount = parseBoundedNonNegativeDecimal(\n userFees.activeStakingDiscount?.discount || '0',\n MAX_API_FEE_DISCOUNT,\n );\n\n if (\n baseUserTakerRate === null ||\n baseUserMakerRate === null ||\n baseUserSpotTakerRate === null ||\n baseUserSpotMakerRate === null ||\n referralDiscount === null ||\n stakingDiscount === null\n ) {\n throw new Error('Invalid fee rates received from API');\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 !Number.isFinite(perpsTakerRate) ||\n !Number.isFinite(perpsMakerRate) ||\n !Number.isFinite(spotTakerRate) ||\n !Number.isFinite(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:\n Number.isFinite(perpsTakerRate) && perpsTakerRate >= 0,\n perpsMakerValid:\n Number.isFinite(perpsMakerRate) && perpsMakerRate >= 0,\n spotTakerValid:\n Number.isFinite(spotTakerRate) && spotTakerRate >= 0,\n spotMakerValid:\n Number.isFinite(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.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'User fee cache write',\n );\n this.#userFeeCache.set(userAddress, rates);\n // Same maker/taker decision as the base rates above, chase included.\n let userFeeRate = chargesMakerRate\n ? rates.perpsMakerRate\n : rates.perpsTakerRate;\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 if (safeError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {\n throw safeError;\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 this.#assertProviderLifecycleCurrent(\n lifecycleGeneration,\n 'Fee calculation',\n );\n\n // Protocol base fee (HyperLiquid's fee)\n const protocolFeeRate = feeRate;\n const protocolFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * protocolFeeRate;\n\n // The provider policy, not the client, owns whether this placement can\n // carry a builder fee. The dedicated TWAP action has no builder field.\n const { chargesMetamaskBuilderFee } = this.#resolveOrderFeePolicy(params);\n const baseMetamaskFeeRate = chargesMetamaskBuilderFee\n ? BUILDER_FEE_CONFIG.MaxFeeDecimal\n : 0;\n const metamaskFeeDiscount =\n this.#userFeeDiscountBips === undefined\n ? 0\n : this.#userFeeDiscountBips / BASIS_POINTS_DIVISOR;\n const metamaskFeeRate = baseMetamaskFeeRate * (1 - metamaskFeeDiscount);\n\n if (chargesMetamaskBuilderFee && this.#userFeeDiscountBips !== undefined) {\n this.#deps.debugLogger.log('HyperLiquid: Applied MetaMask fee discount', {\n originalRate: baseMetamaskFeeRate,\n discountBips: this.#userFeeDiscountBips,\n discountPercentage: this.#userFeeDiscountBips / 100,\n adjustedRate: metamaskFeeRate,\n discountAmount: baseMetamaskFeeRate * metamaskFeeDiscount,\n });\n }\n\n const metamaskFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * metamaskFeeRate;\n\n // Total fees\n const totalFeeRate = protocolFeeRate + metamaskFeeRate;\n const totalFeeAmount =\n parsedAmount === undefined ? undefined : parsedAmount * totalFeeRate;\n if (\n !Number.isFinite(protocolFeeRate) ||\n protocolFeeRate < 0 ||\n !Number.isFinite(metamaskFeeRate) ||\n metamaskFeeRate < 0 ||\n !Number.isFinite(totalFeeRate) ||\n totalFeeRate < 0 ||\n (protocolFeeAmount !== undefined &&\n !Number.isFinite(protocolFeeAmount)) ||\n (metamaskFeeAmount !== undefined &&\n !Number.isFinite(metamaskFeeAmount)) ||\n (totalFeeAmount !== undefined && !Number.isFinite(totalFeeAmount))\n ) {\n throw new Error('Invalid fee calculation result');\n }\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 chargesMetamaskBuilderFee,\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 * Escape hatch for agentic validation flows and test harnesses that drive\n * HL mutations directly. NOT part of the PerpsProvider interface.\n * Production code paths must go through the provider's own methods.\n *\n * @returns A promise resolving to the underlying HyperLiquid SDK\n * ExchangeClient. Promise shape matches the existing agentic flows\n * (hl-provision-fixture) that chain `.then` on the result.\n */\n public async getExchangeClient(): Promise<ExchangeClient> {\n // Initialized here so the client signs through this provider's wallet.\n await this.#ensureClientsInitialized();\n return this.#clientService.getExchangeClient();\n }\n\n /**\n * Disconnect provider\n *\n * @returns A promise that resolves to the result.\n */\n async disconnect(): Promise<DisconnectResult> {\n if (this.#disconnectOperationPromise) {\n return this.#disconnectOperationPromise;\n }\n\n const operation = this.#performDisconnect();\n this.#disconnectOperationPromise = operation;\n try {\n return await operation;\n } finally {\n if (this.#disconnectOperationPromise === operation) {\n this.#disconnectOperationPromise = null;\n }\n }\n }\n\n /**\n * Perform one provider teardown shared by every concurrent caller.\n *\n * @returns A promise that resolves to the result.\n */\n async #performDisconnect(): Promise<DisconnectResult> {\n this.#chasePlacementBlockers += 1;\n this.#strategyGeneration += 1;\n this.#disconnectOperationsInFlight += 1;\n this.#isDisconnected = true;\n this.#lifecycleGeneration += 1;\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 // Stop every chase loop: each holds a pending timer, and re-pricing after\n // a disconnect would sign orders against a client that is being torn down.\n // Orders already resting are deliberately left alone — disconnecting is\n // not a request to cancel the user's positions or orders.\n // Invalidate placements first, then drain every mutation before clearing\n // the registry and tearing down the clients they use.\n for (const [sessionId, session] of this.#chaseSessions.entries()) {\n if (session.active) {\n this.#stopChaseSession(sessionId);\n }\n }\n await Promise.all([...this.#chasePlacementWaiters]);\n await this.#chaseTickQueue;\n await Promise.allSettled([...this.#chaseTerminations.values()]);\n await Promise.all(\n [...this.#chaseSessions.values()].map(\n async (session) => await this.#rebalanceChaseSession(session),\n ),\n );\n this.#chaseSessions.clear();\n this.#chaseTerminations.clear();\n this.#terminatedChaseHandles.clear();\n this.#scaleOrderGroups.clear();\n this.#cancelledScaleOrderGroups.clear();\n\n // Clear session caches. Capability and fee reads use the lifecycle\n // generation above to discard any old response that resolves later.\n this.clearFeeCache();\n this.#referralCheckCache.clear();\n this.#builderFeeCheckCache.clear();\n this.#builderFeeRefusals.clear();\n this.#subscriptionBuilderApprovalEpoch += 1;\n this.#approvedBuilderAddresses.clear();\n this.#userFeeResolution = undefined;\n this.#userFeeDiscountBips = undefined;\n // UnifiedAccountCache stays global to avoid repeated signing requests.\n this.#cachedMetaByDex.clear();\n this.#pendingValidatedDexsPromise = null;\n this.#orderCapabilitiesMarketsByDex.clear();\n this.#orderCapabilitiesRefreshByDex.clear();\n this.#cachedSpotMeta = null;\n this.#dexDiscoveryCache.reset();\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 const pendingBuilderFeeSetups = [\n ...this.#builderFeeSetupPromises.values(),\n ];\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.#builderFeeSetupPromises.clear();\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 for (const pendingBuilderFeeSetup of pendingBuilderFeeSetups) {\n try {\n await pendingBuilderFeeSetup;\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 // Only after the pending setups above settled: a lookup that failed on\n // the transport while they were awaited must not carry its cooldown\n // into the next session.\n this.#unifiedAccountTransportRetryAt = 0;\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 } finally {\n this.#chasePlacementBlockers -= 1;\n this.#disconnectOperationsInFlight -= 1;\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 await this.#clientService.reconnect();\n // The socket was rebuilt: the unified-account setup can run again now.\n this.#unifiedAccountTransportRetryAt = 0;\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 /**\n * The dedicated subscription builder address for this network, if configured.\n *\n * @deprecated Only {@link approveSubscriptionBuilderFee} still reads this;\n * order construction no longer does. See that method for the removal plan.\n * @param isTestnet - Whether the provider is in testnet mode.\n * @returns The configured address, or undefined.\n */\n #getSubscriptionBuilderAddress(isTestnet: boolean): string | undefined {\n return isTestnet\n ? this.#subscriptionBuilderAddressTestnet\n : this.#subscriptionBuilderAddressMainnet;\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 this.#referralSetupNeedsRetry = false;\n this.#referralAwaitsBuilderCode = false;\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 // Skip the referral write for unfunded wallets — same proactive gate\n // as `#ensureUnifiedAccountEnabled`. `exchangeClient.setReferrer`\n // rejects with \"User or API Wallet 0x... does not exist.\" for wallets\n // that have not yet deposited.\n const isRegistered = await this.#isWalletOnHyperliquid(\n userAddress,\n network,\n );\n if (!isRegistered) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Wallet not yet on Hyperliquid, deferring referral setup',\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 hardware wallet prompt spam)',\n { network, success: globalCached.success },\n );\n return;\n }\n\n // Wait while another provider attempts it. That attempt may end without\n // caching a result (its signer could not sign), so take the lock once it\n // is free and re-check the cache under it. The lock is checked and taken\n // with no await in between, so only one of several waiters gets it.\n let inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\n while (inFlightPromise) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Global in-flight, waiting...',\n { network },\n );\n await inFlightPromise;\n inFlightPromise = PerpsSigningCache.isInFlight(\n 'referral',\n network,\n userAddress,\n );\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 codeStatus = await this.#getReferralCodeStatus();\n if (codeStatus !== 'ready') {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Builder referral not ready, skipping',\n { network, codeStatus },\n );\n // Don't cache. A failed lookup (already logged) waits for the next\n // setup; a code that is not ready yet, for the next preparation.\n this.#referralAwaitsBuilderCode = codeStatus === 'pending';\n completeInFlight();\n return;\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 // The signer could not sign (a locked keyring, or an unavailable or\n // rejected agent; HyperLiquid keeps the cause in `cause`): leave the\n // cache empty and attempt the referral again at the next setup.\n if (await this.#classifySignerFailure(error)) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Signer unavailable, will retry later',\n );\n this.#referralSetupNeedsRetry = true;\n completeInFlight();\n return;\n }\n\n // Safety net: wallet looked registered but the SDK still rejects with\n // \"User or API Wallet 0x... does not exist.\" Do not forward to Sentry.\n // The walletRegistered cache stores positive observations only, so no\n // demotion is needed; the next entry will re-probe.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[ensureReferralSet] Wallet not on Hyperliquid (race/stale-cache), deferring referral',\n { network, user: userAddress },\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 whether the builder's referral code can be used.\n *\n * @returns `ready`, `pending` while the builder's code is not ready yet, or\n * `failed` when the lookup failed or the code on file does not match (logged).\n */\n async #getReferralCodeStatus(): Promise<'ready' | 'pending' | 'failed'> {\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 'ready';\n }\n\n // Not ready yet - log as debugLogger since this is expected during setup phase\n this.#deps.debugLogger.log(\n '[getReferralCodeStatus] Referral code not ready',\n {\n stage,\n code,\n referrerAddr,\n },\n );\n return 'pending';\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'HyperLiquidProvider.getReferralCodeStatus'),\n this.#getErrorContext('getReferralCodeStatus', {\n code: this.#getReferralCode(this.#clientService.isTestnetMode()),\n referrerAddress: this.#getBuilderAddress(\n this.#clientService.isTestnetMode(),\n ),\n }),\n );\n return 'failed';\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 // Benign for unfunded wallets — downgrade to debug log, do not Sentry.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[checkReferralSet] Wallet not on Hyperliquid yet, treating as no referral',\n {\n error: ensureError(error, 'HyperLiquidProvider.checkReferralSet')\n .message,\n },\n );\n return false;\n }\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 // Retryable (a locked keyring, an unavailable agent, or one the venue\n // rejected): `#ensureReferralSet` retries at the next entry, so it is\n // not an error to report.\n if (await this.#isSignerFailure(error)) {\n throw error;\n }\n // Benign for unfunded wallets — downgrade and rethrow so the outer\n // `#ensureReferralSet` catch self-heals the walletRegistered gate\n // without forwarding to Sentry.\n if (isHyperLiquidUserNotFoundError(error)) {\n this.#deps.debugLogger.log(\n '[setReferralCode] Wallet not on Hyperliquid yet, skipping referral write',\n {\n error: ensureError(error, 'HyperLiquidProvider.setReferralCode')\n .message,\n },\n );\n throw error;\n }\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"]}
|