@metamask-previews/perps-controller 26.2.0-preview-2cd622db9 → 26.2.0-preview-53b9b7d11
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 +12 -1
- package/dist/PerpsController-method-action-types.d.ts +11 -1
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +8 -1
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +45 -13
- package/dist/PerpsController.js.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.js +10 -2
- package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
- package/dist/constants/eventNames.d.ts +2 -0
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +3 -0
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/lighterConfig.d.ts +11 -0
- package/dist/constants/lighterConfig.d.ts.map +1 -1
- package/dist/constants/lighterConfig.js +11 -0
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +6 -0
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +6 -0
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +10 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -3
- 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 +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +6 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +14 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +1 -3
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +6 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +458 -149
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +13 -1
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +1 -0
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +12 -2
- package/dist/services/StreamChannelManager.d.ts.map +1 -1
- package/dist/services/StreamChannelManager.js +18 -0
- package/dist/services/StreamChannelManager.js.map +1 -1
- package/dist/types/index.d.ts +21 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/docs/architecture.md +5 -4
- package/docs/venues/lighter/api-keys.md +8 -0
- package/package.json +3 -3
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA0B9C;;;;GAIG;AACH,MAAM,CAAN,IAAY,wBAKX;AALD,WAAY,wBAAwB;IAClC,yDAA6B,CAAA;IAC7B,qDAAyB,CAAA;IACzB,mDAAuB,CAAA;IACvB,2DAA+B,CAAA;AACjC,CAAC,EALW,wBAAwB,KAAxB,wBAAwB,QAKnC;AA8FD,gEAAgE;AAChE,MAAM,CAAN,IAAY,cASX;AATD,WAAY,cAAc;IACxB,2CAAyB,CAAA;IACzB,iCAAe,CAAA;IACf,oCAAkB,CAAA;IAClB,iCAAe,CAAA;IACf,6BAAW,CAAA;IACX,yCAAuB,CAAA;IACvB,iCAAe,CAAA;IACf,uCAAqB,CAAA;AACvB,CAAC,EATW,cAAc,KAAd,cAAc,QASzB;AAmCD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,QAAQ;IACR,UAAU;IACV,OAAO;IACP,SAAS;IACT,OAAO;IACP,KAAK;IACL,WAAW;IACX,OAAO;CAC8B,CAAC;AAqgIxC;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,mBAiBX;AAjBD,WAAY,mBAAmB;IAC7B,4EAAqD,CAAA;IACrD,kEAA2C,CAAA;IAC3C,mFAA4D,CAAA;IAC5D,+EAAwD,CAAA;IACxD,0DAAmC,CAAA;IACnC,4DAAqC,CAAA;IACrC,8DAAuC,CAAA;IACvC,gDAAyB,CAAA;IACzB,0DAAmC,CAAA;IACnC,8BAA8B;IAC9B,oFAAoF;IACpF,4EAAqD,CAAA;IACrD,uEAAgD,CAAA;IAChD,wDAAiC,CAAA;IACjC,uEAAgD,CAAA;IAChD,gEAAyC,CAAA;AAC3C,CAAC,EAjBW,mBAAmB,KAAnB,mBAAmB,QAiB9B;AAiED;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,qBAAqB;IACrB,UAAU,EAAE,mBAAmB;IAC/B,SAAS,EAAE,kBAAkB;IAC7B,WAAW,EAAE,oBAAoB;IACjC,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,oBAAoB;IAChC,YAAY,EAAE,qBAAqB;IACnC,YAAY,EAAE,qBAAqB;IAEnC,qBAAqB;IACrB,QAAQ,EAAE,gBAAgB;IAC1B,OAAO,EAAE,eAAe;IAExB,cAAc;IACd,YAAY,EAAE,qBAAqB;IACnC,eAAe,EAAE,yBAAyB;IAC1C,UAAU,EAAE,mBAAmB;IAC/B,uBAAuB,EAAE,mCAAmC;IAC5D,eAAe,EAAE,yBAAyB;IAC1C,WAAW,EAAE,oBAAoB;IACjC,YAAY,EAAE,qBAAqB;IACnC,sBAAsB,EAAE,gCAAgC;IACxD,sBAAsB,EAAE,gCAAgC;IAExD,YAAY;IACZ,cAAc,EAAE,wBAAwB;IAExC,YAAY;IACZ,kBAAkB,EAAE,2BAA2B;IAC/C,qBAAqB,EAAE,8BAA8B;IACrD,uBAAuB,EAAE,iCAAiC;IAC1D,oBAAoB,EAAE,8BAA8B;IACpD,qBAAqB,EAAE,+BAA+B;IAEtD,QAAQ;IACR,cAAc,EAAE,wBAAwB;IACxC,uBAAuB,EAAE,gCAAgC;IACzD,yBAAyB,EAAE,mCAAmC;IAC9D,iBAAiB,EAAE,2BAA2B;IAC9C,eAAe,EAAE,yBAAyB;CACO,CAAC;AAEpD;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,SAAS,EAAE,iBAAiB;IAC5B,eAAe,EAAE,wBAAwB;IACzC,kBAAkB,EAAE,2BAA2B;CACvC,CAAC;AAumBX;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC;QAC7B,WAAW,CAAC,KAAK,EAAE,gBAAgB,CAAC;QACpC,OAAQ,KAA8B,CAAC,OAAO,KAAK,SAAS;QAC5D,OAAQ,KAAqC,CAAC,cAAc,KAAK,QAAQ,CAC1E,CAAC;AACJ,CAAC;AAQD,cAAc,uBAAuB,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n CaipAccountId,\n CaipChainId,\n CaipAssetId,\n Hex,\n} from '@metamask/utils';\n\nimport type { CandlePeriod, TimeDuration } from '../constants/chartConfig.js';\nimport type { PerpsMaxSlippageSource } from '../constants/eventNames.js';\nimport type { CHASE_ORDER_STATUS } from '../constants/perpsConfig.js';\nimport type { PerpsErrorDetails } from '../errors.js';\nimport type { PerpsErrorCode } from '../perpsErrorCodes.js';\nimport type { LighterProvider } from '../providers/LighterProvider.js';\nimport type { HyperLiquidMarginTier } from '../utils/hyperLiquidPositionPreview.js';\nimport type { LighterSignerBridge } from './lighter-types.js';\nimport type {\n CandleData,\n OrderDirection,\n OrderType,\n StrategyOrderType,\n TpslLinkage,\n TriggerDirection,\n TriggerOrderType,\n} from './perps-types.js';\n\n/**\n * Connection states for WebSocket management.\n * Defined inline to avoid importing from Mobile-only services.\n * Must stay in sync with HyperLiquidClientService.WebSocketConnectionState.\n */\nexport enum WebSocketConnectionState {\n Disconnected = 'disconnected',\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnecting = 'disconnecting',\n}\n\n/**\n * Why a provider reports degraded health.\n *\n * - `socket_down`: the venue socket is down or reconnecting while streams need it.\n * - `server_errors`: repeated 5xx responses from the venue's REST API.\n * - `rate_limited`: the venue answered 429/405; reads are held until `cooldownUntil`.\n */\nexport type PerpsProviderHealthReason =\n | 'socket_down'\n | 'server_errors'\n | 'rate_limited';\n\n/**\n * One provider's health. `unavailable` means the provider is not registered,\n * or is disconnected with no reconnect pending (not started or disconnected).\n * It describes the provider, not its socket: Lighter closes its socket when\n * nothing listens and still reports `healthy`.\n */\nexport type PerpsProviderHealth = {\n providerId: PerpsProviderType;\n status: 'healthy' | 'degraded' | 'unavailable';\n /** Empty unless `status` is `degraded`. */\n reasons: PerpsProviderHealthReason[];\n connectionState: WebSocketConnectionState;\n /** Reconnect attempts since the last successful open (0 when connected or idle). */\n reconnectionAttempt: number;\n /** Epoch ms when a rate-limit cooldown ends, set only while `rate_limited`. */\n cooldownUntil?: number;\n /** Epoch ms when this snapshot was taken. */\n updatedAt: number;\n};\n\n/** Parameters for `PerpsController.subscribeToProviderHealth`. */\nexport type SubscribeProviderHealthParams = {\n providerId: PerpsProviderType;\n callback: (health: PerpsProviderHealth) => void;\n};\n\n/** Provider-agnostic raw ledger update. Fields match the common shape across providers. */\nexport type RawLedgerUpdate = {\n hash: string;\n time: number;\n delta: {\n type: string;\n usdc?: string;\n coin?: string;\n };\n};\n\n// User history item for deposits and withdrawals\nexport type UserHistoryItem = {\n id: string;\n timestamp: number;\n type: 'deposit' | 'withdrawal';\n amount: string;\n asset: string;\n txHash: string;\n status: 'completed' | 'failed' | 'pending';\n details: {\n source: string;\n bridgeContract?: string;\n recipient?: string;\n blockNumber?: string;\n chainId?: string;\n synthetic?: boolean;\n };\n};\n\n// Parameters for getting user history\nexport type GetUserHistoryParams = {\n startTime?: number;\n endTime?: number;\n accountId?: CaipAccountId;\n};\n\n// Trade configuration saved per market per network\nexport type TradeConfiguration = {\n leverage?: number; // Last used leverage for this market\n marginMode?: MarginMode; // Last Isolated/Cross pick for this market\n // Pending trade configuration (temporary, expires after 30 seconds)\n pendingConfig?: {\n amount?: string; // Order size in USD\n leverage?: number; // Leverage\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n limitPrice?: string; // Limit price (for limit orders)\n orderType?: OrderType; // Market vs limit\n reduceOnly?: boolean; // Whether the order may only reduce a position\n timestamp: number; // When the config was saved (for expiration check)\n };\n};\n\n// Market asset type classification (reusable across components)\nexport enum MarketCategory {\n CryptoCurrency = 'crypto',\n Stock = 'stock',\n PreIpo = 'pre-ipo',\n Index = 'index',\n Etf = 'etf',\n Commodity = 'commodity',\n Forex = 'forex',\n Memecoin = 'memecoin',\n}\n\nexport type MarketType = `${MarketCategory}`;\n\n/**\n * Metadata extracted from Terminal API for a single asset.\n * Used downstream to enrich PerpsMarketData with name, keywords, tags, etc.\n */\nexport type TerminalAssetMetadata = {\n name?: string;\n description?: string;\n keywords?: string[];\n tags?: string[];\n categories?: string[];\n marketType?: MarketType;\n /**\n * Epoch ms when this market was listed on the Terminal backend.\n * Normalized from the raw API value (number or ISO string).\n */\n listedAt?: number;\n};\n\n// Market type filter for UI category badges\nexport type MarketTypeFilter =\n | 'all'\n | 'crypto'\n | 'memecoin'\n | 'stock'\n | 'pre-ipo'\n | 'index'\n | 'etf'\n | 'commodity'\n | 'forex'\n | 'new';\n\n/**\n * Ordered list of data-model market categories for UI pills.\n * Does not include the 'all' or 'new' sentinel values — those are applied\n * via dedicated UI controls, not the category pills.\n *\n * Note: 'memecoin' is a derived category (marketType === 'crypto' &&\n * tags.includes('memecoin')). It overlaps with 'crypto' by design —\n * memecoins appear under both pills.\n *\n * Kept in sync with {@link MarketTypeFilter} via `satisfies`.\n */\nexport const MARKET_CATEGORIES = [\n 'crypto',\n 'memecoin',\n 'stock',\n 'pre-ipo',\n 'index',\n 'etf',\n 'commodity',\n 'forex',\n] as const satisfies MarketTypeFilter[];\n\n// Input method for amount entry tracking\nexport type InputMethod =\n | 'default'\n | 'slider'\n | 'keypad'\n | 'percentage'\n | 'max';\n\n// Trade action type - differentiates first trade on a market, adding to an\n// existing position, and flipping a position's direction\nexport type TradeAction =\n | 'create_position'\n | 'increase_exposure'\n | 'flip_long_to_short'\n | 'flip_short_to_long';\n\n// Unified tracking data interface for analytics events (never persisted in state)\n// Note: Numeric values are already parsed by hooks (usePerpsOrderFees, etc.) from API responses\nexport type TrackingData = {\n // Common to all operations\n totalFee?: number; // Total fee for the operation (parsed by hooks); omit when unknown\n marketPrice?: number; // Market price at operation time (parsed by hooks); omit when unknown\n metamaskFee?: number; // MetaMask fee amount (parsed by hooks)\n metamaskFeeRate?: number; // MetaMask fee rate (parsed by hooks)\n feeDiscountPercentage?: number; // Fee discount percentage (parsed by hooks)\n estimatedPoints?: number; // Estimated reward points (parsed by hooks)\n\n // Order-specific (used for trade operations)\n marginUsed?: number; // Margin required for this order (calculated by hooks)\n inputMethod?: InputMethod; // How user set the amount\n tradeAction?: TradeAction; // 'create_position' for first trade, 'increase_exposure' for adding to existing\n\n // Close-specific (used for position close operations)\n receivedAmount?: number; // Amount user receives after close (calculated by hooks)\n realizedPnl?: number; // Realized P&L from close (calculated by hooks)\n\n // Entry source for analytics (e.g., 'trending' for Trending page discovery)\n source?: string;\n // Chart library active when the trade was initiated (e.g., lightweight, advanced)\n chartLibrary?: string;\n\n // Entry point / discovery attribution. Propagated onto trade/close/\n // cancel/risk events as entry_point, discovery_source, perp_discovery_source.\n entryPoint?: string;\n discoverySource?: string;\n perpDiscoverySource?: string;\n\n // UI surface that started the action. Omitted from the event when unset.\n environmentType?: string;\n\n // HyperLiquid protocol fee rate. Emitted as hl_fee_rate on trade +\n // close events when present; omitted entirely when unavailable.\n hlFeeRate?: number;\n\n // Slippage context for trade and close transaction analytics.\n maxSlippageBps?: number;\n maxSlippageSource?: PerpsMaxSlippageSource;\n estimatedSlippageBps?: number;\n\n // Pay with any token: true when user paid with a custom token (not Perps balance)\n tradeWithToken?: boolean;\n mmPayTokenSelected?: string; // Token symbol when tradeWithToken is true\n mmPayNetworkSelected?: string; // chainId when tradeWithToken is true\n\n // VIP tier and discount for rewards tracking\n vipTier?: number; // User's VIP tier level\n vipDiscount?: number; // VIP discount percentage applied\n\n // A/B test context to attribute trade events to specific experiments\n abTests?: Record<string, string>;\n};\n\n// TP/SL-specific tracking data for analytics events\nexport type TPSLTrackingData = {\n direction: 'long' | 'short'; // Position direction\n /**\n * @deprecated Source of the TP/SL update (e.g., 'tp_sl_view', 'position_card').\n * Prefer `entryPoint` / `discoverySource` / `perpDiscoverySource` for risk-event\n * attribution; `source` is retained for backward compatibility.\n */\n source: string;\n positionSize: number; // Unsigned position size for metrics\n takeProfitPercentage?: number; // Take profit percentage from entry\n stopLossPercentage?: number; // Stop loss percentage from entry\n isEditingExistingPosition?: boolean; // true = editing existing position, false = creating for new order\n entryPrice?: number; // Entry price for percentage calculations\n\n // Entry point / discovery attribution, propagated onto risk events.\n entryPoint?: string;\n discoverySource?: string;\n perpDiscoverySource?: string;\n\n // UI surface that started the action. Omitted from the event when unset.\n environmentType?: string;\n};\n\n/** Collateral mode requested for a new order. */\nexport type MarginMode = 'isolated' | 'cross';\n\n/** Exact approved Lighter Scale preview. Other providers reject this constraint. */\nexport type ExpectedScaleLadder = Readonly<{\n prices: readonly string[];\n sizes: readonly string[];\n totalSize: string;\n totalNotional: string;\n minimumBaseSize: string;\n minimumQuoteAmount: string;\n sizeDecimals: number;\n}>;\n\n// MetaMask Perps API order parameters for PerpsController\nexport type OrderParams = {\n symbol: string; // Asset identifier (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n isBuy: boolean; // true = BUY order, false = SELL order\n size: string; // Order size as string (derived for validation, provider recalculates from usdAmount)\n orderType: OrderType; // Order type\n price?: string; // Limit price (required for limit orders)\n reduceOnly?: boolean; // Reduce-only flag\n isFullClose?: boolean; // Indicates closing 100% of position (skips $10 minimum validation)\n timeInForce?: 'GTC' | 'IOC' | 'ALO'; // Time in force for plain limit orders\n\n // USD as source of truth (hybrid approach)\n usdAmount?: string; // USD amount (primary source of truth, provider calculates size from this)\n priceAtCalculation?: number; // Price snapshot when size was calculated (for slippage validation)\n maxSlippageBps?: number; // Slippage tolerance in basis points (e.g., 100 = 1%, default if not provided)\n /**\n * @deprecated Use `maxSlippageBps` instead. Retained for one release so that\n * existing publisher consumers (extension, core) that still pass slippage as\n * a decimal (e.g. 0.03 for 3%) continue to work; the provider normalizes the\n * value to basis points when `maxSlippageBps` is absent.\n */\n slippage?: number;\n\n // Trigger placement (stop_market, stop_limit, take_profit_market, take_profit_limit).\n // Required for those order types and rejected for market/limit orders.\n triggerPrice?: string; // Price at which the resting order activates\n\n // Strategy placement (twap, scale, chase). Each group below is required for\n // its own order type and rejected on every other one, so a stray field can\n // never be silently dropped. Strategy orders carry no `price`, `triggerPrice`,\n // `timeInForce` or attached TP/SL — the strategy owns its own execution.\n twapDuration?: number; // TWAP window in whole minutes; each provider enforces its own venue's bounds\n twapRandomize?: boolean; // Randomize each TWAP suborder's size by up to ±20% (default false)\n scaleMinPrice?: string; // Lowest limit price in the scale ladder\n scaleMaxPrice?: string; // Highest limit price in the scale ladder; must exceed scaleMinPrice\n scaleNumOrders?: number; // How many limit orders to spread across the ladder (2..20)\n /**\n * How the ladder's size is weighted across its rungs. Rung weights ramp\n * linearly from 1 at `scaleMinPrice` to this value at `scaleMaxPrice`, in that\n * direction for both sides — a short does not flip it. Above 1 puts more size\n * at `scaleMaxPrice`, below 1 at `scaleMinPrice`. Omitted or exactly 1 spreads\n * the size evenly. Any finite value above 0 is accepted as given; see\n * `splitScaleSizes` for how the sizes are allocated.\n */\n scaleSkew?: number;\n /**\n * Bind Lighter placement to the displayed normalized ladder and minimums.\n * Omission retains legacy placement-time normalization with no displayed-preview guarantee.\n * This is intent evidence, not accepted-order or fill evidence.\n */\n expectedScaleLadder?: ExpectedScaleLadder;\n chaseIntervalMs?: number; // How often the chase re-reads the touch (default 15000, min 1000)\n chaseMaxDurationMs?: number; // Optional hard stop for the chase window (unbounded by default)\n chaseMaxRepricings?: number; // Optional cap on cancel/replace cycles (unbounded by default)\n chaseMaxDistanceBps?: number; // Optional directional distance from arrival price where chasing stops\n\n // Advanced order features\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n // Partial TP/SL: size of the attached TP/SL order. Omit for a TP/SL covering\n // the full order size. Must be positive and no greater than `size`.\n takeProfitSize?: string; // Quantity covered by the attached take profit\n stopLossSize?: string; // Quantity covered by the attached stop loss\n clientOrderId?: string; // Optional client-provided order ID\n /**\n * How an attached TP/SL is linked: to this order (`order`), to the resulting\n * position (`position`), or absent (`none`). Defaults to `none` without TP/SL\n * and `order` with TP/SL. Takes precedence over the deprecated `grouping`.\n */\n tpslLinkage?: TpslLinkage;\n /**\n * @deprecated Use `tpslLinkage`. This field carries HyperLiquid's own grouping\n * vocabulary; it is honoured for existing callers but a provider-agnostic\n * placement should not depend on protocol wording.\n */\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl'; // Override grouping (defaults: 'na' without TP/SL, 'normalTpsl' with TP/SL)\n currentPrice?: number; // Current market price (avoids extra API call if provided)\n leverage?: number; // Leverage to apply for the order (e.g., 10 for 10x leverage)\n /**\n * Explicit collateral mode. Requires leverage. Lighter native orders verify\n * mode execution and visibility before exposure and refuse changes with an\n * open position or resting/pending orders. HyperLiquid validates market\n * support and refuses mode changes with an open position or resting order.\n * Omit to let the provider choose: HyperLiquid keeps an open position's\n * mode and otherwise uses isolated.\n */\n marginMode?: MarginMode;\n existingPositionLeverage?: number; // Existing position leverage for validation (protocol constraint)\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n /**\n * When true, the provider returns a venue failure without logging it.\n * The caller reports that failure under its own operation. Not sent to the venue.\n * Flip sets this so Lighter does not consume the single Sentry event as `place_order`.\n */\n deferProviderErrorReport?: boolean;\n\n // Multi-provider routing (optional: defaults to active/default provider).\n providerId?: PerpsProviderType;\n};\n\nexport type ScaleOrderChild =\n | {\n state: 'resting' | 'filled' | 'canceled';\n orderId: string;\n }\n | {\n state: 'waitingForFill' | 'waitingForTrigger';\n orderId?: never;\n };\n\n/** Durable identities for one native parent plus attached protection group. */\nexport type AttachedOrderGroup = {\n groupId: string;\n providerId: PerpsProviderType;\n symbol: string;\n /** Acceptance never proves activation or the quantity protected after a partial fill. */\n submission: 'prepared' | 'unknown' | 'accepted' | 'canceled' | 'completed';\n parentClientOrderId: string;\n childClientOrderIds: string[];\n /** Exact venue IDs, when observed. Unknown identities remain absent. */\n parentOrderId?: string;\n childOrderIds?: string[];\n /** Automatic parent/child cancellation is not assumed. */\n cancellation: 'explicit-exact-owned-orders';\n /** Explicit review observations; terminal groups without a pending dispatch return local identities only. Absence is not an empty book. */\n orders?: {\n clientOrderId: string;\n orderId?: string;\n status:\n | 'unknown'\n | 'waiting'\n | 'resting'\n | 'partially-filled'\n | 'filled'\n | 'canceled'\n | 'rejected';\n filledSize?: string;\n }[];\n /** A bounded review leaves missing legs unknown rather than asserting absence. */\n historyStatus?: 'complete' | 'bounded';\n /** Parent/child references only; this does not prove automatic OCO cancellation. */\n linkage?: 'confirmed' | 'unknown';\n};\n\n/** Durable strategy inventory without fabricated venue IDs or unknown fills. */\nexport type ScaleOrderGroup = Pick<\n OrderResult,\n | 'orderId'\n | 'submittedSize'\n | 'acceptedSize'\n | 'acceptedChildren'\n | 'childOrderIds'\n | 'weightedAverageLimitPrice'\n | 'filledSize'\n> & {\n groupId: string;\n symbol: string;\n providerId: PerpsProviderType;\n accountIndex: number;\n apiKeyIndex: number;\n state: 'placing' | 'stopped' | 'unknown' | 'terminal';\n walletAddress: string;\n network: 'mainnet' | 'testnet';\n};\n\n/** Same-order edit outcome; acceptance alone remains pending. */\nexport type OrderEditObservation = {\n status: 'pending' | 'settled' | 'failed' | 'terminal';\n requestedPrice: string;\n requestedSize: string;\n observation?: {\n price: string;\n size: string;\n remainingSize: string;\n filledSize: string;\n status: Order['status'];\n };\n};\n\n/** Observed protection outcome; independent legs have no sibling cancellation guarantee. */\nexport type PositionProtectionReceipt = {\n linkage: 'single' | 'equal-quantity-oco' | 'independent';\n legs: {\n role: 'take-profit' | 'stop-loss';\n /** Absent when the caller requested the captured full-position quantity. */\n requestedSize?: string;\n normalizedSize: string;\n clientOrderId?: string;\n orderId?: string;\n status:\n | 'unknown'\n | 'resting'\n | 'partially-filled'\n | 'filled'\n | 'canceled'\n | 'rejected';\n }[];\n};\n\nexport type OrderResult = {\n /** Exact protection intent and any observed leg outcomes, including failures. */\n positionProtection?: PositionProtectionReceipt;\n /** Durable native edit outcome, including unresolved earlier intent on retry. */\n orderEdit?: OrderEditObservation;\n attachedOrderGroup?: AttachedOrderGroup;\n success?: boolean;\n /**\n * What names the placement afterwards.\n *\n * For an ordinary placement this is the exchange's order ID. For a *strategy*\n * placement it is a handle instead — a venue TWAP id, or a client-generated\n * scale-group or chase-session id — which is what `CancelOrderParams` takes\n * together with the matching `orderType` and `providerId`. Hyperliquid Scale handles\n * are encoded in venue client-order IDs and recovered from open-order reads.\n * Lighter Scale handles and unresolved rungs persist in account-scoped local\n * storage. Hyperliquid Chase handles are session-local and cannot be\n * recovered because every replacement receives a new exchange order ID.\n * Lighter retains local durable Chase handles for explicit cleanup but\n * never automatically resumes a loop after reconnect.\n * The individual exchange IDs a strategy expanded into are in\n * `childOrderIds`.\n */\n orderId?: string;\n error?: string;\n /** Stable error classification for client-side translation. */\n errorCode?: PerpsErrorCode;\n /** Optional structured data for the classified error. */\n errorDetails?: PerpsErrorDetails;\n filledSize?: string; // Amount filled\n // Full normalized size submitted to the exchange (post precision rounding,\n // USD recalculation, and any $10-minimum retry). Present only when the\n // provider reached submission.\n submittedSize?: string;\n // Normalized size of the submitted rungs that the exchange accepted. This\n // differs from `submittedSize` when a non-atomic Scale batch is partly\n // rejected.\n acceptedSize?: string;\n // Size-weighted average execution price. Present only when the result\n // includes fills.\n averagePrice?: string;\n // Size-weighted limit price of accepted Scale rungs. This is a submission\n // price, not an execution price.\n weightedAverageLimitPrice?: string;\n // Every accepted child of a Scale batch and its immediate placement state.\n // Waiting children do not carry an exchange order ID; cancel the Scale handle\n // to cancel both resting and waiting children.\n acceptedChildren?: ScaleOrderChild[];\n // Exchange IDs tied to a multi-order or recovery result. On a successful\n // strategy placement, `orderId` carries the strategy handle and these IDs\n // identify its individual children.\n //\n // For a `scale` ladder these identify only resting, cancellable rungs. Every\n // accepted rung and its state is reported in `acceptedChildren`. Scale rungs\n // are never replaced, so a resting ID stays valid after the handle is gone.\n // For a `chase` this is only the order resting at placement time — the\n // strategy cancels and re-places as the touch moves, and each replacement has\n // a new ID that is held in the session rather than reported here, so the value\n // goes stale on the first re-price. Cancel a live chase by its handle.\n //\n // When TP/SL protection cannot be fully restored, these identify the old\n // orders that survived, may still be live when reconciliation failed, or were\n // recreated; an empty array means none are known or potentially live.\n // Successful position TP/SL updates may return an exact receipt: newly\n // created venue IDs in request order (TP then SL), including children that\n // already executed or were cancelled by OCO. A successful removal returns\n // []. Absence means exact receipt identity is unavailable, not zero children.\n // These IDs establish ownership, not current resting status; re-read before\n // cancellation. They exclude the old protection cancelled by replacement.\n childOrderIds?: string[];\n providerId?: PerpsProviderType; // Multi-provider: which provider executed this order (injected by aggregator)\n /**\n * Structured record of venue state that was ALREADY committed before the\n * placement failed — e.g. a leverage change that landed before the order\n * was rejected. Present only on failure results where such state exists;\n * callers must not treat the failure as \"nothing happened\".\n */\n partialState?: {\n /** Leverage (in x) the venue already applied for this symbol. */\n leverageUpdated?: number;\n };\n};\n\n/**\n * A TP/SL protection change that could not be safely completed\n * automatically and requires an explicit new protection intent from the\n * user. Surfaced by providers with durable settlement state (Lighter).\n */\nexport type PerpsPendingManualRecovery = {\n /** Owning provider route; mandatory on aggregated recovery rows. */\n providerId?: PerpsProviderType;\n /** Issuing wallet/network scope when supplied by the provider. */\n walletAddress?: string;\n network?: string;\n /** Opaque selected source-operation identity, when explicit resolution is supported. */\n recoveryId?: string;\n symbol: string;\n /** Durable identity (address:accountIndex:apiKey:symbol). */\n settlementKey: string;\n recordedAt: number;\n /** Human-readable cause of the parked state. */\n reason: string;\n /** Whether the interrupted operation replaced or removed protection. */\n priorIntent: 'replace' | 'remove';\n /** Venue order ids still on the books when the state was parked. */\n survivingOrderIds: string[];\n /**\n * Original fixed coverage, for review only; never permission to replay.\n * A current-key journal may still belong to a running operation. Await its\n * result before selecting explicit recovery; listing does not reconcile it.\n */\n partialIntent?: {\n version: 1 | 2;\n positionSide: 'long' | 'short';\n linkage: 'single' | 'oco' | 'independent';\n legs: {\n type: 'take-profit' | 'stop-loss';\n size: string;\n clientOrderId: string;\n }[];\n };\n /** What the user should do to resolve the state. */\n actionNeeded: string;\n};\n\n/** Fresh, authoritative venue state for one issuing provider context. */\nexport type PerpsRecoveryVenueReview =\n | { status: 'unsupported'; providerId: PerpsProviderType; reason: string }\n | {\n status: 'ready';\n providerId: PerpsProviderType;\n walletAddress: string;\n network: string;\n accountIndex: number;\n positions: Position[];\n orders: Order[];\n reviewedAt: number;\n };\n\n/** Explicit successor protection for one opaque durable source obligation. */\nexport type ResolveRecoveryProtectionParams = UpdatePositionTPSLParams & {\n recoveryId: string;\n};\n\n/** Unsupported capability is distinct from a supported but unresolved intent. */\nexport type PerpsRecoveryProtectionResult =\n | (OrderResult & {\n status: 'settled' | 'unresolved';\n providerId: PerpsProviderType;\n })\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n success: false;\n error: string;\n };\n\n/**\n * A local dispatch requiring reconciliation or acknowledgment. Raw unresolved\n * dispatches include current-session in-flight submissions, have\n * acknowledgeable:false and cannot be acknowledged. Listing starts no\n * background reconciliation. Explicit reconcileRecoveredDispatches checks venue\n * evidence without signing or retrying; TP/SL-owned entries remain pending. A\n * later fenced financial action still blocks unresolved dispatches. For\n * resolved outcomes, writes stay blocked until explicitly acknowledged via\n * `acknowledgeRecoveredDispatch` (after the caller refreshes venue\n * state) — except `failed`, which is retry-safe and non-blocking.\n */\nexport type PerpsRecoveredDispatch = {\n /** Owning provider for strict review and explicit acknowledgment routing. */\n providerId?: PerpsProviderType;\n walletAddress?: string;\n network?: string;\n /** Opaque stable id for selective acknowledgment; preserve exactly, never parse. */\n recoveryId: string;\n /** Original trading-key slot when the provider has per-key recovery ledgers. */\n apiKeyIndex?: number;\n /** False for unresolved raw dispatches: acknowledgment is forbidden until reconciled. */\n acknowledgeable?: boolean;\n /** Venue transaction type of the dispatch. */\n kind: number;\n /** Human-readable operation intent. */\n intent: string;\n txHash: string | null;\n outcome: 'succeeded' | 'failed' | 'unknown';\n /** How the outcome was determined (e.g. `tx-status:2`, `rest-advance`). */\n evidence: string;\n};\n\nexport type ChaseOrderStatus =\n (typeof CHASE_ORDER_STATUS)[keyof typeof CHASE_ORDER_STATUS];\n\nexport type TwapOrderStatus =\n | 'active'\n | 'completed'\n | 'completed_underfilled'\n | 'canceled'\n | 'failed';\n\nexport type TwapOrderFill = {\n fillId: string;\n orderId: string;\n side: 'buy' | 'sell';\n price: string;\n size: string;\n fee: string;\n feeToken: string;\n builderFee?: string;\n timestamp: number;\n transactionHash: string;\n};\n\n/** Current and terminal state of one venue-native TWAP schedule. */\nexport type TwapOrder = {\n orderId: string;\n symbol: string;\n side: 'buy' | 'sell';\n size: string;\n executedSize: string;\n remainingSize: string;\n executedNotional: string;\n averagePrice?: string;\n fillProgressBps: number;\n timeProgressBps: number;\n elapsedTimeMilliseconds: number;\n durationMinutes: number;\n randomize: boolean;\n reduceOnly: boolean;\n status: TwapOrderStatus;\n startedAt: number;\n lastUpdated: number;\n error?: string;\n fills: TwapOrderFill[];\n providerId?: PerpsProviderType;\n};\n\n/**\n * Client-visible state of one emulated Chase placement.\n *\n * The handle remains stable while the exchange child ID and resting price can\n * change on every reprice. Terminal sessions are retained until provider\n * teardown so clients can observe why chasing stopped and then reconcile the\n * surviving child through the ordinary orders stream.\n */\nexport type ChaseOrder = {\n handle: string;\n symbol: string;\n side: 'buy' | 'sell';\n originalSize: string;\n remainingSize: string;\n arrivalPrice: string;\n restingPrice: string;\n restingOrderId: string | null;\n /** Adverse distance of the resting child from arrival, rounded to whole bps. */\n distanceChasedBps: number;\n /**\n * Optional adverse-touch stop, strictly between 0 and 10,000 bps.\n * The resting child may sit just inside this boundary after price-grid rounding.\n */\n maxDistanceBps?: number;\n repricings: number;\n startedAt: number;\n status: ChaseOrderStatus;\n providerId?: PerpsProviderType;\n};\n\n/** How a TWAP is cut into suborders on the venue's cadence. */\nexport type TwapSlicePreview = {\n /** Suborders over the whole running time. */\n sliceCount: number;\n /** Seconds between two suborders. */\n sliceIntervalSeconds: number;\n /** Size of one suborder, floored to the venue's size grid. */\n sizePerSlice: string;\n /** Size precision `sizePerSlice` is expressed in; pass it to `formatPositionSize`. */\n sizeDecimals: number;\n /** Smallest size the grid can express. */\n minimumSize: string;\n /** True when one suborder floors below `minimumSize`. */\n isBelowMinimumSize: boolean;\n /** Value of one suborder at the reference price, when one was given. */\n notionalPerSlice?: string;\n};\n\n/** Chase snapshots split for display, newest first. */\nexport type ChaseOrderLists = {\n /** Chases still chasing or waiting for a cancel to settle. */\n running: ChaseOrder[];\n /** Ended chases, bounded to `CHASE_ORDER_CONFIG.HistoryLimit`. */\n history: ChaseOrder[];\n};\n\n/** Whether another chase fits under the venue's cap. */\nexport type ChasePlacementCheck = {\n canPlace: boolean;\n /** Chases currently chasing, the ones the cap counts. */\n activeCount: number;\n /** Venue cap; omitted when the venue has none. */\n maxActiveSessions?: number;\n /** `PERPS_ERROR_CODES` reason when `canPlace` is false. */\n error?: string;\n};\n\n/** Rung sizes of a scale ladder sized by `sizeScaleLadder`. */\nexport type ScaleLadderSizing = {\n sizes: string[];\n totalSize: string;\n /** Sum of rung price times rung size, in USD. */\n totalNotional: string;\n};\n\n/** A warning about where a scale ladder rests relative to the market. */\nexport type ScalePriceWarning =\n | { code: 'crosses_market' | 'partially_crosses_market' }\n | { code: 'far_from_market'; distancePercent: number };\n\n/** Original durable Chase owner. Observation never grants current cleanup authority. */\nexport type PerpsChaseOrderOwner = {\n providerId: PerpsProviderType;\n walletAddress: string;\n network: 'testnet' | 'mainnet';\n accountIndex: number;\n apiKeyIndex: number;\n};\n\n/** Public transaction identity and durable dispatch phase, without signed payloads. */\nexport type PerpsChaseOrderDispatch = {\n phase: 'prepared' | 'signed' | 'attempted' | 'acknowledged' | 'failed';\n nonce?: number;\n txHash?: string;\n expiresAt?: number;\n};\n\n/** One durable child, including superseded, terminal and unresolved attempts. */\nexport type PerpsChaseOrderChild = {\n /** Exact opaque native client ID. Never infer it from the stable handle. */\n clientOrderId: string;\n size: string;\n price: string;\n quotedAt: number;\n placement: PerpsChaseOrderDispatch;\n cancellations: PerpsChaseOrderDispatch[];\n /**\n * Last exact persisted venue observation, not a fresh venue read. Absence\n * means no observation; an attempted or acknowledged dispatch stays unknown.\n */\n observation?: {\n orderId: string;\n terminal: boolean;\n filledSize: string;\n filledNotional: string;\n remainingSize: string;\n };\n};\n\n/** Select one opaque handle and explicit provider, optionally fencing its original owner. */\nexport type GetChaseOrderOwnershipParams = {\n handle: string;\n providerId: PerpsProviderType;\n owner?: PerpsChaseOrderOwner;\n};\n\n/** Reconcile only the exact already-attempted cancellation under its original owner. */\nexport type ReconcileChaseOrderCancellationParams = {\n handle: string;\n providerId: PerpsProviderType;\n owner: PerpsChaseOrderOwner;\n clientOrderId: string;\n cancellation: Pick<\n Required<PerpsChaseOrderDispatch>,\n 'nonce' | 'txHash' | 'expiresAt'\n >;\n};\n\n/** No result authorizes a new cancellation; uncertain or lost replies stay unresolved. */\nexport type ReconcileChaseOrderCancellationResult =\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n handle: string;\n reason: string;\n }\n | {\n status: 'settled' | 'unresolved';\n providerId: PerpsProviderType;\n handle: string;\n order: ChaseOrder;\n };\n\n/**\n * Validated durable local history for one exact handle. Available means every\n * locally recorded child is included, not that venue reconciliation is complete.\n * Missing records never report an available empty inventory; corrupt storage rejects.\n */\nexport type PerpsChaseOrderOwnership =\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n handle: string;\n reason: string;\n }\n | {\n status: 'unavailable';\n providerId: PerpsProviderType;\n handle: string;\n reason: 'not_found' | 'owner_mismatch';\n }\n | {\n status: 'available';\n providerId: PerpsProviderType;\n handle: string;\n owner: PerpsChaseOrderOwner;\n order: ChaseOrder;\n children: PerpsChaseOrderChild[];\n executedSize: string;\n executedNotional: string;\n lastTickAt: number;\n stopReason?: ChaseOrderStatus;\n };\n\n/** Lifecycle signal emitted when a Chase reaches its configured distance. */\nexport type ChaseOrderMaxDistanceReached = {\n handle: string;\n symbol: string;\n side: 'buy' | 'sell';\n restingOrderId: string | null;\n restingPrice: string;\n maxDistanceBps: number;\n timestamp: number;\n providerId: PerpsProviderType;\n};\n\nexport type Position = {\n symbol: string; // Asset identifier (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n size: string; // Signed position size (+ = LONG, - = SHORT)\n entryPrice: string; // Average entry price\n positionValue: string; // Total position value in USD\n unrealizedPnl: string; // Unrealized profit/loss\n marginUsed: string; // Margin currently used for this position\n /**\n * Margin the venue shows for a cross position. Hyperliquid scales cross\n * margin by `accountValue / totalMarginUsed` when cross equity is below\n * initial margin, so this is `marginUsed` times that ratio (capped at 1).\n * `marginUsed` keeps the raw venue figure. Absent for isolated positions\n * and when the provider does not report one.\n */\n displayMarginUsed?: string;\n leverage: {\n type: 'isolated' | 'cross'; // Margin type\n value?: number; // Leverage multiplier. Undefined when the venue does not report it\n rawUsd?: string; // USD amount (for isolated margin)\n };\n liquidationPrice: string | null; // Liquidation price (null if no risk)\n maxLeverage: number; // Maximum allowed leverage for this asset\n returnOnEquity: string; // ROE percentage\n /**\n * Funding payments history. Absent when the venue does not report it.\n */\n cumulativeFunding?: {\n allTime: string; // Total funding since account opening\n sinceOpen: string; // Funding since position opened\n sinceChange: string; // Funding since last size change\n };\n /**\n * Take profit price (if set).\n *\n * Summary field, resolved for the common case a client renders: when\n * `takeProfitOrders` holds exactly one order this is that order's trigger\n * price, whether or not it covers the whole position. With two or more orders\n * no single price describes them, so this falls back to the position-bound\n * trigger — clients render `takeProfitCount` there instead.\n *\n * It may also reflect a TP/SL child of a *pending* order on this market, which\n * `takeProfitOrders` and `takeProfitCount` deliberately exclude because such a\n * child protects that order rather than the position. A position can therefore\n * report a price here with an empty array and a count of `0`. Prefer\n * `takeProfitOrders` for anything that must be exact.\n */\n takeProfitPrice?: string;\n /**\n * Stop loss price (if set). Same caveat as `takeProfitPrice`.\n */\n stopLossPrice?: string;\n takeProfitCount: number; // Take profit count, how many tps can affect the position\n stopLossCount: number; // Stop loss count, how many sls can affect the position\n // Full view of the trigger orders attached to this position, including\n // quantity-scoped (partial) ones. The scalar `takeProfitPrice`/`stopLossPrice`\n // fields above only carry one price each and cannot represent partial TP/SL.\n takeProfitOrders?: PositionTriggerOrder[];\n stopLossOrders?: PositionTriggerOrder[];\n providerId?: PerpsProviderType; // Multi-provider: which provider holds this position (injected by aggregator)\n};\n\n/**\n * A trigger order attached to a position, as surfaced in position state.\n * Provider-agnostic: protocols map their own trigger representation onto this.\n */\nexport type PositionTriggerOrder = {\n orderId: string; // Exchange order ID (cancelable)\n direction: TriggerDirection; // Whether the trigger takes profit or stops loss. Always known: recovered from the trigger price against the entry when the exchange does not name the placement type\n orderType?: TriggerOrderType; // Normalized placement type. Absent when the exchange reported an unnamed trigger, whose execution mode cannot be recovered\n triggerPrice: string; // Price at which the order activates\n size: string; // Quantity this trigger closes (resolved to position size when the protocol encodes \"whole position\")\n isPartial: boolean; // true when `size` is smaller than the position size\n /**\n * Position coverage cannot be resolved yet. Use the trigger price and order\n * ID normally, but do not present the size as resolved or use the partial\n * flag until a fresh position arrives.\n */\n coverageUnavailable?: true;\n reduceOnly: boolean; // Whether the trigger can only reduce the position\n};\n\n/**\n * Provider-agnostic cross-margin summary, in USD decimal strings. Clients\n * derive account ratio, account leverage and cross margin usage from it.\n *\n * HL: crossMarginSummary + crossMaintenanceMarginUsed, summed across DEXs.\n * Lighter: the bound account's cross positions; accountValue is the total\n * balance less isolated positions' unrealized PnL.\n */\nexport type CrossMarginSummary = {\n accountValue: string;\n maintenanceMargin: string;\n marginUsed: string;\n notional: string;\n};\n\n// Using 'type' instead of 'interface' for BaseController Json compatibility\nexport type AccountState = {\n /**\n * Venue account mode when confirmed by the current account stream or read\n * (Hyperliquid `userAbstraction`). Pass it to `calculateAccountSummary`.\n */\n accountMode?: string;\n /**\n * Total USD equity on this venue — collateral + unrealized PnL. Live MTM.\n * HL Unified / Portfolio Margin: spot USDC total\n * HL Standard: marginSummary.accountValue + spot(USDC) − spot.hold\n */\n totalBalance: string;\n /**\n * Max USD that can immediately collateralize a new position on this venue,\n * with no internal transfer required.\n * HL Unified / Portfolio Margin: spot USDC total − hold\n * HL Standard: withdrawable\n */\n spendableBalance: string;\n /**\n * Max USD that can leave this venue to the user's external wallet.\n * UI reads this value without branching on provider; the provider\n * contract guarantees HL's own abstraction (Unified) or the direct\n * perps-clearinghouse (Standard) is what actually settles the\n * withdraw — no client-side spot→perps sweep is performed.\n * HL Unified / Portfolio Margin: spot USDC total − hold (HL withdraw3 draws from the unified ledger server-side)\n * HL Standard: withdrawable (perps-clearinghouse only; spot is a separate ledger)\n */\n withdrawableBalance: string;\n marginUsed: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n /**\n * Cross-margin account summary. Absent when the provider does not report\n * one for this read.\n */\n crossMarginSummary?: CrossMarginSummary;\n /**\n * Sub-accounts (Hyperliquid DEX names; `''` is the main DEX) whose state is\n * unavailable: the read failed, or on the live stream it has not arrived.\n * The totals exclude them, so the state is partial while this is present.\n */\n unavailableSubAccounts?: string[];\n /**\n * Spot USDC this venue counts as cross collateral, as a decimal string.\n * Pass it to `calculateAccountSummary` as `spotCollateral`.\n *\n * Absent while the spot state or the abstraction mode is still unknown.\n * `calculateAccountSummary` then leaves `accountRatio` and\n * `crossMarginUsage` undefined.\n *\n * `'0'` when spot is not collateral: Hyperliquid Standard (`disabled` /\n * `default`), and venues with no separate spot ledger (Lighter).\n *\n * Free spot USDC (`max(0, total − hold)`, USDC only) for Hyperliquid\n * Unified and portfolio margin.\n */\n spotCollateral?: string;\n /**\n * Per-sub-account balance breakdown (protocol-specific, optional)\n * Maps sub-account identifier to its balance details.\n *\n * Protocol examples:\n * - HyperLiquid HIP-3: '' or 'main' (main DEX), 'xyz' (HIP-3 builder DEX)\n * - dYdX: Sub-account numbers (e.g., '0', '1', '2')\n * - Other protocols: Vault IDs, pool IDs, margin account IDs, etc.\n *\n * Key: Sub-account identifier (protocol-specific string)\n * Value: Balance details for that sub-account\n */\n subAccountBreakdown?: Record<\n string,\n {\n spendableBalance: string;\n withdrawableBalance: string;\n totalBalance: string;\n }\n >;\n /**\n * Per-venue account states, keyed by provider id. Present only when the\n * state was produced by the aggregated provider; direct-provider results\n * omit it. Venue-local detail (`crossMarginSummary`,\n * `subAccountBreakdown`) stays inside each entry — the top-level totals are\n * venue-neutral and never carry venue-local collateral detail.\n */\n providerStates?: Partial<\n Record<PerpsProviderType, PerpsProviderAccountStateEntry>\n >;\n /**\n * Completeness of the top-level totals across every enabled venue.\n * Present only when the state was produced by the aggregated provider.\n */\n aggregate?: AccountAggregateMetadata;\n providerId?: PerpsProviderType; // Multi-provider: which provider this account state is from (injected by aggregator)\n};\n\n/**\n * One venue's account data inside an aggregated {@link AccountState}.\n *\n * A failed read, invalid balance snapshot, or `null` after a venue has reported\n * a snapshot is `unavailable` — never a zero balance. Before its first snapshot,\n * a stream venue is `pending`, even if it emits `null`: no verdict about its\n * balances, so its persisted entry is retained. A confirmed zero or nonexistent\n * venue account is an `available` entry whose balances are zero.\n */\nexport type PerpsProviderAccountStateEntry =\n | {\n status: 'available';\n /** The venue's own account snapshot, attributed to its provider. */\n state: AccountState;\n providerId: PerpsProviderType;\n }\n | {\n status: 'unavailable';\n /** The venue read failed; its balances contribute nothing to totals. */\n error?: string;\n providerId: PerpsProviderType;\n }\n | {\n status: 'pending';\n /** The venue has not reported on this stream yet; no verdict.\n * Stream-only: the read path always awaits every venue. */\n providerId: PerpsProviderType;\n };\n\n/**\n * Completeness metadata for an aggregated account read or stream update.\n *\n * `status: 'partial'` means the top-level totals are subtotals over\n * `availableProviders` only: at least one enabled venue contributed no data.\n * Consumers must not present partial totals as the user's complete portfolio\n * value. With no metadata at all (absent `aggregate`), the state came from a\n * single venue or a legacy producer and has no incompleteness claim.\n */\nexport type AccountAggregateMetadata = {\n status: 'complete' | 'partial';\n availableProviders: PerpsProviderType[];\n unavailableProviders: PerpsProviderType[];\n /** Stream updates only: venues that have not reported yet. They make the\n * totals partial, but unlike `unavailableProviders` there is no verdict\n * about their balances. */\n pendingProviders?: PerpsProviderType[];\n};\n\nexport type ClosePositionParams = {\n /**\n * Account that supplied a batch close target. A changed account cannot close it.\n *\n * @internal\n */\n expectedAccountId?: CaipAccountId;\n symbol: string; // Asset identifier to close (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n size?: string; // Size to close (omit for full close)\n /**\n * Close order type (default: market). Only `market` and `limit` are meaningful\n * here: `ClosePositionParams` carries no trigger price, so a trigger-based\n * close is not expressible and would be rejected during placement.\n *\n * Strategy placements are excluded at the type level rather than left to a\n * runtime rejection, because this type cannot carry any of the fields they\n * require and `closePosition` has no path that executes them. Derived with\n * `Exclude` on purpose: it shrinks as `StrategyOrderType` grows, so a strategy\n * added later is refused here automatically.\n */\n orderType?: Exclude<OrderType, StrategyOrderType>;\n price?: string; // Limit price (required for limit close)\n currentPrice?: number; // Current market price for validation\n\n // USD as source of truth (hybrid approach - same as OrderParams)\n usdAmount?: string; // USD amount (primary source of truth, provider calculates size from this)\n priceAtCalculation?: number; // Price snapshot when size was calculated (for slippage validation)\n maxSlippageBps?: number; // Slippage tolerance in basis points (e.g., 100 = 1%, default if not provided)\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n\n // Multi-provider routing (optional: defaults to active/default provider)\n providerId?: PerpsProviderType; // Optional: override active provider for routing\n\n /**\n * Optional caller snapshot for diagnostics.\n *\n * The provider always resolves the position from the current DEX WebSocket\n * slice or an HTTP read. It never uses this snapshot for order size or side.\n * If neither authoritative source answers, the close fails with\n * `PROVIDER_NOT_AVAILABLE`.\n */\n position?: Position;\n};\n\nexport type ClosePositionsParams = {\n symbols?: string[]; // Optional: specific symbols to close (omit or empty array to close all)\n closeAll?: boolean; // Explicitly close all positions\n /**\n * Explicit provider-tagged close targets. Each target is closed on its\n * named venue only, so identical symbols on different venues are\n * independent. Non-empty targets take precedence over `closeAll` and\n * `symbols`.\n */\n targets?: ClosePositionsTarget[];\n};\n\n/** One close target, tagged with the venue that holds the position. */\nexport type ClosePositionsTarget = {\n symbol: string;\n providerId: PerpsProviderType;\n};\n\n/**\n * Outcome of a batch cancel or close. `all`: every attempted item succeeded.\n * `partial`: some succeeded and some failed. `none`: nothing succeeded,\n * including when nothing matched the request. A cancel target absent from\n * discovery has no result row. An order that disappears after discovery can\n * produce an `ORDER_NO_LONGER_OPEN` failure row.\n */\nexport type BatchOperationStatus = 'all' | 'partial' | 'none';\n\n/**\n * A batch result as `PerpsController` returns it, with its derived `status`.\n */\nexport type WithBatchOperationStatus<\n Result extends ClosePositionsResult | CancelOrdersResult,\n> = Result & { status: BatchOperationStatus };\n\nexport type ClosePositionsResult = {\n /**\n * True when at least one position closed, so it is also true on partial\n * failure. Render from `status` instead.\n */\n success: boolean;\n successCount: number; // Number of positions closed successfully\n /** Failed positions, or one per failed venue when its positions are unknown. */\n failureCount: number;\n /**\n * Batch-level operation error.\n *\n * Merged multi-venue failures use BATCH_INCOMPLETE, including when another\n * venue succeeded; venue details live in `failures`. Direct-provider batches\n * preserve their snapshot/preparation or submission error. Venue text is\n * replaced with a stable code.\n */\n error?: string;\n /** Venue-level errors; `error` remains BATCH_INCOMPLETE on a merged batch. */\n failures?: { providerId: PerpsProviderType; error: string }[];\n /** Stable classification for the batch-level error. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details for the batch-level error. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n results: {\n symbol: string;\n success: boolean;\n error?: string;\n errorCode?: PerpsErrorCode;\n errorDetails?: PerpsErrorDetails;\n /** Venue that (attempted to) execute this close. */\n providerId?: PerpsProviderType;\n }[];\n};\n\nexport type UpdateMarginParams = {\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n amount: string; // Amount to adjust as string (positive = add, negative = remove)\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n};\n\nexport type MarginResult = {\n success: boolean;\n error?: string;\n /** Stable classification for a failed margin update. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type FlipPositionParams = {\n symbol: string; // Asset identifier to flip (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n position: Position; // Current position to flip\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n};\n\nexport type InitializeResult = {\n success: boolean;\n error?: string;\n /** Stable classification when initialization fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n chainId?: string;\n};\n\nexport type ReadyToTradeResult = {\n ready: boolean;\n error?: string;\n /** Stable classification when the readiness check fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n walletConnected?: boolean;\n networkSupported?: boolean;\n authenticatedAddress?: string;\n};\n\nexport type DisconnectResult = {\n success: boolean;\n error?: string;\n /** Stable classification when disconnect fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type MarketInfo = {\n name: string; // HyperLiquid: universe name (asset symbol)\n szDecimals: number; // HyperLiquid: size decimals\n /** Fixed decimal price grid, when the venue declares one. */\n priceDecimals?: number;\n maxLeverage: number; // HyperLiquid: max leverage\n marginTableId: number; // HyperLiquid: margin requirements table ID\n marginMode?: 'strictIsolated' | 'noCross'; // HyperLiquid market capability\n onlyIsolated?: true; // HyperLiquid: isolated margin only (optional, only when true)\n isDelisted?: true; // HyperLiquid: delisted status (optional, only when true)\n /**\n * HyperLiquid margin tiers for `marginTableId`, lowest notional first, as\n * `resolveHyperLiquidMarginTiers` resolves them from the venue's `meta`.\n * Omitted when the table cannot be resolved, and on lists served from the\n * Terminal market snapshot; `getOrderCapabilities` always reads them from\n * the venue.\n */\n marginTiers?: HyperLiquidMarginTier[];\n minimumOrderSize?: number; // Minimum order size in USD (protocol-specific)\n providerId?: PerpsProviderType; // Multi-provider: which provider this market comes from (injected by aggregator)\n /** Cross-venue identity from the Terminal snapshot. */\n marketKey?: string;\n /** Venue price divided by canonical market price. */\n priceScale?: number;\n};\n\n/**\n * Market data with prices for UI display\n * Protocol-agnostic interface for market information with formatted values\n */\nexport type PerpsMarketData = {\n /**\n * Stable backend market identifier supplied by the Terminal global snapshot\n * (e.g. 'btc-hyperliquid-mainnet'). Used as the key for perp-alerts API\n * calls. Only present when data originates from that endpoint; omit checks\n * against this field must guard with `?? undefined`.\n */\n id?: string;\n /**\n * Token symbol (e.g., 'BTC', 'ETH')\n */\n symbol: string;\n /**\n * Full token name (e.g., 'Bitcoin', 'Ethereum')\n */\n name: string;\n /**\n * Human-readable asset description from Terminal API metadata, when available\n * (e.g., 'The leading smart contract platform. Home to DeFi, NFTs...').\n * Only populated when using the Terminal API backend and the asset has one.\n */\n description?: string;\n /**\n * Maximum leverage available as formatted string (e.g., '40x', '25x')\n */\n maxLeverage: string;\n /**\n * Current price as formatted string (e.g., '$50,000.00')\n */\n price: string;\n /**\n * 24h price change as formatted string (e.g., '+$1,250.00', '-$850.50')\n */\n change24h: string;\n /**\n * 24h price change percentage as formatted string (e.g., '+2.5%', '-1.8%')\n */\n change24hPercent: string;\n /**\n * 5-minute mark-price change from the v4 Terminal snapshot, formatted like\n * `change24h`. `--` means the window is unavailable. Clients should hide\n * that period and suppress its alerts.\n */\n change5m?: string;\n /**\n * 5-minute percent change from the v4 Terminal snapshot. `--%` means the\n * window is unavailable.\n */\n changePercent5m?: string;\n /**\n * 1-hour mark-price change from the v4 Terminal snapshot, formatted like\n * `change24h`. `--` means the window is unavailable. Clients should hide\n * that period and suppress its alerts.\n */\n change1h?: string;\n /**\n * 1-hour percent change from the v4 Terminal snapshot. `--%` means the\n * window is unavailable.\n */\n changePercent1h?: string;\n /**\n * Trading volume as formatted string (e.g., '$1.2B', '$850M')\n */\n volume: string;\n /**\n * Open interest as formatted string (e.g., '$24.5M', '$1.2B')\n */\n openInterest?: string;\n /**\n * Next funding time in milliseconds since epoch (optional, market-specific)\n */\n nextFundingTime?: number;\n /**\n * Funding interval in hours (optional, market-specific)\n */\n fundingIntervalHours?: number;\n /**\n * Current funding rate as decimal (optional, from predictedFundings API)\n */\n fundingRate?: number;\n /**\n * Market source DEX identifier (HIP-3 support)\n * - null or undefined: Main validator DEX\n * - \"xyz\", \"abc\", etc: HIP-3 builder-deployed DEX\n */\n marketSource?: string | null;\n /**\n * Market asset type classification (optional)\n * - crypto: Cryptocurrency (default for most markets)\n * - stock: Individual stocks (HIP-3)\n * - pre-ipo: Pre-IPO assets (HIP-3)\n * - index: Market indices (HIP-3)\n * - etf: Exchange-traded funds (HIP-3)\n * - commodity: Commodity markets (HIP-3)\n * - forex: Foreign exchange pairs (HIP-3)\n */\n marketType?: MarketType;\n /**\n * Whether this is a HIP-3 market (has DEX prefix like xyz:, flx:)\n * Used to distinguish between crypto (isHip3=false) and non-crypto markets\n */\n isHip3?: boolean;\n /**\n * Whether this is a new/uncategorized market (HIP-3 markets not yet in explicit mapping)\n * Used for the \"New\" filter tab\n */\n isNewMarket?: boolean;\n /**\n * Multi-provider: which provider this market data comes from (injected by aggregator)\n */\n providerId?: PerpsProviderType;\n /**\n * Indicates this market snapshot came from the last known good cache after live fetch failure.\n */\n isStale?: boolean;\n /** Identifies an atomic Terminal summary whose price/change use mark semantics. */\n dataSource?: 'terminal-global-snapshot-mark';\n /** Source-bounded expiry for an atomic Terminal summary. */\n sourceExpiresAt?: number;\n /**\n * Searchable keywords from Terminal API metadata (e.g., ['defi', 'layer-1'])\n */\n keywords?: string[];\n /**\n * Taxonomy tags from Terminal API metadata (e.g., ['top-100', 'gaming'])\n */\n tags?: string[];\n /**\n * Market categories from Terminal API metadata (e.g., ['crypto', 'meme'])\n */\n categories?: string[];\n /** Timestamped hourly price points supplied by the atomic Terminal snapshot. */\n trend?: [timestampMs: number, price: string][];\n /**\n * Epoch ms when this market was listed on the Terminal backend.\n * Sourced from the Terminal API `listedAt` field.\n * Clients can use this to surface recently added markets (e.g. markets listed within the last 30 days).\n */\n listedAt?: number;\n /** Asset icon URL from the Terminal global snapshot. */\n iconUrl?: string;\n /**\n * Cross-venue market identity from the Terminal global snapshot. Rows from\n * different providers with the same `marketKey` are the same market.\n */\n marketKey?: string;\n /** Venue price divided by canonical market price. */\n priceScale?: number;\n /**\n * Unformatted numbers behind the display strings, which `sortMarkets` sorts\n * on. A value is absent when the venue did not report it.\n */\n numericValues?: PerpsMarketNumericValues;\n};\n\n/**\n * Unformatted values of a {@link PerpsMarketData} row: `price` and USD\n * `volume` and `openInterest`, and `change24hPercent` in percent (`2.5` for\n * 2.5%).\n */\nexport type PerpsMarketNumericValues = {\n price?: number;\n change24hPercent?: number;\n volume?: number;\n openInterest?: number;\n};\n\n/** One display row with its original venue rows, preferred venue first. */\nexport type GroupedPerpsMarket = PerpsMarketData & {\n /** Stable display identity, distinct for a backend group and a venue row. */\n rowId: string;\n venues: PerpsMarketData[];\n};\n\nexport type ToggleTestnetResult = {\n success: boolean;\n isTestnet: boolean;\n error?: string;\n /** Stable classification when the network toggle fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type AssetRoute = {\n assetId: CaipAssetId; // CAIP asset ID (e.g., \"eip155:42161/erc20:0xaf88.../default\")\n chainId: CaipChainId; // CAIP-2 chain ID where the bridge contract is located\n contractAddress: Hex; // Bridge contract address for deposits/withdrawals\n /**\n * Venue this route moves funds to/from. In aggregated mode, routes from\n * every active venue are listed; identical asset/chain routes belonging\n * to different venues are distinct entries.\n */\n providerId?: PerpsProviderType;\n constraints?: {\n minAmount?: string; // Minimum deposit/withdrawal amount\n maxAmount?: string; // Maximum deposit/withdrawal amount\n estimatedTime?: string; // Estimated processing time (formatted string - deprecated, use estimatedMinutes)\n estimatedMinutes?: number; // Estimated processing time in minutes (raw value for UI formatting)\n fees?: {\n fixed?: number; // Fixed fee amount (e.g., 1 for 1 token)\n percentage?: number; // Percentage fee (e.g., 0.05 for 0.05%)\n token?: string; // Fee token symbol (e.g., 'USDC', 'ETH')\n };\n };\n};\n\nexport type SwitchProviderResult = {\n success: boolean;\n providerId: PerpsActiveProviderMode;\n error?: string;\n};\n\n/**\n * Result of setting the default provider used by aggregated-mode routing.\n *\n * `setDefaultProvider` never re-initializes the controller or reconnects\n * any stream, so there is no asynchronous work to await.\n */\nexport type SetDefaultProviderResult = {\n success: boolean;\n defaultProvider: PerpsProviderType;\n error?: string;\n};\n\n/**\n * Temporary trade configuration captured while a placement flow is\n * interrupted. Expires after `PERPS_CONSTANTS.PendingTradeConfigurationTtlMs`.\n */\nexport type PerpsPendingTradeConfiguration = {\n amount?: string; // Order size in USD\n leverage?: number; // Leverage\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n limitPrice?: string; // Limit price (for limit orders)\n orderType?: OrderType; // Market vs limit\n reduceOnly?: boolean; // Whether the order may only reduce a position\n direction?: OrderDirection; // Long vs short\n /** When user used pay-with-token in PerpsPayRow: minimal token shape to restore selection */\n selectedPaymentToken?: PerpsSelectedPaymentToken | null;\n timestamp: number; // When the config was saved (for expiration check)\n};\n\n/**\n * Persisted per-market trade configuration: leverage, order-book grouping,\n * margin mode and the expiring pending config.\n */\nexport type PerpsTradeConfiguration = {\n leverage?: number; // Last used leverage for this market\n orderBookGrouping?: number; // Persisted price grouping for order book\n marginMode?: MarginMode; // Last Isolated/Cross pick for this market\n pendingConfig?: PerpsPendingTradeConfiguration;\n};\n\n/**\n * Trade configurations keyed by provider id and then market symbol, so a\n * value saved for one venue (for example HyperLiquid BTC) never applies to\n * the same symbol on another venue.\n */\nexport type PerpsProviderTradeConfigurations = {\n [providerId: string]: { [marketSymbol: string]: PerpsTradeConfiguration };\n};\n\nexport type CancelOrderParams = {\n orderId: string; // Order ID to cancel, or the strategy handle when orderType is a strategy type\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n /**\n * Placement type of what is being cancelled. Only the strategy types\n * (`twap`, `scale`, `chase`) change anything: each is cancelled through its\n * own path — the venue's TWAP cancel endpoint, a batch cancel of the ladder's\n * children, or stopping the chase session and cancelling its live order.\n * Omit it (or pass an ordinary order type) to cancel a single resting order,\n * which is what every existing caller does.\n */\n orderType?: OrderType;\n // Optional provider override. Omission uses active/default routing.\n providerId?: PerpsProviderType;\n // Optional tracking data for MetaMetrics events (e.g. discovery attribution)\n trackingData?: TrackingData;\n};\n\nexport type CancelOrderResult = {\n success: boolean;\n /**\n * What was cancelled, named the same way it was placed: an exchange order ID\n * for an ordinary cancel, and the strategy handle — TWAP id, scale group, or\n * chase session — when `CancelOrderParams.orderType` named one. Scale and\n * Hyperliquid chase handles can only be cancelled during the provider session\n * that created them. Lighter durable chase handles remain available for\n * explicit owned cleanup after reconnect; TWAP IDs are venue-owned.\n */\n orderId?: string;\n error?: string;\n providerId?: PerpsProviderType; // Multi-provider: source provider identifier\n /**\n * For a chase cancel whose ending the provider knows, the chase's final\n * snapshot (canceled, filled, or the ending it had already stopped with).\n * Absent when the ending is unknown, for example a child the venue reports\n * gone whose status could not be read.\n */\n chaseOrder?: ChaseOrder;\n};\n\nexport type BatchCancelOrdersParams = {\n orderId: string;\n symbol: string;\n /**\n * Venue that holds this order. Execution identity: the aggregated provider\n * groups mixed-venue batches by it and never resolves duplicate order IDs\n * or symbols across venues by falling back to the default provider.\n */\n providerId?: PerpsProviderType;\n}[];\n\nexport type CancelOrdersParams = {\n symbols?: string[]; // Optional: specific symbols (omit to cancel all orders)\n /** Legacy single-venue filter. Refused when multiple venues are registered;\n * use `orders` to identify the venue for each ID. */\n orderIds?: string[];\n /** Venue-scoped targets, matched on both fields. Takes precedence over\n * legacy filters unless `cancelAll` is true. An empty list cancels nothing. */\n orders?: { orderId: string; providerId: PerpsProviderType }[];\n cancelAll?: boolean; // Explicitly cancel all orders\n};\n\nexport type CancelOrdersResult = {\n /**\n * True when at least one order cancelled, so it is also true on partial\n * failure. Render from `status` instead.\n */\n success: boolean;\n successCount: number; // Number of orders cancelled successfully\n /** Failed cancellations plus unresolved discovery targets. For an unscoped\n * discovery failure, counts one failure per unavailable venue (not its unknown order count). */\n failureCount: number;\n /**\n * Batch-level operation error.\n *\n * Refused batches retain their code; incomplete discovery or merged venue\n * batch errors use BATCH_INCOMPLETE, even if other venues succeeded.\n */\n error?: string;\n /** Venue batch errors, matching ClosePositionsResult.failures. Discovery\n * errors remain separate because their targets have no discovered symbol. */\n failures?: { providerId: PerpsProviderType; error: string }[];\n /** Unavailable venues and, for scoped requests, their unresolved order IDs.\n * These targets have no discovered symbol and are not included in results. */\n discoveryFailures?: {\n providerId: PerpsProviderType;\n error: string;\n orderIds?: string[];\n }[];\n results: {\n orderId: string;\n symbol: string;\n success: boolean;\n error?: string;\n /** Venue that (attempted to) execute this cancel. */\n providerId?: PerpsProviderType;\n }[];\n};\n\nexport type EditOrderParams = {\n orderId: string | number; // Order ID or client order ID to modify\n newOrder: OrderParams; // New order parameters\n};\n\nexport type DepositParams = {\n amount: string; // Amount to deposit\n assetId: CaipAssetId; // Asset to deposit (required for validation)\n fromChainId?: CaipChainId; // Source chain (defaults to current network)\n toChainId?: CaipChainId; // Destination chain (defaults to HyperLiquid Arbitrum)\n recipient?: Hex; // Recipient address (defaults to selected account)\n};\n\n/** Params for depositWithConfirmation: prepares transaction for confirmation screen */\nexport type DepositWithConfirmationParams = {\n /** Optional deposit amount (display/tracking; actual amount comes from prepared transaction) */\n amount?: string;\n /** If true, uses addTransaction instead of submit to avoid navigation (e.g. deposit + place order flow) */\n placeOrder?: boolean;\n /**\n * Venue the deposit should settle on. In aggregated mode, omitting it uses\n * the routing default's route. A venue with no deposit route fails closed\n * instead of funding a different exchange.\n */\n providerId?: PerpsProviderType;\n};\n\nexport type DepositResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n};\n\n// Enhanced deposit flow state types for multi-step deposits\nexport type DepositStatus =\n | 'idle' // No deposit in progress\n | 'preparing' // Analyzing route & preparing transactions\n | 'swapping' // Converting token (e.g., ETH → USDC)\n | 'bridging' // Cross-chain transfer\n | 'depositing' // Final deposit to HyperLiquid\n | 'success' // Deposit completed successfully\n | 'error'; // Deposit failed at any step\n\nexport type DepositFlowType =\n | 'direct' // Same chain, same token (USDC on Arbitrum)\n | 'swap' // Same chain, different token (ETH → USDC)\n | 'bridge' // Different chain, same token (USDC on Ethereum → Arbitrum)\n | 'swap_bridge'; // Different chain, different token (ETH on Ethereum → USDC on Arbitrum)\n\nexport type DepositStepInfo = {\n totalSteps: number; // Total number of steps in this flow\n currentStep: number; // Current step (0-based index)\n stepNames: string[]; // Human-readable step names\n stepTxHashes?: string[]; // Transaction hashes for each completed step\n};\n\nexport type WithdrawParams = {\n amount: string; // Amount to withdraw\n destination?: Hex; // Destination address (optional, defaults to current account)\n assetId?: CaipAssetId; // Asset to withdraw (defaults to USDC)\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n environmentType?: string; // UI surface. Omitted from events when unset.\n};\n\nexport type WithdrawResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n /** Stable classification for a failed withdrawal. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n withdrawalId?: string; // Unique ID for tracking\n estimatedArrivalTime?: number; // Provider-specific arrival time\n};\n\nexport type TransferBetweenDexsParams = {\n sourceDex: string; // Source DEX name ('' = main DEX, 'xyz' = HIP-3 DEX)\n destinationDex: string; // Destination DEX name ('' = main DEX, 'xyz' = HIP-3 DEX)\n amount: string; // USDC amount to transfer\n};\n\nexport type TransferBetweenDexsResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n /** Stable classification for a failed transfer. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type GetHistoricalPortfolioParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n};\n\nexport type HistoricalPortfolioResult = {\n accountValue1dAgo: string;\n timestamp: number;\n};\n\nexport type LiveDataConfig = {\n priceThrottleMs?: number; // ms between price updates (default: 2000)\n positionThrottleMs?: number; // ms between position updates (default: 5000)\n maxUpdatesPerSecond?: number; // hard limit to prevent UI blocking\n};\n\nexport type PerpsControllerConfig = {\n /**\n * Fallback blocked regions to use when RemoteFeatureFlagController fails to fetch.\n * The fallback is set by default if defined and replaced with remote block list once available.\n */\n fallbackBlockedRegions?: string[];\n /**\n * Fallback HIP-3 equity perps master switch to use when RemoteFeatureFlagController fails to fetch.\n * Controls whether HIP-3 (builder-deployed) DEXs are enabled.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3Enabled?: boolean;\n /**\n * Fallback HIP-3 market allowlist to use when RemoteFeatureFlagController fails to fetch.\n * Empty array = enable all markets (discovery mode), non-empty = allowlist specific markets.\n * Supports wildcards: \"xyz:*\" (all xyz markets), \"xyz\" (shorthand for \"xyz:*\"), \"BTC\" (main DEX market).\n * Only applies when HIP-3 is enabled.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3AllowlistMarkets?: string[];\n /**\n * Fallback HIP-3 market blocklist to use when RemoteFeatureFlagController fails to fetch.\n * Empty array = no blocking, non-empty = block specific markets.\n * Supports wildcards: \"xyz:*\" (block all xyz markets), \"xyz\" (shorthand for \"xyz:*\"), \"BTC\" (block main DEX market).\n * Always applied regardless of HIP-3 enabled state.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3BlocklistMarkets?: string[];\n\n /**\n * Override for the maximum allowed deviation of a market's price from its oracle\n * (reference) price before it is reported as untradable (`PriceUpdate.isTradable`),\n * as a decimal fraction (e.g. `0.95` = 95%). Protocol-agnostic: each provider applies\n * its own default when omitted (HyperLiquid uses\n * `HYPERLIQUID_CONFIG.OraclePriceDeviationLimit`, `0.95`). Lets a client tune the\n * threshold without a package release.\n */\n fallbackPriceDeviationLimit?: number;\n\n /**\n * Per-provider credentials and configuration.\n * Nested by provider name so each provider's settings are self-contained\n * and new protocols can be added without polluting the top-level config.\n * Passed from the init file where `process.env.X` is babel-transformed at build time.\n */\n providerCredentials?: PerpsProviderCredentials;\n};\n\nexport type HyperLiquidCredentials = {\n /** Builder fee wallet address for testnet. Empty/omitted = uses BUILDER_FEE_CONFIG default. */\n builderAddressTestnet?: string;\n /** Builder fee wallet address for mainnet. Empty/omitted = uses BUILDER_FEE_CONFIG default. */\n builderAddressMainnet?: string;\n /** Dedicated subscription waiver builder for testnet. */\n subscriptionBuilderAddressTestnet?: string;\n /** Dedicated subscription waiver builder for mainnet. */\n subscriptionBuilderAddressMainnet?: string;\n /**\n * Resolves the agent approved for a main account on a network, or null to\n * sign with the main account (for example while the wallet is locked). Asked\n * when an L1 action (order, cancel, leverage, ...) is signed, unless the\n * account and network are bound through `PerpsController:setAgentSigner`.\n * An agent is kept until `setAgentSigner`, `clearAgentSigners` or a venue\n * rejection; null and failures are asked again at the next L1 action.\n * User-signed actions (builder fee, withdraw, ...) stay on the main account.\n * An agent whose signing throws stays in use: call\n * `PerpsController:clearAgentSigners` when its key locks.\n */\n getAgentSigner?: (\n account: PerpsAgentAccount,\n ) => Promise<PerpsAgentSigner | null>;\n /**\n * Called when the venue rejects an agent (revoked or expired, for example\n * after the user approved another agent under its name). The venue either\n * names the agent as an unknown wallet or answers the request it signed\n * with \"Must deposit before performing actions\"; the latter counts only\n * when `extraAgents` no longer lists the agent, or lists it past its\n * `validUntil` by this device's clock. That list holds named agents, so\n * approve the agent with a name. The provider\n * has dropped it, with a `setAgentSigner` binding to it, and the next L1\n * action asks `getAgentSigner` again, so re-check the approval before\n * answering. The rejected action failed with `KEYRING_LOCKED`. It gets the\n * agent's `address` as the `PerpsAgentSigner` supplied it. It is called\n * once per rejected write, so writes already in flight with the same agent\n * call it again: prompt the user at most once per agent.\n */\n onAgentRejected?: (account: PerpsAgentAccount, agentAddress: Hex) => void;\n};\n\nexport type LighterCredentials = {\n /** Explicit bounded Chase probe on the actual testnet provider; ignored on mainnet. */\n chaseTestnetProbe?: boolean;\n /**\n * How long the Lighter socket stays open after its last listener leaves,\n * in milliseconds (defaults to `LIGHTER_SOCKET_IDLE_CLOSE_MS`, 30 s).\n */\n socketIdleCloseMs?: number;\n /** Whether Lighter provider is enabled via local env var. */\n enabled?: boolean;\n /** Lighter account index override (testnet tooling). */\n accountIndexTestnet?: number;\n accountIndexMainnet?: number;\n /**\n * Preferred trading-key slot (defaults to LIGHTER_DEFAULT_API_KEY_INDEX).\n * Discovery-capable bridges may select another matching or unused slot.\n */\n apiKeyIndex?: number;\n /**\n * Client-owned Lighter signer. The client creates and persists the venue\n * key behind this bridge; Core receives only signing results and public\n * registration data, matching the injected-wallet boundary used by\n * HyperLiquid.\n *\n * Mobile uses an off-screen WebView bridge; headless clients may use an\n * in-process WASM bridge.\n * Optional — without it the Lighter provider is read-only. Lives on the\n * Lighter credentials bag, not PerpsPlatformDependencies, so the shared\n * platform surface stays venue-agnostic.\n */\n signerBridge?: LighterSignerBridge;\n /**\n * Loads the Lighter provider module. Clients whose bundler cannot load the\n * controller's own bundler-ignored import (for example Next.js) pass\n * `() => import('@metamask/perps-controller/providers/lighter')`, so only\n * clients that import that path bundle Lighter. Without it the controller\n * imports the module itself.\n */\n loadProvider?: () => Promise<{ LighterProvider: typeof LighterProvider }>;\n};\n\nexport type PerpsProviderCredentials = {\n hyperliquid?: HyperLiquidCredentials;\n lighter?: LighterCredentials;\n};\n\nexport type PriceUpdate = {\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n price: string; // Current mid price (average of best bid and ask)\n timestamp: number; // Update timestamp\n percentChange24h?: string; // 24h price change percentage\n // Order book data (only available when includeOrderBook is true)\n bestBid?: string; // Best bid price (highest price buyers are willing to pay)\n bestAsk?: string; // Best ask price (lowest price sellers are willing to accept)\n spread?: string; // Ask - Bid spread\n /**\n * The venue's mark price (HyperLiquid `markPx`, Lighter `mark_price`): the\n * price unrealized PnL, margin and liquidation use. Not the oracle price.\n */\n markPrice?: string;\n /**\n * The venue's oracle price (HyperLiquid `oraclePx`, Lighter\n * `index_price`): the reference for the limit-price deviation check\n * (`isPriceOutsideDeviationBand`) and `isTradable`.\n */\n oraclePrice?: string;\n // Market data (only available when includeMarketData is true)\n funding?: number; // Current funding rate\n openInterest?: number; // Open interest in USD\n volume24h?: number; // 24h trading volume in USD\n /**\n * Whether the market is currently tradable. Defaults to `true`.\n *\n * Some markets — most often HIP-3 builder-deployed ones — become temporarily\n * untradable when their market price drifts too far from the oracle price, in which\n * case the protocol rejects orders (HyperLiquid: \"Order price cannot be more than 95%\n * away from the reference price\"). Clients use this to proactively show a \"trading\n * unavailable\" warning instead of letting the order fail on submission.\n *\n * Computed per provider/protocol from that protocol's own rules. It is `false` only\n * when a provider determines the market is currently untradable; a provider that has no\n * such rule, or cannot assess tradability yet (e.g. before the oracle price is cached),\n * reports `true`. The value is always a concrete boolean — never `undefined`.\n */\n isTradable: boolean;\n providerId?: PerpsProviderType; // Multi-provider: price source (injected by aggregator)\n};\n\nexport type OrderFill = {\n orderId: string; // Order ID that was filled\n /**\n * Opaque execution identifier, when the venue exposes one. Compare it for\n * equality only; do not parse it.\n *\n * `orderId` identifies an *order*, not an execution: one order can produce\n * many partial fills that legitimately share it, along with timestamp, size\n * and price. Only this field distinguishes two such executions, so clients\n * deduplicating fills across transports (REST history vs. live websocket)\n * must key on it when present. Each provider builds it from the venue's\n * full trade identity, and emits the same value for one execution on every\n * transport.\n *\n * Optional because not every venue exposes an execution id. When it is\n * absent, a client has no exact identity available and must fall back to\n * matching on fill content, which cannot be exact.\n *\n * Unique within a provider, not across providers: under aggregation two\n * venues can mint the same id independently, so the dedupe key is\n * `(providerId, fillId)` when fills from several providers share one list.\n *\n * Sources: HyperLiquid `coin`, `time` and `tid` (the venue documents\n * `(block_time, coin, tid)` as trade identity; `tid` alone is a 50-bit\n * hash), Lighter `tradeId`.\n */\n fillId?: string;\n symbol: string; // Asset symbol\n side: string; // Normalized order side ('buy' or 'sell')\n size: string; // Fill size\n price: string; // Fill price\n /** Realized PnL reported by the venue; absent means unknown, never zero. */\n pnl?: string;\n direction: string; // Direction of the fill\n fee: string; // Fee paid\n feeToken: string; // Fee token symbol\n timestamp: number; // Fill timestamp\n startPosition?: string; // Start position\n success?: boolean; // Whether the order was filled successfully\n liquidation?: {\n liquidatedUser?: string; // Address of the liquidated user. liquidatedUser isn't always the current user. It can also mean the fill filled another user's liquidation.\n markPx: string; // Mark price at liquidation\n method: string; // Liquidation method (e.g., 'market')\n };\n orderType?: 'take_profit' | 'stop_loss' | 'liquidation' | 'regular';\n detailedOrderType?: string; // Original order type from exchange\n providerId?: PerpsProviderType; // Multi-provider: which provider this fill occurred on (injected by aggregator)\n};\n\n// Parameter interfaces - all fully optional for better UX\nexport type CheckEligibilityParams = {\n blockedRegions: string[]; // List of blocked region codes (e.g., ['US', 'CN'])\n geoLocation: string; // User's geolocation from GeolocationController\n};\n\nexport type GetPositionsParams = {\n /**\n * Skip protection lookup for reads that only need position data.\n *\n * @internal\n */\n includeProtection?: boolean;\n /** Reject unavailable discovery instead of returning an empty position list. */\n throwOnUnavailable?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Optional: include historical positions\n skipCache?: boolean; // Optional: bypass WebSocket cache and force API call (default: false)\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n userAddress?: string; // Optional: required when standalone is true - user address to query positions for\n};\n\nexport type GetAccountStateParams = {\n /**\n * Defaults to the selected account. Providers that cannot query another\n * wallet reject unsupported scopes rather than returning the selected\n * wallet's balance, even when `throwOnUnavailable` is false.\n */\n accountId?: CaipAccountId;\n source?: string; // Optional: source of the call for tracing (e.g., 'health_check', 'initial_connection')\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n /** Required for standalone reads. Unsupported wallet scopes reject as above. */\n userAddress?: string;\n /**\n * Hyperliquid rejects the account read when any DEX or spot clearinghouse\n * read fails. Without this option it can return partial DEX totals.\n * Lighter rejects failed balance reads with or without this option.\n * Ordinary Lighter read failures throw `ACCOUNT_STATE_FAILED` with a cause.\n * Malformed payloads and capability errors propagate. Superseded sessions\n * throw `PROVIDER_LIFECYCLE_STALE`. A confirmed absent Lighter account reads\n * empty. An unavailable cross-margin summary does not invalidate balances.\n */\n throwOnUnavailable?: boolean;\n};\n\nexport type GetUserDataSnapshotParams = {\n userAddress: string;\n identity: {\n provider: 'hyperliquid';\n network: 'mainnet' | 'testnet';\n hip3ConfigVersion: number;\n dexes: string[];\n };\n};\n\nexport type PerpsUserDataSnapshot = {\n positions: Position[];\n orders: Order[];\n accountState: AccountState;\n identity: GetUserDataSnapshotParams['identity'] & { address: string };\n};\n\nexport type GetOrderFillsParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n user?: Hex; // Optional: user address (defaults to selected account)\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n aggregateByTime?: boolean; // Optional: aggregate by time\n};\n\n/**\n * Parameters for getOrFetchFills - optimized cache-first fill retrieval.\n * Subset of GetOrderFillsParams for cache filtering.\n */\nexport type GetOrFetchFillsParams = {\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n symbol?: string; // Optional: filter by symbol\n};\n\nexport type GetOrdersParams = {\n /** Reject unavailable open-order discovery instead of returning an empty list.\n * Strict reads throw OrderDiscoveryError carrying any successfully fetched orders. */\n throwOnUnavailable?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n offset?: number; // Optional: offset for pagination\n skipCache?: boolean; // Optional: bypass WebSocket cache and force API call (default: false)\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n userAddress?: string; // Optional: required when standalone is true - user address to query orders for\n};\n\n/**\n * Options for cache-aware provider read calls (getOrders, getOrderFills, etc.).\n * Provider-agnostic: providers without inner caches can ignore; providers that\n * cache at the service layer (e.g. HyperLiquid) must honor forceRefresh.\n */\nexport type PerpsReadOptions = {\n /** Bypass any provider-internal cache. Used for user-initiated refresh (pull-to-refresh). */\n forceRefresh?: boolean;\n};\n\nexport type GetFundingParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n offset?: number; // Optional: offset for pagination\n};\n\nexport type GetSupportedPathsParams = {\n isTestnet?: boolean; // Optional: override current testnet state\n assetId?: CaipAssetId; // Optional: filter by specific asset\n symbol?: string; // Optional: filter by asset symbol (e.g., 'USDC')\n chainId?: CaipChainId; // Optional: filter by chain (CAIP-2 format)\n};\n\n/** Placeholder for future filter/pagination params (e.g., validated, chain). Empty today so the API signature is stable. */\nexport type GetAvailableDexsParams = Record<string, never>;\n\n/** Field to sort markets by. */\nexport type SortField =\n | 'volume'\n | 'priceChange'\n | 'fundingRate'\n | 'openInterest';\n\n/**\n * Field `sortMarkets` sorts on: a {@link SortField}, the current price, or the\n * market name.\n */\nexport type MarketSortField = SortField | 'price' | 'name';\n\n/** Direction for market sorting. */\nexport type SortDirection = 'asc' | 'desc';\n\nexport type GetMarketsParams = {\n symbols?: string[]; // Optional symbol filter (e.g., ['BTC', 'xyz:XYZ100'])\n dex?: string; // HyperLiquid HIP-3: DEX name (empty string '' or undefined for main DEX). Other protocols: ignored.\n skipFilters?: boolean; // Skip market filtering (both allowlist and blocklist, default: false). When true, returns all markets without filtering.\n standalone?: boolean; // Lightweight mode: skip full initialization, only fetch market metadata (no wallet/WebSocket needed). Only main DEX markets returned. Use for discovery use cases like checking if a perps market exists.\n useTerminalApi?: boolean; // When true, enrich provider data from the legacy Terminal market endpoint.\n requireComplete?: boolean; // Reject when part of the venue's list could not be read, instead of leaving it out. Providers that read the list in one request ignore it.\n skipCache?: boolean; // Read the venue's market metadata afresh and refresh the provider's session cache with it. Providers without a metadata cache ignore it.\n};\n\n/**\n * Parameters for {@link PerpsController.getMarketDataWithPrices}.\n * Extends the base market-fetch params with optional category filtering,\n * sorting, and pagination that are applied as post-processing.\n */\nexport type GetMarketDataWithPricesParams = {\n standalone?: boolean; // Lightweight mode: see GetMarketsParams.standalone\n categories?: MarketTypeFilter[]; // Filter to markets matching any of these categories; omit for all markets\n excludeSymbols?: string[]; // Symbols to exclude from results (e.g. the currently viewed market)\n sortBy?: MarketSortField; // Sort results by this field (see sortMarkets)\n direction?: SortDirection; // Sort direction (default: desc)\n limit?: number; // Maximum number of results to return\n useTerminalApi?: boolean; // When true, enrich provider data from the legacy Terminal market endpoint.\n};\n\nexport type SubscribePricesParams = {\n symbols: string[];\n callback: (prices: PriceUpdate[]) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n includeOrderBook?: boolean; // Optional: include bid/ask data from L2 book\n includeMarketData?: boolean; // Optional: include funding, open interest, volume data\n};\n\nexport type SubscribePositionsParams = {\n /** The completeness flag is true for deliveries from the opt-in Hyperliquid stream. */\n callback: (positions: Position[], completeSnapshot?: boolean) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n /** Direct Hyperliquid only. Wait for all configured DEXs to publish positions for this wallet and connection. */\n includeSnapshotStatus?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Future: include historical data\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOrderFillsParams = {\n /**\n * Reports detectable setup failures without asserting an empty account. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error, sourceProviderId?: PerpsProviderType) => void;\n callback: (\n fills: OrderFill[],\n isSnapshot?: boolean,\n sourceProviderId?: PerpsProviderType,\n ) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n since?: number; // Future: only fills after timestamp\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOrdersParams = {\n /**\n * Reports detectable setup failures without asserting an empty account. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error, sourceProviderId?: PerpsProviderType) => void;\n /** The completeness flag is true for deliveries from the opt-in Hyperliquid stream. */\n callback: (\n orders: Order[],\n sourceProviderId?: PerpsProviderType,\n completeSnapshot?: boolean,\n ) => void;\n /** Direct Hyperliquid only. Wait for all configured DEXs to publish orders for this wallet and connection. */\n includeSnapshotStatus?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Optional: include filled/canceled orders\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeTwapOrdersParams = {\n /**\n * Receives current and terminal TWAP schedules, newest first — the same\n * shape `getTwapOrders()` returns, so a client can swap a poll for this\n * subscription without reshaping its state.\n *\n * Retention differs from the REST read on purpose: every active schedule is\n * always delivered, while terminal ones are bounded to the most recent 100\n * so a long-lived stream cannot accumulate an account's entire history.\n * Callers needing older terminal schedules should still read\n * `getTwapOrders()`.\n *\n * `isSnapshot` marks the venue's initial full set; later invocations carry\n * the merged result of a delta.\n */\n callback: (twapOrders: TwapOrder[], isSnapshot?: boolean) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Subscription to the merged live TWAP list. */\nexport type SubscribeLiveTwapOrdersParams = {\n /**\n * Receives every known schedule, newest first, whenever the list changes.\n * One read and the venue's pushes are merged here, with execution totals\n * raised from pushed slice fills; split the list with `partitionTwapOrders`.\n */\n callback: (twapOrders: TwapOrder[]) => void;\n /** Called when a read fails; the list keeps its last state. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Subscription to the live chase lists. */\nexport type SubscribeChaseOrderListsParams = {\n /** Receives running and history chase lists whenever they change. */\n callback: (lists: ChaseOrderLists) => void;\n /** Called when a read fails; the lists keep their last state. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * USD amount the venue lets the account commit to a new order on one market,\n * per side. It is the venue's own figure (Hyperliquid: `activeAssetData`\n * `availableToTrade`), so it reflects the market's open position, its\n * unrealized PnL, resting orders and leverage. It differs from the\n * account-wide `AccountState.spendableBalance` whenever those apply.\n */\nexport type PerpsAvailableToTrade = Readonly<{\n /** Provider that reported the value. */\n providerId: PerpsProviderType;\n /** Market the value applies to, as subscribed. */\n symbol: string;\n /** Available to open or increase a long (buy), as a decimal USD string. */\n long: string;\n /** Available to open or increase a short (sell), as a decimal USD string. */\n short: string;\n}>;\n\n/**\n * Subscription to one market's available to trade.\n *\n * The callback receives venue values only. Until the first one arrives the\n * value is unknown and clients should render a placeholder. A provider that\n * cannot read the value from its venue never invokes the callback, so the\n * value stays unknown: no provider computes an estimate.\n */\nexport type SubscribeAvailableToTradeParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n /** Optional: defaults to the selected account. */\n accountId?: CaipAccountId;\n /** Receives each venue update for the market. */\n callback: (availableToTrade: PerpsAvailableToTrade) => void;\n /**\n * Receives a failure to open the stream, or one that stops it after it\n * opened (for example a rejected resubscription). Also invalidates the old\n * venue's value when a default-routed subscription changes providers.\n * The value is unknown again.\n * Not terminal: keep the subscription, since the stream reopens by itself.\n */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeAccountParams = {\n /** Aggregated streams include completeness metadata even when account is null,\n * so consumers can distinguish pending venues from unavailable ones. */\n callback: (\n account: AccountState | null,\n aggregate?: AccountAggregateMetadata,\n ) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /**\n * Optional: emit `null` instead of a snapshot that is missing part of the\n * venue's account, such as a HyperLiquid DEX or the spot balance that has\n * not loaded. Aggregated account streams set it so an incomplete venue is\n * pending or unavailable rather than a complete balance. Callers that omit\n * it keep each venue's lenient default.\n */\n requireCompleteAccount?: boolean;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOICapsParams = {\n callback: (caps: string[]) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue.\n */\n providerId?: PerpsProviderType;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeCandlesParams = {\n symbol: string;\n interval: CandlePeriod;\n duration?: TimeDuration;\n callback: (data: CandleData) => void;\n onError?: (error: Error) => void;\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue — required when two venues\n * list the same symbol and the data must come from a specific one.\n */\n providerId?: PerpsProviderType;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * One public trade on a market (any user's), the same shape for every\n * provider. Prices and sizes are decimal strings, as in `OrderFill`.\n */\nexport type PublicTrade = {\n /**\n * Venue trade id, compared for equality only. Unique within a provider and\n * market, not across providers, so dedupe on `(providerId, symbol, id)`\n * when trades from several providers share a list.\n * Sources: Hyperliquid `coin:time:tid`, its documented trade identity\n * (`tid` alone can repeat across block times), Lighter `trade_id`.\n */\n id: string;\n /** Market symbol the trade belongs to, as the caller requested it. */\n symbol: string;\n /** Execution price. */\n price: string;\n /** Size in the base asset. */\n size: string;\n /** Side of the aggressor (taker): `buy` lifted an ask, `sell` hit a bid. */\n side: 'buy' | 'sell';\n /** Execution time, Unix milliseconds. */\n timestamp: number;\n /** Transaction hash, when the venue reports one. */\n txHash?: string;\n /** Provider whose venue reported the trade. */\n providerId: PerpsProviderType;\n};\n\nexport type GetPublicTradesParams = {\n /** Market symbol (e.g. 'BTC'), as for the other market-data reads. */\n symbol: string;\n /**\n * Maximum number of trades, newest first (default 50). Must be a positive\n * integer. Venues cap the count: Hyperliquid returns its last 10 trades\n * and Lighter at most 100.\n */\n limit?: number;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n};\n\nexport type SubscribePublicTradesParams = {\n /** Market symbol (e.g. 'BTC'), as for the other market-data streams. */\n symbol: string;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n /**\n * Receives each batch of new trades the venue pushes, newest first. Only a\n * subscription that opens the venue channel may first receive the venue's\n * recent trades; one that joins a market another subscription already\n * streams receives only new trades. Seed the list with `getPublicTrades` and\n * dedupe batches on `id`.\n */\n callback: (trades: PublicTrade[]) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * Single price level in the order book\n */\nexport type OrderBookLevel = {\n /** Price at this level */\n price: string;\n /** Size at this level (in base asset) */\n size: string;\n /** Cumulative size up to and including this level */\n total: string;\n /** Notional value in USD */\n notional: string;\n /** Cumulative notional up to and including this level */\n totalNotional: string;\n};\n\n/**\n * Full order book data with multiple price levels\n */\nexport type OrderBookData = {\n /** Bid levels (buy orders) - highest price first */\n bids: OrderBookLevel[];\n /** Ask levels (sell orders) - lowest price first */\n asks: OrderBookLevel[];\n /** Spread between best bid and best ask */\n spread: string;\n /** Spread as a percentage of mid price */\n spreadPercentage: string;\n /** Mid price (average of best bid and best ask) */\n midPrice: string;\n /** Timestamp of last update */\n lastUpdated: number;\n /** Maximum total size across all levels (for scaling depth bars) */\n maxTotal: string;\n};\n\nexport type SubscribeOrderBookParams = {\n /** Symbol to subscribe to (e.g., 'BTC', 'ETH') */\n symbol: string;\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue.\n */\n providerId?: PerpsProviderType;\n /** Number of levels to return per side (default: 10) */\n levels?: number;\n /** Price aggregation significant figures (2-5, default: 5). Higher = finer granularity */\n nSigFigs?: 2 | 3 | 4 | 5;\n /** Mantissa for aggregation when nSigFigs is 5 (2 or 5). Controls finest price increments */\n mantissa?: 2 | 5;\n /**\n * Enable fast order book updates (5 levels @ ~0.5 s cadence).\n * When omitted, Hyperliquid uses the default cadence (20 levels @ ~2 s).\n * Note: with `fast: true` the widget receives at most 5 levels per side\n * regardless of the `levels` setting.\n */\n fast?: boolean;\n /** Callback function receiving order book updates */\n callback: (orderBook: OrderBookData) => void;\n /** Callback for errors */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** A Cross order to estimate with `estimateCrossLiquidation`. */\nexport type EstimateCrossLiquidationParams = {\n /** Venue market symbol. */\n symbol: string;\n /** Order direction. */\n direction: 'long' | 'short';\n /** Order size in base units, positive. */\n size: string;\n /** Expected fill or limit price, positive. */\n entryPrice: string;\n /** Cross leverage the order sets on the market. */\n leverage: number;\n /**\n * Fee the order pays in USD, taken from the Cross collateral at the fill.\n * Omit for an estimate without the fee. A negative or non-finite fee makes\n * the estimate `unavailable` (`missing_inputs`).\n */\n feeAmountUsd?: number;\n /** Provider that would place the order when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Liquidation price of the Cross position an order would leave. Never a\n * rejection: `none` means no price liquidates it at the account's collateral;\n * `unavailable` says why there is no estimate (`missing_inputs`: an order or\n * market input is invalid or unknown, or the order closes the position;\n * `account_unknown`: the account could not be read or changed during the\n * read; `provider`: the provider or account mode has no Cross estimate).\n */\nexport type CrossLiquidationEstimate =\n | { status: 'price'; price: string }\n | { status: 'none'; reason: 'covered_by_account' }\n | {\n status: 'unavailable';\n reason: 'missing_inputs' | 'account_unknown' | 'provider';\n };\n\nexport type LiquidationPriceParams = {\n entryPrice: number;\n leverage: number;\n direction: 'long' | 'short';\n positionSize?: number; // Optional: for more accurate calculations\n marginType?: 'isolated' | 'cross'; // Optional: defaults to isolated\n asset?: string; // Optional: for asset-specific maintenance margins\n /** Provider that owns the position when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Live position fields required to project a modify. Clients may pass a full\n * {@link Position}; extra fields are ignored.\n */\nexport type PositionModifyPreviewSource = Pick<\n Position,\n | 'symbol'\n | 'size'\n | 'marginUsed'\n | 'liquidationPrice'\n | 'entryPrice'\n | 'leverage'\n | 'positionValue'\n | 'maxLeverage'\n | 'providerId'\n>;\n\n/**\n * Proposed order plus the live position it would modify.\n *\n * Isolated-margin previews model `updateLeverage` before placement: the venue\n * keeps the existing margin and the order margins its own size at\n * `leverage`. Hyperliquid Cross previews margin the whole resulting position\n * at `leverage` and price liquidation against the account's Cross collateral\n * and the maintenance of every Cross position, starting from the position the\n * account holds when it can be read.\n */\nexport type PositionModifyPreviewParams = {\n position: PositionModifyPreviewSource;\n /** Proposed order direction. */\n direction: 'long' | 'short';\n /** Proposed order size in token units. */\n size: string;\n /**\n * Expected fill price for a marketable order, or the resting limit price.\n * Increases and flips require a positive price; a reduce does not.\n * Scale, TWAP, and chase orders should pass the expected fill size and price;\n * this preview models a single fill.\n */\n price: string;\n /**\n * Leverage the provider will set on the asset before placing. Isolated:\n * the order is margined at this leverage and the existing margin is kept.\n * Below the leverage the existing margin can cover, the venue rejects the\n * change and the resulting margin and liquidation price are unavailable.\n * Cross: the whole resulting position is margined at this leverage.\n */\n leverage: number;\n reduceOnly?: boolean;\n /**\n * Estimated trading fees in USD. Deducted from isolated margin, or from\n * Cross collateral, on increases and flips. Omit when unknown: the resulting margin and\n * liquidation price of an increase or flip are then unavailable. Pass 0\n * only for a known zero fee.\n */\n feeAmountUsd?: number;\n /**\n * Explicit venue route. Aggregated providers use this, then\n * `position.providerId`, then the default provider.\n */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Why a projected value is unavailable. `covered_by_account`: no price\n * liquidates the position at the account's collateral. `missing_inputs`: an\n * input the estimate needs is unknown.\n */\nexport type PositionPreviewUnavailableReason =\n | 'covered_by_account'\n | 'missing_inputs';\n\n/**\n * Independently available numeric projection. Margin can be known when\n * liquidation cannot (missing maintenance-tier data, or no liquidation risk).\n * Hyperliquid Cross liquidation previews set `reason`; other previews omit it.\n */\nexport type PositionPreviewValue =\n | { available: true; value: number }\n | { available: false; reason?: PositionPreviewUnavailableReason };\n\nexport type PositionModifyPreviewKind = 'increase' | 'decrease' | 'flip';\n\nexport type PositionModifyPreviewCurrent = {\n margin: PositionPreviewValue;\n liquidationPrice: PositionPreviewValue;\n};\n\nexport type PositionModifyPreviewOpen = {\n status: 'open';\n kind: PositionModifyPreviewKind;\n current: PositionModifyPreviewCurrent;\n resulting: {\n direction: 'long' | 'short';\n /** Resulting token size; always > 0 for `open`. */\n size: number;\n entryPrice: number;\n /**\n * Effective isolated leverage, mark notional / resulting margin. Below the\n * selected leverage when margin kept from before a leverage rise exceeds\n * the new initial margin; the selected leverage when margin is\n * unavailable, and always for a Cross position.\n */\n leverage: number;\n margin: PositionPreviewValue;\n liquidationPrice: PositionPreviewValue;\n };\n};\n\nexport type PositionModifyPreviewFullClose = {\n status: 'full_close';\n current: PositionModifyPreviewCurrent;\n /** Direction of the position being closed. */\n resultingDirection: 'long' | 'short';\n};\n\nexport type PositionModifyPreviewUnsupported = {\n status: 'unsupported';\n /**\n * `cross_margin` comes only from `previewHyperLiquidIsolatedPositionModify`\n * given a Cross position; `previewPositionModify` projects Cross on\n * Hyperliquid.\n */\n reason: 'cross_margin' | 'provider';\n};\n\nexport type PositionModifyPreviewNone = {\n status: 'none';\n};\n\n/**\n * Read-only post-trade position projection.\n *\n * Discriminated on `status` so a non-modifying result cannot carry a\n * flip/full-close kind, and a full close cannot report a remaining size.\n */\nexport type PositionModifyPreviewResult =\n | PositionModifyPreviewNone\n | PositionModifyPreviewUnsupported\n | PositionModifyPreviewFullClose\n | PositionModifyPreviewOpen;\n\nexport type MaintenanceMarginParams = {\n asset: string;\n positionSize?: number; // Optional: for tiered margin systems\n /** Provider that owns the position when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Context used to resolve the provider that owns order capabilities.\n * `symbol` allows providers to narrow capabilities per market, while\n * `providerId` follows the same explicit-over-default routing as placement.\n */\nexport type GetOrderCapabilitiesParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/** Market and optional route whose current margin-mode lock is requested. */\nexport type GetMarginModeLockParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/** What fixes the asset's margin mode on the venue. */\nexport type MarginModeLockReason = 'position' | 'open_order';\n\n/** Reasons the current margin-mode lock cannot be reported. */\nexport type MarginModeLockUnavailableReason =\n | 'provider_unavailable'\n | 'provider_not_found'\n | 'provider_not_routable'\n | 'not_implemented';\n\n/**\n * Margin mode an asset is bound to on the venue. `locked` means an open\n * position or resting order/TWAP fixes the mode, so orders in the other mode\n * are rejected; `unlocked` means nothing currently fixes the mode. It does not\n * mean the market supports Cross: use `supportedMarginModes` from\n * `getOrderCapabilities` for that.\n */\nexport type PerpsMarginModeLock =\n | Readonly<{\n status: 'locked';\n providerId: PerpsProviderType;\n marginMode: MarginMode;\n reason: MarginModeLockReason;\n }>\n | Readonly<{ status: 'unlocked'; providerId: PerpsProviderType }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: MarginModeLockUnavailableReason;\n }>;\n\n/** Isolated position whose margin adjustment limits are requested. */\nexport type GetMarginAdjustmentLimitsParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/**\n * Why margin adjustment limits cannot be reported: no isolated position on\n * the market, an account that changed or could not be read consistently, or\n * a provider (or account mode) that cannot answer.\n */\nexport type MarginAdjustmentLimitsUnavailableReason =\n | 'no_isolated_position'\n | 'account_unknown'\n | 'provider';\n\n/**\n * Margin the venue lets an isolated position take in (`maxAdd`) and release\n * (`maxRemove`), in USD as decimal strings.\n */\nexport type MarginAdjustmentLimits =\n | { status: 'available'; maxAdd: string; maxRemove: string }\n | { status: 'unavailable'; reason: MarginAdjustmentLimitsUnavailableReason };\n\n/**\n * Stream an isolated position's margin adjustment limits. The callback\n * receives the current limits at once, then each change.\n */\nexport type SubscribeMarginAdjustmentLimitsParams =\n GetMarginAdjustmentLimitsParams & {\n /** Receives the limits, or why they are unavailable. */\n callback: (limits: MarginAdjustmentLimits) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n };\n\n/** Market (or every market, when `symbol` is omitted) whose metadata is requested. */\nexport type GetMarketMetaParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol?: string;\n providerId?: PerpsProviderType;\n};\n\n/** Venue metadata for one market, from the provider's session cache. */\nexport type PerpsMarketMeta = {\n /** Market identifier, including any routing prefix. */\n symbol: string;\n /** Hyperliquid margin tiers, ascending; null when the venue has none. */\n marginTiers: HyperLiquidMarginTier[] | null;\n isDelisted: boolean;\n maxLeverage: number;\n /** Whether the market rejects Cross margin. */\n onlyIsolated: boolean;\n};\n\n/**\n * Stream every market's metadata (margin tiers, delisting, max leverage,\n * Cross support). The callback receives the provider's current list at once,\n * then a new list when the venue's own stream shows a listing or a delisting,\n * and after a reconnect.\n */\nexport type SubscribeMarketMetaParams = {\n /** Provider whose markets are streamed; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives the full market list; never an empty list for a failed read. */\n callback: (markets: PerpsMarketMeta[]) => void;\n /** Receives a failed read; the last list stays current. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * Stream the round trip of the provider's WebSocket keepalive. The callback\n * receives the last measured value at once when there is one, then each new\n * measurement.\n */\nexport type SubscribeConnectionLatencyParams = {\n /** Provider whose connection is measured; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives each round trip in whole milliseconds. */\n callback: (latencyMs: number) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * A market's post-discount fee rates: what `calculateFees` returns for a\n * taker fill (`isMaker: false`) and a maker fill (`isMaker: true`).\n */\nexport type PerpsFeeRates = {\n /** Market the rates apply to. */\n symbol: string;\n /** The `calculateFees` result for a taker fill. */\n taker: FeeCalculationResult;\n /** The `calculateFees` result for a maker fill. */\n maker: FeeCalculationResult;\n};\n\n/**\n * Stream a market's fee rates for the selected account. The callback receives\n * one read at once, then a new read after one of the account's own fills (its\n * volume tier can change), an account switch, a Rewards change, the expiry of\n * a trading fee grant or `invalidateSubscriptionBenefits`. There is no\n * repeating timer.\n */\nexport type SubscribeFeeRatesParams = {\n /** Market, including any routing prefix. */\n symbol: string;\n /**\n * Order type both rates are priced for. Omitted, the taker rate is priced\n * as `market` and the maker rate as `limit`.\n */\n orderType?: OrderType;\n /** Provider whose fees are read; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Order amount in USD to price, as in `calculateFees`. */\n amount?: string;\n /** Receives the rates; unchanged reads are not delivered again. */\n callback: (rates: PerpsFeeRates) => void;\n /** Receives a failed read; the last rates stay current. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Told when a venue's markets may have changed; see `PerpsProvider`. */\nexport type SubscribeMarketChangesParams = {\n /** Provider whose markets are watched; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Called on each change; read the markets again. */\n callback: () => void;\n /** Receives a failure to open the venue's feed. */\n onError?: (error: Error) => void;\n};\n\n/** Told when the account's chases may have changed; see `PerpsProvider`. */\nexport type SubscribeChaseOrderChangesParams = {\n /** Called on each change; read the chases again. */\n callback: () => void;\n};\n\n/**\n * Whether an account's trading agent is valid for the venue:\n * - `not_required`: the venue, or this host, signs trades without an agent.\n * - `valid`: the venue lists the agent; `validUntil` is its expiry in epoch\n * milliseconds, or null when it does not expire.\n * - `invalid`: `no_agent` (none is set or resolved for the account),\n * `not_approved` (the venue does not list it), `expired` (listed past its\n * `validUntil` by this device's clock) or `rejected` (the venue refused a\n * request it signed).\n * - `unknown`: the account or the venue's agent list could not be read.\n */\nexport type PerpsTradingAgentValidity =\n | { status: 'not_required' }\n | { status: 'valid'; agentAddress: Hex; validUntil: number | null }\n | {\n status: 'invalid';\n reason: 'no_agent' | 'not_approved' | 'expired' | 'rejected';\n agentAddress?: Hex;\n }\n | { status: 'unknown'; reason: 'account_unknown' | 'read_failed' };\n\n/** Stream whether an account's trading agent is valid for the venue. */\nexport type SubscribeTradingAgentValidityParams = {\n /** Account to check; defaults to the selected account, following switches. */\n accountId?: CaipAccountId;\n /** Provider whose agent is checked; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives the validity; unchanged values are not delivered again. */\n callback: (validity: PerpsTradingAgentValidity) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Parameters of each `PerpsController.subscribeTo*` stream, by stream name. */\nexport type PerpsStreamParams = {\n account: SubscribeAccountParams;\n availableToTrade: SubscribeAvailableToTradeParams;\n candles: SubscribeCandlesParams;\n chaseOrderLists: SubscribeChaseOrderListsParams;\n connectionLatency: SubscribeConnectionLatencyParams;\n feeRates: SubscribeFeeRatesParams;\n liveTwapOrders: SubscribeLiveTwapOrdersParams;\n marginAdjustmentLimits: SubscribeMarginAdjustmentLimitsParams;\n marketMeta: SubscribeMarketMetaParams;\n oiCaps: SubscribeOICapsParams;\n orderBook: SubscribeOrderBookParams;\n orderFills: SubscribeOrderFillsParams;\n orders: SubscribeOrdersParams;\n positions: SubscribePositionsParams;\n prices: SubscribePricesParams;\n publicTrades: SubscribePublicTradesParams;\n tradingAgentValidity: SubscribeTradingAgentValidityParams;\n twapOrders: SubscribeTwapOrdersParams;\n};\n\n/** Name of a `PerpsController.subscribeTo*` stream. */\nexport type PerpsStreamName = keyof PerpsStreamParams;\n\n/**\n * The parameters that pick a stream's channel: the `subscribeTo*` parameters\n * without callbacks and throttle.\n */\nexport type PerpsStreamSnapshotParams<Stream extends PerpsStreamName> = Omit<\n PerpsStreamParams[Stream],\n 'callback' | 'onError' | 'onReset' | 'throttleMs'\n>;\n\n/** The arguments a stream's callback last received. */\nexport type PerpsStreamSnapshot<Stream extends PerpsStreamName> = Parameters<\n PerpsStreamParams[Stream]['callback']\n>;\n\n/** Inputs for a provider-normalized Scale price ladder preview. */\nexport type GetScalePriceLadderParams = {\n /** Market symbol, including its provider route when applicable. */\n symbol: string;\n /** Lowest raw price in the ladder. */\n minPrice: number;\n /** Highest raw price in the ladder. */\n maxPrice: number;\n /** Number of ladder rungs. */\n count: number;\n /** Optional explicit route; omitted uses the active/default provider. */\n providerId?: PerpsProviderType;\n /**\n * Optional exact base size or maximum quote budget, with a rung-size skew.\n * Providers without sizing support leave `sizingPreview` absent.\n */\n sizing?: Readonly<\n (\n | { size: string; usdAmount?: never }\n | { usdAmount: string; size?: never }\n ) & {\n skew?: number;\n }\n >;\n};\n\n/** Reasons provider-owned order capabilities are unavailable for a market. */\nexport type DirectProviderOrderCapabilitiesUnavailableReason =\n | 'provider_unavailable'\n | 'invalid_symbol'\n | 'market_not_found'\n | 'order_market_unsupported'\n | 'strategy_market_unsupported';\n\nexport type RoutedOrderCapabilitiesUnavailableReason =\n | 'provider_not_found'\n | 'provider_not_routable'\n | 'not_implemented';\n\nexport type OrderCapabilitiesUnavailableReason =\n | DirectProviderOrderCapabilitiesUnavailableReason\n | RoutedOrderCapabilitiesUnavailableReason;\n\n/**\n * Price grid a market accepts. `significant_figures` (HyperLiquid): at most\n * `maxSignificantFigures` significant figures and `maxDecimals` decimals;\n * integer prices are always valid. `fixed_decimals` (Lighter): every price is\n * a multiple of `tickSize`, which is `10^-decimals`.\n */\nexport type PerpsPricePrecision =\n | Readonly<{\n type: 'significant_figures';\n maxSignificantFigures: number;\n maxDecimals: number;\n }>\n | Readonly<{\n type: 'fixed_decimals';\n decimals: number;\n /** Decimal string, e.g. \"0.01\". */\n tickSize: string;\n }>;\n\n/**\n * Order limits the provider enforces for a market. Each optional field is\n * omitted when the venue does not report it; clients must not fall back to\n * another venue's value.\n */\nexport type PerpsOrderLimits = Readonly<{\n /** Decimals a base-asset size may carry. */\n sizeDecimals: number;\n /** Minimum value of one order in USD. */\n minOrderNotionalUsd?: number;\n /** Minimum base-asset size of one order, as a decimal string. */\n minOrderSize?: string;\n /**\n * Orders the reported placement minimums apply to. Lighter reports\n * `resting_limit_orders` even when its maker minimums are unavailable.\n * Market and IOC orders there can go down to one size step.\n * A verified full close can qualify for a minimum-order exception.\n * The venue's size grid still applies.\n */\n minimumAppliesTo?: 'all_orders' | 'resting_limit_orders';\n /** Rung count bounds of a Scale placement; present when Scale is supported. */\n scaleOrderCount?: Readonly<{ min: number; max: number }>;\n /** TWAP bounds; present when TWAP is supported. */\n twap?: Readonly<{\n minDurationMinutes: number;\n maxDurationMinutes: number;\n /** Minimum total TWAP value in USD. */\n minNotionalUsd: number;\n }>;\n /**\n * Furthest a limit price may sit from the oracle price, as a fraction\n * (0.95 = 95%): a price `p` is rejected when\n * `|p - oracle| / oracle > maxOraclePriceDeviation`, the rule\n * `isMarketTradable` also applies. Check it with\n * `isPriceOutsideDeviationBand`.\n */\n maxOraclePriceDeviation?: number;\n}>;\n\n/**\n * Venue rules for the strategies a market supports, in venue-neutral units.\n * Read them with `getStrategyRules`; a strategy absent from\n * `supportedStrategies` has no rules and is unsupported on that market.\n */\nexport type PerpsStrategyRules = Readonly<{\n twap?: Readonly<{\n /** Shortest running time the venue accepts, in whole minutes. */\n minDurationMinutes: number;\n /** Longest running time the venue accepts, in whole minutes. */\n maxDurationMinutes: number;\n /** Smallest total TWAP value the venue accepts, in USD. */\n minNotionalUsd: number;\n /** Seconds between two suborders. */\n sliceIntervalSeconds: number;\n }>;\n chase?: Readonly<{\n /** Most chases that may run at once; omitted means no venue cap. */\n maxActiveSessions?: number;\n /** Poll interval used when the caller sets none, in milliseconds. */\n defaultIntervalMs: number;\n /** Shortest poll interval accepted, in milliseconds. */\n minIntervalMs: number;\n }>;\n scale?: Readonly<{\n /** Fewest rungs a ladder may have. */\n minOrders: number;\n /** Most rungs a ladder may have. */\n maxOrders: number;\n }>;\n}>;\n\ntype ReadyPerpsOrderCapabilities = Readonly<{\n status: 'ready';\n providerId: PerpsProviderType;\n supportedStrategies: readonly StrategyOrderType[];\n /** Price grid for this market. Omitted means not reported. */\n pricePrecision?: PerpsPricePrecision;\n /** Size, value, Scale and TWAP limits. Omitted means not reported. */\n orderLimits?: PerpsOrderLimits;\n /** Venue rules for the supported strategies; omitted means unreported. */\n strategyRules?: PerpsStrategyRules;\n /**\n * Standalone stop/take-profit placements this market's provider executes.\n * Omitted means support is not reported; clients must not infer support\n * from the provider name. Attached or position TP/SL is a separate contract.\n */\n supportedTriggerOrderTypes?: readonly TriggerOrderType[];\n /**\n * Position protection mutation guarantees. Omitted means unsupported or\n * unreported. Accepted updates can still omit IDs when exact correlation\n * remains unresolved; clients must not infer identities from book changes.\n */\n positionTpsl?: Readonly<{\n supportsExpectedPosition: true;\n childOrderIds: 'request-correlated';\n takeProfitOrderType: 'take_profit_market' | 'take_profit_limit';\n stopLossOrderType: 'stop_market' | 'stop_limit';\n /** Coverage when the caller omits explicit TP/SL sizes. */\n defaultCoverage?: 'position-snapshot' | 'dynamic-position';\n /** Fixed positive quantities; omitted means support is unreported. */\n partialCoverage?: Readonly<{\n /** When reported, a single explicitly sized leg is supported. */\n single: true;\n /** Equal native OCO quantities, or independently sized sibling triggers. */\n pair: 'equal-quantity-oco' | 'independent';\n /** Explicit alternatives; absent permits only the declared default pair. */\n supportedPairs?: readonly ('equal-quantity-oco' | 'independent')[];\n /** Prior selected protection is canceled before replacement creation. */\n replacement: 'cancel-before-create';\n /** Explicit recovery ID/current intent, or the provider's existing recovery policy. */\n recovery: 'explicit-current-position-intent' | 'provider-default';\n }>;\n }>;\n\n /**\n * Margin modes the market accepts for `OrderParams.marginMode`. Omitted\n * means the provider does not report it, and clients should not offer an\n * explicit margin mode.\n */\n supportedMarginModes?: readonly MarginMode[];\n /** Why a market that reports margin modes prohibits Cross. */\n crossMarginUnavailableReason?: 'noCross' | 'strictIsolated' | 'isolatedOnly';\n /**\n * HyperLiquid margin tiers for the market, lowest notional first, read from\n * the venue's `meta` (`marginTableId` resolved against `marginTables`). Pass\n * them to the liquidation and margin estimates. Omitted when the venue does\n * not use tiers (Lighter) or the table cannot be resolved.\n */\n marginTiers?: HyperLiquidMarginTier[];\n /**\n * Most take-profit and most stop-loss legs one order can attach\n * (`OrderParams.takeProfitPrice` / `stopLossPrice`). Omitted means not\n * reported; clients must not assume another venue's limit.\n */\n attachedTpslGroupLimit?: Readonly<{\n takeProfit: number;\n stopLoss: number;\n }>;\n attachedTpsl?: Readonly<{\n submission: 'native-oto-otoco';\n childCoverage: 'venue-native-zero-size';\n partialSizes: false;\n lifecycleVerification: 'pending';\n cancellation: 'explicit-exact-owned-orders';\n }>;\n}>;\n\nexport type DirectProviderOrderCapabilities =\n | ReadyPerpsOrderCapabilities\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: DirectProviderOrderCapabilitiesUnavailableReason;\n }>;\n\nexport type PerpsOrderCapabilities =\n | ReadyPerpsOrderCapabilities\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: OrderCapabilitiesUnavailableReason;\n }>;\n\n/** Reasons a direct provider cannot produce a Scale price ladder. */\nexport type DirectProviderScalePriceLadderUnavailableReason = Exclude<\n DirectProviderOrderCapabilitiesUnavailableReason,\n 'strategy_market_unsupported' | 'order_market_unsupported'\n>;\n\n/** Reasons a provider-routed Scale price ladder cannot be produced. */\nexport type ScalePriceLadderUnavailableReason =\n | DirectProviderScalePriceLadderUnavailableReason\n | RoutedOrderCapabilitiesUnavailableReason;\n\n/** Result of provider-routed Scale price normalization. */\nexport type PerpsScalePriceLadder =\n | Readonly<{\n status: 'ready';\n providerId: PerpsProviderType;\n prices: readonly string[];\n /**\n * Exact venue-valid rung quantities when sizing is supported and requested.\n * This previews maker minimums and exposure, not account trading readiness.\n */\n sizingPreview?: Readonly<{\n sizes: readonly string[];\n totalSize: string;\n totalNotional: string;\n minimumBaseSize: string;\n minimumQuoteAmount: string;\n sizeDecimals: number;\n }>;\n }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: ScalePriceLadderUnavailableReason;\n }>;\n\nexport type FeeCalculationParams = {\n // Trigger placements are charged as their execution kind (a stop_limit pays\n // limit-order fees when it fills, a stop_market pays taker fees).\n orderType: OrderType;\n isMaker?: boolean;\n amount?: string;\n symbol: string; // Required: Asset identifier for HIP-3 fee calculation (e.g., 'BTC', 'xyz:TSLA')\n // Optional provider override. Omission uses active/default routing.\n providerId?: PerpsProviderType;\n // Read the account's venue rates again instead of a cached copy.\n skipCache?: boolean;\n};\n\nexport type FeeCalculationResult = {\n // Total fees (protocol + MetaMask)\n feeRate?: number; // Total fee rate as decimal (e.g., 0.00145 for 0.145%), undefined when unavailable\n feeAmount?: number; // Total fee amount in USD (when amount is provided)\n // Protocol-specific base fees\n protocolFeeRate?: number; // Protocol fee rate (e.g., 0.00045 for HyperLiquid taker), undefined when unavailable\n protocolFeeAmount?: number; // Protocol fee amount in USD\n\n // MetaMask builder/revenue fee\n metamaskFeeRate?: number; // MetaMask fee rate (e.g., 0.001 for 0.1%), undefined when unavailable. Already discounted: do not apply `metamaskFeeDiscountBips` to it again\n metamaskFeeAmount?: number; // MetaMask fee amount in USD\n\n /**\n * Whether this placement can carry a MetaMask builder fee at all.\n *\n * A `metamaskFeeRate` of zero is ambiguous on its own: it is what a venue or\n * order type that has no builder field reports (`false` here), and also what\n * a fully waived discount leaves behind (`true` here). Only the provider\n * knows which, so it says so rather than leaving callers to guess from the\n * number. Absent when the provider does not report a policy.\n */\n chargesMetamaskBuilderFee?: boolean;\n\n /**\n * Fee source whose rate the MetaMask fee above was priced from: the winner\n * of the unified fee resolution this quote was computed with.\n *\n * Absent when the quote was not re-priced from a resolution, e.g. a\n * placement that carries no MetaMask builder fee. `subscription` always\n * implies a reduced fee. `rewards` can win a tie with the default, so it may\n * carry a 0% discount; check `metamaskFeeRate` before presenting it as a\n * reduction.\n *\n * Describes this preview only. The submit path resolves the fee again, so\n * the order is attributed to whichever source wins at submission.\n */\n feeSource?: PerpsFeeSource;\n\n /**\n * Discount the `feeSource` winner applied, in basis points off the default\n * MetaMask builder fee (e.g. 6500 for 65% off). `0` when no reduction\n * applied: when `default` won, or when `rewards` won with a 0% discount. A\n * `feeSource` other than `default` therefore does not imply a discount; check\n * this value instead.\n *\n * Already applied: `metamaskFeeRate` is `undiscountedMetamaskFeeRate`\n * reduced by this discount and floored to the tenth of a basis point the\n * venue charges. Do not discount `metamaskFeeRate` again. The floor can make\n * the actual reduction slightly larger than this figure, so derive savings\n * amounts from the two rates.\n *\n * Absent under the same rule as `feeSource`.\n */\n metamaskFeeDiscountBips?: number;\n\n /**\n * MetaMask fee rate before `metamaskFeeDiscountBips` was applied, as a\n * decimal (e.g. 0.001 for 0.1%). Equal to `metamaskFeeRate` when no discount\n * applied. Use it to show the original fee next to the discounted one;\n * `metamaskFeeRate` is the rate the order is charged.\n *\n * Absent under the same rule as `feeSource`.\n */\n undiscountedMetamaskFeeRate?: number;\n\n // Optional detailed breakdown for transparency\n breakdown?: {\n baseFeeRate: number;\n volumeTier?: string;\n volumeDiscount?: number;\n stakingDiscount?: number;\n };\n\n /**\n * Read-only subscription fee-waiver preview, sourced from the same cached\n * benefits snapshot the fee resolver uses. Present only when the controller\n * has a subscription source wired.\n *\n * Surfacing this never mutates the cap or the cache. The rates above *are*\n * adjusted from the unified fee resolution — including this waiver when it\n * wins — so they reflect what the order will be charged rather than the\n * undiscounted builder fee. Pass `FeeCalculationParams.amount` to get the\n * rate an order of that size actually pays.\n */\n subscription?: PerpsSubscriptionFeeWaiverStatus;\n};\n\n/**\n * Usage state of the perps fee waiver on a subscription benefits snapshot.\n */\nexport type PerpsSubscriptionUsage = 'available' | 'exhausted';\n\n/**\n * Subscription benefits as returned by `GET /v1/profiles/{profileId}/benefits`.\n *\n * The perps controller never performs this request itself — the client owns the\n * Profile JWT and injects the read through\n * {@link PerpsPlatformDependencies.subscription}. Only the fields the perps fee\n * waiver depends on are modelled here.\n */\nexport type PerpsSubscriptionBenefits = {\n /** Subscription status; only `active` can pass the eligibility gate. */\n status: string;\n\n /** Perps fee waiver entitlement and its remaining allowance. */\n perpsFeeWaiver?: {\n /** Whether the plan entitles this profile to the perps fee waiver. */\n entitled: boolean;\n\n /** Backend usage state; only `available` can pass the eligibility gate. */\n usage?: PerpsSubscriptionUsage;\n\n /**\n * Set by the backend once the notional cap is crossed. Honored on the next\n * cache refresh — there is no client-held reservation to release.\n */\n exhausted?: boolean;\n\n /** Notional (USD) still covered by the waiver, for fee previews. */\n remainingNotionalUsd?: number;\n };\n};\n\n/**\n * Why the subscription fee waiver did or did not apply, plus the remaining\n * allowance for fee previews. Derived purely from the cached benefits snapshot.\n */\nexport type PerpsSubscriptionFeeWaiverStatus = {\n /** True only when every condition of the eligibility gate passed. */\n eligible: boolean;\n\n /**\n * Gate outcome:\n * - `eligible` — every condition passed\n * - `no-source` — no subscription dependency is wired\n * - `not-hydrated` — nothing cached yet; a refresh was kicked off\n * - `stale` — the cached snapshot is past the hard-stale ceiling\n * - `no-subscription` — the read succeeded but reported no subscription at\n * all (signed out, or no profile)\n * - `inactive` — subscription status is not `active`\n * - `not-entitled` — the plan does not include the perps fee waiver\n * - `exhausted` — the backend reported the notional cap as spent\n */\n reason:\n | 'eligible'\n | 'no-source'\n | 'not-hydrated'\n | 'stale'\n | 'no-subscription'\n | 'inactive'\n | 'not-entitled'\n | 'exhausted';\n\n /** Notional (USD) still covered by the waiver, when the backend reports it. */\n remainingNotionalUsd?: number;\n};\n\n/**\n * Fee source that won the unified resolver.\n *\n * `rewards` covers the account-scoped VIP and season discount. `grant` is an\n * independent route-scoped trading-fee grant supplied by RewardsController.\n */\nexport type PerpsFeeSource = 'default' | 'rewards' | 'grant' | 'subscription';\n\n/**\n * Provider route for resolving route-specific fee candidates.\n */\nexport type PerpsFeeResolverScope = {\n providerId: string;\n isTestnet: boolean;\n};\n\n/**\n * Independent RewardsController fee candidate for one exact provider route.\n */\nexport type PerpsTradingFeeGrant = PerpsFeeResolverScope & {\n /** Absolute MetaMask builder fee, in basis points. */\n feeBips: number;\n\n /** Expiry as a Unix timestamp in milliseconds. */\n expiresAt: number;\n};\n\n/**\n * Outcome of the unified fee resolver.\n */\nexport type PerpsFeeResolution = {\n /** Winning MetaMask builder fee, in basis points (lowest across sources). */\n feeBips: number;\n\n /**\n * Winning fee expressed as a discount off the default builder fee, in basis\n * points — the unit providers consume. `undefined` when no source resolved\n * (e.g. rewards state has not hydrated and no subscription waiver applies),\n * so callers do not treat it as a definitive \"no discount\" answer.\n */\n discountBips: number | undefined;\n\n /** Source that produced the winning fee. */\n source: PerpsFeeSource;\n\n /** Subscription gate outcome, always populated for observability. */\n subscription: PerpsSubscriptionFeeWaiverStatus;\n\n /**\n * How much of the order the subscription allowance covered, when the\n * subscription source won.\n *\n * `full` waives the whole MetaMask builder fee; `partial` charges the fee on\n * the share the allowance did not cover. Absent when another source won.\n */\n subscriptionWaiverKind?: 'full' | 'partial';\n\n /**\n * Order notional (USD) the subscription allowance covered, when the backend\n * bounded the allowance and the caller supplied an order notional.\n */\n subscriptionCoveredNotionalUsd?: number;\n};\n\nexport type UpdatePositionTPSLParams = {\n /**\n * Optional mutation precondition, checked against authoritative position data\n * before setup and again before protection writes. Size is signed base units.\n * A mismatch rejects the update rather than protecting a different position.\n */\n expectedPosition?: { size: string; entryPrice: string };\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n takeProfitPrice?: string; // Optional: undefined to remove\n stopLossPrice?: string; // Optional: undefined to remove\n // Partial TP/SL: quantity covered by the TP/SL order. Omit to cover the whole\n // position. When either size is provided the TP/SL orders are placed as\n // standalone reduce-only triggers, since a position-bound TP/SL cannot carry a\n // quantity.\n takeProfitSize?: string;\n stopLossSize?: string;\n /** Pair-only opt-in for partial position coverage; omission keeps the provider default. */\n partialPairLinkage?: 'equal-quantity-oco' | 'independent';\n /**\n * HyperLiquid: max slippage in basis points for a whole-position market leg. Omit\n * to use the saved `maxSlippageBps` preference, else the 10% TP/SL default.\n */\n maxSlippageBps?: number;\n // Optional tracking data for MetaMetrics events\n trackingData?: TPSLTrackingData;\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n /**\n * Optional caller snapshot for diagnostics.\n *\n * The provider always resolves the position from the current DEX WebSocket\n * slice or an HTTP read. It never uses this snapshot for trigger size or side.\n * If neither authoritative source answers, the update fails with\n * `PROVIDER_NOT_AVAILABLE`.\n */\n position?: Position;\n};\n\n/** One side of a position's protection: take profit or stop loss. */\nexport type PositionTPSLLeg = 'tp' | 'sl';\n\nexport type ReplacePositionTPSLLegParams = {\n /** Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA'). */\n symbol: string;\n /** The leg to replace. The other leg is left as it is. */\n leg: PositionTPSLLeg;\n /** New trigger price for the leg. */\n triggerPrice: string;\n /**\n * Price the leg fills at once triggered. Omit to execute at market when the\n * trigger fires.\n */\n limitPrice?: string;\n /**\n * Max slippage in basis points for a market leg (no `limitPrice`). Omit to\n * use the saved `maxSlippageBps` preference, else the 10% TP/SL default.\n */\n maxSlippageBps?: number;\n /**\n * Optional mutation precondition, checked against authoritative position data\n * before setup and again before protection writes. Size is signed base units.\n */\n expectedPosition?: { size: string; entryPrice: string };\n /** Optional tracking data for MetaMetrics events. */\n trackingData?: TPSLTrackingData;\n /** Multi-provider: optional provider override for routing. */\n providerId?: PerpsProviderType;\n};\n\nexport type Order = {\n orderId: string; // Order ID\n symbol: string; // Asset symbol (e.g., 'ETH', 'BTC')\n side: 'buy' | 'sell'; // Normalized order side\n orderType: OrderType; // Order type (market/limit)\n size: string; // Order size\n originalSize: string; // Original order size\n price: string; // Order price (for limit orders)\n filledSize: string; // Amount filled\n remainingSize: string; // Amount remaining\n status: 'open' | 'filled' | 'canceled' | 'rejected' | 'triggered' | 'queued'; // Normalized status\n timestamp: number; // Order timestamp\n lastUpdated?: number; // Last status update timestamp (optional - not provided by all APIs)\n // TODO: Consider creating separate type for OpenOrders (UI Orders) potentially if optional properties muddy up the original Order type\n takeProfitPrice?: string; // Take profit price (if set)\n stopLossPrice?: string; // Stop loss price (if set)\n stopLossOrderId?: string; // Stop loss order ID\n takeProfitOrderId?: string; // Take profit order ID\n detailedOrderType?: string; // Full order type from exchange (e.g., 'Take Profit Limit', 'Stop Market')\n isTrigger?: boolean; // Whether this is a trigger order (TP/SL)\n // Normalized trigger placement type, set for trigger orders only. `orderType`\n // above stays coarse (how the order executes) so existing consumers keep\n // their meaning; this field carries the full placement type.\n triggerOrderType?: TriggerOrderType;\n reduceOnly?: boolean; // Whether this is a reduce-only order\n isPositionTpsl?: boolean; // Whether this TP/SL is associated with the full position\n parentOrderId?: string; // Parent order ID for display-only synthetic TP/SL rows\n isSynthetic?: boolean; // Whether this order is synthetic (display-only, cancelable only when linked to a real child order ID)\n triggerPrice?: string; // Trigger condition price for trigger orders (e.g., TP/SL trigger level)\n strategyGroupId?: string; // Recoverable strategy handle shared by related venue orders\n providerId?: PerpsProviderType; // Multi-provider: which provider this order is on (injected by aggregator)\n};\n\nexport type Funding = {\n symbol: string; // Asset symbol (e.g., 'ETH', 'BTC')\n amountUsd: string; // Funding amount in USD (positive = received, negative = paid)\n rate?: string; // Funding rate applied (undefined when not available from provider)\n timestamp: number; // Funding payment timestamp\n transactionHash?: string; // Optional transaction hash\n};\n\n/**\n * A provider-owned reason that the selected account cannot submit Perps\n * actions through a route.\n */\nexport type PerpsAccountUnsupportedReason = 'multi_sig_account';\n\n/**\n * Whether the selected account can submit Perps actions through a provider.\n */\nexport type PerpsAccountSupport =\n | { isSupported: true }\n | {\n isSupported: false;\n reason: PerpsAccountUnsupportedReason;\n };\n\n/**\n * Selects the provider route whose account support should be checked.\n */\nexport type GetAccountSupportParams = {\n providerId?: PerpsProviderType;\n};\n\n/**\n * Selects the provider route whose withdrawal destination should be resolved.\n * Accepts the same optional route `withdraw` accepts.\n */\nexport type ResolveWithdrawalRouteParams = {\n providerId?: PerpsProviderType;\n};\n\n/**\n * The venue a withdrawal will sign on, or the same refusal `withdraw` returns\n * when several venues are registered and no route is named.\n */\nexport type WithdrawalRoute =\n | { status: 'resolved'; providerId: PerpsProviderType }\n | {\n status: 'route_required';\n error: Extract<PerpsErrorCode, 'PROVIDER_ROUTE_REQUIRED'>;\n };\n\nexport type PerpsProvider = {\n /** Local durable Scale inventory; unsupported providers omit the methods. */\n getScaleOrderGroups?(): Promise<ScaleOrderGroup[]>;\n /** Explicit read-only venue reconciliation, without placement replay. */\n reviewScaleOrderGroups?(params?: {\n providerId?: PerpsProviderType;\n }): Promise<ScaleOrderGroup[]>;\n\n readonly protocolId: string;\n\n /** Whether this provider routes individual requests by `providerId`. */\n readonly routesOrdersByProviderId?: boolean;\n\n /**\n * Return whether the selected account can submit actions through this\n * provider. Providers that omit this hook are treated as supported.\n */\n getAccountSupport?(\n params?: GetAccountSupportParams,\n ): Promise<PerpsAccountSupport>;\n\n /**\n * Return order capabilities for the provider/market route. Providers may\n * omit this hook; the controller then reports capabilities as unavailable.\n */\n getOrderCapabilities?(\n params: GetOrderCapabilitiesParams,\n ): Promise<PerpsOrderCapabilities>;\n\n /**\n * Return the margin mode the market is currently locked to by an open\n * position or resting order. Providers may omit this hook; the controller\n * then reports the lock as unavailable.\n *\n * @param params - Market and optional provider route.\n * @returns The current lock, or a typed unavailable result.\n */\n getMarginModeLock?(\n params: GetMarginModeLockParams,\n ): Promise<PerpsMarginModeLock>;\n\n /**\n * Stream an isolated position's margin adjustment limits from the\n * provider's live account and position streams, without venue reads.\n * The callback receives the current limits at once, then each change.\n * Providers without it are reported as `unavailable`/`provider`.\n *\n * @param params - Market, optional route, callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToMarginAdjustmentLimits?(\n params: SubscribeMarginAdjustmentLimitsParams,\n ): () => void;\n\n /**\n * Stream the round trip of the provider's WebSocket keepalive, in whole\n * milliseconds, measured on the keepalive the transport already sends.\n * Providers without one never call back.\n *\n * @param params - Callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToConnectionLatency?(\n params: SubscribeConnectionLatencyParams,\n ): () => void;\n\n /**\n * Report whether the account's trading agent is valid for the venue. The\n * callback receives one read at once, then a new value on events only: an\n * agent set or cleared, a venue rejection of the agent, and the agent's\n * `validUntil` expiry (one timeout at the deadline). Providers without it\n * have no agent step, and the controller reports `not_required`.\n *\n * @param params - Optional account and route, callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToTradingAgentValidity?(\n params: SubscribeTradingAgentValidityParams,\n ): () => void;\n\n /**\n * Return how much margin an isolated position can take in and release.\n * Providers may omit this hook; the controller then reports the limits as\n * unavailable.\n *\n * @param params - Market and optional provider route.\n * @returns The limits, or a typed unavailable result.\n */\n getMarginAdjustmentLimits?(\n params: GetMarginAdjustmentLimitsParams,\n ): Promise<MarginAdjustmentLimits>;\n\n /**\n * Normalize a Scale ladder using the selected provider's venue rules.\n *\n * @param params - Market, ladder bounds, count, optional sizing and provider route.\n * @returns Provider-normalized prices with sizingPreview when supported, or a typed unavailable result.\n * @throws When bounds or sizing violate the provider's venue rules.\n */\n getScalePriceLadder?(\n params: GetScalePriceLadderParams,\n ): Promise<PerpsScalePriceLadder>;\n\n // Unified asset and route information\n getDepositRoutes(params?: GetSupportedPathsParams): AssetRoute[]; // Assets and their deposit routes\n getWithdrawalRoutes(params?: GetSupportedPathsParams): AssetRoute[]; // Assets and their withdrawal routes\n\n // Trading operations → Redux (persisted, optimistic updates)\n placeOrder(params: OrderParams): Promise<OrderResult>;\n editOrder(params: EditOrderParams): Promise<OrderResult>;\n cancelOrder(params: CancelOrderParams): Promise<CancelOrderResult>;\n cancelOrders?(params: BatchCancelOrdersParams): Promise<CancelOrdersResult>; // Optional: batch cancel for protocols that support it\n getTwapOrders?(): Promise<TwapOrder[]>;\n /**\n * Resolve the venue account index the client enrolls for notifications.\n * Optional: only providers whose notification events are keyed by account\n * index (Lighter) implement it.\n */\n getNotificationAccountIndex?(): Promise<number>;\n /**\n * Stream TWAP lifecycle updates, with slice fills. Optional: providers\n * without a native TWAP push channel omit it.\n */\n subscribeToTwapOrders?(params: SubscribeTwapOrdersParams): () => void;\n getChaseOrders?(): Promise<ChaseOrder[]>;\n /**\n * Call back when a chase of the selected account was placed, re-priced,\n * filled or ended, so `getChaseOrders` is read on changes instead of on a\n * timer. Providers without chases omit it.\n */\n subscribeToChaseOrderChanges?(\n params: SubscribeChaseOrderChangesParams,\n ): () => void;\n /**\n * Call back when the venue's own push shows that a market was listed or\n * delisted, so `getMarkets` is read on changes instead of on a timer.\n * Providers whose stream cannot show it omit it.\n */\n subscribeToMarketChanges?(params: SubscribeMarketChangesParams): () => void;\n /** Pure local observation; no signing, transport, continuation or durable writes. */\n getChaseOrderOwnership?(\n params: GetChaseOrderOwnershipParams,\n ): Promise<PerpsChaseOrderOwnership>;\n /** Observe an exact retained cancellation without signing or dispatching a successor. */\n reconcileChaseOrderCancellation?(\n params: ReconcileChaseOrderCancellationParams,\n ): Promise<ReconcileChaseOrderCancellationResult>;\n suspendChaseOrders?(): Promise<ChaseOrder[]>;\n closePosition(params: ClosePositionParams): Promise<OrderResult>;\n closePositions?(params: ClosePositionsParams): Promise<ClosePositionsResult>; // Optional: batch close for protocols that support it\n /**\n * Discover close targets without requiring display margin.\n *\n * @internal\n */\n getClosePositionTargets?(): Promise<\n Pick<ClosePositionParams, 'symbol' | 'expectedAccountId'>[]\n >;\n updatePositionTPSL(params: UpdatePositionTPSLParams): Promise<OrderResult>;\n /**\n * Replace one TP/SL leg of a position and leave the other leg untouched. The\n * new leg protects the whole position. A provider that cannot do this from\n * its venue rejects with `TPSL_LEG_REPLACE_UNSUPPORTED` before any write;\n * callers treat a provider without this method the same way.\n */\n replacePositionTPSLLeg?(\n params: ReplacePositionTPSLLegParams,\n ): Promise<OrderResult>;\n updateMargin(params: UpdateMarginParams): Promise<MarginResult>;\n // Durable-settlement surfacing (optional: providers with durable local\n // settlement state — Lighter). Read-only listings plus selective,\n // explicit acknowledgment; never destructive read-all.\n getPendingManualRecoveries?(): Promise<PerpsPendingManualRecovery[]>;\n reviewRecoveryVenue?(params?: {\n providerId?: PerpsProviderType;\n }): Promise<PerpsRecoveryVenueReview>;\n resolveRecoveryProtection?(\n params: ResolveRecoveryProtectionParams,\n ): Promise<PerpsRecoveryProtectionResult>;\n getRecoveredDispatches?(): Promise<PerpsRecoveredDispatch[]>;\n /** Read local native attached identities; never creates, reattaches or replays orders. */\n getAttachedOrderGroups?(): Promise<AttachedOrderGroup[]>;\n /** Explicit venue review with existing registered local read authority only. */\n reviewAttachedOrderGroups?(): Promise<AttachedOrderGroup[]>;\n /** Non-financial venue checks with local persistence; no signing, retry or acknowledgment. */\n reconcileRecoveredDispatches?(): Promise<PerpsRecoveredDispatch[]>;\n acknowledgeRecoveredDispatch?(recoveryId: string): Promise<void>;\n getPositions(params?: GetPositionsParams): Promise<Position[]>;\n getAccountState(params?: GetAccountStateParams): Promise<AccountState>;\n getUserDataSnapshot?(\n params: GetUserDataSnapshotParams,\n ): Promise<PerpsUserDataSnapshot>;\n getMarkets(params?: GetMarketsParams): Promise<MarketInfo[]>;\n getMarketDataWithPrices(): Promise<PerpsMarketData[]>;\n withdraw(params: WithdrawParams): Promise<WithdrawResult>; // API operation - stays in provider\n // Note: deposit() is handled by PerpsController routing (blockchain operation)\n validateDeposit(\n params: DepositParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific deposit validation\n validateOrder(\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific order validation\n validateClosePosition(\n params: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific position close validation\n validateWithdrawal(\n params: WithdrawParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific withdrawal validation\n\n // Historical data operations\n /**\n * Historical trade fills - actual executed trades with exact prices and fees.\n * Purpose: Track what actually happened when orders were executed.\n * Example: Market long 1 ETH @ $50,000 → OrderFill with exact execution price and fees\n */\n getOrderFills(\n params?: GetOrderFillsParams,\n options?: PerpsReadOptions,\n ): Promise<OrderFill[]>;\n\n /**\n * A market's most recent public trades (every user's), newest first.\n * Optional so providers without a public trade feed can omit it.\n */\n getPublicTrades?(params: GetPublicTradesParams): Promise<PublicTrade[]>;\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 * Purpose: Prevent 429 errors during rapid market switching by reusing cached fills.\n *\n * @param params - Optional filter parameters (startTime, symbol)\n */\n getOrFetchFills(params?: GetOrFetchFillsParams): Promise<OrderFill[]>;\n\n /**\n * Get historical portfolio data\n * Purpose: Retrieve account value from previous periods for PnL tracking\n * Example: Get account value from yesterday to calculate 24h percentage change\n *\n * @param params - Optional parameters for historical portfolio retrieval\n */\n getHistoricalPortfolio(\n params?: GetHistoricalPortfolioParams,\n ): Promise<HistoricalPortfolioResult>;\n\n /**\n * Historical order lifecycle - order placement, modifications, and status changes.\n * Purpose: Track the complete journey of orders from request to completion.\n * Example: Limit buy 1 ETH @ $48,000 → Order with status 'open' → 'filled' when executed\n */\n getOrders(\n params?: GetOrdersParams,\n options?: PerpsReadOptions,\n ): Promise<Order[]>;\n\n /**\n * Currently active open orders (real-time status).\n * Purpose: Show orders that are currently open/pending execution (not historical states).\n * Different from getOrders() which returns complete historical order lifecycle.\n * Example: Shows only orders that are actually open right now in the exchange.\n */\n getOpenOrders(params?: GetOrdersParams): Promise<Order[]>;\n\n /**\n * Historical funding payments - periodic costs/rewards for holding positions.\n * Purpose: Track ongoing expenses and income from position maintenance.\n * Example: Holding long ETH position → Funding payment of -$5.00 (you pay the funding)\n */\n getFunding(\n params?: GetFundingParams,\n options?: PerpsReadOptions,\n ): Promise<Funding[]>;\n\n /**\n * Get user non-funding ledger updates (deposits, transfers, withdrawals)\n */\n getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]>;\n\n /**\n * Resolve the provider's currently active account identifier.\n * Used by the REST coalesce layer so cached payloads are account-scoped\n * even when callers omit params.accountId (the common hook path) — prevents\n * one account's data from being served after an account switch within\n * the coalesce TTL window.\n */\n getCurrentAccountId(): Promise<CaipAccountId>;\n\n /**\n * Get user history (deposits, withdrawals, transfers)\n */\n getUserHistory(params?: {\n accountId?: CaipAccountId;\n startTime?: number;\n endTime?: number;\n }): Promise<UserHistoryItem[]>;\n\n // Protocol-specific calculations\n calculateLiquidationPrice(params: LiquidationPriceParams): Promise<string>;\n calculateMaintenanceMargin(params: MaintenanceMarginParams): Promise<number>;\n getMaxLeverage(\n asset: string,\n providerId?: PerpsProviderType,\n ): Promise<number>;\n calculateFees(params: FeeCalculationParams): Promise<FeeCalculationResult>;\n /**\n * Read-only projection of the position that would remain after the proposed\n * order. Isolated-margin venues apply selected leverage to the whole\n * resulting position and use the maintenance tier at liquidation notional.\n * Hyperliquid projects Cross positions too; `reason: 'cross_margin'` is no\n * longer returned by it.\n */\n previewPositionModify(\n params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult>;\n /**\n * Liquidation price of the Cross position an order would leave, as a typed\n * result that never rejects. Optional: a provider without it is treated as\n * `{ status: 'unavailable', reason: 'provider' }`.\n */\n estimateCrossLiquidation?(\n params: EstimateCrossLiquidationParams,\n ): Promise<CrossLiquidationEstimate>;\n\n // Live data subscriptions → Direct UI (NO Redux, maximum speed)\n subscribeToPrices(params: SubscribePricesParams): () => void;\n subscribeToPositions(params: SubscribePositionsParams): () => void;\n subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void;\n subscribeToOrders(params: SubscribeOrdersParams): () => void;\n subscribeToAccount(params: SubscribeAccountParams): () => void;\n subscribeToOICaps(params: SubscribeOICapsParams): () => void;\n subscribeToCandles(params: SubscribeCandlesParams): () => void;\n subscribeToOrderBook(params: SubscribeOrderBookParams): () => void;\n /**\n * Stream a market's public trades (every user's). Optional so providers\n * without a public trade feed can omit it.\n */\n subscribeToPublicTrades?(params: SubscribePublicTradesParams): () => void;\n /**\n * Stream one market's per-side available to trade as the venue reports it.\n * Optional: a provider whose venue has no per-market value omits it, and the\n * value stays unknown (`undefined`) for clients. Never computed locally.\n */\n subscribeToAvailableToTrade?(\n params: SubscribeAvailableToTradeParams,\n ): () => void;\n\n // Live data configuration\n setLiveDataConfig(config: Partial<LiveDataConfig>): void;\n\n // Connection management\n toggleTestnet(): Promise<ToggleTestnetResult>;\n initialize(): Promise<InitializeResult>;\n isReadyToTrade(): Promise<ReadyToTradeResult>;\n /**\n * Run the provider's deferred trading setup (for example account migration,\n * builder fee, referral or venue-key registration) ahead of the first\n * order. The result is described on `PerpsController.prepareTradingWallet`.\n * Providers without such setup omit it.\n */\n prepareTradingWallet?(): Promise<ReadyToTradeResult>;\n /**\n * Forget every agent the provider resolved, so the next L1 action asks its\n * resolver again. Providers without agents omit it.\n */\n clearAgentSigners?(): void;\n disconnect(): Promise<DisconnectResult>;\n ping(timeoutMs?: number): Promise<void>; // Lightweight WebSocket health check with configurable timeout\n getWebSocketConnectionState?(): WebSocketConnectionState; // Optional: get current WebSocket connection state\n subscribeToConnectionState?(\n listener: (\n state: WebSocketConnectionState,\n reconnectionAttempt: number,\n ) => void,\n ): () => void; // Optional: subscribe to WebSocket connection state changes\n reconnect?(): Promise<void>; // Optional: manually trigger WebSocket reconnection\n /** Optional: this provider's own health. Others derive it from connection state. */\n getProviderHealth?(): PerpsProviderHealth;\n /** Optional: current health immediately, then every change. */\n subscribeToProviderHealth?(\n listener: (health: PerpsProviderHealth) => void,\n ): () => void;\n\n // Block explorer\n getBlockExplorerUrl(address?: string): string;\n\n // Fee discount context (optional - for MetaMask reward discounts)\n /**\n * Which provider a write with this route actually reaches.\n *\n * Implemented only by an aggregating provider, whose `protocolId` names the\n * aggregate rather than the route and whose reads span every active provider.\n * A single provider needs no answer: every write reaches itself.\n *\n * @param providerId - Explicit route, or undefined for the default.\n * @returns The provider id the write will be submitted through.\n */\n getWriteProviderId?(providerId?: PerpsProviderType): PerpsProviderType;\n\n /**\n * Registered execution venues for an aggregating provider. Unlike position\n * reads, this includes venues whose balances or positions are unavailable.\n *\n * @returns Every venue a close-all operation will reach.\n */\n getProviderIds?(): PerpsProviderType[];\n\n /**\n * Whether the execution venue consumes fee resolutions or discounts.\n * Direct providers may omit this; the presence of a fee setter is sufficient.\n *\n * @param providerId - Venue to check, or the default route when omitted.\n * @returns Whether resolving a fee for this venue has an effect.\n */\n supportsFeeResolution?(providerId?: PerpsProviderType): boolean;\n\n setUserFeeDiscount?(discountBips: number | undefined): void;\n /**\n * Set the full fee resolution context, including attribution source.\n *\n * @param resolution - Resolved fee, or undefined to clear it.\n * @param providerId - Venue the resolution is for. An aggregating provider\n * applies it to that venue only, so a fan-out write can price each venue on\n * its own; when omitted it applies to every venue. A single provider is its\n * only venue and may ignore it.\n */\n setUserFeeResolution?(\n resolution: PerpsFeeResolution | undefined,\n providerId?: PerpsProviderType,\n ): void;\n /**\n * Approve the dedicated subscription builder outside order submission.\n *\n * @deprecated ADR 0064 replaced the dedicated subscription builder with cloid\n * marking on the standard builder. Nothing on the order path reads this\n * approval any more; it is retained only so the previous design can be\n * restored cheaply if cloid marking does not hold up in shadow mode.\n */\n approveSubscriptionBuilderFee?(): Promise<boolean>;\n\n // HIP-3 (Builder-deployed DEXs) operations - optional for backward compatibility\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 getAvailableDexs?(params?: GetAvailableDexsParams): Promise<string[]>;\n\n /**\n * Fetch historical OHLCV candle data for a symbol.\n * Optional: only providers that support historical candles need to implement this.\n */\n fetchHistoricalCandles?(options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData>;\n};\n\n// ============================================================================\n// Multi-Provider Aggregation Types (Phase 1)\n// ============================================================================\n\n/**\n * Provider identifier type for multi-provider support.\n * Add new providers here as they are implemented.\n */\nexport type PerpsProviderType = 'hyperliquid' | 'lighter';\n\n/**\n * Active provider mode for PerpsController state.\n * - Direct providers: 'hyperliquid', 'lighter'\n * - 'aggregated': Multi-provider aggregation mode\n */\nexport type PerpsActiveProviderMode = PerpsProviderType | 'aggregated';\n\n/**\n * Aggregation mode for read operations.\n * - 'all': Aggregate data from all registered providers\n * - 'active': Only aggregate from providers with active connections\n * - 'specific': Aggregate from a specific subset of providers\n */\nexport type AggregationMode = 'all' | 'active' | 'specific';\n\n/**\n * Routing strategy for write operations.\n * Phase 1 only supports 'default_provider' - advanced strategies deferred to Phase 3.\n */\nexport type RoutingStrategy = 'default_provider';\n\n/**\n * Configuration for AggregatedPerpsProvider\n */\nexport type AggregatedProviderConfig = {\n /** Map of provider ID to provider instance */\n providers: Map<PerpsProviderType, PerpsProvider>;\n /** Default provider for write operations when providerId not specified */\n defaultProvider: PerpsProviderType;\n /** Aggregation mode for read operations (default: 'all') */\n aggregationMode?: AggregationMode;\n /** Platform dependencies for logging, metrics, etc. */\n infrastructure: PerpsPlatformDependencies;\n /** Whether the providers run on testnet; tags the errors it logs. */\n isTestnet?: boolean;\n};\n\n/**\n * Provider-specific error with context for multi-provider error handling\n */\nexport type ProviderError = {\n /** Which provider the error originated from */\n providerId: PerpsProviderType;\n /** Human-readable error message */\n message: string;\n /** Original error object if available */\n originalError?: Error;\n /** Whether the operation can be retried */\n isRetryable?: boolean;\n};\n\n/**\n * Aggregated account state combining data from multiple providers\n */\nexport type AggregatedAccountState = {\n /** Combined totals across all providers */\n total: AccountState;\n /** Per-provider breakdown */\n byProvider: Map<PerpsProviderType, AccountState>;\n};\n\n// ============================================================================\n// Injectable Dependency Interfaces\n// These interfaces enable dependency injection for platform-specific services,\n// allowing PerpsController to be moved to core without mobile-specific imports.\n// ============================================================================\n\n/**\n * Injectable logger interface for error reporting.\n * Allows core package to be platform-agnostic (mobile: Sentry, extension: different impl)\n */\nexport type PerpsLogger = {\n error(\n error: Error,\n options?: {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n },\n ): void;\n};\n\n/**\n * Analytics events specific to Perps feature.\n * These are the actual event names sent to analytics backend.\n * Values must match the corresponding MetaMetricsEvents values in mobile for compatibility.\n *\n * When migrating to core monorepo, this enum travels with PerpsController.\n */\nexport enum PerpsAnalyticsEvent {\n WithdrawalTransaction = 'Perp Withdrawal Transaction',\n TradeTransaction = 'Perp Trade Transaction',\n PositionCloseTransaction = 'Perp Position Close Transaction',\n OrderCancelTransaction = 'Perp Order Cancel Transaction',\n ScreenViewed = 'Perp Screen Viewed',\n UiInteraction = 'Perp UI Interaction',\n RiskManagement = 'Perp Risk Management',\n PerpsError = 'Perp Error',\n AccountSetup = 'Perp Account Setup',\n // New funnel + search events.\n // Names must match MetaMetrics/Mixpanel exactly; no other event names may be added.\n TransactionConsidered = 'Perp Transaction Considered',\n TradeQuoteReceived = 'Perp Trade Quote Received',\n SearchQuery = 'Perp Search Query',\n SearchResultTapped = 'Perp Search Result Tapped',\n SearchAbandoned = 'Perp Search Abandoned',\n}\n\n/**\n * UTM / discovery attribution context for Perps analytics.\n *\n * Held transiently in-memory by PerpsController (never persisted in state) and\n * merged into analytics event properties so client-originated UTM attribution\n * can be propagated onto core-emitted transaction events.\n */\nexport type PerpsAttributionContext = {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n};\n\n/**\n * Perps-specific trace names. These must match TraceName enum values in mobile.\n * When in core monorepo, this defines the valid trace names for Perps operations.\n */\nexport type PerpsTraceName =\n | 'Perps Open Position'\n | 'Perps Close Position'\n | 'Perps Deposit'\n | 'Perps Withdraw'\n | 'Perps Place Order'\n | 'Perps Edit Order'\n | 'Perps Cancel Order'\n | 'Perps Update TP/SL'\n | 'Perps Update Margin'\n | 'Perps Flip Position'\n | 'Perps Market Data Update'\n | 'Perps Order View'\n | 'Perps Tab View'\n | 'Perps Market List View'\n | 'Perps Position Details View'\n | 'Perps Adjust Margin View'\n | 'Perps Order Details View'\n | 'Perps Order Book View'\n | 'Perps Flip Position Sheet'\n | 'Perps Transactions View'\n | 'Perps Order Fills Fetch'\n | 'Perps Orders Fetch'\n | 'Perps Funding Fetch'\n | 'Perps Get Positions'\n | 'Perps Get Account State'\n | 'Perps Get Historical Portfolio'\n | 'Perps Get Markets'\n | 'Perps Get Market Data With Prices'\n | 'Perps Fetch Historical Candles'\n | 'Perps WebSocket Connected'\n | 'Perps WebSocket Disconnected'\n | 'Perps WebSocket First Positions'\n | 'Perps WebSocket First Orders'\n | 'Perps WebSocket First Account'\n | 'Perps Data Lake Report'\n | 'Perps Rewards API Call'\n | 'Perps Close Position View'\n | 'Perps Withdraw View'\n | 'Perps Connection Establishment'\n | 'Perps Account Switch Reconnection'\n | 'Perps Market Data Preload'\n | 'Perps User Data Preload';\n\n/**\n * Perps trace name constants. Values match TraceName enum in mobile.\n * When in core, these ARE the source of truth - mobile will re-export from core.\n */\nexport const PerpsTraceNames = {\n // Trading operations\n PlaceOrder: 'Perps Place Order',\n EditOrder: 'Perps Edit Order',\n CancelOrder: 'Perps Cancel Order',\n ClosePosition: 'Perps Close Position',\n UpdateTpsl: 'Perps Update TP/SL',\n UpdateMargin: 'Perps Update Margin',\n FlipPosition: 'Perps Flip Position',\n\n // Account operations\n Withdraw: 'Perps Withdraw',\n Deposit: 'Perps Deposit',\n\n // Market data\n GetPositions: 'Perps Get Positions',\n GetAccountState: 'Perps Get Account State',\n GetMarkets: 'Perps Get Markets',\n GetMarketDataWithPrices: 'Perps Get Market Data With Prices',\n OrderFillsFetch: 'Perps Order Fills Fetch',\n OrdersFetch: 'Perps Orders Fetch',\n FundingFetch: 'Perps Funding Fetch',\n GetHistoricalPortfolio: 'Perps Get Historical Portfolio',\n FetchHistoricalCandles: 'Perps Fetch Historical Candles',\n\n // Data lake\n DataLakeReport: 'Perps Data Lake Report',\n\n // WebSocket\n WebsocketConnected: 'Perps WebSocket Connected',\n WebsocketDisconnected: 'Perps WebSocket Disconnected',\n WebsocketFirstPositions: 'Perps WebSocket First Positions',\n WebsocketFirstOrders: 'Perps WebSocket First Orders',\n WebsocketFirstAccount: 'Perps WebSocket First Account',\n\n // Other\n RewardsApiCall: 'Perps Rewards API Call',\n ConnectionEstablishment: 'Perps Connection Establishment',\n AccountSwitchReconnection: 'Perps Account Switch Reconnection',\n MarketDataPreload: 'Perps Market Data Preload',\n UserDataPreload: 'Perps User Data Preload',\n} as const satisfies Record<string, PerpsTraceName>;\n\n/**\n * Perps trace operation constants. Values match TraceOperation enum in mobile.\n * These categorize traces by type of operation for Sentry/observability filtering.\n */\nexport const PerpsTraceOperations = {\n Operation: 'perps.operation',\n OrderSubmission: 'perps.order_submission',\n PositionManagement: 'perps.position_management',\n} as const;\n\n/**\n * Values allowed in trace data/tags. Matches Sentry's TraceValue type.\n */\nexport type PerpsTraceValue = string | number | boolean;\n\n/**\n * Terminal status of a Perps trace.\n *\n * Platform adapters map this value to their tracing SDK's span status.\n */\nexport type PerpsTraceStatus = 'ok' | 'error';\n\n/**\n * Properties allowed in analytics events. More constrained than unknown.\n * Named PerpsAnalyticsProperties to avoid conflict with PERPS_EVENT_PROPERTY\n * constant object from eventNames.ts (which contains property key names).\n */\nexport type PerpsAnalyticsProperties = Record<\n string,\n string | number | boolean | Record<string, string> | null | undefined\n>;\n\n/**\n * Injectable metrics interface for analytics.\n * Allows core package to work with different analytics backends.\n */\nexport type PerpsMetrics = {\n isEnabled(): boolean;\n\n /**\n * Track a Perps-specific analytics event with properties.\n * This abstracts away the MetricsEventBuilder pattern used in mobile.\n *\n * @param event - The Perps analytics event type (enum with actual event name values)\n * @param properties - Type-safe key-value properties to attach to the event\n */\n trackPerpsEvent(\n event: PerpsAnalyticsEvent,\n properties: PerpsAnalyticsProperties,\n ): void;\n};\n\n/**\n * Injectable debug logger for development logging.\n * Only logs in development mode.\n * Accepts `unknown` to allow logging error objects from catch blocks.\n */\nexport type PerpsDebugLogger = {\n log(...args: unknown[]): void;\n};\n\n/**\n * Injectable stream manager interface for pause/resume during critical operations.\n *\n * WHY THIS IS NEEDED:\n * PerpsStreamManager is a React-based mobile-specific singleton that:\n * - Uses React Context for subscription management\n * - Uses react-native-performance for tracing\n * - Directly accesses Engine.context (mobile singleton pattern)\n * - Manages WebSocket connections with throttling/caching\n *\n * PerpsController only needs pause/resume during critical operations (withStreamPause method)\n * to prevent stale UI updates during batch operations. The minimal interface allows:\n * - Mobile: Wrap existing singleton (streamManager[channel].pause())\n * - Extension: Implement with whatever streaming solution they use\n */\n/**\n * Injectable stream manager interface for pause/resume during critical operations.\n *\n * WHY THIS IS NEEDED:\n * PerpsStreamManager is a React-based mobile-specific singleton that:\n * - Uses React Context for subscription management\n * - Uses react-native-performance for tracing\n * - Directly accesses Engine.context (mobile singleton pattern)\n * - Manages WebSocket connections with throttling/caching\n *\n * PerpsController only needs pause/resume during critical operations (withStreamPause method)\n * to prevent stale UI updates during batch operations. The minimal interface allows:\n * - Mobile: Wrap existing singleton (streamManager[channel].pause())\n * - Extension: Implement with whatever streaming solution they use\n */\nexport type PerpsStreamManager = {\n /**\n * @deprecated Core pauses its own stream channels. Still called for one\n * release so a client-side stream manager keeps working.\n */\n pauseChannel(channel: string): void;\n /**\n * @deprecated Core resumes its own stream channels. Still called for one\n * release so a client-side stream manager keeps working.\n */\n resumeChannel(channel: string): void;\n clearAllChannels(): void;\n};\n\n/**\n * Injectable performance monitor interface.\n * Wraps react-native-performance or browser Performance API.\n */\nexport type PerpsPerformance = {\n now(): number;\n /**\n * Optional platform hook invoked once after constructor disk hydration.\n * Receives `performance.now()` — not a Sentry write.\n */\n onControllerConstructed?: (monotonicMs: number) => void;\n};\n\ntype PerpsSetMeasurement = ((\n name: string,\n value: number,\n unit: string,\n) => void) &\n ((name: string, value: number, unit: string, id: string) => void);\n\n/**\n * Injectable tracer interface for Sentry/observability tracing.\n * Services use this to create spans and measure operation durations.\n *\n * Note: trace() returns void because services use name/id pairs to identify traces.\n * The actual span management is handled internally by the platform adapter.\n */\nexport type PerpsTracer = {\n trace(params: {\n name: PerpsTraceName;\n id: string;\n op: string;\n tags?: Record<string, PerpsTraceValue>;\n data?: Record<string, PerpsTraceValue>;\n }): void;\n\n endTrace(params: {\n name: PerpsTraceName;\n id: string;\n status?: PerpsTraceStatus;\n data?: Record<string, PerpsTraceValue>;\n }): void;\n\n setMeasurement: PerpsSetMeasurement;\n\n addBreadcrumb(breadcrumb: {\n category: string;\n message: string;\n level: 'fatal' | 'error' | 'warning' | 'log' | 'info' | 'debug';\n data?: Record<string, unknown>;\n }): void;\n};\n\n// ============================================================================\n// Minimal local types for cross-controller DI (no external controller imports)\n// ============================================================================\n\n/**\n * Minimal typed-message params passed to keyring for EIP-712 signing.\n * Structurally matches KeyringController's TypedMessageParams.\n */\nexport type PerpsTypedMessageParams = {\n from: string;\n data: unknown;\n};\n\n/**\n * EIP-712 payload produced by the HyperLiquid SDK, signed with\n * `eth_signTypedData_v4` semantics. `types` includes the `EIP712Domain`\n * entry derived from `domain`, as `eth_signTypedData_v4` expects.\n */\nexport type PerpsTypedDataPayload = {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Hex;\n };\n types: Record<string, { name: string; type: string }[]>;\n primaryType: string;\n message: Record<string, unknown>;\n};\n\n/**\n * Client-implemented signer for the user's main EVM account. When provided,\n * the wallet services sign through it and never call `KeyringController`.\n * Clients that own a KeyringController omit it. The signing address still\n * comes from the messenger's selected account.\n */\nexport type PerpsAccountSigner = {\n /**\n * Sign EIP-712 typed data as `address`, exactly as given. HyperLiquid's\n * `domain.chainId` is not the wallet's connected chain: L1 actions signed\n * without an agent use 1337, and user-signed actions (builder fee,\n * withdraw, ...) use 1 unless `getChainId` is set. A wallet that only signs\n * for its connected chain (many EIP-1193 wallets) must route L1 actions\n * through an agent (see `providerCredentials.hyperliquid.getAgentSigner`)\n * and set `getChainId`.\n *\n * @param address - The account that signs.\n * @param payload - The typed data to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signTypedData(address: Hex, payload: PerpsTypedDataPayload): Promise<Hex>;\n\n /**\n * EIP-191 `personal_sign` as `address`. Required so a host that sets\n * `accountSigner` never falls back to `KeyringController` (Lighter signs\n * its venue-key registration this way).\n *\n * @param address - The account that signs.\n * @param message - Plaintext message to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signPersonalMessage(address: Hex, message: string): Promise<Hex>;\n\n /**\n * False while the signer cannot sign (e.g. wallet disconnected). Signing\n * then fails with `KEYRING_LOCKED`. Defaults to true.\n */\n isReady?(): boolean;\n\n /**\n * True when every signature needs a user confirmation (a hardware wallet,\n * or an interactive wallet such as a browser extension). HyperLiquid then\n * defers its optional init-time signing prompts to action time. When\n * omitted, the selected account's keyring type decides.\n */\n requiresSignatureConfirmation?(): boolean;\n\n /**\n * The chain the signer signs for, such as a browser wallet's connected\n * chain. HyperLiquid user-signed actions are then signed for it instead of\n * chain 1, so the wallet does not switch chains to sign them. Read at\n * every user-signed action.\n *\n * @returns The chain ID.\n */\n getChainId?(): Promise<number>;\n};\n\n/**\n * The main account and network an agent is approved for.\n */\nexport type PerpsAgentAccount = {\n /** The main account the agent acts for. */\n mainAddress: Hex;\n /** Whether the agent is approved on testnet rather than mainnet. */\n isTestnet: boolean;\n};\n\n/**\n * Host-owned delegated signer for a venue agent (HyperLiquid API wallet).\n * The host creates the key, gets it approved by the user's main account, and\n * keeps it; Core only asks it to sign. A viem local account satisfies this\n * shape.\n */\nexport type PerpsAgentSigner = {\n /** The agent account address. */\n address: Hex;\n\n /**\n * Sign EIP-712 typed data with the agent key.\n *\n * @param payload - The typed data to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signTypedData(payload: PerpsTypedDataPayload): Promise<Hex>;\n};\n\n/**\n * Minimal transaction params passed to TransactionController.addTransaction.\n * Only the fields PerpsController actually sets.\n */\nexport type PerpsTransactionParams = {\n from: string;\n to?: string;\n value?: string;\n data?: string;\n gas?: string;\n};\n\n/**\n * Options passed to TransactionController.addTransaction.\n */\nexport type PerpsAddTransactionOptions = {\n networkClientId: string;\n origin?: string;\n type?: string;\n skipInitialGasEstimate?: boolean;\n};\n\n/**\n * Minimal account shape read from AccountTreeController.\n * Only the fields PerpsController and its services actually use.\n */\nexport type PerpsInternalAccount = {\n address: string;\n type: string;\n id: string;\n};\n\n/**\n * Minimal remote feature flag state shape.\n * Only the remoteFeatureFlags record is needed by PerpsController.\n */\nexport type PerpsRemoteFeatureFlagState = {\n remoteFeatureFlags: Record<string, unknown>;\n};\n\n/**\n * Injectable interface for the Terminal-market service.\n *\n * `MarketDataService` programs against this contract so the concrete\n * `TerminalMarketService` class (which lives in `services/`) never leaks\n * into the types barrel — callers can supply any implementation that\n * satisfies the shape (production, stub, mock, etc.).\n */\nexport type PerpsTerminalMarketService = {\n fetchMarkets(): Promise<{\n markets: MarketInfo[];\n metadata: Map<string, TerminalAssetMetadata>;\n }>;\n clearCache(): void;\n logError(error: unknown, method: string): void;\n fetchGlobalSnapshot?(\n request: PerpsGlobalSnapshotRequest,\n ): Promise<PerpsGlobalSnapshotResult>;\n};\n\n/**\n * Exact identity a client expects from an atomic global Perps snapshot.\n * Lighter has a single DEX, so its `enabledDexes` is `['main']`.\n */\nexport type PerpsGlobalSnapshotRequest = {\n provider: 'hyperliquid' | 'lighter';\n network: 'mainnet' | 'testnet';\n enabledDexes: string[];\n};\n\n/** Validated snapshot data and its source-bounded expiry. */\nexport type PerpsGlobalSnapshotResult = {\n markets: PerpsMarketData[];\n /**\n * Trading-rule rows for `markets`, in the same order. `getMarkets` reads\n * this instead of mapping the snapshot a second time.\n */\n marketInfos: MarketInfo[];\n expiresAt: number;\n};\n\n/**\n * Platform dependencies for PerpsController and services.\n *\n * Architecture:\n * - Observability: logger, debugLogger, metrics, performance, tracer\n * - Platform: streamManager (mobile/extension specific)\n * - Cache: cache invalidation for standalone queries\n * - Rewards: delegated rewards interaction (DI — no RewardsController in Core yet)\n *\n * Cross-controller communication uses the messenger pattern (messenger.call).\n * Only rewards remains as DI because RewardsController is not yet in Core.\n */\nexport type PerpsPlatformDependencies = {\n // === Observability (stateless utilities) ===\n logger: PerpsLogger;\n debugLogger: PerpsDebugLogger;\n metrics: PerpsMetrics;\n performance: PerpsPerformance;\n tracer: PerpsTracer;\n\n // === Platform Services (mobile/extension specific) ===\n /**\n * @deprecated Core's stream channels pause, rebind and reopen themselves\n * (`PerpsController.resubscribeStreams` replaces a client-side reconnect).\n * Still called for one release; a client without its own stream manager\n * can pass no-ops.\n */\n streamManager: PerpsStreamManager;\n\n // === Feature Flags (platform-specific version gating) ===\n featureFlags: {\n /**\n * Validate a version-gated feature flag against current app version.\n * Returns true if flag is enabled AND app meets minimum version,\n * false if flag is disabled, or undefined if flag is misconfigured/overridden.\n *\n * Platform-specific because it uses react-native-device-info (mobile)\n * or browser APIs (extension) to get the app version.\n */\n validateVersionGated(flag: VersionGatedFeatureFlag): boolean | undefined;\n };\n\n // === Market Data Formatting (platform-specific number formatting) ===\n marketDataFormatters: MarketDataFormatters;\n\n // === Cache Invalidation (for standalone query caches) ===\n cacheInvalidator: PerpsCacheInvalidator;\n\n // === Disk Cache (cold-start persistence) ===\n diskCache: {\n getItem(key: string): Promise<string | null>;\n getItemSync?(key: string): string | null;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n };\n\n // === Terminal API (market metadata source) ===\n terminalApi?: {\n /** Full endpoint URL for the legacy perpetuals market-data endpoint. */\n marketDataUrl?: string;\n\n /**\n * Full endpoint URL for the schema-v4 atomic global Perps snapshot\n * (`GET /v4/perpetuals`).\n */\n globalSnapshotUrl?: string;\n };\n\n // === notify-perps API (Lighter account enrollment) ===\n notifyPerpsApi?: {\n /**\n * Base URL of the notify-perps API for the current environment (for\n * example `https://perps.api.cx.metamask.io`). Lighter accounts are\n * enrolled at `${baseUrl}/api/v1/lighter/accounts`. When omitted,\n * enrollment is skipped.\n */\n baseUrl?: string;\n };\n\n /** @deprecated Use `terminalApi.marketDataUrl`. */\n terminalApiUrl?: string;\n\n /**\n * Optional Terminal-market service instance for fetching structured market\n * metadata from the MetaMask Terminal API.\n *\n * When provided, `MarketDataService` uses this service to attempt the\n * Terminal API path before falling back to the provider.\n * Clients that do not use the Terminal API can omit this field.\n */\n terminalMarketService?: PerpsTerminalMarketService;\n\n // === Rewards (DI — no RewardsController in Core yet) ===\n rewards: {\n /**\n * Get the VIP and season fee discount for an account.\n *\n * Returns a numeric discount in basis points (e.g., 6500 = 65%), or `null`\n * when rewards state has not hydrated yet.\n *\n * Pass the perps MetaMask builder base fee in bips so the rewards\n * controller can convert an absolute VIP fee into a discount fraction.\n */\n getPerpsDiscountForAccount(\n caipAccountId: `${string}:${string}:${string}`,\n baseFeeBips: number,\n ): Promise<number | null>;\n\n /**\n * Get the independent trading fee grant for an explicit provider route.\n *\n * The client owns grant retrieval, authentication, payload validation, and\n * deciding which routes it supports. Core calls this only when the resolver\n * has an explicit scope, validates the returned fee, expiry, and exact scope\n * match after concurrent candidate work settles, and compares valid\n * candidates with the other fee sources.\n *\n * Optional so clients predating grant support retain their existing\n * behavior.\n */\n getPerpsTradingFeeGrant?(\n scope: PerpsFeeResolverScope,\n ): Promise<PerpsTradingFeeGrant | null>;\n\n /**\n * Call the listener when an answer of the two reads above may have changed\n * (a Rewards session started, ended or expired, or a tier changed), so fee\n * rate streams are priced again. Optional: without it they follow fills\n * and account changes only.\n */\n subscribeToPerpsFeeChanges?(listener: () => void): () => void;\n };\n\n // === Subscription (DI — benefits endpoint is owned by the Subscription team) ===\n /**\n * Optional subscription source for the unified fee resolver.\n *\n * The client owns the Profile JWT, so it performs\n * `GET /v1/profiles/{profileId}/benefits` and hands the perps controller the\n * parsed body. The controller caches the result stale-while-revalidate and\n * never awaits this call on the order-signing path.\n *\n * Omit it entirely on clients that do not ship the subscription waiver; the\n * resolver then falls back to the rewards and default sources.\n */\n subscription?: {\n /**\n * Read the current profile's subscription benefits.\n * Resolve `null` when there is no subscription to report (signed out, no\n * profile). Rejections are tolerated: the resolver keeps the previous\n * snapshot and never grants the waiver from a failed read.\n */\n getPerpsBenefits(): Promise<PerpsSubscriptionBenefits | null>;\n\n /**\n * Register the current HyperLiquid trading address (CAIP-10) against the\n * subscription profile, so a later fill can be attributed to it.\n *\n * Optional compatibility fallback for clients that do not register the\n * structural `SubscriptionController:registerAddress` action.\n */\n registerTradingAddress?(caipAccountId: string): Promise<void>;\n };\n\n // === Account Signer (DI — for clients without a KeyringController) ===\n /**\n * Optional signer for the user's main EVM account. When set, it takes\n * precedence over the `KeyringController:*` messenger actions.\n */\n accountSigner?: PerpsAccountSigner;\n};\n\n/**\n * Cache types that can be invalidated.\n * Used by standalone query caches (e.g., usePerpsPositionForAsset).\n */\nexport type PerpsCacheType = 'positions' | 'accountState' | 'markets';\n\n/**\n * Parameters for invalidating a specific cache type.\n */\nexport type InvalidateCacheParams = {\n /** The type of cache to invalidate */\n cacheType: PerpsCacheType;\n};\n\n/**\n * Cache invalidation interface for standalone query caches.\n * Allows services to signal when data has changed without depending on\n * mobile-specific implementations.\n */\nexport type PerpsCacheInvalidator = {\n /**\n * Invalidate a specific cache type.\n * Notifies all subscribers that cached data is stale.\n */\n invalidate(params: InvalidateCacheParams): void;\n\n /**\n * Invalidate all cache types.\n */\n invalidateAll(): void;\n};\n\n// ============================================================================\n// Market Data Formatting\n// ============================================================================\n\n/**\n * Injectable formatters for market data transformation.\n * Decouples marketDataTransform from mobile-specific intl/formatUtils imports.\n *\n * Range configs are opaque (unknown[]) because the concrete type\n * (FiatRangeConfig on mobile) is platform-specific. The formatter\n * implementation casts internally.\n */\nexport type MarketDataFormatters = {\n /** Format a number as a USD volume string (e.g., '$1.2B', '$850M') */\n formatVolume(value: number): string;\n /** Format a number as a USD fiat string with adaptive precision */\n formatPerpsFiat(value: number, options?: { ranges?: unknown[] }): string;\n /** Format a number as a percentage string (e.g., '2.50%', '-1.80%') */\n formatPercentage(percent: number): string;\n /** Universal price ranges for formatting (opaque to portable code) */\n priceRangesUniversal: unknown[];\n};\n\n// ============================================================================\n// Payment Token (portable replacement for mobile-only AssetType)\n// ============================================================================\n\n/**\n * Minimal payment token for deposit flow.\n * Only the fields actually used by PerpsController are included.\n * Replaces the mobile-only AssetType (which extends TokenI and uses ImageSourcePropType).\n */\nexport type PaymentToken = {\n description?: string;\n address: string;\n chainId?: string;\n symbol?: string;\n};\n\n/**\n * Selected pay-with token shape used in PerpsController state, pending trade config,\n * selectors, and UI hooks. Use this type everywhere this shape is needed.\n */\nexport type PerpsSelectedPaymentToken = {\n description?: string;\n address: string;\n chainId: string;\n symbol?: string;\n};\n\n// ============================================================================\n// Version-gated Feature Flag (portable)\n// ============================================================================\n\n/**\n * Structure for a version-gated feature flag from LaunchDarkly.\n * Portable: no platform-specific imports.\n */\nexport type VersionGatedFeatureFlag = {\n enabled: boolean;\n minimumVersion: string;\n};\n\n/**\n * Type guard for VersionGatedFeatureFlag.\n * Pure logic, no platform dependencies.\n *\n * @param value - The value to check.\n * @returns True if the value is a VersionGatedFeatureFlag.\n */\nexport function isVersionGatedFeatureFlag(\n value: unknown,\n): value is VersionGatedFeatureFlag {\n return (\n typeof value === 'object' &&\n value !== null &&\n hasProperty(value, 'enabled') &&\n hasProperty(value, 'minimumVersion') &&\n typeof (value as { enabled: unknown }).enabled === 'boolean' &&\n typeof (value as { minimumVersion: unknown }).minimumVersion === 'string'\n );\n}\n\n// ============================================================================\n// Sub-module type re-exports\n// These types live in separate files within types/ and need to be accessible\n// from the root barrel via `export * from './types.js'`.\n// ============================================================================\nexport type * from './perps-types.js';\nexport * from './transactionTypes.js';\n// hyperliquid-types: selective export to avoid OrderType clash with main types\nexport type {\n HyperLiquidAbstractionMode,\n AssetPosition,\n SpotBalance,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n FrontendOrder,\n SDKOrderParams,\n ClearinghouseStateResponse,\n SpotClearinghouseStateResponse,\n MetaResponse,\n FrontendOpenOrdersResponse,\n AllMidsResponse,\n MetaAndAssetCtxsResponse,\n PredictedFundingsResponse,\n SpotMetaResponse,\n} from './hyperliquid-types.js';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA0B9C;;;;GAIG;AACH,MAAM,CAAN,IAAY,wBAKX;AALD,WAAY,wBAAwB;IAClC,yDAA6B,CAAA;IAC7B,qDAAyB,CAAA;IACzB,mDAAuB,CAAA;IACvB,2DAA+B,CAAA;AACjC,CAAC,EALW,wBAAwB,KAAxB,wBAAwB,QAKnC;AA8FD,gEAAgE;AAChE,MAAM,CAAN,IAAY,cASX;AATD,WAAY,cAAc;IACxB,2CAAyB,CAAA;IACzB,iCAAe,CAAA;IACf,oCAAkB,CAAA;IAClB,iCAAe,CAAA;IACf,6BAAW,CAAA;IACX,yCAAuB,CAAA;IACvB,iCAAe,CAAA;IACf,uCAAqB,CAAA;AACvB,CAAC,EATW,cAAc,KAAd,cAAc,QASzB;AAmCD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,QAAQ;IACR,UAAU;IACV,OAAO;IACP,SAAS;IACT,OAAO;IACP,KAAK;IACL,WAAW;IACX,OAAO;CAC8B,CAAC;AAwhIxC;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,mBAiBX;AAjBD,WAAY,mBAAmB;IAC7B,4EAAqD,CAAA;IACrD,kEAA2C,CAAA;IAC3C,mFAA4D,CAAA;IAC5D,+EAAwD,CAAA;IACxD,0DAAmC,CAAA;IACnC,4DAAqC,CAAA;IACrC,8DAAuC,CAAA;IACvC,gDAAyB,CAAA;IACzB,0DAAmC,CAAA;IACnC,8BAA8B;IAC9B,oFAAoF;IACpF,4EAAqD,CAAA;IACrD,uEAAgD,CAAA;IAChD,wDAAiC,CAAA;IACjC,uEAAgD,CAAA;IAChD,gEAAyC,CAAA;AAC3C,CAAC,EAjBW,mBAAmB,KAAnB,mBAAmB,QAiB9B;AAiED;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,qBAAqB;IACrB,UAAU,EAAE,mBAAmB;IAC/B,SAAS,EAAE,kBAAkB;IAC7B,WAAW,EAAE,oBAAoB;IACjC,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,oBAAoB;IAChC,YAAY,EAAE,qBAAqB;IACnC,YAAY,EAAE,qBAAqB;IAEnC,qBAAqB;IACrB,QAAQ,EAAE,gBAAgB;IAC1B,OAAO,EAAE,eAAe;IAExB,cAAc;IACd,YAAY,EAAE,qBAAqB;IACnC,eAAe,EAAE,yBAAyB;IAC1C,UAAU,EAAE,mBAAmB;IAC/B,uBAAuB,EAAE,mCAAmC;IAC5D,eAAe,EAAE,yBAAyB;IAC1C,WAAW,EAAE,oBAAoB;IACjC,YAAY,EAAE,qBAAqB;IACnC,sBAAsB,EAAE,gCAAgC;IACxD,sBAAsB,EAAE,gCAAgC;IAExD,YAAY;IACZ,cAAc,EAAE,wBAAwB;IAExC,YAAY;IACZ,kBAAkB,EAAE,2BAA2B;IAC/C,qBAAqB,EAAE,8BAA8B;IACrD,uBAAuB,EAAE,iCAAiC;IAC1D,oBAAoB,EAAE,8BAA8B;IACpD,qBAAqB,EAAE,+BAA+B;IAEtD,QAAQ;IACR,cAAc,EAAE,wBAAwB;IACxC,uBAAuB,EAAE,gCAAgC;IACzD,yBAAyB,EAAE,mCAAmC;IAC9D,iBAAiB,EAAE,2BAA2B;IAC9C,eAAe,EAAE,yBAAyB;CACO,CAAC;AAEpD;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,SAAS,EAAE,iBAAiB;IAC5B,eAAe,EAAE,wBAAwB;IACzC,kBAAkB,EAAE,2BAA2B;CACvC,CAAC;AAumBX;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC;QAC7B,WAAW,CAAC,KAAK,EAAE,gBAAgB,CAAC;QACpC,OAAQ,KAA8B,CAAC,OAAO,KAAK,SAAS;QAC5D,OAAQ,KAAqC,CAAC,cAAc,KAAK,QAAQ,CAC1E,CAAC;AACJ,CAAC;AAQD,cAAc,uBAAuB,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n CaipAccountId,\n CaipChainId,\n CaipAssetId,\n Hex,\n} from '@metamask/utils';\n\nimport type { CandlePeriod, TimeDuration } from '../constants/chartConfig.js';\nimport type { PerpsMaxSlippageSource } from '../constants/eventNames.js';\nimport type { CHASE_ORDER_STATUS } from '../constants/perpsConfig.js';\nimport type { PerpsErrorDetails } from '../errors.js';\nimport type { PerpsErrorCode } from '../perpsErrorCodes.js';\nimport type { LighterProvider } from '../providers/LighterProvider.js';\nimport type { HyperLiquidMarginTier } from '../utils/hyperLiquidPositionPreview.js';\nimport type { LighterSignerBridge } from './lighter-types.js';\nimport type {\n CandleData,\n OrderDirection,\n OrderType,\n StrategyOrderType,\n TpslLinkage,\n TriggerDirection,\n TriggerOrderType,\n} from './perps-types.js';\n\n/**\n * Connection states for WebSocket management.\n * Defined inline to avoid importing from Mobile-only services.\n * Must stay in sync with HyperLiquidClientService.WebSocketConnectionState.\n */\nexport enum WebSocketConnectionState {\n Disconnected = 'disconnected',\n Connecting = 'connecting',\n Connected = 'connected',\n Disconnecting = 'disconnecting',\n}\n\n/**\n * Why a provider reports degraded health.\n *\n * - `socket_down`: the venue socket is down or reconnecting while streams need it.\n * - `server_errors`: repeated 5xx responses from the venue's REST API.\n * - `rate_limited`: the venue answered 429/405; reads are held until `cooldownUntil`.\n */\nexport type PerpsProviderHealthReason =\n | 'socket_down'\n | 'server_errors'\n | 'rate_limited';\n\n/**\n * One provider's health. `unavailable` means the provider is not registered,\n * or is disconnected with no reconnect pending (not started or disconnected).\n * It describes the provider, not its socket: Lighter closes its socket when\n * nothing listens and still reports `healthy`.\n */\nexport type PerpsProviderHealth = {\n providerId: PerpsProviderType;\n status: 'healthy' | 'degraded' | 'unavailable';\n /** Empty unless `status` is `degraded`. */\n reasons: PerpsProviderHealthReason[];\n connectionState: WebSocketConnectionState;\n /** Reconnect attempts since the last successful open (0 when connected or idle). */\n reconnectionAttempt: number;\n /** Epoch ms when a rate-limit cooldown ends, set only while `rate_limited`. */\n cooldownUntil?: number;\n /** Epoch ms when this snapshot was taken. */\n updatedAt: number;\n};\n\n/** Parameters for `PerpsController.subscribeToProviderHealth`. */\nexport type SubscribeProviderHealthParams = {\n providerId: PerpsProviderType;\n callback: (health: PerpsProviderHealth) => void;\n};\n\n/** Provider-agnostic raw ledger update. Fields match the common shape across providers. */\nexport type RawLedgerUpdate = {\n hash: string;\n time: number;\n delta: {\n type: string;\n usdc?: string;\n coin?: string;\n };\n};\n\n// User history item for deposits and withdrawals\nexport type UserHistoryItem = {\n id: string;\n timestamp: number;\n type: 'deposit' | 'withdrawal';\n amount: string;\n asset: string;\n txHash: string;\n status: 'completed' | 'failed' | 'pending';\n details: {\n source: string;\n bridgeContract?: string;\n recipient?: string;\n blockNumber?: string;\n chainId?: string;\n synthetic?: boolean;\n };\n};\n\n// Parameters for getting user history\nexport type GetUserHistoryParams = {\n startTime?: number;\n endTime?: number;\n accountId?: CaipAccountId;\n};\n\n// Trade configuration saved per market per network\nexport type TradeConfiguration = {\n leverage?: number; // Last used leverage for this market\n marginMode?: MarginMode; // Last Isolated/Cross pick for this market\n // Pending trade configuration (temporary, expires after 30 seconds)\n pendingConfig?: {\n amount?: string; // Order size in USD\n leverage?: number; // Leverage\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n limitPrice?: string; // Limit price (for limit orders)\n orderType?: OrderType; // Market vs limit\n reduceOnly?: boolean; // Whether the order may only reduce a position\n timestamp: number; // When the config was saved (for expiration check)\n };\n};\n\n// Market asset type classification (reusable across components)\nexport enum MarketCategory {\n CryptoCurrency = 'crypto',\n Stock = 'stock',\n PreIpo = 'pre-ipo',\n Index = 'index',\n Etf = 'etf',\n Commodity = 'commodity',\n Forex = 'forex',\n Memecoin = 'memecoin',\n}\n\nexport type MarketType = `${MarketCategory}`;\n\n/**\n * Metadata extracted from Terminal API for a single asset.\n * Used downstream to enrich PerpsMarketData with name, keywords, tags, etc.\n */\nexport type TerminalAssetMetadata = {\n name?: string;\n description?: string;\n keywords?: string[];\n tags?: string[];\n categories?: string[];\n marketType?: MarketType;\n /**\n * Epoch ms when this market was listed on the Terminal backend.\n * Normalized from the raw API value (number or ISO string).\n */\n listedAt?: number;\n};\n\n// Market type filter for UI category badges\nexport type MarketTypeFilter =\n | 'all'\n | 'crypto'\n | 'memecoin'\n | 'stock'\n | 'pre-ipo'\n | 'index'\n | 'etf'\n | 'commodity'\n | 'forex'\n | 'new';\n\n/**\n * Ordered list of data-model market categories for UI pills.\n * Does not include the 'all' or 'new' sentinel values — those are applied\n * via dedicated UI controls, not the category pills.\n *\n * Note: 'memecoin' is a derived category (marketType === 'crypto' &&\n * tags.includes('memecoin')). It overlaps with 'crypto' by design —\n * memecoins appear under both pills.\n *\n * Kept in sync with {@link MarketTypeFilter} via `satisfies`.\n */\nexport const MARKET_CATEGORIES = [\n 'crypto',\n 'memecoin',\n 'stock',\n 'pre-ipo',\n 'index',\n 'etf',\n 'commodity',\n 'forex',\n] as const satisfies MarketTypeFilter[];\n\n// Input method for amount entry tracking\nexport type InputMethod =\n | 'default'\n | 'slider'\n | 'keypad'\n | 'percentage'\n | 'max';\n\n// Trade action type - differentiates first trade on a market, adding to an\n// existing position, and flipping a position's direction\nexport type TradeAction =\n | 'create_position'\n | 'increase_exposure'\n | 'flip_long_to_short'\n | 'flip_short_to_long';\n\n// Unified tracking data interface for analytics events (never persisted in state)\n// Note: Numeric values are already parsed by hooks (usePerpsOrderFees, etc.) from API responses\nexport type TrackingData = {\n // Common to all operations\n totalFee?: number; // Total fee for the operation (parsed by hooks); omit when unknown\n marketPrice?: number; // Market price at operation time (parsed by hooks); omit when unknown\n metamaskFee?: number; // MetaMask fee amount (parsed by hooks)\n metamaskFeeRate?: number; // MetaMask fee rate (parsed by hooks)\n feeDiscountPercentage?: number; // Fee discount percentage (parsed by hooks)\n estimatedPoints?: number; // Estimated reward points (parsed by hooks)\n\n // Order-specific (used for trade operations)\n marginUsed?: number; // Margin required for this order (calculated by hooks)\n inputMethod?: InputMethod; // How user set the amount\n tradeAction?: TradeAction; // 'create_position' for first trade, 'increase_exposure' for adding to existing\n\n // Close-specific (used for position close operations)\n receivedAmount?: number; // Amount user receives after close (calculated by hooks)\n realizedPnl?: number; // Realized P&L from close (calculated by hooks)\n\n // Entry source for analytics (e.g., 'trending' for Trending page discovery)\n source?: string;\n // Chart library active when the trade was initiated (e.g., lightweight, advanced)\n chartLibrary?: string;\n\n // Entry point / discovery attribution. Propagated onto trade/close/\n // cancel/risk events as entry_point, discovery_source, perp_discovery_source.\n entryPoint?: string;\n discoverySource?: string;\n perpDiscoverySource?: string;\n\n // UI surface that started the action. Omitted from the event when unset.\n environmentType?: string;\n\n // HyperLiquid protocol fee rate. Emitted as hl_fee_rate on trade +\n // close events when present; omitted entirely when unavailable.\n hlFeeRate?: number;\n\n // Slippage context for trade and close transaction analytics.\n maxSlippageBps?: number;\n maxSlippageSource?: PerpsMaxSlippageSource;\n estimatedSlippageBps?: number;\n\n // Pay with any token: true when user paid with a custom token (not Perps balance)\n tradeWithToken?: boolean;\n mmPayTokenSelected?: string; // Token symbol when tradeWithToken is true\n mmPayNetworkSelected?: string; // chainId when tradeWithToken is true\n\n // VIP tier and discount for rewards tracking\n vipTier?: number; // User's VIP tier level\n vipDiscount?: number; // VIP discount percentage applied\n\n // A/B test context to attribute trade events to specific experiments\n abTests?: Record<string, string>;\n};\n\n// TP/SL-specific tracking data for analytics events\nexport type TPSLTrackingData = {\n direction: 'long' | 'short'; // Position direction\n /**\n * @deprecated Source of the TP/SL update (e.g., 'tp_sl_view', 'position_card').\n * Prefer `entryPoint` / `discoverySource` / `perpDiscoverySource` for risk-event\n * attribution; `source` is retained for backward compatibility.\n */\n source: string;\n positionSize: number; // Unsigned position size for metrics\n takeProfitPercentage?: number; // Take profit percentage from entry\n stopLossPercentage?: number; // Stop loss percentage from entry\n isEditingExistingPosition?: boolean; // true = editing existing position, false = creating for new order\n entryPrice?: number; // Entry price for percentage calculations\n\n // Entry point / discovery attribution, propagated onto risk events.\n entryPoint?: string;\n discoverySource?: string;\n perpDiscoverySource?: string;\n\n // UI surface that started the action. Omitted from the event when unset.\n environmentType?: string;\n};\n\n/** Collateral mode requested for a new order. */\nexport type MarginMode = 'isolated' | 'cross';\n\n/** Exact approved Lighter Scale preview. Other providers reject this constraint. */\nexport type ExpectedScaleLadder = Readonly<{\n prices: readonly string[];\n sizes: readonly string[];\n totalSize: string;\n totalNotional: string;\n minimumBaseSize: string;\n minimumQuoteAmount: string;\n sizeDecimals: number;\n}>;\n\n// MetaMask Perps API order parameters for PerpsController\nexport type OrderParams = {\n symbol: string; // Asset identifier (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n isBuy: boolean; // true = BUY order, false = SELL order\n size: string; // Order size as string (derived for validation, provider recalculates from usdAmount)\n orderType: OrderType; // Order type\n price?: string; // Limit price (required for limit orders)\n reduceOnly?: boolean; // Reduce-only flag\n isFullClose?: boolean; // Indicates closing 100% of position (skips $10 minimum validation)\n timeInForce?: 'GTC' | 'IOC' | 'ALO'; // Time in force for plain limit orders\n\n // USD as source of truth (hybrid approach)\n usdAmount?: string; // USD amount (primary source of truth, provider calculates size from this)\n priceAtCalculation?: number; // Price snapshot when size was calculated (for slippage validation)\n maxSlippageBps?: number; // Slippage tolerance in basis points (e.g., 100 = 1%, default if not provided)\n /**\n * @deprecated Use `maxSlippageBps` instead. Retained for one release so that\n * existing publisher consumers (extension, core) that still pass slippage as\n * a decimal (e.g. 0.03 for 3%) continue to work; the provider normalizes the\n * value to basis points when `maxSlippageBps` is absent.\n */\n slippage?: number;\n\n // Trigger placement (stop_market, stop_limit, take_profit_market, take_profit_limit).\n // Required for those order types and rejected for market/limit orders.\n triggerPrice?: string; // Price at which the resting order activates\n\n // Strategy placement (twap, scale, chase). Each group below is required for\n // its own order type and rejected on every other one, so a stray field can\n // never be silently dropped. Strategy orders carry no `price`, `triggerPrice`,\n // `timeInForce` or attached TP/SL — the strategy owns its own execution.\n twapDuration?: number; // TWAP window in whole minutes; each provider enforces its own venue's bounds\n twapRandomize?: boolean; // Randomize each TWAP suborder's size by up to ±20% (default false)\n scaleMinPrice?: string; // Lowest limit price in the scale ladder\n scaleMaxPrice?: string; // Highest limit price in the scale ladder; must exceed scaleMinPrice\n scaleNumOrders?: number; // How many limit orders to spread across the ladder (2..20)\n /**\n * How the ladder's size is weighted across its rungs. Rung weights ramp\n * linearly from 1 at `scaleMinPrice` to this value at `scaleMaxPrice`, in that\n * direction for both sides — a short does not flip it. Above 1 puts more size\n * at `scaleMaxPrice`, below 1 at `scaleMinPrice`. Omitted or exactly 1 spreads\n * the size evenly. Any finite value above 0 is accepted as given; see\n * `splitScaleSizes` for how the sizes are allocated.\n */\n scaleSkew?: number;\n /**\n * Bind Lighter placement to the displayed normalized ladder and minimums.\n * Omission retains legacy placement-time normalization with no displayed-preview guarantee.\n * This is intent evidence, not accepted-order or fill evidence.\n */\n expectedScaleLadder?: ExpectedScaleLadder;\n chaseIntervalMs?: number; // How often the chase re-reads the touch (default 15000, min 1000)\n chaseMaxDurationMs?: number; // Optional hard stop for the chase window (unbounded by default)\n chaseMaxRepricings?: number; // Optional cap on cancel/replace cycles (unbounded by default)\n chaseMaxDistanceBps?: number; // Optional directional distance from arrival price where chasing stops\n\n // Advanced order features\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n // Partial TP/SL: size of the attached TP/SL order. Omit for a TP/SL covering\n // the full order size. Must be positive and no greater than `size`.\n takeProfitSize?: string; // Quantity covered by the attached take profit\n stopLossSize?: string; // Quantity covered by the attached stop loss\n clientOrderId?: string; // Optional client-provided order ID\n /**\n * How an attached TP/SL is linked: to this order (`order`), to the resulting\n * position (`position`), or absent (`none`). Defaults to `none` without TP/SL\n * and `order` with TP/SL. Takes precedence over the deprecated `grouping`.\n */\n tpslLinkage?: TpslLinkage;\n /**\n * @deprecated Use `tpslLinkage`. This field carries HyperLiquid's own grouping\n * vocabulary; it is honoured for existing callers but a provider-agnostic\n * placement should not depend on protocol wording.\n */\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl'; // Override grouping (defaults: 'na' without TP/SL, 'normalTpsl' with TP/SL)\n currentPrice?: number; // Current market price (avoids extra API call if provided)\n leverage?: number; // Leverage to apply for the order (e.g., 10 for 10x leverage)\n /**\n * Explicit collateral mode. Requires leverage. Lighter native orders verify\n * mode execution and visibility before exposure and refuse changes with an\n * open position or resting/pending orders. HyperLiquid validates market\n * support and refuses mode changes with an open position or resting order.\n * Omit to let the provider choose: HyperLiquid keeps an open position's\n * mode and otherwise uses isolated.\n */\n marginMode?: MarginMode;\n existingPositionLeverage?: number; // Existing position leverage for validation (protocol constraint)\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n /**\n * When true, the provider returns a venue failure without logging it.\n * The caller reports that failure under its own operation. Not sent to the venue.\n * Flip sets this so Lighter does not consume the single Sentry event as `place_order`.\n */\n deferProviderErrorReport?: boolean;\n\n // Multi-provider routing (optional: defaults to active/default provider).\n providerId?: PerpsProviderType;\n};\n\nexport type ScaleOrderChild =\n | {\n state: 'resting' | 'filled' | 'canceled';\n orderId: string;\n }\n | {\n state: 'waitingForFill' | 'waitingForTrigger';\n orderId?: never;\n };\n\n/** Durable identities for one native parent plus attached protection group. */\nexport type AttachedOrderGroup = {\n groupId: string;\n providerId: PerpsProviderType;\n symbol: string;\n /** Acceptance never proves activation or the quantity protected after a partial fill. */\n submission: 'prepared' | 'unknown' | 'accepted' | 'canceled' | 'completed';\n parentClientOrderId: string;\n childClientOrderIds: string[];\n /** Exact venue IDs, when observed. Unknown identities remain absent. */\n parentOrderId?: string;\n childOrderIds?: string[];\n /** Automatic parent/child cancellation is not assumed. */\n cancellation: 'explicit-exact-owned-orders';\n /** Explicit review observations; terminal groups without a pending dispatch return local identities only. Absence is not an empty book. */\n orders?: {\n clientOrderId: string;\n orderId?: string;\n status:\n | 'unknown'\n | 'waiting'\n | 'resting'\n | 'partially-filled'\n | 'filled'\n | 'canceled'\n | 'rejected';\n filledSize?: string;\n }[];\n /** A bounded review leaves missing legs unknown rather than asserting absence. */\n historyStatus?: 'complete' | 'bounded';\n /** Parent/child references only; this does not prove automatic OCO cancellation. */\n linkage?: 'confirmed' | 'unknown';\n};\n\n/** Durable strategy inventory without fabricated venue IDs or unknown fills. */\nexport type ScaleOrderGroup = Pick<\n OrderResult,\n | 'orderId'\n | 'submittedSize'\n | 'acceptedSize'\n | 'acceptedChildren'\n | 'childOrderIds'\n | 'weightedAverageLimitPrice'\n | 'filledSize'\n> & {\n groupId: string;\n symbol: string;\n providerId: PerpsProviderType;\n accountIndex: number;\n apiKeyIndex: number;\n state: 'placing' | 'stopped' | 'unknown' | 'terminal';\n walletAddress: string;\n network: 'mainnet' | 'testnet';\n};\n\n/** Same-order edit outcome; acceptance alone remains pending. */\nexport type OrderEditObservation = {\n status: 'pending' | 'settled' | 'failed' | 'terminal';\n requestedPrice: string;\n requestedSize: string;\n observation?: {\n price: string;\n size: string;\n remainingSize: string;\n filledSize: string;\n status: Order['status'];\n };\n};\n\n/** Observed protection outcome; independent legs have no sibling cancellation guarantee. */\nexport type PositionProtectionReceipt = {\n linkage: 'single' | 'equal-quantity-oco' | 'independent';\n legs: {\n role: 'take-profit' | 'stop-loss';\n /** Absent when the caller requested the captured full-position quantity. */\n requestedSize?: string;\n normalizedSize: string;\n clientOrderId?: string;\n orderId?: string;\n status:\n | 'unknown'\n | 'resting'\n | 'partially-filled'\n | 'filled'\n | 'canceled'\n | 'rejected';\n }[];\n};\n\nexport type OrderResult = {\n /** Exact protection intent and any observed leg outcomes, including failures. */\n positionProtection?: PositionProtectionReceipt;\n /** Durable native edit outcome, including unresolved earlier intent on retry. */\n orderEdit?: OrderEditObservation;\n attachedOrderGroup?: AttachedOrderGroup;\n success?: boolean;\n /**\n * What names the placement afterwards.\n *\n * For an ordinary placement this is the exchange's order ID. For a *strategy*\n * placement it is a handle instead — a venue TWAP id, or a client-generated\n * scale-group or chase-session id — which is what `CancelOrderParams` takes\n * together with the matching `orderType` and `providerId`. Hyperliquid Scale handles\n * are encoded in venue client-order IDs and recovered from open-order reads.\n * Lighter Scale handles and unresolved rungs persist in account-scoped local\n * storage. Hyperliquid Chase handles are session-local and cannot be\n * recovered because every replacement receives a new exchange order ID.\n * Lighter retains local durable Chase handles for explicit cleanup but\n * never automatically resumes a loop after reconnect.\n * The individual exchange IDs a strategy expanded into are in\n * `childOrderIds`.\n */\n orderId?: string;\n error?: string;\n /** Stable error classification for client-side translation. */\n errorCode?: PerpsErrorCode;\n /** Optional structured data for the classified error. */\n errorDetails?: PerpsErrorDetails;\n filledSize?: string; // Amount filled\n // Full normalized size submitted to the exchange (post precision rounding,\n // USD recalculation, and any $10-minimum retry). Present only when the\n // provider reached submission.\n submittedSize?: string;\n // Normalized size of the submitted rungs that the exchange accepted. This\n // differs from `submittedSize` when a non-atomic Scale batch is partly\n // rejected.\n acceptedSize?: string;\n // Size-weighted average execution price. Present only when the result\n // includes fills.\n averagePrice?: string;\n // Size-weighted limit price of accepted Scale rungs. This is a submission\n // price, not an execution price.\n weightedAverageLimitPrice?: string;\n // Every accepted child of a Scale batch and its immediate placement state.\n // Waiting children do not carry an exchange order ID; cancel the Scale handle\n // to cancel both resting and waiting children.\n acceptedChildren?: ScaleOrderChild[];\n // Exchange IDs tied to a multi-order or recovery result. On a successful\n // strategy placement, `orderId` carries the strategy handle and these IDs\n // identify its individual children.\n //\n // For a `scale` ladder these identify only resting, cancellable rungs. Every\n // accepted rung and its state is reported in `acceptedChildren`. Scale rungs\n // are never replaced, so a resting ID stays valid after the handle is gone.\n // For a `chase` this is only the order resting at placement time — the\n // strategy cancels and re-places as the touch moves, and each replacement has\n // a new ID that is held in the session rather than reported here, so the value\n // goes stale on the first re-price. Cancel a live chase by its handle.\n //\n // When TP/SL protection cannot be fully restored, these identify the old\n // orders that survived, may still be live when reconciliation failed, or were\n // recreated; an empty array means none are known or potentially live.\n // Successful position TP/SL updates may return an exact receipt: newly\n // created venue IDs in request order (TP then SL), including children that\n // already executed or were cancelled by OCO. A successful removal returns\n // []. Absence means exact receipt identity is unavailable, not zero children.\n // These IDs establish ownership, not current resting status; re-read before\n // cancellation. They exclude the old protection cancelled by replacement.\n childOrderIds?: string[];\n providerId?: PerpsProviderType; // Multi-provider: which provider executed this order (injected by aggregator)\n /**\n * Structured record of venue state that was ALREADY committed before the\n * placement failed — e.g. a leverage change that landed before the order\n * was rejected. Present only on failure results where such state exists;\n * callers must not treat the failure as \"nothing happened\".\n */\n partialState?: {\n /** Leverage (in x) the venue already applied for this symbol. */\n leverageUpdated?: number;\n };\n};\n\n/**\n * A TP/SL protection change that could not be safely completed\n * automatically and requires an explicit new protection intent from the\n * user. Surfaced by providers with durable settlement state (Lighter).\n */\nexport type PerpsPendingManualRecovery = {\n /** Owning provider route; mandatory on aggregated recovery rows. */\n providerId?: PerpsProviderType;\n /** Issuing wallet/network scope when supplied by the provider. */\n walletAddress?: string;\n network?: string;\n /** Opaque selected source-operation identity, when explicit resolution is supported. */\n recoveryId?: string;\n symbol: string;\n /** Durable identity (address:accountIndex:apiKey:symbol). */\n settlementKey: string;\n recordedAt: number;\n /** Human-readable cause of the parked state. */\n reason: string;\n /** Whether the interrupted operation replaced or removed protection. */\n priorIntent: 'replace' | 'remove';\n /** Venue order ids still on the books when the state was parked. */\n survivingOrderIds: string[];\n /**\n * Original fixed coverage, for review only; never permission to replay.\n * A current-key journal may still belong to a running operation. Await its\n * result before selecting explicit recovery; listing does not reconcile it.\n */\n partialIntent?: {\n version: 1 | 2;\n positionSide: 'long' | 'short';\n linkage: 'single' | 'oco' | 'independent';\n legs: {\n type: 'take-profit' | 'stop-loss';\n size: string;\n clientOrderId: string;\n }[];\n };\n /** What the user should do to resolve the state. */\n actionNeeded: string;\n};\n\n/** Fresh, authoritative venue state for one issuing provider context. */\nexport type PerpsRecoveryVenueReview =\n | { status: 'unsupported'; providerId: PerpsProviderType; reason: string }\n | {\n status: 'ready';\n providerId: PerpsProviderType;\n walletAddress: string;\n network: string;\n accountIndex: number;\n positions: Position[];\n orders: Order[];\n reviewedAt: number;\n };\n\n/** Explicit successor protection for one opaque durable source obligation. */\nexport type ResolveRecoveryProtectionParams = UpdatePositionTPSLParams & {\n recoveryId: string;\n};\n\n/** Unsupported capability is distinct from a supported but unresolved intent. */\nexport type PerpsRecoveryProtectionResult =\n | (OrderResult & {\n status: 'settled' | 'unresolved';\n providerId: PerpsProviderType;\n })\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n success: false;\n error: string;\n };\n\n/**\n * A local dispatch requiring reconciliation or acknowledgment. Raw unresolved\n * dispatches include current-session in-flight submissions, have\n * acknowledgeable:false and cannot be acknowledged. Listing starts no\n * background reconciliation. Explicit reconcileRecoveredDispatches checks venue\n * evidence without signing or retrying; TP/SL-owned entries remain pending. A\n * later fenced financial action still blocks unresolved dispatches. For\n * resolved outcomes, writes stay blocked until explicitly acknowledged via\n * `acknowledgeRecoveredDispatch` (after the caller refreshes venue\n * state) — except `failed`, which is retry-safe and non-blocking.\n */\nexport type PerpsRecoveredDispatch = {\n /** Owning provider for strict review and explicit acknowledgment routing. */\n providerId?: PerpsProviderType;\n walletAddress?: string;\n network?: string;\n /** Opaque stable id for selective acknowledgment; preserve exactly, never parse. */\n recoveryId: string;\n /** Original trading-key slot when the provider has per-key recovery ledgers. */\n apiKeyIndex?: number;\n /** False for unresolved raw dispatches: acknowledgment is forbidden until reconciled. */\n acknowledgeable?: boolean;\n /** Venue transaction type of the dispatch. */\n kind: number;\n /** Human-readable operation intent. */\n intent: string;\n txHash: string | null;\n outcome: 'succeeded' | 'failed' | 'unknown';\n /** How the outcome was determined (e.g. `tx-status:2`, `rest-advance`). */\n evidence: string;\n};\n\nexport type ChaseOrderStatus =\n (typeof CHASE_ORDER_STATUS)[keyof typeof CHASE_ORDER_STATUS];\n\nexport type TwapOrderStatus =\n | 'active'\n | 'completed'\n | 'completed_underfilled'\n | 'canceled'\n | 'failed';\n\nexport type TwapOrderFill = {\n fillId: string;\n orderId: string;\n side: 'buy' | 'sell';\n price: string;\n size: string;\n fee: string;\n feeToken: string;\n builderFee?: string;\n timestamp: number;\n transactionHash: string;\n};\n\n/** Current and terminal state of one venue-native TWAP schedule. */\nexport type TwapOrder = {\n orderId: string;\n symbol: string;\n side: 'buy' | 'sell';\n size: string;\n executedSize: string;\n remainingSize: string;\n executedNotional: string;\n averagePrice?: string;\n fillProgressBps: number;\n timeProgressBps: number;\n elapsedTimeMilliseconds: number;\n durationMinutes: number;\n randomize: boolean;\n reduceOnly: boolean;\n status: TwapOrderStatus;\n startedAt: number;\n lastUpdated: number;\n error?: string;\n fills: TwapOrderFill[];\n providerId?: PerpsProviderType;\n};\n\n/**\n * Client-visible state of one emulated Chase placement.\n *\n * The handle remains stable while the exchange child ID and resting price can\n * change on every reprice. Terminal sessions are retained until provider\n * teardown so clients can observe why chasing stopped and then reconcile the\n * surviving child through the ordinary orders stream.\n */\nexport type ChaseOrder = {\n handle: string;\n symbol: string;\n side: 'buy' | 'sell';\n originalSize: string;\n remainingSize: string;\n arrivalPrice: string;\n restingPrice: string;\n restingOrderId: string | null;\n /** Adverse distance of the resting child from arrival, rounded to whole bps. */\n distanceChasedBps: number;\n /**\n * Optional adverse-touch stop, strictly between 0 and 10,000 bps.\n * The resting child may sit just inside this boundary after price-grid rounding.\n */\n maxDistanceBps?: number;\n repricings: number;\n startedAt: number;\n status: ChaseOrderStatus;\n providerId?: PerpsProviderType;\n};\n\n/** How a TWAP is cut into suborders on the venue's cadence. */\nexport type TwapSlicePreview = {\n /** Suborders over the whole running time. */\n sliceCount: number;\n /** Seconds between two suborders. */\n sliceIntervalSeconds: number;\n /** Size of one suborder, floored to the venue's size grid. */\n sizePerSlice: string;\n /** Size precision `sizePerSlice` is expressed in; pass it to `formatPositionSize`. */\n sizeDecimals: number;\n /** Smallest size the grid can express. */\n minimumSize: string;\n /** True when one suborder floors below `minimumSize`. */\n isBelowMinimumSize: boolean;\n /** Value of one suborder at the reference price, when one was given. */\n notionalPerSlice?: string;\n};\n\n/** Chase snapshots split for display, newest first. */\nexport type ChaseOrderLists = {\n /** Chases still chasing or waiting for a cancel to settle. */\n running: ChaseOrder[];\n /** Ended chases, bounded to `CHASE_ORDER_CONFIG.HistoryLimit`. */\n history: ChaseOrder[];\n};\n\n/** Whether another chase fits under the venue's cap. */\nexport type ChasePlacementCheck = {\n canPlace: boolean;\n /** Chases currently chasing, the ones the cap counts. */\n activeCount: number;\n /** Venue cap; omitted when the venue has none. */\n maxActiveSessions?: number;\n /** `PERPS_ERROR_CODES` reason when `canPlace` is false. */\n error?: string;\n};\n\n/** Rung sizes of a scale ladder sized by `sizeScaleLadder`. */\nexport type ScaleLadderSizing = {\n sizes: string[];\n totalSize: string;\n /** Sum of rung price times rung size, in USD. */\n totalNotional: string;\n};\n\n/** A warning about where a scale ladder rests relative to the market. */\nexport type ScalePriceWarning =\n | { code: 'crosses_market' | 'partially_crosses_market' }\n | { code: 'far_from_market'; distancePercent: number };\n\n/** Original durable Chase owner. Observation never grants current cleanup authority. */\nexport type PerpsChaseOrderOwner = {\n providerId: PerpsProviderType;\n walletAddress: string;\n network: 'testnet' | 'mainnet';\n accountIndex: number;\n apiKeyIndex: number;\n};\n\n/** Public transaction identity and durable dispatch phase, without signed payloads. */\nexport type PerpsChaseOrderDispatch = {\n phase: 'prepared' | 'signed' | 'attempted' | 'acknowledged' | 'failed';\n nonce?: number;\n txHash?: string;\n expiresAt?: number;\n};\n\n/** One durable child, including superseded, terminal and unresolved attempts. */\nexport type PerpsChaseOrderChild = {\n /** Exact opaque native client ID. Never infer it from the stable handle. */\n clientOrderId: string;\n size: string;\n price: string;\n quotedAt: number;\n placement: PerpsChaseOrderDispatch;\n cancellations: PerpsChaseOrderDispatch[];\n /**\n * Last exact persisted venue observation, not a fresh venue read. Absence\n * means no observation; an attempted or acknowledged dispatch stays unknown.\n */\n observation?: {\n orderId: string;\n terminal: boolean;\n filledSize: string;\n filledNotional: string;\n remainingSize: string;\n };\n};\n\n/** Select one opaque handle and explicit provider, optionally fencing its original owner. */\nexport type GetChaseOrderOwnershipParams = {\n handle: string;\n providerId: PerpsProviderType;\n owner?: PerpsChaseOrderOwner;\n};\n\n/** Reconcile only the exact already-attempted cancellation under its original owner. */\nexport type ReconcileChaseOrderCancellationParams = {\n handle: string;\n providerId: PerpsProviderType;\n owner: PerpsChaseOrderOwner;\n clientOrderId: string;\n cancellation: Pick<\n Required<PerpsChaseOrderDispatch>,\n 'nonce' | 'txHash' | 'expiresAt'\n >;\n};\n\n/** No result authorizes a new cancellation; uncertain or lost replies stay unresolved. */\nexport type ReconcileChaseOrderCancellationResult =\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n handle: string;\n reason: string;\n }\n | {\n status: 'settled' | 'unresolved';\n providerId: PerpsProviderType;\n handle: string;\n order: ChaseOrder;\n };\n\n/**\n * Validated durable local history for one exact handle. Available means every\n * locally recorded child is included, not that venue reconciliation is complete.\n * Missing records never report an available empty inventory; corrupt storage rejects.\n */\nexport type PerpsChaseOrderOwnership =\n | {\n status: 'unsupported';\n providerId: PerpsProviderType;\n handle: string;\n reason: string;\n }\n | {\n status: 'unavailable';\n providerId: PerpsProviderType;\n handle: string;\n reason: 'not_found' | 'owner_mismatch';\n }\n | {\n status: 'available';\n providerId: PerpsProviderType;\n handle: string;\n owner: PerpsChaseOrderOwner;\n order: ChaseOrder;\n children: PerpsChaseOrderChild[];\n executedSize: string;\n executedNotional: string;\n lastTickAt: number;\n stopReason?: ChaseOrderStatus;\n };\n\n/** Lifecycle signal emitted when a Chase reaches its configured distance. */\nexport type ChaseOrderMaxDistanceReached = {\n handle: string;\n symbol: string;\n side: 'buy' | 'sell';\n restingOrderId: string | null;\n restingPrice: string;\n maxDistanceBps: number;\n timestamp: number;\n providerId: PerpsProviderType;\n};\n\nexport type Position = {\n symbol: string; // Asset identifier (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n size: string; // Signed position size (+ = LONG, - = SHORT)\n entryPrice: string; // Average entry price\n positionValue: string; // Total position value in USD\n unrealizedPnl: string; // Unrealized profit/loss\n marginUsed: string; // Margin currently used for this position\n /**\n * Margin the venue shows for a cross position. Hyperliquid scales cross\n * margin by `accountValue / totalMarginUsed` when cross equity is below\n * initial margin, so this is `marginUsed` times that ratio (capped at 1).\n * `marginUsed` keeps the raw venue figure. Absent for isolated positions\n * and when the provider does not report one.\n */\n displayMarginUsed?: string;\n leverage: {\n type: 'isolated' | 'cross'; // Margin type\n value?: number; // Leverage multiplier. Undefined when the venue does not report it\n rawUsd?: string; // USD amount (for isolated margin)\n };\n liquidationPrice: string | null; // Liquidation price (null if no risk)\n maxLeverage: number; // Maximum allowed leverage for this asset\n returnOnEquity: string; // ROE percentage\n /**\n * Funding payments history. Absent when the venue does not report it.\n */\n cumulativeFunding?: {\n allTime: string; // Total funding since account opening\n sinceOpen: string; // Funding since position opened\n sinceChange: string; // Funding since last size change\n };\n /**\n * Take profit price (if set).\n *\n * Summary field, resolved for the common case a client renders: when\n * `takeProfitOrders` holds exactly one order this is that order's trigger\n * price, whether or not it covers the whole position. With two or more orders\n * no single price describes them, so this falls back to the position-bound\n * trigger — clients render `takeProfitCount` there instead.\n *\n * It may also reflect a TP/SL child of a *pending* order on this market, which\n * `takeProfitOrders` and `takeProfitCount` deliberately exclude because such a\n * child protects that order rather than the position. A position can therefore\n * report a price here with an empty array and a count of `0`. Prefer\n * `takeProfitOrders` for anything that must be exact.\n */\n takeProfitPrice?: string;\n /**\n * Stop loss price (if set). Same caveat as `takeProfitPrice`.\n */\n stopLossPrice?: string;\n takeProfitCount: number; // Take profit count, how many tps can affect the position\n stopLossCount: number; // Stop loss count, how many sls can affect the position\n // Full view of the trigger orders attached to this position, including\n // quantity-scoped (partial) ones. The scalar `takeProfitPrice`/`stopLossPrice`\n // fields above only carry one price each and cannot represent partial TP/SL.\n takeProfitOrders?: PositionTriggerOrder[];\n stopLossOrders?: PositionTriggerOrder[];\n providerId?: PerpsProviderType; // Multi-provider: which provider holds this position (injected by aggregator)\n};\n\n/**\n * A trigger order attached to a position, as surfaced in position state.\n * Provider-agnostic: protocols map their own trigger representation onto this.\n */\nexport type PositionTriggerOrder = {\n orderId: string; // Exchange order ID (cancelable)\n direction: TriggerDirection; // Whether the trigger takes profit or stops loss. Always known: recovered from the trigger price against the entry when the exchange does not name the placement type\n orderType?: TriggerOrderType; // Normalized placement type. Absent when the exchange reported an unnamed trigger, whose execution mode cannot be recovered\n triggerPrice: string; // Price at which the order activates\n size: string; // Quantity this trigger closes (resolved to position size when the protocol encodes \"whole position\")\n isPartial: boolean; // true when `size` is smaller than the position size\n /**\n * Position coverage cannot be resolved yet. Use the trigger price and order\n * ID normally, but do not present the size as resolved or use the partial\n * flag until a fresh position arrives.\n */\n coverageUnavailable?: true;\n reduceOnly: boolean; // Whether the trigger can only reduce the position\n};\n\n/**\n * Provider-agnostic cross-margin summary, in USD decimal strings. Clients\n * derive account ratio, account leverage and cross margin usage from it.\n *\n * HL: crossMarginSummary + crossMaintenanceMarginUsed, summed across DEXs.\n * Lighter: the bound account's cross positions; accountValue is the total\n * balance less isolated positions' unrealized PnL.\n */\nexport type CrossMarginSummary = {\n accountValue: string;\n maintenanceMargin: string;\n marginUsed: string;\n notional: string;\n};\n\n// Using 'type' instead of 'interface' for BaseController Json compatibility\nexport type AccountState = {\n /** Registration of this wallet on this venue, when reported. */\n exchangeAccountStatus?: ExchangeAccountStatus;\n /**\n * Venue account mode when confirmed by the current account stream or read\n * (Hyperliquid `userAbstraction`). Pass it to `calculateAccountSummary`.\n */\n accountMode?: string;\n /**\n * Total USD equity on this venue — collateral + unrealized PnL. Live MTM.\n * HL Unified / Portfolio Margin: spot USDC total\n * HL Standard: marginSummary.accountValue + spot(USDC) − spot.hold\n */\n totalBalance: string;\n /**\n * Max USD that can immediately collateralize a new position on this venue,\n * with no internal transfer required.\n * HL Unified / Portfolio Margin: spot USDC total − hold\n * HL Standard: withdrawable\n */\n spendableBalance: string;\n /**\n * Max USD that can leave this venue to the user's external wallet.\n * UI reads this value without branching on provider; the provider\n * contract guarantees HL's own abstraction (Unified) or the direct\n * perps-clearinghouse (Standard) is what actually settles the\n * withdraw — no client-side spot→perps sweep is performed.\n * HL Unified / Portfolio Margin: spot USDC total − hold (HL withdraw3 draws from the unified ledger server-side)\n * HL Standard: withdrawable (perps-clearinghouse only; spot is a separate ledger)\n */\n withdrawableBalance: string;\n marginUsed: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n /**\n * Cross-margin account summary. Absent when the provider does not report\n * one for this read.\n */\n crossMarginSummary?: CrossMarginSummary;\n /**\n * Sub-accounts (Hyperliquid DEX names; `''` is the main DEX) whose state is\n * unavailable: the read failed, or on the live stream it has not arrived.\n * The totals exclude them, so the state is partial while this is present.\n */\n unavailableSubAccounts?: string[];\n /**\n * Spot USDC this venue counts as cross collateral, as a decimal string.\n * Pass it to `calculateAccountSummary` as `spotCollateral`.\n *\n * Absent while the spot state or the abstraction mode is still unknown.\n * `calculateAccountSummary` then leaves `accountRatio` and\n * `crossMarginUsage` undefined.\n *\n * `'0'` when spot is not collateral: Hyperliquid Standard (`disabled` /\n * `default`), and venues with no separate spot ledger (Lighter).\n *\n * Free spot USDC (`max(0, total − hold)`, USDC only) for Hyperliquid\n * Unified and portfolio margin.\n */\n spotCollateral?: string;\n /**\n * Per-sub-account balance breakdown (protocol-specific, optional)\n * Maps sub-account identifier to its balance details.\n *\n * Protocol examples:\n * - HyperLiquid HIP-3: '' or 'main' (main DEX), 'xyz' (HIP-3 builder DEX)\n * - dYdX: Sub-account numbers (e.g., '0', '1', '2')\n * - Other protocols: Vault IDs, pool IDs, margin account IDs, etc.\n *\n * Key: Sub-account identifier (protocol-specific string)\n * Value: Balance details for that sub-account\n */\n subAccountBreakdown?: Record<\n string,\n {\n spendableBalance: string;\n withdrawableBalance: string;\n totalBalance: string;\n }\n >;\n /**\n * Per-venue account states, keyed by provider id. Present only when the\n * state was produced by the aggregated provider; direct-provider results\n * omit it. Venue-local detail (`crossMarginSummary`,\n * `subAccountBreakdown`) stays inside each entry — the top-level totals are\n * venue-neutral and never carry venue-local collateral detail.\n */\n providerStates?: Partial<\n Record<PerpsProviderType, PerpsProviderAccountStateEntry>\n >;\n /**\n * Completeness of the top-level totals across every enabled venue.\n * Present only when the state was produced by the aggregated provider.\n */\n aggregate?: AccountAggregateMetadata;\n providerId?: PerpsProviderType; // Multi-provider: which provider this account state is from (injected by aggregator)\n};\n\n/**\n * One venue's account data inside an aggregated {@link AccountState}.\n *\n * A failed read, invalid balance snapshot, or `null` after a venue has reported\n * a snapshot is `unavailable` — never a zero balance. Before its first snapshot,\n * a stream venue is `pending`, even if it emits `null`: no verdict about its\n * balances, so its persisted entry is retained. A confirmed zero or nonexistent\n * venue account is an `available` entry whose balances are zero.\n */\nexport type PerpsProviderAccountStateEntry =\n | {\n status: 'available';\n /** The venue's own account snapshot, attributed to its provider. */\n state: AccountState;\n providerId: PerpsProviderType;\n }\n | {\n status: 'unavailable';\n /** The venue read failed; its balances contribute nothing to totals. */\n error?: string;\n providerId: PerpsProviderType;\n }\n | {\n status: 'pending';\n /** The venue has not reported on this stream yet; no verdict.\n * Stream-only: the read path always awaits every venue. */\n providerId: PerpsProviderType;\n };\n\n/**\n * Completeness metadata for an aggregated account read or stream update.\n *\n * `status: 'partial'` means the top-level totals are subtotals over\n * `availableProviders` only: at least one enabled venue contributed no data.\n * Consumers must not present partial totals as the user's complete portfolio\n * value. With no metadata at all (absent `aggregate`), the state came from a\n * single venue or a legacy producer and has no incompleteness claim.\n */\nexport type AccountAggregateMetadata = {\n status: 'complete' | 'partial';\n availableProviders: PerpsProviderType[];\n unavailableProviders: PerpsProviderType[];\n /** Stream updates only: venues that have not reported yet. They make the\n * totals partial, but unlike `unavailableProviders` there is no verdict\n * about their balances. */\n pendingProviders?: PerpsProviderType[];\n};\n\nexport type ClosePositionParams = {\n /**\n * Account that supplied a batch close target. A changed account cannot close it.\n *\n * @internal\n */\n expectedAccountId?: CaipAccountId;\n symbol: string; // Asset identifier to close (e.g., 'ETH', 'BTC', 'xyz:TSLA')\n size?: string; // Size to close (omit for full close)\n /**\n * Close order type (default: market). Only `market` and `limit` are meaningful\n * here: `ClosePositionParams` carries no trigger price, so a trigger-based\n * close is not expressible and would be rejected during placement.\n *\n * Strategy placements are excluded at the type level rather than left to a\n * runtime rejection, because this type cannot carry any of the fields they\n * require and `closePosition` has no path that executes them. Derived with\n * `Exclude` on purpose: it shrinks as `StrategyOrderType` grows, so a strategy\n * added later is refused here automatically.\n */\n orderType?: Exclude<OrderType, StrategyOrderType>;\n price?: string; // Limit price (required for limit close)\n currentPrice?: number; // Current market price for validation\n\n // USD as source of truth (hybrid approach - same as OrderParams)\n usdAmount?: string; // USD amount (primary source of truth, provider calculates size from this)\n priceAtCalculation?: number; // Price snapshot when size was calculated (for slippage validation)\n maxSlippageBps?: number; // Slippage tolerance in basis points (e.g., 100 = 1%, default if not provided)\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n\n // Multi-provider routing (optional: defaults to active/default provider)\n providerId?: PerpsProviderType; // Optional: override active provider for routing\n\n /**\n * Optional caller snapshot for diagnostics.\n *\n * The provider always resolves the position from the current DEX WebSocket\n * slice or an HTTP read. It never uses this snapshot for order size or side.\n * If neither authoritative source answers, the close fails with\n * `PROVIDER_NOT_AVAILABLE`.\n */\n position?: Position;\n};\n\nexport type ClosePositionsParams = {\n symbols?: string[]; // Optional: specific symbols to close (omit or empty array to close all)\n closeAll?: boolean; // Explicitly close all positions\n /**\n * Explicit provider-tagged close targets. Each target is closed on its\n * named venue only, so identical symbols on different venues are\n * independent. Non-empty targets take precedence over `closeAll` and\n * `symbols`.\n */\n targets?: ClosePositionsTarget[];\n};\n\n/** One close target, tagged with the venue that holds the position. */\nexport type ClosePositionsTarget = {\n symbol: string;\n providerId: PerpsProviderType;\n};\n\n/**\n * Outcome of a batch cancel or close. `all`: every attempted item succeeded.\n * `partial`: some succeeded and some failed. `none`: nothing succeeded,\n * including when nothing matched the request. A cancel target absent from\n * discovery has no result row. An order that disappears after discovery can\n * produce an `ORDER_NO_LONGER_OPEN` failure row.\n */\nexport type BatchOperationStatus = 'all' | 'partial' | 'none';\n\n/**\n * A batch result as `PerpsController` returns it, with its derived `status`.\n */\nexport type WithBatchOperationStatus<\n Result extends ClosePositionsResult | CancelOrdersResult,\n> = Result & { status: BatchOperationStatus };\n\nexport type ClosePositionsResult = {\n /**\n * True when at least one position closed, so it is also true on partial\n * failure. Render from `status` instead.\n */\n success: boolean;\n successCount: number; // Number of positions closed successfully\n /** Failed positions, or one per failed venue when its positions are unknown. */\n failureCount: number;\n /**\n * Batch-level operation error.\n *\n * Merged multi-venue failures use BATCH_INCOMPLETE, including when another\n * venue succeeded; venue details live in `failures`. Direct-provider batches\n * preserve their snapshot/preparation or submission error. Venue text is\n * replaced with a stable code.\n */\n error?: string;\n /** Venue-level errors; `error` remains BATCH_INCOMPLETE on a merged batch. */\n failures?: { providerId: PerpsProviderType; error: string }[];\n /** Stable classification for the batch-level error. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details for the batch-level error. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n results: {\n symbol: string;\n success: boolean;\n error?: string;\n errorCode?: PerpsErrorCode;\n errorDetails?: PerpsErrorDetails;\n /** Venue that (attempted to) execute this close. */\n providerId?: PerpsProviderType;\n }[];\n};\n\nexport type UpdateMarginParams = {\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n amount: string; // Amount to adjust as string (positive = add, negative = remove)\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n};\n\nexport type MarginResult = {\n success: boolean;\n error?: string;\n /** Stable classification for a failed margin update. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type FlipPositionParams = {\n symbol: string; // Asset identifier to flip (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n position: Position; // Current position to flip\n\n // Optional tracking data for MetaMetrics events\n trackingData?: TrackingData;\n};\n\nexport type InitializeResult = {\n success: boolean;\n error?: string;\n /** Stable classification when initialization fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n chainId?: string;\n};\n\nexport type ReadyToTradeResult = {\n ready: boolean;\n error?: string;\n /** Stable classification when the readiness check fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n walletConnected?: boolean;\n networkSupported?: boolean;\n authenticatedAddress?: string;\n};\n\nexport type DisconnectResult = {\n success: boolean;\n error?: string;\n /** Stable classification when disconnect fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type MarketInfo = {\n name: string; // HyperLiquid: universe name (asset symbol)\n szDecimals: number; // HyperLiquid: size decimals\n /** Fixed decimal price grid, when the venue declares one. */\n priceDecimals?: number;\n maxLeverage: number; // HyperLiquid: max leverage\n marginTableId: number; // HyperLiquid: margin requirements table ID\n marginMode?: 'strictIsolated' | 'noCross'; // HyperLiquid market capability\n onlyIsolated?: true; // HyperLiquid: isolated margin only (optional, only when true)\n isDelisted?: true; // HyperLiquid: delisted status (optional, only when true)\n /**\n * HyperLiquid margin tiers for `marginTableId`, lowest notional first, as\n * `resolveHyperLiquidMarginTiers` resolves them from the venue's `meta`.\n * Omitted when the table cannot be resolved, and on lists served from the\n * Terminal market snapshot; `getOrderCapabilities` always reads them from\n * the venue.\n */\n marginTiers?: HyperLiquidMarginTier[];\n minimumOrderSize?: number; // Minimum order size in USD (protocol-specific)\n providerId?: PerpsProviderType; // Multi-provider: which provider this market comes from (injected by aggregator)\n /** Cross-venue identity from the Terminal snapshot. */\n marketKey?: string;\n /** Venue price divided by canonical market price. */\n priceScale?: number;\n};\n\n/**\n * Market data with prices for UI display\n * Protocol-agnostic interface for market information with formatted values\n */\nexport type PerpsMarketData = {\n /**\n * Stable backend market identifier supplied by the Terminal global snapshot\n * (e.g. 'btc-hyperliquid-mainnet'). Used as the key for perp-alerts API\n * calls. Only present when data originates from that endpoint; omit checks\n * against this field must guard with `?? undefined`.\n */\n id?: string;\n /**\n * Token symbol (e.g., 'BTC', 'ETH')\n */\n symbol: string;\n /**\n * Full token name (e.g., 'Bitcoin', 'Ethereum')\n */\n name: string;\n /**\n * Human-readable asset description from Terminal API metadata, when available\n * (e.g., 'The leading smart contract platform. Home to DeFi, NFTs...').\n * Only populated when using the Terminal API backend and the asset has one.\n */\n description?: string;\n /**\n * Maximum leverage available as formatted string (e.g., '40x', '25x')\n */\n maxLeverage: string;\n /**\n * Current price as formatted string (e.g., '$50,000.00')\n */\n price: string;\n /**\n * 24h price change as formatted string (e.g., '+$1,250.00', '-$850.50')\n */\n change24h: string;\n /**\n * 24h price change percentage as formatted string (e.g., '+2.5%', '-1.8%')\n */\n change24hPercent: string;\n /**\n * 5-minute mark-price change from the v4 Terminal snapshot, formatted like\n * `change24h`. `--` means the window is unavailable. Clients should hide\n * that period and suppress its alerts.\n */\n change5m?: string;\n /**\n * 5-minute percent change from the v4 Terminal snapshot. `--%` means the\n * window is unavailable.\n */\n changePercent5m?: string;\n /**\n * 1-hour mark-price change from the v4 Terminal snapshot, formatted like\n * `change24h`. `--` means the window is unavailable. Clients should hide\n * that period and suppress its alerts.\n */\n change1h?: string;\n /**\n * 1-hour percent change from the v4 Terminal snapshot. `--%` means the\n * window is unavailable.\n */\n changePercent1h?: string;\n /**\n * Trading volume as formatted string (e.g., '$1.2B', '$850M')\n */\n volume: string;\n /**\n * Open interest as formatted string (e.g., '$24.5M', '$1.2B')\n */\n openInterest?: string;\n /**\n * Next funding time in milliseconds since epoch (optional, market-specific)\n */\n nextFundingTime?: number;\n /**\n * Funding interval in hours (optional, market-specific)\n */\n fundingIntervalHours?: number;\n /**\n * Current funding rate as decimal (optional, from predictedFundings API)\n */\n fundingRate?: number;\n /**\n * Market source DEX identifier (HIP-3 support)\n * - null or undefined: Main validator DEX\n * - \"xyz\", \"abc\", etc: HIP-3 builder-deployed DEX\n */\n marketSource?: string | null;\n /**\n * Market asset type classification (optional)\n * - crypto: Cryptocurrency (default for most markets)\n * - stock: Individual stocks (HIP-3)\n * - pre-ipo: Pre-IPO assets (HIP-3)\n * - index: Market indices (HIP-3)\n * - etf: Exchange-traded funds (HIP-3)\n * - commodity: Commodity markets (HIP-3)\n * - forex: Foreign exchange pairs (HIP-3)\n */\n marketType?: MarketType;\n /**\n * Whether this is a HIP-3 market (has DEX prefix like xyz:, flx:)\n * Used to distinguish between crypto (isHip3=false) and non-crypto markets\n */\n isHip3?: boolean;\n /**\n * Whether this is a new/uncategorized market (HIP-3 markets not yet in explicit mapping)\n * Used for the \"New\" filter tab\n */\n isNewMarket?: boolean;\n /**\n * Multi-provider: which provider this market data comes from (injected by aggregator)\n */\n providerId?: PerpsProviderType;\n /**\n * Indicates this market snapshot came from the last known good cache after live fetch failure.\n */\n isStale?: boolean;\n /** Identifies an atomic Terminal summary whose price/change use mark semantics. */\n dataSource?: 'terminal-global-snapshot-mark';\n /** Source-bounded expiry for an atomic Terminal summary. */\n sourceExpiresAt?: number;\n /**\n * Searchable keywords from Terminal API metadata (e.g., ['defi', 'layer-1'])\n */\n keywords?: string[];\n /**\n * Taxonomy tags from Terminal API metadata (e.g., ['top-100', 'gaming'])\n */\n tags?: string[];\n /**\n * Market categories from Terminal API metadata (e.g., ['crypto', 'meme'])\n */\n categories?: string[];\n /** Timestamped hourly price points supplied by the atomic Terminal snapshot. */\n trend?: [timestampMs: number, price: string][];\n /**\n * Epoch ms when this market was listed on the Terminal backend.\n * Sourced from the Terminal API `listedAt` field.\n * Clients can use this to surface recently added markets (e.g. markets listed within the last 30 days).\n */\n listedAt?: number;\n /** Asset icon URL from the Terminal global snapshot. */\n iconUrl?: string;\n /**\n * Cross-venue market identity from the Terminal global snapshot. Rows from\n * different providers with the same `marketKey` are the same market.\n */\n marketKey?: string;\n /** Venue price divided by canonical market price. */\n priceScale?: number;\n /**\n * Unformatted numbers behind the display strings, which `sortMarkets` sorts\n * on. A value is absent when the venue did not report it.\n */\n numericValues?: PerpsMarketNumericValues;\n};\n\n/**\n * Unformatted values of a {@link PerpsMarketData} row: `price` and USD\n * `volume` and `openInterest`, and `change24hPercent` in percent (`2.5` for\n * 2.5%).\n */\nexport type PerpsMarketNumericValues = {\n price?: number;\n change24hPercent?: number;\n volume?: number;\n openInterest?: number;\n};\n\n/** One display row with its original venue rows, preferred venue first. */\nexport type GroupedPerpsMarket = PerpsMarketData & {\n /** Stable display identity, distinct for a backend group and a venue row. */\n rowId: string;\n venues: PerpsMarketData[];\n};\n\nexport type ToggleTestnetResult = {\n success: boolean;\n isTestnet: boolean;\n error?: string;\n /** Stable classification when the network toggle fails. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type AssetRoute = {\n assetId: CaipAssetId; // CAIP asset ID (e.g., \"eip155:42161/erc20:0xaf88.../default\")\n chainId: CaipChainId; // CAIP-2 chain ID where the bridge contract is located\n contractAddress: Hex; // Bridge contract address for deposits/withdrawals\n /**\n * Venue this route moves funds to/from. In aggregated mode, routes from\n * every active venue are listed; identical asset/chain routes belonging\n * to different venues are distinct entries.\n */\n providerId?: PerpsProviderType;\n constraints?: {\n minAmount?: string; // Minimum deposit/withdrawal amount\n maxAmount?: string; // Maximum deposit/withdrawal amount\n estimatedTime?: string; // Estimated processing time (formatted string - deprecated, use estimatedMinutes)\n estimatedMinutes?: number; // Estimated processing time in minutes (raw value for UI formatting)\n fees?: {\n fixed?: number; // Fixed fee amount (e.g., 1 for 1 token)\n percentage?: number; // Percentage fee (e.g., 0.05 for 0.05%)\n token?: string; // Fee token symbol (e.g., 'USDC', 'ETH')\n };\n };\n};\n\nexport type SwitchProviderResult = {\n success: boolean;\n providerId: PerpsActiveProviderMode;\n error?: string;\n};\n\n/**\n * Result of setting the default provider used by aggregated-mode routing.\n *\n * `setDefaultProvider` never re-initializes the controller or reconnects\n * any stream, so there is no asynchronous work to await.\n */\nexport type SetDefaultProviderResult = {\n success: boolean;\n defaultProvider: PerpsProviderType;\n error?: string;\n};\n\n/**\n * Temporary trade configuration captured while a placement flow is\n * interrupted. Expires after `PERPS_CONSTANTS.PendingTradeConfigurationTtlMs`.\n */\nexport type PerpsPendingTradeConfiguration = {\n amount?: string; // Order size in USD\n leverage?: number; // Leverage\n takeProfitPrice?: string; // Take profit price\n stopLossPrice?: string; // Stop loss price\n limitPrice?: string; // Limit price (for limit orders)\n orderType?: OrderType; // Market vs limit\n reduceOnly?: boolean; // Whether the order may only reduce a position\n direction?: OrderDirection; // Long vs short\n /** When user used pay-with-token in PerpsPayRow: minimal token shape to restore selection */\n selectedPaymentToken?: PerpsSelectedPaymentToken | null;\n timestamp: number; // When the config was saved (for expiration check)\n};\n\n/**\n * Persisted per-market trade configuration: leverage, order-book grouping,\n * margin mode and the expiring pending config.\n */\nexport type PerpsTradeConfiguration = {\n leverage?: number; // Last used leverage for this market\n orderBookGrouping?: number; // Persisted price grouping for order book\n marginMode?: MarginMode; // Last Isolated/Cross pick for this market\n pendingConfig?: PerpsPendingTradeConfiguration;\n};\n\n/**\n * Trade configurations keyed by provider id and then market symbol, so a\n * value saved for one venue (for example HyperLiquid BTC) never applies to\n * the same symbol on another venue.\n */\nexport type PerpsProviderTradeConfigurations = {\n [providerId: string]: { [marketSymbol: string]: PerpsTradeConfiguration };\n};\n\nexport type CancelOrderParams = {\n orderId: string; // Order ID to cancel, or the strategy handle when orderType is a strategy type\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n /**\n * Placement type of what is being cancelled. Only the strategy types\n * (`twap`, `scale`, `chase`) change anything: each is cancelled through its\n * own path — the venue's TWAP cancel endpoint, a batch cancel of the ladder's\n * children, or stopping the chase session and cancelling its live order.\n * Omit it (or pass an ordinary order type) to cancel a single resting order,\n * which is what every existing caller does.\n */\n orderType?: OrderType;\n // Optional provider override. Omission uses active/default routing.\n providerId?: PerpsProviderType;\n // Optional tracking data for MetaMetrics events (e.g. discovery attribution)\n trackingData?: TrackingData;\n};\n\nexport type CancelOrderResult = {\n success: boolean;\n /**\n * What was cancelled, named the same way it was placed: an exchange order ID\n * for an ordinary cancel, and the strategy handle — TWAP id, scale group, or\n * chase session — when `CancelOrderParams.orderType` named one. Scale and\n * Hyperliquid chase handles can only be cancelled during the provider session\n * that created them. Lighter durable chase handles remain available for\n * explicit owned cleanup after reconnect; TWAP IDs are venue-owned.\n */\n orderId?: string;\n error?: string;\n providerId?: PerpsProviderType; // Multi-provider: source provider identifier\n /**\n * For a chase cancel whose ending the provider knows, the chase's final\n * snapshot (canceled, filled, or the ending it had already stopped with).\n * Absent when the ending is unknown, for example a child the venue reports\n * gone whose status could not be read.\n */\n chaseOrder?: ChaseOrder;\n};\n\nexport type BatchCancelOrdersParams = {\n orderId: string;\n symbol: string;\n /**\n * Venue that holds this order. Execution identity: the aggregated provider\n * groups mixed-venue batches by it and never resolves duplicate order IDs\n * or symbols across venues by falling back to the default provider.\n */\n providerId?: PerpsProviderType;\n}[];\n\nexport type CancelOrdersParams = {\n symbols?: string[]; // Optional: specific symbols (omit to cancel all orders)\n /** Legacy single-venue filter. Refused when multiple venues are registered;\n * use `orders` to identify the venue for each ID. */\n orderIds?: string[];\n /** Venue-scoped targets, matched on both fields. Takes precedence over\n * legacy filters unless `cancelAll` is true. An empty list cancels nothing. */\n orders?: { orderId: string; providerId: PerpsProviderType }[];\n cancelAll?: boolean; // Explicitly cancel all orders\n};\n\nexport type CancelOrdersResult = {\n /**\n * True when at least one order cancelled, so it is also true on partial\n * failure. Render from `status` instead.\n */\n success: boolean;\n successCount: number; // Number of orders cancelled successfully\n /** Failed cancellations plus unresolved discovery targets. For an unscoped\n * discovery failure, counts one failure per unavailable venue (not its unknown order count). */\n failureCount: number;\n /**\n * Batch-level operation error.\n *\n * Refused batches retain their code; incomplete discovery or merged venue\n * batch errors use BATCH_INCOMPLETE, even if other venues succeeded.\n */\n error?: string;\n /** Venue batch errors, matching ClosePositionsResult.failures. Discovery\n * errors remain separate because their targets have no discovered symbol. */\n failures?: { providerId: PerpsProviderType; error: string }[];\n /** Unavailable venues and, for scoped requests, their unresolved order IDs.\n * These targets have no discovered symbol and are not included in results. */\n discoveryFailures?: {\n providerId: PerpsProviderType;\n error: string;\n orderIds?: string[];\n }[];\n results: {\n orderId: string;\n symbol: string;\n success: boolean;\n error?: string;\n /** Venue that (attempted to) execute this cancel. */\n providerId?: PerpsProviderType;\n }[];\n};\n\nexport type EditOrderParams = {\n orderId: string | number; // Order ID or client order ID to modify\n newOrder: OrderParams; // New order parameters\n};\n\nexport type DepositParams = {\n amount: string; // Amount to deposit\n assetId: CaipAssetId; // Asset to deposit (required for validation)\n fromChainId?: CaipChainId; // Source chain (defaults to current network)\n toChainId?: CaipChainId; // Destination chain (defaults to HyperLiquid Arbitrum)\n recipient?: Hex; // Recipient address (defaults to selected account)\n};\n\n/** Params for depositWithConfirmation: prepares transaction for confirmation screen */\nexport type DepositWithConfirmationParams = {\n /** Optional deposit amount (display/tracking; actual amount comes from prepared transaction) */\n amount?: string;\n /** If true, uses addTransaction instead of submit to avoid navigation (e.g. deposit + place order flow) */\n placeOrder?: boolean;\n /**\n * Venue the deposit should settle on. In aggregated mode, omitting it uses\n * the routing default's route. A venue with no deposit route fails closed\n * instead of funding a different exchange.\n */\n providerId?: PerpsProviderType;\n};\n\nexport type DepositResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n};\n\n// Enhanced deposit flow state types for multi-step deposits\nexport type DepositStatus =\n | 'idle' // No deposit in progress\n | 'preparing' // Analyzing route & preparing transactions\n | 'swapping' // Converting token (e.g., ETH → USDC)\n | 'bridging' // Cross-chain transfer\n | 'depositing' // Final deposit to HyperLiquid\n | 'success' // Deposit completed successfully\n | 'error'; // Deposit failed at any step\n\nexport type DepositFlowType =\n | 'direct' // Same chain, same token (USDC on Arbitrum)\n | 'swap' // Same chain, different token (ETH → USDC)\n | 'bridge' // Different chain, same token (USDC on Ethereum → Arbitrum)\n | 'swap_bridge'; // Different chain, different token (ETH on Ethereum → USDC on Arbitrum)\n\nexport type DepositStepInfo = {\n totalSteps: number; // Total number of steps in this flow\n currentStep: number; // Current step (0-based index)\n stepNames: string[]; // Human-readable step names\n stepTxHashes?: string[]; // Transaction hashes for each completed step\n};\n\nexport type WithdrawParams = {\n amount: string; // Amount to withdraw\n destination?: Hex; // Destination address (optional, defaults to current account)\n assetId?: CaipAssetId; // Asset to withdraw (defaults to USDC)\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n environmentType?: string; // UI surface. Omitted from events when unset.\n};\n\nexport type WithdrawResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n /** Stable classification for a failed withdrawal. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n withdrawalId?: string; // Unique ID for tracking\n estimatedArrivalTime?: number; // Provider-specific arrival time\n};\n\nexport type TransferBetweenDexsParams = {\n sourceDex: string; // Source DEX name ('' = main DEX, 'xyz' = HIP-3 DEX)\n destinationDex: string; // Destination DEX name ('' = main DEX, 'xyz' = HIP-3 DEX)\n amount: string; // USDC amount to transfer\n};\n\nexport type TransferBetweenDexsResult = {\n success: boolean;\n txHash?: string;\n error?: string;\n /** Stable classification for a failed transfer. */\n errorCode?: PerpsErrorCode;\n /** Provider-tagged details. Raw venue text is excluded. */\n errorDetails?: PerpsErrorDetails;\n};\n\nexport type GetHistoricalPortfolioParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n};\n\nexport type HistoricalPortfolioResult = {\n accountValue1dAgo: string;\n timestamp: number;\n};\n\nexport type LiveDataConfig = {\n priceThrottleMs?: number; // ms between price updates (default: 2000)\n positionThrottleMs?: number; // ms between position updates (default: 5000)\n maxUpdatesPerSecond?: number; // hard limit to prevent UI blocking\n};\n\nexport type PerpsControllerConfig = {\n /**\n * Fallback blocked regions to use when RemoteFeatureFlagController fails to fetch.\n * The fallback is set by default if defined and replaced with remote block list once available.\n */\n fallbackBlockedRegions?: string[];\n /**\n * Fallback HIP-3 equity perps master switch to use when RemoteFeatureFlagController fails to fetch.\n * Controls whether HIP-3 (builder-deployed) DEXs are enabled.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3Enabled?: boolean;\n /**\n * Fallback HIP-3 market allowlist to use when RemoteFeatureFlagController fails to fetch.\n * Empty array = enable all markets (discovery mode), non-empty = allowlist specific markets.\n * Supports wildcards: \"xyz:*\" (all xyz markets), \"xyz\" (shorthand for \"xyz:*\"), \"BTC\" (main DEX market).\n * Only applies when HIP-3 is enabled.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3AllowlistMarkets?: string[];\n /**\n * Fallback HIP-3 market blocklist to use when RemoteFeatureFlagController fails to fetch.\n * Empty array = no blocking, non-empty = block specific markets.\n * Supports wildcards: \"xyz:*\" (block all xyz markets), \"xyz\" (shorthand for \"xyz:*\"), \"BTC\" (block main DEX market).\n * Always applied regardless of HIP-3 enabled state.\n * The fallback is set by default if defined and replaced with remote feature flag once available.\n */\n fallbackHip3BlocklistMarkets?: string[];\n\n /**\n * Override for the maximum allowed deviation of a market's price from its oracle\n * (reference) price before it is reported as untradable (`PriceUpdate.isTradable`),\n * as a decimal fraction (e.g. `0.95` = 95%). Protocol-agnostic: each provider applies\n * its own default when omitted (HyperLiquid uses\n * `HYPERLIQUID_CONFIG.OraclePriceDeviationLimit`, `0.95`). Lets a client tune the\n * threshold without a package release.\n */\n fallbackPriceDeviationLimit?: number;\n\n /**\n * Per-provider credentials and configuration.\n * Nested by provider name so each provider's settings are self-contained\n * and new protocols can be added without polluting the top-level config.\n * Passed from the init file where `process.env.X` is babel-transformed at build time.\n */\n providerCredentials?: PerpsProviderCredentials;\n};\n\nexport type HyperLiquidCredentials = {\n /** Builder fee wallet address for testnet. Empty/omitted = uses BUILDER_FEE_CONFIG default. */\n builderAddressTestnet?: string;\n /** Builder fee wallet address for mainnet. Empty/omitted = uses BUILDER_FEE_CONFIG default. */\n builderAddressMainnet?: string;\n /** Dedicated subscription waiver builder for testnet. */\n subscriptionBuilderAddressTestnet?: string;\n /** Dedicated subscription waiver builder for mainnet. */\n subscriptionBuilderAddressMainnet?: string;\n /**\n * Resolves the agent approved for a main account on a network, or null to\n * sign with the main account (for example while the wallet is locked). Asked\n * when an L1 action (order, cancel, leverage, ...) is signed, unless the\n * account and network are bound through `PerpsController:setAgentSigner`.\n * An agent is kept until `setAgentSigner`, `clearAgentSigners` or a venue\n * rejection; null and failures are asked again at the next L1 action.\n * User-signed actions (builder fee, withdraw, ...) stay on the main account.\n * An agent whose signing throws stays in use: call\n * `PerpsController:clearAgentSigners` when its key locks.\n */\n getAgentSigner?: (\n account: PerpsAgentAccount,\n ) => Promise<PerpsAgentSigner | null>;\n /**\n * Called when the venue rejects an agent (revoked or expired, for example\n * after the user approved another agent under its name). The venue either\n * names the agent as an unknown wallet or answers the request it signed\n * with \"Must deposit before performing actions\"; the latter counts only\n * when `extraAgents` no longer lists the agent, or lists it past its\n * `validUntil` by this device's clock. That list holds named agents, so\n * approve the agent with a name. The provider\n * has dropped it, with a `setAgentSigner` binding to it, and the next L1\n * action asks `getAgentSigner` again, so re-check the approval before\n * answering. The rejected action failed with `KEYRING_LOCKED`. It gets the\n * agent's `address` as the `PerpsAgentSigner` supplied it. It is called\n * once per rejected write, so writes already in flight with the same agent\n * call it again: prompt the user at most once per agent.\n */\n onAgentRejected?: (account: PerpsAgentAccount, agentAddress: Hex) => void;\n};\n\nexport type LighterCredentials = {\n /** Explicit bounded Chase probe on the actual testnet provider; ignored on mainnet. */\n chaseTestnetProbe?: boolean;\n /**\n * How long the Lighter socket stays open after its last listener leaves,\n * in milliseconds (defaults to `LIGHTER_SOCKET_IDLE_CLOSE_MS`, 30 s).\n */\n socketIdleCloseMs?: number;\n /** Whether Lighter provider is enabled via local env var. */\n enabled?: boolean;\n /** Lighter account index override (testnet tooling). */\n accountIndexTestnet?: number;\n accountIndexMainnet?: number;\n /**\n * Preferred trading-key slot (defaults to LIGHTER_DEFAULT_API_KEY_INDEX).\n * Discovery-capable bridges may select another matching or unused slot.\n */\n apiKeyIndex?: number;\n /**\n * Client-owned Lighter signer. The client creates and persists the venue\n * key behind this bridge; Core receives only signing results and public\n * registration data, matching the injected-wallet boundary used by\n * HyperLiquid.\n *\n * Mobile uses an off-screen WebView bridge; headless clients may use an\n * in-process WASM bridge.\n * Optional — without it the Lighter provider is read-only. Lives on the\n * Lighter credentials bag, not PerpsPlatformDependencies, so the shared\n * platform surface stays venue-agnostic.\n */\n signerBridge?: LighterSignerBridge;\n /**\n * Loads the Lighter provider module. Clients whose bundler cannot load the\n * controller's own bundler-ignored import (for example Next.js) pass\n * `() => import('@metamask/perps-controller/providers/lighter')`, so only\n * clients that import that path bundle Lighter. Without it the controller\n * imports the module itself.\n */\n loadProvider?: () => Promise<{ LighterProvider: typeof LighterProvider }>;\n};\n\nexport type PerpsProviderCredentials = {\n hyperliquid?: HyperLiquidCredentials;\n lighter?: LighterCredentials;\n};\n\nexport type PriceUpdate = {\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n price: string; // Current mid price (average of best bid and ask)\n timestamp: number; // Update timestamp\n percentChange24h?: string; // 24h price change percentage\n // Order book data (only available when includeOrderBook is true)\n bestBid?: string; // Best bid price (highest price buyers are willing to pay)\n bestAsk?: string; // Best ask price (lowest price sellers are willing to accept)\n spread?: string; // Ask - Bid spread\n /**\n * The venue's mark price (HyperLiquid `markPx`, Lighter `mark_price`): the\n * price unrealized PnL, margin and liquidation use. Not the oracle price.\n */\n markPrice?: string;\n /**\n * The venue's oracle price (HyperLiquid `oraclePx`, Lighter\n * `index_price`): the reference for the limit-price deviation check\n * (`isPriceOutsideDeviationBand`) and `isTradable`.\n */\n oraclePrice?: string;\n // Market data (only available when includeMarketData is true)\n funding?: number; // Current funding rate\n openInterest?: number; // Open interest in USD\n volume24h?: number; // 24h trading volume in USD\n /**\n * Whether the market is currently tradable. Defaults to `true`.\n *\n * Some markets — most often HIP-3 builder-deployed ones — become temporarily\n * untradable when their market price drifts too far from the oracle price, in which\n * case the protocol rejects orders (HyperLiquid: \"Order price cannot be more than 95%\n * away from the reference price\"). Clients use this to proactively show a \"trading\n * unavailable\" warning instead of letting the order fail on submission.\n *\n * Computed per provider/protocol from that protocol's own rules. It is `false` only\n * when a provider determines the market is currently untradable; a provider that has no\n * such rule, or cannot assess tradability yet (e.g. before the oracle price is cached),\n * reports `true`. The value is always a concrete boolean — never `undefined`.\n */\n isTradable: boolean;\n providerId?: PerpsProviderType; // Multi-provider: price source (injected by aggregator)\n};\n\nexport type OrderFill = {\n orderId: string; // Order ID that was filled\n /**\n * Opaque execution identifier, when the venue exposes one. Compare it for\n * equality only; do not parse it.\n *\n * `orderId` identifies an *order*, not an execution: one order can produce\n * many partial fills that legitimately share it, along with timestamp, size\n * and price. Only this field distinguishes two such executions, so clients\n * deduplicating fills across transports (REST history vs. live websocket)\n * must key on it when present. Each provider builds it from the venue's\n * full trade identity, and emits the same value for one execution on every\n * transport.\n *\n * Optional because not every venue exposes an execution id. When it is\n * absent, a client has no exact identity available and must fall back to\n * matching on fill content, which cannot be exact.\n *\n * Unique within a provider, not across providers: under aggregation two\n * venues can mint the same id independently, so the dedupe key is\n * `(providerId, fillId)` when fills from several providers share one list.\n *\n * Sources: HyperLiquid `coin`, `time` and `tid` (the venue documents\n * `(block_time, coin, tid)` as trade identity; `tid` alone is a 50-bit\n * hash), Lighter `tradeId`.\n */\n fillId?: string;\n symbol: string; // Asset symbol\n side: string; // Normalized order side ('buy' or 'sell')\n size: string; // Fill size\n price: string; // Fill price\n /** Realized PnL reported by the venue; absent means unknown, never zero. */\n pnl?: string;\n direction: string; // Direction of the fill\n fee: string; // Fee paid\n feeToken: string; // Fee token symbol\n timestamp: number; // Fill timestamp\n startPosition?: string; // Start position\n success?: boolean; // Whether the order was filled successfully\n liquidation?: {\n liquidatedUser?: string; // Address of the liquidated user. liquidatedUser isn't always the current user. It can also mean the fill filled another user's liquidation.\n markPx: string; // Mark price at liquidation\n method: string; // Liquidation method (e.g., 'market')\n };\n orderType?: 'take_profit' | 'stop_loss' | 'liquidation' | 'regular';\n detailedOrderType?: string; // Original order type from exchange\n providerId?: PerpsProviderType; // Multi-provider: which provider this fill occurred on (injected by aggregator)\n};\n\n// Parameter interfaces - all fully optional for better UX\nexport type CheckEligibilityParams = {\n blockedRegions: string[]; // List of blocked region codes (e.g., ['US', 'CN'])\n geoLocation: string; // User's geolocation from GeolocationController\n};\n\nexport type GetPositionsParams = {\n /**\n * Skip protection lookup for reads that only need position data.\n *\n * @internal\n */\n includeProtection?: boolean;\n /** Reject unavailable discovery instead of returning an empty position list. */\n throwOnUnavailable?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Optional: include historical positions\n skipCache?: boolean; // Optional: bypass WebSocket cache and force API call (default: false)\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n userAddress?: string; // Optional: required when standalone is true - user address to query positions for\n};\n\nexport type GetAccountStateParams = {\n /**\n * Defaults to the selected account. Providers that cannot query another\n * wallet reject unsupported scopes rather than returning the selected\n * wallet's balance, even when `throwOnUnavailable` is false.\n */\n accountId?: CaipAccountId;\n source?: string; // Optional: source of the call for tracing (e.g., 'health_check', 'initial_connection')\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n /** Required for standalone reads. Unsupported wallet scopes reject as above. */\n userAddress?: string;\n /**\n * Hyperliquid rejects the account read when any DEX or spot clearinghouse\n * read fails. Without this option it can return partial DEX totals.\n * Lighter rejects failed balance reads with or without this option.\n * Ordinary Lighter read failures throw `ACCOUNT_STATE_FAILED` with a cause.\n * Malformed payloads and capability errors propagate. Superseded sessions\n * throw `PROVIDER_LIFECYCLE_STALE`. A confirmed absent Lighter account reads\n * empty. An unavailable cross-margin summary does not invalidate balances.\n */\n throwOnUnavailable?: boolean;\n};\n\nexport type GetUserDataSnapshotParams = {\n userAddress: string;\n identity: {\n provider: 'hyperliquid';\n network: 'mainnet' | 'testnet';\n hip3ConfigVersion: number;\n dexes: string[];\n };\n};\n\nexport type PerpsUserDataSnapshot = {\n positions: Position[];\n orders: Order[];\n accountState: AccountState;\n identity: GetUserDataSnapshotParams['identity'] & { address: string };\n};\n\nexport type GetOrderFillsParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n user?: Hex; // Optional: user address (defaults to selected account)\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n aggregateByTime?: boolean; // Optional: aggregate by time\n};\n\n/**\n * Parameters for getOrFetchFills - optimized cache-first fill retrieval.\n * Subset of GetOrderFillsParams for cache filtering.\n */\nexport type GetOrFetchFillsParams = {\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n symbol?: string; // Optional: filter by symbol\n};\n\nexport type GetOrdersParams = {\n /** Reject unavailable open-order discovery instead of returning an empty list.\n * Strict reads throw OrderDiscoveryError carrying any successfully fetched orders. */\n throwOnUnavailable?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n offset?: number; // Optional: offset for pagination\n skipCache?: boolean; // Optional: bypass WebSocket cache and force API call (default: false)\n standalone?: boolean; // Optional: lightweight mode - skip full initialization, use standalone HTTP client (no wallet/WebSocket needed)\n userAddress?: string; // Optional: required when standalone is true - user address to query orders for\n};\n\n/**\n * Options for cache-aware provider read calls (getOrders, getOrderFills, etc.).\n * Provider-agnostic: providers without inner caches can ignore; providers that\n * cache at the service layer (e.g. HyperLiquid) must honor forceRefresh.\n */\nexport type PerpsReadOptions = {\n /** Bypass any provider-internal cache. Used for user-initiated refresh (pull-to-refresh). */\n forceRefresh?: boolean;\n};\n\nexport type GetFundingParams = {\n accountId?: CaipAccountId; // Optional: defaults to selected account\n startTime?: number; // Optional: start timestamp (Unix milliseconds)\n endTime?: number; // Optional: end timestamp (Unix milliseconds)\n limit?: number; // Optional: max number of results for pagination\n offset?: number; // Optional: offset for pagination\n};\n\nexport type GetSupportedPathsParams = {\n isTestnet?: boolean; // Optional: override current testnet state\n assetId?: CaipAssetId; // Optional: filter by specific asset\n symbol?: string; // Optional: filter by asset symbol (e.g., 'USDC')\n chainId?: CaipChainId; // Optional: filter by chain (CAIP-2 format)\n};\n\n/** Placeholder for future filter/pagination params (e.g., validated, chain). Empty today so the API signature is stable. */\nexport type GetAvailableDexsParams = Record<string, never>;\n\n/** Field to sort markets by. */\nexport type SortField =\n | 'volume'\n | 'priceChange'\n | 'fundingRate'\n | 'openInterest';\n\n/**\n * Field `sortMarkets` sorts on: a {@link SortField}, the current price, or the\n * market name.\n */\nexport type MarketSortField = SortField | 'price' | 'name';\n\n/** Direction for market sorting. */\nexport type SortDirection = 'asc' | 'desc';\n\nexport type GetMarketsParams = {\n symbols?: string[]; // Optional symbol filter (e.g., ['BTC', 'xyz:XYZ100'])\n dex?: string; // HyperLiquid HIP-3: DEX name (empty string '' or undefined for main DEX). Other protocols: ignored.\n skipFilters?: boolean; // Skip market filtering (both allowlist and blocklist, default: false). When true, returns all markets without filtering.\n standalone?: boolean; // Lightweight mode: skip full initialization, only fetch market metadata (no wallet/WebSocket needed). Only main DEX markets returned. Use for discovery use cases like checking if a perps market exists.\n useTerminalApi?: boolean; // When true, enrich provider data from the legacy Terminal market endpoint.\n requireComplete?: boolean; // Reject when part of the venue's list could not be read, instead of leaving it out. Providers that read the list in one request ignore it.\n skipCache?: boolean; // Read the venue's market metadata afresh and refresh the provider's session cache with it. Providers without a metadata cache ignore it.\n};\n\n/**\n * Parameters for {@link PerpsController.getMarketDataWithPrices}.\n * Extends the base market-fetch params with optional category filtering,\n * sorting, and pagination that are applied as post-processing.\n */\nexport type GetMarketDataWithPricesParams = {\n standalone?: boolean; // Lightweight mode: see GetMarketsParams.standalone\n categories?: MarketTypeFilter[]; // Filter to markets matching any of these categories; omit for all markets\n excludeSymbols?: string[]; // Symbols to exclude from results (e.g. the currently viewed market)\n sortBy?: MarketSortField; // Sort results by this field (see sortMarkets)\n direction?: SortDirection; // Sort direction (default: desc)\n limit?: number; // Maximum number of results to return\n useTerminalApi?: boolean; // When true, enrich provider data from the legacy Terminal market endpoint.\n};\n\nexport type SubscribePricesParams = {\n symbols: string[];\n callback: (prices: PriceUpdate[]) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n includeOrderBook?: boolean; // Optional: include bid/ask data from L2 book\n includeMarketData?: boolean; // Optional: include funding, open interest, volume data\n};\n\nexport type SubscribePositionsParams = {\n /** The completeness flag is true for deliveries from the opt-in Hyperliquid stream. */\n callback: (positions: Position[], completeSnapshot?: boolean) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n /** Direct Hyperliquid only. Wait for all configured DEXs to publish positions for this wallet and connection. */\n includeSnapshotStatus?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Future: include historical data\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOrderFillsParams = {\n /**\n * Reports detectable setup failures without asserting an empty account. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error, sourceProviderId?: PerpsProviderType) => void;\n callback: (\n fills: OrderFill[],\n isSnapshot?: boolean,\n sourceProviderId?: PerpsProviderType,\n ) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n since?: number; // Future: only fills after timestamp\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOrdersParams = {\n /**\n * Reports an unavailable orders stream without asserting an empty account.\n * Lighter reports setup failures and loss of signer authentication. Keep the\n * subscription for the next authenticated snapshot.\n */\n onError?: (error: Error, sourceProviderId?: PerpsProviderType) => void;\n /** The completeness flag is true for deliveries from the opt-in Hyperliquid stream. */\n callback: (\n orders: Order[],\n sourceProviderId?: PerpsProviderType,\n completeSnapshot?: boolean,\n ) => void;\n /** Direct Hyperliquid only. Wait for all configured DEXs to publish orders for this wallet and connection. */\n includeSnapshotStatus?: boolean;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n includeHistory?: boolean; // Optional: include filled/canceled orders\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeTwapOrdersParams = {\n /**\n * Receives current and terminal TWAP schedules, newest first — the same\n * shape `getTwapOrders()` returns, so a client can swap a poll for this\n * subscription without reshaping its state.\n *\n * Retention differs from the REST read on purpose: every active schedule is\n * always delivered, while terminal ones are bounded to the most recent 100\n * so a long-lived stream cannot accumulate an account's entire history.\n * Callers needing older terminal schedules should still read\n * `getTwapOrders()`.\n *\n * `isSnapshot` marks the venue's initial full set; later invocations carry\n * the merged result of a delta.\n */\n callback: (twapOrders: TwapOrder[], isSnapshot?: boolean) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Subscription to the merged live TWAP list. */\nexport type SubscribeLiveTwapOrdersParams = {\n /**\n * Receives every known schedule, newest first, whenever the list changes.\n * One read and the venue's pushes are merged here, with execution totals\n * raised from pushed slice fills; split the list with `partitionTwapOrders`.\n */\n callback: (twapOrders: TwapOrder[]) => void;\n /** Called when a read fails; the list keeps its last state. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Subscription to the live chase lists. */\nexport type SubscribeChaseOrderListsParams = {\n /** Receives running and history chase lists whenever they change. */\n callback: (lists: ChaseOrderLists) => void;\n /** Called when a read fails; the lists keep their last state. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * USD amount the venue lets the account commit to a new order on one market,\n * per side. It is the venue's own figure (Hyperliquid: `activeAssetData`\n * `availableToTrade`), so it reflects the market's open position, its\n * unrealized PnL, resting orders and leverage. It differs from the\n * account-wide `AccountState.spendableBalance` whenever those apply.\n */\nexport type PerpsAvailableToTrade = Readonly<{\n /** Provider that reported the value. */\n providerId: PerpsProviderType;\n /** Market the value applies to, as subscribed. */\n symbol: string;\n /** Available to open or increase a long (buy), as a decimal USD string. */\n long: string;\n /** Available to open or increase a short (sell), as a decimal USD string. */\n short: string;\n}>;\n\n/**\n * Subscription to one market's available to trade.\n *\n * The callback receives venue values only. Until the first one arrives the\n * value is unknown and clients should render a placeholder. A provider that\n * cannot read the value from its venue never invokes the callback, so the\n * value stays unknown: no provider computes an estimate.\n */\nexport type SubscribeAvailableToTradeParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n /** Optional: defaults to the selected account. */\n accountId?: CaipAccountId;\n /** Receives each venue update for the market. */\n callback: (availableToTrade: PerpsAvailableToTrade) => void;\n /**\n * Receives a failure to open the stream, or one that stops it after it\n * opened (for example a rejected resubscription). Also invalidates the old\n * venue's value when a default-routed subscription changes providers.\n * The value is unknown again.\n * Not terminal: keep the subscription, since the stream reopens by itself.\n */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeAccountParams = {\n /** Aggregated streams include completeness metadata even when account is null,\n * so consumers can distinguish pending venues from unavailable ones. */\n callback: (\n account: AccountState | null,\n aggregate?: AccountAggregateMetadata,\n ) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /**\n * Optional: emit `null` instead of a snapshot that is missing part of the\n * venue's account, such as a HyperLiquid DEX or the spot balance that has\n * not loaded. Aggregated account streams set it so an incomplete venue is\n * pending or unavailable rather than a complete balance. Callers that omit\n * it keep each venue's lenient default.\n */\n requireCompleteAccount?: boolean;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeOICapsParams = {\n callback: (caps: string[]) => void;\n /**\n * Receives a failure to open the stream or to read its first value. The\n * stream retries by itself; a later delivery means that it recovered.\n */\n onError?: (error: Error) => void;\n accountId?: CaipAccountId; // Optional: defaults to selected account\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue.\n */\n providerId?: PerpsProviderType;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\nexport type SubscribeCandlesParams = {\n symbol: string;\n interval: CandlePeriod;\n duration?: TimeDuration;\n callback: (data: CandleData) => void;\n onError?: (error: Error) => void;\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue — required when two venues\n * list the same symbol and the data must come from a specific one.\n */\n providerId?: PerpsProviderType;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * One public trade on a market (any user's), the same shape for every\n * provider. Prices and sizes are decimal strings, as in `OrderFill`.\n */\nexport type PublicTrade = {\n /**\n * Venue trade id, compared for equality only. Unique within a provider and\n * market, not across providers, so dedupe on `(providerId, symbol, id)`\n * when trades from several providers share a list.\n * Sources: Hyperliquid `coin:time:tid`, its documented trade identity\n * (`tid` alone can repeat across block times), Lighter `trade_id`.\n */\n id: string;\n /** Market symbol the trade belongs to, as the caller requested it. */\n symbol: string;\n /** Execution price. */\n price: string;\n /** Size in the base asset. */\n size: string;\n /** Side of the aggressor (taker): `buy` lifted an ask, `sell` hit a bid. */\n side: 'buy' | 'sell';\n /** Execution time, Unix milliseconds. */\n timestamp: number;\n /** Transaction hash, when the venue reports one. */\n txHash?: string;\n /** Provider whose venue reported the trade. */\n providerId: PerpsProviderType;\n};\n\nexport type GetPublicTradesParams = {\n /** Market symbol (e.g. 'BTC'), as for the other market-data reads. */\n symbol: string;\n /**\n * Maximum number of trades, newest first (default 50). Must be a positive\n * integer. Venues cap the count: Hyperliquid returns its last 10 trades\n * and Lighter at most 100.\n */\n limit?: number;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n};\n\nexport type SubscribePublicTradesParams = {\n /** Market symbol (e.g. 'BTC'), as for the other market-data streams. */\n symbol: string;\n /** Explicit provider route; defaults to the active/default provider. */\n providerId?: PerpsProviderType;\n /**\n * Receives each batch of new trades the venue pushes, newest first. Only a\n * subscription that opens the venue channel may first receive the venue's\n * recent trades; one that joins a market another subscription already\n * streams receives only new trades. Seed the list with `getPublicTrades` and\n * dedupe batches on `id`.\n */\n callback: (trades: PublicTrade[]) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * Single price level in the order book\n */\nexport type OrderBookLevel = {\n /** Price at this level */\n price: string;\n /** Size at this level (in base asset) */\n size: string;\n /** Cumulative size up to and including this level */\n total: string;\n /** Notional value in USD */\n notional: string;\n /** Cumulative notional up to and including this level */\n totalNotional: string;\n};\n\n/**\n * Full order book data with multiple price levels\n */\nexport type OrderBookData = {\n /** Bid levels (buy orders) - highest price first */\n bids: OrderBookLevel[];\n /** Ask levels (sell orders) - lowest price first */\n asks: OrderBookLevel[];\n /** Spread between best bid and best ask */\n spread: string;\n /** Spread as a percentage of mid price */\n spreadPercentage: string;\n /** Mid price (average of best bid and best ask) */\n midPrice: string;\n /** Timestamp of last update */\n lastUpdated: number;\n /** Maximum total size across all levels (for scaling depth bars) */\n maxTotal: string;\n};\n\nexport type SubscribeOrderBookParams = {\n /** Symbol to subscribe to (e.g., 'BTC', 'ETH') */\n symbol: string;\n /**\n * Optional explicit venue route. Omit for the default-routed behavior\n * (subscribes on the current default venue and rebinds when it changes);\n * supply one to pin the stream to that venue.\n */\n providerId?: PerpsProviderType;\n /** Number of levels to return per side (default: 10) */\n levels?: number;\n /** Price aggregation significant figures (2-5, default: 5). Higher = finer granularity */\n nSigFigs?: 2 | 3 | 4 | 5;\n /** Mantissa for aggregation when nSigFigs is 5 (2 or 5). Controls finest price increments */\n mantissa?: 2 | 5;\n /**\n * Enable fast order book updates (5 levels @ ~0.5 s cadence).\n * When omitted, Hyperliquid uses the default cadence (20 levels @ ~2 s).\n * Note: with `fast: true` the widget receives at most 5 levels per side\n * regardless of the `levels` setting.\n */\n fast?: boolean;\n /** Callback function receiving order book updates */\n callback: (orderBook: OrderBookData) => void;\n /** Callback for errors */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** A Cross order to estimate with `estimateCrossLiquidation`. */\nexport type EstimateCrossLiquidationParams = {\n /** Venue market symbol. */\n symbol: string;\n /** Order direction. */\n direction: 'long' | 'short';\n /** Order size in base units, positive. */\n size: string;\n /** Expected fill or limit price, positive. */\n entryPrice: string;\n /** Cross leverage the order sets on the market. */\n leverage: number;\n /**\n * Fee the order pays in USD, taken from the Cross collateral at the fill.\n * Omit for an estimate without the fee. A negative or non-finite fee makes\n * the estimate `unavailable` (`missing_inputs`).\n */\n feeAmountUsd?: number;\n /** Provider that would place the order when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Liquidation price of the Cross position an order would leave. Never a\n * rejection: `none` means no price liquidates it at the account's collateral;\n * `unavailable` says why there is no estimate (`missing_inputs`: an order or\n * market input is invalid or unknown, or the order closes the position;\n * `account_unknown`: the account could not be read or changed during the\n * read; `provider`: the provider or account mode has no Cross estimate).\n */\nexport type CrossLiquidationEstimate =\n | { status: 'price'; price: string }\n | { status: 'none'; reason: 'covered_by_account' }\n | {\n status: 'unavailable';\n reason: 'missing_inputs' | 'account_unknown' | 'provider';\n };\n\nexport type LiquidationPriceParams = {\n entryPrice: number;\n leverage: number;\n direction: 'long' | 'short';\n positionSize?: number; // Optional: for more accurate calculations\n marginType?: 'isolated' | 'cross'; // Optional: defaults to isolated\n asset?: string; // Optional: for asset-specific maintenance margins\n /** Provider that owns the position when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Live position fields required to project a modify. Clients may pass a full\n * {@link Position}; extra fields are ignored.\n */\nexport type PositionModifyPreviewSource = Pick<\n Position,\n | 'symbol'\n | 'size'\n | 'marginUsed'\n | 'liquidationPrice'\n | 'entryPrice'\n | 'leverage'\n | 'positionValue'\n | 'maxLeverage'\n | 'providerId'\n>;\n\n/**\n * Proposed order plus the live position it would modify.\n *\n * Isolated-margin previews model `updateLeverage` before placement: the venue\n * keeps the existing margin and the order margins its own size at\n * `leverage`. Hyperliquid Cross previews margin the whole resulting position\n * at `leverage` and price liquidation against the account's Cross collateral\n * and the maintenance of every Cross position, starting from the position the\n * account holds when it can be read.\n */\nexport type PositionModifyPreviewParams = {\n position: PositionModifyPreviewSource;\n /** Proposed order direction. */\n direction: 'long' | 'short';\n /** Proposed order size in token units. */\n size: string;\n /**\n * Expected fill price for a marketable order, or the resting limit price.\n * Increases and flips require a positive price; a reduce does not.\n * Scale, TWAP, and chase orders should pass the expected fill size and price;\n * this preview models a single fill.\n */\n price: string;\n /**\n * Leverage the provider will set on the asset before placing. Isolated:\n * the order is margined at this leverage and the existing margin is kept.\n * Below the leverage the existing margin can cover, the venue rejects the\n * change and the resulting margin and liquidation price are unavailable.\n * Cross: the whole resulting position is margined at this leverage.\n */\n leverage: number;\n reduceOnly?: boolean;\n /**\n * Estimated trading fees in USD. Deducted from isolated margin, or from\n * Cross collateral, on increases and flips. Omit when unknown: the resulting margin and\n * liquidation price of an increase or flip are then unavailable. Pass 0\n * only for a known zero fee.\n */\n feeAmountUsd?: number;\n /**\n * Explicit venue route. Aggregated providers use this, then\n * `position.providerId`, then the default provider.\n */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Why a projected value is unavailable. `covered_by_account`: no price\n * liquidates the position at the account's collateral. `missing_inputs`: an\n * input the estimate needs is unknown.\n */\nexport type PositionPreviewUnavailableReason =\n | 'covered_by_account'\n | 'missing_inputs';\n\n/**\n * Independently available numeric projection. Margin can be known when\n * liquidation cannot (missing maintenance-tier data, or no liquidation risk).\n * Hyperliquid Cross liquidation previews set `reason`; other previews omit it.\n */\nexport type PositionPreviewValue =\n | { available: true; value: number }\n | { available: false; reason?: PositionPreviewUnavailableReason };\n\nexport type PositionModifyPreviewKind = 'increase' | 'decrease' | 'flip';\n\nexport type PositionModifyPreviewCurrent = {\n margin: PositionPreviewValue;\n liquidationPrice: PositionPreviewValue;\n};\n\nexport type PositionModifyPreviewOpen = {\n status: 'open';\n kind: PositionModifyPreviewKind;\n current: PositionModifyPreviewCurrent;\n resulting: {\n direction: 'long' | 'short';\n /** Resulting token size; always > 0 for `open`. */\n size: number;\n entryPrice: number;\n /**\n * Effective isolated leverage, mark notional / resulting margin. Below the\n * selected leverage when margin kept from before a leverage rise exceeds\n * the new initial margin; the selected leverage when margin is\n * unavailable, and always for a Cross position.\n */\n leverage: number;\n margin: PositionPreviewValue;\n liquidationPrice: PositionPreviewValue;\n };\n};\n\nexport type PositionModifyPreviewFullClose = {\n status: 'full_close';\n current: PositionModifyPreviewCurrent;\n /** Direction of the position being closed. */\n resultingDirection: 'long' | 'short';\n};\n\nexport type PositionModifyPreviewUnsupported = {\n status: 'unsupported';\n /**\n * `cross_margin` comes only from `previewHyperLiquidIsolatedPositionModify`\n * given a Cross position; `previewPositionModify` projects Cross on\n * Hyperliquid.\n */\n reason: 'cross_margin' | 'provider';\n};\n\nexport type PositionModifyPreviewNone = {\n status: 'none';\n};\n\n/**\n * Read-only post-trade position projection.\n *\n * Discriminated on `status` so a non-modifying result cannot carry a\n * flip/full-close kind, and a full close cannot report a remaining size.\n */\nexport type PositionModifyPreviewResult =\n | PositionModifyPreviewNone\n | PositionModifyPreviewUnsupported\n | PositionModifyPreviewFullClose\n | PositionModifyPreviewOpen;\n\nexport type MaintenanceMarginParams = {\n asset: string;\n positionSize?: number; // Optional: for tiered margin systems\n /** Provider that owns the position when calculations are aggregated. */\n providerId?: PerpsProviderType;\n};\n\n/**\n * Context used to resolve the provider that owns order capabilities.\n * `symbol` allows providers to narrow capabilities per market, while\n * `providerId` follows the same explicit-over-default routing as placement.\n */\nexport type GetOrderCapabilitiesParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/** Market and optional route whose current margin-mode lock is requested. */\nexport type GetMarginModeLockParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/** What fixes the asset's margin mode on the venue. */\nexport type MarginModeLockReason = 'position' | 'open_order';\n\n/** Reasons the current margin-mode lock cannot be reported. */\nexport type MarginModeLockUnavailableReason =\n | 'provider_unavailable'\n | 'provider_not_found'\n | 'provider_not_routable'\n | 'not_implemented';\n\n/**\n * Margin mode an asset is bound to on the venue. `locked` means an open\n * position or resting order/TWAP fixes the mode, so orders in the other mode\n * are rejected; `unlocked` means nothing currently fixes the mode. It does not\n * mean the market supports Cross: use `supportedMarginModes` from\n * `getOrderCapabilities` for that.\n */\nexport type PerpsMarginModeLock =\n | Readonly<{\n status: 'locked';\n providerId: PerpsProviderType;\n marginMode: MarginMode;\n reason: MarginModeLockReason;\n }>\n | Readonly<{ status: 'unlocked'; providerId: PerpsProviderType }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: MarginModeLockUnavailableReason;\n }>;\n\n/** Isolated position whose margin adjustment limits are requested. */\nexport type GetMarginAdjustmentLimitsParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol: string;\n providerId?: PerpsProviderType;\n};\n\n/**\n * Why margin adjustment limits cannot be reported: no isolated position on\n * the market, an account that changed or could not be read consistently, or\n * a provider (or account mode) that cannot answer.\n */\nexport type MarginAdjustmentLimitsUnavailableReason =\n | 'no_isolated_position'\n | 'account_unknown'\n | 'provider';\n\n/**\n * Margin the venue lets an isolated position take in (`maxAdd`) and release\n * (`maxRemove`), in USD as decimal strings.\n */\nexport type MarginAdjustmentLimits =\n | { status: 'available'; maxAdd: string; maxRemove: string }\n | { status: 'unavailable'; reason: MarginAdjustmentLimitsUnavailableReason };\n\n/**\n * Stream an isolated position's margin adjustment limits. The callback\n * receives the current limits at once, then each change.\n */\nexport type SubscribeMarginAdjustmentLimitsParams =\n GetMarginAdjustmentLimitsParams & {\n /** Receives the limits, or why they are unavailable. */\n callback: (limits: MarginAdjustmentLimits) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n };\n\n/** Market (or every market, when `symbol` is omitted) whose metadata is requested. */\nexport type GetMarketMetaParams = {\n /** Provider-specific market identifier, including any routing prefix. */\n symbol?: string;\n providerId?: PerpsProviderType;\n};\n\n/** Venue metadata for one market, from the provider's session cache. */\nexport type PerpsMarketMeta = {\n /** Market identifier, including any routing prefix. */\n symbol: string;\n /** Hyperliquid margin tiers, ascending; null when the venue has none. */\n marginTiers: HyperLiquidMarginTier[] | null;\n isDelisted: boolean;\n maxLeverage: number;\n /** Whether the market rejects Cross margin. */\n onlyIsolated: boolean;\n};\n\n/**\n * Stream every market's metadata (margin tiers, delisting, max leverage,\n * Cross support). The callback receives the provider's current list at once,\n * then a new list when the venue's own stream shows a listing or a delisting,\n * and after a reconnect.\n */\nexport type SubscribeMarketMetaParams = {\n /** Provider whose markets are streamed; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives the full market list; never an empty list for a failed read. */\n callback: (markets: PerpsMarketMeta[]) => void;\n /** Receives a failed read; the last list stays current. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * Stream the round trip of the provider's WebSocket keepalive. The callback\n * receives the last measured value at once when there is one, then each new\n * measurement.\n */\nexport type SubscribeConnectionLatencyParams = {\n /** Provider whose connection is measured; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives each round trip in whole milliseconds. */\n callback: (latencyMs: number) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/**\n * A market's post-discount fee rates: what `calculateFees` returns for a\n * taker fill (`isMaker: false`) and a maker fill (`isMaker: true`).\n */\nexport type PerpsFeeRates = {\n /** Market the rates apply to. */\n symbol: string;\n /** The `calculateFees` result for a taker fill. */\n taker: FeeCalculationResult;\n /** The `calculateFees` result for a maker fill. */\n maker: FeeCalculationResult;\n};\n\n/**\n * Stream a market's fee rates for the selected account. The callback receives\n * one read at once, then a new read after one of the account's own fills (its\n * volume tier can change), an account switch, a Rewards change, the expiry of\n * a trading fee grant or `invalidateSubscriptionBenefits`. There is no\n * repeating timer.\n */\nexport type SubscribeFeeRatesParams = {\n /** Market, including any routing prefix. */\n symbol: string;\n /**\n * Order type both rates are priced for. Omitted, the taker rate is priced\n * as `market` and the maker rate as `limit`.\n */\n orderType?: OrderType;\n /** Provider whose fees are read; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Order amount in USD to price, as in `calculateFees`. */\n amount?: string;\n /** Receives the rates; unchanged reads are not delivered again. */\n callback: (rates: PerpsFeeRates) => void;\n /** Receives a failed read; the last rates stay current. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Told when a venue's markets may have changed; see `PerpsProvider`. */\nexport type SubscribeMarketChangesParams = {\n /** Provider whose markets are watched; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Called on each change; read the markets again. */\n callback: () => void;\n /** Receives a failure to open the venue's feed. */\n onError?: (error: Error) => void;\n};\n\n/** Told when the account's chases may have changed; see `PerpsProvider`. */\nexport type SubscribeChaseOrderChangesParams = {\n /** Called on each change; read the chases again. */\n callback: () => void;\n};\n\n/**\n * Whether an account's trading agent is valid for the venue:\n * - `not_required`: the venue, or this host, signs trades without an agent.\n * - `valid`: the venue lists the agent; `validUntil` is its expiry in epoch\n * milliseconds, or null when it does not expire.\n * - `invalid`: `no_agent` (none is set or resolved for the account),\n * `not_approved` (the venue does not list it), `expired` (listed past its\n * `validUntil` by this device's clock) or `rejected` (the venue refused a\n * request it signed).\n * - `unknown`: the account or the venue's agent list could not be read.\n */\nexport type PerpsTradingAgentValidity =\n | { status: 'not_required' }\n | { status: 'valid'; agentAddress: Hex; validUntil: number | null }\n | {\n status: 'invalid';\n reason: 'no_agent' | 'not_approved' | 'expired' | 'rejected';\n agentAddress?: Hex;\n }\n | { status: 'unknown'; reason: 'account_unknown' | 'read_failed' };\n\n/** Stream whether an account's trading agent is valid for the venue. */\nexport type SubscribeTradingAgentValidityParams = {\n /** Account to check; defaults to the selected account, following switches. */\n accountId?: CaipAccountId;\n /** Provider whose agent is checked; defaults to the active route. */\n providerId?: PerpsProviderType;\n /** Receives the validity; unchanged values are not delivered again. */\n callback: (validity: PerpsTradingAgentValidity) => void;\n /** Receives a failure to open the stream. */\n onError?: (error: Error) => void;\n /** Minimum time between deliveries to this subscriber; other subscribers of the same channel are unaffected. */\n throttleMs?: number;\n /** Called when the stream moves to another provider or account; the next delivery is the new context's data. */\n onReset?: () => void;\n};\n\n/** Parameters of each `PerpsController.subscribeTo*` stream, by stream name. */\nexport type PerpsStreamParams = {\n account: SubscribeAccountParams;\n availableToTrade: SubscribeAvailableToTradeParams;\n candles: SubscribeCandlesParams;\n chaseOrderLists: SubscribeChaseOrderListsParams;\n connectionLatency: SubscribeConnectionLatencyParams;\n feeRates: SubscribeFeeRatesParams;\n liveTwapOrders: SubscribeLiveTwapOrdersParams;\n marginAdjustmentLimits: SubscribeMarginAdjustmentLimitsParams;\n marketMeta: SubscribeMarketMetaParams;\n oiCaps: SubscribeOICapsParams;\n orderBook: SubscribeOrderBookParams;\n orderFills: SubscribeOrderFillsParams;\n orders: SubscribeOrdersParams;\n positions: SubscribePositionsParams;\n prices: SubscribePricesParams;\n publicTrades: SubscribePublicTradesParams;\n tradingAgentValidity: SubscribeTradingAgentValidityParams;\n twapOrders: SubscribeTwapOrdersParams;\n};\n\n/** Name of a `PerpsController.subscribeTo*` stream. */\nexport type PerpsStreamName = keyof PerpsStreamParams;\n\n/**\n * The parameters that pick a stream's channel: the `subscribeTo*` parameters\n * without callbacks and throttle.\n */\nexport type PerpsStreamSnapshotParams<Stream extends PerpsStreamName> = Omit<\n PerpsStreamParams[Stream],\n 'callback' | 'onError' | 'onReset' | 'throttleMs'\n>;\n\n/** The arguments a stream's callback last received. */\nexport type PerpsStreamSnapshot<Stream extends PerpsStreamName> = Parameters<\n PerpsStreamParams[Stream]['callback']\n>;\n\n/** Inputs for a provider-normalized Scale price ladder preview. */\nexport type GetScalePriceLadderParams = {\n /** Market symbol, including its provider route when applicable. */\n symbol: string;\n /** Lowest raw price in the ladder. */\n minPrice: number;\n /** Highest raw price in the ladder. */\n maxPrice: number;\n /** Number of ladder rungs. */\n count: number;\n /** Optional explicit route; omitted uses the active/default provider. */\n providerId?: PerpsProviderType;\n /**\n * Optional exact base size or maximum quote budget, with a rung-size skew.\n * Providers without sizing support leave `sizingPreview` absent.\n */\n sizing?: Readonly<\n (\n | { size: string; usdAmount?: never }\n | { usdAmount: string; size?: never }\n ) & {\n skew?: number;\n }\n >;\n};\n\n/** Reasons provider-owned order capabilities are unavailable for a market. */\nexport type DirectProviderOrderCapabilitiesUnavailableReason =\n | 'provider_unavailable'\n | 'invalid_symbol'\n | 'market_not_found'\n | 'order_market_unsupported'\n | 'strategy_market_unsupported';\n\nexport type RoutedOrderCapabilitiesUnavailableReason =\n | 'provider_not_found'\n | 'provider_not_routable'\n | 'not_implemented';\n\nexport type OrderCapabilitiesUnavailableReason =\n | DirectProviderOrderCapabilitiesUnavailableReason\n | RoutedOrderCapabilitiesUnavailableReason;\n\n/**\n * Price grid a market accepts. `significant_figures` (HyperLiquid): at most\n * `maxSignificantFigures` significant figures and `maxDecimals` decimals;\n * integer prices are always valid. `fixed_decimals` (Lighter): every price is\n * a multiple of `tickSize`, which is `10^-decimals`.\n */\nexport type PerpsPricePrecision =\n | Readonly<{\n type: 'significant_figures';\n maxSignificantFigures: number;\n maxDecimals: number;\n }>\n | Readonly<{\n type: 'fixed_decimals';\n decimals: number;\n /** Decimal string, e.g. \"0.01\". */\n tickSize: string;\n }>;\n\n/**\n * Order limits the provider enforces for a market. Each optional field is\n * omitted when the venue does not report it; clients must not fall back to\n * another venue's value.\n */\nexport type PerpsOrderLimits = Readonly<{\n /** Decimals a base-asset size may carry. */\n sizeDecimals: number;\n /** Minimum value of one order in USD. */\n minOrderNotionalUsd?: number;\n /** Minimum base-asset size of one order, as a decimal string. */\n minOrderSize?: string;\n /**\n * Orders the reported placement minimums apply to. Lighter reports\n * `resting_limit_orders` even when its maker minimums are unavailable.\n * Market and IOC orders there can go down to one size step.\n * A verified full close can qualify for a minimum-order exception.\n * The venue's size grid still applies.\n */\n minimumAppliesTo?: 'all_orders' | 'resting_limit_orders';\n /** Rung count bounds of a Scale placement; present when Scale is supported. */\n scaleOrderCount?: Readonly<{ min: number; max: number }>;\n /** TWAP bounds; present when TWAP is supported. */\n twap?: Readonly<{\n minDurationMinutes: number;\n maxDurationMinutes: number;\n /** Minimum total TWAP value in USD. */\n minNotionalUsd: number;\n }>;\n /**\n * Furthest a limit price may sit from the oracle price, as a fraction\n * (0.95 = 95%): a price `p` is rejected when\n * `|p - oracle| / oracle > maxOraclePriceDeviation`, the rule\n * `isMarketTradable` also applies. Check it with\n * `isPriceOutsideDeviationBand`.\n */\n maxOraclePriceDeviation?: number;\n}>;\n\n/**\n * Venue rules for the strategies a market supports, in venue-neutral units.\n * Read them with `getStrategyRules`; a strategy absent from\n * `supportedStrategies` has no rules and is unsupported on that market.\n */\nexport type PerpsStrategyRules = Readonly<{\n twap?: Readonly<{\n /** Shortest running time the venue accepts, in whole minutes. */\n minDurationMinutes: number;\n /** Longest running time the venue accepts, in whole minutes. */\n maxDurationMinutes: number;\n /** Smallest total TWAP value the venue accepts, in USD. */\n minNotionalUsd: number;\n /** Seconds between two suborders. */\n sliceIntervalSeconds: number;\n }>;\n chase?: Readonly<{\n /** Most chases that may run at once; omitted means no venue cap. */\n maxActiveSessions?: number;\n /** Poll interval used when the caller sets none, in milliseconds. */\n defaultIntervalMs: number;\n /** Shortest poll interval accepted, in milliseconds. */\n minIntervalMs: number;\n }>;\n scale?: Readonly<{\n /** Fewest rungs a ladder may have. */\n minOrders: number;\n /** Most rungs a ladder may have. */\n maxOrders: number;\n }>;\n}>;\n\ntype ReadyPerpsOrderCapabilities = Readonly<{\n status: 'ready';\n providerId: PerpsProviderType;\n supportedStrategies: readonly StrategyOrderType[];\n /** Price grid for this market. Omitted means not reported. */\n pricePrecision?: PerpsPricePrecision;\n /** Size, value, Scale and TWAP limits. Omitted means not reported. */\n orderLimits?: PerpsOrderLimits;\n /** Venue rules for the supported strategies; omitted means unreported. */\n strategyRules?: PerpsStrategyRules;\n /**\n * Standalone stop/take-profit placements this market's provider executes.\n * Omitted means support is not reported; clients must not infer support\n * from the provider name. Attached or position TP/SL is a separate contract.\n */\n supportedTriggerOrderTypes?: readonly TriggerOrderType[];\n /**\n * Position protection mutation guarantees. Omitted means unsupported or\n * unreported. Accepted updates can still omit IDs when exact correlation\n * remains unresolved; clients must not infer identities from book changes.\n */\n positionTpsl?: Readonly<{\n supportsExpectedPosition: true;\n childOrderIds: 'request-correlated';\n takeProfitOrderType: 'take_profit_market' | 'take_profit_limit';\n stopLossOrderType: 'stop_market' | 'stop_limit';\n /** Coverage when the caller omits explicit TP/SL sizes. */\n defaultCoverage?: 'position-snapshot' | 'dynamic-position';\n /** Fixed positive quantities; omitted means support is unreported. */\n partialCoverage?: Readonly<{\n /** When reported, a single explicitly sized leg is supported. */\n single: true;\n /** Equal native OCO quantities, or independently sized sibling triggers. */\n pair: 'equal-quantity-oco' | 'independent';\n /** Explicit alternatives; absent permits only the declared default pair. */\n supportedPairs?: readonly ('equal-quantity-oco' | 'independent')[];\n /** Prior selected protection is canceled before replacement creation. */\n replacement: 'cancel-before-create';\n /** Explicit recovery ID/current intent, or the provider's existing recovery policy. */\n recovery: 'explicit-current-position-intent' | 'provider-default';\n }>;\n }>;\n\n /**\n * Margin modes the market accepts for `OrderParams.marginMode`. Omitted\n * means the provider does not report it, and clients should not offer an\n * explicit margin mode.\n */\n supportedMarginModes?: readonly MarginMode[];\n /** Why a market that reports margin modes prohibits Cross. */\n crossMarginUnavailableReason?: 'noCross' | 'strictIsolated' | 'isolatedOnly';\n /**\n * HyperLiquid margin tiers for the market, lowest notional first, read from\n * the venue's `meta` (`marginTableId` resolved against `marginTables`). Pass\n * them to the liquidation and margin estimates. Omitted when the venue does\n * not use tiers (Lighter) or the table cannot be resolved.\n */\n marginTiers?: HyperLiquidMarginTier[];\n /**\n * Most take-profit and most stop-loss legs one order can attach\n * (`OrderParams.takeProfitPrice` / `stopLossPrice`). Omitted means not\n * reported; clients must not assume another venue's limit.\n */\n attachedTpslGroupLimit?: Readonly<{\n takeProfit: number;\n stopLoss: number;\n }>;\n attachedTpsl?: Readonly<{\n submission: 'native-oto-otoco';\n childCoverage: 'venue-native-zero-size';\n partialSizes: false;\n lifecycleVerification: 'pending';\n cancellation: 'explicit-exact-owned-orders';\n }>;\n}>;\n\nexport type DirectProviderOrderCapabilities =\n | ReadyPerpsOrderCapabilities\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: DirectProviderOrderCapabilitiesUnavailableReason;\n }>;\n\nexport type PerpsOrderCapabilities =\n | ReadyPerpsOrderCapabilities\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: OrderCapabilitiesUnavailableReason;\n }>;\n\n/** Reasons a direct provider cannot produce a Scale price ladder. */\nexport type DirectProviderScalePriceLadderUnavailableReason = Exclude<\n DirectProviderOrderCapabilitiesUnavailableReason,\n 'strategy_market_unsupported' | 'order_market_unsupported'\n>;\n\n/** Reasons a provider-routed Scale price ladder cannot be produced. */\nexport type ScalePriceLadderUnavailableReason =\n | DirectProviderScalePriceLadderUnavailableReason\n | RoutedOrderCapabilitiesUnavailableReason;\n\n/** Result of provider-routed Scale price normalization. */\nexport type PerpsScalePriceLadder =\n | Readonly<{\n status: 'ready';\n providerId: PerpsProviderType;\n prices: readonly string[];\n /**\n * Exact venue-valid rung quantities when sizing is supported and requested.\n * This previews maker minimums and exposure, not account trading readiness.\n */\n sizingPreview?: Readonly<{\n sizes: readonly string[];\n totalSize: string;\n totalNotional: string;\n minimumBaseSize: string;\n minimumQuoteAmount: string;\n sizeDecimals: number;\n }>;\n }>\n | Readonly<{\n status: 'unavailable';\n providerId?: PerpsProviderType;\n reason: ScalePriceLadderUnavailableReason;\n }>;\n\nexport type FeeCalculationParams = {\n // Trigger placements are charged as their execution kind (a stop_limit pays\n // limit-order fees when it fills, a stop_market pays taker fees).\n orderType: OrderType;\n isMaker?: boolean;\n amount?: string;\n symbol: string; // Required: Asset identifier for HIP-3 fee calculation (e.g., 'BTC', 'xyz:TSLA')\n // Optional provider override. Omission uses active/default routing.\n providerId?: PerpsProviderType;\n // Read the account's venue rates again instead of a cached copy.\n skipCache?: boolean;\n};\n\nexport type FeeCalculationResult = {\n // Total fees (protocol + MetaMask)\n feeRate?: number; // Total fee rate as decimal (e.g., 0.00145 for 0.145%), undefined when unavailable\n feeAmount?: number; // Total fee amount in USD (when amount is provided)\n // Protocol-specific base fees\n protocolFeeRate?: number; // Protocol fee rate (e.g., 0.00045 for HyperLiquid taker), undefined when unavailable\n protocolFeeAmount?: number; // Protocol fee amount in USD\n\n // MetaMask builder/revenue fee\n metamaskFeeRate?: number; // MetaMask fee rate (e.g., 0.001 for 0.1%), undefined when unavailable. Already discounted: do not apply `metamaskFeeDiscountBips` to it again\n metamaskFeeAmount?: number; // MetaMask fee amount in USD\n\n /**\n * Whether this placement can carry a MetaMask builder fee at all.\n *\n * A `metamaskFeeRate` of zero is ambiguous on its own: it is what a venue or\n * order type that has no builder field reports (`false` here), and also what\n * a fully waived discount leaves behind (`true` here). Only the provider\n * knows which, so it says so rather than leaving callers to guess from the\n * number. Absent when the provider does not report a policy.\n */\n chargesMetamaskBuilderFee?: boolean;\n\n /**\n * Fee source whose rate the MetaMask fee above was priced from: the winner\n * of the unified fee resolution this quote was computed with.\n *\n * Absent when the quote was not re-priced from a resolution, e.g. a\n * placement that carries no MetaMask builder fee. `subscription` always\n * implies a reduced fee. `rewards` can win a tie with the default, so it may\n * carry a 0% discount; check `metamaskFeeRate` before presenting it as a\n * reduction.\n *\n * Describes this preview only. The submit path resolves the fee again, so\n * the order is attributed to whichever source wins at submission.\n */\n feeSource?: PerpsFeeSource;\n\n /**\n * Discount the `feeSource` winner applied, in basis points off the default\n * MetaMask builder fee (e.g. 6500 for 65% off). `0` when no reduction\n * applied: when `default` won, or when `rewards` won with a 0% discount. A\n * `feeSource` other than `default` therefore does not imply a discount; check\n * this value instead.\n *\n * Already applied: `metamaskFeeRate` is `undiscountedMetamaskFeeRate`\n * reduced by this discount and floored to the tenth of a basis point the\n * venue charges. Do not discount `metamaskFeeRate` again. The floor can make\n * the actual reduction slightly larger than this figure, so derive savings\n * amounts from the two rates.\n *\n * Absent under the same rule as `feeSource`.\n */\n metamaskFeeDiscountBips?: number;\n\n /**\n * MetaMask fee rate before `metamaskFeeDiscountBips` was applied, as a\n * decimal (e.g. 0.001 for 0.1%). Equal to `metamaskFeeRate` when no discount\n * applied. Use it to show the original fee next to the discounted one;\n * `metamaskFeeRate` is the rate the order is charged.\n *\n * Absent under the same rule as `feeSource`.\n */\n undiscountedMetamaskFeeRate?: number;\n\n // Optional detailed breakdown for transparency\n breakdown?: {\n baseFeeRate: number;\n volumeTier?: string;\n volumeDiscount?: number;\n stakingDiscount?: number;\n };\n\n /**\n * Read-only subscription fee-waiver preview, sourced from the same cached\n * benefits snapshot the fee resolver uses. Present only when the controller\n * has a subscription source wired.\n *\n * Surfacing this never mutates the cap or the cache. The rates above *are*\n * adjusted from the unified fee resolution — including this waiver when it\n * wins — so they reflect what the order will be charged rather than the\n * undiscounted builder fee. Pass `FeeCalculationParams.amount` to get the\n * rate an order of that size actually pays.\n */\n subscription?: PerpsSubscriptionFeeWaiverStatus;\n};\n\n/**\n * Usage state of the perps fee waiver on a subscription benefits snapshot.\n */\nexport type PerpsSubscriptionUsage = 'available' | 'exhausted';\n\n/**\n * Subscription benefits as returned by `GET /v1/profiles/{profileId}/benefits`.\n *\n * The perps controller never performs this request itself — the client owns the\n * Profile JWT and injects the read through\n * {@link PerpsPlatformDependencies.subscription}. Only the fields the perps fee\n * waiver depends on are modelled here.\n */\nexport type PerpsSubscriptionBenefits = {\n /** Subscription status; only `active` can pass the eligibility gate. */\n status: string;\n\n /** Perps fee waiver entitlement and its remaining allowance. */\n perpsFeeWaiver?: {\n /** Whether the plan entitles this profile to the perps fee waiver. */\n entitled: boolean;\n\n /** Backend usage state; only `available` can pass the eligibility gate. */\n usage?: PerpsSubscriptionUsage;\n\n /**\n * Set by the backend once the notional cap is crossed. Honored on the next\n * cache refresh — there is no client-held reservation to release.\n */\n exhausted?: boolean;\n\n /** Notional (USD) still covered by the waiver, for fee previews. */\n remainingNotionalUsd?: number;\n };\n};\n\n/**\n * Why the subscription fee waiver did or did not apply, plus the remaining\n * allowance for fee previews. Derived purely from the cached benefits snapshot.\n */\nexport type PerpsSubscriptionFeeWaiverStatus = {\n /** True only when every condition of the eligibility gate passed. */\n eligible: boolean;\n\n /**\n * Gate outcome:\n * - `eligible` — every condition passed\n * - `no-source` — no subscription dependency is wired\n * - `not-hydrated` — nothing cached yet; a refresh was kicked off\n * - `stale` — the cached snapshot is past the hard-stale ceiling\n * - `no-subscription` — the read succeeded but reported no subscription at\n * all (signed out, or no profile)\n * - `inactive` — subscription status is not `active`\n * - `not-entitled` — the plan does not include the perps fee waiver\n * - `exhausted` — the backend reported the notional cap as spent\n */\n reason:\n | 'eligible'\n | 'no-source'\n | 'not-hydrated'\n | 'stale'\n | 'no-subscription'\n | 'inactive'\n | 'not-entitled'\n | 'exhausted';\n\n /** Notional (USD) still covered by the waiver, when the backend reports it. */\n remainingNotionalUsd?: number;\n};\n\n/**\n * Fee source that won the unified resolver.\n *\n * `rewards` covers the account-scoped VIP and season discount. `grant` is an\n * independent route-scoped trading-fee grant supplied by RewardsController.\n */\nexport type PerpsFeeSource = 'default' | 'rewards' | 'grant' | 'subscription';\n\n/**\n * Provider route for resolving route-specific fee candidates.\n */\nexport type PerpsFeeResolverScope = {\n providerId: string;\n isTestnet: boolean;\n};\n\n/**\n * Independent RewardsController fee candidate for one exact provider route.\n */\nexport type PerpsTradingFeeGrant = PerpsFeeResolverScope & {\n /** Absolute MetaMask builder fee, in basis points. */\n feeBips: number;\n\n /** Expiry as a Unix timestamp in milliseconds. */\n expiresAt: number;\n};\n\n/**\n * Outcome of the unified fee resolver.\n */\nexport type PerpsFeeResolution = {\n /** Winning MetaMask builder fee, in basis points (lowest across sources). */\n feeBips: number;\n\n /**\n * Winning fee expressed as a discount off the default builder fee, in basis\n * points — the unit providers consume. `undefined` when no source resolved\n * (e.g. rewards state has not hydrated and no subscription waiver applies),\n * so callers do not treat it as a definitive \"no discount\" answer.\n */\n discountBips: number | undefined;\n\n /** Source that produced the winning fee. */\n source: PerpsFeeSource;\n\n /** Subscription gate outcome, always populated for observability. */\n subscription: PerpsSubscriptionFeeWaiverStatus;\n\n /**\n * How much of the order the subscription allowance covered, when the\n * subscription source won.\n *\n * `full` waives the whole MetaMask builder fee; `partial` charges the fee on\n * the share the allowance did not cover. Absent when another source won.\n */\n subscriptionWaiverKind?: 'full' | 'partial';\n\n /**\n * Order notional (USD) the subscription allowance covered, when the backend\n * bounded the allowance and the caller supplied an order notional.\n */\n subscriptionCoveredNotionalUsd?: number;\n};\n\nexport type UpdatePositionTPSLParams = {\n /**\n * Optional mutation precondition, checked against authoritative position data\n * before setup and again before protection writes. Size is signed base units.\n * A mismatch rejects the update rather than protecting a different position.\n */\n expectedPosition?: { size: string; entryPrice: string };\n symbol: string; // Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA')\n takeProfitPrice?: string; // Optional: undefined to remove\n stopLossPrice?: string; // Optional: undefined to remove\n // Partial TP/SL: quantity covered by the TP/SL order. Omit to cover the whole\n // position. When either size is provided the TP/SL orders are placed as\n // standalone reduce-only triggers, since a position-bound TP/SL cannot carry a\n // quantity.\n takeProfitSize?: string;\n stopLossSize?: string;\n /** Pair-only opt-in for partial position coverage; omission keeps the provider default. */\n partialPairLinkage?: 'equal-quantity-oco' | 'independent';\n /**\n * HyperLiquid: max slippage in basis points for a whole-position market leg. Omit\n * to use the saved `maxSlippageBps` preference, else the 10% TP/SL default.\n */\n maxSlippageBps?: number;\n // Optional tracking data for MetaMetrics events\n trackingData?: TPSLTrackingData;\n providerId?: PerpsProviderType; // Multi-provider: optional provider override for routing\n /**\n * Optional caller snapshot for diagnostics.\n *\n * The provider always resolves the position from the current DEX WebSocket\n * slice or an HTTP read. It never uses this snapshot for trigger size or side.\n * If neither authoritative source answers, the update fails with\n * `PROVIDER_NOT_AVAILABLE`.\n */\n position?: Position;\n};\n\n/** One side of a position's protection: take profit or stop loss. */\nexport type PositionTPSLLeg = 'tp' | 'sl';\n\nexport type ReplacePositionTPSLLegParams = {\n /** Asset identifier (e.g., 'BTC', 'ETH', 'xyz:TSLA'). */\n symbol: string;\n /** The leg to replace. The other leg is left as it is. */\n leg: PositionTPSLLeg;\n /** New trigger price for the leg. */\n triggerPrice: string;\n /**\n * Price the leg fills at once triggered. Omit to execute at market when the\n * trigger fires.\n */\n limitPrice?: string;\n /**\n * Max slippage in basis points for a market leg (no `limitPrice`). Omit to\n * use the saved `maxSlippageBps` preference, else the 10% TP/SL default.\n */\n maxSlippageBps?: number;\n /**\n * Optional mutation precondition, checked against authoritative position data\n * before setup and again before protection writes. Size is signed base units.\n */\n expectedPosition?: { size: string; entryPrice: string };\n /** Optional tracking data for MetaMetrics events. */\n trackingData?: TPSLTrackingData;\n /** Multi-provider: optional provider override for routing. */\n providerId?: PerpsProviderType;\n};\n\nexport type Order = {\n orderId: string; // Order ID\n symbol: string; // Asset symbol (e.g., 'ETH', 'BTC')\n side: 'buy' | 'sell'; // Normalized order side\n orderType: OrderType; // Order type (market/limit)\n size: string; // Order size\n originalSize: string; // Original order size\n price: string; // Order price (for limit orders)\n filledSize: string; // Amount filled\n remainingSize: string; // Amount remaining\n status: 'open' | 'filled' | 'canceled' | 'rejected' | 'triggered' | 'queued'; // Normalized status\n timestamp: number; // Order timestamp\n lastUpdated?: number; // Last status update timestamp (optional - not provided by all APIs)\n // TODO: Consider creating separate type for OpenOrders (UI Orders) potentially if optional properties muddy up the original Order type\n takeProfitPrice?: string; // Take profit price (if set)\n stopLossPrice?: string; // Stop loss price (if set)\n stopLossOrderId?: string; // Stop loss order ID\n takeProfitOrderId?: string; // Take profit order ID\n detailedOrderType?: string; // Full order type from exchange (e.g., 'Take Profit Limit', 'Stop Market')\n isTrigger?: boolean; // Whether this is a trigger order (TP/SL)\n // Normalized trigger placement type, set for trigger orders only. `orderType`\n // above stays coarse (how the order executes) so existing consumers keep\n // their meaning; this field carries the full placement type.\n triggerOrderType?: TriggerOrderType;\n reduceOnly?: boolean; // Whether this is a reduce-only order\n isPositionTpsl?: boolean; // Whether this TP/SL is associated with the full position\n parentOrderId?: string; // Parent order ID for display-only synthetic TP/SL rows\n isSynthetic?: boolean; // Whether this order is synthetic (display-only, cancelable only when linked to a real child order ID)\n triggerPrice?: string; // Trigger condition price for trigger orders (e.g., TP/SL trigger level)\n strategyGroupId?: string; // Recoverable strategy handle shared by related venue orders\n providerId?: PerpsProviderType; // Multi-provider: which provider this order is on (injected by aggregator)\n};\n\nexport type Funding = {\n symbol: string; // Asset symbol (e.g., 'ETH', 'BTC')\n amountUsd: string; // Funding amount in USD (positive = received, negative = paid)\n rate?: string; // Funding rate applied (undefined when not available from provider)\n timestamp: number; // Funding payment timestamp\n transactionHash?: string; // Optional transaction hash\n};\n\n/**\n * A provider-owned reason that the selected account cannot submit Perps\n * actions through a route.\n */\nexport type PerpsAccountUnsupportedReason = 'multi_sig_account';\n\n/**\n * Whether the selected account can submit Perps actions through a provider.\n */\nexport type PerpsAccountSupport =\n | { isSupported: true }\n | {\n isSupported: false;\n reason: PerpsAccountUnsupportedReason;\n };\n\n/**\n * Selects the provider route whose account support should be checked.\n */\nexport type GetAccountSupportParams = {\n providerId?: PerpsProviderType;\n};\n\n/** Selects the venue whose registration should be checked. */\nexport type GetExchangeAccountStatusParams = { providerId: PerpsProviderType };\n\n/** The selected wallet's venue registration and, when applicable, master index. */\nexport type ExchangeAccountStatus =\n | { registered: true; accountIndex?: number }\n | { registered: false };\n\n/**\n * Selects the provider route whose withdrawal destination should be resolved.\n * Accepts the same optional route `withdraw` accepts.\n */\nexport type ResolveWithdrawalRouteParams = {\n providerId?: PerpsProviderType;\n};\n\n/**\n * The venue a withdrawal will sign on, or the same refusal `withdraw` returns\n * when several venues are registered and no route is named.\n */\nexport type WithdrawalRoute =\n | { status: 'resolved'; providerId: PerpsProviderType }\n | {\n status: 'route_required';\n error: Extract<PerpsErrorCode, 'PROVIDER_ROUTE_REQUIRED'>;\n };\n\nexport type PerpsProvider = {\n /** Local durable Scale inventory; unsupported providers omit the methods. */\n getScaleOrderGroups?(): Promise<ScaleOrderGroup[]>;\n /** Explicit read-only venue reconciliation, without placement replay. */\n reviewScaleOrderGroups?(params?: {\n providerId?: PerpsProviderType;\n }): Promise<ScaleOrderGroup[]>;\n\n readonly protocolId: string;\n\n /** Whether this provider routes individual requests by `providerId`. */\n readonly routesOrdersByProviderId?: boolean;\n\n /**\n * Return whether the selected account can submit actions through this\n * provider. Providers that omit this hook are treated as supported.\n */\n getAccountSupport?(\n params?: GetAccountSupportParams,\n ): Promise<PerpsAccountSupport>;\n\n /**\n * Check the selected wallet’s venue registration once, without signing.\n * Omit this hook for venues with no registration step.\n */\n getExchangeAccountStatus?(\n params: GetExchangeAccountStatusParams,\n ): Promise<ExchangeAccountStatus>;\n\n /**\n * Return order capabilities for the provider/market route. Providers may\n * omit this hook; the controller then reports capabilities as unavailable.\n */\n getOrderCapabilities?(\n params: GetOrderCapabilitiesParams,\n ): Promise<PerpsOrderCapabilities>;\n\n /**\n * Return the margin mode the market is currently locked to by an open\n * position or resting order. Providers may omit this hook; the controller\n * then reports the lock as unavailable.\n *\n * @param params - Market and optional provider route.\n * @returns The current lock, or a typed unavailable result.\n */\n getMarginModeLock?(\n params: GetMarginModeLockParams,\n ): Promise<PerpsMarginModeLock>;\n\n /**\n * Stream an isolated position's margin adjustment limits from the\n * provider's live account and position streams, without venue reads.\n * The callback receives the current limits at once, then each change.\n * Providers without it are reported as `unavailable`/`provider`.\n *\n * @param params - Market, optional route, callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToMarginAdjustmentLimits?(\n params: SubscribeMarginAdjustmentLimitsParams,\n ): () => void;\n\n /**\n * Stream the round trip of the provider's WebSocket keepalive, in whole\n * milliseconds, measured on the keepalive the transport already sends.\n * Providers without one never call back.\n *\n * @param params - Callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToConnectionLatency?(\n params: SubscribeConnectionLatencyParams,\n ): () => void;\n\n /**\n * Report whether the account's trading agent is valid for the venue. The\n * callback receives one read at once, then a new value on events only: an\n * agent set or cleared, a venue rejection of the agent, and the agent's\n * `validUntil` expiry (one timeout at the deadline). Providers without it\n * have no agent step, and the controller reports `not_required`.\n *\n * @param params - Optional account and route, callback and error handler.\n * @returns A cleanup function to unsubscribe.\n */\n subscribeToTradingAgentValidity?(\n params: SubscribeTradingAgentValidityParams,\n ): () => void;\n\n /**\n * Return how much margin an isolated position can take in and release.\n * Providers may omit this hook; the controller then reports the limits as\n * unavailable.\n *\n * @param params - Market and optional provider route.\n * @returns The limits, or a typed unavailable result.\n */\n getMarginAdjustmentLimits?(\n params: GetMarginAdjustmentLimitsParams,\n ): Promise<MarginAdjustmentLimits>;\n\n /**\n * Normalize a Scale ladder using the selected provider's venue rules.\n *\n * @param params - Market, ladder bounds, count, optional sizing and provider route.\n * @returns Provider-normalized prices with sizingPreview when supported, or a typed unavailable result.\n * @throws When bounds or sizing violate the provider's venue rules.\n */\n getScalePriceLadder?(\n params: GetScalePriceLadderParams,\n ): Promise<PerpsScalePriceLadder>;\n\n // Unified asset and route information\n getDepositRoutes(params?: GetSupportedPathsParams): AssetRoute[]; // Assets and their deposit routes\n getWithdrawalRoutes(params?: GetSupportedPathsParams): AssetRoute[]; // Assets and their withdrawal routes\n\n // Trading operations → Redux (persisted, optimistic updates)\n placeOrder(params: OrderParams): Promise<OrderResult>;\n editOrder(params: EditOrderParams): Promise<OrderResult>;\n cancelOrder(params: CancelOrderParams): Promise<CancelOrderResult>;\n cancelOrders?(params: BatchCancelOrdersParams): Promise<CancelOrdersResult>; // Optional: batch cancel for protocols that support it\n getTwapOrders?(): Promise<TwapOrder[]>;\n /**\n * Resolve the venue account index the client enrolls for notifications.\n * Optional: only providers whose notification events are keyed by account\n * index (Lighter) implement it.\n */\n getNotificationAccountIndex?(): Promise<number>;\n /**\n * Stream TWAP lifecycle updates, with slice fills. Optional: providers\n * without a native TWAP push channel omit it.\n */\n subscribeToTwapOrders?(params: SubscribeTwapOrdersParams): () => void;\n getChaseOrders?(): Promise<ChaseOrder[]>;\n /**\n * Call back when a chase of the selected account was placed, re-priced,\n * filled or ended, so `getChaseOrders` is read on changes instead of on a\n * timer. Providers without chases omit it.\n */\n subscribeToChaseOrderChanges?(\n params: SubscribeChaseOrderChangesParams,\n ): () => void;\n /**\n * Call back when the venue's own push shows that a market was listed or\n * delisted, so `getMarkets` is read on changes instead of on a timer.\n * Providers whose stream cannot show it omit it.\n */\n subscribeToMarketChanges?(params: SubscribeMarketChangesParams): () => void;\n /** Pure local observation; no signing, transport, continuation or durable writes. */\n getChaseOrderOwnership?(\n params: GetChaseOrderOwnershipParams,\n ): Promise<PerpsChaseOrderOwnership>;\n /** Observe an exact retained cancellation without signing or dispatching a successor. */\n reconcileChaseOrderCancellation?(\n params: ReconcileChaseOrderCancellationParams,\n ): Promise<ReconcileChaseOrderCancellationResult>;\n suspendChaseOrders?(): Promise<ChaseOrder[]>;\n closePosition(params: ClosePositionParams): Promise<OrderResult>;\n closePositions?(params: ClosePositionsParams): Promise<ClosePositionsResult>; // Optional: batch close for protocols that support it\n /**\n * Discover close targets without requiring display margin.\n *\n * @internal\n */\n getClosePositionTargets?(): Promise<\n Pick<ClosePositionParams, 'symbol' | 'expectedAccountId'>[]\n >;\n updatePositionTPSL(params: UpdatePositionTPSLParams): Promise<OrderResult>;\n /**\n * Replace one TP/SL leg of a position and leave the other leg untouched. The\n * new leg protects the whole position. A provider that cannot do this from\n * its venue rejects with `TPSL_LEG_REPLACE_UNSUPPORTED` before any write;\n * callers treat a provider without this method the same way.\n */\n replacePositionTPSLLeg?(\n params: ReplacePositionTPSLLegParams,\n ): Promise<OrderResult>;\n updateMargin(params: UpdateMarginParams): Promise<MarginResult>;\n // Durable-settlement surfacing (optional: providers with durable local\n // settlement state — Lighter). Read-only listings plus selective,\n // explicit acknowledgment; never destructive read-all.\n getPendingManualRecoveries?(): Promise<PerpsPendingManualRecovery[]>;\n reviewRecoveryVenue?(params?: {\n providerId?: PerpsProviderType;\n }): Promise<PerpsRecoveryVenueReview>;\n resolveRecoveryProtection?(\n params: ResolveRecoveryProtectionParams,\n ): Promise<PerpsRecoveryProtectionResult>;\n getRecoveredDispatches?(): Promise<PerpsRecoveredDispatch[]>;\n /** Read local native attached identities; never creates, reattaches or replays orders. */\n getAttachedOrderGroups?(): Promise<AttachedOrderGroup[]>;\n /** Explicit venue review with existing registered local read authority only. */\n reviewAttachedOrderGroups?(): Promise<AttachedOrderGroup[]>;\n /** Non-financial venue checks with local persistence; no signing, retry or acknowledgment. */\n reconcileRecoveredDispatches?(): Promise<PerpsRecoveredDispatch[]>;\n acknowledgeRecoveredDispatch?(recoveryId: string): Promise<void>;\n getPositions(params?: GetPositionsParams): Promise<Position[]>;\n getAccountState(params?: GetAccountStateParams): Promise<AccountState>;\n getUserDataSnapshot?(\n params: GetUserDataSnapshotParams,\n ): Promise<PerpsUserDataSnapshot>;\n getMarkets(params?: GetMarketsParams): Promise<MarketInfo[]>;\n getMarketDataWithPrices(): Promise<PerpsMarketData[]>;\n withdraw(params: WithdrawParams): Promise<WithdrawResult>; // API operation - stays in provider\n // Note: deposit() is handled by PerpsController routing (blockchain operation)\n validateDeposit(\n params: DepositParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific deposit validation\n validateOrder(\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific order validation\n validateClosePosition(\n params: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific position close validation\n validateWithdrawal(\n params: WithdrawParams,\n ): Promise<{ isValid: boolean; error?: string }>; // Protocol-specific withdrawal validation\n\n // Historical data operations\n /**\n * Historical trade fills - actual executed trades with exact prices and fees.\n * Purpose: Track what actually happened when orders were executed.\n * Example: Market long 1 ETH @ $50,000 → OrderFill with exact execution price and fees\n */\n getOrderFills(\n params?: GetOrderFillsParams,\n options?: PerpsReadOptions,\n ): Promise<OrderFill[]>;\n\n /**\n * A market's most recent public trades (every user's), newest first.\n * Optional so providers without a public trade feed can omit it.\n */\n getPublicTrades?(params: GetPublicTradesParams): Promise<PublicTrade[]>;\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 * Purpose: Prevent 429 errors during rapid market switching by reusing cached fills.\n *\n * @param params - Optional filter parameters (startTime, symbol)\n */\n getOrFetchFills(params?: GetOrFetchFillsParams): Promise<OrderFill[]>;\n\n /**\n * Get historical portfolio data\n * Purpose: Retrieve account value from previous periods for PnL tracking\n * Example: Get account value from yesterday to calculate 24h percentage change\n *\n * @param params - Optional parameters for historical portfolio retrieval\n */\n getHistoricalPortfolio(\n params?: GetHistoricalPortfolioParams,\n ): Promise<HistoricalPortfolioResult>;\n\n /**\n * Historical order lifecycle - order placement, modifications, and status changes.\n * Purpose: Track the complete journey of orders from request to completion.\n * Example: Limit buy 1 ETH @ $48,000 → Order with status 'open' → 'filled' when executed\n */\n getOrders(\n params?: GetOrdersParams,\n options?: PerpsReadOptions,\n ): Promise<Order[]>;\n\n /**\n * Currently active open orders (real-time status).\n * Purpose: Show orders that are currently open/pending execution (not historical states).\n * Different from getOrders() which returns complete historical order lifecycle.\n * Example: Shows only orders that are actually open right now in the exchange.\n */\n getOpenOrders(params?: GetOrdersParams): Promise<Order[]>;\n\n /**\n * Historical funding payments - periodic costs/rewards for holding positions.\n * Purpose: Track ongoing expenses and income from position maintenance.\n * Example: Holding long ETH position → Funding payment of -$5.00 (you pay the funding)\n */\n getFunding(\n params?: GetFundingParams,\n options?: PerpsReadOptions,\n ): Promise<Funding[]>;\n\n /**\n * Get user non-funding ledger updates (deposits, transfers, withdrawals)\n */\n getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]>;\n\n /**\n * Resolve the provider's currently active account identifier.\n * Used by the REST coalesce layer so cached payloads are account-scoped\n * even when callers omit params.accountId (the common hook path) — prevents\n * one account's data from being served after an account switch within\n * the coalesce TTL window.\n */\n getCurrentAccountId(): Promise<CaipAccountId>;\n\n /**\n * Get user history (deposits, withdrawals, transfers)\n */\n getUserHistory(params?: {\n accountId?: CaipAccountId;\n startTime?: number;\n endTime?: number;\n }): Promise<UserHistoryItem[]>;\n\n // Protocol-specific calculations\n calculateLiquidationPrice(params: LiquidationPriceParams): Promise<string>;\n calculateMaintenanceMargin(params: MaintenanceMarginParams): Promise<number>;\n getMaxLeverage(\n asset: string,\n providerId?: PerpsProviderType,\n ): Promise<number>;\n calculateFees(params: FeeCalculationParams): Promise<FeeCalculationResult>;\n /**\n * Read-only projection of the position that would remain after the proposed\n * order. Isolated-margin venues apply selected leverage to the whole\n * resulting position and use the maintenance tier at liquidation notional.\n * Hyperliquid projects Cross positions too; `reason: 'cross_margin'` is no\n * longer returned by it.\n */\n previewPositionModify(\n params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult>;\n /**\n * Liquidation price of the Cross position an order would leave, as a typed\n * result that never rejects. Optional: a provider without it is treated as\n * `{ status: 'unavailable', reason: 'provider' }`.\n */\n estimateCrossLiquidation?(\n params: EstimateCrossLiquidationParams,\n ): Promise<CrossLiquidationEstimate>;\n\n // Live data subscriptions → Direct UI (NO Redux, maximum speed)\n subscribeToPrices(params: SubscribePricesParams): () => void;\n subscribeToPositions(params: SubscribePositionsParams): () => void;\n subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void;\n subscribeToOrders(params: SubscribeOrdersParams): () => void;\n subscribeToAccount(params: SubscribeAccountParams): () => void;\n subscribeToOICaps(params: SubscribeOICapsParams): () => void;\n subscribeToCandles(params: SubscribeCandlesParams): () => void;\n subscribeToOrderBook(params: SubscribeOrderBookParams): () => void;\n /**\n * Stream a market's public trades (every user's). Optional so providers\n * without a public trade feed can omit it.\n */\n subscribeToPublicTrades?(params: SubscribePublicTradesParams): () => void;\n /**\n * Stream one market's per-side available to trade as the venue reports it.\n * Optional: a provider whose venue has no per-market value omits it, and the\n * value stays unknown (`undefined`) for clients. Never computed locally.\n */\n subscribeToAvailableToTrade?(\n params: SubscribeAvailableToTradeParams,\n ): () => void;\n\n // Live data configuration\n setLiveDataConfig(config: Partial<LiveDataConfig>): void;\n\n // Connection management\n toggleTestnet(): Promise<ToggleTestnetResult>;\n initialize(): Promise<InitializeResult>;\n isReadyToTrade(): Promise<ReadyToTradeResult>;\n /**\n * Run the provider's deferred trading setup (for example account migration,\n * builder fee, referral or venue-key registration) ahead of the first\n * order. The result is described on `PerpsController.prepareTradingWallet`.\n * Providers without such setup omit it.\n */\n prepareTradingWallet?(): Promise<ReadyToTradeResult>;\n /**\n * Forget every agent the provider resolved, so the next L1 action asks its\n * resolver again. Providers without agents omit it.\n */\n clearAgentSigners?(): void;\n disconnect(): Promise<DisconnectResult>;\n ping(timeoutMs?: number): Promise<void>; // Lightweight WebSocket health check with configurable timeout\n getWebSocketConnectionState?(): WebSocketConnectionState; // Optional: get current WebSocket connection state\n subscribeToConnectionState?(\n listener: (\n state: WebSocketConnectionState,\n reconnectionAttempt: number,\n ) => void,\n ): () => void; // Optional: subscribe to WebSocket connection state changes\n reconnect?(): Promise<void>; // Optional: manually trigger WebSocket reconnection\n /** Optional: this provider's own health. Others derive it from connection state. */\n getProviderHealth?(): PerpsProviderHealth;\n /** Optional: current health immediately, then every change. */\n subscribeToProviderHealth?(\n listener: (health: PerpsProviderHealth) => void,\n ): () => void;\n\n // Block explorer\n getBlockExplorerUrl(address?: string): string;\n\n // Fee discount context (optional - for MetaMask reward discounts)\n /**\n * Which provider a write with this route actually reaches.\n *\n * Implemented only by an aggregating provider, whose `protocolId` names the\n * aggregate rather than the route and whose reads span every active provider.\n * A single provider needs no answer: every write reaches itself.\n *\n * @param providerId - Explicit route, or undefined for the default.\n * @returns The provider id the write will be submitted through.\n */\n getWriteProviderId?(providerId?: PerpsProviderType): PerpsProviderType;\n\n /**\n * Registered execution venues for an aggregating provider. Unlike position\n * reads, this includes venues whose balances or positions are unavailable.\n *\n * @returns Every venue a close-all operation will reach.\n */\n getProviderIds?(): PerpsProviderType[];\n\n /**\n * Whether the execution venue consumes fee resolutions or discounts.\n * Direct providers may omit this; the presence of a fee setter is sufficient.\n *\n * @param providerId - Venue to check, or the default route when omitted.\n * @returns Whether resolving a fee for this venue has an effect.\n */\n supportsFeeResolution?(providerId?: PerpsProviderType): boolean;\n\n setUserFeeDiscount?(discountBips: number | undefined): void;\n /**\n * Set the full fee resolution context, including attribution source.\n *\n * @param resolution - Resolved fee, or undefined to clear it.\n * @param providerId - Venue the resolution is for. An aggregating provider\n * applies it to that venue only, so a fan-out write can price each venue on\n * its own; when omitted it applies to every venue. A single provider is its\n * only venue and may ignore it.\n */\n setUserFeeResolution?(\n resolution: PerpsFeeResolution | undefined,\n providerId?: PerpsProviderType,\n ): void;\n /**\n * Approve the dedicated subscription builder outside order submission.\n *\n * @deprecated ADR 0064 replaced the dedicated subscription builder with cloid\n * marking on the standard builder. Nothing on the order path reads this\n * approval any more; it is retained only so the previous design can be\n * restored cheaply if cloid marking does not hold up in shadow mode.\n */\n approveSubscriptionBuilderFee?(): Promise<boolean>;\n\n // HIP-3 (Builder-deployed DEXs) operations - optional for backward compatibility\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 getAvailableDexs?(params?: GetAvailableDexsParams): Promise<string[]>;\n\n /**\n * Fetch historical OHLCV candle data for a symbol.\n * Optional: only providers that support historical candles need to implement this.\n */\n fetchHistoricalCandles?(options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData>;\n};\n\n// ============================================================================\n// Multi-Provider Aggregation Types (Phase 1)\n// ============================================================================\n\n/**\n * Provider identifier type for multi-provider support.\n * Add new providers here as they are implemented.\n */\nexport type PerpsProviderType = 'hyperliquid' | 'lighter';\n\n/**\n * Active provider mode for PerpsController state.\n * - Direct providers: 'hyperliquid', 'lighter'\n * - 'aggregated': Multi-provider aggregation mode\n */\nexport type PerpsActiveProviderMode = PerpsProviderType | 'aggregated';\n\n/**\n * Aggregation mode for read operations.\n * - 'all': Aggregate data from all registered providers\n * - 'active': Only aggregate from providers with active connections\n * - 'specific': Aggregate from a specific subset of providers\n */\nexport type AggregationMode = 'all' | 'active' | 'specific';\n\n/**\n * Routing strategy for write operations.\n * Phase 1 only supports 'default_provider' - advanced strategies deferred to Phase 3.\n */\nexport type RoutingStrategy = 'default_provider';\n\n/**\n * Configuration for AggregatedPerpsProvider\n */\nexport type AggregatedProviderConfig = {\n /** Map of provider ID to provider instance */\n providers: Map<PerpsProviderType, PerpsProvider>;\n /** Default provider for write operations when providerId not specified */\n defaultProvider: PerpsProviderType;\n /** Aggregation mode for read operations (default: 'all') */\n aggregationMode?: AggregationMode;\n /** Platform dependencies for logging, metrics, etc. */\n infrastructure: PerpsPlatformDependencies;\n /** Whether the providers run on testnet; tags the errors it logs. */\n isTestnet?: boolean;\n};\n\n/**\n * Provider-specific error with context for multi-provider error handling\n */\nexport type ProviderError = {\n /** Which provider the error originated from */\n providerId: PerpsProviderType;\n /** Human-readable error message */\n message: string;\n /** Original error object if available */\n originalError?: Error;\n /** Whether the operation can be retried */\n isRetryable?: boolean;\n};\n\n/**\n * Aggregated account state combining data from multiple providers\n */\nexport type AggregatedAccountState = {\n /** Combined totals across all providers */\n total: AccountState;\n /** Per-provider breakdown */\n byProvider: Map<PerpsProviderType, AccountState>;\n};\n\n// ============================================================================\n// Injectable Dependency Interfaces\n// These interfaces enable dependency injection for platform-specific services,\n// allowing PerpsController to be moved to core without mobile-specific imports.\n// ============================================================================\n\n/**\n * Injectable logger interface for error reporting.\n * Allows core package to be platform-agnostic (mobile: Sentry, extension: different impl)\n */\nexport type PerpsLogger = {\n error(\n error: Error,\n options?: {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n extras?: Record<string, unknown>;\n },\n ): void;\n};\n\n/**\n * Analytics events specific to Perps feature.\n * These are the actual event names sent to analytics backend.\n * Values must match the corresponding MetaMetricsEvents values in mobile for compatibility.\n *\n * When migrating to core monorepo, this enum travels with PerpsController.\n */\nexport enum PerpsAnalyticsEvent {\n WithdrawalTransaction = 'Perp Withdrawal Transaction',\n TradeTransaction = 'Perp Trade Transaction',\n PositionCloseTransaction = 'Perp Position Close Transaction',\n OrderCancelTransaction = 'Perp Order Cancel Transaction',\n ScreenViewed = 'Perp Screen Viewed',\n UiInteraction = 'Perp UI Interaction',\n RiskManagement = 'Perp Risk Management',\n PerpsError = 'Perp Error',\n AccountSetup = 'Perp Account Setup',\n // New funnel + search events.\n // Names must match MetaMetrics/Mixpanel exactly; no other event names may be added.\n TransactionConsidered = 'Perp Transaction Considered',\n TradeQuoteReceived = 'Perp Trade Quote Received',\n SearchQuery = 'Perp Search Query',\n SearchResultTapped = 'Perp Search Result Tapped',\n SearchAbandoned = 'Perp Search Abandoned',\n}\n\n/**\n * UTM / discovery attribution context for Perps analytics.\n *\n * Held transiently in-memory by PerpsController (never persisted in state) and\n * merged into analytics event properties so client-originated UTM attribution\n * can be propagated onto core-emitted transaction events.\n */\nexport type PerpsAttributionContext = {\n utmSource?: string;\n utmMedium?: string;\n utmCampaign?: string;\n utmContent?: string;\n utmTerm?: string;\n};\n\n/**\n * Perps-specific trace names. These must match TraceName enum values in mobile.\n * When in core monorepo, this defines the valid trace names for Perps operations.\n */\nexport type PerpsTraceName =\n | 'Perps Open Position'\n | 'Perps Close Position'\n | 'Perps Deposit'\n | 'Perps Withdraw'\n | 'Perps Place Order'\n | 'Perps Edit Order'\n | 'Perps Cancel Order'\n | 'Perps Update TP/SL'\n | 'Perps Update Margin'\n | 'Perps Flip Position'\n | 'Perps Market Data Update'\n | 'Perps Order View'\n | 'Perps Tab View'\n | 'Perps Market List View'\n | 'Perps Position Details View'\n | 'Perps Adjust Margin View'\n | 'Perps Order Details View'\n | 'Perps Order Book View'\n | 'Perps Flip Position Sheet'\n | 'Perps Transactions View'\n | 'Perps Order Fills Fetch'\n | 'Perps Orders Fetch'\n | 'Perps Funding Fetch'\n | 'Perps Get Positions'\n | 'Perps Get Account State'\n | 'Perps Get Historical Portfolio'\n | 'Perps Get Markets'\n | 'Perps Get Market Data With Prices'\n | 'Perps Fetch Historical Candles'\n | 'Perps WebSocket Connected'\n | 'Perps WebSocket Disconnected'\n | 'Perps WebSocket First Positions'\n | 'Perps WebSocket First Orders'\n | 'Perps WebSocket First Account'\n | 'Perps Data Lake Report'\n | 'Perps Rewards API Call'\n | 'Perps Close Position View'\n | 'Perps Withdraw View'\n | 'Perps Connection Establishment'\n | 'Perps Account Switch Reconnection'\n | 'Perps Market Data Preload'\n | 'Perps User Data Preload';\n\n/**\n * Perps trace name constants. Values match TraceName enum in mobile.\n * When in core, these ARE the source of truth - mobile will re-export from core.\n */\nexport const PerpsTraceNames = {\n // Trading operations\n PlaceOrder: 'Perps Place Order',\n EditOrder: 'Perps Edit Order',\n CancelOrder: 'Perps Cancel Order',\n ClosePosition: 'Perps Close Position',\n UpdateTpsl: 'Perps Update TP/SL',\n UpdateMargin: 'Perps Update Margin',\n FlipPosition: 'Perps Flip Position',\n\n // Account operations\n Withdraw: 'Perps Withdraw',\n Deposit: 'Perps Deposit',\n\n // Market data\n GetPositions: 'Perps Get Positions',\n GetAccountState: 'Perps Get Account State',\n GetMarkets: 'Perps Get Markets',\n GetMarketDataWithPrices: 'Perps Get Market Data With Prices',\n OrderFillsFetch: 'Perps Order Fills Fetch',\n OrdersFetch: 'Perps Orders Fetch',\n FundingFetch: 'Perps Funding Fetch',\n GetHistoricalPortfolio: 'Perps Get Historical Portfolio',\n FetchHistoricalCandles: 'Perps Fetch Historical Candles',\n\n // Data lake\n DataLakeReport: 'Perps Data Lake Report',\n\n // WebSocket\n WebsocketConnected: 'Perps WebSocket Connected',\n WebsocketDisconnected: 'Perps WebSocket Disconnected',\n WebsocketFirstPositions: 'Perps WebSocket First Positions',\n WebsocketFirstOrders: 'Perps WebSocket First Orders',\n WebsocketFirstAccount: 'Perps WebSocket First Account',\n\n // Other\n RewardsApiCall: 'Perps Rewards API Call',\n ConnectionEstablishment: 'Perps Connection Establishment',\n AccountSwitchReconnection: 'Perps Account Switch Reconnection',\n MarketDataPreload: 'Perps Market Data Preload',\n UserDataPreload: 'Perps User Data Preload',\n} as const satisfies Record<string, PerpsTraceName>;\n\n/**\n * Perps trace operation constants. Values match TraceOperation enum in mobile.\n * These categorize traces by type of operation for Sentry/observability filtering.\n */\nexport const PerpsTraceOperations = {\n Operation: 'perps.operation',\n OrderSubmission: 'perps.order_submission',\n PositionManagement: 'perps.position_management',\n} as const;\n\n/**\n * Values allowed in trace data/tags. Matches Sentry's TraceValue type.\n */\nexport type PerpsTraceValue = string | number | boolean;\n\n/**\n * Terminal status of a Perps trace.\n *\n * Platform adapters map this value to their tracing SDK's span status.\n */\nexport type PerpsTraceStatus = 'ok' | 'error';\n\n/**\n * Properties allowed in analytics events. More constrained than unknown.\n * Named PerpsAnalyticsProperties to avoid conflict with PERPS_EVENT_PROPERTY\n * constant object from eventNames.ts (which contains property key names).\n */\nexport type PerpsAnalyticsProperties = Record<\n string,\n string | number | boolean | Record<string, string> | null | undefined\n>;\n\n/**\n * Injectable metrics interface for analytics.\n * Allows core package to work with different analytics backends.\n */\nexport type PerpsMetrics = {\n isEnabled(): boolean;\n\n /**\n * Track a Perps-specific analytics event with properties.\n * This abstracts away the MetricsEventBuilder pattern used in mobile.\n *\n * @param event - The Perps analytics event type (enum with actual event name values)\n * @param properties - Type-safe key-value properties to attach to the event\n */\n trackPerpsEvent(\n event: PerpsAnalyticsEvent,\n properties: PerpsAnalyticsProperties,\n ): void;\n};\n\n/**\n * Injectable debug logger for development logging.\n * Only logs in development mode.\n * Accepts `unknown` to allow logging error objects from catch blocks.\n */\nexport type PerpsDebugLogger = {\n log(...args: unknown[]): void;\n};\n\n/**\n * Injectable stream manager interface for pause/resume during critical operations.\n *\n * WHY THIS IS NEEDED:\n * PerpsStreamManager is a React-based mobile-specific singleton that:\n * - Uses React Context for subscription management\n * - Uses react-native-performance for tracing\n * - Directly accesses Engine.context (mobile singleton pattern)\n * - Manages WebSocket connections with throttling/caching\n *\n * PerpsController only needs pause/resume during critical operations (withStreamPause method)\n * to prevent stale UI updates during batch operations. The minimal interface allows:\n * - Mobile: Wrap existing singleton (streamManager[channel].pause())\n * - Extension: Implement with whatever streaming solution they use\n */\n/**\n * Injectable stream manager interface for pause/resume during critical operations.\n *\n * WHY THIS IS NEEDED:\n * PerpsStreamManager is a React-based mobile-specific singleton that:\n * - Uses React Context for subscription management\n * - Uses react-native-performance for tracing\n * - Directly accesses Engine.context (mobile singleton pattern)\n * - Manages WebSocket connections with throttling/caching\n *\n * PerpsController only needs pause/resume during critical operations (withStreamPause method)\n * to prevent stale UI updates during batch operations. The minimal interface allows:\n * - Mobile: Wrap existing singleton (streamManager[channel].pause())\n * - Extension: Implement with whatever streaming solution they use\n */\nexport type PerpsStreamManager = {\n /**\n * @deprecated Core pauses its own stream channels. Still called for one\n * release so a client-side stream manager keeps working.\n */\n pauseChannel(channel: string): void;\n /**\n * @deprecated Core resumes its own stream channels. Still called for one\n * release so a client-side stream manager keeps working.\n */\n resumeChannel(channel: string): void;\n clearAllChannels(): void;\n};\n\n/**\n * Injectable performance monitor interface.\n * Wraps react-native-performance or browser Performance API.\n */\nexport type PerpsPerformance = {\n now(): number;\n /**\n * Optional platform hook invoked once after constructor disk hydration.\n * Receives `performance.now()` — not a Sentry write.\n */\n onControllerConstructed?: (monotonicMs: number) => void;\n};\n\ntype PerpsSetMeasurement = ((\n name: string,\n value: number,\n unit: string,\n) => void) &\n ((name: string, value: number, unit: string, id: string) => void);\n\n/**\n * Injectable tracer interface for Sentry/observability tracing.\n * Services use this to create spans and measure operation durations.\n *\n * Note: trace() returns void because services use name/id pairs to identify traces.\n * The actual span management is handled internally by the platform adapter.\n */\nexport type PerpsTracer = {\n trace(params: {\n name: PerpsTraceName;\n id: string;\n op: string;\n tags?: Record<string, PerpsTraceValue>;\n data?: Record<string, PerpsTraceValue>;\n }): void;\n\n endTrace(params: {\n name: PerpsTraceName;\n id: string;\n status?: PerpsTraceStatus;\n data?: Record<string, PerpsTraceValue>;\n }): void;\n\n setMeasurement: PerpsSetMeasurement;\n\n addBreadcrumb(breadcrumb: {\n category: string;\n message: string;\n level: 'fatal' | 'error' | 'warning' | 'log' | 'info' | 'debug';\n data?: Record<string, unknown>;\n }): void;\n};\n\n// ============================================================================\n// Minimal local types for cross-controller DI (no external controller imports)\n// ============================================================================\n\n/**\n * Minimal typed-message params passed to keyring for EIP-712 signing.\n * Structurally matches KeyringController's TypedMessageParams.\n */\nexport type PerpsTypedMessageParams = {\n from: string;\n data: unknown;\n};\n\n/**\n * EIP-712 payload produced by the HyperLiquid SDK, signed with\n * `eth_signTypedData_v4` semantics. `types` includes the `EIP712Domain`\n * entry derived from `domain`, as `eth_signTypedData_v4` expects.\n */\nexport type PerpsTypedDataPayload = {\n domain: {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: Hex;\n };\n types: Record<string, { name: string; type: string }[]>;\n primaryType: string;\n message: Record<string, unknown>;\n};\n\n/**\n * Client-implemented signer for the user's main EVM account. When provided,\n * the wallet services sign through it and never call `KeyringController`.\n * Clients that own a KeyringController omit it. The signing address still\n * comes from the messenger's selected account.\n */\nexport type PerpsAccountSigner = {\n /**\n * Sign EIP-712 typed data as `address`, exactly as given. HyperLiquid's\n * `domain.chainId` is not the wallet's connected chain: L1 actions signed\n * without an agent use 1337, and user-signed actions (builder fee,\n * withdraw, ...) use 1 unless `getChainId` is set. A wallet that only signs\n * for its connected chain (many EIP-1193 wallets) must route L1 actions\n * through an agent (see `providerCredentials.hyperliquid.getAgentSigner`)\n * and set `getChainId`.\n *\n * @param address - The account that signs.\n * @param payload - The typed data to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signTypedData(address: Hex, payload: PerpsTypedDataPayload): Promise<Hex>;\n\n /**\n * EIP-191 `personal_sign` as `address`. Required so a host that sets\n * `accountSigner` never falls back to `KeyringController` (Lighter signs\n * its venue-key registration this way).\n *\n * @param address - The account that signs.\n * @param message - Plaintext message to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signPersonalMessage(address: Hex, message: string): Promise<Hex>;\n\n /**\n * False while the signer cannot sign (e.g. wallet disconnected). Signing\n * then fails with `KEYRING_LOCKED`. Defaults to true.\n */\n isReady?(): boolean;\n\n /**\n * True when every signature needs a user confirmation (a hardware wallet,\n * or an interactive wallet such as a browser extension). HyperLiquid then\n * defers its optional init-time signing prompts to action time. When\n * omitted, the selected account's keyring type decides.\n */\n requiresSignatureConfirmation?(): boolean;\n\n /**\n * The chain the signer signs for, such as a browser wallet's connected\n * chain. HyperLiquid user-signed actions are then signed for it instead of\n * chain 1, so the wallet does not switch chains to sign them. Read at\n * every user-signed action.\n *\n * @returns The chain ID.\n */\n getChainId?(): Promise<number>;\n};\n\n/**\n * The main account and network an agent is approved for.\n */\nexport type PerpsAgentAccount = {\n /** The main account the agent acts for. */\n mainAddress: Hex;\n /** Whether the agent is approved on testnet rather than mainnet. */\n isTestnet: boolean;\n};\n\n/**\n * Host-owned delegated signer for a venue agent (HyperLiquid API wallet).\n * The host creates the key, gets it approved by the user's main account, and\n * keeps it; Core only asks it to sign. A viem local account satisfies this\n * shape.\n */\nexport type PerpsAgentSigner = {\n /** The agent account address. */\n address: Hex;\n\n /**\n * Sign EIP-712 typed data with the agent key.\n *\n * @param payload - The typed data to sign.\n * @returns A 65-byte 0x-prefixed signature.\n */\n signTypedData(payload: PerpsTypedDataPayload): Promise<Hex>;\n};\n\n/**\n * Minimal transaction params passed to TransactionController.addTransaction.\n * Only the fields PerpsController actually sets.\n */\nexport type PerpsTransactionParams = {\n from: string;\n to?: string;\n value?: string;\n data?: string;\n gas?: string;\n};\n\n/**\n * Options passed to TransactionController.addTransaction.\n */\nexport type PerpsAddTransactionOptions = {\n networkClientId: string;\n origin?: string;\n type?: string;\n skipInitialGasEstimate?: boolean;\n};\n\n/**\n * Minimal account shape read from AccountTreeController.\n * Only the fields PerpsController and its services actually use.\n */\nexport type PerpsInternalAccount = {\n address: string;\n type: string;\n id: string;\n};\n\n/**\n * Minimal remote feature flag state shape.\n * Only the remoteFeatureFlags record is needed by PerpsController.\n */\nexport type PerpsRemoteFeatureFlagState = {\n remoteFeatureFlags: Record<string, unknown>;\n};\n\n/**\n * Injectable interface for the Terminal-market service.\n *\n * `MarketDataService` programs against this contract so the concrete\n * `TerminalMarketService` class (which lives in `services/`) never leaks\n * into the types barrel — callers can supply any implementation that\n * satisfies the shape (production, stub, mock, etc.).\n */\nexport type PerpsTerminalMarketService = {\n fetchMarkets(): Promise<{\n markets: MarketInfo[];\n metadata: Map<string, TerminalAssetMetadata>;\n }>;\n clearCache(): void;\n logError(error: unknown, method: string): void;\n fetchGlobalSnapshot?(\n request: PerpsGlobalSnapshotRequest,\n ): Promise<PerpsGlobalSnapshotResult>;\n};\n\n/**\n * Exact identity a client expects from an atomic global Perps snapshot.\n * Lighter has a single DEX, so its `enabledDexes` is `['main']`.\n */\nexport type PerpsGlobalSnapshotRequest = {\n provider: 'hyperliquid' | 'lighter';\n network: 'mainnet' | 'testnet';\n enabledDexes: string[];\n};\n\n/** Validated snapshot data and its source-bounded expiry. */\nexport type PerpsGlobalSnapshotResult = {\n markets: PerpsMarketData[];\n /**\n * Trading-rule rows for `markets`, in the same order. `getMarkets` reads\n * this instead of mapping the snapshot a second time.\n */\n marketInfos: MarketInfo[];\n expiresAt: number;\n};\n\n/**\n * Platform dependencies for PerpsController and services.\n *\n * Architecture:\n * - Observability: logger, debugLogger, metrics, performance, tracer\n * - Platform: streamManager (mobile/extension specific)\n * - Cache: cache invalidation for standalone queries\n * - Rewards: delegated rewards interaction (DI — no RewardsController in Core yet)\n *\n * Cross-controller communication uses the messenger pattern (messenger.call).\n * Only rewards remains as DI because RewardsController is not yet in Core.\n */\nexport type PerpsPlatformDependencies = {\n // === Observability (stateless utilities) ===\n logger: PerpsLogger;\n debugLogger: PerpsDebugLogger;\n metrics: PerpsMetrics;\n performance: PerpsPerformance;\n tracer: PerpsTracer;\n\n // === Platform Services (mobile/extension specific) ===\n /**\n * @deprecated Core's stream channels pause, rebind and reopen themselves\n * (`PerpsController.resubscribeStreams` replaces a client-side reconnect).\n * Still called for one release; a client without its own stream manager\n * can pass no-ops.\n */\n streamManager: PerpsStreamManager;\n\n // === Feature Flags (platform-specific version gating) ===\n featureFlags: {\n /**\n * Validate a version-gated feature flag against current app version.\n * Returns true if flag is enabled AND app meets minimum version,\n * false if flag is disabled, or undefined if flag is misconfigured/overridden.\n *\n * Platform-specific because it uses react-native-device-info (mobile)\n * or browser APIs (extension) to get the app version.\n */\n validateVersionGated(flag: VersionGatedFeatureFlag): boolean | undefined;\n };\n\n // === Market Data Formatting (platform-specific number formatting) ===\n marketDataFormatters: MarketDataFormatters;\n\n // === Cache Invalidation (for standalone query caches) ===\n cacheInvalidator: PerpsCacheInvalidator;\n\n // === Disk Cache (cold-start persistence) ===\n diskCache: {\n getItem(key: string): Promise<string | null>;\n getItemSync?(key: string): string | null;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n };\n\n // === Terminal API (market metadata source) ===\n terminalApi?: {\n /** Full endpoint URL for the legacy perpetuals market-data endpoint. */\n marketDataUrl?: string;\n\n /**\n * Full endpoint URL for the schema-v4 atomic global Perps snapshot\n * (`GET /v4/perpetuals`).\n */\n globalSnapshotUrl?: string;\n };\n\n // === notify-perps API (Lighter account enrollment) ===\n notifyPerpsApi?: {\n /**\n * Base URL of the notify-perps API for the current environment (for\n * example `https://perps.api.cx.metamask.io`). Lighter accounts are\n * enrolled at `${baseUrl}/api/v1/lighter/accounts`. When omitted,\n * enrollment is skipped.\n */\n baseUrl?: string;\n };\n\n /** @deprecated Use `terminalApi.marketDataUrl`. */\n terminalApiUrl?: string;\n\n /**\n * Optional Terminal-market service instance for fetching structured market\n * metadata from the MetaMask Terminal API.\n *\n * When provided, `MarketDataService` uses this service to attempt the\n * Terminal API path before falling back to the provider.\n * Clients that do not use the Terminal API can omit this field.\n */\n terminalMarketService?: PerpsTerminalMarketService;\n\n // === Rewards (DI — no RewardsController in Core yet) ===\n rewards: {\n /**\n * Get the VIP and season fee discount for an account.\n *\n * Returns a numeric discount in basis points (e.g., 6500 = 65%), or `null`\n * when rewards state has not hydrated yet.\n *\n * Pass the perps MetaMask builder base fee in bips so the rewards\n * controller can convert an absolute VIP fee into a discount fraction.\n */\n getPerpsDiscountForAccount(\n caipAccountId: `${string}:${string}:${string}`,\n baseFeeBips: number,\n ): Promise<number | null>;\n\n /**\n * Get the independent trading fee grant for an explicit provider route.\n *\n * The client owns grant retrieval, authentication, payload validation, and\n * deciding which routes it supports. Core calls this only when the resolver\n * has an explicit scope, validates the returned fee, expiry, and exact scope\n * match after concurrent candidate work settles, and compares valid\n * candidates with the other fee sources.\n *\n * Optional so clients predating grant support retain their existing\n * behavior.\n */\n getPerpsTradingFeeGrant?(\n scope: PerpsFeeResolverScope,\n ): Promise<PerpsTradingFeeGrant | null>;\n\n /**\n * Call the listener when an answer of the two reads above may have changed\n * (a Rewards session started, ended or expired, or a tier changed), so fee\n * rate streams are priced again. Optional: without it they follow fills\n * and account changes only.\n */\n subscribeToPerpsFeeChanges?(listener: () => void): () => void;\n };\n\n // === Subscription (DI — benefits endpoint is owned by the Subscription team) ===\n /**\n * Optional subscription source for the unified fee resolver.\n *\n * The client owns the Profile JWT, so it performs\n * `GET /v1/profiles/{profileId}/benefits` and hands the perps controller the\n * parsed body. The controller caches the result stale-while-revalidate and\n * never awaits this call on the order-signing path.\n *\n * Omit it entirely on clients that do not ship the subscription waiver; the\n * resolver then falls back to the rewards and default sources.\n */\n subscription?: {\n /**\n * Read the current profile's subscription benefits.\n * Resolve `null` when there is no subscription to report (signed out, no\n * profile). Rejections are tolerated: the resolver keeps the previous\n * snapshot and never grants the waiver from a failed read.\n */\n getPerpsBenefits(): Promise<PerpsSubscriptionBenefits | null>;\n\n /**\n * Register the current HyperLiquid trading address (CAIP-10) against the\n * subscription profile, so a later fill can be attributed to it.\n *\n * Optional compatibility fallback for clients that do not register the\n * structural `SubscriptionController:registerAddress` action.\n */\n registerTradingAddress?(caipAccountId: string): Promise<void>;\n };\n\n // === Account Signer (DI — for clients without a KeyringController) ===\n /**\n * Optional signer for the user's main EVM account. When set, it takes\n * precedence over the `KeyringController:*` messenger actions.\n */\n accountSigner?: PerpsAccountSigner;\n};\n\n/**\n * Cache types that can be invalidated.\n * Used by standalone query caches (e.g., usePerpsPositionForAsset).\n */\nexport type PerpsCacheType = 'positions' | 'accountState' | 'markets';\n\n/**\n * Parameters for invalidating a specific cache type.\n */\nexport type InvalidateCacheParams = {\n /** The type of cache to invalidate */\n cacheType: PerpsCacheType;\n};\n\n/**\n * Cache invalidation interface for standalone query caches.\n * Allows services to signal when data has changed without depending on\n * mobile-specific implementations.\n */\nexport type PerpsCacheInvalidator = {\n /**\n * Invalidate a specific cache type.\n * Notifies all subscribers that cached data is stale.\n */\n invalidate(params: InvalidateCacheParams): void;\n\n /**\n * Invalidate all cache types.\n */\n invalidateAll(): void;\n};\n\n// ============================================================================\n// Market Data Formatting\n// ============================================================================\n\n/**\n * Injectable formatters for market data transformation.\n * Decouples marketDataTransform from mobile-specific intl/formatUtils imports.\n *\n * Range configs are opaque (unknown[]) because the concrete type\n * (FiatRangeConfig on mobile) is platform-specific. The formatter\n * implementation casts internally.\n */\nexport type MarketDataFormatters = {\n /** Format a number as a USD volume string (e.g., '$1.2B', '$850M') */\n formatVolume(value: number): string;\n /** Format a number as a USD fiat string with adaptive precision */\n formatPerpsFiat(value: number, options?: { ranges?: unknown[] }): string;\n /** Format a number as a percentage string (e.g., '2.50%', '-1.80%') */\n formatPercentage(percent: number): string;\n /** Universal price ranges for formatting (opaque to portable code) */\n priceRangesUniversal: unknown[];\n};\n\n// ============================================================================\n// Payment Token (portable replacement for mobile-only AssetType)\n// ============================================================================\n\n/**\n * Minimal payment token for deposit flow.\n * Only the fields actually used by PerpsController are included.\n * Replaces the mobile-only AssetType (which extends TokenI and uses ImageSourcePropType).\n */\nexport type PaymentToken = {\n description?: string;\n address: string;\n chainId?: string;\n symbol?: string;\n};\n\n/**\n * Selected pay-with token shape used in PerpsController state, pending trade config,\n * selectors, and UI hooks. Use this type everywhere this shape is needed.\n */\nexport type PerpsSelectedPaymentToken = {\n description?: string;\n address: string;\n chainId: string;\n symbol?: string;\n};\n\n// ============================================================================\n// Version-gated Feature Flag (portable)\n// ============================================================================\n\n/**\n * Structure for a version-gated feature flag from LaunchDarkly.\n * Portable: no platform-specific imports.\n */\nexport type VersionGatedFeatureFlag = {\n enabled: boolean;\n minimumVersion: string;\n};\n\n/**\n * Type guard for VersionGatedFeatureFlag.\n * Pure logic, no platform dependencies.\n *\n * @param value - The value to check.\n * @returns True if the value is a VersionGatedFeatureFlag.\n */\nexport function isVersionGatedFeatureFlag(\n value: unknown,\n): value is VersionGatedFeatureFlag {\n return (\n typeof value === 'object' &&\n value !== null &&\n hasProperty(value, 'enabled') &&\n hasProperty(value, 'minimumVersion') &&\n typeof (value as { enabled: unknown }).enabled === 'boolean' &&\n typeof (value as { minimumVersion: unknown }).minimumVersion === 'string'\n );\n}\n\n// ============================================================================\n// Sub-module type re-exports\n// These types live in separate files within types/ and need to be accessible\n// from the root barrel via `export * from './types.js'`.\n// ============================================================================\nexport type * from './perps-types.js';\nexport * from './transactionTypes.js';\n// hyperliquid-types: selective export to avoid OrderType clash with main types\nexport type {\n HyperLiquidAbstractionMode,\n AssetPosition,\n SpotBalance,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n FrontendOrder,\n SDKOrderParams,\n ClearinghouseStateResponse,\n SpotClearinghouseStateResponse,\n MetaResponse,\n FrontendOpenOrdersResponse,\n AllMidsResponse,\n MetaAndAssetCtxsResponse,\n PredictedFundingsResponse,\n SpotMetaResponse,\n} from './hyperliquid-types.js';\n"]}
|