@metamask-previews/perps-controller 17.3.0-preview-d3f9964be → 17.4.0-preview-aecbce4ff
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 +72 -1
- package/dist/PerpsController-method-action-types.d.ts +10 -3
- 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 +10 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +62 -8
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +55 -0
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +55 -0
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +19 -0
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +21 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +7 -0
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +133 -34
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +2 -0
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +16 -4
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/RewardsIntegrationService.d.ts +47 -2
- package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
- package/dist/services/RewardsIntegrationService.js +400 -19
- package/dist/services/RewardsIntegrationService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +9 -1
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TerminalMarketService.d.ts +1 -1
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +11 -2
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +291 -18
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +65 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/messenger.d.ts +17 -1
- package/dist/types/messenger.d.ts.map +1 -1
- package/dist/types/messenger.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +7 -0
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +1 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/subscriptionFeeWaiver.d.ts +201 -0
- package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -0
- package/dist/utils/subscriptionFeeWaiver.js +334 -0
- package/dist/utils/subscriptionFeeWaiver.js.map +1 -0
- package/package.json +11 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LighterProvider.js","sourceRoot":"","sources":["../../src/providers/LighterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,EAClB,iBAAiB,EACjB,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,6BAA6B,EAC7B,wBAAwB,EACxB,yBAAyB,EACzB,wBAAwB,EACxB,yBAAyB,EACzB,oCAAoC,EACpC,oBAAoB,EACpB,iCAAiC,EACjC,yCAAyC,EACzC,qBAAqB,EACrB,4BAA4B,EAC5B,8BAA8B,EAC9B,sCAAsC,EACtC,4BAA4B,EAC5B,8BAA8B,EAC9B,qCAAqC,EACrC,4BAA4B,EAC5B,+BAA+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;QAClD,sEAAsE;QACtE,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,IAAI,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;QAChE,IAAI,SAAS,EAAE,CAAC;YACd,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,IAAI,CAAC,YAAY,CAAC,qBAAqB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAC1E,CAAC;IAED,+EAA+E;IAC/E,iBAAiB;IACjB,+EAA+E;IAE/E,mBAAmB,CAAC,OAAgB;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU;YAC7B,CAAC,CAAC,4BAA4B;YAC9B,CAAC,CAAC,4BAA4B,CAAC;QACjC,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,YAAY,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7D,CAAC;CACF","sourcesContent":["/**\n * LighterProvider\n *\n * Provider implementation for the zkLighter protocol (POC).\n * Implements the PerpsProvider interface with live REST reads and a real\n * write path (place/cancel limit orders) driven through the Lighter Go/WASM\n * signer behind the transport-agnostic {@link LighterSignerBridge} seam.\n *\n * Key differences from HyperLiquid:\n * - Venue-specific key (Schnorr over ECgFp5) registered per API-key slot via\n * a ChangePubKey L2 transaction carrying an EIP-191 personal_sign L1Sig.\n * - Order prices/sizes are integers scaled by per-market decimals.\n * - REST reads plus WebSocket market, account, position, order, fill,\n * order-book, and candle streams, with price polling as a fallback.\n */\n\nimport type { CaipAccountId } from '@metamask/utils';\n\nimport type { CandlePeriod } from '../constants/chartConfig.js';\nimport {\n computeLighterMinOrderSize,\n fromLighterInteger,\n getLighterChainId,\n getLighterTransactionOutcome,\n LIGHTER_RESOLUTION_MS,\n LIGHTER_SUPPORTED_RESOLUTIONS,\n LIGHTER_DEFAULT_API_KEY_INDEX,\n LIGHTER_NO_TRIGGER_PRICE,\n LIGHTER_ORDER_EXPIRY_NONE,\n LIGHTER_ORDER_TYPE_LIMIT,\n LIGHTER_ORDER_TYPE_MARKET,\n LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME,\n getLighterWsEndpoint,\n LIGHTER_PRICE_POLLING_INTERVAL_MS,\n LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n LIGHTER_BRIDGE_CONFIG,\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n LIGHTER_TX_TYPE_CHANGE_PUB_KEY,\n LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER,\n LIGHTER_ORDER_TYPE_STOP_LOSS,\n LIGHTER_ORDER_TYPE_TAKE_PROFIT,\n LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS,\n LIGHTER_TX_TYPE_CREATE_ORDER,\n LIGHTER_TX_TYPE_UPDATE_LEVERAGE,\n LIGHTER_TX_TYPE_UPDATE_MARGIN,\n LIGHTER_TX_TYPE_WITHDRAW,\n LIGHTER_MARGIN_MODE_CROSS,\n LIGHTER_MARGIN_MODE_ISOLATED,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n LIGHTER_USDC_ASSET_INDEX,\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MARGIN_METADATA_TTL_MS,\n parseLighterStrictDecimal,\n toLighterInteger,\n} from '../constants/lighterConfig.js';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport type { PerpsControllerMessenger } from '../PerpsController.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport {\n convertKeysToCamelCase,\n LighterApiError,\n LighterClientService,\n} from '../services/LighterClientService.js';\nimport { LighterWalletService } from '../services/LighterWalletService.js';\nimport { WebSocketConnectionState } from '../types/index.js';\nimport type {\n AccountState,\n AssetRoute,\n CandleData,\n CandleStick,\n CancelOrderParams,\n CancelOrderResult,\n ClosePositionParams,\n DepositParams,\n DisconnectResult,\n EditOrderParams,\n FeeCalculationParams,\n FeeCalculationResult,\n Funding,\n GetAccountStateParams,\n GetFundingParams,\n GetHistoricalPortfolioParams,\n GetMarketsParams,\n GetOrderFillsParams,\n GetOrdersParams,\n GetOrFetchFillsParams,\n GetPositionsParams,\n GetSupportedPathsParams,\n HistoricalPortfolioResult,\n InitializeResult,\n LiquidationPriceParams,\n LiveDataConfig,\n MaintenanceMarginParams,\n MarginResult,\n MarketInfo,\n Order,\n OrderFill,\n OrderParams,\n OrderResult,\n PerpsMarketData,\n PerpsPlatformDependencies,\n PerpsProvider,\n PerpsReadOptions,\n Position,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n RawLedgerUpdate,\n ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n OrderBookData,\n OrderBookLevel,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n PriceUpdate,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterAccountsByL1AddressResponse,\n LighterAuthConfig,\n LighterTxLookupResponse,\n LighterTransferHistoryItem,\n LighterCreateClientResult,\n LighterCreateOrderWireParams,\n LighterGroupedOrderWireParams,\n LighterOrderBookMeta,\n LighterSendTxResponse,\n LighterSignerBridge,\n LighterSignerOperation,\n LighterSignerResult,\n LighterWasmCall,\n LighterTxResult,\n LighterWebSocketCtor,\n LighterWebSocketLike,\n LighterWsAccountMessage,\n LighterCandle,\n LighterWsCandleMessage,\n LighterWsOrderBookMessage,\n LighterWsTradesMessage,\n LighterWsMarketStat,\n LighterWsMarketStatsMessage,\n} from '../types/lighter-types.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport {\n adaptAccountStateFromLighter,\n adaptAccountStateFromLighterUserStats,\n adaptFillFromLighterTrade,\n adaptMarketDataFromLighter,\n adaptMarketFromLighter,\n adaptOrderFromLighter,\n adaptPositionFromLighter,\n adaptPriceUpdateFromLighter,\n adaptPriceUpdateFromLighterWsStat,\n} from '../utils/lighterAdapter.js';\n\ntype LighterFillQuery = GetOrderFillsParams & {\n symbol?: string;\n};\n\ntype LighterMarginMetadata = {\n marketId: number;\n minInitial?: number;\n maintenance?: number;\n lastTradePrice?: number;\n};\n\ntype LighterOrderBookState = {\n bids: Map<string, string>;\n asks: Map<string, string>;\n nonce: number;\n};\n\nconst NOOP_UNSUBSCRIBE = (): void => undefined;\n\nconst LIGHTER_INACTIVE_HISTORY_ROW_LIMIT = 10_000;\n\nconst deriveLighterMaxLeverage = (\n minInitialMarginFraction: number | undefined,\n market: string | number,\n): number => {\n if (\n typeof minInitialMarginFraction !== 'number' ||\n !Number.isSafeInteger(minInitialMarginFraction) ||\n minInitialMarginFraction < 1 ||\n minInitialMarginFraction > 10_000\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid initial margin fraction for market ${String(market)}`,\n );\n }\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage < 1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid max leverage for market ${String(market)}`,\n );\n }\n return maxLeverage;\n};\n\nconst isInactiveMarketWithoutUsableRiskMetadata = (market: {\n status: string;\n minInitialMarginFraction?: number;\n maintenanceMarginFraction?: number;\n}): boolean =>\n // Lighter retains inactive rows for historical identity but can zero their\n // trading constraints. They are valid venue records, not usable markets.\n market.status === 'inactive' &&\n (market.minInitialMarginFraction === undefined ||\n market.minInitialMarginFraction === 0 ||\n market.maintenanceMarginFraction === 0);\n\nconst adaptLighterTransferDelta = (\n entry: LighterTransferHistoryItem,\n): RawLedgerUpdate['delta'] => {\n if (entry.type === 'L2TransferOutflow') {\n return { type: 'transferOut', usdc: `-${entry.amount}` };\n }\n if (entry.type === 'L2TransferInflow') {\n return { type: 'transferIn', usdc: entry.amount };\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown transfer type ${String(entry.type)}`,\n );\n};\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Full-string decimal/scientific literal (optional sign and exponent). */\n/**\n * Strict full-string numeric parsing shared with the adaptation boundary\n * (see lighterConfig.parseLighterStrictDecimal): '10USD' or '0.001BTC'\n * would prefix-parse into signed intent under bare parseFloat.\n */\nconst parseStrictDecimal = parseLighterStrictDecimal;\n\n/**\n * Parse caller-supplied numeric intent, accepting only finite positive\n * values from a strictly numeric string.\n *\n * @param value - Raw numeric string from params.\n * @returns The parsed number, or null when malformed, non-finite or\n * non-positive.\n */\nconst parseFinitePositive = (value: string): number | null => {\n const parsed = parseStrictDecimal(value);\n return parsed !== null && Number.isFinite(parsed) && parsed > 0\n ? parsed\n : null;\n};\n\n/**\n * Integerize a SIGNER-BOUND value: the scaled result must be a positive\n * safe wire integer. The positive-intent policy lives here, not in the\n * generic public converter.\n *\n * @param value - Human-units value.\n * @param decimals - Market/asset decimals.\n * @returns The positive wire integer.\n */\nconst toSignerWireInteger = (value: number, decimals: number): number => {\n const scaled = toLighterInteger(value, decimals);\n if (scaled < 1) {\n throw new Error(`Value ${value} rounds to zero at ${decimals} decimals`);\n }\n return scaled;\n};\n\n/**\n * Snap a base size onto the market's size grid exactly as wire\n * integerization will (round to nearest step). Minimum-size checks must\n * judge the SNAPPED size: a raw USD/price quotient one hair under the\n * minimum still reaches the venue as the valid minimum step, and\n * rejecting the raw quotient refuses orders the venue accepts.\n *\n * @param size - Raw base size (human units).\n * @param supportedSizeDecimals - Market size decimals.\n * @returns The grid-snapped size, or the input unchanged when it cannot\n * be integerized (range overflow) — later wire conversion fails closed.\n */\nconst snapToLighterSizeGrid = (\n size: number,\n supportedSizeDecimals: number,\n): number => {\n try {\n return fromLighterInteger(\n toLighterInteger(size, supportedSizeDecimals),\n supportedSizeDecimals,\n );\n } catch {\n return size;\n }\n};\n\n/**\n * Whether Lighter applies its documented maker-only order minimums.\n *\n * @param params - Order intent to classify.\n * @returns Whether the order rests as a maker order.\n */\nconst isLighterMakerOrder = (params: OrderParams): boolean =>\n params.orderType === 'limit' && params.timeInForce !== 'IOC';\n\n/**\n * Parse a candle field without JavaScript's null/boolean/blank coercions.\n *\n * @param value - Raw candle field from the venue.\n * @returns A finite number, or null when the field is malformed.\n */\nconst toFiniteCandleNumber = (value: unknown): number | null => {\n const parsed = typeof value === 'number' ? value : parseStrictDecimal(value);\n return parsed !== null && Number.isFinite(parsed) ? parsed : null;\n};\n\n/**\n * Map one venue candle onto the CandleStick contract, or null when any\n * field is non-finite. WS/REST candle payloads are cast at the boundary,\n * not validated — a malformed candle stringified blind reaches the chart\n * as \"undefined\"/NaN, the same native-SVG crash class the bare\n * order-book levels produced.\n *\n * @param candle - Raw venue candle.\n * @returns The contract candle, or null when unmappable.\n */\nconst toFiniteCandle = (candle: LighterCandle): CandleStick | null => {\n const time = toFiniteCandleNumber(candle?.t);\n const fields = [candle?.o, candle?.h, candle?.l, candle?.c, candle?.v].map(\n toFiniteCandleNumber,\n );\n if (time === null || fields.some((value) => value === null)) {\n return null;\n }\n const [open, high, low, close, volume] = fields as number[];\n return {\n time,\n open: String(open),\n high: String(high),\n low: String(low),\n close: String(close),\n volume: String(volume),\n };\n};\n\n/** The pinned signer casts price fields to uint32. */\nconst LIGHTER_MAX_WIRE_PRICE = 4_294_967_295;\n\n/**\n * One recorded TP/SL venue mutation attempt. Each attempt carries its own\n * nonce and outcome: a single flat flag cannot represent \"create accepted,\n * cancel #1 accepted, cancel #2 response-lost\".\n */\ntype TpslCreateAttempt = {\n kind: 'create';\n /**\n * Unique per-journal attempt identity. Nonces CANNOT identify\n * attempts: a proven-never-landed submission releases its nonce and a\n * retry legitimately reuses it.\n */\n attemptId: number;\n /** See TpslCancelAttempt.terminalStatus. */\n terminalStatus?: number;\n /** The venue nonce this submission attempted to consume. */\n nonce: number;\n /** 'accepted' only after the venue's 200 was OBSERVED. */\n outcome: 'unknown' | 'accepted';\n /** Created client ids (nonempty). */\n clientIds: number[];\n /** The signed transaction hash (known BEFORE submission). */\n txHash: string;\n /**\n * Signed payload expiry (ms). After this instant (+ clock slack) the\n * sequencer can no longer accept the payload, so a not-found hash is\n * authoritatively never-landed.\n */\n expiresAt: number;\n /** What this create IS: the replacement, or a restore of the old set. */\n role: 'replacement' | 'restore';\n /**\n * For role 'restore' only: the prior triggers (by original orderId in\n * `priorTriggers`) this attempt restores, INDEX-ALIGNED with\n * `clientIds` (a grouped OCO restore carries two legs). With multiple\n * prior triggers and a crash mid-restore, recovery uses this to\n * restore exactly the remaining intents — never duplicating or\n * omitting one.\n */\n priorOrderIds?: string[];\n};\n\ntype TpslCancelAttempt = {\n kind: 'cancel';\n /** Unique per-journal attempt identity (see TpslCreateAttempt). */\n attemptId: number;\n /**\n * Venue-reported terminal status (4 failed / 5 rejected) recorded by\n * reconciliation for an attempt that LANDED but did not mutate the\n * books — makes it compactable.\n */\n terminalStatus?: number;\n nonce: number;\n outcome: 'unknown' | 'accepted';\n /** The cancelled order id. */\n orderId: string;\n txHash: string;\n expiresAt: number;\n /** Whether this cancels OLD protection or rolls back a failed leg. */\n role: 'stale' | 'rollback';\n};\n\n/** A recorded TP/SL venue mutation attempt (discriminated by kind). */\ntype TpslAttempt = TpslCreateAttempt | TpslCancelAttempt;\n\n/**\n * The wire intent of a PRIOR trigger, persisted before it is cancelled so\n * a crash-then-terminal-failure can still RESTORE the old protection.\n */\ntype TpslPriorTrigger = {\n orderId: string;\n side: 'buy' | 'sell';\n /**\n * EXACT signer wire order type (2 stop-loss, 3 stop-loss-limit,\n * 4 take-profit, 5 take-profit-limit). A restore must rebuild the\n * prior order faithfully — never coerce a limit trigger to market.\n */\n wireOrderType: 2 | 3 | 4 | 5;\n /** Exact signer wire time-in-force (0 IOC, 1 GTT, 2 post-only). */\n wireTimeInForce: 0 | 1 | 2;\n /**\n * Venue-reported absolute order expiry (ms). Restores reuse it while\n * still in the future; otherwise the signer's default sentinel.\n */\n orderExpiry: number;\n /** Execution price (market triggers) or exact limit price. */\n price: string;\n /** User-facing trigger level. */\n triggerPrice: string;\n remainingSize: string;\n};\n\n/**\n * Identity of the position the journalled protection belonged to. A\n * delayed restore must never attach old triggers to a DIFFERENT\n * lifecycle (original closed, new same-symbol position opened).\n */\n/**\n * Durable nonce dispatch ledger document. Entries carry the OPERATION\n * kind (tx type) and a human-readable intent so a dispatch whose\n * response was lost but which is later PROVEN consumed can be surfaced\n * as a recovered outcome — blocking blind retries of financial\n * operations until explicitly acknowledged.\n */\ntype LighterRecoveredDispatch = {\n /** Stable identity for selective acknowledgment. */\n recoveryId: string;\n kind: number;\n intent: string;\n txHash: string | null;\n /**\n * Authoritative outcome: 'succeeded' (exact-hash lookup, venue status\n * executed), 'failed' (exact-hash lookup, venue status failed/rejected\n * — retry-safe, non-blocking), 'unknown' (only the nonce advance is\n * proven, e.g. another device moved the nonce; the intent's own fate\n * is NOT known and must never be reported as completed).\n */\n outcome: 'succeeded' | 'failed' | 'unknown';\n /** What proved the outcome (e.g. 'tx-status:2', 'rest-advance'). */\n evidence: string;\n};\n\ntype LighterNonceLedgerDoc = {\n consumedFloor: number;\n entries: {\n nonce: number;\n txHash: string | null;\n expiresAt: number | null;\n kind: number;\n intent: string;\n /**\n * Operation that owns reconciliation of this dispatch (a TP/SL\n * journal's operationId). Owned dispatches resolve through their\n * own state machine and are NEVER quarantined into the generic\n * recovered list — that would deadlock the machine behind an\n * acknowledgment it cannot give.\n */\n owner: string | null;\n }[];\n recovered: LighterRecoveredDispatch[];\n};\n\n/**\n * Durable transition state: 'creating' means the old protection is still\n * untouched (a failed replacement needs at most a rollback of surviving\n * legs); 'cancelling' means old cancels are underway/done; 'manual'\n * parks the obligation for explicit user re-establishment.\n */\ntype TpslJournalState = {\n attempts: TpslAttempt[];\n recordedAt: number;\n /**\n * IMMUTABLE identity of the operation this journal records. Clears and\n * updates are compare-and-swap on this id so a recovery pass holding a\n * STALE snapshot can never erase a newer operation's journal.\n */\n operationId: string;\n /** When the OPERATION began (immutable; `recordedAt` moves per write). */\n createdAt: number;\n /**\n * DURABLE monotonic attempt-id allocator: compaction removes attempts,\n * so deriving the next id from the surviving maximum could recycle an\n * identity a removed attempt already used.\n */\n nextAttemptId: number;\n /**\n * The durable OPERATION intent: a 'remove' journals only cancels and\n * must NEVER be \"recovered\" by restoring the cancelled protection —\n * that would silently undo an intentional removal.\n */\n intent: 'replace' | 'remove';\n /**\n * 'creating': old protection untouched (failure needs at most a\n * rollback of surviving replacement legs). 'cancelling': old cancels\n * underway/done. 'manual': the venue has NO atomic primitive that\n * could prove a restore attaches to the same position lifecycle, so a\n * fully-failed replacement after old cancels is NEVER auto-restored —\n * the journal parks durably in this state, is surfaced to callers via\n * `getPendingManualRecoveries`, and only an explicit NEW protection\n * intent from the user resolves it.\n */\n phase: 'creating' | 'cancelling' | 'manual';\n /**\n * Whether the prior set was a venue-linked auto-cancel TP+SL pair\n * (decided ONLY by the venue's own linkage fields).\n */\n priorGrouping: 'oco' | 'independent';\n priorTriggers: TpslPriorTrigger[];\n};\n\n/**\n * DURABLE manual-recovery record, SEPARATE from the settlement journal:\n * parking releases the journal slot (so a successor protection intent\n * can run), while this warning survives until a successor intent\n * SUCCEEDS — a failed successor must never erase the warning.\n */\ntype TpslManualRecovery = {\n settlementKey: string;\n symbol: string;\n /** Human-readable cause of the parked state. */\n reason: string;\n priorIntent: 'replace' | 'remove';\n /** Exact wire intents of the protection that was in place before. */\n priorTriggers: TpslPriorTrigger[];\n /** Venue order ids still on the books when the state was parked. */\n survivingOrderIds: string[];\n operationId: string;\n recordedAt: number;\n};\n\n/**\n * Clock slack added to a signed payload's ExpiredAt before a not-found\n * transaction hash is declared never-landed.\n */\nconst LIGHTER_TX_EXPIRY_SLACK_MS = 30_000;\n/** Maximum durable recovered-dispatch outcomes retained per nonce ledger. */\nconst LIGHTER_RECOVERED_DISPATCH_LIMIT = 32;\n/** Maximum durable TP/SL manual-recovery obligations retained per network. */\nconst LIGHTER_TPSL_MANUAL_RECOVERY_LIMIT = 64;\n\n/**\n * Extract the signed txHash and ExpiredAt from a bridge signing result,\n * failing CLOSED: without them the settlement journal cannot resolve a\n * lost response authoritatively, so the mutation must not be submitted.\n *\n * @param signed - Bridge signing result.\n * @param signed.txHash - Signed transaction hash (hex).\n * @param signed.txInfo - Signed wire payload JSON (carries ExpiredAt).\n * @returns The transaction hash and expiry (ms).\n */\nconst requireSignedTxIdentity = (signed: {\n txHash?: string;\n txInfo?: string;\n}): { txHash: string; expiresAt: number } => {\n const { txHash } = signed;\n if (\n typeof txHash !== 'string' ||\n !/^(0x)?[0-9a-fA-F]{8,128}$/u.test(txHash)\n ) {\n throw new Error(\n 'Lighter signing result carries no usable txHash; refusing to submit an unreconcilable mutation',\n );\n }\n let expiresAt: unknown;\n try {\n expiresAt = (JSON.parse(signed.txInfo ?? '') as Record<string, unknown>)\n .ExpiredAt;\n } catch {\n expiresAt = undefined;\n }\n if (\n typeof expiresAt !== 'number' ||\n !Number.isSafeInteger(expiresAt) ||\n expiresAt <= 0\n ) {\n throw new Error(\n 'Lighter signing result carries no usable ExpiredAt; refusing to submit an unreconcilable mutation',\n );\n }\n return { txHash, expiresAt };\n};\n\n/**\n * PROCESS-WIDE mutexes: venue write sections, the per-settlement journal\n * state machine, and journal/index read-modify-writes are serialized\n * across ALL provider instances in this runtime. Instance-local write\n * chains cannot protect two live providers sharing one venue account or\n * one disk cache. Completed tails are evicted to keep the map bounded.\n */\nconst processMutexTails = new Map<string, Promise<unknown>>();\n\n/**\n * Run an operation atomically w.r.t. every other holder of the same key\n * in this process.\n *\n * @param key - Key to serialize on.\n * @param operation - The critical operation.\n * @returns The operation's result.\n */\nconst withProcessMutex = async <Result>(\n key: string,\n operation: () => Promise<Result>,\n): Promise<Result> => {\n const tail = processMutexTails.get(key) ?? Promise.resolve();\n const run = tail.then(operation, operation);\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n processMutexTails.set(key, settled);\n settled\n .then(() => {\n // Evict when no newer holder queued behind us.\n if (processMutexTails.get(key) === settled) {\n processMutexTails.delete(key);\n }\n return undefined;\n })\n .catch(() => undefined);\n return await run;\n};\n\n/**\n * Storage-scoped alias of the process mutex (kept for call-site clarity).\n *\n * @param key - Storage key to serialize on.\n * @param operation - The read-modify-write.\n * @returns The operation's result.\n */\nconst withStorageMutex = withProcessMutex;\n\n/**\n * The WASM signer hosts ONE global client per bridge. These module maps\n * track which venue identity (`network:account:apiKey`) currently owns\n * each bridge's client, and give every bridge a process-unique mutex key\n * so all sign-and-dispatch sections across ALL provider instances\n * sharing a bridge are serialized and re-establish the correct client\n * before signing.\n */\n/**\n * Cryptographic randomness with a bounded Math.random fallback for hosts\n * without WebCrypto. Collision-resistant ids matter here: a recycled\n * operation id could let a stale journal resolver clear a live journal.\n *\n * @param byteCount - Number of random bytes.\n * @returns The random bytes.\n */\nconst randomBytes = (byteCount: number): Uint8Array => {\n const bytes = new Uint8Array(byteCount);\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoObj?.getRandomValues) {\n cryptoObj.getRandomValues(bytes);\n return bytes;\n }\n for (let index = 0; index < byteCount; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n return bytes;\n};\n\n/**\n * Two independent 24-bit random values (client order id halves).\n *\n * @returns The [high, low] pair.\n */\nconst randomUint24Pair = (): [number, number] => {\n const bytes = randomBytes(6);\n return [\n bytes[0] * 65_536 + bytes[1] * 256 + bytes[2],\n bytes[3] * 65_536 + bytes[4] * 256 + bytes[5],\n ];\n};\n\n/**\n * Collision-resistant id suffix (80 bits, hex).\n *\n * @returns The suffix string.\n */\nconst randomIdSuffix = (): string =>\n Array.from(randomBytes(10), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('');\n\nconst bridgeClientOwners = new WeakMap<object, string>();\nconst bridgeIds = new WeakMap<object, number>();\nlet nextBridgeId = 1;\n\n/**\n * Process-unique mutex key for a bridge instance.\n *\n * @param bridge - The signer bridge.\n * @returns The mutex key.\n */\nconst bridgeMutexKey = (bridge: object): string => {\n let id = bridgeIds.get(bridge);\n if (id === undefined) {\n id = nextBridgeId;\n nextBridgeId += 1;\n bridgeIds.set(bridge, id);\n }\n return `lighterBridge:${id}`;\n};\n\n/**\n * Parse a journal-pointer document, or null when the content is not a\n * pointer (legacy inline journal or corrupt data — both handled by the\n * caller's payload validation path).\n *\n * @param raw - Raw base-key content.\n * @returns The pointer, or null.\n */\nconst parseTpslJournalPointer = (\n raw: string,\n): { operationId: string } | null => {\n try {\n const parsed = JSON.parse(raw) as {\n pointerVersion?: unknown;\n operationId?: unknown;\n };\n if (\n parsed.pointerVersion === 1 &&\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length >= 1 &&\n parsed.operationId.length <= 64\n ) {\n return { operationId: parsed.operationId };\n }\n } catch {\n // Not JSON: not a pointer.\n }\n return null;\n};\n\n/**\n * Best-effort dispatch identity from a bridge signing result. The pinned\n * WASM contract (web-wasm light_client.go) returns `{txHash, txInfo}`\n * where txInfo is the marshaled wire payload — it carries Nonce and\n * ExpiredAt but NEVER the hash. Non-throwing: ops whose signers omit a\n * field dispatch with a partial identity (resolvable only by REST\n * advance, never by expiry).\n *\n * @param signed - Bridge signing result.\n * @param signed.txHash - Signed transaction hash from the RESULT.\n * @param signed.txInfo - Marshaled wire payload.\n * @returns The dispatch identity (null fields when unavailable).\n */\nconst extractDispatchIdentity = (signed: {\n txHash?: unknown;\n txInfo?: string;\n}): { txHash: string | null; expiresAt: number | null } => {\n const txHash =\n typeof signed.txHash === 'string' &&\n /^(0x)?[0-9a-fA-F]{8,128}$/u.test(signed.txHash)\n ? signed.txHash\n : null;\n let expiresAt: number | null = null;\n try {\n const wire = JSON.parse(signed.txInfo ?? '') as Record<string, unknown>;\n expiresAt =\n typeof wire.ExpiredAt === 'number' &&\n Number.isSafeInteger(wire.ExpiredAt) &&\n wire.ExpiredAt > 0\n ? wire.ExpiredAt\n : null;\n } catch {\n expiresAt = null;\n }\n return { txHash, expiresAt };\n};\n\n/**\n * Allocate the next unique attempt identity from the journal's DURABLE\n * monotonic counter (compaction can therefore never recycle an id).\n *\n * @param journal - The journal being appended to.\n * @returns The allocated attempt id.\n */\nconst nextAttemptIdFor = (journal: TpslJournalState): number => {\n const allocated = journal.nextAttemptId;\n journal.nextAttemptId += 1;\n return allocated;\n};\n\n/** Delay between TP/SL settlement visibility polls. */\nconst LIGHTER_TPSL_SETTLE_POLL_MS = 150;\n\n/** Bounded attempts for TP/SL settlement visibility. */\nconst LIGHTER_TPSL_SETTLE_ATTEMPTS = 10;\n\n/**\n * Integerize a signer-bound PRICE (order price / trigger price): the\n * pinned lighter-go signer casts these to uint32 (web-wasm/main.go), so a\n * safe-integer above 2^32-1 silently WRAPS (e.g. 429496729.7 at 1 decimal\n * scales to 4,294,967,297 and wires as 1).\n *\n * @param value - Human-units price.\n * @param decimals - Market price decimals.\n * @returns The positive uint32 wire integer.\n */\nconst toSignerWirePriceInteger = (value: number, decimals: number): number => {\n const scaled = toSignerWireInteger(value, decimals);\n if (scaled > LIGHTER_MAX_WIRE_PRICE) {\n throw new Error(\n `Price ${value} exceeds Lighter's uint32 wire range at ${decimals} decimals`,\n );\n }\n return scaled;\n};\n\n/**\n * Map a RAW venue trigger row to its durable prior wire intent, or null\n * when it cannot be faithfully restored: unknown type/TIF/expiry, a\n * MISSING trigger price (never substituted — that would change the\n * user's protection semantics), a malformed/non-positive decimal, or a\n * value that cannot be integerized onto the wire (range/sub-tick). The\n * writer must never persist state the loader (or the signer) would\n * later reject. A mutation that would cancel such a row must fail\n * closed BEFORE any cancel.\n *\n * @param raw - Raw venue order row.\n * @param market - Market integerization parameters.\n * @param market.supportedSizeDecimals - Size integerization decimals.\n * @param market.supportedPriceDecimals - Price integerization decimals.\n * @returns The exact prior wire intent, or null when unmappable.\n */\nconst mapRawTriggerToPriorIntent = (\n raw: LighterApiOrder,\n market: {\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n },\n): TpslPriorTrigger | null => {\n const wireOrderTypeByVenueType: Record<string, 2 | 3 | 4 | 5> = {\n 'stop-loss': 2,\n 'stop-loss-limit': 3,\n 'take-profit': 4,\n 'take-profit-limit': 5,\n };\n const wireTimeInForceByVenueTif: Record<string, 0 | 1 | 2> = {\n 'immediate-or-cancel': 0,\n 'good-till-time': 1,\n 'post-only': 2,\n };\n const wireOrderType = wireOrderTypeByVenueType[raw.type];\n const wireTimeInForce = wireTimeInForceByVenueTif[raw.timeInForce];\n if (\n wireOrderType === undefined ||\n wireTimeInForce === undefined ||\n !Number.isSafeInteger(raw.orderExpiry) ||\n raw.orderExpiry < -1 ||\n !/^\\d{1,20}$/u.test(String(raw.orderIndex)) ||\n // A trigger's trigger price is REQUIRED verbatim.\n typeof raw.triggerPrice !== 'string'\n ) {\n return null;\n }\n const price = parseStrictDecimal(raw.price);\n const triggerPrice = parseStrictDecimal(raw.triggerPrice);\n const remainingSize = parseStrictDecimal(raw.remainingBaseAmount);\n if (\n price === null ||\n !Number.isFinite(price) ||\n price <= 0 ||\n triggerPrice === null ||\n !Number.isFinite(triggerPrice) ||\n triggerPrice <= 0 ||\n remainingSize === null ||\n !Number.isFinite(remainingSize) ||\n remainingSize <= 0\n ) {\n return null;\n }\n // Wire PREFLIGHT: integerize exactly what a restore would sign. A\n // range/sub-tick failure here refuses the whole mutation up front.\n try {\n toSignerWireInteger(remainingSize, market.supportedSizeDecimals);\n toSignerWirePriceInteger(price, market.supportedPriceDecimals);\n toSignerWirePriceInteger(triggerPrice, market.supportedPriceDecimals);\n } catch {\n return null;\n }\n return {\n orderId: String(raw.orderIndex),\n side: raw.isAsk ? 'sell' : 'buy',\n wireOrderType,\n wireTimeInForce,\n orderExpiry: raw.orderExpiry,\n price: raw.price,\n triggerPrice: raw.triggerPrice,\n remainingSize: raw.remainingBaseAmount,\n };\n};\n\n/**\n * Validate caller leverage intent against what Lighter can represent.\n *\n * @param leverage - Requested leverage, if any.\n * @returns The exact rejection message, or null when acceptable.\n */\nconst lighterLeverageError = (leverage: number | undefined): string | null => {\n if (leverage === undefined) {\n return null;\n }\n if (!Number.isFinite(leverage) || !(leverage > 0)) {\n return `Invalid leverage ${leverage}: must be a positive number`;\n }\n // UpdateLeverage signs an initial margin fraction in hundredths of a\n // percent. The derived IMF must itself be a positive safe integer within\n // the venue's fraction range: huge finite leverage rounds it to zero,\n // tiny finite leverage (Number.MIN_VALUE) overflows the division to\n // Infinity, and sub-1x leverage exceeds a 100% margin fraction.\n const imfHundredths = Math.round(10_000 / leverage);\n if (\n !Number.isSafeInteger(imfHundredths) ||\n imfHundredths < 1 ||\n imfHundredths > 10_000\n ) {\n return `Invalid leverage ${leverage}: outside Lighter's representable leverage range`;\n }\n return null;\n};\n\n/**\n * Derive the protection/execution price a market order signs from its\n * reference price — shared by placement and both validators so wire-range\n * checks always inspect the exact value the signer receives.\n *\n * @param referencePrice - Fresh venue reference price.\n * @param isBuy - Order side; buys protect above, sells below.\n * @param slippageFraction - Slippage tolerance (validated < 1).\n * @returns The slippage-adjusted execution price.\n */\nconst deriveLighterExecutionPrice = (\n referencePrice: number,\n isBuy: boolean,\n slippageFraction: number,\n): number =>\n isBuy\n ? referencePrice * (1 + slippageFraction)\n : referencePrice * (1 - slippageFraction);\n\nconst LIGHTER_NOT_SUPPORTED_ERROR = 'Lighter operation not yet supported';\nconst LIGHTER_SIGNER_UNAVAILABLE_ERROR = 'Lighter signer bridge not configured';\nconst LIGHTER_MAINNET_EXPLORER_URL = 'https://scan.lighter.xyz';\nconst LIGHTER_TESTNET_EXPLORER_URL = 'https://testnet.zklighter.elliot.ai';\n\n/** A definitive venue response that the selected wallet has no account. */\nclass LighterAccountNotFoundError extends Error {\n constructor(address: string) {\n super(\n `No Lighter account exists for ${address}; fund it via the bridge (or the testnet faucet) first`,\n );\n this.name = 'LighterAccountNotFoundError';\n }\n}\n\n/**\n * Empty account state returned when reads fail or no account exists.\n */\nconst EMPTY_ACCOUNT_STATE: AccountState = {\n totalBalance: '0',\n spendableBalance: '0',\n withdrawableBalance: '0',\n marginUsed: '0',\n unrealizedPnl: '0',\n returnOnEquity: '0',\n providerId: 'lighter',\n};\n\n// ============================================================================\n// LighterProvider\n// ============================================================================\n\n/**\n * Lighter provider implementation (POC).\n */\nexport class LighterProvider implements PerpsProvider {\n readonly protocolId = 'lighter';\n\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #clientService: LighterClientService;\n\n readonly #walletService: LighterWalletService;\n\n readonly #messenger: PerpsControllerMessenger | null;\n\n readonly #signerBridge: LighterSignerBridge | null;\n\n #signerResetUnsubscribe: (() => void) | null = null;\n\n readonly #isTestnet: boolean;\n\n readonly #apiKeyIndex: number;\n\n readonly #configuredAccountIndex: number | undefined;\n\n /** Markets cache keyed by symbol (freshness delegated to client service). */\n #marketsBySymbol: Map<string, LighterOrderBookMeta> = new Map();\n\n #marketsById: Map<number, LighterOrderBookMeta> = new Map();\n\n /** Resolved Lighter account index (after ensureAccount()). */\n #accountIndex: number | null = null;\n\n /** L1 address the current venue session (index/signer/auth) is bound to. */\n #boundAddress: string | null = null;\n\n /** Terminal lifecycle fence set by disconnect(). */\n #isDisconnected = false;\n\n /**\n * Monotonic counter bumped on every session rebind. Async resolutions\n * capture it before awaiting and refuse to cache results from a stale\n * generation (an account-A lookup resolving after the switch to B).\n */\n #sessionGeneration = 0;\n\n /** Active price-stream subscribers (REST polling fan-out). */\n readonly #priceSubscribers: Set<SubscribePricesParams> = new Set();\n\n #pricePollTimer: ReturnType<typeof setInterval> | null = null;\n\n #priceWs: LighterWebSocketLike | null = null;\n\n /** Injectable WebSocket constructor (null → REST polling fallback). */\n readonly #webSocketCtor: LighterWebSocketCtor | null;\n\n /** Channels the shared socket should be subscribed to (subscribe payloads). */\n readonly #wsWantedChannels: Map<string, { auth?: string }> = new Map();\n\n #wsKeepaliveTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Live WS connection state, mirrored to subscribed listeners. */\n #connectionState: WebSocketConnectionState =\n WebSocketConnectionState.Disconnected;\n\n /** Consecutive reconnect attempts since the last successful open. */\n #wsReconnectAttempts = 0;\n\n readonly #connectionListeners = new Set<\n (state: WebSocketConnectionState, reconnectionAttempt: number) => void\n >();\n\n readonly #setConnectionState = (state: WebSocketConnectionState): void => {\n if (this.#connectionState === state) {\n return;\n }\n this.#connectionState = state;\n for (const listener of this.#connectionListeners) {\n try {\n listener(state, this.#wsReconnectAttempts);\n } catch (error) {\n this.#logSubscriberError('connection-state', error);\n }\n }\n };\n\n #wsReconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Merged latest price per symbol, replayed to late price subscribers. */\n readonly #lastPriceBySymbol: Map<string, PriceUpdate> = new Map();\n\n /** Merged live position state from account_all_positions (keyed marketId). */\n readonly #wsPositions: Map<number, Position> = new Map();\n\n /** Merged live open orders from account_all_orders (keyed orderId). */\n readonly #wsOrders: Map<string, Order> = new Map();\n\n readonly #oiCapSubscribers: Set<SubscribeOICapsParams> = new Set();\n\n readonly #accountSubscribers: Set<SubscribeAccountParams> = new Set();\n\n readonly #positionSubscribers: Set<SubscribePositionsParams> = new Set();\n\n readonly #orderSubscribers: Set<SubscribeOrdersParams> = new Set();\n\n readonly #fillSubscribers: Set<SubscribeOrderFillsParams> = new Set();\n\n /** Order-book subscribers keyed by market id. */\n readonly #orderBookSubscribers: Map<number, Set<SubscribeOrderBookParams>> =\n new Map();\n\n /** Live order-book level state per market (price → size). */\n readonly #orderBookState: Map<number, LighterOrderBookState> = new Map();\n\n /** Candle subscribers keyed by `marketId:resolution`. */\n readonly #candleSubscribers: Map<string, Set<SubscribeCandlesParams>> =\n new Map();\n\n /** Cached candle series per `marketId:resolution` (keyed by open time). */\n readonly #candleSeries: Map<string, Map<number, CandleStick>> = new Map();\n\n /** Dedup for the async account-channel setup. */\n #accountChannelsPromise: Promise<void> | null = null;\n\n /** Derived venue public key hex, set after the signer client is created. */\n #venuePublicKey: string | null = null;\n\n /** Signer session dedup. */\n #signerReadyPromise: Promise<void> | null = null;\n\n /** Cached auth token (deadline-managed). */\n #authToken: { token: string; deadline: number } | null = null;\n\n constructor(options: {\n isTestnet?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger?: PerpsControllerMessenger;\n lighterAuthConfig?: LighterAuthConfig;\n signerBridge?: LighterSignerBridge;\n webSocketCtor?: LighterWebSocketCtor | null;\n }) {\n this.#deps = options.platformDependencies;\n this.#isTestnet = options.isTestnet ?? true;\n this.#messenger = options.messenger ?? null;\n this.#signerBridge = options.signerBridge ?? null;\n this.#ensureSignerResetListener();\n const globalWebSocket = Reflect.get(globalThis, 'WebSocket') as\n | LighterWebSocketCtor\n | undefined;\n const defaultWebSocketCtor =\n typeof globalWebSocket === 'function' ? globalWebSocket : null;\n this.#webSocketCtor =\n options.webSocketCtor === undefined\n ? defaultWebSocketCtor\n : options.webSocketCtor;\n this.#apiKeyIndex =\n options.lighterAuthConfig?.apiKeyIndex ?? LIGHTER_DEFAULT_API_KEY_INDEX;\n this.#configuredAccountIndex = options.lighterAuthConfig?.accountIndex;\n\n this.#clientService = new LighterClientService(this.#deps, {\n isTestnet: this.#isTestnet,\n });\n this.#walletService = new LighterWalletService(this.#deps, {\n isTestnet: this.#isTestnet,\n messenger: options.messenger,\n personalSigner: options.lighterAuthConfig?.personalSigner,\n l1Address: options.lighterAuthConfig?.l1Address,\n });\n\n this.#deps.debugLogger.log('[LighterProvider] Constructor complete', {\n protocolId: this.protocolId,\n isTestnet: this.#isTestnet,\n hasMessenger: Boolean(this.#messenger),\n hasSignerBridge: Boolean(this.#signerBridge),\n apiKeyIndex: this.#apiKeyIndex,\n });\n }\n\n // ============================================================================\n // Error Context Helper\n // ============================================================================\n\n readonly #getErrorContext = (\n method: string,\n extra?: Record<string, unknown>,\n ): {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n } => {\n return {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: 'LighterProvider',\n network: this.#isTestnet ? 'testnet' : 'mainnet',\n },\n context: {\n name: `LighterProvider.${method}`,\n data: {\n isTestnet: this.#isTestnet,\n ...extra,\n },\n },\n };\n };\n\n // ============================================================================\n // Initialization & Lifecycle\n // ============================================================================\n\n async initialize(): Promise<InitializeResult> {\n try {\n const markets = await this.#clientService.getOrderBooks(true);\n if (this.#isDisconnected) {\n return { success: false, error: 'Lighter provider is disconnected' };\n }\n this.#marketsBySymbol = new Map(\n markets.map((market) => [market.symbol, market]),\n );\n this.#marketsById = new Map(\n markets.map((market) => [market.marketId, market]),\n );\n this.#deps.debugLogger.log('[LighterProvider] Initialized', {\n markets: markets.length,\n });\n return { success: true };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.initialize',\n );\n this.#deps.debugLogger.log('[LighterProvider] initialize failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('initialize'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async disconnect(): Promise<DisconnectResult> {\n // A disconnect (provider switch, shutdown) invalidates the whole\n // session: an in-flight write paused inside the lock must fail its\n // fences instead of submitting after the provider was torn down.\n this.#isDisconnected = true;\n this.#invalidateSessionState();\n this.#removeSignerResetListener();\n this.#teardownStream();\n this.#priceSubscribers.clear();\n this.#oiCapSubscribers.clear();\n this.#accountSubscribers.clear();\n this.#positionSubscribers.clear();\n this.#orderSubscribers.clear();\n this.#fillSubscribers.clear();\n this.#orderBookSubscribers.clear();\n this.#candleSubscribers.clear();\n return { success: true };\n }\n\n async ping(_timeoutMs?: number): Promise<void> {\n await this.#clientService.getOrderBooks();\n }\n\n async toggleTestnet(): Promise<ToggleTestnetResult> {\n // Network is fixed at construction.\n return {\n success: false,\n isTestnet: this.#isTestnet,\n error: 'Lighter network is fixed at construction',\n };\n }\n\n async isReadyToTrade(): Promise<ReadyToTradeResult> {\n try {\n if (!this.#signerBridge) {\n return {\n ready: false,\n error: LIGHTER_SIGNER_UNAVAILABLE_ERROR,\n walletConnected: false,\n networkSupported: true,\n };\n }\n await this.#ensureSignerReady();\n return {\n ready: true,\n walletConnected: true,\n networkSupported: true,\n authenticatedAddress: this.#walletService.getUserAddress(),\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.isReadyToTrade',\n );\n return {\n ready: false,\n error: wrappedError.message,\n walletConnected: false,\n networkSupported: true,\n };\n }\n }\n\n // ============================================================================\n // Signer session\n // ============================================================================\n\n /**\n * The RAW bridge instance — the STABLE identity object for the\n * process-wide ownership map and mutex key. The `#getSignerBridge`\n * wrapper below is a fresh object per call and must NEVER key either.\n *\n * @returns The raw signer bridge.\n */\n readonly #rawSignerBridge = (): LighterSignerBridge => {\n if (!this.#signerBridge) {\n throw new Error(LIGHTER_SIGNER_UNAVAILABLE_ERROR);\n }\n return this.#signerBridge;\n };\n\n readonly #getSignerBridge = (): LighterSignerBridge => {\n if (!this.#signerBridge) {\n throw new Error(LIGHTER_SIGNER_UNAVAILABLE_ERROR);\n }\n const bridge = this.#signerBridge;\n // The WASM client lives inside the bridge host (mobile: a WebView that\n // can reload and lose it). When the venue signer reports a missing\n // client, drop the cached session so the next call re-runs setup\n // instead of failing forever against a resolved-but-dead session.\n return {\n createClient: async (params): Promise<LighterCreateClientResult> => {\n try {\n const result = await bridge.createClient(params);\n if (result.error) {\n this.#invalidateSignerSession();\n }\n return result;\n } catch (error) {\n this.#invalidateSignerSession();\n throw error;\n }\n },\n execute: async <Operation extends LighterSignerOperation>(\n call: LighterWasmCall<Operation>,\n ): Promise<LighterSignerResult<Operation>> => {\n const lostClientPattern =\n /client is not created|WebView reloaded|signer not ready|executor not connected|timed out/iu;\n try {\n const result = await bridge.execute(call);\n const error = (result as { error?: string } | null)?.error;\n if (error && lostClientPattern.test(error)) {\n this.#invalidateSignerSession();\n }\n return result;\n } catch (error) {\n if (lostClientPattern.test(String(error))) {\n this.#invalidateSignerSession();\n }\n throw error;\n }\n },\n };\n };\n\n readonly #invalidateSignerSession = (): void => {\n // Advancing the generation aborts any in-flight setup/write that was\n // started against the now-dead WASM client.\n this.#sessionGeneration += 1;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#clearBridgeOwnership();\n this.#deps.debugLogger.log(\n '[LighterProvider] signer session invalidated (client lost); will re-setup on next call',\n );\n };\n\n /** Replace this provider's listener on the client-owned signer bridge. */\n readonly #replaceSignerResetListener = (): void => {\n this.#removeSignerResetListener();\n this.#ensureSignerResetListener();\n };\n\n /** Install the reset listener when the current binding has none. */\n readonly #ensureSignerResetListener = (): void => {\n if (this.#isDisconnected || this.#signerResetUnsubscribe) {\n return;\n }\n this.#signerResetUnsubscribe =\n this.#signerBridge?.onReset?.(() => this.#invalidateSignerSession()) ??\n null;\n };\n\n /** Remove this provider's listener when its session is retired. */\n readonly #removeSignerResetListener = (): void => {\n this.#signerResetUnsubscribe?.();\n this.#signerResetUnsubscribe = null;\n };\n\n /**\n * Drop ALL bridge-client ownership material for this provider: the\n * identity, the recreate params, and — when WE are the recorded owner\n * — the process-wide ownership entry, so a dead/rebound session can\n * never be mistaken for the live owner of the singleton client.\n */\n readonly #clearBridgeOwnership = (): void => {\n if (\n this.#signerBridge &&\n this.#signerIdentity !== null &&\n bridgeClientOwners.get(this.#signerBridge) === this.#signerIdentity\n ) {\n bridgeClientOwners.delete(this.#signerBridge);\n }\n this.#signerIdentity = null;\n this.#signerRecreateParams = null;\n };\n\n /**\n * Bind the venue session to the currently selected wallet address.\n *\n * Everything downstream — account index, venue signer, auth token, and\n * the account-scoped stream channels — is derived from one L1 address.\n * When the wallet switches accounts, all of it must be dropped\n * atomically or reads/writes would keep targeting the previous account.\n */\n readonly #ensureSessionBinding = (): void => {\n if (this.#isDisconnected) {\n return;\n }\n let address: string;\n try {\n address = this.#walletService.getUserAddress().toLowerCase();\n } catch {\n if (this.#boundAddress !== null) {\n // All accounts deselected while a session existed: invalidate so\n // nothing in flight can still act for the old account.\n this.#emitAccountBindingReset();\n this.#invalidateSessionState();\n this.#removeSignerResetListener();\n this.#teardownStream();\n }\n // The caller's own address resolution surfaces the error.\n return;\n }\n if (this.#boundAddress === address) {\n return;\n }\n const hadPreviousBinding = this.#boundAddress !== null;\n this.#boundAddress = address;\n if (!hadPreviousBinding) {\n this.#ensureSignerResetListener();\n // First binding (or first after a deselection): surviving\n // subscribers may be sitting on an empty channel set.\n if (this.#hasAnySubscriber() && this.#wsWantedChannels.size === 0) {\n this.#rebuildStreamForSubscribers();\n }\n return;\n }\n // Invalidate in-flight async resolutions started under the previous\n // binding: they compare this generation after their awaits and retry\n // instead of caching results for the wrong account.\n this.#sessionGeneration += 1;\n this.#accountIndex = null;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#replaceSignerResetListener();\n // #tpslUnsettled is NOT cleared: entries are keyed by\n // address+accountIndex+symbol, so B never consumes A's pending ids and\n // switching back to A retains its reconciliation obligation.\n this.#emitAccountBindingReset();\n this.#teardownStream();\n this.#rebuildStreamForSubscribers();\n this.#deps.debugLogger.log(\n '[LighterProvider] session rebound to new wallet account',\n );\n };\n\n /** Clear subscriber-visible account data before a wallet rebind. */\n readonly #emitAccountBindingReset = (): void => {\n for (const subscriber of this.#accountSubscribers) {\n try {\n subscriber.callback(EMPTY_ACCOUNT_STATE);\n } catch (error) {\n this.#logSubscriberError('account', error);\n }\n }\n for (const subscriber of this.#positionSubscribers) {\n try {\n subscriber.callback([]);\n } catch (error) {\n this.#logSubscriberError('positions', error);\n }\n }\n this.#emitToOrderSubscribers([]);\n };\n\n /**\n * Re-request every channel the current subscriber registries imply.\n *\n * #teardownStream clears the wanted-channel intents; without this,\n * subscribers that outlive an account switch would sit on a fresh socket\n * subscribed to nothing.\n */\n readonly #rebuildStreamForSubscribers = (): void => {\n if (this.#isDisconnected || !this.#hasAnySubscriber()) {\n return;\n }\n if (this.#priceSubscribers.size > 0 || this.#oiCapSubscribers.size > 0) {\n this.#requestChannel('market_stats/all');\n }\n for (const marketId of this.#orderBookSubscribers.keys()) {\n this.#requestChannel(`order_book/${marketId}`);\n }\n for (const seriesKey of this.#candleSubscribers.keys()) {\n // Series keys are `${marketId}:${resolution}`; the channel form uses\n // slashes. The teardown cleared the series state, and the message\n // router drops updates for unknown series — recreate an empty series\n // so live candles flow again (history reseeds on the next fetch).\n this.#candleSeries.set(seriesKey, new Map());\n this.#requestChannel(`candle/${seriesKey.replace(':', '/')}`);\n }\n if (\n this.#accountSubscribers.size > 0 ||\n this.#positionSubscribers.size > 0 ||\n this.#orderSubscribers.size > 0 ||\n this.#fillSubscribers.size > 0\n ) {\n // The promise was cleared by the teardown, so this re-resolves the\n // account channels against the newly bound address.\n this.#ensureAccountChannels();\n }\n this.#ensureStream();\n };\n\n /**\n * Resolve the Lighter account index for the current user.\n *\n * @returns The account index.\n */\n readonly #ensureAccountIndex = async (): Promise<number> => {\n this.#ensureSessionBinding();\n // Account-bound work requires a bound wallet — including the cached\n // fast path and the configured-index path.\n this.#assertSession(this.#sessionGeneration);\n if (this.#accountIndex !== null) {\n return this.#accountIndex;\n }\n if (this.#configuredAccountIndex !== undefined) {\n // A configured index must be a Standard (0-fee) account AND owned by\n // the bound wallet address: a signed-in wallet must never read or\n // trade another owner's account just because an env var names it.\n const generationAtCheck = this.#sessionGeneration;\n const configured = await this.#clientService.getAccountByIndex(\n this.#configuredAccountIndex,\n );\n this.#ensureSessionBinding();\n if (generationAtCheck !== this.#sessionGeneration) {\n return await this.#ensureAccountIndex();\n }\n const configuredAccount = configured.accounts[0];\n this.#assertStandardAccount(configuredAccount?.accountType);\n const ownerAddress = configuredAccount?.l1Address?.toLowerCase();\n if (!ownerAddress || ownerAddress !== this.#boundAddress) {\n // Capability-prefixed so read catches SURFACE it instead of\n // degrading a cross-owner misconfiguration into empty state.\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} configured account ${this.#configuredAccountIndex} is not owned by the selected wallet address`,\n );\n }\n this.#accountIndex = this.#configuredAccountIndex;\n return this.#accountIndex;\n }\n const generation = this.#sessionGeneration;\n const address = this.#walletService.getUserAddress();\n let response: LighterAccountsByL1AddressResponse;\n try {\n response = await this.#clientService.getAccountsByL1Address(address);\n } catch (error) {\n if (error instanceof LighterApiError && error.code === 21100) {\n throw new LighterAccountNotFoundError(address);\n }\n throw error;\n }\n // Re-run the binding so an EXTERNAL switch nothing else observed also\n // advances the generation, then compare: caching after any switch\n // would poison the new session with the old account. Retry instead.\n this.#ensureSessionBinding();\n if (generation !== this.#sessionGeneration) {\n return await this.#ensureAccountIndex();\n }\n if (!response.subAccounts?.length) {\n throw new LighterAccountNotFoundError(address);\n }\n const master = response.subAccounts.reduce((min, account) =>\n account.index < min.index ? account : min,\n );\n this.#assertStandardAccount(master.accountType);\n this.#accountIndex = master.index;\n return this.#accountIndex;\n };\n\n /**\n * Capability gate: only Standard (0-fee) Lighter accounts are supported.\n * Premium accounts pay nonzero maker/taker fees whose wire unit is\n * unverified — serving their history would show financially false zero\n * fees, so the whole account-bound surface refuses instead.\n *\n * @param accountType - Venue account type code (0 = Standard).\n */\n readonly #assertStandardAccount = (accountType: number | undefined): void => {\n // Fail closed: only a PROVEN Standard (type 0) account passes. A\n // missing account/type is not evidence of Standard.\n if (accountType === undefined) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} account type could not be verified (account not found); refusing to assume a Standard account`,\n );\n }\n if (accountType !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} Premium accounts are not supported yet: their fee semantics are unverified and history would be financially incorrect`,\n );\n }\n };\n\n /**\n * Whether an error is an explicit capability gate (unsupported account\n * tier / unverified fee semantics). These must SURFACE to callers —\n * swallowing them into empty state would present false data.\n *\n * @param error - Caught error.\n * @returns True for capability-gate errors.\n */\n readonly #isUnsupportedCapabilityError = (error: unknown): boolean =>\n String(error).includes(LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX);\n\n readonly #isDataIntegrityError = (error: unknown): boolean =>\n String(error).includes(LIGHTER_DATA_INTEGRITY_PREFIX);\n\n /**\n * Whether a read error represents an explicit non-empty state.\n *\n * @param error - Caught read error.\n * @returns Whether the error must surface to the caller.\n */\n readonly #mustSurfaceReadError = (error: unknown): boolean =>\n this.#isUnsupportedCapabilityError(error) ||\n this.#isDataIntegrityError(error);\n\n /**\n * TP/SL settlement expectations that timed out before becoming visible\n * on the venue's REST book, per symbol. While an entry exists, further\n * TP/SL mutations for that symbol must reconcile it first.\n */\n readonly #tpslUnsettled = new Map<string, TpslJournalState>();\n\n /**\n * Session-global nonce reservation per `accountIndex:apiKeyIndex`.\n * Advanced at submission DISPATCH; consulted by every write-lock\n * section so a lagging nextNonce endpoint can never reissue a nonce an\n * earlier (possibly response-lost) submission may have consumed. A\n * reconciliation that PROVES a submission never landed (exact-hash\n * not-found after signed expiry) releases the reservation again.\n */\n readonly #nonceReservations = new Map<string, number>();\n\n /** Monotonic source for journal operation ids within this session. */\n #tpslOperationCounter = 0;\n\n /** This provider's bridge-client ownership identity (set at setup). */\n #signerIdentity: string | null = null;\n\n /**\n * Parameters to re-create OUR venue client on the shared bridge. The\n * wallet-derived seed is NEVER retained here — it is re-derived under\n * the bridge lease each time re-establishment is needed.\n */\n #signerRecreateParams: {\n chainId: number;\n accountIndex: number;\n } | null = null;\n\n /**\n * Durable dispatch-ledger key: every nonce-consuming submission is\n * recorded here BEFORE dispatch so a restart can never reissue a nonce\n * whose outcome is unknown, and a proven never-landed dispatch can\n * release its nonce for the venue to consume.\n *\n * @param accountIndex - Venue account index.\n * @returns The disk-cache key.\n */\n readonly #nonceLedgerKey = (accountIndex: number): string =>\n `lighterNonceLedger:${this.#isTestnet ? 'testnet' : 'mainnet'}:${accountIndex}:${this.#apiKeyIndex}`;\n\n /**\n * Read and strictly validate the durable dispatch ledger. Corruption\n * fails CLOSED (writes stay blocked) — guessing at nonce state could\n * duplicate or wedge submissions.\n *\n * @param accountIndex - Venue account index.\n * @returns The ledger document (consumed-nonce watermark + unresolved\n * dispatch entries).\n */\n readonly #readNonceLedger = async (\n accountIndex: number,\n ): Promise<LighterNonceLedgerDoc> => {\n let raw: string | null;\n try {\n raw = await this.#deps.diskCache.getItem(\n this.#nonceLedgerKey(accountIndex),\n );\n } catch (error) {\n throw new Error(\n `Lighter nonce ledger read failed; refusing writes: ${ensureError(error, 'LighterProvider.#readNonceLedger').message}`,\n );\n }\n if (raw === null) {\n return { consumedFloor: 0, entries: [], recovered: [] };\n }\n try {\n const parsed = JSON.parse(raw) as {\n version?: unknown;\n consumedFloor?: unknown;\n entries?: unknown;\n recovered?: unknown;\n };\n // EXPLICIT schema evolution: earlier documents (v1 without the\n // consumed watermark, v2 without operation kind/intent) migrate in\n // place — calling valid outstanding dispatch state corrupt would\n // block writes permanently.\n const consumedFloor =\n parsed.version === 1 && parsed.consumedFloor === undefined\n ? 0\n : parsed.consumedFloor;\n if (\n (parsed.version === 1 ||\n parsed.version === 2 ||\n parsed.version === 3 ||\n parsed.version === 4) &&\n typeof consumedFloor === 'number' &&\n Number.isSafeInteger(consumedFloor) &&\n consumedFloor >= 0 &&\n Array.isArray(parsed.entries) &&\n parsed.entries.length <= 16 &&\n parsed.entries.every((entry) => {\n if (typeof entry !== 'object' || entry === null) {\n return false;\n }\n const candidate = entry as Record<string, unknown>;\n return (\n typeof candidate.nonce === 'number' &&\n Number.isSafeInteger(candidate.nonce) &&\n candidate.nonce >= 0 &&\n (candidate.txHash === null ||\n typeof candidate.txHash === 'string') &&\n (candidate.expiresAt === null ||\n (typeof candidate.expiresAt === 'number' &&\n Number.isSafeInteger(candidate.expiresAt) &&\n candidate.expiresAt > 0))\n );\n })\n ) {\n // v4 recovered outcomes are safety state: silently dropping a\n // malformed or overflow row could make a completed/unknown\n // financial intent retryable. Older schemas predate the list.\n const recoveredRaw = parsed.version === 4 ? parsed.recovered : [];\n if (\n !Array.isArray(recoveredRaw) ||\n recoveredRaw.length > LIGHTER_RECOVERED_DISPATCH_LIMIT ||\n !recoveredRaw.every((row): row is LighterRecoveredDispatch => {\n if (typeof row !== 'object' || row === null) {\n return false;\n }\n const candidate = row as Record<string, unknown>;\n return (\n typeof candidate.recoveryId === 'string' &&\n candidate.recoveryId.length >= 1 &&\n candidate.recoveryId.length <= 160 &&\n typeof candidate.kind === 'number' &&\n typeof candidate.intent === 'string' &&\n candidate.intent.length <= 200 &&\n (candidate.txHash === null ||\n typeof candidate.txHash === 'string') &&\n (candidate.outcome === 'succeeded' ||\n candidate.outcome === 'failed' ||\n candidate.outcome === 'unknown') &&\n typeof candidate.evidence === 'string'\n );\n })\n ) {\n throw new Error('Malformed recovered-dispatch safety state');\n }\n const recovered = recoveredRaw;\n return {\n consumedFloor,\n entries: (\n parsed.entries as {\n nonce: number;\n txHash: string | null;\n expiresAt: number | null;\n kind?: number;\n intent?: string;\n owner?: string | null;\n }[]\n ).map((entry) => ({\n ...entry,\n // v1-v3 migration: kind/intent/owner unknown.\n kind: typeof entry.kind === 'number' ? entry.kind : -1,\n intent: typeof entry.intent === 'string' ? entry.intent : 'unknown',\n owner: typeof entry.owner === 'string' ? entry.owner : null,\n })),\n recovered,\n };\n }\n } catch {\n // fall through to fail closed\n }\n throw new Error(\n 'Lighter nonce dispatch ledger is corrupt; refusing further writes until it is resolved',\n );\n };\n\n /**\n * Persist the dispatch ledger document.\n *\n * @param accountIndex - Venue account index.\n * @param doc - The ledger document.\n * @param doc.consumedFloor - Highest proven-consumed nonce + 1.\n * @param doc.entries - Unresolved dispatch entries.\n */\n readonly #writeNonceLedger = async (\n accountIndex: number,\n doc: LighterNonceLedgerDoc,\n ): Promise<void> => {\n await this.#deps.diskCache.setItem(\n this.#nonceLedgerKey(accountIndex),\n JSON.stringify({ version: 4, ...doc }),\n );\n };\n\n /**\n * Resolve one dispatch entry as CONSUMED: remove it and advance the\n * durable consumed-nonce watermark so no later (stale) reconciliation\n * can ever release the nonce back.\n *\n * @param accountIndex - Venue account index.\n * @param entry - The consumed entry.\n * @param entry.nonce - The dispatched nonce.\n * @param entry.txHash - The dispatched tx hash (or null).\n */\n /**\n * EVERY ledger read-modify-write (append, resolve, consumed-resolve,\n * selective acknowledgment) serializes on this ONE process-wide mutex\n * per account+slot document. The venue write mutex alone cannot\n * protect the document: `acknowledgeRecoveredDispatch` legitimately\n * runs OUTSIDE it, and an unserialized ack RMW could overwrite a\n * concurrent append with a stale doc — silently erasing an unresolved\n * dispatch entry. Lock order is always venueWrite → bridge → ledger\n * (the ack path takes only the ledger mutex), so no cycle exists.\n *\n * @param accountIndex - Venue account index.\n * @param operation - The ledger RMW critical section.\n * @returns The operation's result.\n */\n readonly #withLedgerLock = async <Result>(\n accountIndex: number,\n operation: () => Promise<Result>,\n ): Promise<Result> =>\n await withProcessMutex(this.#nonceLedgerKey(accountIndex), operation);\n\n /**\n * Append a recovered dispatch without ever sacrificing a blocking\n * succeeded/unknown outcome to bounded storage. Retry-safe failures may\n * be omitted at capacity; a blocking outcome may replace one such row.\n * If every retained row is already blocking, fail before persistence so\n * the original unresolved ledger entry remains authoritative.\n *\n * @param doc - Mutable nonce ledger document held under its mutex.\n * @param outcome - Recovered dispatch to retain when safety requires it.\n */\n readonly #appendRecoveredDispatch = (\n doc: LighterNonceLedgerDoc,\n outcome: LighterRecoveredDispatch,\n ): void => {\n if (\n doc.recovered.some(\n (candidate) => candidate.recoveryId === outcome.recoveryId,\n )\n ) {\n return;\n }\n if (doc.recovered.length < LIGHTER_RECOVERED_DISPATCH_LIMIT) {\n doc.recovered.push(outcome);\n return;\n }\n if (outcome.outcome === 'failed') {\n return;\n }\n const failedIndex = doc.recovered.findIndex(\n (candidate) => candidate.outcome === 'failed',\n );\n if (failedIndex < 0) {\n throw new Error(\n 'Lighter recovered-dispatch ledger is full of unresolved blocking outcomes; refusing to discard the current dispatch',\n );\n }\n doc.recovered.splice(failedIndex, 1, outcome);\n };\n\n /**\n * ATOMIC post-dispatch entry transition, decided by the session fence\n * BEFORE any ledger mutation: fence passed → the entry is consumed and\n * removed (watermark advances); fence failed → the entry converts to a\n * durable recovered SUCCEEDED outcome (the venue mutation is committed\n * and a later retry under the original account would double the\n * financial intent). Both shapes land in ONE write under the ledger\n * lock — if that write fails, the ORIGINAL unresolved entry remains\n * the durable record and every retry stays blocked. The entry is never\n * consumed first and quarantined second. TP/SL-journal-owned entries\n * are consumed without quarantine in both cases (their machine\n * reconciles the intent by exact hash).\n *\n * @param accountIndex - Venue account index of the ORIGINAL session.\n * @param entry - The dispatched (accepted) ledger entry.\n * @param fenceFailed - Whether the post-send session fence rejected.\n * @returns Resolves when the transition is durably committed.\n */\n readonly #resolveEntryPostDispatch = async (\n accountIndex: number,\n entry: LighterNonceLedgerDoc['entries'][number],\n fenceFailed: boolean,\n ): Promise<void> =>\n await this.#withLedgerLock(accountIndex, async () => {\n const doc = await this.#readNonceLedger(accountIndex);\n const at = doc.entries.findIndex(\n (candidate) =>\n candidate.nonce === entry.nonce && candidate.txHash === entry.txHash,\n );\n if (at >= 0) {\n doc.entries.splice(at, 1);\n }\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n if (fenceFailed && entry.owner === null) {\n const recoveryId = `${String(entry.nonce)}:${entry.txHash ?? 'nohash'}`;\n this.#appendRecoveredDispatch(doc, {\n recoveryId,\n kind: entry.kind,\n intent: entry.intent,\n txHash: entry.txHash,\n outcome: 'succeeded',\n evidence: 'post-dispatch-session-cancelled',\n });\n }\n await this.#writeNonceLedger(accountIndex, doc);\n });\n\n /**\n * Resolve every unresolved dispatch before a write section may issue\n * nonces. Consumption is proven by REST-nonce advance or an exact tx\n * lookup verifying the FULL identity (hash + account + api-key slot +\n * nonce + a numeric venue status); never-landed is proven ONLY by\n * venue-confirmed absence of the exact HASH after the signed validity\n * elapsed. A hashless dispatch can never be proven absent — it stays\n * blocking until the venue advances. Ambiguity blocks the write.\n * Runs under the account+slot ledger lock.\n *\n * @param accountIndex - Venue account index.\n * @returns Resolves when every prior dispatch is accounted for.\n */\n readonly #resolveNonceLedger = async (accountIndex: number): Promise<void> =>\n await this.#withLedgerLock(accountIndex, async () =>\n this.#resolveNonceLedgerLocked(accountIndex),\n );\n\n /**\n * @param accountIndex - Venue account index.\n * @returns Resolves when the pass completes.\n */\n readonly #resolveNonceLedgerLocked = async (\n accountIndex: number,\n ): Promise<void> => {\n const doc = await this.#readNonceLedger(accountIndex);\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n // The durable consumed watermark always seeds the memory floor.\n if (doc.consumedFloor > 0) {\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, doc.consumedFloor),\n );\n }\n // QUARANTINE CHECK FIRST: unacknowledged recovered outcomes block\n // EVERY retry, including retries arriving when no unresolved\n // entries remain — an early empty-entries return here would let the\n // second retry sail past the quarantine.\n const throwIfQuarantined = (): void => {\n const blocking = doc.recovered.filter(\n (outcome) => outcome.outcome !== 'failed',\n );\n if (blocking.length > 0) {\n throw new Error(\n `A previous Lighter submission believed failed actually ${blocking.some((outcome) => outcome.outcome === 'succeeded') ? 'completed' : 'landed with an UNKNOWN outcome'} (${blocking\n .map((outcome) => outcome.intent)\n .join(\n ', ',\n )}); refresh state and call acknowledgeRecoveredDispatch before retrying`,\n );\n }\n };\n throwIfQuarantined();\n if (doc.entries.length === 0) {\n return;\n }\n const quarantine = (\n entry: LighterNonceLedgerDoc['entries'][number],\n outcome: LighterRecoveredDispatch['outcome'],\n evidence: string,\n ): void => {\n // TP/SL-journal-OWNED dispatches resolve through their own state\n // machine (journal attempts + exact-hash reconciliation) — they\n // are never parked behind the generic acknowledgment.\n if (entry.owner !== null) {\n return;\n }\n this.#appendRecoveredDispatch(doc, {\n recoveryId: `${String(entry.nonce)}:${entry.txHash ?? 'nohash'}`,\n kind: entry.kind,\n intent: entry.intent,\n txHash: entry.txHash,\n outcome,\n evidence,\n });\n };\n const nonceResponse = await this.#clientService.getNextNonce(\n accountIndex,\n this.#apiKeyIndex,\n );\n const remaining: typeof doc.entries = [];\n for (const entry of doc.entries) {\n if (entry.txHash === null && nonceResponse.nonce > entry.nonce) {\n // Only the nonce ADVANCE is proven (possibly by another device):\n // the intent's own fate is UNKNOWN — never reported completed.\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n quarantine(entry, 'unknown', 'rest-advance');\n continue;\n }\n if (entry.txHash !== null) {\n let lookedUp: LighterTxLookupResponse | null;\n try {\n lookedUp = await this.#clientService.getTx(entry.txHash);\n } catch {\n // Lookup failure is AMBIGUITY, never evidence either way: the\n // entry stays and the write remains blocked.\n remaining.push(entry);\n continue;\n }\n if (lookedUp !== null) {\n const matchesIdentity =\n typeof lookedUp.hash === 'string' &&\n lookedUp.hash.toLowerCase().replace(/^0x/u, '') ===\n entry.txHash.toLowerCase().replace(/^0x/u, '') &&\n lookedUp.accountIndex === accountIndex &&\n lookedUp.apiKeyIndex === this.#apiKeyIndex &&\n lookedUp.nonce === entry.nonce &&\n typeof lookedUp.status === 'number';\n if (matchesIdentity) {\n const transactionOutcome = getLighterTransactionOutcome(\n lookedUp.status,\n );\n // A matching hash is not enough to prove the transaction's\n // outcome. Non-terminal statuses must retain the unresolved\n // entry so no acknowledgment can make the intent retryable\n // while the original transaction is still in flight.\n if (\n transactionOutcome !== 'failed' &&\n transactionOutcome !== 'executed'\n ) {\n remaining.push(entry);\n continue;\n }\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n // The EXACT tx status decides the intent's fate: executed →\n // succeeded (blocking until acknowledged); failed/rejected →\n // retry-safe FAILURE (recorded, non-blocking); anything else\n // still pending → keep blocking as unresolved.\n if (transactionOutcome === 'failed') {\n quarantine(\n entry,\n 'failed',\n `tx-status:${String(lookedUp.status)}`,\n );\n } else {\n quarantine(\n entry,\n 'succeeded',\n `tx-status:${String(lookedUp.status)}`,\n );\n }\n continue;\n }\n // A DIFFERENT payload under this hash: ambiguity, fail closed.\n remaining.push(entry);\n continue;\n }\n if (nonceResponse.nonce > entry.nonce) {\n // The venue moved past this nonce while OUR exact hash is\n // absent: another dispatch (e.g. a second device) consumed it.\n // Our payload can never land now — retry-safe never-landed,\n // no quarantine; the floor advances with the venue.\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n continue;\n }\n if (\n entry.expiresAt !== null &&\n Date.now() > entry.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS\n ) {\n // Venue-confirmed absent after the signed validity: PROVEN\n // never landed — the venue still expects this nonce (unless a\n // later dispatch already consumed it: consumedFloor guards).\n if (entry.nonce >= doc.consumedFloor) {\n this.#releaseNonceReservation(accountIndex, entry.nonce);\n }\n continue;\n }\n }\n // Hashless, or hash present but unexpired-and-absent: ambiguous.\n remaining.push(entry);\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: remaining,\n recovered: doc.recovered,\n });\n if (remaining.length > 0) {\n throw new Error(\n 'A previous Lighter submission has an unresolved outcome; writes are blocked until it can be proven consumed or never-landed',\n );\n }\n // RECOVERED-OUTCOME quarantine: succeeded/unknown outcomes block\n // every subsequent write until selectively acknowledged (a blind\n // retry could double the financial intent). FAILED outcomes are\n // retry-safe and never block.\n throwIfQuarantined();\n };\n\n /**\n * List TP/SL obligations parked in DURABLE manual-recovery state: the\n * venue removed (or rejected) protection in a way that cannot be\n * safely re-established automatically. Surfaced to callers/UI; each\n * entry resolves when the user issues a new explicit TP/SL update for\n * the symbol.\n *\n * @returns Parked manual-recovery entries.\n */\n async getPendingManualRecoveries(): Promise<\n {\n symbol: string;\n settlementKey: string;\n recordedAt: number;\n reason: string;\n priorIntent: 'replace' | 'remove';\n survivingOrderIds: string[];\n actionNeeded: string;\n }[]\n > {\n this.#ensureSessionBinding();\n const accountIndex = await this.#ensureAccountIndex();\n // ONLY the bound identity's parked warnings: another account's (or\n // api key's) protection state must never leak into this session.\n const identityPrefix = `${this.#boundAddress ?? 'unbound'}:${accountIndex}:${this.#apiKeyIndex}:`;\n const pending: {\n symbol: string;\n settlementKey: string;\n recordedAt: number;\n reason: string;\n priorIntent: 'replace' | 'remove';\n survivingOrderIds: string[];\n actionNeeded: string;\n }[] = [];\n const actionNeeded =\n 'Review the position and submit a new explicit TP/SL update for this symbol to re-establish protection';\n // Storage errors PROPAGATE — a corrupt index degrading to \"nothing\n // pending\" would hide a naked position.\n const manualIndex = await this.#readTpslManualIndex();\n for (const settlementKey of manualIndex) {\n if (!settlementKey.startsWith(identityPrefix)) {\n continue;\n }\n const doc = await this.#loadTpslManualRecovery(settlementKey);\n if (doc) {\n pending.push({\n symbol: doc.symbol,\n settlementKey,\n recordedAt: doc.recordedAt,\n reason: doc.reason,\n priorIntent: doc.priorIntent,\n survivingOrderIds: doc.survivingOrderIds,\n actionNeeded,\n });\n }\n }\n // Legacy: journals parked 'manual' in the journal slot by an earlier\n // version (migrated to the doc on the next settle pass).\n const journalIndex = await this.#readTpslJournalIndex();\n for (const settlementKey of journalIndex) {\n if (\n !settlementKey.startsWith(identityPrefix) ||\n pending.some((entry) => entry.settlementKey === settlementKey)\n ) {\n continue;\n }\n const journal = await this.#loadTpslJournal(settlementKey);\n if (journal?.phase === 'manual') {\n pending.push({\n symbol: settlementKey.split(':').at(-1) ?? settlementKey,\n settlementKey,\n recordedAt: journal.recordedAt,\n reason:\n 'TP/SL protection could not be safely re-established automatically (parked by an earlier session)',\n priorIntent: journal.intent,\n survivingOrderIds: [],\n actionNeeded,\n });\n }\n }\n return pending;\n }\n\n /**\n * READ-ONLY view of the durable recovered-dispatch outcomes\n * (previously ambiguous submissions later resolved). Never mutates the\n * ledger — acknowledgment is a separate, per-outcome call so a crash\n * between reading and acting can never silently drop an outcome.\n *\n * @returns The pending recovered-dispatch outcomes.\n */\n async getRecoveredDispatches(): Promise<LighterRecoveredDispatch[]> {\n this.#ensureSessionBinding();\n const accountIndex = await this.#ensureAccountIndex();\n const doc = await this.#readNonceLedger(accountIndex);\n return doc.recovered.map((outcome) => ({ ...outcome }));\n }\n\n /**\n * Acknowledge ONE recovered-dispatch outcome by its stable id, after\n * the caller has refreshed venue state and decided how to proceed.\n * Runs under the ledger mutex and re-verifies the session generation\n * inside it so an account switch mid-acknowledge can never clear\n * another account's outcome.\n *\n * @param recoveryId - Stable id from {@link getRecoveredDispatches}.\n */\n async acknowledgeRecoveredDispatch(recoveryId: string): Promise<void> {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n await withProcessMutex(this.#nonceLedgerKey(accountIndex), async () => {\n this.#ensureSessionBinding();\n this.#assertSession(generation);\n const doc = await this.#readNonceLedger(accountIndex);\n const remaining = doc.recovered.filter(\n (outcome) => outcome.recoveryId !== recoveryId,\n );\n if (remaining.length === doc.recovered.length) {\n throw new Error(\n `No pending recovered Lighter dispatch matches id ${recoveryId}; refresh and re-read before acknowledging`,\n );\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: doc.entries,\n recovered: remaining,\n });\n });\n }\n\n /**\n * Release a nonce reservation for a PROVEN never-landed dispatch —\n * refused when the durable consumed watermark shows a later dispatch\n * (e.g. a retry) already consumed the nonce.\n *\n * @param accountIndex - Venue account index.\n * @param nonce - The proven-unconsumed nonce.\n */\n readonly #releaseNonceReservationIfUnconsumed = async (\n accountIndex: number,\n nonce: number,\n ): Promise<void> => {\n const doc = await this.#readNonceLedger(accountIndex).catch(() => null);\n if (doc === null || nonce < doc.consumedFloor) {\n return;\n }\n this.#releaseNonceReservation(accountIndex, nonce);\n };\n\n /**\n * Durable TP/SL journal key (network + address + accountIndex + symbol\n * scoped): the in-memory map alone cannot survive app/WebView/provider\n * death between venue commit and visibility.\n *\n * @param settlementKey - address:accountIndex:symbol identity.\n * @returns The disk-cache key.\n */\n readonly #tpslJournalKey = (settlementKey: string): string =>\n `lighterTpslJournal:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`;\n\n /**\n * Operation-scoped journal payload key: each operation's journal lives\n * under its OWN key so a stale resolver physically cannot overwrite or\n * delete a newer operation's payload — only its own.\n *\n * @param settlementKey - Settlement identity.\n * @param operationId - The operation identity.\n * @returns The disk-cache key.\n */\n readonly #tpslJournalOpKey = (\n settlementKey: string,\n operationId: string,\n ): string =>\n `lighterTpslJournalOp:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}:${operationId}`;\n\n /**\n * Load and strictly validate a persisted journal entry. Malformed or\n * unsupported disk data BLOCKS protection changes (fail closed) — it is\n * never trusted into signing decisions nor silently dropped.\n *\n * @param settlementKey - Settlement identity.\n * @returns The validated entry, or null.\n */\n readonly #loadTpslJournal = async (\n settlementKey: string,\n ): Promise<TpslJournalState | null> => {\n const key = this.#tpslJournalKey(settlementKey);\n // FAIL CLOSED on read failure and on corruption: turning either into\n // \"no entry\" would erase exactly the uncertainty this journal exists\n // to preserve and could duplicate a committed mutation. Malformed\n // data is NOT auto-removed — it blocks until inspected/resolved.\n let baseRaw: string | null;\n try {\n baseRaw = await this.#deps.diskCache.getItem(key);\n } catch (error) {\n throw new Error(\n `Lighter TP/SL journal read failed for ${settlementKey}; refusing protection changes: ${ensureError(error, 'LighterProvider.#loadTpslJournal').message}`,\n );\n }\n if (baseRaw === null) {\n return null;\n }\n // The base key holds either a POINTER to an operation-scoped payload\n // (code-written journals: a stale writer physically cannot destroy a\n // newer operation's payload) or a legacy inline journal.\n let raw = baseRaw;\n const pointer = parseTpslJournalPointer(baseRaw);\n if (pointer !== null) {\n const payloadRaw = await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, pointer.operationId),\n );\n if (payloadRaw === null) {\n // Dangling pointer (payload already resolved elsewhere).\n return null;\n }\n raw = payloadRaw;\n }\n let parsed: {\n version?: unknown;\n recordedAt?: unknown;\n operationId?: unknown;\n createdAt?: unknown;\n nextAttemptId?: unknown;\n apiKeyIndex?: unknown;\n intent?: unknown;\n phase?: unknown;\n priorGrouping?: unknown;\n priorTriggers?: unknown;\n attempts?: unknown;\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} is corrupt; refusing protection changes until it is resolved`,\n );\n }\n const isWireId = (value: unknown): boolean =>\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value > 0 &&\n value < 2 ** 48;\n const isNonce = (value: unknown): boolean =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n const isOrderIdString = (value: unknown): boolean =>\n typeof value === 'string' && /^\\d{1,20}$/u.test(value);\n const isTxHash = (value: unknown): boolean =>\n typeof value === 'string' && /^(0x)?[0-9a-fA-F]{8,128}$/u.test(value);\n const isExpiry = (value: unknown): boolean =>\n typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n const isAttempt = (value: unknown): value is TpslAttempt => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const attempt = value as Record<string, unknown>;\n if (\n !isNonce(attempt.nonce) ||\n typeof attempt.attemptId !== 'number' ||\n !Number.isSafeInteger(attempt.attemptId) ||\n attempt.attemptId < 1 ||\n (attempt.terminalStatus !== undefined &&\n (typeof attempt.terminalStatus !== 'number' ||\n !Number.isSafeInteger(attempt.terminalStatus))) ||\n (attempt.outcome !== 'unknown' && attempt.outcome !== 'accepted') ||\n !isTxHash(attempt.txHash) ||\n !isExpiry(attempt.expiresAt)\n ) {\n return false;\n }\n if (attempt.kind === 'create') {\n return (\n attempt.orderId === undefined &&\n (attempt.role === 'replacement' || attempt.role === 'restore') &&\n // priorOrderIds durably key WHICH prior intents a restore\n // restores, INDEX-ALIGNED with clientIds; REQUIRED on\n // restores, forbidden on replacements.\n (attempt.role === 'restore'\n ? Array.isArray(attempt.priorOrderIds) &&\n Array.isArray(attempt.clientIds) &&\n attempt.priorOrderIds.length === attempt.clientIds.length &&\n attempt.priorOrderIds.every(isOrderIdString)\n : attempt.priorOrderIds === undefined) &&\n Array.isArray(attempt.clientIds) &&\n attempt.clientIds.length >= 1 &&\n attempt.clientIds.length <= 2 &&\n attempt.clientIds.every(isWireId) &&\n new Set(attempt.clientIds).size === attempt.clientIds.length\n );\n }\n if (attempt.kind === 'cancel') {\n return (\n attempt.clientIds === undefined &&\n (attempt.role === 'stale' || attempt.role === 'rollback') &&\n isOrderIdString(attempt.orderId)\n );\n }\n return false;\n };\n // Recovery SIGNS from these values: they must be strict, finite and\n // strictly positive before they can reach the wire.\n const isPositiveDecimalString = (value: unknown): boolean => {\n if (typeof value !== 'string') {\n return false;\n }\n const numeric = parseStrictDecimal(value);\n return numeric !== null && Number.isFinite(numeric) && numeric > 0;\n };\n const isPriorTrigger = (value: unknown): value is TpslPriorTrigger => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const trigger = value as Record<string, unknown>;\n return (\n isOrderIdString(trigger.orderId) &&\n (trigger.side === 'buy' || trigger.side === 'sell') &&\n (trigger.wireOrderType === 2 ||\n trigger.wireOrderType === 3 ||\n trigger.wireOrderType === 4 ||\n trigger.wireOrderType === 5) &&\n (trigger.wireTimeInForce === 0 ||\n trigger.wireTimeInForce === 1 ||\n trigger.wireTimeInForce === 2) &&\n typeof trigger.orderExpiry === 'number' &&\n Number.isSafeInteger(trigger.orderExpiry) &&\n trigger.orderExpiry >= -1 &&\n isPositiveDecimalString(trigger.price) &&\n isPositiveDecimalString(trigger.triggerPrice) &&\n isPositiveDecimalString(trigger.remainingSize)\n );\n };\n // EXPLICIT remediation policy for early schemas (v1/v2): their\n // transition state cannot be interpreted safely, so instead of a\n // permanent opaque block they convert to a DURABLE MANUAL-recovery\n // state — surfaced to the user, resolved only by an explicit new\n // protection intent.\n if (parsed.version === 1 || parsed.version === 2) {\n return {\n attempts: [],\n recordedAt:\n typeof parsed.recordedAt === 'number' ? parsed.recordedAt : 0,\n operationId:\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length > 0\n ? parsed.operationId\n : `legacy-v${String(parsed.version)}`,\n createdAt: typeof parsed.createdAt === 'number' ? parsed.createdAt : 0,\n nextAttemptId: 1,\n intent: 'replace',\n phase: 'manual',\n priorGrouping: 'independent',\n priorTriggers: [],\n };\n }\n if (\n (parsed.version === 3 || parsed.version === 4) &&\n typeof parsed.recordedAt === 'number' &&\n Number.isSafeInteger(parsed.recordedAt) &&\n parsed.recordedAt >= 0 &&\n // The journal is bound to ONE api-key slot: nonces are per slot.\n parsed.apiKeyIndex === this.#apiKeyIndex &&\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length >= 1 &&\n parsed.operationId.length <= 64 &&\n typeof parsed.createdAt === 'number' &&\n Number.isSafeInteger(parsed.createdAt) &&\n parsed.createdAt >= 0 &&\n typeof parsed.nextAttemptId === 'number' &&\n Number.isSafeInteger(parsed.nextAttemptId) &&\n parsed.nextAttemptId >= 1 &&\n // An explicit durable operation intent is REQUIRED: without it a\n // remove could be misread as a failed replacement.\n (parsed.intent === 'replace' || parsed.intent === 'remove') &&\n (parsed.phase === 'creating' ||\n parsed.phase === 'cancelling' ||\n // v3's 'restoring' migrates to 'manual' below.\n parsed.phase === 'restoring' ||\n parsed.phase === 'manual') &&\n // 'oco' grouping structurally requires the linked pair.\n (parsed.priorGrouping === 'independent' ||\n (parsed.priorGrouping === 'oco' &&\n Array.isArray(parsed.priorTriggers) &&\n parsed.priorTriggers.length === 2)) &&\n Array.isArray(parsed.priorTriggers) &&\n parsed.priorTriggers.length <= 4 &&\n parsed.priorTriggers.every(isPriorTrigger) &&\n new Set(parsed.priorTriggers.map((trigger) => trigger.orderId)).size ===\n parsed.priorTriggers.length &&\n Array.isArray(parsed.attempts) &&\n // An EMPTY journal is malformed — empty-but-shape-valid would be\n // accepted and silently cleared.\n parsed.attempts.length >= 1 &&\n parsed.attempts.length <= 40 &&\n parsed.attempts.every(isAttempt) &&\n // Attempt IDENTITY is the attemptId — nonces may legitimately\n // repeat when a proven-never-landed submission is retried. The\n // durable allocator must sit strictly ABOVE every recorded id so\n // compaction can never recycle one.\n new Set(parsed.attempts.map((entry) => entry.attemptId)).size ===\n parsed.attempts.length &&\n parsed.attempts.every(\n (entry) => entry.attemptId < (parsed.nextAttemptId as number),\n )\n ) {\n const { attempts } = parsed;\n const { priorTriggers } = parsed;\n // Every restore leg must link to a persisted prior intent — an\n // unlinked restore could sign a duplicate or orphan a prior one.\n const restoresLinked = attempts.every(\n (attempt) =>\n attempt.kind !== 'create' ||\n attempt.role !== 'restore' ||\n (attempt.priorOrderIds ?? []).every((priorOrderId) =>\n priorTriggers.some((trigger) => trigger.orderId === priorOrderId),\n ),\n );\n if (restoresLinked) {\n return {\n attempts,\n recordedAt: parsed.recordedAt,\n operationId: parsed.operationId,\n createdAt: parsed.createdAt,\n nextAttemptId: parsed.nextAttemptId,\n intent: parsed.intent,\n // v3 MIGRATION: an interrupted 'restoring' operation predates\n // the no-auto-restore policy — it parks as MANUAL.\n phase: parsed.phase === 'restoring' ? 'manual' : parsed.phase,\n priorGrouping: parsed.priorGrouping,\n priorTriggers,\n };\n }\n }\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} is malformed; refusing protection changes until it is resolved`,\n );\n };\n\n /**\n * Durable index of settlement keys with pending journals.\n *\n * @returns The disk-cache key of the index.\n */\n readonly #tpslJournalIndexKey = (): string =>\n `lighterTpslJournalIndex:${this.#isTestnet ? 'testnet' : 'mainnet'}`;\n\n /**\n * Read the durable journal index (strictly validated; failures fail\n * closed by throwing).\n *\n * @returns The list of settlement keys with pending journals.\n */\n readonly #readTpslJournalIndex = async (): Promise<string[]> => {\n const raw = await this.#deps.diskCache.getItem(this.#tpslJournalIndexKey());\n if (raw === null) {\n return [];\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (\n Array.isArray(parsed) &&\n parsed.length <= 64 &&\n parsed.every((entry) => typeof entry === 'string')\n ) {\n return parsed;\n }\n } catch {\n // fall through\n }\n throw new Error('Lighter TP/SL journal index is corrupt');\n };\n\n /**\n * Durable manual-recovery doc key (separate from the journal slot).\n *\n * @param settlementKey - Settlement identity.\n * @returns The disk-cache key.\n */\n readonly #tpslManualKey = (settlementKey: string): string =>\n `lighterTpslManual:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`;\n\n /**\n * Manual-recovery index key.\n *\n * @returns The disk-cache key.\n */\n readonly #tpslManualIndexKey = (): string =>\n `lighterTpslManualIndex:${this.#isTestnet ? 'testnet' : 'mainnet'}`;\n\n /**\n * Read the manual-recovery index. Corruption THROWS — a parked\n * protection warning silently degrading to \"nothing pending\" would\n * hide a naked position.\n *\n * @returns Settlement keys with pending manual recoveries.\n */\n readonly #readTpslManualIndex = async (): Promise<string[]> => {\n const raw = await this.#deps.diskCache.getItem(this.#tpslManualIndexKey());\n if (raw === null) {\n return [];\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (\n Array.isArray(parsed) &&\n parsed.length <= 64 &&\n parsed.every((entry) => typeof entry === 'string')\n ) {\n return parsed;\n }\n } catch {\n // fall through\n }\n throw new Error('Lighter TP/SL manual-recovery index is corrupt');\n };\n\n /**\n * Durably record a manual-recovery warning (doc + index entry).\n *\n * @param doc - The manual-recovery record.\n */\n readonly #writeTpslManualRecovery = async (\n doc: TpslManualRecovery,\n ): Promise<void> => {\n await withStorageMutex(this.#tpslManualIndexKey(), async () => {\n const index = await this.#readTpslManualIndex();\n if (\n !index.includes(doc.settlementKey) &&\n index.length >= LIGHTER_TPSL_MANUAL_RECOVERY_LIMIT\n ) {\n throw new Error(\n 'Lighter TP/SL manual-recovery index is full; refusing to hide a new recovery obligation',\n );\n }\n await this.#deps.diskCache.setItem(\n this.#tpslManualKey(doc.settlementKey),\n JSON.stringify({ version: 1, ...doc }),\n );\n if (!index.includes(doc.settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslManualIndexKey(),\n JSON.stringify([...index, doc.settlementKey]),\n );\n }\n });\n };\n\n /**\n * Load a manual-recovery record. Corruption THROWS (never null) so a\n * parked warning cannot silently vanish.\n *\n * @param settlementKey - Settlement identity.\n * @returns The record, or null when none is parked.\n */\n readonly #loadTpslManualRecovery = async (\n settlementKey: string,\n ): Promise<TpslManualRecovery | null> => {\n const raw = await this.#deps.diskCache.getItem(\n this.#tpslManualKey(settlementKey),\n );\n if (raw === null) {\n return null;\n }\n try {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (\n parsed.version === 1 &&\n typeof parsed.settlementKey === 'string' &&\n typeof parsed.symbol === 'string' &&\n typeof parsed.reason === 'string' &&\n parsed.reason.length <= 500 &&\n (parsed.priorIntent === 'replace' || parsed.priorIntent === 'remove') &&\n Array.isArray(parsed.priorTriggers) &&\n Array.isArray(parsed.survivingOrderIds) &&\n (parsed.survivingOrderIds as unknown[]).every(\n (id) => typeof id === 'string',\n ) &&\n typeof parsed.operationId === 'string' &&\n typeof parsed.recordedAt === 'number'\n ) {\n return {\n settlementKey: parsed.settlementKey,\n symbol: parsed.symbol,\n reason: parsed.reason,\n priorIntent: parsed.priorIntent,\n priorTriggers: parsed.priorTriggers as TpslPriorTrigger[],\n survivingOrderIds: parsed.survivingOrderIds as string[],\n operationId: parsed.operationId,\n recordedAt: parsed.recordedAt,\n };\n }\n } catch {\n // fall through to fail closed\n }\n throw new Error(\n `Lighter TP/SL manual-recovery record for ${settlementKey} is corrupt; resolve storage before proceeding`,\n );\n };\n\n /**\n * Clear a manual-recovery record — called ONLY after a successor\n * protection intent has authoritatively succeeded.\n *\n * @param settlementKey - Settlement identity.\n */\n readonly #clearTpslManualRecovery = async (\n settlementKey: string,\n ): Promise<void> => {\n await withStorageMutex(this.#tpslManualIndexKey(), async () => {\n const index = await this.#readTpslManualIndex();\n await this.#deps.diskCache.removeItem(this.#tpslManualKey(settlementKey));\n if (index.includes(settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslManualIndexKey(),\n JSON.stringify(index.filter((entry) => entry !== settlementKey)),\n );\n }\n });\n };\n\n /**\n * Persist a journal entry durably and ensure the index lists its key so\n * restart recovery can enumerate pending obligations without waiting\n * for the next mutation.\n *\n * @param settlementKey - Settlement identity.\n * @param journal - The journal entry.\n */\n readonly #persistTpslJournal = async (\n settlementKey: string,\n journal: TpslJournalState,\n ): Promise<void> => {\n // WRITER-SIDE capacity enforcement, mirrored from the loader: a\n // journal the loader would reject as malformed must never be written\n // in the first place. Throwing here aborts BEFORE the submission the\n // entry was journalling, with every older obligation intact.\n if (journal.priorTriggers.length > 4) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} would record too many prior triggers (${journal.priorTriggers.length} > 4); refusing the mutation`,\n );\n }\n if (journal.attempts.length > 40) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} would record too many attempts (${journal.attempts.length} > 40); refusing further submissions until pending obligations resolve`,\n );\n }\n // INDEX-FIRST: a dangling index entry (no journal behind it) is\n // safely prunable by recovery, whereas compensating a failed index\n // write by removing the journal could erase an EXISTING authoritative\n // journal holding already-accepted attempts. Any failure here aborts\n // BEFORE the next submission with every older obligation intact.\n // Index RMW under its OWN process-wide mutex: concurrent persists\n // for different settlement keys must never lose each other's entry.\n await withStorageMutex(this.#tpslJournalIndexKey(), async () => {\n const index = await this.#readTpslJournalIndex();\n if (!index.includes(settlementKey)) {\n if (index.length >= 64) {\n // NEVER evict a live obligation: fail the mutation before\n // submission instead.\n throw new Error(\n 'Lighter TP/SL journal index is full; refusing further protection changes until pending obligations resolve',\n );\n }\n await this.#deps.diskCache.setItem(\n this.#tpslJournalIndexKey(),\n JSON.stringify([...index, settlementKey]),\n );\n }\n });\n const baseKey = this.#tpslJournalKey(settlementKey);\n // The pointer read-modify-write is serialized PROCESS-WIDE: the\n // instance-local write lock cannot protect two live provider\n // instances sharing one disk cache.\n await withStorageMutex(baseKey, async () => {\n // COMPARE-AND-SWAP on the operation identity: a writer holding a\n // stale snapshot must never take over a DIFFERENT operation's\n // journal. (A missing journal is fine — first write of an op.)\n const currentRaw = await this.#deps.diskCache.getItem(baseKey);\n const pointerAlreadyOurs =\n currentRaw !== null &&\n parseTpslJournalPointer(currentRaw)?.operationId ===\n journal.operationId;\n // A DANGLING pointer (payload already resolved; only the base\n // removal failed) has no live owner — it is claimable, otherwise a\n // partial clear would block every future operation forever.\n let danglingPointer = false;\n if (currentRaw !== null) {\n const staleCheck = parseTpslJournalPointer(currentRaw);\n if (\n staleCheck !== null &&\n staleCheck.operationId !== journal.operationId\n ) {\n danglingPointer =\n (await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, staleCheck.operationId),\n )) === null;\n }\n }\n if (currentRaw !== null && !danglingPointer) {\n const pointer = parseTpslJournalPointer(currentRaw);\n let currentOperationId: unknown = pointer?.operationId ?? null;\n if (pointer === null) {\n try {\n currentOperationId = (\n JSON.parse(currentRaw) as { operationId?: unknown }\n ).operationId;\n } catch {\n // Corrupt current journal: fail closed below via mismatch.\n }\n }\n if (currentOperationId !== journal.operationId) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} belongs to a different operation; refusing a stale write`,\n );\n }\n }\n // Payload first, under the operation's OWN key — then the pointer.\n await this.#deps.diskCache.setItem(\n this.#tpslJournalOpKey(settlementKey, journal.operationId),\n JSON.stringify({\n version: 4,\n recordedAt: journal.recordedAt,\n operationId: journal.operationId,\n createdAt: journal.createdAt,\n nextAttemptId: journal.nextAttemptId,\n apiKeyIndex: this.#apiKeyIndex,\n intent: journal.intent,\n phase: journal.phase,\n priorGrouping: journal.priorGrouping,\n priorTriggers: journal.priorTriggers,\n attempts: journal.attempts,\n }),\n );\n try {\n await this.#deps.diskCache.setItem(\n baseKey,\n JSON.stringify({\n pointerVersion: 1,\n operationId: journal.operationId,\n }),\n );\n } catch (error) {\n // Pointer write failed on the FIRST persist of this operation:\n // remove the freshly written payload so no orphan accumulates.\n // (When an earlier persist already pointed here, the payload is\n // referenced durable state — keep it.)\n if (!pointerAlreadyOurs) {\n await this.#deps.diskCache\n .removeItem(\n this.#tpslJournalOpKey(settlementKey, journal.operationId),\n )\n .catch(() => undefined);\n }\n throw error;\n }\n });\n // A NEW pending obligation invalidates any \"recovery complete\"\n // marker recorded earlier in this session — otherwise later read\n // kicks would skip it until a restart or another mutation.\n this.#tpslRecoveryGeneration = -1;\n };\n\n /**\n * Resolve a settlement obligation everywhere — compare-and-swap on the\n * operation identity: a resolver holding a STALE snapshot must never\n * erase a NEWER operation's journal. Disk removal failures PROPAGATE\n * and the in-memory entry is retained: silently dropping only the\n * memory copy would leave a stale durable obligation to wedge a later\n * session.\n *\n * @param settlementKey - Settlement identity.\n * @param expectedOperationId - The operation this resolver settled;\n * null prunes only a dangling index entry with NO journal behind it.\n * @returns True when the obligation was cleared (or already gone);\n * false when a NEWER operation owns the journal (unresolved).\n */\n readonly #clearTpslJournal = async (\n settlementKey: string,\n expectedOperationId: string | null,\n ): Promise<boolean> => {\n const journalKey = this.#tpslJournalKey(settlementKey);\n const cleared = await withStorageMutex(journalKey, async () => {\n const currentRaw = await this.#deps.diskCache.getItem(journalKey);\n if (currentRaw === null) {\n // Already resolved (or never journalled): nothing left to clear.\n return true;\n }\n const pointer = parseTpslJournalPointer(currentRaw);\n if (pointer !== null) {\n if (expectedOperationId === null) {\n // Prune mode: only a DANGLING pointer may be pruned.\n const payloadRaw = await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, pointer.operationId),\n );\n if (payloadRaw !== null) {\n return false;\n }\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n }\n if (pointer.operationId !== expectedOperationId) {\n // A NEWER operation owns the journal: remove only OUR OWN\n // payload (physically incapable of touching theirs) and\n // report the clear as unresolved.\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal clear refused: different operation',\n { settlementKey },\n );\n await this.#deps.diskCache\n .removeItem(\n this.#tpslJournalOpKey(settlementKey, expectedOperationId),\n )\n .catch(() => undefined);\n return false;\n }\n await this.#deps.diskCache.removeItem(\n this.#tpslJournalOpKey(settlementKey, expectedOperationId),\n );\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n }\n // Legacy inline journal at the base key.\n if (expectedOperationId === null) {\n return false;\n }\n let currentOperationId: unknown = null;\n try {\n const inline = JSON.parse(currentRaw) as {\n operationId?: unknown;\n version?: unknown;\n };\n currentOperationId =\n inline.operationId ??\n // Early schemas carry no operation id: the loader synthesizes\n // `legacy-v{n}` for their manual-remediation state — mirror it\n // so the explicit new intent can clear them.\n (inline.version === 1 || inline.version === 2\n ? `legacy-v${String(inline.version)}`\n : null);\n } catch {\n // Corrupt journal is never silently cleared.\n }\n if (currentOperationId !== expectedOperationId) {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal clear refused: different operation',\n { settlementKey },\n );\n return false;\n }\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n });\n if (!cleared) {\n return false;\n }\n // Index removal under the index mutex, RE-VERIFYING the journal is\n // still gone: a newer operation may have persisted (journal +\n // index entry) between our clear and this removal — removing the\n // entry then would blind restart recovery to a live obligation.\n // A storage READ failure here is AMBIGUITY, never absence: it\n // propagates (the index entry is retained and the settlement stays\n // unresolved) — guessing could orphan a live obligation.\n await withStorageMutex(this.#tpslJournalIndexKey(), async () => {\n const stillGone =\n (await this.#deps.diskCache.getItem(journalKey)) === null;\n if (!stillGone) {\n return;\n }\n const index = await this.#readTpslJournalIndex();\n if (index.includes(settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslJournalIndexKey(),\n JSON.stringify(index.filter((entry) => entry !== settlementKey)),\n );\n }\n });\n const memoryEntry = this.#tpslUnsettled.get(settlementKey);\n if (\n memoryEntry === undefined ||\n expectedOperationId === null ||\n memoryEntry.operationId === expectedOperationId\n ) {\n this.#tpslUnsettled.delete(settlementKey);\n }\n return true;\n };\n\n /**\n * Targeted, cached, active-first inactive-history reader shared by the\n * mutation transition and recovery: terminal rows are immutable so they\n * cache across polls; page 1 per call; the deep cursor walk runs at\n * most ONCE per reader and stops when every target id is found.\n *\n * @param accountIndex - Captured account index.\n * @param authToken - Captured auth token.\n * @param generation - Captured session generation (fenced per read).\n * @param marketId - Market to scope inactive-history requests to.\n * @returns The reader closure.\n */\n readonly #makeInactiveReader = (\n accountIndex: number,\n authToken: string,\n generation: number,\n marketId: number,\n ): ((targetClientIds: number[]) => Promise<LighterApiOrder[]>) => {\n const terminalCache = new Map<string, LighterApiOrder>();\n let deepTraversalDone = false;\n return async (targetClientIds: number[]): Promise<LighterApiOrder[]> => {\n this.#assertSession(generation);\n const targets = targetClientIds.map(String);\n const missing = (): boolean =>\n targets.some((id) => !terminalCache.has(id));\n const ingest = (orders: LighterApiOrder[]): void => {\n for (const order of orders) {\n if (order.ownerAccountIndex === accountIndex) {\n terminalCache.set(String(order.clientOrderIndex), order);\n }\n }\n };\n const firstPage = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n 100,\n undefined,\n marketId,\n );\n this.#assertSession(generation);\n let rowsRead = firstPage.orders.length;\n if (rowsRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} rows; TP/SL recovery is still pending`,\n );\n }\n ingest(firstPage.orders);\n if (missing() && !deepTraversalDone) {\n let cursor = firstPage.nextCursor;\n const seenCursors = new Set<string>();\n let pagesRead = 1;\n while (cursor && missing()) {\n if (seenCursors.has(cursor)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history repeated cursor ${cursor} after ${rowsRead} rows; TP/SL recovery is still pending`,\n );\n }\n seenCursors.add(cursor);\n const response = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n 100,\n cursor,\n marketId,\n );\n this.#assertSession(generation);\n pagesRead += 1;\n if (\n response.orders.length === 0 &&\n response.nextCursor !== undefined\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history advanced without returning rows; TP/SL recovery is still pending`,\n );\n }\n if (pagesRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} pages; TP/SL recovery is still pending`,\n );\n }\n rowsRead += response.orders.length;\n if (rowsRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} rows (${rowsRead} rows returned); TP/SL recovery is still pending`,\n );\n }\n ingest(response.orders);\n cursor = response.nextCursor;\n }\n deepTraversalDone = !cursor || !missing();\n }\n return [...terminalCache.values()];\n };\n };\n\n /** Session generation whose journal recovery fully resolved. */\n #tpslRecoveryGeneration = -1;\n\n /** In-flight journal recovery (deduplicates concurrent triggers). */\n #tpslRecoveryInFlight: Promise<void> | null = null;\n\n /**\n * Detached, deduplicated recovery kick. Wired into signer setup AND the\n * public read paths: a recovery that returned unresolved (e.g. REST\n * visibility lag) must get another chance later in the SAME session,\n * not only at the next signer setup.\n */\n /** A kick arrived while a (possibly stale) recovery was in flight. */\n #tpslRecoveryKickPending = false;\n\n readonly #kickTpslRecovery = (): void => {\n if (this.#tpslRecoveryGeneration === this.#sessionGeneration) {\n return;\n }\n if (this.#tpslRecoveryInFlight) {\n // A stale-generation recovery may be finishing: remember this kick\n // so the CURRENT generation's journals are not silently skipped.\n this.#tpslRecoveryKickPending = true;\n return;\n }\n setTimeout(() => {\n this.#recoverPendingTpslJournals().catch((error) => {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal recovery failed',\n { error: String(error) },\n );\n });\n }, 0);\n };\n\n /**\n * Enumerate durable journal-index entries for the CURRENT identity and\n * recover each: reconcile, complete an interrupted replacement's stale\n * cancels when its created protection is live, then clear. Bounded and\n * deduplicated per session generation; unresolved entries stay for the\n * next attempt.\n */\n readonly #recoverPendingTpslJournals = async (): Promise<void> => {\n const generation = this.#sessionGeneration;\n if (this.#tpslRecoveryGeneration === generation) {\n return;\n }\n if (this.#tpslRecoveryInFlight) {\n await this.#tpslRecoveryInFlight;\n return;\n }\n this.#tpslRecoveryInFlight = (async (): Promise<void> => {\n try {\n // Index corruption/read failure PROPAGATES (logged by the hook):\n // silently treating it as empty would disable recovery entirely.\n const index = await this.#readTpslJournalIndex();\n if (index.length === 0) {\n this.#tpslRecoveryGeneration = generation;\n return;\n }\n const address = this.#boundAddress;\n if (!address) {\n return;\n }\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generation);\n const prefix = `${address}:${accountIndex}:${this.#apiKeyIndex}:`;\n let allResolved = true;\n for (const settlementKey of index) {\n if (!settlementKey.startsWith(prefix)) {\n continue;\n }\n const resolved = await this.#recoverTpslSymbol(\n settlementKey.slice(prefix.length),\n settlementKey,\n generation,\n accountIndex,\n ).catch((error) => {\n // Surface the exact cause (corruption, transport, session\n // fence) — the entry stays retryable, but never silently.\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal entry recovery failed',\n {\n settlementKey,\n error:\n error instanceof Error\n ? (error.stack ?? error.message)\n : String(error),\n },\n );\n return false;\n });\n if (!resolved) {\n allResolved = false;\n }\n }\n // Marked complete ONLY when everything resolved: unresolved or\n // errored entries stay retryable within this session.\n if (allResolved) {\n this.#tpslRecoveryGeneration = generation;\n }\n } finally {\n this.#tpslRecoveryInFlight = null;\n if (this.#tpslRecoveryKickPending) {\n this.#tpslRecoveryKickPending = false;\n this.#kickTpslRecovery();\n }\n }\n })();\n await this.#tpslRecoveryInFlight;\n };\n\n /**\n * Recover one pending TP/SL journal without any new protection intent.\n *\n * @param symbol - Market symbol from the settlement key.\n * @param settlementKey - Full settlement identity.\n * @param generation - Captured session generation.\n * @param accountIndex - Captured account index.\n * @returns True when the obligation fully resolved (journal cleared);\n * false when it remains pending and must be retried.\n */\n readonly #recoverTpslSymbol = async (\n symbol: string,\n settlementKey: string,\n generation: number,\n accountIndex: number,\n ): Promise<boolean> => {\n const markets = await this.#ensureMarkets();\n const market = markets.get(symbol);\n if (!market) {\n return false;\n }\n await this.#ensureSignerReady();\n this.#assertSession(generation);\n const authToken = await this.#getAuthToken();\n this.#assertSession(generation);\n return await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit): Promise<boolean> => {\n // The journal is loaded INSIDE the lock: a snapshot taken while\n // waiting for the lock could be superseded by a foreground\n // operation that settles it and journals a NEW one — acting on\n // the stale snapshot could erase the newer obligation.\n const journalEntry = await this.#loadTpslJournal(settlementKey);\n if (!journalEntry) {\n // Stale index entry with no journal behind it: prune.\n return await this.#clearTpslJournal(settlementKey, null).catch(\n () => false,\n );\n }\n const readActiveRaw = async (): Promise<LighterApiOrder[]> => {\n this.#assertSession(generation);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generation);\n return response.orders;\n };\n const readInactiveFor = this.#makeInactiveReader(\n accountIndex,\n authToken,\n generation,\n market.marketId,\n );\n return await this.#settleTpslObligation({\n settlementKey,\n symbol,\n journalEntry,\n market,\n accountIndex,\n authToken,\n generation,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n });\n },\n generation,\n );\n };\n\n /**\n * THE TP/SL obligation state machine — the single implementation run by\n * startup/read-path recovery AND by a direct foreground update that\n * finds a pending journal. Reconciles every attempt authoritatively,\n * then acts per durable intent and phase, and clears the journal ONLY\n * on a fully-settled outcome.\n *\n * @param context - Captured settlement context.\n * @param context.settlementKey - Full settlement identity.\n * @param context.symbol - Market symbol.\n * @param context.journalEntry - The pending journal.\n * @param context.market - Market integerization parameters.\n * @param context.market.marketId - Venue market id.\n * @param context.market.supportedSizeDecimals - Size integerization decimals.\n * @param context.market.supportedPriceDecimals - Price integerization decimals.\n * @param context.accountIndex - Captured account index.\n * @param context.authToken - Captured venue auth token.\n * @param context.generation - Captured session generation.\n * @param context.readActiveRaw - Session-fenced raw active reader.\n * @param context.readInactiveFor - Targeted inactive reader.\n * @param context.nextNonce - Lock-section nonce issuer.\n * @param context.submit - Lock-section submitter.\n * @returns True when fully resolved (journal cleared); false when the\n * obligation remains pending and must be retried.\n */\n readonly #settleTpslObligation = async (context: {\n settlementKey: string;\n symbol: string;\n journalEntry: TpslJournalState;\n market: {\n marketId: number;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n };\n accountIndex: number;\n authToken: string;\n generation: number;\n readActiveRaw: () => Promise<LighterApiOrder[]>;\n readInactiveFor: (targetClientIds: number[]) => Promise<LighterApiOrder[]>;\n nextNonce: () => Promise<number>;\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>;\n }): Promise<boolean> => {\n const { settlementKey } = context;\n // The ENTIRE same-settlement state machine is serialized\n // PROCESS-WIDE: two live providers resolving the same operation\n // could otherwise both choose and submit identical restores/cancels\n // and overwrite each other's attempt state.\n return await withProcessMutex(\n `lighterTpslSettle:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`,\n async () => await this.#settleTpslObligationLocked(context),\n );\n };\n\n /**\n * The settlement machine body — MUST only run under the per-settlement\n * process mutex (see #settleTpslObligation).\n *\n * @param context - See #settleTpslObligation.\n * @param context.settlementKey - Full settlement identity.\n * @param context.symbol - Market symbol.\n * @param context.journalEntry - Caller's journal snapshot (reloaded).\n * @param context.market - Market integerization parameters.\n * @param context.market.marketId - Venue market id.\n * @param context.market.supportedSizeDecimals - Size decimals.\n * @param context.market.supportedPriceDecimals - Price decimals.\n * @param context.accountIndex - Captured account index.\n * @param context.authToken - Captured venue auth token.\n * @param context.generation - Captured session generation.\n * @param context.readActiveRaw - Session-fenced raw active reader.\n * @param context.readInactiveFor - Targeted inactive reader.\n * @param context.nextNonce - Lock-section nonce issuer.\n * @param context.submit - Lock-section submitter.\n * @returns See #settleTpslObligation.\n */\n readonly #settleTpslObligationLocked = async (context: {\n settlementKey: string;\n symbol: string;\n journalEntry: TpslJournalState;\n market: {\n marketId: number;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n };\n accountIndex: number;\n authToken: string;\n generation: number;\n readActiveRaw: () => Promise<LighterApiOrder[]>;\n readInactiveFor: (targetClientIds: number[]) => Promise<LighterApiOrder[]>;\n nextNonce: () => Promise<number>;\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>;\n }): Promise<boolean> => {\n const {\n settlementKey,\n symbol,\n market,\n accountIndex,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n } = context;\n // RELOAD inside the settlement mutex: the caller's snapshot may have\n // been superseded while waiting for the mutex — decisions must be\n // made on the CURRENT journal of the SAME operation only. Disk is\n // AUTHORITATIVE: absence means another resolver cleared it, so any\n // stale in-memory copy must be dropped, never resurrected.\n const journalEntry = await this.#loadTpslJournal(settlementKey);\n if (!journalEntry) {\n this.#tpslUnsettled.delete(settlementKey);\n return await this.#clearTpslJournal(settlementKey, null).catch(\n () => false,\n );\n }\n if (journalEntry.operationId !== context.journalEntry.operationId) {\n // A different operation owns the journal now: this resolver's\n // obligation no longer exists — report unresolved so the caller\n // re-evaluates against the fresh state.\n return false;\n }\n const reconciled = await this.#reconcilePriorTpsl(\n readActiveRaw,\n readInactiveFor,\n accountIndex,\n journalEntry,\n );\n if (reconciled === 'unresolved') {\n return false;\n }\n const persistEntry = async (): Promise<void> => {\n this.#tpslUnsettled.set(settlementKey, journalEntry);\n await this.#persistTpslJournal(settlementKey, journalEntry);\n };\n // Same journalled cancel discipline as the live transition.\n const submitRecoveryCancel = async (\n orderId: string,\n role: 'stale' | 'rollback',\n ): Promise<void> => {\n if (role === 'stale' && journalEntry.intent === 'replace') {\n journalEntry.phase = 'cancelling';\n }\n const cancelNonce = await nextNonce();\n const signedCancel = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, orderId, cancelNonce],\n });\n if (signedCancel.error) {\n throw new Error(\n `Failed to cancel trigger order ${orderId}: ${signedCancel.error}`,\n );\n }\n const cancelIdentity = requireSignedTxIdentity(signedCancel);\n const cancelAttempt: TpslCancelAttempt = {\n kind: 'cancel',\n attemptId: nextAttemptIdFor(journalEntry),\n nonce: cancelNonce,\n outcome: 'unknown',\n orderId,\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n role,\n };\n journalEntry.attempts.push(cancelAttempt);\n await persistEntry();\n await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signedCancel.txInfo,\n () => {\n cancelAttempt.outcome = 'accepted';\n },\n {\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n owner: journalEntry.operationId,\n },\n );\n };\n // Classify every journalled create leg on the books (reconcile\n // proved each attempt either landed or never can).\n const replacementIds = journalEntry.attempts\n .filter(\n (attempt): attempt is TpslCreateAttempt =>\n attempt.kind === 'create' && attempt.role === 'replacement',\n )\n .flatMap((attempt) => attempt.clientIds);\n const restoreAttempts = journalEntry.attempts.filter(\n (attempt): attempt is TpslCreateAttempt =>\n attempt.kind === 'create' && attempt.role === 'restore',\n );\n const allCreateIds = [\n ...replacementIds,\n ...restoreAttempts.flatMap((attempt) => attempt.clientIds),\n ];\n const rawActive = await readActiveRaw();\n const missingFromActive = allCreateIds.filter(\n (clientId) =>\n !rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const rawInactive =\n missingFromActive.length > 0\n ? await readInactiveFor(missingFromActive)\n : [];\n const stateOf = (clientId: number): 'active' | 'success' | 'failed' => {\n if (\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n )\n ) {\n return 'active';\n }\n const terminal = rawInactive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (!terminal) {\n // Reconcile proved never-landed: same outcome as failed.\n return 'failed';\n }\n const status = terminal.status.toLowerCase();\n const fullyExecuted =\n (status === 'filled' || status === 'executed') &&\n parseStrictDecimal(terminal.remainingBaseAmount) === 0;\n return fullyExecuted ? 'success' : 'failed';\n };\n const replacementStates = replacementIds.map(stateOf);\n const anySuccess = replacementStates.includes('success');\n const anyActive = replacementStates.includes('active');\n const anyFailed = replacementStates.includes('failed');\n const priorActive = (prior: TpslPriorTrigger): boolean =>\n rawActive.some((order) => String(order.orderIndex) === prior.orderId);\n const cancelledOrderIds: string[] = [];\n const createdClientIds: number[] = [];\n // Aggregation groups parallel to createdClientIds: one group per\n // create ATTEMPT (grouped OCO semantics within, independence across).\n const createdGroups: number[][] = [];\n const pushCreatedGroup = (group: number[]): void => {\n createdClientIds.push(...group);\n createdGroups.push(group);\n };\n const cancelPriorLeftovers = async (): Promise<void> => {\n // The replacement must STAY proven while the old protection is\n // removed: keep its live ids in the final expectation so a leg\n // terminal-failing DURING these cancels (the phase race) fails\n // this pass instead of clearing the journal naked. Grouped per\n // replacement ATTEMPT: an executed OCO leg legitimately\n // auto-cancels its sibling.\n for (const attempt of journalEntry.attempts) {\n if (attempt.kind !== 'create' || attempt.role !== 'replacement') {\n continue;\n }\n const activeLegs = attempt.clientIds.filter(\n (clientId) => stateOf(clientId) === 'active',\n );\n if (activeLegs.length > 0) {\n pushCreatedGroup(attempt.clientIds);\n }\n }\n for (const prior of journalEntry.priorTriggers) {\n if (priorActive(prior)) {\n await submitRecoveryCancel(prior.orderId, 'stale');\n cancelledOrderIds.push(prior.orderId);\n }\n }\n };\n const rollbackActiveJournalledLegs = async (\n legIds: number[],\n ): Promise<void> => {\n for (const clientId of legIds) {\n if (stateOf(clientId) !== 'active') {\n continue;\n }\n const survivor = rawActive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (survivor) {\n await submitRecoveryCancel(String(survivor.orderIndex), 'rollback');\n cancelledOrderIds.push(String(survivor.orderIndex));\n }\n }\n };\n const rollbackActiveReplacements = async (): Promise<void> =>\n await rollbackActiveJournalledLegs(replacementIds);\n // COMPACTION: proven-resolved attempts with no live effect and no\n // coverage are dropped so repeated retries can never dead-end at the\n // attempt cap: FAILED restore creates (never landed/terminal-failed)\n // and resolved cancels (target gone, or proven never-landed).\n const compactionNow = Date.now();\n journalEntry.attempts = journalEntry.attempts.filter((attempt) => {\n if (attempt.kind === 'create') {\n return (\n attempt.role !== 'restore' ||\n attempt.clientIds.some((clientId) => stateOf(clientId) !== 'failed')\n );\n }\n const targetGone = !rawActive.some(\n (order) => String(order.orderIndex) === attempt.orderId,\n );\n const provenNeverLanded =\n attempt.outcome === 'unknown' &&\n compactionNow > attempt.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS;\n // Accepted-but-terminal-FAILED cancels (venue status 0) landed\n // without mutating the books: proven-resolved, compactable.\n const landedTerminalFailed =\n getLighterTransactionOutcome(attempt.terminalStatus) === 'failed';\n return !(targetGone || provenNeverLanded || landedTerminalFailed);\n });\n // NO AUTOMATIC RESTORE: the venue exposes no atomic primitive that\n // could prove a re-created trigger attaches to the SAME position\n // lifecycle, so a fully-failed replacement after old cancels parks\n // the journal in a DURABLE 'manual' state — surfaced via\n // `getPendingManualRecoveries` and resolved only by an explicit NEW\n // protection intent from the user. Never restored, never silently\n // cleared.\n const parkManual = async (reason: string): Promise<boolean> => {\n // Survivors: prior triggers still on the books + replacement legs\n // still active — deliberately LEFT (only remaining protection).\n const survivingOrderIds = [\n ...new Set([\n ...journalEntry.priorTriggers\n .filter((prior) => priorActive(prior))\n .map((prior) => prior.orderId),\n ...rawActive\n .filter((order) =>\n replacementIds.some(\n (clientId) =>\n String(order.clientOrderIndex) === String(clientId),\n ),\n )\n .map((order) => String(order.orderIndex)),\n ]),\n ];\n // The DURABLE warning lives in its own doc; the journal slot is\n // released so a successor protection intent can run. The doc\n // clears only after a successor SUCCEEDS.\n await this.#writeTpslManualRecovery({\n settlementKey,\n symbol,\n reason,\n priorIntent: journalEntry.intent,\n priorTriggers: journalEntry.priorTriggers,\n survivingOrderIds,\n operationId: journalEntry.operationId,\n recordedAt: Date.now(),\n });\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL protection requires MANUAL re-establishment',\n { settlementKey, reason },\n );\n await this.#clearTpslJournal(settlementKey, journalEntry.operationId);\n return true;\n };\n if (journalEntry.phase === 'manual') {\n // Journal parked 'manual' by an earlier version: migrate the\n // warning into the dedicated durable doc.\n return await parkManual(\n 'TP/SL protection could not be safely re-established automatically (parked by an earlier session)',\n );\n }\n if (journalEntry.intent === 'remove') {\n // An intentional REMOVAL is never \"recovered\" by restoring the\n // cancelled protection: finish/reconcile the cancels exactly.\n for (const prior of journalEntry.priorTriggers) {\n if (priorActive(prior)) {\n await submitRecoveryCancel(prior.orderId, 'stale');\n cancelledOrderIds.push(prior.orderId);\n }\n }\n } else if (journalEntry.phase === 'creating') {\n // Old protection untouched. Nothing landed / everything failed\n // → the old set is still the only intent: just clear.\n if (replacementIds.length > 0 && (anySuccess || anyActive)) {\n if (!anySuccess && anyFailed) {\n // Partial OCO before old cancels: roll surviving legs back so\n // the OLD protection remains authoritative.\n await rollbackActiveReplacements();\n } else {\n // Replacement in force (or executed): finish the swap.\n await cancelPriorLeftovers();\n }\n }\n } else if (journalEntry.phase === 'cancelling') {\n if (anySuccess || (anyActive && !anyFailed)) {\n // Replacement fully won — finish cancelling the old protection.\n await cancelPriorLeftovers();\n } else {\n // Replacement fully failed (or degraded to a partial set) AFTER\n // old cancels began: the position's protection can no longer be\n // proven — park durably for MANUAL re-establishment. Any\n // surviving leg is deliberately LEFT (it is the only protection\n // remaining); nothing is restored.\n return await parkManual(\n 'Replacement TP/SL orders failed after the previous protection cancels began; the position may be under-protected',\n );\n }\n }\n if (cancelledOrderIds.length > 0 || createdClientIds.length > 0) {\n const settled = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n { createdClientIds, cancelledOrderIds },\n // PER-ATTEMPT groups: a grouped OCO replacement's executed leg\n // legitimately auto-cancels its sibling.\n { createdGroups },\n );\n // ONLY a fully-settled pass may clear; a replacement dying DURING\n // the old cancels parks for manual re-establishment.\n if (settled.outcome === 'timeout') {\n return false;\n }\n if (settled.outcome === 'created-terminal-failed') {\n return await parkManual(\n 'Replacement TP/SL order was cancelled or rejected by the venue after the previous protection was already removed',\n );\n }\n }\n // A refused clear (superseded by a newer operation) is UNRESOLVED —\n // never reported as success.\n return await this.#clearTpslJournal(\n settlementKey,\n journalEntry.operationId,\n );\n };\n\n /**\n * Reconcile a PRIOR transition's expectation before any new mutation.\n * Only created ids can cause duplicates from a stale snapshot, so they\n * must be accounted for (active or terminal). Cancelled ids are safe in\n * either state: still-active targets reappear in the fresh snapshot and\n * are re-cancelled.\n *\n * @param readActiveRaw - Strict raw active-orders reader.\n * @param readInactive - Targeted inactive-history reader (cached, bounded).\n * @param accountIndex - Captured account index.\n * @param entry - The recorded expectation.\n * @param entry.attempts - Journalled per-attempt submissions.\n * @param entry.recordedAt - When the journal was recorded (ms).\n * @returns 'resolved' when safe to proceed; 'unresolved' when an\n * ACCEPTED mutation is still not visible.\n */\n readonly #reconcilePriorTpsl = async (\n readActiveRaw: () => Promise<LighterApiOrder[]>,\n readInactive: (targetClientIds: number[]) => Promise<LighterApiOrder[]>,\n accountIndex: number,\n entry: { attempts: TpslAttempt[]; recordedAt: number },\n ): Promise<'resolved' | 'unresolved'> => {\n // Per-attempt reconciliation, authoritative and never time-guessed:\n // 1. Books first — a create is resolved when its ids are all\n // active/terminal, a cancel when its target left the active book.\n // 2. Otherwise the EXACT signed tx hash is looked up: a strict match\n // (hash + account + api key slot + nonce) proves the payload\n // reached the sequencer, so absence from the books can only be\n // visibility lag (keep blocking). A venue-confirmed not-found is\n // only never-landed once the signed ExpiredAt (+ clock slack) has\n // passed — the sequencer cannot accept an expired payload.\n const satisfiedOnBooks = (\n attempt: TpslAttempt,\n rawActive: LighterApiOrder[],\n rawInactive: LighterApiOrder[],\n ): boolean =>\n attempt.kind === 'create'\n ? attempt.clientIds.every(\n (clientId) =>\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ) ||\n rawInactive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n )\n : !rawActive.some(\n (order) => String(order.orderIndex) === attempt.orderId,\n );\n // Books can satisfy only OBSERVED-accepted attempts. An UNKNOWN\n // attempt's desired book state may hold for INDEPENDENT reasons (a\n // fill, an external cancel) while the signed payload could still\n // land later and consume its nonce — every unknown attempt must\n // resolve by exact hash identity or proven expiry.\n let rawActive: LighterApiOrder[] = [];\n let rawInactive: LighterApiOrder[] = [];\n for (let poll = 0; poll < LIGHTER_TPSL_SETTLE_ATTEMPTS; poll += 1) {\n const activeNow = await readActiveRaw();\n // ACTIVE-FIRST (see #awaitTpslVisibility): inactive history is only\n // consulted for create ids not already visible active.\n const createIdsMissingFromActive = entry.attempts\n .filter(\n (attempt): attempt is TpslCreateAttempt => attempt.kind === 'create',\n )\n .flatMap((attempt) => attempt.clientIds)\n .filter(\n (clientId) =>\n !activeNow.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const inactiveNow =\n createIdsMissingFromActive.length > 0\n ? await readInactive(createIdsMissingFromActive)\n : [];\n rawActive = activeNow;\n rawInactive = inactiveNow;\n // Poll the books through visibility lag for ALL attempts — book\n // convergence resolves accepted attempts directly and lets an\n // unknown-but-landed attempt pass its final identity check below.\n const anyUnsatisfied = entry.attempts.some(\n (attempt) => !satisfiedOnBooks(attempt, activeNow, inactiveNow),\n );\n if (!anyUnsatisfied) {\n break;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, LIGHTER_TPSL_SETTLE_POLL_MS),\n );\n }\n for (const attempt of entry.attempts) {\n if (\n attempt.outcome === 'accepted' &&\n satisfiedOnBooks(attempt, rawActive, rawInactive)\n ) {\n continue;\n }\n let lookedUp: LighterTxLookupResponse | null;\n try {\n lookedUp = await this.#clientService.getTx(attempt.txHash);\n } catch {\n // Lookup failure is AMBIGUOUS, never evidence of non-acceptance.\n return 'unresolved';\n }\n if (lookedUp !== null) {\n // The exact signed hash exists at the venue. With a matching\n // identity (hash + account + api key slot + nonce):\n // - terminal FAILED status (0) resolves the attempt\n // deterministically — the nonce was consumed but the books\n // were never mutated (the machine re-acts on book state);\n // - any other status with the books already reflecting the\n // attempt resolves it;\n // - otherwise it reached the sequencer but is not yet visible —\n // keep blocking. A NON-matching payload under this hash fails\n // closed identically, and is logged (signer/venue defect).\n const matchesIdentity =\n typeof lookedUp.hash === 'string' &&\n lookedUp.hash.toLowerCase().replace(/^0x/u, '') ===\n attempt.txHash.toLowerCase().replace(/^0x/u, '') &&\n lookedUp.accountIndex === accountIndex &&\n lookedUp.apiKeyIndex === this.#apiKeyIndex &&\n lookedUp.nonce === attempt.nonce;\n if (!matchesIdentity) {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL tx lookup identity mismatch; failing closed',\n { txHash: attempt.txHash },\n );\n return 'unresolved';\n }\n const transactionOutcome = getLighterTransactionOutcome(\n lookedUp.status,\n );\n if (transactionOutcome === 'failed') {\n // Record the terminal venue status durably (next persist):\n // compaction can then drop this attempt even though its target\n // may still be on the books.\n attempt.terminalStatus = lookedUp.status;\n continue;\n }\n if (satisfiedOnBooks(attempt, rawActive, rawInactive)) {\n continue;\n }\n // Executed proves the transaction landed, but the order books may\n // still lag. Keep the journal until the expected create/cancel state\n // is visible.\n return 'unresolved';\n }\n // Venue-confirmed not-found: only never-landed once the signed\n // payload can no longer be accepted.\n if (Date.now() <= attempt.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS) {\n return 'unresolved';\n }\n // Expired and venue-confirmed absent: authoritatively never landed —\n // its reserved nonce may be released UNLESS a later dispatch (a\n // retry) already consumed it (durable consumed watermark guards).\n await this.#releaseNonceReservationIfUnconsumed(\n accountIndex,\n attempt.nonce,\n );\n }\n return 'resolved';\n };\n\n /**\n * Release a session-global nonce reservation once a submission is\n * PROVEN never-landed. Only the topmost reservation can be safely\n * lowered; anything else stays reserved until proven in turn.\n *\n * @param accountIndex - Venue account index.\n * @param nonce - The proven-unconsumed nonce.\n */\n readonly #releaseNonceReservation = (\n accountIndex: number,\n nonce: number,\n ): void => {\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n if (this.#nonceReservations.get(reservationKey) === nonce + 1) {\n this.#nonceReservations.set(reservationKey, nonce);\n }\n };\n\n /**\n * Bounded poll until the venue reflects a TP/SL transition: every\n * created client id accounted for and every cancelled order id absent\n * from the active book.\n *\n * A created trigger can EXECUTE, expire, or be venue-cancelled before\n * the first poll (an immediate/crossed TP/SL never rests), so created\n * ids reconcile against the active book PLUS the inactive/terminal\n * history — otherwise the obligation could never resolve and would\n * permanently block the symbol.\n *\n * @param readActiveRaw - Strict raw active-orders reader (session-fenced).\n * @param readInactive - Targeted inactive-history reader (cached, bounded).\n * @param expectation - Ids the venue must account for.\n * @param expectation.createdClientIds - Client ids that must be active\n * or terminal.\n * @param expectation.cancelledOrderIds - Order ids that must leave the\n * active book.\n * @param options - Aggregation options.\n * @param options.createdGroups - Per-attempt aggregation groups over\n * the created ids (see inline doc).\n * @returns Outcome: 'settled' when every id is accounted for and no\n * created id failed ('executedCreated' marks created ids that reached a\n * SUCCESS terminal state — filled/executed — instead of resting\n * active); 'created-terminal-failed' when the venue reports a created\n * id cancelled/rejected/expired (the obligation RESOLVES — the caller\n * surfaces the failure but no permanent block remains); 'timeout' when\n * the bound elapsed unresolved.\n */\n readonly #awaitTpslVisibility = async (\n readActiveRaw: () => Promise<LighterApiOrder[]>,\n readInactive: (targetClientIds: number[]) => Promise<LighterApiOrder[]>,\n expectation: { createdClientIds: number[]; cancelledOrderIds: string[] },\n options: {\n /**\n * PER-ATTEMPT aggregation groups over `createdClientIds`: within a\n * group, grouped-OCO semantics hold (one fully executed leg\n * legitimately auto-cancels its sibling — the GROUP succeeded);\n * ACROSS groups every group must independently succeed or rest\n * active. Omitted: all created ids form one group (legacy grouped\n * semantics).\n */\n createdGroups?: number[][];\n } = {},\n ): Promise<\n | { outcome: 'settled'; executedCreated: boolean }\n | {\n outcome: 'created-terminal-failed';\n /** New legs still resting ACTIVE despite a failed sibling. */\n survivingActiveClientIds: number[];\n }\n | { outcome: 'timeout' }\n > => {\n for (\n let attempt = 0;\n attempt < LIGHTER_TPSL_SETTLE_ATTEMPTS;\n attempt += 1\n ) {\n const rawActive = await readActiveRaw();\n // ACTIVE-FIRST: only ids not already proven active need the\n // high-weight inactive-history lookup; a normal freshly-active\n // replacement performs ZERO inactive requests.\n const missingFromActive = expectation.createdClientIds.filter(\n (clientId) =>\n !rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const rawInactive =\n missingFromActive.length > 0\n ? await readInactive(missingFromActive)\n : [];\n // Per-id classification. Success is EXACT-whitelisted\n // ('filled'/'executed') AND requires a strictly ZERO remaining size\n // (a 'filled' row with remainder is not a proven execution);\n // everything else terminal — including unknown statuses — fails\n // CLOSED.\n const classified = expectation.createdClientIds.map((clientId) => {\n if (\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n )\n ) {\n return { clientId, state: 'active' as const };\n }\n const terminal = rawInactive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (!terminal) {\n return { clientId, state: 'missing' as const };\n }\n const status = terminal.status.toLowerCase();\n // STRICT remaining parse: a prefix-parsed '0oops' must never\n // count as a proven zero remainder.\n const fullyExecuted =\n (status === 'filled' || status === 'executed') &&\n parseStrictDecimal(terminal.remainingBaseAmount) === 0;\n return {\n clientId,\n state: fullyExecuted ? ('success' as const) : ('failed' as const),\n };\n });\n const createdAccounted = !classified.some(\n (entry) => entry.state === 'missing',\n );\n const cancelledGone = expectation.cancelledOrderIds.every(\n (orderId) =>\n !rawActive.some((order) => String(order.orderIndex) === orderId),\n );\n if (createdAccounted && cancelledGone) {\n // PER-GROUP aggregation: within a group one fully executed leg\n // auto-cancels its sibling (grouped OCO — the GROUP succeeded);\n // across groups each must independently succeed or rest active.\n const groups =\n options.createdGroups ??\n (expectation.createdClientIds.length > 0\n ? [expectation.createdClientIds]\n : []);\n const stateOfId = new Map(\n classified.map((entry) => [entry.clientId, entry.state]),\n );\n let anyGroupSuccess = false;\n const failedGroupActiveIds: number[] = [];\n let anyGroupFailed = false;\n for (const group of groups) {\n const states = group.map(\n (clientId) => stateOfId.get(clientId) ?? 'missing',\n );\n if (states.includes('success')) {\n anyGroupSuccess = true;\n continue;\n }\n if (states.includes('failed')) {\n anyGroupFailed = true;\n failedGroupActiveIds.push(\n ...group.filter(\n (clientId) => stateOfId.get(clientId) === 'active',\n ),\n );\n }\n }\n if (anyGroupFailed) {\n return {\n outcome: 'created-terminal-failed',\n survivingActiveClientIds: failedGroupActiveIds,\n };\n }\n return { outcome: 'settled', executedCreated: anyGroupSuccess };\n }\n await new Promise((resolve) =>\n setTimeout(resolve, LIGHTER_TPSL_SETTLE_POLL_MS),\n );\n }\n return { outcome: 'timeout' };\n };\n\n /**\n * Throws when the session generation moved past the captured one — used\n * after every await in account-bound async work so a delayed account-A\n * step can never mutate account-B's session.\n *\n * @param generation - Generation captured when the work started.\n */\n readonly #assertSession = (generation: number): void => {\n if (this.#isDisconnected) {\n throw new Error(\n 'Operation cancelled: the Lighter provider was disconnected',\n );\n }\n if (generation !== this.#sessionGeneration) {\n throw new Error(\n 'Operation cancelled: the wallet switched accounts (or the signer reset) while this operation was in flight',\n );\n }\n // The generation only advances when some provider call rebinds; also\n // notice a wallet switch nothing has observed yet. Account-bound work\n // must never run without a binding: every legitimate flow (including\n // headless l1Address and configured-index setups) binds first, so a\n // null binding here means the wallet was deselected — fail closed even\n // when a configured account index could still resolve.\n if (this.#boundAddress === null) {\n throw new Error(\n 'Operation cancelled: no wallet account is bound to the venue session',\n );\n }\n let address: string | null = null;\n try {\n address = this.#walletService.getUserAddress().toLowerCase();\n } catch {\n address = null;\n }\n if (address !== this.#boundAddress) {\n if (address === null) {\n // Deselected: nothing to rebind to yet.\n this.#invalidateSessionState();\n this.#teardownStream();\n } else {\n // Unobserved switch: rebind properly (invalidates caches and\n // rebuilds stream channels for the new account) before cancelling\n // the stale operation.\n this.#ensureSessionBinding();\n }\n throw new Error(\n 'Operation cancelled: the wallet switched accounts (or the signer reset) while this operation was in flight',\n );\n }\n };\n\n /** Drop every cache derived from the previously bound account. */\n readonly #invalidateSessionState = (): void => {\n this.#sessionGeneration += 1;\n this.#boundAddress = null;\n this.#accountIndex = null;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#clearBridgeOwnership();\n // #tpslUnsettled survives (address+accountIndex+symbol keyed): a\n // reselect of the same account must still reconcile its pending ids.\n };\n\n /**\n * Create the WASM signer client and register the venue key if the\n * account's key slot does not hold it yet. Deduplicated.\n *\n * @returns Resolves when the signer session is ready.\n */\n readonly #ensureSignerReady = async (): Promise<void> => {\n this.#ensureSessionBinding();\n this.#assertSession(this.#sessionGeneration);\n if (this.#signerReadyPromise) {\n return await this.#signerReadyPromise;\n }\n const generation = this.#sessionGeneration;\n const setupPromise = this.#setupSigner(generation);\n this.#signerReadyPromise = setupPromise;\n try {\n return await setupPromise;\n } catch (error) {\n // Only clear the promise WE installed — a newer session may already\n // have replaced it, and an old rejection must not tear that down.\n if (this.#signerReadyPromise === setupPromise) {\n this.#signerReadyPromise = null;\n }\n throw error;\n }\n };\n\n readonly #setupSigner = async (generation: number): Promise<void> => {\n const bridge = this.#getSignerBridge();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generation);\n const chainId = getLighterChainId(this.#clientService.network);\n // The WASM client is a singleton inside the bridge host and the venue\n // key registration is a nonce-consuming write. Both therefore run\n // INSIDE the venue write lock: a stale previous-account setup aborts at\n // the lock's fence before it can touch the bridge, and no other\n // account's setup or write can interleave with this critical section.\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n const nonce = await nextNonce();\n this.#assertSession(generation);\n const created = await bridge.createClient({\n chainId,\n accountIndex,\n nonce,\n apiKeyIndex: this.#apiKeyIndex,\n });\n if (created.error || !created.success) {\n throw new Error(\n `Lighter signer client creation failed: ${created.error ?? 'unknown'}`,\n );\n }\n this.#assertSession(generation);\n this.#venuePublicKey = created.pk;\n // Record bridge-client OWNERSHIP: the WASM client is a singleton\n // per bridge, so every later write section re-establishes it\n // when another identity has since overwritten it.\n this.#signerIdentity = `${this.#clientService.network}:${accountIndex}:${this.#apiKeyIndex}`;\n // Re-establishment passes only public session metadata. The client\n // owns and restores the venue key inside the bridge.\n this.#signerRecreateParams = { chainId, accountIndex };\n bridgeClientOwners.set(this.#rawSignerBridge(), this.#signerIdentity);\n\n // Register the venue key when the slot does not hold it yet. The\n // bridge returns only public registration data; the client-owned\n // venue private key never crosses into Core.\n const registered = await this.#isVenueKeyRegistered(accountIndex);\n this.#assertSession(generation);\n if (!registered) {\n await this.#registerVenueKey(\n accountIndex,\n created.body,\n generation,\n nextNonce,\n submit,\n );\n this.#assertSession(generation);\n }\n },\n generation,\n );\n // AUTOMATIC bounded recovery: pending TP/SL journals must be\n // reconciled at startup/reconnect, not only when the next mutation\n // happens to run. Detached so it awaits THIS setup's resolved promise\n // instead of deadlocking on it.\n this.#kickTpslRecovery();\n };\n\n readonly #isVenueKeyRegistered = async (\n accountIndex: number,\n ): Promise<boolean> => {\n // Query all slots. Lighter returns `api key not found` when a missing\n // slot is requested directly, which would make first-time registration\n // impossible. The all-slots response is successful and represents an\n // unused slot by omitting it from `apiKeys`.\n const response = await this.#clientService.getApiKeys(accountIndex);\n const configuredSlot = response.apiKeys.find(\n (key) => key.apiKeyIndex === this.#apiKeyIndex,\n );\n if (!configuredSlot) {\n return false;\n }\n const normalizeKey = (key: string | null): string =>\n (key ?? '').replace(/^0x/u, '').toLowerCase();\n if (\n normalizeKey(configuredSlot.publicKey) ===\n normalizeKey(this.#venuePublicKey)\n ) {\n return true;\n }\n throw new Error(\n `Lighter API key slot ${String(this.#apiKeyIndex)} already contains a different key; automatic replacement is disabled because personal_sign output is not guaranteed to be byte-identical across signer implementations or devices`,\n );\n };\n\n readonly #registerVenueKey = async (\n accountIndex: number,\n changePubKeyBody: string,\n generation: number,\n nextNonce: () => Promise<number>,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ): Promise<void> => {\n const bridge = this.#getSignerBridge();\n // The ChangePubKey plaintext from _createClient embeds the nonce used at\n // client creation; sign it with the user's L1 account (EIP-191). Every\n // await is fenced and the submission goes through the lock's fenced\n // submit — a stale registration can never reach the venue.\n const l1Signature =\n await this.#walletService.signPersonalMessage(changePubKeyBody);\n this.#assertSession(generation);\n const nonce = await nextNonce();\n this.#assertSession(generation);\n const signed = await bridge.execute({\n function: '_signChangePubKey',\n params: [accountIndex, l1Signature, nonce, this.#apiKeyIndex],\n });\n if (signed.error) {\n throw new Error(`Lighter ChangePubKey signing failed: ${signed.error}`);\n }\n this.#assertSession(generation);\n const result = await submit(\n LIGHTER_TX_TYPE_CHANGE_PUB_KEY,\n signed.txInfo,\n undefined,\n extractDispatchIdentity(signed),\n );\n this.#deps.debugLogger.log('[LighterProvider] Venue key registered', {\n accountIndex,\n apiKeyIndex: this.#apiKeyIndex,\n txHash: result.txHash,\n });\n };\n\n /**\n * Mint (or reuse) an auth token for authenticated REST reads.\n *\n * @returns Auth token string.\n */\n /** Tail of the serialized venue-write chain (see #withVenueNonce). */\n #writeChain: Promise<void> = Promise.resolve();\n\n /** Every client order id this instance has issued (collision set). */\n readonly #issuedClientOrderIds = new Set<number>();\n\n /**\n * Atomically reserve unique client order indexes.\n *\n * The venue requires client_order_index to be UNIQUE ACROSS ALL MARKETS\n * for the account (official Get Started docs) and does not require\n * monotonicity. Ids are uniform random draws over the uint48 space\n * (two 24-bit draws, exact in float space) with a per-instance\n * collision set and retry: within an instance duplicates are\n * impossible; across simultaneous instances/devices a single pair\n * collides with probability 1/2^48 (~3.6e-15) and the birthday bound\n * over n total ids is ~n(n-1)/2^49 — about 1.8e-7 after ten thousand\n * orders, versus the 1% per-pair risk of the previous 100-lane scheme.\n *\n * @param count - How many ids to reserve.\n * @returns The reserved ids.\n */\n readonly #allocateClientOrderIndexes = (count: number): number[] => {\n const ids: number[] = [];\n // Bounded: a degenerate randomness source (or an absurdly full\n // collision set) must surface as an error, never a synchronous spin.\n // 100 attempts per id makes accidental exhaustion unreachable in\n // practice (collision odds per draw stay astronomically small).\n let attempts = 0;\n const maxAttempts = count * 100;\n while (ids.length < count) {\n if (attempts >= maxAttempts) {\n throw new Error(\n `Unable to allocate a unique Lighter client order id after ${maxAttempts} attempts`,\n );\n }\n attempts += 1;\n const [high, low] = randomUint24Pair();\n const candidate = high * 2 ** 24 + low;\n if (candidate === 0 || this.#issuedClientOrderIds.has(candidate)) {\n continue;\n }\n this.#issuedClientOrderIds.add(candidate);\n ids.push(candidate);\n }\n return ids;\n };\n\n /**\n * Serialize a nonce-consuming venue write.\n *\n * Lighter nonces are strictly ordered per key slot; two interleaved\n * fetch→submit pairs (e.g. the controller's per-item batch fallbacks\n * running concurrently) would sign with the same nonce and get one\n * rejection. Every write acquires the chain, fetches a fresh nonce\n * inside it, and submits before the next write's fetch runs. A section\n * queued under a wallet account that has since been switched away from\n * refuses to run — a delayed account-A write must never execute inside\n * account-B's session.\n *\n * @param accountIndex - Account whose key-slot nonce is consumed.\n * @param section - Work to run exclusively; fetch nonces via the\n * provided helper (each call returns the next fresh nonce).\n * @param generationAtIntent - Session generation captured when the\n * caller's intent was formed (defaults to now).\n * @returns The section's result.\n */\n readonly #withVenueWriteLock = async <Result>(\n accountIndex: number,\n section: (\n nextNonce: () => Promise<number>,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ) => Promise<Result>,\n generationAtIntent = this.#sessionGeneration,\n ): Promise<Result> => {\n const criticalSection = async (): Promise<Result> => {\n this.#assertSession(generationAtIntent);\n // Every unresolved prior dispatch (this session OR a previous one —\n // the ledger is durable) must resolve before this section may issue\n // nonces: a restart would otherwise reuse a consumed-but-lagging\n // nonce, and a proven never-landed dispatch must release its nonce.\n await this.#resolveNonceLedger(accountIndex);\n this.#assertSession(generationAtIntent);\n // Monotonic nonce reservation: the venue's nextNonce endpoint can\n // LAG accepted submissions. The floor is SESSION-GLOBAL per\n // accountIndex:apiKeyIndex — a queued/next lock section (any\n // symbol, any operation) must never be handed a nonce an earlier\n // submission may have consumed, even when that submission's\n // response was lost. Reservation advances at DISPATCH (a signing\n // failure never burns a nonce the venue still expects); a proven\n // never-landed submission releases it again via reconciliation.\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n let lastIssuedNonce: number | null = null;\n const nextNonce = async (): Promise<number> => {\n // Re-fenced on every fetch AND after it resolves: the account can\n // switch between the section's own await points, not only while it\n // sat in the queue.\n this.#assertSession(generationAtIntent);\n const nonceResponse = await this.#clientService.getNextNonce(\n accountIndex,\n this.#apiKeyIndex,\n );\n this.#assertSession(generationAtIntent);\n const reservedFloor = this.#nonceReservations.get(reservationKey);\n const issued =\n reservedFloor === undefined\n ? nonceResponse.nonce\n : Math.max(nonceResponse.nonce, reservedFloor);\n lastIssuedNonce = issued;\n return issued;\n };\n // BRIDGE OWNERSHIP: the WASM client is a singleton per bridge —\n // another provider (different account/network sharing the bridge)\n // may have overwritten it since our setup. Re-establish OUR client\n // before any signing in this section. (During initial setup the\n // identity is not yet recorded; setup itself creates the client.)\n if (\n this.#signerIdentity !== null &&\n this.#signerRecreateParams !== null &&\n bridgeClientOwners.get(this.#rawSignerBridge()) !== this.#signerIdentity\n ) {\n await this.#reestablishSignerClient(\n generationAtIntent,\n await nextNonce(),\n );\n }\n const submit = async (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ): Promise<LighterSendTxResponse> => {\n // Last fence before anything reaches the venue: a switch that\n // happened while SIGNING must abort before submission.\n this.#assertSession(generationAtIntent);\n // Record the dispatch DURABLY BEFORE anything else: a failed\n // ledger read/write means NO dispatch and an UNTOUCHED memory\n // floor — the nonce stays safely unissued at the venue. The\n // identity comes from the SIGNING RESULT (pinned WASM contract:\n // txInfo never carries the hash).\n let ledgerEntry: LighterNonceLedgerDoc['entries'][number] | null = null;\n if (lastIssuedNonce !== null) {\n // COMPLETE identity is REQUIRED before anything reaches the\n // wire: a hashless dispatch could never be proven absent, so a\n // response loss would wedge writes until the venue advances.\n if (\n identity?.txHash === null ||\n identity?.expiresAt === null ||\n identity === undefined\n ) {\n throw new Error(\n 'Lighter dispatch refused: the signing result did not provide a complete transaction identity (hash + expiry)',\n );\n }\n ledgerEntry = {\n nonce: lastIssuedNonce,\n txHash: identity.txHash,\n expiresAt: identity.expiresAt,\n kind: txType,\n intent: identity.intent ?? `txType:${txType}`,\n owner: identity.owner ?? null,\n };\n const appendedEntry = ledgerEntry;\n await this.#withLedgerLock(accountIndex, async () => {\n const doc = await this.#readNonceLedger(accountIndex);\n if (doc.entries.length >= 16) {\n throw new Error(\n 'Too many unresolved Lighter dispatches; refusing further writes until they resolve',\n );\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: [...doc.entries, appendedEntry],\n recovered: doc.recovered,\n });\n });\n // Only AFTER the durable append: reserve in memory — from this\n // point the venue may consume the nonce even if the response\n // never arrives.\n this.#nonceReservations.set(reservationKey, lastIssuedNonce + 1);\n }\n // EVERY error path below keeps the durable entry — a coded venue\n // or HTTP error can mask a commit, so nothing short of an exact\n // authoritative reconciliation may release the nonce.\n const response: LighterSendTxResponse =\n await this.#clientService.sendTx(txType, txInfo);\n // Acceptance bookkeeping runs SYNCHRONOUSLY before anything can\n // fail: a switch during network submission must cancel the\n // operation, never the record of an accepted venue mutation.\n onAccepted?.();\n // POST-SEND ORDER: evaluate the session fence BEFORE the ledger\n // entry transitions, then commit the transition ATOMICALLY in\n // ONE write under the ledger lock — fence pass → consumed/\n // removed; fence fail → recovered(SUCCEEDED). If that single\n // write fails, the ORIGINAL unresolved entry remains the durable\n // record and every retry stays blocked; the only durable proof\n // of the accepted mutation is never consumed first and\n // quarantined second.\n let fenceError: unknown = null;\n try {\n this.#assertSession(generationAtIntent);\n } catch (error) {\n fenceError = error;\n }\n if (ledgerEntry !== null) {\n await this.#resolveEntryPostDispatch(\n accountIndex,\n ledgerEntry,\n fenceError !== null,\n ).catch(() => undefined);\n }\n if (fenceError !== null) {\n throw ensureError(fenceError, 'LighterProvider.submit');\n }\n return response;\n };\n return await section(nextNonce, submit);\n };\n // The ENTIRE nonce resolve→fetch→sign/append→dispatch sequence is\n // serialized PROCESS-WIDE per network+account+api-key slot: the\n // instance chain alone cannot stop a second live provider from\n // issuing the same nonce or interleaving ledger writes.\n const guardedSection = async (): Promise<Result> =>\n await withProcessMutex(\n `lighterVenueWrite:${this.#isTestnet ? 'testnet' : 'mainnet'}:${accountIndex}:${this.#apiKeyIndex}`,\n // INNERMOST: the bridge mutex — the WASM client is a singleton\n // per bridge, so ensure-correct-client + every sign of a section\n // are serialized across ALL providers sharing the bridge.\n async () =>\n await withProcessMutex(\n bridgeMutexKey(this.#rawSignerBridge()),\n criticalSection,\n ),\n );\n const run = this.#writeChain.then(guardedSection, guardedSection);\n this.#writeChain = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n };\n\n readonly #withVenueNonce = async <Result>(\n accountIndex: number,\n operation: (\n nonce: number,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ) => Promise<Result>,\n generationAtIntent = this.#sessionGeneration,\n ): Promise<Result> =>\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => operation(await nextNonce(), submit),\n generationAtIntent,\n );\n\n /**\n * Re-create OUR venue client on the shared bridge after another\n * identity overwrote the singleton. MUST run while holding the bridge\n * mutex. The bridge owns key generation and persistence.\n *\n * @param generation - The caller's captured session generation.\n * @param nonce - A fresh venue nonce for the client creation.\n */\n readonly #reestablishSignerClient = async (\n generation: number,\n nonce: number,\n ): Promise<void> => {\n const recreateParams = this.#signerRecreateParams;\n const identity = this.#signerIdentity;\n if (recreateParams === null || identity === null) {\n throw new Error(\n 'Lighter signer client re-establishment attempted before setup',\n );\n }\n this.#assertSession(generation);\n const recreated = await this.#getSignerBridge().createClient({\n chainId: recreateParams.chainId,\n accountIndex: recreateParams.accountIndex,\n nonce,\n apiKeyIndex: this.#apiKeyIndex,\n });\n if (recreated.error || !recreated.success) {\n throw new Error(\n `Lighter signer client re-establishment failed: ${recreated.error ?? 'unknown'}`,\n );\n }\n this.#assertSession(generation);\n bridgeClientOwners.set(this.#rawSignerBridge(), identity);\n };\n\n readonly #getAuthToken = async (): Promise<string> => {\n this.#ensureSessionBinding();\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (this.#authToken && this.#authToken.deadline - nowSeconds > 60) {\n return this.#authToken.token;\n }\n const generation = this.#sessionGeneration;\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n // The auth-token mint is a singleton-client call like any other sign:\n // it runs under the BRIDGE LEASE, and re-establishes OUR client first\n // when another identity has since overwritten it — otherwise the\n // token would be minted by the wrong account's venue key.\n const token = await withProcessMutex(\n bridgeMutexKey(this.#rawSignerBridge()),\n async () => {\n if (\n this.#signerIdentity !== null &&\n this.#signerRecreateParams !== null &&\n bridgeClientOwners.get(this.#rawSignerBridge()) !==\n this.#signerIdentity\n ) {\n // Client creation is bridge-local: the read-only nonce fetch\n // seeds its tracking without dispatching anything.\n const nonceResponse = await this.#clientService.getNextNonce(\n this.#signerRecreateParams.accountIndex,\n this.#apiKeyIndex,\n );\n this.#assertSession(generation);\n await this.#reestablishSignerClient(generation, nonceResponse.nonce);\n }\n return await this.#getSignerBridge().execute({\n function: '_createAuthToken',\n params: [accountIndex, this.#apiKeyIndex],\n });\n },\n );\n if (token.error || !token.token) {\n throw new Error(\n `Lighter auth token creation failed: ${token.error ?? 'unknown'}`,\n );\n }\n // Rebind first so an unobserved external switch during the bridge call\n // advances the generation, then compare: a token minted under a binding\n // that no longer exists must never be cached — re-mint under the new\n // captured session instead.\n this.#ensureSessionBinding();\n if (generation !== this.#sessionGeneration) {\n return await this.#getAuthToken();\n }\n this.#authToken = { token: token.token, deadline: token.deadline };\n return token.token;\n };\n\n readonly #ensureMarkets = async (): Promise<\n Map<string, LighterOrderBookMeta>\n > => {\n if (this.#marketsBySymbol.size === 0) {\n await this.initialize();\n }\n return this.#marketsBySymbol;\n };\n\n // ============================================================================\n // Market Data Operations (Public Reads)\n // ============================================================================\n\n async getMarkets(_params?: GetMarketsParams): Promise<MarketInfo[]> {\n try {\n const markets = await this.#clientService.getOrderBooks();\n await this.#ensureMarketMargins();\n return markets\n .filter((market) => market.marketType === 'perp')\n .flatMap((market) => {\n const margins = this.#marginBySymbol.get(market.symbol);\n if (!margins) {\n // #ensureMarketMargins deliberately omits inactive rows whose\n // retired risk metadata cannot produce a canonical MarketInfo.\n if (market.status === 'inactive') {\n return [];\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n const adapted = adaptMarketFromLighter(\n market,\n deriveLighterMaxLeverage(margins.minInitial, market.symbol),\n );\n // minBaseAmount and minQuoteAmount are maker-only. Market and\n // IOC orders can use one base-size tick, so the public universal\n // minimum must report that tick rather than the maker floor.\n delete adapted.minimumOrderSize;\n if (margins?.lastTradePrice && margins.lastTradePrice > 0) {\n const oneTickUsd =\n margins.lastTradePrice / 10 ** market.supportedSizeDecimals;\n if (Number.isFinite(oneTickUsd) && oneTickUsd > 0) {\n adapted.minimumOrderSize = oneTickUsd;\n }\n }\n return [adapted];\n });\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getMarkets',\n );\n this.#deps.debugLogger.log('[LighterProvider] getMarkets failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getMarkets'),\n });\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n throw caughtError;\n }\n return [];\n }\n }\n\n async getMarketDataWithPrices(): Promise<PerpsMarketData[]> {\n try {\n const response = await this.#clientService.getOrderBookDetails();\n return response.orderBookDetails\n .filter((detail) => detail.marketType === 'perp')\n .filter((detail) => !isInactiveMarketWithoutUsableRiskMetadata(detail))\n .map((detail) =>\n adaptMarketDataFromLighter(detail, this.#deps.marketDataFormatters),\n );\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getMarketDataWithPrices',\n );\n this.#deps.debugLogger.log(\n '[LighterProvider] getMarketDataWithPrices failed',\n {\n error: String(wrappedError),\n ...this.#getErrorContext('getMarketDataWithPrices'),\n },\n );\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n throw caughtError;\n }\n return [];\n }\n }\n\n // ============================================================================\n // Account Operations\n // ============================================================================\n\n async getPositions(_params?: GetPositionsParams): Promise<Position[]> {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n // Risk metadata is required for every returned position. A transport\n // failure must reject instead of looking like an authoritative empty\n // account.\n await this.#ensureMarketMargins();\n try {\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n this.#assertSession(generation);\n const account = response.accounts[0];\n if (!account?.positions) {\n return [];\n }\n // Adapt BEFORE filtering: the adapter strict-validates raw numeric\n // sizes, and a prefix-parsing filter would silently drop (or keep)\n // malformed entries like '0oops' before validation could fire.\n return account.positions\n .map((position) =>\n adaptPositionFromLighter(\n position,\n this.#maxLeverageForPosition(position),\n ),\n )\n .filter((position) => parseFloat(position.size) !== 0);\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates and venue-data integrity failures must surface,\n // never degrade into empty state that can preserve stale views.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getPositions',\n );\n this.#deps.debugLogger.log('[LighterProvider] getPositions failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getPositions'),\n });\n return [];\n }\n }\n\n async getAccountState(\n _params?: GetAccountStateParams,\n ): Promise<AccountState> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n // A delayed response for the previous account must never surface as\n // the current account's state.\n this.#assertSession(generation);\n const account = response.accounts[0];\n if (!account) {\n return EMPTY_ACCOUNT_STATE;\n }\n return adaptAccountStateFromLighter(account);\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates and venue-data integrity failures must surface,\n // never degrade into empty state that can preserve stale views.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getAccountState',\n );\n this.#deps.debugLogger.log('[LighterProvider] getAccountState failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getAccountState'),\n });\n return EMPTY_ACCOUNT_STATE;\n }\n }\n\n /**\n * STRICT active-orders read: any REST/auth failure THROWS. Mutation\n * flows (TP/SL replacement/removal) must use this — treating a swallowed\n * [] as authoritative would let them \"succeed\" while cancelling nothing.\n *\n * @returns Adapted open orders.\n */\n readonly #readOpenOrdersStrict = async (): Promise<Order[]> => {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n // The index and the token must belong to the SAME session — never\n // pair the previous account's index with the new account's token.\n this.#assertSession(generation);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generation);\n return response.orders.map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n };\n\n async getOpenOrders(_params?: GetOrdersParams): Promise<Order[]> {\n // Public reads re-kick pending journal recovery (deduped, detached).\n this.#kickTpslRecovery();\n try {\n return await this.#readOpenOrdersStrict();\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates must surface, never degrade into empty state.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getOpenOrders',\n );\n this.#deps.debugLogger.log('[LighterProvider] getOpenOrders failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getOpenOrders'),\n });\n return [];\n }\n }\n\n async getOrders(\n params?: GetOrdersParams,\n _options?: PerpsReadOptions,\n ): Promise<Order[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n this.#assertSession(generation);\n await this.#ensureMarkets();\n const response = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n );\n // Both legs (historical + open) must come from one session — a\n // switch mid-way would merge account A's history with B's orders.\n this.#assertSession(generation);\n const historical = (response.orders ?? []).map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n // Full lifecycle: open orders first, then the historical states.\n const open = await this.getOpenOrders(params);\n // getOpenOrders swallows its own cancellation into []; the merge must\n // still refuse to pair A's history with B's session.\n this.#assertSession(generation);\n return [...open, ...historical];\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates must surface, never degrade into empty state.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getOrders',\n );\n this.#deps.debugLogger.log('[LighterProvider] getOrders failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getOrders'),\n });\n return [];\n }\n }\n\n async getCurrentAccountId(): Promise<CaipAccountId> {\n const address = this.#walletService.getUserAddress();\n const chainId = getLighterChainId(this.#clientService.network);\n return `eip155:${chainId}:${address}` as CaipAccountId;\n }\n\n // ============================================================================\n // Trading Operations (POC: limit/market place + cancel)\n // ============================================================================\n\n /**\n * Apply the leverage the caller requested with the order.\n *\n * Lighter models leverage as a per-market account setting (UpdateLeverage,\n * tx 20; initial margin fraction in hundredths of a percent), not an order\n * field. The venue rejects the update while a position or resting order\n * exists on the market, so in that case the request is skipped with a log\n * (matching the already-set leverage is not an error).\n *\n * @param accountIndex - Lighter account index.\n * @param market - Market metadata for the order being placed.\n * @param params - The original order params carrying `leverage`.\n */\n /**\n * Decide whether the caller's requested leverage needs a venue update.\n *\n * @param params - The order params carrying `leverage`.\n * @returns The UpdateLeverage margin fraction (hundredths of a percent)\n * to sign, or null when no change is needed.\n */\n readonly #resolveLeverageIntent = async (\n params: OrderParams,\n ): Promise<number | null> => {\n const requested = params.leverage;\n if (requested === undefined) {\n return null;\n }\n // Venue state decides, never the caller's possibly-stale\n // existingPositionLeverage snapshot.\n const positions = await this.getPositions();\n const held = positions.find(\n (position) => position.symbol === params.symbol,\n );\n if (\n held?.leverage?.value !== undefined &&\n Math.abs(held.leverage.value - requested) < 0.5\n ) {\n // Requested leverage already in effect — intent satisfied.\n return null;\n }\n // Otherwise sign the update inside the placement's own write lock. If\n // the market has a position or resting order the venue rejects it with\n // a clear error, failing the placement instead of silently trading at\n // a leverage the caller did not ask for.\n return Math.round(10_000 / requested);\n };\n\n async placeOrder(\n params: OrderParams,\n inheritedGeneration?: number,\n ): Promise<OrderResult> {\n // Tracks a COMMITTED leverage change so an order failing afterwards\n // reports the partial venue state explicitly instead of implying no\n // mutation happened.\n let leverageCommitted = false;\n try {\n if (params.marginMode !== undefined) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n if (params.orderType !== 'limit' && params.orderType !== 'market') {\n return { success: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n // User intent is never silently dropped: fields this venue path does\n // not execute are rejected so the caller can adapt, not surprised.\n if (params.takeProfitPrice || params.stopLossPrice) {\n return {\n success: false,\n error:\n 'Lighter does not support TP/SL attached at placement; place the order, then call updatePositionTPSL',\n };\n }\n if (params.timeInForce === 'ALO') {\n return {\n success: false,\n error: 'Lighter placement does not support post-only (ALO) yet',\n };\n }\n const leverageError = lighterLeverageError(params.leverage);\n if (leverageError) {\n return { success: false, error: leverageError };\n }\n // Bind the write to the wallet account it was INITIATED under; if the\n // wallet switches before the queued critical section runs, it aborts.\n // A composite caller (closePosition) passes ITS generation so the\n // whole read-then-write sequence shares one intent identity.\n this.#ensureSessionBinding();\n const generationAtIntent = inheritedGeneration ?? this.#sessionGeneration;\n this.#assertSession(generationAtIntent);\n // All intent validation below uses PUBLIC market data only; signer\n // and account setup are deferred until it passes so invalid intent\n // causes zero bridge calls (no client creation or key registration\n // side effects).\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n if (params.orderType === 'limit' && !params.price) {\n return { success: false, error: 'Limit order requires a price' };\n }\n if (params.leverage !== undefined) {\n // Authoritative metadata REQUIRED: the display fallback (global\n // 50x) must never approve leverage for a market whose published\n // bound is unavailable.\n const maxLeverage = await this.#requireMarketMaxLeverage(params.symbol);\n if (maxLeverage === null) {\n return {\n success: false,\n error: `Cannot validate leverage for ${params.symbol}: venue margin metadata unavailable`,\n };\n }\n if (params.leverage > maxLeverage) {\n return {\n success: false,\n error: `Invalid leverage ${params.leverage}: exceeds the ${params.symbol} maximum of ${maxLeverage}x`,\n };\n }\n }\n\n // Slippage tolerance: caller basis points win, then the deprecated\n // decimal field, then the venue-conventional 5%.\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? (params.slippage ?? 0.05)\n : params.maxSlippageBps / 10_000;\n // The reference price sizes the order; market orders additionally get\n // a protection price offset by the slippage tolerance. They are kept\n // separate so usdAmount sizing is never distorted by the protection\n // offset.\n let referencePrice: number;\n if (params.orderType === 'limit') {\n // STRICT full-string parse: '90000USD' prefix-parses under\n // parseFloat and must never become signed intent.\n const parsedLimitPrice = parseFinitePositive(params.price ?? '');\n if (parsedLimitPrice === null) {\n return {\n success: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n referencePrice = parsedLimitPrice;\n } else {\n referencePrice = parseFloat(\n params.price ?? String(params.currentPrice ?? 0),\n );\n }\n let executionPrice = referencePrice;\n if (params.orderType === 'market') {\n const resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n if (resolved.error !== null) {\n return { success: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n params.isBuy,\n slippageFraction,\n );\n }\n // Finite AND positive: 'Infinity' passes a bare > 0 check but would\n // corrupt integerization/signing downstream.\n if (\n !Number.isFinite(referencePrice) ||\n !(referencePrice > 0) ||\n !Number.isFinite(executionPrice) ||\n !(executionPrice > 0)\n ) {\n return {\n success: false,\n error: 'Unable to resolve a finite execution price for the order',\n };\n }\n // USD is the source of truth when provided (hybrid sizing contract),\n // converted at the reference price — not the protection price. A\n // provided-but-invalid usdAmount is an error, never a silent fallback\n // to the size field.\n let requestedSize: number;\n if (params.usdAmount === undefined) {\n const parsedSize = parseFinitePositive(params.size);\n if (parsedSize === null) {\n return { success: false, error: 'Order size must be positive' };\n }\n requestedSize = parsedSize;\n } else {\n const usdAmount = parseFinitePositive(params.usdAmount);\n if (usdAmount === null) {\n return {\n success: false,\n error: `Invalid usdAmount ${params.usdAmount}: must be a positive number`,\n };\n }\n // A USD amount is approximate by contract (converted at the\n // reference price), so it is snapped onto the venue size grid the\n // way wire integerization will round it — an explicit size string\n // is exact user intent and is never adjusted here.\n requestedSize = snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n );\n }\n if (!(requestedSize > 0)) {\n return { success: false, error: 'Order size must be positive' };\n }\n if (params.usdAmount === undefined) {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n fromLighterInteger(requestedSizeInt, market.supportedSizeDecimals) !==\n requestedSize\n ) {\n return {\n success: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n }\n const minSize = isLighterMakerOrder(params)\n ? computeLighterMinOrderSize(market, referencePrice)\n : 0;\n if (minSize > 0 && requestedSize < minSize) {\n // Only a LIVE-VERIFIED full close may be bumped to the venue\n // minimum: reduce-only execution clamps to the position, so no\n // extra exposure results and dust positions stay closable. The\n // isFullClose flag is a hint, never trusted — a partial close\n // bumped to the minimum would close more than the caller asked.\n const verifiedFullClose = params.reduceOnly\n ? await this.#isVerifiedFullClose(params.symbol, requestedSize)\n : false;\n if (!verifiedFullClose) {\n return {\n success: false,\n error: `Order size ${requestedSize} is below the Lighter minimum of ${minSize} ${params.symbol}`,\n };\n }\n }\n const size =\n minSize > 0 ? Math.max(requestedSize, minSize) : requestedSize;\n\n // Wire-format integerization runs BEFORE signer setup: overflow and\n // sub-tick rejections throw here, still with zero bridge calls.\n const priceInt = toSignerWirePriceInteger(\n executionPrice,\n market.supportedPriceDecimals,\n );\n const sizeInt = toSignerWireInteger(size, market.supportedSizeDecimals);\n\n const leverageImfHundredths = await this.#resolveLeverageIntent(params);\n // Margin mode is sent only with an explicit leverage update. An\n // omitted leverage leaves both leverage and margin mode unchanged;\n // an explicit update preserves an existing position's venue mode and\n // uses isolated only for a flat market.\n const leverageMarginMode =\n leverageImfHundredths === null\n ? null\n : await this.#resolveMarginModeForSymbol(params.symbol);\n\n // Intent validated — only now do signer and account setup run.\n // Re-fence FIRST: the preflight awaited public/account reads during\n // which the wallet may have switched, and a stale intent must never\n // create or register the new account's venue key.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generationAtIntent);\n const [clientOrderIndex] = this.#allocateClientOrderIndexes(1);\n\n // Leverage update and order placement share ONE lock acquisition so a\n // concurrent write can never interleave between the caller's leverage\n // intent and the order that depends on it.\n const result = await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n if (leverageImfHundredths !== null && leverageMarginMode !== null) {\n const signedLeverage = await this.#getSignerBridge().execute({\n function: '_signUpdateLeverage',\n // Contract: [accountIndex, marketId, imfHundredths,\n // marginMode, nonce] — exactly five params.\n params: [\n accountIndex,\n market.marketId,\n leverageImfHundredths,\n leverageMarginMode,\n await nextNonce(),\n ],\n });\n if (signedLeverage.error) {\n throw new Error(\n `Lighter leverage update failed: ${signedLeverage.error}`,\n );\n }\n await submit(\n LIGHTER_TX_TYPE_UPDATE_LEVERAGE,\n signedLeverage.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signedLeverage),\n intent: `updateLeverage:${params.symbol}:${String(params.leverage)}`,\n },\n );\n leverageCommitted = true;\n }\n const signed = await this.#getSignerBridge().execute({\n function: '_signCreateOrder',\n params: [\n accountIndex,\n market.marketId,\n clientOrderIndex,\n String(sizeInt),\n String(priceInt),\n params.isBuy ? 0 : 1,\n params.orderType === 'limit'\n ? LIGHTER_ORDER_TYPE_LIMIT\n : LIGHTER_ORDER_TYPE_MARKET,\n params.orderType === 'limit' && params.timeInForce !== 'IOC'\n ? LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME\n : LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n params.reduceOnly ? 1 : 0,\n String(LIGHTER_NO_TRIGGER_PRICE),\n // GTT orders auto-expire in 28 days (signer sentinel -1);\n // IOC orders must carry a zero expiry.\n params.orderType === 'limit' && params.timeInForce !== 'IOC'\n ? LIGHTER_ORDER_EXPIRY_NONE\n : 0,\n await nextNonce(),\n ],\n });\n if (signed.error) {\n throw new Error(`Lighter order signing failed: ${signed.error}`);\n }\n return await submit(\n LIGHTER_TX_TYPE_CREATE_ORDER,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `placeOrder:${params.symbol}:${clientOrderIndex}`,\n },\n );\n },\n generationAtIntent,\n );\n\n this.#deps.debugLogger.log('[LighterProvider] Order placed', {\n symbol: params.symbol,\n clientOrderIndex,\n txHash: result.txHash,\n });\n\n return {\n success: true,\n orderId: String(clientOrderIndex),\n submittedSize: String(size),\n providerId: 'lighter',\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.placeOrder',\n );\n this.#deps.debugLogger.log('[LighterProvider] placeOrder failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('placeOrder', { symbol: params.symbol }),\n });\n // PARTIAL VENUE STATE is contract-visible: a committed leverage\n // change followed by an order failure must never imply \"nothing\n // happened\".\n const partialPrefix = leverageCommitted\n ? `PARTIAL STATE: leverage for ${params.symbol} was already updated to ${String(params.leverage)}x before the order failed. `\n : '';\n return {\n success: false,\n error: `${partialPrefix}${wrappedError.message}`,\n ...(leverageCommitted\n ? { partialState: { leverageUpdated: Number(params.leverage) } }\n : {}),\n };\n }\n }\n\n async cancelOrder(\n params: CancelOrderParams,\n inheritedGeneration?: number,\n ): Promise<CancelOrderResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = inheritedGeneration ?? this.#sessionGeneration;\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n\n await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, params.orderId, nonce],\n });\n if (signed.error) {\n throw new Error(`Lighter cancel signing failed: ${signed.error}`);\n }\n return await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `cancelOrder:${params.symbol}:${params.orderId}`,\n },\n );\n },\n generationAtIntent,\n );\n\n return {\n success: true,\n orderId: params.orderId,\n providerId: 'lighter',\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.cancelOrder',\n );\n this.#deps.debugLogger.log('[LighterProvider] cancelOrder failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('cancelOrder', { symbol: params.symbol }),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n // ============================================================================\n // Trading Operations (POC: stubbed)\n // ============================================================================\n\n async editOrder(_params: EditOrderParams): Promise<OrderResult> {\n // ModifyOrder (tx 17) is accepted by the venue's sendTx but the resting\n // order keeps its original price — an execution no-op we have raised\n // with Lighter. Reporting success here would misrepresent user intent,\n // so the operation refuses until the venue behavior is resolved.\n // Callers can cancel + re-place instead.\n return {\n success: false,\n error:\n 'Lighter order editing is unavailable: the venue currently accepts but does not apply ModifyOrder. Cancel and re-place the order instead.',\n };\n }\n\n /**\n * Resolve the FRESH venue reference price for a market-order sizing,\n * with the same fail-closed and drift semantics as execution — shared\n * by placement and close validation so they can never disagree.\n *\n * @param symbol - Market symbol.\n * @param slippageFraction - Caller slippage tolerance (fraction).\n * @param priceAtCalculation - Caller's sizing snapshot, if any.\n * @returns The fresh reference price, or the exact execution error.\n */\n readonly #resolveMarketReferencePrice = async (\n symbol: string,\n slippageFraction: number,\n priceAtCalculation?: number,\n ): Promise<\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string }\n > => {\n // Numeric intent validates fail-closed BEFORE any drift math. A\n // non-finite/non-positive snapshot makes the drift comparison NaN\n // (silently bypassing protection), and a tolerance at or above 100%\n // derives a zero-or-negative protection price on sells.\n if (\n !Number.isFinite(slippageFraction) ||\n slippageFraction < 0 ||\n slippageFraction >= 1\n ) {\n return {\n referencePrice: null,\n error: `Invalid slippage tolerance ${slippageFraction * 10_000} bps: must be at least 0 and below 10000`,\n };\n }\n if (\n priceAtCalculation !== undefined &&\n (!Number.isFinite(priceAtCalculation) || !(priceAtCalculation > 0))\n ) {\n return {\n referencePrice: null,\n error: `Invalid price snapshot ${priceAtCalculation}: must be a positive finite number`,\n };\n }\n // Always a FRESH venue price: the caller's currentPrice is the same\n // snapshot as priceAtCalculation, and a drift check that compares a\n // snapshot to itself would never fire.\n const details = await this.#clientService.getOrderBookDetails();\n const freshPrice =\n details.orderBookDetails.find((entry) => entry.symbol === symbol)\n ?.lastTradePrice ?? 0;\n if (!Number.isFinite(freshPrice) || !(freshPrice > 0)) {\n // Fail closed: falling back to the caller's snapshot would let the\n // drift check compare that snapshot to itself.\n return {\n referencePrice: null,\n error: `No live venue price available for ${symbol}; refusing to size a market order`,\n };\n }\n if (\n priceAtCalculation !== undefined &&\n priceAtCalculation > 0 &&\n Math.abs(freshPrice - priceAtCalculation) / priceAtCalculation >\n slippageFraction\n ) {\n return {\n referencePrice: null,\n error: `Price moved beyond the ${(slippageFraction * 100).toFixed(2)}% slippage tolerance since sizing`,\n };\n }\n return { referencePrice: freshPrice, error: null };\n };\n\n /**\n * Validate the shape of a close request (shared by validateClosePosition\n * and closePosition so validation can never approve a close the\n * execution path refuses).\n *\n * @param params - Close request.\n * @returns Error message, or null when the shape is acceptable.\n */\n /**\n * The mobile close sheet sends a FULL close as an EMPTY size string\n * (`size: sizeToClose || ''`); HyperLiquid and TradingService treat a\n * falsy size as \"no explicit size\", so this venue honors the same\n * contract — an empty/whitespace size or usdAmount means full close,\n * never a validation failure.\n *\n * @param params - Raw close request.\n * @returns The request with empty-string sizing normalized to absent.\n */\n readonly #normalizeCloseParams = (\n params: ClosePositionParams,\n ): ClosePositionParams => ({\n ...params,\n size: params.size?.trim() ? params.size : undefined,\n usdAmount: params.usdAmount?.trim() ? params.usdAmount : undefined,\n });\n\n readonly #validateCloseShape = (\n params: ClosePositionParams,\n ): string | null => {\n const closeOrderType = params.orderType ?? 'market';\n if (closeOrderType !== 'market' && closeOrderType !== 'limit') {\n return `Lighter cannot close with a ${closeOrderType} order; use market or limit`;\n }\n if (closeOrderType === 'limit' && !params.price) {\n return 'Limit close requires a price';\n }\n if (\n params.usdAmount !== undefined &&\n parseFinitePositive(params.usdAmount) === null\n ) {\n // Finite REQUIRED: a non-finite usdAmount must never fall back to\n // held-size validation while execution forwards the infinite USD\n // into placement.\n return `Invalid usdAmount ${params.usdAmount}: must be a positive number`;\n }\n // closePosition forwards an explicit size to placement, which rejects\n // non-finite or non-positive values; validation must match.\n if (\n params.usdAmount === undefined &&\n params.size !== undefined &&\n parseFinitePositive(params.size) === null\n ) {\n return 'Order size must be positive';\n }\n return null;\n };\n\n /**\n * Live check whether a below-minimum reduce-only request is actually a\n * full close of the held position (shared by placement and validation).\n *\n * @param symbol - Market symbol.\n * @param requestedSize - Requested base size.\n * @returns True when the live position verifies a full close.\n */\n readonly #isVerifiedFullClose = async (\n symbol: string,\n requestedSize: number,\n ): Promise<boolean> => {\n const positions = await this.getPositions();\n const held = Math.abs(\n parseFloat(\n positions.find((entry) => entry.symbol === symbol)?.size ?? '0',\n ),\n );\n // Exact match (float epsilon only): closePosition forwards the precise\n // live size, and anything less is a deliberate partial that a min-size\n // bump would silently over-close.\n return held > 0 && requestedSize >= held * (1 - 1e-9);\n };\n\n async closePosition(rawParams: ClosePositionParams): Promise<OrderResult> {\n const params = this.#normalizeCloseParams(rawParams);\n try {\n // One intent identity from the position read through the final write:\n // an account switch mid-sequence aborts instead of trading the new\n // account with sizing derived from the old one.\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const closeOrderType = params.orderType ?? 'market';\n const shapeError = this.#validateCloseShape(params);\n if (shapeError) {\n return { success: false, error: shapeError };\n }\n const positions = await this.getPositions();\n this.#assertSession(generationAtIntent);\n const position = positions.find(\n (entry) => entry.symbol === params.symbol,\n );\n if (!position) {\n return {\n success: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n const signedSize = parseFloat(position.size);\n const explicitSizing =\n params.size !== undefined || params.usdAmount !== undefined;\n const closeSize = params.size ?? String(Math.abs(signedSize));\n // Reduce-only order on the opposite side; the caller's full sizing\n // and protection intent (usdAmount, slippage, price snapshot, limit\n // price) rides through the placement path unchanged.\n return await this.placeOrder(\n {\n symbol: params.symbol,\n isBuy: signedSize < 0,\n size: closeSize,\n usdAmount: params.usdAmount,\n orderType: closeOrderType,\n price: params.price,\n reduceOnly: true,\n // Without explicit sizing this is a full close and must never be\n // rejected by the minimum-notional check on a dust position.\n isFullClose: !explicitSizing,\n currentPrice: params.currentPrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n },\n generationAtIntent,\n );\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.closePosition');\n this.#deps.debugLogger.log('[LighterProvider] closePosition failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('closePosition'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async updatePositionTPSL(\n params: UpdatePositionTPSLParams,\n ): Promise<OrderResult> {\n try {\n // Partial TP/SL sizes are NOT wired to this venue path: it always\n // covers the full position. Silently ignoring a requested partial\n // size would close the entire position when the trigger fires, so\n // the request is refused before any read, signer setup or mutation.\n if (\n params.takeProfitSize !== undefined ||\n params.stopLossSize !== undefined\n ) {\n return {\n success: false,\n error:\n 'Lighter TP/SL covers the full position: partial takeProfitSize/stopLossSize are not supported',\n };\n }\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n // The lifecycle boundary is captured BEFORE the position read: a\n // fill landing DURING the read belongs to the operation's window\n // and must count as lifecycle evidence.\n const lifecycleBoundary = Date.now();\n const positions = await this.getPositions();\n const position = positions.find(\n (entry) => entry.symbol === params.symbol,\n );\n if (!position) {\n return {\n success: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n\n // FULL local preflight: construct the entire deterministic\n // replacement payload BEFORE signer setup, the open-orders read and\n // any cancellation. Everything that can fail locally — venue\n // position-size parsing/integerization, trigger/execution price\n // parsing/integerization, bounded client-id allocation — must fail\n // while the existing protection is still in place.\n const wantsReplacement =\n Boolean(params.takeProfitPrice) || Boolean(params.stopLossPrice);\n let singleOrderPayload: LighterCreateOrderWireParams | null = null;\n let groupedOrderPayload: LighterGroupedOrderWireParams | null = null;\n let createdClientIds: number[] = [];\n let createdIdsNeedingFinalCheck: number[] = [];\n let preflightPositionWireSize: number | null = null;\n let preflightPositionSign: 1 | -1 | null = null;\n if (wantsReplacement) {\n // getPositions does not validate venue sizes; a non-finite or\n // sub-tick size must abort here, not after the cancels.\n const signedSize = parseFloat(position.size);\n if (!Number.isFinite(signedSize) || signedSize === 0) {\n return {\n success: false,\n error: `Invalid live position size ${position.size} for ${params.symbol}`,\n };\n }\n const isLong = signedSize > 0;\n const coverSize = Math.abs(signedSize);\n const sizeInt = toSignerWireInteger(\n coverSize,\n market.supportedSizeDecimals,\n );\n preflightPositionWireSize = sizeInt;\n preflightPositionSign = isLong ? 1 : -1;\n // Closing side is opposite the position; trigger market orders\n // execute at a protection price 5% beyond the trigger in the taker\n // direction.\n const isAsk = isLong ? 1 : 0;\n const orderIntents: {\n orderType: number;\n raw: string;\n label: string;\n }[] = [];\n if (params.takeProfitPrice) {\n orderIntents.push({\n orderType: LIGHTER_ORDER_TYPE_TAKE_PROFIT,\n raw: params.takeProfitPrice,\n label: 'takeProfitPrice',\n });\n }\n if (params.stopLossPrice) {\n orderIntents.push({\n orderType: LIGHTER_ORDER_TYPE_STOP_LOSS,\n raw: params.stopLossPrice,\n label: 'stopLossPrice',\n });\n }\n const validatedOrders: {\n orderType: number;\n execInt: number;\n triggerInt: number;\n }[] = [];\n for (const intent of orderIntents) {\n const trigger = parseFinitePositive(intent.raw);\n if (trigger === null) {\n return {\n success: false,\n error: `Invalid ${intent.label} ${intent.raw}: must be a positive number`,\n };\n }\n const execution = isLong ? trigger * 0.95 : trigger * 1.05;\n validatedOrders.push({\n orderType: intent.orderType,\n execInt: toSignerWirePriceInteger(\n execution,\n market.supportedPriceDecimals,\n ),\n triggerInt: toSignerWirePriceInteger(\n trigger,\n market.supportedPriceDecimals,\n ),\n });\n }\n // Only the ids actually required: allocation attempts are bounded\n // and a degenerate RNG must exhaust BEFORE any cancellation.\n const clientOrderIds = this.#allocateClientOrderIndexes(\n validatedOrders.length,\n );\n createdClientIds = clientOrderIds;\n // VENUE CONTRACT (proven live: 'GroupingType is not valid'):\n // CreateGroupedOrders only accepts grouping types 1/2/3 and OCO\n // requires two siblings, so a SINGLE TP or SL must be an ordinary\n // CreateOrder trigger; grouped OCO is reserved for both together.\n const wireOrders = validatedOrders.map(\n (entry, index): LighterCreateOrderWireParams => {\n const clientOrderIndex = clientOrderIds[index];\n if (clientOrderIndex === undefined) {\n throw new Error(\n 'Lighter TP/SL preflight did not allocate a client order id',\n );\n }\n return [\n market.marketId,\n clientOrderIndex,\n String(sizeInt),\n String(entry.execInt),\n isAsk,\n entry.orderType,\n LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n 1,\n String(entry.triggerInt),\n // Trigger orders rest until fired: the signer expands the -1\n // sentinel to the 28-day default expiry.\n LIGHTER_ORDER_EXPIRY_NONE,\n ];\n },\n );\n const [first, second] = wireOrders;\n if (first === undefined) {\n throw new Error('Lighter TP/SL preflight produced no trigger order');\n }\n if (second === undefined) {\n singleOrderPayload = first;\n } else {\n groupedOrderPayload = [...first, ...second];\n }\n }\n\n // Re-fence BEFORE signer setup: the preflight awaited public reads\n // during which the wallet may have switched, and a stale intent must\n // never create or register the new account's venue key.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generationAtIntent);\n // Pre-mint the auth token OUTSIDE the write lock: #getAuthToken can\n // trigger signer setup, and signer setup queues on the write chain —\n // calling any setup-capable helper from inside the held section\n // would self-deadlock after a bridge reset or unobserved switch.\n const authToken = await this.#getAuthToken();\n this.#assertSession(generationAtIntent);\n // Settlement identity: pending expectations are keyed by the\n // captured normalized address + account index + symbol so another\n // account can never consume (or be blocked by) this account's ids,\n // while a same-account bridge reset or switch-away-and-back retains\n // the reconciliation obligation.\n // Includes the API KEY SLOT: nonces are per key slot, so a journal\n // recorded under one slot must never be reconciled under another.\n const settlementKey = `${this.#boundAddress ?? 'unbound'}:${accountIndex}:${this.#apiKeyIndex}:${params.symbol}`;\n\n // The ENTIRE snapshot -> create -> cancel lifecycle runs as ONE\n // serialized transition on the account's write chain. Two concurrent\n // replacements would otherwise both snapshot the same old trigger,\n // each create a new set, and each cancel only the original — leaving\n // both protection sets live; a concurrent remove could miss a\n // just-created replacement. Cancels are INLINED (not this.cancelOrder)\n // so no nested lock acquisition can deadlock; nonce serialization is\n // preserved because every nonce comes from this section's nextNonce.\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n // STRICT direct read with the CAPTURED account/auth/generation:\n // a swallowed [] would make remove \"succeed\" cancelling nothing;\n // a setup-capable helper here could self-deadlock (see auth\n // pre-mint above). Session fences on every read.\n const readActiveRaw = async (): Promise<LighterApiOrder[]> => {\n this.#assertSession(generationAtIntent);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generationAtIntent);\n return response.orders;\n };\n // Shared targeted inactive reader (cached, active-first callers,\n // one bounded deep cursor walk per section, market-scoped).\n const readInactiveFor = this.#makeInactiveReader(\n accountIndex,\n authToken,\n generationAtIntent,\n market.marketId,\n );\n\n // VENUE LINEARIZABILITY: if a previous TP/SL transition's\n // settlement never became visible, run it through the SAME\n // obligation state machine as startup recovery — a pending\n // 'cancelling'/'restoring' journal may owe a rollback or a\n // RESTORE, and merely reconciling-then-clearing it here would\n // erase that obligation and leave the position naked.\n // Pending obligations survive provider death via the durable\n // journal. DISK IS AUTHORITATIVE: absence means the obligation\n // was resolved (possibly by another provider) — a stale\n // in-memory copy is dropped, never resurrected.\n const unsettled = await this.#loadTpslJournal(settlementKey);\n if (unsettled === null) {\n this.#tpslUnsettled.delete(settlementKey);\n }\n if (unsettled) {\n const resolved = await this.#settleTpslObligation({\n settlementKey,\n symbol: params.symbol,\n journalEntry: unsettled,\n market,\n accountIndex,\n authToken,\n generation: generationAtIntent,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n });\n if (!resolved) {\n // Keep both records for the next attempt.\n this.#tpslUnsettled.set(settlementKey, unsettled);\n throw new Error(\n `Lighter TP/SL settlement for ${params.symbol} is unresolved; refusing further protection changes until the venue reflects the previous update`,\n );\n }\n // The machine may have PARKED the obligation into the\n // durable manual-recovery doc (releasing the journal slot).\n // The doc is NOT cleared here: only this operation's own\n // SUCCESS — the successor protection authoritatively in\n // force — clears the warning below.\n this.#assertSession(generationAtIntent);\n }\n\n const rawOrders = await readActiveRaw();\n const openOrders = rawOrders.map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n const staleTriggers = openOrders.filter(\n (order) =>\n order.symbol === params.symbol &&\n order.reduceOnly &&\n (Boolean(order.orderType?.includes('stop')) ||\n Boolean(order.orderType?.includes('take')) ||\n order.isTrigger === true),\n );\n // The prior triggers' EXACT wire intents ride along with the\n // journal: a crash can still restore/rollback faithfully. A\n // stale trigger that CANNOT be faithfully restored (unknown\n // venue type/TIF) refuses the whole mutation BEFORE any cancel\n // or create — coercing its semantics on restore is worse than\n // rejecting the update.\n const priorTriggers: TpslPriorTrigger[] = [];\n for (const stale of staleTriggers) {\n const rawRow = rawOrders.find(\n (order) => String(order.orderIndex) === stale.orderId,\n );\n const priorIntent = rawRow\n ? mapRawTriggerToPriorIntent(rawRow, market)\n : null;\n if (!priorIntent) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: existing trigger order ${stale.orderId} cannot be faithfully restored (unsupported type/time-in-force), so it will not be cancelled`,\n );\n }\n priorTriggers.push(priorIntent);\n }\n // OCO grouping is decided by the VENUE'S OWN linkage fields —\n // never inferred from \"one TP plus one SL\". Linkage FAILS\n // CLOSED: ANY dangling or one-sided linkage (parent, to_cancel\n // or to_trigger references that do not form an exact mutual\n // two-leg pair among the triggers being replaced) is an order\n // relationship this integration cannot faithfully re-establish\n // — the mutation is refused BEFORE anything is touched, never\n // classified independent.\n const staleRawRows = staleTriggers.map((stale) =>\n rawOrders.find(\n (order) => String(order.orderIndex) === stale.orderId,\n ),\n );\n // LIVE-VENUE contract (probed): ABSENT linkage is the string\n // sentinel '0' (parent_order_id, to_trigger_order_id_*), never\n // an empty string.\n const linkageSet = (value: string | undefined): boolean =>\n typeof value === 'string' && value.length > 0 && value !== '0';\n const hasAnyLinkage = (row: LighterApiOrder | undefined): boolean =>\n row !== undefined &&\n (linkageSet(row.toCancelOrderId0) ||\n linkageSet(row.parentOrderId) ||\n (typeof row.parentOrderIndex === 'number' &&\n row.parentOrderIndex > 0) ||\n linkageSet(row.toTriggerOrderId0) ||\n linkageSet(row.toTriggerOrderId1));\n const rowLinksTo = (\n source: LighterApiOrder | undefined,\n target: LighterApiOrder | undefined,\n ): boolean =>\n source !== undefined &&\n target !== undefined &&\n linkageSet(source.toCancelOrderId0) &&\n [String(target.orderIndex), target.orderId ?? ''].includes(\n source.toCancelOrderId0 as string,\n );\n const mutualPair =\n priorTriggers.length === 2 &&\n rowLinksTo(staleRawRows[0], staleRawRows[1]) &&\n rowLinksTo(staleRawRows[1], staleRawRows[0]) &&\n // A mutual pair must not ALSO carry parent/OTO relations.\n staleRawRows.every(\n (row) =>\n row !== undefined &&\n !(\n linkageSet(row.parentOrderId) ||\n (typeof row.parentOrderIndex === 'number' &&\n row.parentOrderIndex > 0) ||\n linkageSet(row.toTriggerOrderId0) ||\n linkageSet(row.toTriggerOrderId1)\n ),\n );\n if (!mutualPair && staleRawRows.some(hasAnyLinkage)) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: an existing trigger carries venue linkage (OCO/OTO/parent) this integration cannot faithfully re-establish, so it will not be cancelled`,\n );\n }\n const priorGrouping: 'oco' | 'independent' = mutualPair\n ? 'oco'\n : 'independent';\n if (priorGrouping === 'oco') {\n // Pinned grouped invariants (same closing side, size AND\n // expiry): a linked pair violating them cannot be faithfully\n // re-signed as one group — refuse BEFORE touching it.\n if (\n priorTriggers[0].side !== priorTriggers[1].side ||\n parseStrictDecimal(priorTriggers[0].remainingSize) !==\n parseStrictDecimal(priorTriggers[1].remainingSize) ||\n priorTriggers[0].orderExpiry !== priorTriggers[1].orderExpiry\n ) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: the existing linked OCO pair cannot be faithfully restored as a group, so it will not be cancelled`,\n );\n }\n }\n // Per-attempt mutation journal, persisted incrementally.\n // RESPONSE-LOSS safety: every attempt is recorded UNKNOWN with\n // its own venue nonce BEFORE submission (the venue may commit\n // even when the response is lost), flips to accepted inside\n // onAccepted (pre-fence), and reconciliation disambiguates each\n // attempt individually via books + nonce.\n const journal: TpslJournalState = {\n attempts: [],\n recordedAt: Date.now(),\n // Collision-resistant across processes: time + counter + two\n // independent random draws (~104 bits of entropy).\n operationId: `op-${Date.now().toString(36)}-${(this.#tpslOperationCounter += 1).toString(36)}-${randomIdSuffix()}`,\n createdAt: lifecycleBoundary,\n nextAttemptId: 1,\n intent: wantsReplacement ? 'replace' : 'remove',\n phase: 'creating',\n priorGrouping,\n priorTriggers,\n };\n const persistJournal = async (): Promise<void> => {\n journal.recordedAt = Date.now();\n await this.#persistTpslJournal(settlementKey, journal);\n };\n // Sign+journal+submit one tracked cancel (stale protection or a\n // rollback of a surviving replacement leg).\n const submitTrackedCancel = async (\n orderId: string,\n role: 'stale' | 'rollback',\n ): Promise<void> => {\n if (role === 'stale' && journal.intent === 'replace') {\n // Durable phase transition BEFORE the old protection is\n // touched: a crash from here on may require a RESTORE.\n // (A 'remove' journal never restores — phase is moot.)\n journal.phase = 'cancelling';\n }\n const cancelNonce = await nextNonce();\n const signedCancel = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, orderId, cancelNonce],\n });\n if (signedCancel.error) {\n throw new Error(\n `Failed to cancel trigger order ${orderId}: ${signedCancel.error}`,\n );\n }\n const cancelIdentity = requireSignedTxIdentity(signedCancel);\n const cancelAttempt: TpslCancelAttempt = {\n kind: 'cancel',\n attemptId: nextAttemptIdFor(journal),\n nonce: cancelNonce,\n outcome: 'unknown',\n orderId,\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n role,\n };\n journal.attempts.push(cancelAttempt);\n this.#tpslUnsettled.set(settlementKey, journal);\n await persistJournal();\n await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signedCancel.txInfo,\n () => {\n cancelAttempt.outcome = 'accepted';\n },\n {\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n owner: journal.operationId,\n },\n );\n };\n\n // CREATE FIRST, cancel after: if signing or submission of the\n // new protection fails, the old triggers were never touched and\n // the position is never left naked. The temporary overlap is\n // safe — both sets are reduce-only and clamp to the position.\n if (\n wantsReplacement &&\n (singleOrderPayload !== null || groupedOrderPayload !== null)\n ) {\n // The public preflight position read occurred before signer\n // setup and write serialization. Re-read the raw venue position\n // inside the held transition immediately before any create or\n // cancel signature: an intervening fill or side flip would make\n // the captured cover payload under-sized or wrong-sided.\n this.#assertSession(generationAtIntent);\n const liveAccount =\n await this.#clientService.getAccountByIndex(accountIndex);\n this.#assertSession(generationAtIntent);\n const livePosition = liveAccount.accounts[0]?.positions?.find(\n (entry) => entry.symbol === params.symbol,\n );\n const liveMagnitude = livePosition\n ? parseStrictDecimal(livePosition.position)\n : null;\n let liveWireSize: number | null = null;\n if (\n liveMagnitude !== null &&\n Number.isFinite(liveMagnitude) &&\n liveMagnitude > 0 &&\n (livePosition?.sign === 1 || livePosition?.sign === -1)\n ) {\n try {\n liveWireSize = toSignerWireInteger(\n liveMagnitude,\n market.supportedSizeDecimals,\n );\n } catch {\n liveWireSize = null;\n }\n }\n if (\n liveWireSize === null ||\n liveWireSize !== preflightPositionWireSize ||\n livePosition?.sign !== preflightPositionSign\n ) {\n throw new Error(\n `Lighter position changed before TP/SL signing for ${params.symbol}; refresh and retry protection against the current position`,\n );\n }\n const createNonce = await nextNonce();\n // A lone trigger is an ordinary CreateOrder (same wire\n // layout); only a TP+SL pair uses the grouped OCO transaction.\n let signed: LighterTxResult;\n let isSingleTrigger = false;\n if (singleOrderPayload === null) {\n if (groupedOrderPayload === null) {\n throw new Error('Lighter TP/SL preflight payload is missing');\n }\n signed = await this.#getSignerBridge().execute({\n function: '_signCreateGroupedOrders',\n params: [\n accountIndex,\n LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER,\n 2,\n ...groupedOrderPayload,\n createNonce,\n ],\n });\n } else {\n isSingleTrigger = true;\n signed = await this.#getSignerBridge().execute({\n function: '_signCreateOrder',\n params: [accountIndex, ...singleOrderPayload, createNonce],\n });\n }\n if (signed.error) {\n throw new Error(signed.error);\n }\n // UNKNOWN recorded BEFORE the wire — in memory AND durably\n // (awaited): a transport failure after venue commit, or\n // provider/process death, must still leave a reconciliation\n // obligation resolvable by EXACT tx hash. A failed durable\n // write, or a signing result without hash/expiry, aborts the\n // mutation before submission.\n const createIdentity = requireSignedTxIdentity(signed);\n const createAttempt: TpslCreateAttempt = {\n kind: 'create',\n attemptId: nextAttemptIdFor(journal),\n nonce: createNonce,\n outcome: 'unknown',\n clientIds: [...createdClientIds],\n txHash: createIdentity.txHash,\n expiresAt: createIdentity.expiresAt,\n role: 'replacement',\n };\n journal.attempts.push(createAttempt);\n this.#tpslUnsettled.set(settlementKey, journal);\n await persistJournal();\n await submit(\n isSingleTrigger\n ? LIGHTER_TX_TYPE_CREATE_ORDER\n : LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS,\n signed.txInfo,\n () => {\n // Acceptance OBSERVED (pre-fence): absence from the books\n // can now only mean visibility lag, never never-landed.\n createAttempt.outcome = 'accepted';\n },\n {\n txHash: createIdentity.txHash,\n expiresAt: createIdentity.expiresAt,\n owner: journal.operationId,\n },\n );\n\n // PHASE BARRIER: prove the replacement is on the venue's books\n // BEFORE touching the old protection. An accepted create can\n // be asynchronously rejected/venue-cancelled; cancelling stale\n // triggers first would strip valid protection and discover it\n // afterwards.\n const createVisibility = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n {\n createdClientIds,\n cancelledOrderIds: [],\n },\n );\n if (createVisibility.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n if (createVisibility.outcome === 'created-terminal-failed') {\n // The replacement (or one OCO leg) failed before the old\n // protection was touched. ROLL BACK any leg still resting\n // active so the venue returns to exactly the prior\n // protection, then resolve the obligation for a retry.\n if (createVisibility.survivingActiveClientIds.length > 0) {\n const activeNow = await readActiveRaw();\n const survivorOrderIds: string[] = [];\n for (const clientId of createVisibility.survivingActiveClientIds) {\n const survivor = activeNow.find(\n (order) =>\n String(order.clientOrderIndex) === String(clientId),\n );\n if (survivor) {\n survivorOrderIds.push(String(survivor.orderIndex));\n await submitTrackedCancel(\n String(survivor.orderIndex),\n 'rollback',\n );\n }\n }\n const rollback = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n { createdClientIds: [], cancelledOrderIds: survivorOrderIds },\n );\n if (rollback.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n }\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n throw new Error(\n `Lighter replacement TP/SL for ${params.symbol} was cancelled or rejected by the venue before becoming active; the existing protection was left untouched`,\n );\n }\n // Barrier-proved TERMINAL success is immutable: skip those ids\n // in the final settlement check (no duplicate high-weight\n // inactive read); active-at-barrier ids are still re-verified\n // there (they can terminal-fail before the cancels settle).\n createdIdsNeedingFinalCheck = createVisibility.executedCreated\n ? []\n : createdClientIds;\n if (createVisibility.executedCreated) {\n // The trigger EXECUTED before activation was observed (an\n // immediate/crossed TP/SL): not a failure — the position may\n // already be closed. Stale triggers below are still cleaned\n // up as reduce-only leftovers.\n this.#deps.debugLogger.log(\n '[LighterProvider] replacement trigger executed immediately',\n { symbol: params.symbol },\n );\n }\n }\n\n for (const order of staleTriggers) {\n await submitTrackedCancel(order.orderId, 'stale');\n }\n\n // Await authoritative visibility of the CANCELS before releasing\n // the lock (created ids were proven at the phase barrier): the\n // next queued transition must never snapshot a stale book.\n if (journal.attempts.length > 0) {\n const settled = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n {\n // Barrier-proved terminal successes are immutable and\n // excluded; active-at-barrier ids are re-verified.\n createdClientIds: createdIdsNeedingFinalCheck,\n cancelledOrderIds: journal.attempts\n .filter(\n (attempt): attempt is TpslCancelAttempt =>\n attempt.kind === 'cancel',\n )\n .map((attempt) => attempt.orderId),\n },\n );\n if (settled.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n if (settled.outcome === 'created-terminal-failed') {\n // Active at the phase barrier but venue-cancelled/rejected\n // AFTER the old protection was already cancelled. The\n // venue exposes no atomic primitive that could prove a\n // re-created trigger attaches to the same position\n // lifecycle, so nothing is auto-restored: the warning\n // parks DURABLY in the manual-recovery doc (surfaced via\n // getPendingManualRecoveries) and any surviving leg is\n // deliberately left as the only remaining protection.\n const rawNow = await readActiveRaw();\n const survivingOrderIds = rawNow\n .filter((order) =>\n journal.attempts.some(\n (attempt) =>\n attempt.kind === 'create' &&\n attempt.clientIds.some(\n (clientId) =>\n String(order.clientOrderIndex) === String(clientId),\n ),\n ),\n )\n .map((order) => String(order.orderIndex));\n await this.#writeTpslManualRecovery({\n settlementKey,\n symbol: params.symbol,\n reason:\n 'Replacement TP/SL order was cancelled or rejected by the venue after the previous protection was already removed',\n priorIntent: journal.intent,\n priorTriggers: journal.priorTriggers,\n survivingOrderIds,\n operationId: journal.operationId,\n recordedAt: Date.now(),\n });\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n this.#assertSession(generationAtIntent);\n throw new Error(\n `Lighter replacement TP/SL for ${params.symbol} was cancelled or rejected by the venue after the previous protection was already removed; the position's protection could NOT be safely re-established automatically — MANUAL re-establishment is required (a new explicit TP/SL update resolves this state)`,\n );\n }\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n // A switch DURING the final journal-clear await must not let\n // stale A protection report success under B.\n this.#assertSession(generationAtIntent);\n }\n // ONLY here — the successor protection intent authoritatively\n // in force (created and settled, or removal completed) — may a\n // parked manual-recovery warning for this symbol be cleared. A\n // failed successor leaves the warning untouched.\n await this.#clearTpslManualRecovery(settlementKey);\n this.#assertSession(generationAtIntent);\n },\n generationAtIntent,\n );\n return { success: true };\n } catch (error) {\n const wrappedError = ensureError(\n error,\n 'LighterProvider.updatePositionTPSL',\n );\n this.#deps.debugLogger.log(\n '[LighterProvider] updatePositionTPSL failed',\n {\n error: String(wrappedError),\n ...this.#getErrorContext('updatePositionTPSL'),\n },\n );\n return { success: false, error: wrappedError.message };\n }\n }\n\n async updateMargin(params: UpdateMarginParams): Promise<MarginResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n // Strict full-string parse: '5USD' must not prefix-parse into\n // signed intent. Signed values are meaningful here (add/remove).\n const amount = parseStrictDecimal(params.amount) ?? Number.NaN;\n if (!Number.isFinite(amount) || amount === 0) {\n return {\n success: false,\n error: 'updateMargin requires a non-zero amount',\n };\n }\n // USDC uses 6 decimals. Integerize BEFORE signer setup so a huge\n // finite amount fails closed with zero bridge calls instead of\n // raw-scaling to an unsafe integer inside signer params.\n const marginAmountInt = toSignerWireInteger(Math.abs(amount), 6);\n // Re-fence before signer setup: the market lookup above awaited, and\n // a stale intent must never initialize the new account's signer.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n // USDC uses 6 decimals; direction 1 adds isolated margin, 0 removes it\n // (types/txtypes/constants.go: RemoveFromIsolatedMargin=0, Add=1).\n await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signUpdateMargin',\n params: [\n accountIndex,\n market.marketId,\n marginAmountInt,\n amount > 0 ? 1 : 0,\n nonce,\n ],\n });\n if (signed.error) {\n throw new Error(signed.error);\n }\n return await submit(\n LIGHTER_TX_TYPE_UPDATE_MARGIN,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `updateMargin:${params.symbol}:${params.amount}`,\n },\n );\n },\n generationAtIntent,\n );\n return { success: true };\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.updateMargin');\n this.#deps.debugLogger.log('[LighterProvider] updateMargin failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('updateMargin'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async withdraw(params: WithdrawParams): Promise<WithdrawResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const amount = parseFinitePositive(params.amount);\n if (amount === null) {\n return { success: false, error: 'withdraw requires a positive amount' };\n }\n // Enforce the advertised route minimum: getWithdrawalRoutes reports\n // minWithdrawUsdc, and signing below it would either burn a nonce on\n // a venue rejection or strand dust.\n const minWithdraw = parseFloat(\n LIGHTER_BRIDGE_CONFIG[this.#isTestnet ? 'testnet' : 'mainnet']\n .minWithdrawUsdc,\n );\n if (amount < minWithdraw) {\n return {\n success: false,\n error: `Withdrawal amount ${params.amount} is below the Lighter minimum of ${minWithdraw} USDC`,\n };\n }\n // USDC uses 6 decimals on zkLighter. Integerize BEFORE signer setup:\n // overflow/sub-tick amounts fail closed with zero bridge calls,\n // matching validateWithdrawal exactly.\n const assetAmount = String(toSignerWireInteger(amount, 6));\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n const result = await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signWithdraw',\n params: [\n accountIndex,\n LIGHTER_USDC_ASSET_INDEX,\n 0,\n assetAmount,\n nonce,\n ],\n });\n if (signed.error) {\n throw new Error(signed.error);\n }\n return await submit(\n LIGHTER_TX_TYPE_WITHDRAW,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `withdraw:${params.amount}`,\n },\n );\n },\n generationAtIntent,\n );\n return { success: true, txHash: result.txHash };\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.withdraw');\n this.#deps.debugLogger.log('[LighterProvider] withdraw failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('withdraw'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n // ============================================================================\n // History Operations (POC: stubbed)\n // ============================================================================\n\n async getOrderFills(\n params?: GetOrderFillsParams,\n _options?: PerpsReadOptions,\n ): Promise<OrderFill[]> {\n return await this.#getOrderFillsForQuery(params);\n }\n\n readonly #getOrderFillsForQuery = async (\n params?: LighterFillQuery,\n ): Promise<OrderFill[]> => {\n const selectedAddress = this.#walletService.getUserAddress().toLowerCase();\n const requestedAddress =\n params?.user?.toLowerCase() ??\n params?.accountId?.split(':').at(-1)?.toLowerCase();\n if (requestedAddress && requestedAddress !== selectedAddress) {\n throw new Error(\n 'Lighter fill history can only query the selected wallet account',\n );\n }\n if (params?.aggregateByTime) {\n throw new Error('Lighter fill history does not support aggregateByTime');\n }\n if (\n params?.startTime !== undefined &&\n params.endTime !== undefined &&\n params.startTime > params.endTime\n ) {\n throw new Error('Lighter fill history startTime must not exceed endTime');\n }\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const token = await this.#getAuthToken();\n const markets = await this.#ensureMarkets();\n const requestedLimit = Math.min(Math.max(params?.limit ?? 50, 1), 100);\n const marketId = params?.symbol\n ? markets.get(params.symbol)?.marketId\n : undefined;\n if (params?.symbol && marketId === undefined) {\n return [];\n }\n const needsPaging =\n params?.startTime !== undefined ||\n params?.endTime !== undefined ||\n params?.symbol !== undefined;\n const pageLimit = needsPaging ? 100 : requestedLimit;\n const fills: OrderFill[] = [];\n let cursor: string | undefined;\n let reachedStartBoundary = false;\n for (let page = 0; page < 100; page += 1) {\n const { trades, nextCursor } = await this.#clientService.getTrades(\n accountIndex,\n token,\n { limit: pageLimit, cursor, marketId },\n );\n this.#assertSession(generation);\n for (const trade of trades) {\n const fill = adaptFillFromLighterTrade(\n trade,\n this.#marketsById.get(trade.marketId)?.symbol ??\n String(trade.marketId),\n accountIndex,\n );\n if (\n (params?.startTime === undefined ||\n fill.timestamp >= params.startTime) &&\n (params?.endTime === undefined || fill.timestamp <= params.endTime)\n ) {\n fills.push(fill);\n }\n if (\n params?.startTime !== undefined &&\n fill.timestamp < params.startTime\n ) {\n reachedStartBoundary = true;\n }\n }\n cursor = nextCursor;\n if (\n fills.length >= requestedLimit ||\n cursor === undefined ||\n trades.length === 0 ||\n reachedStartBoundary\n ) {\n return fills.slice(0, requestedLimit);\n }\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} fill history pagination did not reach the requested boundary`,\n );\n } catch (error) {\n this.#deps.debugLogger.log('[LighterProvider] getOrderFills failed', {\n error: String(error),\n });\n throw error;\n }\n };\n\n async getOrFetchFills(params?: GetOrFetchFillsParams): Promise<OrderFill[]> {\n return await this.#getOrderFillsForQuery(params);\n }\n\n async getHistoricalPortfolio(\n _params?: GetHistoricalPortfolioParams,\n ): Promise<HistoricalPortfolioResult> {\n // Capability-gated: the venue's PnLEntry carries trade, pool, spot, and\n // staking flows; reconstructing account value from the trade flows\n // alone is materially wrong for accounts using the other routes, and\n // no captured payload proves the full-flow semantics. Reporting a\n // plausible number would show false daily history — fail explicitly.\n throw new Error(\n 'Historical portfolio is unavailable for Lighter: account-value reconstruction requires pool/spot/staking flow semantics that are not yet verified against the venue',\n );\n }\n\n async getFunding(\n _params?: GetFundingParams,\n _options?: PerpsReadOptions,\n ): Promise<Funding[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const token = await this.#getAuthToken();\n await this.#ensureMarkets();\n const response = await this.#clientService.getPositionFundings(\n accountIndex,\n token,\n );\n this.#assertSession(generation);\n return response.positionFundings.map((entry) => ({\n symbol:\n this.#marketsById.get(entry.marketId)?.symbol ??\n String(entry.marketId),\n // `change` is the signed USDC funding flow for the account's side.\n amountUsd: entry.change,\n rate: entry.rate,\n timestamp: entry.timestamp * 1000,\n }));\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log('[LighterProvider] getFunding failed', {\n error: String(error),\n });\n return [];\n }\n }\n\n async getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n const l1Address = this.#walletService.getUserAddress();\n const [deposits, withdraws, transfers] = await Promise.all([\n this.#clientService.getDepositHistory(\n accountIndex,\n l1Address,\n authToken,\n ),\n this.#clientService.getWithdrawHistory(accountIndex, authToken),\n this.#clientService.getTransferHistory(accountIndex, authToken),\n ]);\n const updates: RawLedgerUpdate[] = [\n ...(deposits.deposits ?? []).map((entry) => ({\n hash: entry.l1TxHash,\n time: entry.timestamp,\n delta: { type: 'deposit', usdc: entry.amount },\n })),\n ...(withdraws.withdraws ?? []).map((entry) => ({\n hash: entry.l1TxHash,\n time: entry.timestamp,\n delta: { type: 'withdraw', usdc: `-${entry.amount}` },\n })),\n ...(transfers.transfers ?? []).map((entry) => ({\n hash: entry.txHash,\n time: entry.timestamp,\n delta: adaptLighterTransferDelta(entry),\n })),\n ].sort((first, second) => second.time - first.time);\n const { startTime, endTime } = params ?? {};\n this.#assertSession(generation);\n return updates.filter(\n (update) =>\n (startTime === undefined || update.time >= startTime) &&\n (endTime === undefined || update.time <= endTime),\n );\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log(\n '[LighterProvider] getUserNonFundingLedgerUpdates failed',\n { error: String(error) },\n );\n return [];\n }\n }\n\n async getUserHistory(params?: {\n accountId?: CaipAccountId;\n startTime?: number;\n endTime?: number;\n }): Promise<UserHistoryItem[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n const l1Address = this.#walletService.getUserAddress();\n const [deposits, withdraws] = await Promise.all([\n this.#clientService.getDepositHistory(\n accountIndex,\n l1Address,\n authToken,\n ),\n this.#clientService.getWithdrawHistory(accountIndex, authToken),\n ]);\n const toStatus = (venueStatus: string): UserHistoryItem['status'] => {\n if (venueStatus === 'completed') {\n return 'completed';\n }\n return venueStatus === 'failed' ? 'failed' : 'pending';\n };\n const items: UserHistoryItem[] = [\n ...(deposits.deposits ?? []).map((entry) => ({\n id: `deposit-${entry.id}`,\n timestamp: entry.timestamp,\n type: 'deposit' as const,\n amount: entry.amount,\n asset: 'USDC',\n txHash: entry.l1TxHash,\n status: toStatus(entry.status),\n details: { source: 'lighter' },\n })),\n ...(withdraws.withdraws ?? []).map((entry) => ({\n id: `withdrawal-${entry.id}`,\n timestamp: entry.timestamp,\n type: 'withdrawal' as const,\n amount: entry.amount,\n asset: 'USDC',\n txHash: entry.l1TxHash,\n status: toStatus(entry.status),\n details: { source: 'lighter' },\n })),\n ].sort((first, second) => second.timestamp - first.timestamp);\n const { startTime, endTime } = params ?? {};\n this.#assertSession(generation);\n return items.filter(\n (item) =>\n (startTime === undefined || item.timestamp >= startTime) &&\n (endTime === undefined || item.timestamp <= endTime),\n );\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log('[LighterProvider] getUserHistory failed', {\n error: String(error),\n });\n return [];\n }\n }\n\n // ============================================================================\n // Validation (POC: minimal)\n // ============================================================================\n\n async validateDeposit(\n _params: DepositParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n return { isValid: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n\n async validateOrder(\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n // ONE error-to-invalid boundary: a validator RESOLVES, never rejects,\n // whichever awaited venue read fails (markets, margin metadata, fresh\n // price, live positions, data integrity).\n try {\n return await this.#validateOrderChecks(params);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n\n readonly #validateOrderChecks = async (\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }> => {\n if (params.marginMode !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n // Mirrors placeOrder's own rejections so validation never approves an\n // order shape the placement path would refuse.\n if (params.orderType !== 'limit' && params.orderType !== 'market') {\n return { isValid: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n if (params.takeProfitPrice || params.stopLossPrice) {\n return {\n isValid: false,\n error:\n 'Lighter does not support TP/SL attached at placement; place the order, then call updatePositionTPSL',\n };\n }\n if (params.timeInForce === 'ALO') {\n return {\n isValid: false,\n error: 'Lighter placement does not support post-only (ALO) yet',\n };\n }\n if (params.orderType === 'limit' && !params.price) {\n return { isValid: false, error: 'Limit order requires a price' };\n }\n if (params.orderType === 'limit' && params.price !== undefined) {\n // Strict finite parity with placement, LIMIT ONLY: 'Infinity' and\n // prefix-numeric strings ('90000USD') both parse under a bare\n // parseFloat check but placement refuses them. Market placement\n // ignores params.price entirely (fresh venue price), so rejecting\n // it here would fail orders placement accepts.\n if (parseFinitePositive(params.price) === null) {\n return {\n isValid: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n }\n const leverageError = lighterLeverageError(params.leverage);\n if (leverageError) {\n return { isValid: false, error: leverageError };\n }\n let usdAmount: number | undefined;\n if (params.usdAmount !== undefined) {\n const parsedUsd = parseFinitePositive(params.usdAmount);\n if (parsedUsd === null) {\n return {\n isValid: false,\n error: `Invalid usdAmount ${params.usdAmount}: must be a positive number`,\n };\n }\n usdAmount = parsedUsd;\n }\n const hasUsdSizing = usdAmount !== undefined;\n if (!hasUsdSizing && parseFinitePositive(params.size) === null) {\n return { isValid: false, error: 'Order size must be positive' };\n }\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n isValid: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n if (params.leverage !== undefined) {\n // Same authoritative-metadata requirement as placement.\n const maxLeverage = await this.#requireMarketMaxLeverage(params.symbol);\n if (maxLeverage === null) {\n return {\n isValid: false,\n error: `Cannot validate leverage for ${params.symbol}: venue margin metadata unavailable`,\n };\n }\n if (params.leverage > maxLeverage) {\n return {\n isValid: false,\n error: `Invalid leverage ${params.leverage}: exceeds the ${params.symbol} maximum of ${maxLeverage}x`,\n };\n }\n }\n // Reference-price parity with placement: a MARKET order sizes at the\n // FRESH venue price through the SAME resolver (fail-closed missing\n // price, snapshot and slippage intent validation, drift) — the\n // caller's price/currentPrice is never trusted for min-size. A LIMIT\n // order sizes at the caller's (finite-validated) price. The EXECUTION\n // price is derived through the same helper placement signs with, so\n // the wire-range check below inspects the exact signed value.\n let referencePrice: number;\n let executionPrice: number;\n if (params.orderType === 'market') {\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? (params.slippage ?? 0.05)\n : params.maxSlippageBps / 10_000;\n // A validator must RESOLVE to an invalid result, never reject: the\n // fresh-price lookup can throw on REST failure.\n let resolved:\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string };\n try {\n resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n if (resolved.error !== null) {\n return { isValid: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n params.isBuy,\n slippageFraction,\n );\n } else {\n referencePrice = parseFloat(\n params.price ?? String(params.currentPrice ?? 0),\n );\n executionPrice = referencePrice;\n }\n if (referencePrice > 0) {\n // USD-derived sizes snap onto the venue grid (placement parity);\n // explicit size strings stay verbatim.\n const requestedSize =\n usdAmount === undefined\n ? parseFloat(params.size)\n : snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n );\n if (usdAmount === undefined) {\n try {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n fromLighterInteger(\n requestedSizeInt,\n market.supportedSizeDecimals,\n ) !== requestedSize\n ) {\n return {\n isValid: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n const minSize = isLighterMakerOrder(params)\n ? computeLighterMinOrderSize(market, referencePrice)\n : 0;\n if (minSize > 0 && requestedSize < minSize) {\n // EXACTLY the placement rule: only reduce-only orders may bump to\n // the venue minimum, and only when the live position verifies a\n // full close; isFullClose remains an untrusted hint. The live read\n // can THROW (capability gates, venue-data integrity): a validator\n // must resolve to an explicit invalid result, never reject.\n let verifiedFullClose = false;\n if (params.reduceOnly) {\n try {\n verifiedFullClose = await this.#isVerifiedFullClose(\n params.symbol,\n requestedSize,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder')\n .message,\n };\n }\n }\n if (!verifiedFullClose) {\n return {\n isValid: false,\n error: `Order size ${requestedSize} is below the Lighter minimum of ${minSize} ${params.symbol}`,\n };\n }\n }\n // Wire-format parity: placement integerizes size and the\n // slippage-adjusted EXECUTION price; toLighterInteger throws on\n // safe-integer overflow and wire-zero there; surface the identical\n // error here so validation never approves an order the signer path\n // refuses (a safe reference can still overflow after +5%).\n try {\n toSignerWireInteger(requestedSize, market.supportedSizeDecimals);\n toSignerWirePriceInteger(executionPrice, market.supportedPriceDecimals);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n return { isValid: true };\n };\n\n async validateClosePosition(\n params: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n // Same single error-to-invalid boundary as validateOrder.\n try {\n return await this.#validateClosePositionChecks(params);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n }\n\n readonly #validateClosePositionChecks = async (\n rawParams: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }> => {\n const params = this.#normalizeCloseParams(rawParams);\n // Same shape rules the execution path enforces.\n const shapeError = this.#validateCloseShape(params);\n if (shapeError) {\n return { isValid: false, error: shapeError };\n }\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n isValid: false,\n error: `Unknown Lighter market ${params.symbol}`,\n };\n }\n // Live sizing parity with closePosition→placeOrder: a validator that\n // approves a close the execution path rejects is worse than none.\n // Capability and data-integrity errors from the read surface as an\n // explicit invalid result, never an exception or a silent empty.\n let positions: Position[];\n try {\n positions = await this.getPositions();\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n const signedHeld = parseFloat(\n positions.find((entry) => entry.symbol === params.symbol)?.size ?? '0',\n );\n const held = Math.abs(signedHeld);\n if (held === 0) {\n return {\n isValid: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n // Order-type-specific pricing, matching execution exactly: a LIMIT\n // close is sized at the caller's price (which must be a finite\n // positive number — never silently replaced by a live price the\n // execution path would not use); a MARKET close resolves the FRESH\n // venue price through the SAME helper as placement, inheriting its\n // fail-closed missing-price and drift semantics.\n let referencePrice: number;\n let executionPrice: number;\n if ((params.orderType ?? 'market') === 'limit') {\n const parsedLimitPrice = parseFinitePositive(params.price ?? '');\n if (parsedLimitPrice === null) {\n return {\n isValid: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n referencePrice = parsedLimitPrice;\n executionPrice = referencePrice;\n } else {\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? 0.05\n : params.maxSlippageBps / 10_000;\n // Same validator contract as validateOrder: REST failures resolve.\n let resolved:\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string };\n try {\n resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n if (resolved.error !== null) {\n return { isValid: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n // Closing is the opposite side: a SHORT closes with a BUY, whose\n // +slippage protection price is what placement actually signs.\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n signedHeld < 0,\n slippageFraction,\n );\n }\n if (referencePrice > 0) {\n const usdAmount = parseFloat(params.usdAmount ?? '');\n // USD-derived sizes snap onto the venue grid (placement parity);\n // explicit size strings stay verbatim.\n const requestedSize =\n Number.isFinite(usdAmount) && usdAmount > 0\n ? snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n )\n : parseFloat(params.size ?? String(held));\n const hasExplicitSize =\n params.usdAmount === undefined && params.size !== undefined;\n // Wire-format parity with the placement path closePosition uses:\n // the EXECUTION price is what gets integerized and signed.\n try {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n hasExplicitSize &&\n fromLighterInteger(requestedSizeInt, market.supportedSizeDecimals) !==\n requestedSize\n ) {\n return {\n isValid: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n toSignerWirePriceInteger(executionPrice, market.supportedPriceDecimals);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n }\n return { isValid: true };\n };\n\n async validateWithdrawal(\n params: WithdrawParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n const amount = parseFinitePositive(params.amount ?? '');\n if (amount === null) {\n return { isValid: false, error: 'Withdrawal amount must be positive' };\n }\n // Advertised route-minimum parity with withdraw.\n const minWithdraw = parseFloat(\n LIGHTER_BRIDGE_CONFIG[this.#isTestnet ? 'testnet' : 'mainnet']\n .minWithdrawUsdc,\n );\n if (amount < minWithdraw) {\n return {\n isValid: false,\n error: `Withdrawal amount ${params.amount} is below the Lighter minimum of ${minWithdraw} USDC`,\n };\n }\n // Scaled wire-range parity with withdraw's own integerization.\n try {\n toSignerWireInteger(amount, 6);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateWithdrawal').message,\n };\n }\n return { isValid: true };\n }\n\n // ============================================================================\n // Calculations (POC: coarse)\n // ============================================================================\n\n async calculateLiquidationPrice(\n params: LiquidationPriceParams,\n ): Promise<string> {\n // Cross liquidation is account-wide and cannot be derived truthfully\n // from this per-position input. Live positions carry the venue's\n // authoritative liquidationPrice; previews support isolated only.\n if (params.marginType === 'cross') {\n throw new Error(\n 'Lighter cross-margin liquidation previews require account-wide collateral and position inputs that are unavailable',\n );\n }\n const { entryPrice, leverage, direction } = params;\n if (\n !isFinite(entryPrice) ||\n !isFinite(leverage) ||\n entryPrice <= 0 ||\n leverage <= 0\n ) {\n return '0.00';\n }\n const maintenanceFraction = await this.calculateMaintenanceMargin({\n asset: params.asset ?? '',\n });\n const initialMargin = 1 / leverage;\n if (initialMargin <= maintenanceFraction) {\n throw new Error(\n `Invalid leverage: ${leverage}x cannot cover the ${maintenanceFraction * 100}% maintenance requirement`,\n );\n }\n const side = direction === 'long' ? 1 : -1;\n const marginAvailable = initialMargin - maintenanceFraction;\n const denominator = 1 - maintenanceFraction * side;\n if (Math.abs(denominator) < 0.0001) {\n return String(entryPrice);\n }\n const liquidationPrice =\n entryPrice - (side * marginAvailable * entryPrice) / denominator;\n return String(Math.max(0, liquidationPrice));\n }\n\n async calculateMaintenanceMargin(\n params: MaintenanceMarginParams,\n ): Promise<number> {\n // The venue publishes per-market maintenance margin fractions\n // (hundredths of a percent, e.g. 240 = 2.4%) in orderBookDetails.\n await this.#ensureMarketMargins();\n const maintenance = this.#marginBySymbol.get(params.asset)?.maintenance;\n if (maintenance && maintenance > 0) {\n return maintenance / 10_000;\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} maintenance margin metadata unavailable for ${params.asset || 'unknown market'}`,\n );\n }\n\n /**\n * Margin mode the venue will accept for a leverage update on this\n * market: an existing position's current mode (the venue refuses mode\n * changes while a position is open; a missing field means the venue\n * default, cross), otherwise ISOLATED — the only mode the app manages.\n *\n * @param symbol - Market symbol.\n * @returns The wire margin mode for UpdateLeverage.\n */\n readonly #resolveMarginModeForSymbol = async (\n symbol: string,\n ): Promise<number> => {\n try {\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n const row = response.accounts?.[0]?.positions?.find(\n (position) =>\n position.symbol === symbol && parseFloat(position.position) !== 0,\n );\n if (row) {\n return row.marginMode ?? LIGHTER_MARGIN_MODE_CROSS;\n }\n } catch {\n // Fall through: prefer isolated; a wrong guess surfaces as an\n // explicit venue rejection of the leverage update, never as state.\n }\n return LIGHTER_MARGIN_MODE_ISOLATED;\n };\n\n /** Per-market margin fractions + last price from orderBookDetails. */\n readonly #marginBySymbol = new Map<string, LighterMarginMetadata>();\n\n /**\n * Synchronous per-market max leverage from the authoritative margin cache.\n *\n * Inactive markets cannot increase exposure. When Lighter has retired their\n * risk metadata, the position's current leverage is therefore the highest\n * leverage that can be reported without inventing a tradable venue limit.\n *\n * @param position - Position carrying the market id and current margin.\n * @returns Max leverage for the market.\n * @throws If the market identity or margin metadata is unavailable.\n */\n readonly #maxLeverageForPosition = (\n position: Pick<LighterApiPosition, 'marketId' | 'initialMarginFraction'>,\n ): number => {\n const { marketId } = position;\n const symbol = this.#marketsById.get(marketId)?.symbol;\n const metadata =\n (symbol ? this.#marginBySymbol.get(symbol) : undefined) ??\n [...this.#marginBySymbol.values()].find(\n (entry) => entry.marketId === marketId,\n );\n if (metadata) {\n return deriveLighterMaxLeverage(metadata.minInitial, marketId);\n }\n if (this.#marketsById.get(marketId)?.status === 'inactive') {\n const marginFraction = parseStrictDecimal(position.initialMarginFraction);\n const currentLeverage =\n marginFraction !== null && marginFraction > 0\n ? Math.round(100 / marginFraction)\n : 0;\n if (Number.isSafeInteger(currentLeverage) && currentLeverage > 0) {\n return currentLeverage;\n }\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} margin metadata unavailable for market ${marketId}`,\n );\n };\n\n /**\n * Authoritative per-market max leverage for trading validation. This returns\n * null when venue metadata is missing or unreadable so placement can return\n * its validation result instead of throwing.\n *\n * @param symbol - Market symbol.\n * @returns The published max leverage, or null when unavailable.\n */\n readonly #requireMarketMaxLeverage = async (\n symbol: string,\n ): Promise<number | null> => {\n try {\n await this.#ensureMarketMargins();\n } catch {\n return null;\n }\n const metadata = this.#marginBySymbol.get(symbol);\n if (!metadata) {\n return null;\n }\n try {\n return deriveLighterMaxLeverage(metadata.minInitial, symbol);\n } catch {\n return null;\n }\n };\n\n /** When the margin-metadata cache was last refreshed (0 = never). */\n #marginFetchedAt = 0;\n\n /** In-flight authoritative margin refresh, shared by the stale epoch. */\n #marginRefreshInFlight: Promise<void> | null = null;\n\n readonly #ensureMarketMargins = async (): Promise<void> => {\n // TTL refresh: metadata cached once for the whole session would keep\n // validating leverage against a stale (possibly higher) max. On\n // expiry the fetch re-runs; if it fails, the throw propagates and\n // every authoritative risk caller fails closed until a later retry.\n if (\n this.#marginBySymbol.size > 0 &&\n Date.now() - this.#marginFetchedAt < LIGHTER_MARGIN_METADATA_TTL_MS\n ) {\n return;\n }\n // ONE authoritative request per stale epoch: overlapping independent\n // fetches can resolve out of order, letting a DELAYED older payload\n // overwrite a fresher cap for a full TTL. A rejection propagates to\n // every waiter of this epoch (fail closed) and clears the in-flight\n // slot in finally so a later call can retry.\n if (!this.#marginRefreshInFlight) {\n this.#marginRefreshInFlight = (async (): Promise<void> => {\n try {\n const details = await this.#clientService.getOrderBookDetails();\n if (this.#isDisconnected) {\n return;\n }\n // Atomic replacement: set()-ing into the old map would let a\n // symbol REMOVED from fresh metadata keep its stale cap forever.\n // The timestamp only advances on success.\n const fresh = new Map<string, LighterMarginMetadata>();\n for (const detail of details.orderBookDetails) {\n if (isInactiveMarketWithoutUsableRiskMetadata(detail)) {\n continue;\n }\n if (detail.minInitialMarginFraction !== undefined) {\n deriveLighterMaxLeverage(\n detail.minInitialMarginFraction,\n detail.symbol,\n );\n }\n if (\n detail.maintenanceMarginFraction !== undefined &&\n (!Number.isSafeInteger(detail.maintenanceMarginFraction) ||\n detail.maintenanceMarginFraction < 1 ||\n detail.maintenanceMarginFraction > 10_000)\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid maintenance margin fraction for market ${detail.symbol}`,\n );\n }\n fresh.set(detail.symbol, {\n marketId: detail.marketId,\n minInitial: detail.minInitialMarginFraction,\n maintenance: detail.maintenanceMarginFraction,\n lastTradePrice: detail.lastTradePrice,\n });\n }\n this.#marginBySymbol.clear();\n for (const [symbol, entry] of fresh) {\n this.#marginBySymbol.set(symbol, entry);\n }\n this.#marginFetchedAt = Date.now();\n } finally {\n this.#marginRefreshInFlight = null;\n }\n })();\n }\n await this.#marginRefreshInFlight;\n };\n\n async getMaxLeverage(asset: string): Promise<number> {\n // The venue publishes per-market minimum initial margin fractions\n // (hundredths of a percent): 400 → 25x. Missing metadata is unavailable,\n // never evidence that the global maximum applies to this market.\n await this.#ensureMarketMargins();\n const metadata = this.#marginBySymbol.get(asset);\n if (metadata) {\n return deriveLighterMaxLeverage(metadata.minInitial, asset);\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} margin metadata unavailable for ${asset}`,\n );\n }\n\n async calculateFees(\n params: FeeCalculationParams,\n ): Promise<FeeCalculationResult> {\n // The market metadata's zero fee is only true for Standard accounts —\n // resolve and gate the account tier first so a Premium account can\n // never be quoted a false zero (throws for Premium/unverified).\n await this.#ensureAccountIndex();\n // Sourced from the venue's own per-market metadata rather than assumed:\n // Lighter standard accounts currently report 0 maker/taker fees.\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n const feeRate = parseFloat(\n (params.isMaker ? market?.makerFee : market?.takerFee) ?? '0',\n );\n const amount = parseFloat(params.amount ?? '0');\n return {\n feeRate,\n feeAmount: Number.isFinite(amount) ? amount * feeRate : 0,\n protocolFeeRate: feeRate,\n metamaskFeeRate: 0,\n };\n }\n\n async previewPositionModify(\n _params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult> {\n return { status: 'unsupported', reason: 'provider' };\n }\n\n // ============================================================================\n // Live subscriptions over Lighter WebSocket channels, with REST polling\n // only as the price-stream fallback when no WebSocket transport exists.\n // ============================================================================\n\n subscribeToPrices(params: SubscribePricesParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#priceSubscribers.add(params);\n if (this.#lastPriceBySymbol.size > 0) {\n this.#deliverPrices(params, [...this.#lastPriceBySymbol.values()]);\n }\n this.#requestChannel('market_stats/all');\n this.#ensureStream();\n return () => {\n this.#priceSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOICaps(params: SubscribeOICapsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#oiCapSubscribers.add(params);\n this.#requestChannel('market_stats/all');\n this.#ensureStream();\n return () => {\n this.#oiCapSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToAccount(params: SubscribeAccountParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#accountSubscribers.add(params);\n this.#ensureAccountChannels();\n return () => {\n this.#accountSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToPositions(params: SubscribePositionsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#positionSubscribers.add(params);\n if (this.#wsPositions.size > 0) {\n params.callback([...this.#wsPositions.values()]);\n }\n this.#ensureAccountChannels();\n return () => {\n this.#positionSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOrders(params: SubscribeOrdersParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#orderSubscribers.add(params);\n if (this.#wsOrders.size > 0) {\n params.callback([...this.#wsOrders.values()]);\n }\n this.#ensureAccountChannels();\n return () => {\n this.#orderSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#fillSubscribers.add(params);\n this.#ensureAccountChannels();\n return () => {\n this.#fillSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n // ============================================================================\n // Shared WebSocket stream manager (market_stats / user_stats /\n // account_all_positions / account_all_orders), REST polling fallback for\n // prices when no WebSocket implementation is available.\n // ============================================================================\n\n /**\n * Resolve the Lighter account index and request the account-scoped\n * channels. When the venue definitively reports no Lighter account,\n * account-scoped subscribers receive an empty emission.\n */\n readonly #ensureAccountChannels = (): void => {\n if (this.#isDisconnected) {\n return;\n }\n if (this.#accountChannelsPromise) {\n this.#ensureStream();\n return;\n }\n const generation = this.#sessionGeneration;\n let channelsRequested = false;\n const setupPromise = (async (): Promise<void> => {\n try {\n // Warm the margin cache before any WS position frame is adapted.\n await this.#ensureMarketMargins().catch(() => undefined);\n const accountIndex = await this.#ensureAccountIndex();\n // Address-aware: an EXTERNAL switch during the lookup (with no other\n // provider call to advance the generation) must also stop these\n // channels from being requested for the old account. The rebind\n // inside the binding call triggers its own rebuild for the new one.\n // Fails closed when no wallet account is bound — a configured\n // account index alone must never subscribe user channels.\n this.#assertSession(generation);\n this.#requestChannel(`user_stats/${accountIndex}`);\n this.#requestChannel(`account_all_positions/${accountIndex}`);\n this.#requestChannel(`account_all_trades/${accountIndex}`);\n channelsRequested = true;\n try {\n const auth = await this.#getAuthToken();\n this.#assertSession(generation);\n this.#requestChannel(`account_all_orders/${accountIndex}`, auth);\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] orders channel skipped (no auth token)',\n { error: String(error) },\n );\n // Setup failures are not authoritative empty order state. Account\n // switches and deselection already emit their synchronous reset.\n channelsRequested = false;\n }\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] account channels unavailable',\n { error: String(error) },\n );\n // A venue-confirmed absent account is authoritative empty state for\n // this exact wallet binding. It must settle initial subscribers so\n // clients do not render loading skeletons forever. All other failures\n // preserve the last snapshot: transport, malformed data, auth and\n // capability errors cannot prove that the account is empty.\n this.#ensureSessionBinding();\n if (\n error instanceof LighterAccountNotFoundError &&\n generation === this.#sessionGeneration\n ) {\n this.#emitAccountBindingReset();\n }\n // An aborted previous-account setup has no authority over the new\n // session. Current-session failures also preserve the last known data.\n // Transport, auth, capability, and integrity failures are not\n // authoritative empty account state. Explicit account switches and\n // deselection already emit their synchronous reset.\n }\n })();\n this.#accountChannelsPromise = setupPromise;\n // A setup that never requested channels (no wallet account yet, or an\n // aborted switch) must not satisfy future ensure calls — clear it so\n // the next bind retries, without clobbering a newer session's promise.\n setupPromise\n .then(() => {\n if (\n !channelsRequested &&\n this.#accountChannelsPromise === setupPromise\n ) {\n this.#accountChannelsPromise = null;\n }\n return undefined;\n })\n .catch(() => undefined);\n this.#ensureStream();\n };\n\n readonly #hasAnySubscriber = (): boolean => {\n return (\n this.#priceSubscribers.size > 0 ||\n this.#oiCapSubscribers.size > 0 ||\n this.#accountSubscribers.size > 0 ||\n this.#positionSubscribers.size > 0 ||\n this.#orderSubscribers.size > 0 ||\n this.#fillSubscribers.size > 0 ||\n [...this.#orderBookSubscribers.values()].some(\n (subscribers) => subscribers.size > 0,\n ) ||\n [...this.#candleSubscribers.values()].some(\n (subscribers) => subscribers.size > 0,\n )\n );\n };\n\n readonly #requestChannel = (channel: string, auth?: string): void => {\n if (this.#isDisconnected) {\n return;\n }\n if (this.#wsWantedChannels.has(channel)) {\n return;\n }\n this.#wsWantedChannels.set(channel, { auth });\n if (this.#priceWs && this.#priceWs.readyState === 1) {\n this.#sendSubscribe(channel, auth);\n }\n };\n\n readonly #sendSubscribe = (channel: string, auth?: string): void => {\n this.#priceWs?.send(\n JSON.stringify(\n auth\n ? { type: 'subscribe', channel, auth }\n : { type: 'subscribe', channel },\n ),\n );\n };\n\n readonly #releaseChannelIfUnused = (): void => {\n if (!this.#hasAnySubscriber()) {\n this.#teardownStream();\n }\n };\n\n readonly #ensureStream = (): void => {\n if (this.#isDisconnected || this.#priceWs || this.#pricePollTimer) {\n return;\n }\n if (this.#webSocketCtor) {\n this.#connectWs();\n } else {\n this.#startPricePolling();\n }\n };\n\n readonly #connectWs = (): void => {\n if (this.#isDisconnected || !this.#webSocketCtor) {\n return;\n }\n const url = getLighterWsEndpoint(this.#isTestnet ? 'testnet' : 'mainnet');\n const WebSocketCtor = this.#webSocketCtor;\n const ws = new WebSocketCtor(url);\n this.#priceWs = ws;\n this.#setConnectionState(WebSocketConnectionState.Connecting);\n\n ws.onopen = (): void => {\n if (this.#isDisconnected) {\n try {\n ws.close();\n } catch {\n // The transport may already have closed during disconnect.\n }\n return;\n }\n // Observe any external switch first, then drop if this socket was\n // replaced (by that rebind or an earlier one).\n this.#ensureSessionBinding();\n if (this.#priceWs !== ws) {\n return;\n }\n const generationAtOpen = this.#sessionGeneration;\n this.#wsReconnectAttempts = 0;\n this.#setConnectionState(WebSocketConnectionState.Connected);\n for (const [channel, meta] of this.#wsWantedChannels) {\n if (meta.auth) {\n // Auth tokens are short-lived; a reconnect after the deadline must\n // re-mint instead of replaying the token captured at subscribe\n // time. #getAuthToken reuses the cached token while it is fresh.\n this.#getAuthToken()\n .then((freshToken) => {\n // The async continuation may resolve after an account switch\n // replaced the socket or the channel set: never reinsert a\n // stale channel or pair it with the new session's token.\n if (\n this.#priceWs !== ws ||\n generationAtOpen !== this.#sessionGeneration ||\n !this.#wsWantedChannels.has(channel)\n ) {\n return undefined;\n }\n this.#wsWantedChannels.set(channel, { auth: freshToken });\n this.#sendSubscribe(channel, freshToken);\n return undefined;\n })\n .catch((error) => {\n this.#deps.debugLogger.log(\n '[LighterProvider] auth channel resubscribe failed',\n { channel, error: String(error) },\n );\n });\n } else {\n this.#sendSubscribe(channel, meta.auth);\n }\n }\n // The server closes idle sockets; any frame under 2 minutes keeps it up.\n // Unconditional replacement: `??=` would keep a timer bound to a dead\n // socket when a new one opens before the old socket's onclose fired.\n this.#clearKeepalive();\n this.#wsKeepaliveTimer = setInterval(() => {\n try {\n ws.send(JSON.stringify({ type: 'ping' }));\n } catch {\n // Socket closing; onclose handles recovery.\n }\n }, 60_000);\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream connected (ws)',\n { url, channels: [...this.#wsWantedChannels.keys()] },\n );\n };\n\n ws.onmessage = (event: { data: unknown }): void => {\n try {\n if (this.#isDisconnected) {\n return;\n }\n // Re-run the live binding first: an EXTERNAL account switch that no\n // provider call has observed yet must tear this socket down (the\n // rebind replaces it) before any frame routes into current UI.\n this.#ensureSessionBinding();\n // Frames from a socket that was replaced (account rebind, reconnect)\n // must never reach the router — they carry the previous session's data.\n if (this.#priceWs !== ws) {\n return;\n }\n this.#handleWsMessage(String(event.data));\n } catch (error) {\n // WebSocket callbacks run on the host event loop. Venue-data\n // integrity failures (and any other malformed frame failure) must\n // drop the whole frame rather than throw globally or emit partial\n // account/position state.\n this.#deps.debugLogger.log(\n '[LighterProvider] dropped malformed WebSocket frame',\n { error: String(error) },\n );\n }\n };\n\n ws.onclose = (): void => {\n if (this.#priceWs !== ws) {\n return;\n }\n this.#priceWs = null;\n this.#clearKeepalive();\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n if (this.#hasAnySubscriber()) {\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream closed; reconnecting in 5s',\n );\n this.#wsReconnectAttempts += 1;\n this.#wsReconnectTimer = setTimeout((): void => {\n this.#wsReconnectTimer = null;\n this.#ensureStream();\n }, 5_000);\n }\n };\n\n ws.onerror = (): void => {\n this.#deps.debugLogger.log('[LighterProvider] price stream ws error');\n };\n };\n\n readonly #handleWsMessage = (raw: string): void => {\n let message: LighterWsMarketStatsMessage & LighterWsAccountMessage;\n try {\n message = convertKeysToCamelCase(JSON.parse(raw)) as typeof message;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream message parse failed',\n { error: String(error) },\n );\n return;\n }\n const type = message.type ?? '';\n if (type.includes('market_stats') && message.marketStats) {\n const timestamp = message.timestamp ?? Date.now();\n const updates = Object.values(message.marketStats).map((stat) =>\n adaptPriceUpdateFromLighterWsStat(stat, timestamp),\n );\n this.#dispatchPriceUpdates(updates);\n this.#dispatchOICaps(Object.values(message.marketStats));\n return;\n }\n if (type.includes('user_stats') && message.stats) {\n const accountState = adaptAccountStateFromLighterUserStats(message.stats);\n for (const subscriber of this.#accountSubscribers) {\n try {\n subscriber.callback(accountState);\n } catch (error) {\n this.#logSubscriberError('account', error);\n }\n }\n return;\n }\n if (type.includes('account_all_positions') && message.positions) {\n const isSnapshot = type.startsWith('subscribed');\n const nextPositions = isSnapshot\n ? new Map<number, Position>()\n : new Map(this.#wsPositions);\n for (const [marketId, position] of Object.entries(message.positions)) {\n const adapted = adaptPositionFromLighter(\n position,\n this.#maxLeverageForPosition(position),\n );\n if (parseFloat(adapted.size) === 0) {\n nextPositions.delete(Number(marketId));\n } else {\n nextPositions.set(Number(marketId), adapted);\n }\n }\n this.#wsPositions.clear();\n for (const [marketId, position] of nextPositions) {\n this.#wsPositions.set(marketId, position);\n }\n const positions = [...this.#wsPositions.values()];\n for (const subscriber of this.#positionSubscribers) {\n try {\n subscriber.callback(positions);\n } catch (error) {\n this.#logSubscriberError('positions', error);\n }\n }\n return;\n }\n if (type.includes('order_book')) {\n this.#handleOrderBookMessage(type, message as LighterWsOrderBookMessage);\n return;\n }\n if (type.includes('candle')) {\n this.#handleCandleMessage(message as LighterWsCandleMessage);\n return;\n }\n if (type.includes('account_all_trades')) {\n this.#handleTradesMessage(message as LighterWsTradesMessage);\n return;\n }\n if (type.includes('account_all_orders') && message.orders) {\n const isSnapshot = type.startsWith('subscribed');\n const nextOrders = isSnapshot\n ? new Map<string, Order>()\n : new Map(this.#wsOrders);\n for (const marketOrders of Object.values(message.orders)) {\n for (const order of marketOrders) {\n const adapted = adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n );\n const isOpen =\n adapted.status === 'queued' || adapted.status === 'open';\n if (isOpen) {\n nextOrders.set(adapted.orderId, adapted);\n } else {\n nextOrders.delete(adapted.orderId);\n }\n }\n }\n this.#wsOrders.clear();\n for (const [orderId, order] of nextOrders) {\n this.#wsOrders.set(orderId, order);\n }\n this.#emitToOrderSubscribers([...this.#wsOrders.values()]);\n }\n };\n\n /**\n * Apply an order_book snapshot/delta and fan the assembled book out.\n *\n * @param type - Message type (subscribed = full snapshot, update = delta).\n * @param message - Camelized order_book payload.\n */\n readonly #handleOrderBookMessage = (\n type: string,\n message: LighterWsOrderBookMessage,\n ): void => {\n const channel = message.channel ?? '';\n const marketId = Number(channel.split(':')[1] ?? Number.NaN);\n if (!Number.isFinite(marketId) || !message.orderBook) {\n return;\n }\n const { nonce, beginNonce } = message.orderBook;\n if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce)) {\n return;\n }\n const currentState = this.#orderBookState.get(marketId);\n let nextState: LighterOrderBookState;\n if (type.startsWith('subscribed')) {\n nextState = { bids: new Map(), asks: new Map(), nonce };\n } else if (\n !currentState ||\n typeof beginNonce !== 'number' ||\n !Number.isSafeInteger(beginNonce) ||\n beginNonce !== currentState.nonce\n ) {\n // A delta cannot be applied to an unknown or discontinuous base.\n // Drop the local book and request a new subscribed snapshot.\n this.#orderBookState.delete(marketId);\n const channelName = `order_book/${marketId}`;\n if (this.#priceWs?.readyState === 1) {\n this.#priceWs.send(\n JSON.stringify({ type: 'unsubscribe', channel: channelName }),\n );\n this.#sendSubscribe(channelName);\n }\n return;\n } else {\n nextState = {\n bids: new Map(currentState.bids),\n asks: new Map(currentState.asks),\n nonce: currentState.nonce,\n };\n }\n for (const side of ['bids', 'asks'] as const) {\n for (const level of message.orderBook[side] ?? []) {\n const price = parseStrictDecimal(level?.price);\n const size = parseStrictDecimal(level?.size);\n if (\n price === null ||\n !Number.isFinite(price) ||\n price <= 0 ||\n size === null ||\n !Number.isFinite(size) ||\n size < 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} malformed order-book level`,\n );\n }\n if (size === 0) {\n nextState[side].delete(level.price);\n } else {\n nextState[side].set(level.price, level.size);\n }\n }\n }\n nextState.nonce = nonce;\n this.#orderBookState.set(marketId, nextState);\n const subscribers = this.#orderBookSubscribers.get(marketId);\n if (!subscribers || subscribers.size === 0) {\n return;\n }\n // Levels must carry the FULL OrderBookLevel contract. The depth chart\n // draws Y-coordinates from parseFloat(level.total): a bare {price, size}\n // level renders as an SVG path full of NaN and crashes the native path\n // parser (found live on device, RNSVGPathParser InvalidNumber).\n const toContractLevels = (\n entries: [string, string][],\n ): OrderBookLevel[] => {\n let cumulativeSize = 0;\n let cumulativeNotional = 0;\n return entries.map(([price, size]) => {\n const sizeNum = Number(size);\n const notional = Number(price) * sizeNum;\n cumulativeSize += sizeNum;\n cumulativeNotional += notional;\n return {\n price,\n size,\n total: String(cumulativeSize),\n notional: String(notional),\n totalNotional: String(cumulativeNotional),\n };\n });\n };\n for (const subscriber of subscribers) {\n const levels = subscriber.levels ?? 10;\n const bids = toContractLevels(\n [...nextState.bids.entries()]\n .sort((a, b) => Number(b[0]) - Number(a[0]))\n .slice(0, levels),\n );\n const asks = toContractLevels(\n [...nextState.asks.entries()]\n .sort((a, b) => Number(a[0]) - Number(b[0]))\n .slice(0, levels),\n );\n const bestBid = Number(bids[0]?.price ?? '0');\n const bestAsk = Number(asks[0]?.price ?? '0');\n const mid = bestBid > 0 && bestAsk > 0 ? (bestBid + bestAsk) / 2 : 0;\n const maxTotal = Math.max(\n Number(bids[bids.length - 1]?.total ?? '0'),\n Number(asks[asks.length - 1]?.total ?? '0'),\n );\n const book: OrderBookData = {\n bids,\n asks,\n spread: String(bestAsk - bestBid),\n spreadPercentage:\n mid > 0 ? String(((bestAsk - bestBid) / mid) * 100) : '0',\n midPrice: String(mid),\n lastUpdated: Date.now(),\n maxTotal: String(maxTotal),\n };\n try {\n subscriber.callback(book);\n } catch (error) {\n this.#logSubscriberError('orderBook', error);\n }\n }\n };\n\n /**\n * Merge live candle updates into the cached series and fan out.\n *\n * @param message - Camelized candle payload.\n */\n readonly #handleCandleMessage = (message: LighterWsCandleMessage): void => {\n const channel = message.channel ?? '';\n const [, marketIdRaw, resolution] = channel.split(':');\n const key = `${marketIdRaw}:${resolution}`;\n const series = this.#candleSeries.get(key);\n const subscribers = this.#candleSubscribers.get(key);\n if (!series || !subscribers || subscribers.size === 0) {\n return;\n }\n for (const candle of message.candles ?? []) {\n const mapped = toFiniteCandle(candle);\n if (mapped) {\n series.set(mapped.time, mapped);\n }\n }\n const candles = [...series.values()].sort((a, b) => a.time - b.time);\n for (const subscriber of subscribers) {\n try {\n subscriber.callback({\n symbol: subscriber.symbol,\n interval: subscriber.interval,\n candles,\n });\n } catch (error) {\n this.#logSubscriberError('candles', error);\n }\n }\n };\n\n /**\n * Adapt live account trades into OrderFill emissions.\n *\n * @param message - Camelized account_all_trades payload.\n */\n readonly #handleTradesMessage = (message: LighterWsTradesMessage): void => {\n if (this.#fillSubscribers.size === 0) {\n return;\n }\n const isSnapshot = (message.type ?? '').startsWith('subscribed');\n const fills: OrderFill[] = [];\n let droppedUnsupportedFill = false;\n for (const marketTrades of Object.values(message.trades ?? {})) {\n for (const trade of marketTrades) {\n const symbol =\n this.#marketsById.get(trade.marketId)?.symbol ??\n String(trade.marketId);\n // One adapter serves REST history and the live stream so pnl,\n // fees, and direction vocabulary can never diverge between them.\n // A capability-refused fill (unverified nonzero fee) must never be\n // rendered with a false zero fee, nor crash the event handler.\n try {\n fills.push(\n adaptFillFromLighterTrade(trade, symbol, this.#accountIndex ?? -1),\n );\n } catch (error) {\n droppedUnsupportedFill = true;\n this.#deps.debugLogger.log(\n '[LighterProvider] dropped unsupported fill from stream',\n { tradeId: trade.tradeId, error: String(error) },\n );\n }\n }\n }\n if (fills.length === 0 && !isSnapshot) {\n return;\n }\n // A snapshot that lost fills to a capability refusal is PARTIAL:\n // emitting it would overwrite valid cached history with false\n // emptiness. Preserve what subscribers already have; REST reads\n // surface the capability error explicitly.\n if (isSnapshot && droppedUnsupportedFill) {\n this.#deps.debugLogger.log(\n '[LighterProvider] withholding partial fills snapshot (unsupported fills present)',\n );\n return;\n }\n for (const subscriber of this.#fillSubscribers) {\n try {\n subscriber.callback(fills, isSnapshot);\n } catch (error) {\n this.#logSubscriberError('fills', error);\n }\n }\n };\n\n readonly #dispatchOICaps = (stats: LighterWsMarketStat[]): void => {\n if (this.#oiCapSubscribers.size === 0) {\n return;\n }\n const capped = stats\n .filter((stat) => {\n const openInterest = parseFloat(stat.openInterest ?? '0');\n const limit = parseFloat(\n (stat as { openInterestLimit?: string }).openInterestLimit ?? '0',\n );\n return limit > 0 && openInterest >= limit;\n })\n .map((stat) => stat.symbol);\n for (const subscriber of this.#oiCapSubscribers) {\n try {\n subscriber.callback(capped);\n } catch (error) {\n this.#logSubscriberError('oiCaps', error);\n }\n }\n };\n\n readonly #emitToOrderSubscribers = (orders: Order[]): void => {\n if (this.#isDisconnected) {\n return;\n }\n for (const subscriber of this.#orderSubscribers) {\n try {\n subscriber.callback(orders);\n } catch (error) {\n this.#logSubscriberError('orders', error);\n }\n }\n };\n\n readonly #logSubscriberError = (channel: string, error: unknown): void => {\n this.#deps.debugLogger.log(\n `[LighterProvider] ${channel} subscriber callback failed`,\n { error: String(error) },\n );\n };\n\n readonly #startPricePolling = (): void => {\n if (this.#isDisconnected || this.#pricePollTimer) {\n return;\n }\n const poll = (): void => {\n this.#emitPolledPrices().catch((error: unknown) => {\n this.#deps.debugLogger.log('[LighterProvider] price poll failed', {\n error: String(error),\n });\n });\n };\n this.#pricePollTimer = setInterval(poll, LIGHTER_PRICE_POLLING_INTERVAL_MS);\n this.#setConnectionState(WebSocketConnectionState.Connected);\n poll();\n };\n\n /**\n * REST fallback: fetch market stats once and fan them out.\n */\n readonly #emitPolledPrices = async (): Promise<void> => {\n if (this.#priceSubscribers.size === 0) {\n return;\n }\n const response = await this.#clientService.getOrderBookDetails();\n if (this.#isDisconnected) {\n return;\n }\n const timestamp = Date.now();\n const updates = (response.orderBookDetails ?? []).map((detail) =>\n adaptPriceUpdateFromLighter(detail, timestamp),\n );\n this.#dispatchPriceUpdates(updates);\n };\n\n /**\n * Fan price updates out to every subscriber, honoring symbol filters.\n *\n * @param updates - Adapted price updates for this cycle.\n */\n readonly #dispatchPriceUpdates = (updates: PriceUpdate[]): void => {\n if (this.#isDisconnected || updates.length === 0) {\n return;\n }\n for (const update of updates) {\n this.#lastPriceBySymbol.set(update.symbol, update);\n }\n for (const subscriber of this.#priceSubscribers) {\n this.#deliverPrices(subscriber, updates);\n }\n };\n\n readonly #deliverPrices = (\n subscriber: SubscribePricesParams,\n updates: PriceUpdate[],\n ): void => {\n if (this.#isDisconnected) {\n return;\n }\n const filtered =\n subscriber.symbols.length > 0\n ? updates.filter((update) => subscriber.symbols.includes(update.symbol))\n : updates;\n if (filtered.length === 0) {\n return;\n }\n try {\n subscriber.callback(filtered);\n } catch (error) {\n this.#logSubscriberError('prices', error);\n }\n };\n\n readonly #clearKeepalive = (): void => {\n if (this.#wsKeepaliveTimer) {\n clearInterval(this.#wsKeepaliveTimer);\n this.#wsKeepaliveTimer = null;\n }\n };\n\n readonly #teardownStream = (): void => {\n if (this.#pricePollTimer) {\n clearInterval(this.#pricePollTimer);\n this.#pricePollTimer = null;\n }\n if (this.#wsReconnectTimer) {\n clearTimeout(this.#wsReconnectTimer);\n this.#wsReconnectTimer = null;\n }\n this.#clearKeepalive();\n this.#wsWantedChannels.clear();\n this.#accountChannelsPromise = null;\n this.#wsPositions.clear();\n this.#wsOrders.clear();\n this.#orderBookState.clear();\n this.#candleSeries.clear();\n this.#lastPriceBySymbol.clear();\n if (this.#priceWs) {\n const ws = this.#priceWs;\n this.#priceWs = null;\n try {\n ws.close();\n } catch {\n // Socket may already be closed.\n }\n }\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n };\n\n subscribeToCandles(params: SubscribeCandlesParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n let released = false;\n let seriesKey: string | null = null;\n const resolution = LIGHTER_SUPPORTED_RESOLUTIONS.has(params.interval)\n ? params.interval\n : '15m';\n this.#ensureMarkets()\n .then(async (markets) => {\n const market = markets.get(params.symbol);\n if (this.#isDisconnected || !market || released) {\n return undefined;\n }\n seriesKey = `${market.marketId}:${resolution}`;\n // Seed with history so charts render immediately, then let the WS\n // candle channel keep the series live.\n const seeded = await this.fetchHistoricalCandles({\n symbol: params.symbol,\n interval: params.interval,\n limit: 120,\n });\n if (this.#isDisconnected || released) {\n return undefined;\n }\n const series = new Map<number, CandleStick>();\n for (const candle of seeded.candles) {\n series.set(candle.time, candle);\n }\n this.#candleSeries.set(seriesKey, series);\n let subscribers = this.#candleSubscribers.get(seriesKey);\n if (!subscribers) {\n subscribers = new Set();\n this.#candleSubscribers.set(seriesKey, subscribers);\n }\n subscribers.add(params);\n params.callback(seeded);\n this.#requestChannel(`candle/${market.marketId}/${resolution}`);\n this.#ensureStream();\n return undefined;\n })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log('[LighterProvider] candle seed failed', {\n error: String(error),\n });\n });\n return () => {\n released = true;\n if (seriesKey !== null) {\n this.#candleSubscribers.get(seriesKey)?.delete(params);\n }\n this.#releaseChannelIfUnused();\n };\n }\n\n readonly fetchHistoricalCandles = async (options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData> => {\n const empty: CandleData = {\n symbol: options.symbol,\n interval: options.interval,\n candles: [],\n };\n try {\n const markets = await this.#ensureMarkets();\n const market = markets.get(options.symbol);\n if (!market) {\n return empty;\n }\n const resolution = LIGHTER_SUPPORTED_RESOLUTIONS.has(options.interval)\n ? options.interval\n : '15m';\n const intervalMs =\n LIGHTER_RESOLUTION_MS[resolution] ?? LIGHTER_RESOLUTION_MS['15m'];\n const limit = options.limit ?? 120;\n const endTimestamp = options.endTime ?? Date.now();\n const startTimestamp = endTimestamp - intervalMs * limit;\n const response = await this.#clientService.getCandles(\n market.marketId,\n resolution,\n startTimestamp,\n endTimestamp,\n limit,\n );\n return {\n symbol: options.symbol,\n interval: options.interval,\n candles: (response.c ?? []).flatMap((candle) => {\n const mapped = toFiniteCandle(candle);\n return mapped ? [mapped] : [];\n }),\n };\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] fetchHistoricalCandles failed',\n { error: String(error) },\n );\n return empty;\n }\n };\n\n subscribeToOrderBook(params: SubscribeOrderBookParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n let released = false;\n let marketId: number | null = null;\n this.#ensureMarkets()\n .then((markets) => {\n const market = markets.get(params.symbol);\n if (this.#isDisconnected || !market || released) {\n return undefined;\n }\n marketId = market.marketId;\n let subscribers = this.#orderBookSubscribers.get(marketId);\n if (!subscribers) {\n subscribers = new Set();\n this.#orderBookSubscribers.set(marketId, subscribers);\n }\n subscribers.add(params);\n this.#requestChannel(`order_book/${marketId}`);\n this.#ensureStream();\n return undefined;\n })\n .catch((error: unknown) => {\n if (!this.#isDisconnected && !released) {\n params.onError?.(ensureError(error));\n }\n });\n return () => {\n released = true;\n if (marketId !== null) {\n this.#orderBookSubscribers.get(marketId)?.delete(params);\n }\n this.#releaseChannelIfUnused();\n };\n }\n\n setLiveDataConfig(_config: Partial<LiveDataConfig>): void {\n // POC: no live data configuration\n }\n\n getWebSocketConnectionState(): WebSocketConnectionState {\n // REST-polling transport has no socket to report on; treat an active\n // poll loop as connected so callers don't tear down live subscriptions.\n if (!this.#webSocketCtor) {\n return this.#pricePollTimer\n ? WebSocketConnectionState.Connected\n : WebSocketConnectionState.Disconnected;\n }\n return this.#connectionState;\n }\n\n subscribeToConnectionState(\n listener: (\n state: WebSocketConnectionState,\n reconnectionAttempt: number,\n ) => void,\n ): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#connectionListeners.add(listener);\n listener(this.getWebSocketConnectionState(), this.#wsReconnectAttempts);\n return (): void => {\n this.#connectionListeners.delete(listener);\n };\n }\n\n async reconnect(): Promise<void> {\n if (this.#isDisconnected) {\n return;\n }\n const ws = this.#priceWs;\n if (ws) {\n // Detach first so the onclose handler's 5s backoff never races the\n // immediate reconnect below.\n this.#priceWs = null;\n this.#clearKeepalive();\n try {\n ws.close();\n } catch {\n // Socket may already be closed.\n }\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n }\n if (this.#wsReconnectTimer) {\n clearTimeout(this.#wsReconnectTimer);\n this.#wsReconnectTimer = null;\n }\n if (this.#hasAnySubscriber()) {\n this.#ensureStream();\n }\n }\n\n // ============================================================================\n // Asset Routes\n // ============================================================================\n\n /**\n * The venue's USDC bridge route for the active network, in AssetRoute\n * shape. Facts sourced live from `layer1BasicInfo` + venue docs (see\n * LIGHTER_BRIDGE_CONFIG).\n *\n * @param minAmount - Which venue minimum applies (deposit vs withdrawal).\n * @returns Single-element route list.\n */\n readonly #bridgeRoute = (minAmount: string): AssetRoute[] => {\n // Only the MAINNET bridge is ever advertised: the effective-testnet\n // branches return [] before reaching here (devnet L1 unreachable).\n const bridge = LIGHTER_BRIDGE_CONFIG.mainnet;\n return [\n {\n assetId:\n `${bridge.chainId}/erc20:${bridge.usdcContract}/default` as AssetRoute['assetId'],\n chainId: bridge.chainId as AssetRoute['chainId'],\n contractAddress: bridge.bridgeContract as AssetRoute['contractAddress'],\n constraints: { minAmount },\n },\n ];\n };\n\n getDepositRoutes(_params?: GetSupportedPathsParams): AssetRoute[] {\n // DepositService currently builds an ERC-20 transfer, while Lighter\n // requires approval plus a call to the bridge proxy's deposit method.\n // Do not advertise a route until that provider-owned transaction builder\n // exists and has integration coverage.\n return [];\n }\n\n getWithdrawalRoutes(params?: GetSupportedPathsParams): AssetRoute[] {\n // Same devnet-L1 reality and fail-closed network binding as deposits.\n const isTestnet = this.#isTestnet || params?.isTestnet === true;\n if (isTestnet) {\n return [];\n }\n return this.#bridgeRoute(LIGHTER_BRIDGE_CONFIG.mainnet.minWithdrawUsdc);\n }\n\n // ============================================================================\n // Block Explorer\n // ============================================================================\n\n getBlockExplorerUrl(address?: string): string {\n const baseUrl = this.#isTestnet\n ? LIGHTER_TESTNET_EXPLORER_URL\n : LIGHTER_MAINNET_EXPLORER_URL;\n return address ? `${baseUrl}/address/${address}` : baseUrl;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"LighterProvider.js","sourceRoot":"","sources":["../../src/providers/LighterProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,EAClB,iBAAiB,EACjB,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,6BAA6B,EAC7B,wBAAwB,EACxB,yBAAyB,EACzB,wBAAwB,EACxB,yBAAyB,EACzB,oCAAoC,EACpC,oBAAoB,EACpB,iCAAiC,EACjC,yCAAyC,EACzC,qBAAqB,EACrB,4BAA4B,EAC5B,8BAA8B,EAC9B,sCAAsC,EACtC,4BA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QACpE,sEAAsE;QACtE,yEAAyE;QACzE,uCAAuC;QACvC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,mBAAmB,CAAC,MAAgC;QAClD,sEAAsE;QACtE,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,IAAI,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;QAChE,IAAI,SAAS,EAAE,CAAC;YACd,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,IAAI,CAAC,YAAY,CAAC,qBAAqB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAC1E,CAAC;IAED,+EAA+E;IAC/E,iBAAiB;IACjB,+EAA+E;IAE/E,mBAAmB,CAAC,OAAgB;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU;YAC7B,CAAC,CAAC,4BAA4B;YAC9B,CAAC,CAAC,4BAA4B,CAAC;QACjC,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,YAAY,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7D,CAAC;CACF","sourcesContent":["/**\n * LighterProvider\n *\n * Provider implementation for the zkLighter protocol (POC).\n * Implements the PerpsProvider interface with live REST reads and a real\n * write path (place/cancel limit orders) driven through the Lighter Go/WASM\n * signer behind the transport-agnostic {@link LighterSignerBridge} seam.\n *\n * Key differences from HyperLiquid:\n * - Venue-specific key (Schnorr over ECgFp5) registered per API-key slot via\n * a ChangePubKey L2 transaction carrying an EIP-191 personal_sign L1Sig.\n * - Order prices/sizes are integers scaled by per-market decimals.\n * - REST reads plus WebSocket market, account, position, order, fill,\n * order-book, and candle streams, with price polling as a fallback.\n */\n\nimport type { CaipAccountId } from '@metamask/utils';\n\nimport type { CandlePeriod } from '../constants/chartConfig.js';\nimport {\n computeLighterMinOrderSize,\n fromLighterInteger,\n getLighterChainId,\n getLighterTransactionOutcome,\n LIGHTER_RESOLUTION_MS,\n LIGHTER_SUPPORTED_RESOLUTIONS,\n LIGHTER_DEFAULT_API_KEY_INDEX,\n LIGHTER_NO_TRIGGER_PRICE,\n LIGHTER_ORDER_EXPIRY_NONE,\n LIGHTER_ORDER_TYPE_LIMIT,\n LIGHTER_ORDER_TYPE_MARKET,\n LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME,\n getLighterWsEndpoint,\n LIGHTER_PRICE_POLLING_INTERVAL_MS,\n LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n LIGHTER_BRIDGE_CONFIG,\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n LIGHTER_TX_TYPE_CHANGE_PUB_KEY,\n LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER,\n LIGHTER_ORDER_TYPE_STOP_LOSS,\n LIGHTER_ORDER_TYPE_TAKE_PROFIT,\n LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS,\n LIGHTER_TX_TYPE_CREATE_ORDER,\n LIGHTER_TX_TYPE_UPDATE_LEVERAGE,\n LIGHTER_TX_TYPE_UPDATE_MARGIN,\n LIGHTER_TX_TYPE_WITHDRAW,\n LIGHTER_MARGIN_MODE_CROSS,\n LIGHTER_MARGIN_MODE_ISOLATED,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n LIGHTER_USDC_ASSET_INDEX,\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MARGIN_METADATA_TTL_MS,\n parseLighterStrictDecimal,\n toLighterInteger,\n} from '../constants/lighterConfig.js';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport type { PerpsControllerMessenger } from '../PerpsController.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport {\n convertKeysToCamelCase,\n LighterApiError,\n LighterClientService,\n} from '../services/LighterClientService.js';\nimport { LighterWalletService } from '../services/LighterWalletService.js';\nimport { WebSocketConnectionState } from '../types/index.js';\nimport type {\n AccountState,\n AssetRoute,\n CandleData,\n CandleStick,\n CancelOrderParams,\n CancelOrderResult,\n ClosePositionParams,\n DepositParams,\n DisconnectResult,\n EditOrderParams,\n FeeCalculationParams,\n FeeCalculationResult,\n Funding,\n GetAccountStateParams,\n GetFundingParams,\n GetHistoricalPortfolioParams,\n GetMarketsParams,\n GetOrderFillsParams,\n GetOrdersParams,\n GetOrFetchFillsParams,\n GetPositionsParams,\n GetSupportedPathsParams,\n HistoricalPortfolioResult,\n InitializeResult,\n LiquidationPriceParams,\n LiveDataConfig,\n MaintenanceMarginParams,\n MarginResult,\n MarketInfo,\n Order,\n OrderFill,\n OrderParams,\n OrderResult,\n PerpsMarketData,\n PerpsPlatformDependencies,\n PerpsProvider,\n PerpsReadOptions,\n Position,\n PositionModifyPreviewParams,\n PositionModifyPreviewResult,\n RawLedgerUpdate,\n ReadyToTradeResult,\n SubscribeAccountParams,\n SubscribeCandlesParams,\n SubscribeOICapsParams,\n OrderBookData,\n OrderBookLevel,\n SubscribeOrderBookParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n PriceUpdate,\n SubscribePositionsParams,\n SubscribePricesParams,\n ToggleTestnetResult,\n UpdateMarginParams,\n UpdatePositionTPSLParams,\n UserHistoryItem,\n WithdrawParams,\n WithdrawResult,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterAccountsByL1AddressResponse,\n LighterAuthConfig,\n LighterTxLookupResponse,\n LighterTransferHistoryItem,\n LighterCreateClientResult,\n LighterCreateOrderWireParams,\n LighterGroupedOrderWireParams,\n LighterOrderBookMeta,\n LighterSendTxResponse,\n LighterSignerBridge,\n LighterSignerOperation,\n LighterSignerResult,\n LighterWasmCall,\n LighterTxResult,\n LighterWebSocketCtor,\n LighterWebSocketLike,\n LighterWsAccountMessage,\n LighterCandle,\n LighterWsCandleMessage,\n LighterWsOrderBookMessage,\n LighterWsTradesMessage,\n LighterWsMarketStat,\n LighterWsMarketStatsMessage,\n} from '../types/lighter-types.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport {\n adaptAccountStateFromLighter,\n adaptAccountStateFromLighterUserStats,\n adaptFillFromLighterTrade,\n adaptMarketDataFromLighter,\n adaptMarketFromLighter,\n adaptOrderFromLighter,\n adaptPositionFromLighter,\n adaptPriceUpdateFromLighter,\n adaptPriceUpdateFromLighterWsStat,\n} from '../utils/lighterAdapter.js';\n\ntype LighterFillQuery = GetOrderFillsParams & {\n symbol?: string;\n};\n\ntype LighterMarginMetadata = {\n marketId: number;\n minInitial?: number;\n maintenance?: number;\n lastTradePrice?: number;\n};\n\ntype LighterOrderBookState = {\n bids: Map<string, string>;\n asks: Map<string, string>;\n nonce: number;\n};\n\nconst NOOP_UNSUBSCRIBE = (): void => undefined;\n\nconst LIGHTER_INACTIVE_HISTORY_ROW_LIMIT = 10_000;\n\nconst deriveLighterMaxLeverage = (\n minInitialMarginFraction: number | undefined,\n market: string | number,\n): number => {\n if (\n typeof minInitialMarginFraction !== 'number' ||\n !Number.isSafeInteger(minInitialMarginFraction) ||\n minInitialMarginFraction < 1 ||\n minInitialMarginFraction > 10_000\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid initial margin fraction for market ${String(market)}`,\n );\n }\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage < 1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid max leverage for market ${String(market)}`,\n );\n }\n return maxLeverage;\n};\n\nconst isInactiveMarketWithoutUsableRiskMetadata = (market: {\n status: string;\n minInitialMarginFraction?: number;\n maintenanceMarginFraction?: number;\n}): boolean =>\n // Lighter retains inactive rows for historical identity but can zero their\n // trading constraints. They are valid venue records, not usable markets.\n market.status === 'inactive' &&\n (market.minInitialMarginFraction === undefined ||\n market.minInitialMarginFraction === 0 ||\n market.maintenanceMarginFraction === 0);\n\nconst adaptLighterTransferDelta = (\n entry: LighterTransferHistoryItem,\n): RawLedgerUpdate['delta'] => {\n if (entry.type === 'L2TransferOutflow') {\n return { type: 'transferOut', usdc: `-${entry.amount}` };\n }\n if (entry.type === 'L2TransferInflow') {\n return { type: 'transferIn', usdc: entry.amount };\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown transfer type ${String(entry.type)}`,\n );\n};\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Full-string decimal/scientific literal (optional sign and exponent). */\n/**\n * Strict full-string numeric parsing shared with the adaptation boundary\n * (see lighterConfig.parseLighterStrictDecimal): '10USD' or '0.001BTC'\n * would prefix-parse into signed intent under bare parseFloat.\n */\nconst parseStrictDecimal = parseLighterStrictDecimal;\n\n/**\n * Parse caller-supplied numeric intent, accepting only finite positive\n * values from a strictly numeric string.\n *\n * @param value - Raw numeric string from params.\n * @returns The parsed number, or null when malformed, non-finite or\n * non-positive.\n */\nconst parseFinitePositive = (value: string): number | null => {\n const parsed = parseStrictDecimal(value);\n return parsed !== null && Number.isFinite(parsed) && parsed > 0\n ? parsed\n : null;\n};\n\n/**\n * Integerize a SIGNER-BOUND value: the scaled result must be a positive\n * safe wire integer. The positive-intent policy lives here, not in the\n * generic public converter.\n *\n * @param value - Human-units value.\n * @param decimals - Market/asset decimals.\n * @returns The positive wire integer.\n */\nconst toSignerWireInteger = (value: number, decimals: number): number => {\n const scaled = toLighterInteger(value, decimals);\n if (scaled < 1) {\n throw new Error(`Value ${value} rounds to zero at ${decimals} decimals`);\n }\n return scaled;\n};\n\n/**\n * Snap a base size onto the market's size grid exactly as wire\n * integerization will (round to nearest step). Minimum-size checks must\n * judge the SNAPPED size: a raw USD/price quotient one hair under the\n * minimum still reaches the venue as the valid minimum step, and\n * rejecting the raw quotient refuses orders the venue accepts.\n *\n * @param size - Raw base size (human units).\n * @param supportedSizeDecimals - Market size decimals.\n * @returns The grid-snapped size, or the input unchanged when it cannot\n * be integerized (range overflow) — later wire conversion fails closed.\n */\nconst snapToLighterSizeGrid = (\n size: number,\n supportedSizeDecimals: number,\n): number => {\n try {\n return fromLighterInteger(\n toLighterInteger(size, supportedSizeDecimals),\n supportedSizeDecimals,\n );\n } catch {\n return size;\n }\n};\n\n/**\n * Whether Lighter applies its documented maker-only order minimums.\n *\n * @param params - Order intent to classify.\n * @returns Whether the order rests as a maker order.\n */\nconst isLighterMakerOrder = (params: OrderParams): boolean =>\n params.orderType === 'limit' && params.timeInForce !== 'IOC';\n\n/**\n * Parse a candle field without JavaScript's null/boolean/blank coercions.\n *\n * @param value - Raw candle field from the venue.\n * @returns A finite number, or null when the field is malformed.\n */\nconst toFiniteCandleNumber = (value: unknown): number | null => {\n const parsed = typeof value === 'number' ? value : parseStrictDecimal(value);\n return parsed !== null && Number.isFinite(parsed) ? parsed : null;\n};\n\n/**\n * Map one venue candle onto the CandleStick contract, or null when any\n * field is non-finite. WS/REST candle payloads are cast at the boundary,\n * not validated — a malformed candle stringified blind reaches the chart\n * as \"undefined\"/NaN, the same native-SVG crash class the bare\n * order-book levels produced.\n *\n * @param candle - Raw venue candle.\n * @returns The contract candle, or null when unmappable.\n */\nconst toFiniteCandle = (candle: LighterCandle): CandleStick | null => {\n const time = toFiniteCandleNumber(candle?.t);\n const fields = [candle?.o, candle?.h, candle?.l, candle?.c, candle?.v].map(\n toFiniteCandleNumber,\n );\n if (time === null || fields.some((value) => value === null)) {\n return null;\n }\n const [open, high, low, close, volume] = fields as number[];\n return {\n time,\n open: String(open),\n high: String(high),\n low: String(low),\n close: String(close),\n volume: String(volume),\n };\n};\n\n/** The pinned signer casts price fields to uint32. */\nconst LIGHTER_MAX_WIRE_PRICE = 4_294_967_295;\n\n/**\n * One recorded TP/SL venue mutation attempt. Each attempt carries its own\n * nonce and outcome: a single flat flag cannot represent \"create accepted,\n * cancel #1 accepted, cancel #2 response-lost\".\n */\ntype TpslCreateAttempt = {\n kind: 'create';\n /**\n * Unique per-journal attempt identity. Nonces CANNOT identify\n * attempts: a proven-never-landed submission releases its nonce and a\n * retry legitimately reuses it.\n */\n attemptId: number;\n /** See TpslCancelAttempt.terminalStatus. */\n terminalStatus?: number;\n /** The venue nonce this submission attempted to consume. */\n nonce: number;\n /** 'accepted' only after the venue's 200 was OBSERVED. */\n outcome: 'unknown' | 'accepted';\n /** Created client ids (nonempty). */\n clientIds: number[];\n /** The signed transaction hash (known BEFORE submission). */\n txHash: string;\n /**\n * Signed payload expiry (ms). After this instant (+ clock slack) the\n * sequencer can no longer accept the payload, so a not-found hash is\n * authoritatively never-landed.\n */\n expiresAt: number;\n /** What this create IS: the replacement, or a restore of the old set. */\n role: 'replacement' | 'restore';\n /**\n * For role 'restore' only: the prior triggers (by original orderId in\n * `priorTriggers`) this attempt restores, INDEX-ALIGNED with\n * `clientIds` (a grouped OCO restore carries two legs). With multiple\n * prior triggers and a crash mid-restore, recovery uses this to\n * restore exactly the remaining intents — never duplicating or\n * omitting one.\n */\n priorOrderIds?: string[];\n};\n\ntype TpslCancelAttempt = {\n kind: 'cancel';\n /** Unique per-journal attempt identity (see TpslCreateAttempt). */\n attemptId: number;\n /**\n * Venue-reported terminal status (4 failed / 5 rejected) recorded by\n * reconciliation for an attempt that LANDED but did not mutate the\n * books — makes it compactable.\n */\n terminalStatus?: number;\n nonce: number;\n outcome: 'unknown' | 'accepted';\n /** The cancelled order id. */\n orderId: string;\n txHash: string;\n expiresAt: number;\n /** Whether this cancels OLD protection or rolls back a failed leg. */\n role: 'stale' | 'rollback';\n};\n\n/** A recorded TP/SL venue mutation attempt (discriminated by kind). */\ntype TpslAttempt = TpslCreateAttempt | TpslCancelAttempt;\n\n/**\n * The wire intent of a PRIOR trigger, persisted before it is cancelled so\n * a crash-then-terminal-failure can still RESTORE the old protection.\n */\ntype TpslPriorTrigger = {\n orderId: string;\n side: 'buy' | 'sell';\n /**\n * EXACT signer wire order type (2 stop-loss, 3 stop-loss-limit,\n * 4 take-profit, 5 take-profit-limit). A restore must rebuild the\n * prior order faithfully — never coerce a limit trigger to market.\n */\n wireOrderType: 2 | 3 | 4 | 5;\n /** Exact signer wire time-in-force (0 IOC, 1 GTT, 2 post-only). */\n wireTimeInForce: 0 | 1 | 2;\n /**\n * Venue-reported absolute order expiry (ms). Restores reuse it while\n * still in the future; otherwise the signer's default sentinel.\n */\n orderExpiry: number;\n /** Execution price (market triggers) or exact limit price. */\n price: string;\n /** User-facing trigger level. */\n triggerPrice: string;\n remainingSize: string;\n};\n\n/**\n * Identity of the position the journalled protection belonged to. A\n * delayed restore must never attach old triggers to a DIFFERENT\n * lifecycle (original closed, new same-symbol position opened).\n */\n/**\n * Durable nonce dispatch ledger document. Entries carry the OPERATION\n * kind (tx type) and a human-readable intent so a dispatch whose\n * response was lost but which is later PROVEN consumed can be surfaced\n * as a recovered outcome — blocking blind retries of financial\n * operations until explicitly acknowledged.\n */\ntype LighterRecoveredDispatch = {\n /** Stable identity for selective acknowledgment. */\n recoveryId: string;\n kind: number;\n intent: string;\n txHash: string | null;\n /**\n * Authoritative outcome: 'succeeded' (exact-hash lookup, venue status\n * executed), 'failed' (exact-hash lookup, venue status failed/rejected\n * — retry-safe, non-blocking), 'unknown' (only the nonce advance is\n * proven, e.g. another device moved the nonce; the intent's own fate\n * is NOT known and must never be reported as completed).\n */\n outcome: 'succeeded' | 'failed' | 'unknown';\n /** What proved the outcome (e.g. 'tx-status:2', 'rest-advance'). */\n evidence: string;\n};\n\ntype LighterNonceLedgerDoc = {\n consumedFloor: number;\n entries: {\n nonce: number;\n txHash: string | null;\n expiresAt: number | null;\n kind: number;\n intent: string;\n /**\n * Operation that owns reconciliation of this dispatch (a TP/SL\n * journal's operationId). Owned dispatches resolve through their\n * own state machine and are NEVER quarantined into the generic\n * recovered list — that would deadlock the machine behind an\n * acknowledgment it cannot give.\n */\n owner: string | null;\n }[];\n recovered: LighterRecoveredDispatch[];\n};\n\n/**\n * Durable transition state: 'creating' means the old protection is still\n * untouched (a failed replacement needs at most a rollback of surviving\n * legs); 'cancelling' means old cancels are underway/done; 'manual'\n * parks the obligation for explicit user re-establishment.\n */\ntype TpslJournalState = {\n attempts: TpslAttempt[];\n recordedAt: number;\n /**\n * IMMUTABLE identity of the operation this journal records. Clears and\n * updates are compare-and-swap on this id so a recovery pass holding a\n * STALE snapshot can never erase a newer operation's journal.\n */\n operationId: string;\n /** When the OPERATION began (immutable; `recordedAt` moves per write). */\n createdAt: number;\n /**\n * DURABLE monotonic attempt-id allocator: compaction removes attempts,\n * so deriving the next id from the surviving maximum could recycle an\n * identity a removed attempt already used.\n */\n nextAttemptId: number;\n /**\n * The durable OPERATION intent: a 'remove' journals only cancels and\n * must NEVER be \"recovered\" by restoring the cancelled protection —\n * that would silently undo an intentional removal.\n */\n intent: 'replace' | 'remove';\n /**\n * 'creating': old protection untouched (failure needs at most a\n * rollback of surviving replacement legs). 'cancelling': old cancels\n * underway/done. 'manual': the venue has NO atomic primitive that\n * could prove a restore attaches to the same position lifecycle, so a\n * fully-failed replacement after old cancels is NEVER auto-restored —\n * the journal parks durably in this state, is surfaced to callers via\n * `getPendingManualRecoveries`, and only an explicit NEW protection\n * intent from the user resolves it.\n */\n phase: 'creating' | 'cancelling' | 'manual';\n /**\n * Whether the prior set was a venue-linked auto-cancel TP+SL pair\n * (decided ONLY by the venue's own linkage fields).\n */\n priorGrouping: 'oco' | 'independent';\n priorTriggers: TpslPriorTrigger[];\n};\n\n/**\n * DURABLE manual-recovery record, SEPARATE from the settlement journal:\n * parking releases the journal slot (so a successor protection intent\n * can run), while this warning survives until a successor intent\n * SUCCEEDS — a failed successor must never erase the warning.\n */\ntype TpslManualRecovery = {\n settlementKey: string;\n symbol: string;\n /** Human-readable cause of the parked state. */\n reason: string;\n priorIntent: 'replace' | 'remove';\n /** Exact wire intents of the protection that was in place before. */\n priorTriggers: TpslPriorTrigger[];\n /** Venue order ids still on the books when the state was parked. */\n survivingOrderIds: string[];\n operationId: string;\n recordedAt: number;\n};\n\n/**\n * Clock slack added to a signed payload's ExpiredAt before a not-found\n * transaction hash is declared never-landed.\n */\nconst LIGHTER_TX_EXPIRY_SLACK_MS = 30_000;\n/** Maximum durable recovered-dispatch outcomes retained per nonce ledger. */\nconst LIGHTER_RECOVERED_DISPATCH_LIMIT = 32;\n/** Maximum durable TP/SL manual-recovery obligations retained per network. */\nconst LIGHTER_TPSL_MANUAL_RECOVERY_LIMIT = 64;\n\n/**\n * Extract the signed txHash and ExpiredAt from a bridge signing result,\n * failing CLOSED: without them the settlement journal cannot resolve a\n * lost response authoritatively, so the mutation must not be submitted.\n *\n * @param signed - Bridge signing result.\n * @param signed.txHash - Signed transaction hash (hex).\n * @param signed.txInfo - Signed wire payload JSON (carries ExpiredAt).\n * @returns The transaction hash and expiry (ms).\n */\nconst requireSignedTxIdentity = (signed: {\n txHash?: string;\n txInfo?: string;\n}): { txHash: string; expiresAt: number } => {\n const { txHash } = signed;\n if (\n typeof txHash !== 'string' ||\n !/^(0x)?[0-9a-fA-F]{8,128}$/u.test(txHash)\n ) {\n throw new Error(\n 'Lighter signing result carries no usable txHash; refusing to submit an unreconcilable mutation',\n );\n }\n let expiresAt: unknown;\n try {\n expiresAt = (JSON.parse(signed.txInfo ?? '') as Record<string, unknown>)\n .ExpiredAt;\n } catch {\n expiresAt = undefined;\n }\n if (\n typeof expiresAt !== 'number' ||\n !Number.isSafeInteger(expiresAt) ||\n expiresAt <= 0\n ) {\n throw new Error(\n 'Lighter signing result carries no usable ExpiredAt; refusing to submit an unreconcilable mutation',\n );\n }\n return { txHash, expiresAt };\n};\n\n/**\n * PROCESS-WIDE mutexes: venue write sections, the per-settlement journal\n * state machine, and journal/index read-modify-writes are serialized\n * across ALL provider instances in this runtime. Instance-local write\n * chains cannot protect two live providers sharing one venue account or\n * one disk cache. Completed tails are evicted to keep the map bounded.\n */\nconst processMutexTails = new Map<string, Promise<unknown>>();\n\n/**\n * Run an operation atomically w.r.t. every other holder of the same key\n * in this process.\n *\n * @param key - Key to serialize on.\n * @param operation - The critical operation.\n * @returns The operation's result.\n */\nconst withProcessMutex = async <Result>(\n key: string,\n operation: () => Promise<Result>,\n): Promise<Result> => {\n const tail = processMutexTails.get(key) ?? Promise.resolve();\n const run = tail.then(operation, operation);\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n processMutexTails.set(key, settled);\n settled\n .then(() => {\n // Evict when no newer holder queued behind us.\n if (processMutexTails.get(key) === settled) {\n processMutexTails.delete(key);\n }\n return undefined;\n })\n .catch(() => undefined);\n return await run;\n};\n\n/**\n * Storage-scoped alias of the process mutex (kept for call-site clarity).\n *\n * @param key - Storage key to serialize on.\n * @param operation - The read-modify-write.\n * @returns The operation's result.\n */\nconst withStorageMutex = withProcessMutex;\n\n/**\n * The WASM signer hosts ONE global client per bridge. These module maps\n * track which venue identity (`network:account:apiKey`) currently owns\n * each bridge's client, and give every bridge a process-unique mutex key\n * so all sign-and-dispatch sections across ALL provider instances\n * sharing a bridge are serialized and re-establish the correct client\n * before signing.\n */\n/**\n * Cryptographic randomness with a bounded Math.random fallback for hosts\n * without WebCrypto. Collision-resistant ids matter here: a recycled\n * operation id could let a stale journal resolver clear a live journal.\n *\n * @param byteCount - Number of random bytes.\n * @returns The random bytes.\n */\nconst randomBytes = (byteCount: number): Uint8Array => {\n const bytes = new Uint8Array(byteCount);\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoObj?.getRandomValues) {\n cryptoObj.getRandomValues(bytes);\n return bytes;\n }\n for (let index = 0; index < byteCount; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n return bytes;\n};\n\n/**\n * Two independent 24-bit random values (client order id halves).\n *\n * @returns The [high, low] pair.\n */\nconst randomUint24Pair = (): [number, number] => {\n const bytes = randomBytes(6);\n return [\n bytes[0] * 65_536 + bytes[1] * 256 + bytes[2],\n bytes[3] * 65_536 + bytes[4] * 256 + bytes[5],\n ];\n};\n\n/**\n * Collision-resistant id suffix (80 bits, hex).\n *\n * @returns The suffix string.\n */\nconst randomIdSuffix = (): string =>\n Array.from(randomBytes(10), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('');\n\nconst bridgeClientOwners = new WeakMap<object, string>();\nconst bridgeIds = new WeakMap<object, number>();\nlet nextBridgeId = 1;\n\n/**\n * Process-unique mutex key for a bridge instance.\n *\n * @param bridge - The signer bridge.\n * @returns The mutex key.\n */\nconst bridgeMutexKey = (bridge: object): string => {\n let id = bridgeIds.get(bridge);\n if (id === undefined) {\n id = nextBridgeId;\n nextBridgeId += 1;\n bridgeIds.set(bridge, id);\n }\n return `lighterBridge:${id}`;\n};\n\n/**\n * Parse a journal-pointer document, or null when the content is not a\n * pointer (legacy inline journal or corrupt data — both handled by the\n * caller's payload validation path).\n *\n * @param raw - Raw base-key content.\n * @returns The pointer, or null.\n */\nconst parseTpslJournalPointer = (\n raw: string,\n): { operationId: string } | null => {\n try {\n const parsed = JSON.parse(raw) as {\n pointerVersion?: unknown;\n operationId?: unknown;\n };\n if (\n parsed.pointerVersion === 1 &&\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length >= 1 &&\n parsed.operationId.length <= 64\n ) {\n return { operationId: parsed.operationId };\n }\n } catch {\n // Not JSON: not a pointer.\n }\n return null;\n};\n\n/**\n * Best-effort dispatch identity from a bridge signing result. The pinned\n * WASM contract (web-wasm light_client.go) returns `{txHash, txInfo}`\n * where txInfo is the marshaled wire payload — it carries Nonce and\n * ExpiredAt but NEVER the hash. Non-throwing: ops whose signers omit a\n * field dispatch with a partial identity (resolvable only by REST\n * advance, never by expiry).\n *\n * @param signed - Bridge signing result.\n * @param signed.txHash - Signed transaction hash from the RESULT.\n * @param signed.txInfo - Marshaled wire payload.\n * @returns The dispatch identity (null fields when unavailable).\n */\nconst extractDispatchIdentity = (signed: {\n txHash?: unknown;\n txInfo?: string;\n}): { txHash: string | null; expiresAt: number | null } => {\n const txHash =\n typeof signed.txHash === 'string' &&\n /^(0x)?[0-9a-fA-F]{8,128}$/u.test(signed.txHash)\n ? signed.txHash\n : null;\n let expiresAt: number | null = null;\n try {\n const wire = JSON.parse(signed.txInfo ?? '') as Record<string, unknown>;\n expiresAt =\n typeof wire.ExpiredAt === 'number' &&\n Number.isSafeInteger(wire.ExpiredAt) &&\n wire.ExpiredAt > 0\n ? wire.ExpiredAt\n : null;\n } catch {\n expiresAt = null;\n }\n return { txHash, expiresAt };\n};\n\n/**\n * Allocate the next unique attempt identity from the journal's DURABLE\n * monotonic counter (compaction can therefore never recycle an id).\n *\n * @param journal - The journal being appended to.\n * @returns The allocated attempt id.\n */\nconst nextAttemptIdFor = (journal: TpslJournalState): number => {\n const allocated = journal.nextAttemptId;\n journal.nextAttemptId += 1;\n return allocated;\n};\n\n/** Delay between TP/SL settlement visibility polls. */\nconst LIGHTER_TPSL_SETTLE_POLL_MS = 150;\n\n/** Bounded attempts for TP/SL settlement visibility. */\nconst LIGHTER_TPSL_SETTLE_ATTEMPTS = 10;\n\n/**\n * Integerize a signer-bound PRICE (order price / trigger price): the\n * pinned lighter-go signer casts these to uint32 (web-wasm/main.go), so a\n * safe-integer above 2^32-1 silently WRAPS (e.g. 429496729.7 at 1 decimal\n * scales to 4,294,967,297 and wires as 1).\n *\n * @param value - Human-units price.\n * @param decimals - Market price decimals.\n * @returns The positive uint32 wire integer.\n */\nconst toSignerWirePriceInteger = (value: number, decimals: number): number => {\n const scaled = toSignerWireInteger(value, decimals);\n if (scaled > LIGHTER_MAX_WIRE_PRICE) {\n throw new Error(\n `Price ${value} exceeds Lighter's uint32 wire range at ${decimals} decimals`,\n );\n }\n return scaled;\n};\n\n/**\n * Map a RAW venue trigger row to its durable prior wire intent, or null\n * when it cannot be faithfully restored: unknown type/TIF/expiry, a\n * MISSING trigger price (never substituted — that would change the\n * user's protection semantics), a malformed/non-positive decimal, or a\n * value that cannot be integerized onto the wire (range/sub-tick). The\n * writer must never persist state the loader (or the signer) would\n * later reject. A mutation that would cancel such a row must fail\n * closed BEFORE any cancel.\n *\n * @param raw - Raw venue order row.\n * @param market - Market integerization parameters.\n * @param market.supportedSizeDecimals - Size integerization decimals.\n * @param market.supportedPriceDecimals - Price integerization decimals.\n * @returns The exact prior wire intent, or null when unmappable.\n */\nconst mapRawTriggerToPriorIntent = (\n raw: LighterApiOrder,\n market: {\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n },\n): TpslPriorTrigger | null => {\n const wireOrderTypeByVenueType: Record<string, 2 | 3 | 4 | 5> = {\n 'stop-loss': 2,\n 'stop-loss-limit': 3,\n 'take-profit': 4,\n 'take-profit-limit': 5,\n };\n const wireTimeInForceByVenueTif: Record<string, 0 | 1 | 2> = {\n 'immediate-or-cancel': 0,\n 'good-till-time': 1,\n 'post-only': 2,\n };\n const wireOrderType = wireOrderTypeByVenueType[raw.type];\n const wireTimeInForce = wireTimeInForceByVenueTif[raw.timeInForce];\n if (\n wireOrderType === undefined ||\n wireTimeInForce === undefined ||\n !Number.isSafeInteger(raw.orderExpiry) ||\n raw.orderExpiry < -1 ||\n !/^\\d{1,20}$/u.test(String(raw.orderIndex)) ||\n // A trigger's trigger price is REQUIRED verbatim.\n typeof raw.triggerPrice !== 'string'\n ) {\n return null;\n }\n const price = parseStrictDecimal(raw.price);\n const triggerPrice = parseStrictDecimal(raw.triggerPrice);\n const remainingSize = parseStrictDecimal(raw.remainingBaseAmount);\n if (\n price === null ||\n !Number.isFinite(price) ||\n price <= 0 ||\n triggerPrice === null ||\n !Number.isFinite(triggerPrice) ||\n triggerPrice <= 0 ||\n remainingSize === null ||\n !Number.isFinite(remainingSize) ||\n remainingSize <= 0\n ) {\n return null;\n }\n // Wire PREFLIGHT: integerize exactly what a restore would sign. A\n // range/sub-tick failure here refuses the whole mutation up front.\n try {\n toSignerWireInteger(remainingSize, market.supportedSizeDecimals);\n toSignerWirePriceInteger(price, market.supportedPriceDecimals);\n toSignerWirePriceInteger(triggerPrice, market.supportedPriceDecimals);\n } catch {\n return null;\n }\n return {\n orderId: String(raw.orderIndex),\n side: raw.isAsk ? 'sell' : 'buy',\n wireOrderType,\n wireTimeInForce,\n orderExpiry: raw.orderExpiry,\n price: raw.price,\n triggerPrice: raw.triggerPrice,\n remainingSize: raw.remainingBaseAmount,\n };\n};\n\n/**\n * Validate caller leverage intent against what Lighter can represent.\n *\n * @param leverage - Requested leverage, if any.\n * @returns The exact rejection message, or null when acceptable.\n */\nconst lighterLeverageError = (leverage: number | undefined): string | null => {\n if (leverage === undefined) {\n return null;\n }\n if (!Number.isFinite(leverage) || !(leverage > 0)) {\n return `Invalid leverage ${leverage}: must be a positive number`;\n }\n // UpdateLeverage signs an initial margin fraction in hundredths of a\n // percent. The derived IMF must itself be a positive safe integer within\n // the venue's fraction range: huge finite leverage rounds it to zero,\n // tiny finite leverage (Number.MIN_VALUE) overflows the division to\n // Infinity, and sub-1x leverage exceeds a 100% margin fraction.\n const imfHundredths = Math.round(10_000 / leverage);\n if (\n !Number.isSafeInteger(imfHundredths) ||\n imfHundredths < 1 ||\n imfHundredths > 10_000\n ) {\n return `Invalid leverage ${leverage}: outside Lighter's representable leverage range`;\n }\n return null;\n};\n\n/**\n * Derive the protection/execution price a market order signs from its\n * reference price — shared by placement and both validators so wire-range\n * checks always inspect the exact value the signer receives.\n *\n * @param referencePrice - Fresh venue reference price.\n * @param isBuy - Order side; buys protect above, sells below.\n * @param slippageFraction - Slippage tolerance (validated < 1).\n * @returns The slippage-adjusted execution price.\n */\nconst deriveLighterExecutionPrice = (\n referencePrice: number,\n isBuy: boolean,\n slippageFraction: number,\n): number =>\n isBuy\n ? referencePrice * (1 + slippageFraction)\n : referencePrice * (1 - slippageFraction);\n\nconst LIGHTER_NOT_SUPPORTED_ERROR = 'Lighter operation not yet supported';\nconst LIGHTER_SIGNER_UNAVAILABLE_ERROR = 'Lighter signer bridge not configured';\nconst LIGHTER_MAINNET_EXPLORER_URL = 'https://scan.lighter.xyz';\nconst LIGHTER_TESTNET_EXPLORER_URL = 'https://testnet.zklighter.elliot.ai';\n\n/** A definitive venue response that the selected wallet has no account. */\nclass LighterAccountNotFoundError extends Error {\n constructor(address: string) {\n super(\n `No Lighter account exists for ${address}; fund it via the bridge (or the testnet faucet) first`,\n );\n this.name = 'LighterAccountNotFoundError';\n }\n}\n\n/**\n * Empty account state returned when reads fail or no account exists.\n */\nconst EMPTY_ACCOUNT_STATE: AccountState = {\n totalBalance: '0',\n spendableBalance: '0',\n withdrawableBalance: '0',\n marginUsed: '0',\n unrealizedPnl: '0',\n returnOnEquity: '0',\n providerId: 'lighter',\n};\n\n// ============================================================================\n// LighterProvider\n// ============================================================================\n\n/**\n * Lighter provider implementation (POC).\n */\nexport class LighterProvider implements PerpsProvider {\n readonly protocolId = 'lighter';\n\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #clientService: LighterClientService;\n\n readonly #walletService: LighterWalletService;\n\n readonly #messenger: PerpsControllerMessenger | null;\n\n readonly #signerBridge: LighterSignerBridge | null;\n\n #signerResetUnsubscribe: (() => void) | null = null;\n\n readonly #isTestnet: boolean;\n\n readonly #apiKeyIndex: number;\n\n readonly #configuredAccountIndex: number | undefined;\n\n /** Markets cache keyed by symbol (freshness delegated to client service). */\n #marketsBySymbol: Map<string, LighterOrderBookMeta> = new Map();\n\n #marketsById: Map<number, LighterOrderBookMeta> = new Map();\n\n /** Resolved Lighter account index (after ensureAccount()). */\n #accountIndex: number | null = null;\n\n /** L1 address the current venue session (index/signer/auth) is bound to. */\n #boundAddress: string | null = null;\n\n /** Terminal lifecycle fence set by disconnect(). */\n #isDisconnected = false;\n\n /**\n * Monotonic counter bumped on every session rebind. Async resolutions\n * capture it before awaiting and refuse to cache results from a stale\n * generation (an account-A lookup resolving after the switch to B).\n */\n #sessionGeneration = 0;\n\n /** Active price-stream subscribers (REST polling fan-out). */\n readonly #priceSubscribers: Set<SubscribePricesParams> = new Set();\n\n #pricePollTimer: ReturnType<typeof setInterval> | null = null;\n\n #priceWs: LighterWebSocketLike | null = null;\n\n /** Injectable WebSocket constructor (null → REST polling fallback). */\n readonly #webSocketCtor: LighterWebSocketCtor | null;\n\n /** Channels the shared socket should be subscribed to (subscribe payloads). */\n readonly #wsWantedChannels: Map<string, { auth?: string }> = new Map();\n\n #wsKeepaliveTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Live WS connection state, mirrored to subscribed listeners. */\n #connectionState: WebSocketConnectionState =\n WebSocketConnectionState.Disconnected;\n\n /** Consecutive reconnect attempts since the last successful open. */\n #wsReconnectAttempts = 0;\n\n readonly #connectionListeners = new Set<\n (state: WebSocketConnectionState, reconnectionAttempt: number) => void\n >();\n\n readonly #setConnectionState = (state: WebSocketConnectionState): void => {\n if (this.#connectionState === state) {\n return;\n }\n this.#connectionState = state;\n for (const listener of this.#connectionListeners) {\n try {\n listener(state, this.#wsReconnectAttempts);\n } catch (error) {\n this.#logSubscriberError('connection-state', error);\n }\n }\n };\n\n #wsReconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Merged latest price per symbol, replayed to late price subscribers. */\n readonly #lastPriceBySymbol: Map<string, PriceUpdate> = new Map();\n\n /** Merged live position state from account_all_positions (keyed marketId). */\n readonly #wsPositions: Map<number, Position> = new Map();\n\n /** Merged live open orders from account_all_orders (keyed orderId). */\n readonly #wsOrders: Map<string, Order> = new Map();\n\n readonly #oiCapSubscribers: Set<SubscribeOICapsParams> = new Set();\n\n readonly #accountSubscribers: Set<SubscribeAccountParams> = new Set();\n\n readonly #positionSubscribers: Set<SubscribePositionsParams> = new Set();\n\n readonly #orderSubscribers: Set<SubscribeOrdersParams> = new Set();\n\n readonly #fillSubscribers: Set<SubscribeOrderFillsParams> = new Set();\n\n /** Order-book subscribers keyed by market id. */\n readonly #orderBookSubscribers: Map<number, Set<SubscribeOrderBookParams>> =\n new Map();\n\n /** Live order-book level state per market (price → size). */\n readonly #orderBookState: Map<number, LighterOrderBookState> = new Map();\n\n /** Candle subscribers keyed by `marketId:resolution`. */\n readonly #candleSubscribers: Map<string, Set<SubscribeCandlesParams>> =\n new Map();\n\n /** Cached candle series per `marketId:resolution` (keyed by open time). */\n readonly #candleSeries: Map<string, Map<number, CandleStick>> = new Map();\n\n /** Dedup for the async account-channel setup. */\n #accountChannelsPromise: Promise<void> | null = null;\n\n /** Derived venue public key hex, set after the signer client is created. */\n #venuePublicKey: string | null = null;\n\n /** Signer session dedup. */\n #signerReadyPromise: Promise<void> | null = null;\n\n /** Cached auth token (deadline-managed). */\n #authToken: { token: string; deadline: number } | null = null;\n\n constructor(options: {\n isTestnet?: boolean;\n platformDependencies: PerpsPlatformDependencies;\n messenger?: PerpsControllerMessenger;\n lighterAuthConfig?: LighterAuthConfig;\n signerBridge?: LighterSignerBridge;\n webSocketCtor?: LighterWebSocketCtor | null;\n }) {\n this.#deps = options.platformDependencies;\n this.#isTestnet = options.isTestnet ?? true;\n this.#messenger = options.messenger ?? null;\n this.#signerBridge = options.signerBridge ?? null;\n this.#ensureSignerResetListener();\n const globalWebSocket = Reflect.get(globalThis, 'WebSocket') as\n | LighterWebSocketCtor\n | undefined;\n const defaultWebSocketCtor =\n typeof globalWebSocket === 'function' ? globalWebSocket : null;\n this.#webSocketCtor =\n options.webSocketCtor === undefined\n ? defaultWebSocketCtor\n : options.webSocketCtor;\n this.#apiKeyIndex =\n options.lighterAuthConfig?.apiKeyIndex ?? LIGHTER_DEFAULT_API_KEY_INDEX;\n this.#configuredAccountIndex = options.lighterAuthConfig?.accountIndex;\n\n this.#clientService = new LighterClientService(this.#deps, {\n isTestnet: this.#isTestnet,\n });\n this.#walletService = new LighterWalletService(this.#deps, {\n isTestnet: this.#isTestnet,\n messenger: options.messenger,\n personalSigner: options.lighterAuthConfig?.personalSigner,\n l1Address: options.lighterAuthConfig?.l1Address,\n });\n\n this.#deps.debugLogger.log('[LighterProvider] Constructor complete', {\n protocolId: this.protocolId,\n isTestnet: this.#isTestnet,\n hasMessenger: Boolean(this.#messenger),\n hasSignerBridge: Boolean(this.#signerBridge),\n apiKeyIndex: this.#apiKeyIndex,\n });\n }\n\n // ============================================================================\n // Error Context Helper\n // ============================================================================\n\n readonly #getErrorContext = (\n method: string,\n extra?: Record<string, unknown>,\n ): {\n tags?: Record<string, string | number>;\n context?: { name: string; data: Record<string, unknown> };\n } => {\n return {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: 'LighterProvider',\n network: this.#isTestnet ? 'testnet' : 'mainnet',\n },\n context: {\n name: `LighterProvider.${method}`,\n data: {\n isTestnet: this.#isTestnet,\n ...extra,\n },\n },\n };\n };\n\n // ============================================================================\n // Initialization & Lifecycle\n // ============================================================================\n\n async initialize(): Promise<InitializeResult> {\n try {\n const markets = await this.#clientService.getOrderBooks(true);\n if (this.#isDisconnected) {\n return { success: false, error: 'Lighter provider is disconnected' };\n }\n this.#marketsBySymbol = new Map(\n markets.map((market) => [market.symbol, market]),\n );\n this.#marketsById = new Map(\n markets.map((market) => [market.marketId, market]),\n );\n this.#deps.debugLogger.log('[LighterProvider] Initialized', {\n markets: markets.length,\n });\n return { success: true };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.initialize',\n );\n this.#deps.debugLogger.log('[LighterProvider] initialize failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('initialize'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async disconnect(): Promise<DisconnectResult> {\n // A disconnect (provider switch, shutdown) invalidates the whole\n // session: an in-flight write paused inside the lock must fail its\n // fences instead of submitting after the provider was torn down.\n this.#isDisconnected = true;\n this.#invalidateSessionState();\n this.#removeSignerResetListener();\n this.#teardownStream();\n this.#priceSubscribers.clear();\n this.#oiCapSubscribers.clear();\n this.#accountSubscribers.clear();\n this.#positionSubscribers.clear();\n this.#orderSubscribers.clear();\n this.#fillSubscribers.clear();\n this.#orderBookSubscribers.clear();\n this.#candleSubscribers.clear();\n return { success: true };\n }\n\n async ping(_timeoutMs?: number): Promise<void> {\n await this.#clientService.getOrderBooks();\n }\n\n async toggleTestnet(): Promise<ToggleTestnetResult> {\n // Network is fixed at construction.\n return {\n success: false,\n isTestnet: this.#isTestnet,\n error: 'Lighter network is fixed at construction',\n };\n }\n\n async isReadyToTrade(): Promise<ReadyToTradeResult> {\n try {\n if (!this.#signerBridge) {\n return {\n ready: false,\n error: LIGHTER_SIGNER_UNAVAILABLE_ERROR,\n walletConnected: false,\n networkSupported: true,\n };\n }\n await this.#ensureSignerReady();\n return {\n ready: true,\n walletConnected: true,\n networkSupported: true,\n authenticatedAddress: this.#walletService.getUserAddress(),\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.isReadyToTrade',\n );\n return {\n ready: false,\n error: wrappedError.message,\n walletConnected: false,\n networkSupported: true,\n };\n }\n }\n\n // ============================================================================\n // Signer session\n // ============================================================================\n\n /**\n * The RAW bridge instance — the STABLE identity object for the\n * process-wide ownership map and mutex key. The `#getSignerBridge`\n * wrapper below is a fresh object per call and must NEVER key either.\n *\n * @returns The raw signer bridge.\n */\n readonly #rawSignerBridge = (): LighterSignerBridge => {\n if (!this.#signerBridge) {\n throw new Error(LIGHTER_SIGNER_UNAVAILABLE_ERROR);\n }\n return this.#signerBridge;\n };\n\n readonly #getSignerBridge = (): LighterSignerBridge => {\n if (!this.#signerBridge) {\n throw new Error(LIGHTER_SIGNER_UNAVAILABLE_ERROR);\n }\n const bridge = this.#signerBridge;\n // The WASM client lives inside the bridge host (mobile: a WebView that\n // can reload and lose it). When the venue signer reports a missing\n // client, drop the cached session so the next call re-runs setup\n // instead of failing forever against a resolved-but-dead session.\n return {\n createClient: async (params): Promise<LighterCreateClientResult> => {\n try {\n const result = await bridge.createClient(params);\n if (result.error) {\n this.#invalidateSignerSession();\n }\n return result;\n } catch (error) {\n this.#invalidateSignerSession();\n throw error;\n }\n },\n execute: async <Operation extends LighterSignerOperation>(\n call: LighterWasmCall<Operation>,\n ): Promise<LighterSignerResult<Operation>> => {\n const lostClientPattern =\n /client is not created|WebView reloaded|signer not ready|executor not connected|timed out/iu;\n try {\n const result = await bridge.execute(call);\n const error = (result as { error?: string } | null)?.error;\n if (error && lostClientPattern.test(error)) {\n this.#invalidateSignerSession();\n }\n return result;\n } catch (error) {\n if (lostClientPattern.test(String(error))) {\n this.#invalidateSignerSession();\n }\n throw error;\n }\n },\n };\n };\n\n readonly #invalidateSignerSession = (): void => {\n // Advancing the generation aborts any in-flight setup/write that was\n // started against the now-dead WASM client.\n this.#sessionGeneration += 1;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#clearBridgeOwnership();\n this.#deps.debugLogger.log(\n '[LighterProvider] signer session invalidated (client lost); will re-setup on next call',\n );\n };\n\n /** Replace this provider's listener on the client-owned signer bridge. */\n readonly #replaceSignerResetListener = (): void => {\n this.#removeSignerResetListener();\n this.#ensureSignerResetListener();\n };\n\n /** Install the reset listener when the current binding has none. */\n readonly #ensureSignerResetListener = (): void => {\n if (this.#isDisconnected || this.#signerResetUnsubscribe) {\n return;\n }\n this.#signerResetUnsubscribe =\n this.#signerBridge?.onReset?.(() => this.#invalidateSignerSession()) ??\n null;\n };\n\n /** Remove this provider's listener when its session is retired. */\n readonly #removeSignerResetListener = (): void => {\n this.#signerResetUnsubscribe?.();\n this.#signerResetUnsubscribe = null;\n };\n\n /**\n * Drop ALL bridge-client ownership material for this provider: the\n * identity, the recreate params, and — when WE are the recorded owner\n * — the process-wide ownership entry, so a dead/rebound session can\n * never be mistaken for the live owner of the singleton client.\n */\n readonly #clearBridgeOwnership = (): void => {\n if (\n this.#signerBridge &&\n this.#signerIdentity !== null &&\n bridgeClientOwners.get(this.#signerBridge) === this.#signerIdentity\n ) {\n bridgeClientOwners.delete(this.#signerBridge);\n }\n this.#signerIdentity = null;\n this.#signerRecreateParams = null;\n };\n\n /**\n * Bind the venue session to the currently selected wallet address.\n *\n * Everything downstream — account index, venue signer, auth token, and\n * the account-scoped stream channels — is derived from one L1 address.\n * When the wallet switches accounts, all of it must be dropped\n * atomically or reads/writes would keep targeting the previous account.\n */\n readonly #ensureSessionBinding = (): void => {\n if (this.#isDisconnected) {\n return;\n }\n let address: string;\n try {\n address = this.#walletService.getUserAddress().toLowerCase();\n } catch {\n if (this.#boundAddress !== null) {\n // All accounts deselected while a session existed: invalidate so\n // nothing in flight can still act for the old account.\n this.#emitAccountBindingReset();\n this.#invalidateSessionState();\n this.#removeSignerResetListener();\n this.#teardownStream();\n }\n // The caller's own address resolution surfaces the error.\n return;\n }\n if (this.#boundAddress === address) {\n return;\n }\n const hadPreviousBinding = this.#boundAddress !== null;\n this.#boundAddress = address;\n if (!hadPreviousBinding) {\n this.#ensureSignerResetListener();\n // First binding (or first after a deselection): surviving\n // subscribers may be sitting on an empty channel set.\n if (this.#hasAnySubscriber() && this.#wsWantedChannels.size === 0) {\n this.#rebuildStreamForSubscribers();\n }\n return;\n }\n // Invalidate in-flight async resolutions started under the previous\n // binding: they compare this generation after their awaits and retry\n // instead of caching results for the wrong account.\n this.#sessionGeneration += 1;\n this.#accountIndex = null;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#replaceSignerResetListener();\n // #tpslUnsettled is NOT cleared: entries are keyed by\n // address+accountIndex+symbol, so B never consumes A's pending ids and\n // switching back to A retains its reconciliation obligation.\n this.#emitAccountBindingReset();\n this.#teardownStream();\n this.#rebuildStreamForSubscribers();\n this.#deps.debugLogger.log(\n '[LighterProvider] session rebound to new wallet account',\n );\n };\n\n /** Clear subscriber-visible account data before a wallet rebind. */\n readonly #emitAccountBindingReset = (): void => {\n for (const subscriber of this.#accountSubscribers) {\n try {\n subscriber.callback(EMPTY_ACCOUNT_STATE);\n } catch (error) {\n this.#logSubscriberError('account', error);\n }\n }\n for (const subscriber of this.#positionSubscribers) {\n try {\n subscriber.callback([]);\n } catch (error) {\n this.#logSubscriberError('positions', error);\n }\n }\n this.#emitToOrderSubscribers([]);\n };\n\n /**\n * Re-request every channel the current subscriber registries imply.\n *\n * #teardownStream clears the wanted-channel intents; without this,\n * subscribers that outlive an account switch would sit on a fresh socket\n * subscribed to nothing.\n */\n readonly #rebuildStreamForSubscribers = (): void => {\n if (this.#isDisconnected || !this.#hasAnySubscriber()) {\n return;\n }\n if (this.#priceSubscribers.size > 0 || this.#oiCapSubscribers.size > 0) {\n this.#requestChannel('market_stats/all');\n }\n for (const marketId of this.#orderBookSubscribers.keys()) {\n this.#requestChannel(`order_book/${marketId}`);\n }\n for (const seriesKey of this.#candleSubscribers.keys()) {\n // Series keys are `${marketId}:${resolution}`; the channel form uses\n // slashes. The teardown cleared the series state, and the message\n // router drops updates for unknown series — recreate an empty series\n // so live candles flow again (history reseeds on the next fetch).\n this.#candleSeries.set(seriesKey, new Map());\n this.#requestChannel(`candle/${seriesKey.replace(':', '/')}`);\n }\n if (\n this.#accountSubscribers.size > 0 ||\n this.#positionSubscribers.size > 0 ||\n this.#orderSubscribers.size > 0 ||\n this.#fillSubscribers.size > 0\n ) {\n // The promise was cleared by the teardown, so this re-resolves the\n // account channels against the newly bound address.\n this.#ensureAccountChannels();\n }\n this.#ensureStream();\n };\n\n /**\n * Resolve the Lighter account index for the current user.\n *\n * @returns The account index.\n */\n readonly #ensureAccountIndex = async (): Promise<number> => {\n this.#ensureSessionBinding();\n // Account-bound work requires a bound wallet — including the cached\n // fast path and the configured-index path.\n this.#assertSession(this.#sessionGeneration);\n if (this.#accountIndex !== null) {\n return this.#accountIndex;\n }\n if (this.#configuredAccountIndex !== undefined) {\n // A configured index must be a Standard (0-fee) account AND owned by\n // the bound wallet address: a signed-in wallet must never read or\n // trade another owner's account just because an env var names it.\n const generationAtCheck = this.#sessionGeneration;\n const configured = await this.#clientService.getAccountByIndex(\n this.#configuredAccountIndex,\n );\n this.#ensureSessionBinding();\n if (generationAtCheck !== this.#sessionGeneration) {\n return await this.#ensureAccountIndex();\n }\n const configuredAccount = configured.accounts[0];\n this.#assertStandardAccount(configuredAccount?.accountType);\n const ownerAddress = configuredAccount?.l1Address?.toLowerCase();\n if (!ownerAddress || ownerAddress !== this.#boundAddress) {\n // Capability-prefixed so read catches SURFACE it instead of\n // degrading a cross-owner misconfiguration into empty state.\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} configured account ${this.#configuredAccountIndex} is not owned by the selected wallet address`,\n );\n }\n this.#accountIndex = this.#configuredAccountIndex;\n return this.#accountIndex;\n }\n const generation = this.#sessionGeneration;\n const address = this.#walletService.getUserAddress();\n let response: LighterAccountsByL1AddressResponse;\n try {\n response = await this.#clientService.getAccountsByL1Address(address);\n } catch (error) {\n if (error instanceof LighterApiError && error.code === 21100) {\n throw new LighterAccountNotFoundError(address);\n }\n throw error;\n }\n // Re-run the binding so an EXTERNAL switch nothing else observed also\n // advances the generation, then compare: caching after any switch\n // would poison the new session with the old account. Retry instead.\n this.#ensureSessionBinding();\n if (generation !== this.#sessionGeneration) {\n return await this.#ensureAccountIndex();\n }\n if (!response.subAccounts?.length) {\n throw new LighterAccountNotFoundError(address);\n }\n const master = response.subAccounts.reduce((min, account) =>\n account.index < min.index ? account : min,\n );\n this.#assertStandardAccount(master.accountType);\n this.#accountIndex = master.index;\n return this.#accountIndex;\n };\n\n /**\n * Capability gate: only Standard (0-fee) Lighter accounts are supported.\n * Premium accounts pay nonzero maker/taker fees whose wire unit is\n * unverified — serving their history would show financially false zero\n * fees, so the whole account-bound surface refuses instead.\n *\n * @param accountType - Venue account type code (0 = Standard).\n */\n readonly #assertStandardAccount = (accountType: number | undefined): void => {\n // Fail closed: only a PROVEN Standard (type 0) account passes. A\n // missing account/type is not evidence of Standard.\n if (accountType === undefined) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} account type could not be verified (account not found); refusing to assume a Standard account`,\n );\n }\n if (accountType !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} Premium accounts are not supported yet: their fee semantics are unverified and history would be financially incorrect`,\n );\n }\n };\n\n /**\n * Whether an error is an explicit capability gate (unsupported account\n * tier / unverified fee semantics). These must SURFACE to callers —\n * swallowing them into empty state would present false data.\n *\n * @param error - Caught error.\n * @returns True for capability-gate errors.\n */\n readonly #isUnsupportedCapabilityError = (error: unknown): boolean =>\n String(error).includes(LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX);\n\n readonly #isDataIntegrityError = (error: unknown): boolean =>\n String(error).includes(LIGHTER_DATA_INTEGRITY_PREFIX);\n\n /**\n * Whether a read error represents an explicit non-empty state.\n *\n * @param error - Caught read error.\n * @returns Whether the error must surface to the caller.\n */\n readonly #mustSurfaceReadError = (error: unknown): boolean =>\n this.#isUnsupportedCapabilityError(error) ||\n this.#isDataIntegrityError(error);\n\n /**\n * TP/SL settlement expectations that timed out before becoming visible\n * on the venue's REST book, per symbol. While an entry exists, further\n * TP/SL mutations for that symbol must reconcile it first.\n */\n readonly #tpslUnsettled = new Map<string, TpslJournalState>();\n\n /**\n * Session-global nonce reservation per `accountIndex:apiKeyIndex`.\n * Advanced at submission DISPATCH; consulted by every write-lock\n * section so a lagging nextNonce endpoint can never reissue a nonce an\n * earlier (possibly response-lost) submission may have consumed. A\n * reconciliation that PROVES a submission never landed (exact-hash\n * not-found after signed expiry) releases the reservation again.\n */\n readonly #nonceReservations = new Map<string, number>();\n\n /** Monotonic source for journal operation ids within this session. */\n #tpslOperationCounter = 0;\n\n /** This provider's bridge-client ownership identity (set at setup). */\n #signerIdentity: string | null = null;\n\n /**\n * Parameters to re-create OUR venue client on the shared bridge. The\n * wallet-derived seed is NEVER retained here — it is re-derived under\n * the bridge lease each time re-establishment is needed.\n */\n #signerRecreateParams: {\n chainId: number;\n accountIndex: number;\n } | null = null;\n\n /**\n * Durable dispatch-ledger key: every nonce-consuming submission is\n * recorded here BEFORE dispatch so a restart can never reissue a nonce\n * whose outcome is unknown, and a proven never-landed dispatch can\n * release its nonce for the venue to consume.\n *\n * @param accountIndex - Venue account index.\n * @returns The disk-cache key.\n */\n readonly #nonceLedgerKey = (accountIndex: number): string =>\n `lighterNonceLedger:${this.#isTestnet ? 'testnet' : 'mainnet'}:${accountIndex}:${this.#apiKeyIndex}`;\n\n /**\n * Read and strictly validate the durable dispatch ledger. Corruption\n * fails CLOSED (writes stay blocked) — guessing at nonce state could\n * duplicate or wedge submissions.\n *\n * @param accountIndex - Venue account index.\n * @returns The ledger document (consumed-nonce watermark + unresolved\n * dispatch entries).\n */\n readonly #readNonceLedger = async (\n accountIndex: number,\n ): Promise<LighterNonceLedgerDoc> => {\n let raw: string | null;\n try {\n raw = await this.#deps.diskCache.getItem(\n this.#nonceLedgerKey(accountIndex),\n );\n } catch (error) {\n throw new Error(\n `Lighter nonce ledger read failed; refusing writes: ${ensureError(error, 'LighterProvider.#readNonceLedger').message}`,\n );\n }\n if (raw === null) {\n return { consumedFloor: 0, entries: [], recovered: [] };\n }\n try {\n const parsed = JSON.parse(raw) as {\n version?: unknown;\n consumedFloor?: unknown;\n entries?: unknown;\n recovered?: unknown;\n };\n // EXPLICIT schema evolution: earlier documents (v1 without the\n // consumed watermark, v2 without operation kind/intent) migrate in\n // place — calling valid outstanding dispatch state corrupt would\n // block writes permanently.\n const consumedFloor =\n parsed.version === 1 && parsed.consumedFloor === undefined\n ? 0\n : parsed.consumedFloor;\n if (\n (parsed.version === 1 ||\n parsed.version === 2 ||\n parsed.version === 3 ||\n parsed.version === 4) &&\n typeof consumedFloor === 'number' &&\n Number.isSafeInteger(consumedFloor) &&\n consumedFloor >= 0 &&\n Array.isArray(parsed.entries) &&\n parsed.entries.length <= 16 &&\n parsed.entries.every((entry) => {\n if (typeof entry !== 'object' || entry === null) {\n return false;\n }\n const candidate = entry as Record<string, unknown>;\n return (\n typeof candidate.nonce === 'number' &&\n Number.isSafeInteger(candidate.nonce) &&\n candidate.nonce >= 0 &&\n (candidate.txHash === null ||\n typeof candidate.txHash === 'string') &&\n (candidate.expiresAt === null ||\n (typeof candidate.expiresAt === 'number' &&\n Number.isSafeInteger(candidate.expiresAt) &&\n candidate.expiresAt > 0))\n );\n })\n ) {\n // v4 recovered outcomes are safety state: silently dropping a\n // malformed or overflow row could make a completed/unknown\n // financial intent retryable. Older schemas predate the list.\n const recoveredRaw = parsed.version === 4 ? parsed.recovered : [];\n if (\n !Array.isArray(recoveredRaw) ||\n recoveredRaw.length > LIGHTER_RECOVERED_DISPATCH_LIMIT ||\n !recoveredRaw.every((row): row is LighterRecoveredDispatch => {\n if (typeof row !== 'object' || row === null) {\n return false;\n }\n const candidate = row as Record<string, unknown>;\n return (\n typeof candidate.recoveryId === 'string' &&\n candidate.recoveryId.length >= 1 &&\n candidate.recoveryId.length <= 160 &&\n typeof candidate.kind === 'number' &&\n typeof candidate.intent === 'string' &&\n candidate.intent.length <= 200 &&\n (candidate.txHash === null ||\n typeof candidate.txHash === 'string') &&\n (candidate.outcome === 'succeeded' ||\n candidate.outcome === 'failed' ||\n candidate.outcome === 'unknown') &&\n typeof candidate.evidence === 'string'\n );\n })\n ) {\n throw new Error('Malformed recovered-dispatch safety state');\n }\n const recovered = recoveredRaw;\n return {\n consumedFloor,\n entries: (\n parsed.entries as {\n nonce: number;\n txHash: string | null;\n expiresAt: number | null;\n kind?: number;\n intent?: string;\n owner?: string | null;\n }[]\n ).map((entry) => ({\n ...entry,\n // v1-v3 migration: kind/intent/owner unknown.\n kind: typeof entry.kind === 'number' ? entry.kind : -1,\n intent: typeof entry.intent === 'string' ? entry.intent : 'unknown',\n owner: typeof entry.owner === 'string' ? entry.owner : null,\n })),\n recovered,\n };\n }\n } catch {\n // fall through to fail closed\n }\n throw new Error(\n 'Lighter nonce dispatch ledger is corrupt; refusing further writes until it is resolved',\n );\n };\n\n /**\n * Persist the dispatch ledger document.\n *\n * @param accountIndex - Venue account index.\n * @param doc - The ledger document.\n * @param doc.consumedFloor - Highest proven-consumed nonce + 1.\n * @param doc.entries - Unresolved dispatch entries.\n */\n readonly #writeNonceLedger = async (\n accountIndex: number,\n doc: LighterNonceLedgerDoc,\n ): Promise<void> => {\n await this.#deps.diskCache.setItem(\n this.#nonceLedgerKey(accountIndex),\n JSON.stringify({ version: 4, ...doc }),\n );\n };\n\n /**\n * Resolve one dispatch entry as CONSUMED: remove it and advance the\n * durable consumed-nonce watermark so no later (stale) reconciliation\n * can ever release the nonce back.\n *\n * @param accountIndex - Venue account index.\n * @param entry - The consumed entry.\n * @param entry.nonce - The dispatched nonce.\n * @param entry.txHash - The dispatched tx hash (or null).\n */\n /**\n * EVERY ledger read-modify-write (append, resolve, consumed-resolve,\n * selective acknowledgment) serializes on this ONE process-wide mutex\n * per account+slot document. The venue write mutex alone cannot\n * protect the document: `acknowledgeRecoveredDispatch` legitimately\n * runs OUTSIDE it, and an unserialized ack RMW could overwrite a\n * concurrent append with a stale doc — silently erasing an unresolved\n * dispatch entry. Lock order is always venueWrite → bridge → ledger\n * (the ack path takes only the ledger mutex), so no cycle exists.\n *\n * @param accountIndex - Venue account index.\n * @param operation - The ledger RMW critical section.\n * @returns The operation's result.\n */\n readonly #withLedgerLock = async <Result>(\n accountIndex: number,\n operation: () => Promise<Result>,\n ): Promise<Result> =>\n await withProcessMutex(this.#nonceLedgerKey(accountIndex), operation);\n\n /**\n * Append a recovered dispatch without ever sacrificing a blocking\n * succeeded/unknown outcome to bounded storage. Retry-safe failures may\n * be omitted at capacity; a blocking outcome may replace one such row.\n * If every retained row is already blocking, fail before persistence so\n * the original unresolved ledger entry remains authoritative.\n *\n * @param doc - Mutable nonce ledger document held under its mutex.\n * @param outcome - Recovered dispatch to retain when safety requires it.\n */\n readonly #appendRecoveredDispatch = (\n doc: LighterNonceLedgerDoc,\n outcome: LighterRecoveredDispatch,\n ): void => {\n if (\n doc.recovered.some(\n (candidate) => candidate.recoveryId === outcome.recoveryId,\n )\n ) {\n return;\n }\n if (doc.recovered.length < LIGHTER_RECOVERED_DISPATCH_LIMIT) {\n doc.recovered.push(outcome);\n return;\n }\n if (outcome.outcome === 'failed') {\n return;\n }\n const failedIndex = doc.recovered.findIndex(\n (candidate) => candidate.outcome === 'failed',\n );\n if (failedIndex < 0) {\n throw new Error(\n 'Lighter recovered-dispatch ledger is full of unresolved blocking outcomes; refusing to discard the current dispatch',\n );\n }\n doc.recovered.splice(failedIndex, 1, outcome);\n };\n\n /**\n * ATOMIC post-dispatch entry transition, decided by the session fence\n * BEFORE any ledger mutation: fence passed → the entry is consumed and\n * removed (watermark advances); fence failed → the entry converts to a\n * durable recovered SUCCEEDED outcome (the venue mutation is committed\n * and a later retry under the original account would double the\n * financial intent). Both shapes land in ONE write under the ledger\n * lock — if that write fails, the ORIGINAL unresolved entry remains\n * the durable record and every retry stays blocked. The entry is never\n * consumed first and quarantined second. TP/SL-journal-owned entries\n * are consumed without quarantine in both cases (their machine\n * reconciles the intent by exact hash).\n *\n * @param accountIndex - Venue account index of the ORIGINAL session.\n * @param entry - The dispatched (accepted) ledger entry.\n * @param fenceFailed - Whether the post-send session fence rejected.\n * @returns Resolves when the transition is durably committed.\n */\n readonly #resolveEntryPostDispatch = async (\n accountIndex: number,\n entry: LighterNonceLedgerDoc['entries'][number],\n fenceFailed: boolean,\n ): Promise<void> =>\n await this.#withLedgerLock(accountIndex, async () => {\n const doc = await this.#readNonceLedger(accountIndex);\n const at = doc.entries.findIndex(\n (candidate) =>\n candidate.nonce === entry.nonce && candidate.txHash === entry.txHash,\n );\n if (at >= 0) {\n doc.entries.splice(at, 1);\n }\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n if (fenceFailed && entry.owner === null) {\n const recoveryId = `${String(entry.nonce)}:${entry.txHash ?? 'nohash'}`;\n this.#appendRecoveredDispatch(doc, {\n recoveryId,\n kind: entry.kind,\n intent: entry.intent,\n txHash: entry.txHash,\n outcome: 'succeeded',\n evidence: 'post-dispatch-session-cancelled',\n });\n }\n await this.#writeNonceLedger(accountIndex, doc);\n });\n\n /**\n * Resolve every unresolved dispatch before a write section may issue\n * nonces. Consumption is proven by REST-nonce advance or an exact tx\n * lookup verifying the FULL identity (hash + account + api-key slot +\n * nonce + a numeric venue status); never-landed is proven ONLY by\n * venue-confirmed absence of the exact HASH after the signed validity\n * elapsed. A hashless dispatch can never be proven absent — it stays\n * blocking until the venue advances. Ambiguity blocks the write.\n * Runs under the account+slot ledger lock.\n *\n * @param accountIndex - Venue account index.\n * @returns Resolves when every prior dispatch is accounted for.\n */\n readonly #resolveNonceLedger = async (accountIndex: number): Promise<void> =>\n await this.#withLedgerLock(accountIndex, async () =>\n this.#resolveNonceLedgerLocked(accountIndex),\n );\n\n /**\n * @param accountIndex - Venue account index.\n * @returns Resolves when the pass completes.\n */\n readonly #resolveNonceLedgerLocked = async (\n accountIndex: number,\n ): Promise<void> => {\n const doc = await this.#readNonceLedger(accountIndex);\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n // The durable consumed watermark always seeds the memory floor.\n if (doc.consumedFloor > 0) {\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, doc.consumedFloor),\n );\n }\n // QUARANTINE CHECK FIRST: unacknowledged recovered outcomes block\n // EVERY retry, including retries arriving when no unresolved\n // entries remain — an early empty-entries return here would let the\n // second retry sail past the quarantine.\n const throwIfQuarantined = (): void => {\n const blocking = doc.recovered.filter(\n (outcome) => outcome.outcome !== 'failed',\n );\n if (blocking.length > 0) {\n throw new Error(\n `A previous Lighter submission believed failed actually ${blocking.some((outcome) => outcome.outcome === 'succeeded') ? 'completed' : 'landed with an UNKNOWN outcome'} (${blocking\n .map((outcome) => outcome.intent)\n .join(\n ', ',\n )}); refresh state and call acknowledgeRecoveredDispatch before retrying`,\n );\n }\n };\n throwIfQuarantined();\n if (doc.entries.length === 0) {\n return;\n }\n const quarantine = (\n entry: LighterNonceLedgerDoc['entries'][number],\n outcome: LighterRecoveredDispatch['outcome'],\n evidence: string,\n ): void => {\n // TP/SL-journal-OWNED dispatches resolve through their own state\n // machine (journal attempts + exact-hash reconciliation) — they\n // are never parked behind the generic acknowledgment.\n if (entry.owner !== null) {\n return;\n }\n this.#appendRecoveredDispatch(doc, {\n recoveryId: `${String(entry.nonce)}:${entry.txHash ?? 'nohash'}`,\n kind: entry.kind,\n intent: entry.intent,\n txHash: entry.txHash,\n outcome,\n evidence,\n });\n };\n const nonceResponse = await this.#clientService.getNextNonce(\n accountIndex,\n this.#apiKeyIndex,\n );\n const remaining: typeof doc.entries = [];\n for (const entry of doc.entries) {\n if (entry.txHash === null && nonceResponse.nonce > entry.nonce) {\n // Only the nonce ADVANCE is proven (possibly by another device):\n // the intent's own fate is UNKNOWN — never reported completed.\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n quarantine(entry, 'unknown', 'rest-advance');\n continue;\n }\n if (entry.txHash !== null) {\n let lookedUp: LighterTxLookupResponse | null;\n try {\n lookedUp = await this.#clientService.getTx(entry.txHash);\n } catch {\n // Lookup failure is AMBIGUITY, never evidence either way: the\n // entry stays and the write remains blocked.\n remaining.push(entry);\n continue;\n }\n if (lookedUp !== null) {\n const matchesIdentity =\n typeof lookedUp.hash === 'string' &&\n lookedUp.hash.toLowerCase().replace(/^0x/u, '') ===\n entry.txHash.toLowerCase().replace(/^0x/u, '') &&\n lookedUp.accountIndex === accountIndex &&\n lookedUp.apiKeyIndex === this.#apiKeyIndex &&\n lookedUp.nonce === entry.nonce &&\n typeof lookedUp.status === 'number';\n if (matchesIdentity) {\n const transactionOutcome = getLighterTransactionOutcome(\n lookedUp.status,\n );\n // A matching hash is not enough to prove the transaction's\n // outcome. Non-terminal statuses must retain the unresolved\n // entry so no acknowledgment can make the intent retryable\n // while the original transaction is still in flight.\n if (\n transactionOutcome !== 'failed' &&\n transactionOutcome !== 'executed'\n ) {\n remaining.push(entry);\n continue;\n }\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n // The EXACT tx status decides the intent's fate: executed →\n // succeeded (blocking until acknowledged); failed/rejected →\n // retry-safe FAILURE (recorded, non-blocking); anything else\n // still pending → keep blocking as unresolved.\n if (transactionOutcome === 'failed') {\n quarantine(\n entry,\n 'failed',\n `tx-status:${String(lookedUp.status)}`,\n );\n } else {\n quarantine(\n entry,\n 'succeeded',\n `tx-status:${String(lookedUp.status)}`,\n );\n }\n continue;\n }\n // A DIFFERENT payload under this hash: ambiguity, fail closed.\n remaining.push(entry);\n continue;\n }\n if (nonceResponse.nonce > entry.nonce) {\n // The venue moved past this nonce while OUR exact hash is\n // absent: another dispatch (e.g. a second device) consumed it.\n // Our payload can never land now — retry-safe never-landed,\n // no quarantine; the floor advances with the venue.\n doc.consumedFloor = Math.max(doc.consumedFloor, entry.nonce + 1);\n const floor = this.#nonceReservations.get(reservationKey) ?? 0;\n this.#nonceReservations.set(\n reservationKey,\n Math.max(floor, entry.nonce + 1),\n );\n continue;\n }\n if (\n entry.expiresAt !== null &&\n Date.now() > entry.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS\n ) {\n // Venue-confirmed absent after the signed validity: PROVEN\n // never landed — the venue still expects this nonce (unless a\n // later dispatch already consumed it: consumedFloor guards).\n if (entry.nonce >= doc.consumedFloor) {\n this.#releaseNonceReservation(accountIndex, entry.nonce);\n }\n continue;\n }\n }\n // Hashless, or hash present but unexpired-and-absent: ambiguous.\n remaining.push(entry);\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: remaining,\n recovered: doc.recovered,\n });\n if (remaining.length > 0) {\n throw new Error(\n 'A previous Lighter submission has an unresolved outcome; writes are blocked until it can be proven consumed or never-landed',\n );\n }\n // RECOVERED-OUTCOME quarantine: succeeded/unknown outcomes block\n // every subsequent write until selectively acknowledged (a blind\n // retry could double the financial intent). FAILED outcomes are\n // retry-safe and never block.\n throwIfQuarantined();\n };\n\n /**\n * List TP/SL obligations parked in DURABLE manual-recovery state: the\n * venue removed (or rejected) protection in a way that cannot be\n * safely re-established automatically. Surfaced to callers/UI; each\n * entry resolves when the user issues a new explicit TP/SL update for\n * the symbol.\n *\n * @returns Parked manual-recovery entries.\n */\n async getPendingManualRecoveries(): Promise<\n {\n symbol: string;\n settlementKey: string;\n recordedAt: number;\n reason: string;\n priorIntent: 'replace' | 'remove';\n survivingOrderIds: string[];\n actionNeeded: string;\n }[]\n > {\n this.#ensureSessionBinding();\n const accountIndex = await this.#ensureAccountIndex();\n // ONLY the bound identity's parked warnings: another account's (or\n // api key's) protection state must never leak into this session.\n const identityPrefix = `${this.#boundAddress ?? 'unbound'}:${accountIndex}:${this.#apiKeyIndex}:`;\n const pending: {\n symbol: string;\n settlementKey: string;\n recordedAt: number;\n reason: string;\n priorIntent: 'replace' | 'remove';\n survivingOrderIds: string[];\n actionNeeded: string;\n }[] = [];\n const actionNeeded =\n 'Review the position and submit a new explicit TP/SL update for this symbol to re-establish protection';\n // Storage errors PROPAGATE — a corrupt index degrading to \"nothing\n // pending\" would hide a naked position.\n const manualIndex = await this.#readTpslManualIndex();\n for (const settlementKey of manualIndex) {\n if (!settlementKey.startsWith(identityPrefix)) {\n continue;\n }\n const doc = await this.#loadTpslManualRecovery(settlementKey);\n if (doc) {\n pending.push({\n symbol: doc.symbol,\n settlementKey,\n recordedAt: doc.recordedAt,\n reason: doc.reason,\n priorIntent: doc.priorIntent,\n survivingOrderIds: doc.survivingOrderIds,\n actionNeeded,\n });\n }\n }\n // Legacy: journals parked 'manual' in the journal slot by an earlier\n // version (migrated to the doc on the next settle pass).\n const journalIndex = await this.#readTpslJournalIndex();\n for (const settlementKey of journalIndex) {\n if (\n !settlementKey.startsWith(identityPrefix) ||\n pending.some((entry) => entry.settlementKey === settlementKey)\n ) {\n continue;\n }\n const journal = await this.#loadTpslJournal(settlementKey);\n if (journal?.phase === 'manual') {\n pending.push({\n symbol: settlementKey.split(':').at(-1) ?? settlementKey,\n settlementKey,\n recordedAt: journal.recordedAt,\n reason:\n 'TP/SL protection could not be safely re-established automatically (parked by an earlier session)',\n priorIntent: journal.intent,\n survivingOrderIds: [],\n actionNeeded,\n });\n }\n }\n return pending;\n }\n\n /**\n * READ-ONLY view of the durable recovered-dispatch outcomes\n * (previously ambiguous submissions later resolved). Never mutates the\n * ledger — acknowledgment is a separate, per-outcome call so a crash\n * between reading and acting can never silently drop an outcome.\n *\n * @returns The pending recovered-dispatch outcomes.\n */\n async getRecoveredDispatches(): Promise<LighterRecoveredDispatch[]> {\n this.#ensureSessionBinding();\n const accountIndex = await this.#ensureAccountIndex();\n const doc = await this.#readNonceLedger(accountIndex);\n return doc.recovered.map((outcome) => ({ ...outcome }));\n }\n\n /**\n * Acknowledge ONE recovered-dispatch outcome by its stable id, after\n * the caller has refreshed venue state and decided how to proceed.\n * Runs under the ledger mutex and re-verifies the session generation\n * inside it so an account switch mid-acknowledge can never clear\n * another account's outcome.\n *\n * @param recoveryId - Stable id from {@link getRecoveredDispatches}.\n */\n async acknowledgeRecoveredDispatch(recoveryId: string): Promise<void> {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n await withProcessMutex(this.#nonceLedgerKey(accountIndex), async () => {\n this.#ensureSessionBinding();\n this.#assertSession(generation);\n const doc = await this.#readNonceLedger(accountIndex);\n const remaining = doc.recovered.filter(\n (outcome) => outcome.recoveryId !== recoveryId,\n );\n if (remaining.length === doc.recovered.length) {\n throw new Error(\n `No pending recovered Lighter dispatch matches id ${recoveryId}; refresh and re-read before acknowledging`,\n );\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: doc.entries,\n recovered: remaining,\n });\n });\n }\n\n /**\n * Release a nonce reservation for a PROVEN never-landed dispatch —\n * refused when the durable consumed watermark shows a later dispatch\n * (e.g. a retry) already consumed the nonce.\n *\n * @param accountIndex - Venue account index.\n * @param nonce - The proven-unconsumed nonce.\n */\n readonly #releaseNonceReservationIfUnconsumed = async (\n accountIndex: number,\n nonce: number,\n ): Promise<void> => {\n const doc = await this.#readNonceLedger(accountIndex).catch(() => null);\n if (doc === null || nonce < doc.consumedFloor) {\n return;\n }\n this.#releaseNonceReservation(accountIndex, nonce);\n };\n\n /**\n * Durable TP/SL journal key (network + address + accountIndex + symbol\n * scoped): the in-memory map alone cannot survive app/WebView/provider\n * death between venue commit and visibility.\n *\n * @param settlementKey - address:accountIndex:symbol identity.\n * @returns The disk-cache key.\n */\n readonly #tpslJournalKey = (settlementKey: string): string =>\n `lighterTpslJournal:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`;\n\n /**\n * Operation-scoped journal payload key: each operation's journal lives\n * under its OWN key so a stale resolver physically cannot overwrite or\n * delete a newer operation's payload — only its own.\n *\n * @param settlementKey - Settlement identity.\n * @param operationId - The operation identity.\n * @returns The disk-cache key.\n */\n readonly #tpslJournalOpKey = (\n settlementKey: string,\n operationId: string,\n ): string =>\n `lighterTpslJournalOp:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}:${operationId}`;\n\n /**\n * Load and strictly validate a persisted journal entry. Malformed or\n * unsupported disk data BLOCKS protection changes (fail closed) — it is\n * never trusted into signing decisions nor silently dropped.\n *\n * @param settlementKey - Settlement identity.\n * @returns The validated entry, or null.\n */\n readonly #loadTpslJournal = async (\n settlementKey: string,\n ): Promise<TpslJournalState | null> => {\n const key = this.#tpslJournalKey(settlementKey);\n // FAIL CLOSED on read failure and on corruption: turning either into\n // \"no entry\" would erase exactly the uncertainty this journal exists\n // to preserve and could duplicate a committed mutation. Malformed\n // data is NOT auto-removed — it blocks until inspected/resolved.\n let baseRaw: string | null;\n try {\n baseRaw = await this.#deps.diskCache.getItem(key);\n } catch (error) {\n throw new Error(\n `Lighter TP/SL journal read failed for ${settlementKey}; refusing protection changes: ${ensureError(error, 'LighterProvider.#loadTpslJournal').message}`,\n );\n }\n if (baseRaw === null) {\n return null;\n }\n // The base key holds either a POINTER to an operation-scoped payload\n // (code-written journals: a stale writer physically cannot destroy a\n // newer operation's payload) or a legacy inline journal.\n let raw = baseRaw;\n const pointer = parseTpslJournalPointer(baseRaw);\n if (pointer !== null) {\n const payloadRaw = await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, pointer.operationId),\n );\n if (payloadRaw === null) {\n // Dangling pointer (payload already resolved elsewhere).\n return null;\n }\n raw = payloadRaw;\n }\n let parsed: {\n version?: unknown;\n recordedAt?: unknown;\n operationId?: unknown;\n createdAt?: unknown;\n nextAttemptId?: unknown;\n apiKeyIndex?: unknown;\n intent?: unknown;\n phase?: unknown;\n priorGrouping?: unknown;\n priorTriggers?: unknown;\n attempts?: unknown;\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} is corrupt; refusing protection changes until it is resolved`,\n );\n }\n const isWireId = (value: unknown): boolean =>\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value > 0 &&\n value < 2 ** 48;\n const isNonce = (value: unknown): boolean =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n const isOrderIdString = (value: unknown): boolean =>\n typeof value === 'string' && /^\\d{1,20}$/u.test(value);\n const isTxHash = (value: unknown): boolean =>\n typeof value === 'string' && /^(0x)?[0-9a-fA-F]{8,128}$/u.test(value);\n const isExpiry = (value: unknown): boolean =>\n typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n const isAttempt = (value: unknown): value is TpslAttempt => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const attempt = value as Record<string, unknown>;\n if (\n !isNonce(attempt.nonce) ||\n typeof attempt.attemptId !== 'number' ||\n !Number.isSafeInteger(attempt.attemptId) ||\n attempt.attemptId < 1 ||\n (attempt.terminalStatus !== undefined &&\n (typeof attempt.terminalStatus !== 'number' ||\n !Number.isSafeInteger(attempt.terminalStatus))) ||\n (attempt.outcome !== 'unknown' && attempt.outcome !== 'accepted') ||\n !isTxHash(attempt.txHash) ||\n !isExpiry(attempt.expiresAt)\n ) {\n return false;\n }\n if (attempt.kind === 'create') {\n return (\n attempt.orderId === undefined &&\n (attempt.role === 'replacement' || attempt.role === 'restore') &&\n // priorOrderIds durably key WHICH prior intents a restore\n // restores, INDEX-ALIGNED with clientIds; REQUIRED on\n // restores, forbidden on replacements.\n (attempt.role === 'restore'\n ? Array.isArray(attempt.priorOrderIds) &&\n Array.isArray(attempt.clientIds) &&\n attempt.priorOrderIds.length === attempt.clientIds.length &&\n attempt.priorOrderIds.every(isOrderIdString)\n : attempt.priorOrderIds === undefined) &&\n Array.isArray(attempt.clientIds) &&\n attempt.clientIds.length >= 1 &&\n attempt.clientIds.length <= 2 &&\n attempt.clientIds.every(isWireId) &&\n new Set(attempt.clientIds).size === attempt.clientIds.length\n );\n }\n if (attempt.kind === 'cancel') {\n return (\n attempt.clientIds === undefined &&\n (attempt.role === 'stale' || attempt.role === 'rollback') &&\n isOrderIdString(attempt.orderId)\n );\n }\n return false;\n };\n // Recovery SIGNS from these values: they must be strict, finite and\n // strictly positive before they can reach the wire.\n const isPositiveDecimalString = (value: unknown): boolean => {\n if (typeof value !== 'string') {\n return false;\n }\n const numeric = parseStrictDecimal(value);\n return numeric !== null && Number.isFinite(numeric) && numeric > 0;\n };\n const isPriorTrigger = (value: unknown): value is TpslPriorTrigger => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const trigger = value as Record<string, unknown>;\n return (\n isOrderIdString(trigger.orderId) &&\n (trigger.side === 'buy' || trigger.side === 'sell') &&\n (trigger.wireOrderType === 2 ||\n trigger.wireOrderType === 3 ||\n trigger.wireOrderType === 4 ||\n trigger.wireOrderType === 5) &&\n (trigger.wireTimeInForce === 0 ||\n trigger.wireTimeInForce === 1 ||\n trigger.wireTimeInForce === 2) &&\n typeof trigger.orderExpiry === 'number' &&\n Number.isSafeInteger(trigger.orderExpiry) &&\n trigger.orderExpiry >= -1 &&\n isPositiveDecimalString(trigger.price) &&\n isPositiveDecimalString(trigger.triggerPrice) &&\n isPositiveDecimalString(trigger.remainingSize)\n );\n };\n // EXPLICIT remediation policy for early schemas (v1/v2): their\n // transition state cannot be interpreted safely, so instead of a\n // permanent opaque block they convert to a DURABLE MANUAL-recovery\n // state — surfaced to the user, resolved only by an explicit new\n // protection intent.\n if (parsed.version === 1 || parsed.version === 2) {\n return {\n attempts: [],\n recordedAt:\n typeof parsed.recordedAt === 'number' ? parsed.recordedAt : 0,\n operationId:\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length > 0\n ? parsed.operationId\n : `legacy-v${String(parsed.version)}`,\n createdAt: typeof parsed.createdAt === 'number' ? parsed.createdAt : 0,\n nextAttemptId: 1,\n intent: 'replace',\n phase: 'manual',\n priorGrouping: 'independent',\n priorTriggers: [],\n };\n }\n if (\n (parsed.version === 3 || parsed.version === 4) &&\n typeof parsed.recordedAt === 'number' &&\n Number.isSafeInteger(parsed.recordedAt) &&\n parsed.recordedAt >= 0 &&\n // The journal is bound to ONE api-key slot: nonces are per slot.\n parsed.apiKeyIndex === this.#apiKeyIndex &&\n typeof parsed.operationId === 'string' &&\n parsed.operationId.length >= 1 &&\n parsed.operationId.length <= 64 &&\n typeof parsed.createdAt === 'number' &&\n Number.isSafeInteger(parsed.createdAt) &&\n parsed.createdAt >= 0 &&\n typeof parsed.nextAttemptId === 'number' &&\n Number.isSafeInteger(parsed.nextAttemptId) &&\n parsed.nextAttemptId >= 1 &&\n // An explicit durable operation intent is REQUIRED: without it a\n // remove could be misread as a failed replacement.\n (parsed.intent === 'replace' || parsed.intent === 'remove') &&\n (parsed.phase === 'creating' ||\n parsed.phase === 'cancelling' ||\n // v3's 'restoring' migrates to 'manual' below.\n parsed.phase === 'restoring' ||\n parsed.phase === 'manual') &&\n // 'oco' grouping structurally requires the linked pair.\n (parsed.priorGrouping === 'independent' ||\n (parsed.priorGrouping === 'oco' &&\n Array.isArray(parsed.priorTriggers) &&\n parsed.priorTriggers.length === 2)) &&\n Array.isArray(parsed.priorTriggers) &&\n parsed.priorTriggers.length <= 4 &&\n parsed.priorTriggers.every(isPriorTrigger) &&\n new Set(parsed.priorTriggers.map((trigger) => trigger.orderId)).size ===\n parsed.priorTriggers.length &&\n Array.isArray(parsed.attempts) &&\n // An EMPTY journal is malformed — empty-but-shape-valid would be\n // accepted and silently cleared.\n parsed.attempts.length >= 1 &&\n parsed.attempts.length <= 40 &&\n parsed.attempts.every(isAttempt) &&\n // Attempt IDENTITY is the attemptId — nonces may legitimately\n // repeat when a proven-never-landed submission is retried. The\n // durable allocator must sit strictly ABOVE every recorded id so\n // compaction can never recycle one.\n new Set(parsed.attempts.map((entry) => entry.attemptId)).size ===\n parsed.attempts.length &&\n parsed.attempts.every(\n (entry) => entry.attemptId < (parsed.nextAttemptId as number),\n )\n ) {\n const { attempts } = parsed;\n const { priorTriggers } = parsed;\n // Every restore leg must link to a persisted prior intent — an\n // unlinked restore could sign a duplicate or orphan a prior one.\n const restoresLinked = attempts.every(\n (attempt) =>\n attempt.kind !== 'create' ||\n attempt.role !== 'restore' ||\n (attempt.priorOrderIds ?? []).every((priorOrderId) =>\n priorTriggers.some((trigger) => trigger.orderId === priorOrderId),\n ),\n );\n if (restoresLinked) {\n return {\n attempts,\n recordedAt: parsed.recordedAt,\n operationId: parsed.operationId,\n createdAt: parsed.createdAt,\n nextAttemptId: parsed.nextAttemptId,\n intent: parsed.intent,\n // v3 MIGRATION: an interrupted 'restoring' operation predates\n // the no-auto-restore policy — it parks as MANUAL.\n phase: parsed.phase === 'restoring' ? 'manual' : parsed.phase,\n priorGrouping: parsed.priorGrouping,\n priorTriggers,\n };\n }\n }\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} is malformed; refusing protection changes until it is resolved`,\n );\n };\n\n /**\n * Durable index of settlement keys with pending journals.\n *\n * @returns The disk-cache key of the index.\n */\n readonly #tpslJournalIndexKey = (): string =>\n `lighterTpslJournalIndex:${this.#isTestnet ? 'testnet' : 'mainnet'}`;\n\n /**\n * Read the durable journal index (strictly validated; failures fail\n * closed by throwing).\n *\n * @returns The list of settlement keys with pending journals.\n */\n readonly #readTpslJournalIndex = async (): Promise<string[]> => {\n const raw = await this.#deps.diskCache.getItem(this.#tpslJournalIndexKey());\n if (raw === null) {\n return [];\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (\n Array.isArray(parsed) &&\n parsed.length <= 64 &&\n parsed.every((entry) => typeof entry === 'string')\n ) {\n return parsed;\n }\n } catch {\n // fall through\n }\n throw new Error('Lighter TP/SL journal index is corrupt');\n };\n\n /**\n * Durable manual-recovery doc key (separate from the journal slot).\n *\n * @param settlementKey - Settlement identity.\n * @returns The disk-cache key.\n */\n readonly #tpslManualKey = (settlementKey: string): string =>\n `lighterTpslManual:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`;\n\n /**\n * Manual-recovery index key.\n *\n * @returns The disk-cache key.\n */\n readonly #tpslManualIndexKey = (): string =>\n `lighterTpslManualIndex:${this.#isTestnet ? 'testnet' : 'mainnet'}`;\n\n /**\n * Read the manual-recovery index. Corruption THROWS — a parked\n * protection warning silently degrading to \"nothing pending\" would\n * hide a naked position.\n *\n * @returns Settlement keys with pending manual recoveries.\n */\n readonly #readTpslManualIndex = async (): Promise<string[]> => {\n const raw = await this.#deps.diskCache.getItem(this.#tpslManualIndexKey());\n if (raw === null) {\n return [];\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (\n Array.isArray(parsed) &&\n parsed.length <= 64 &&\n parsed.every((entry) => typeof entry === 'string')\n ) {\n return parsed;\n }\n } catch {\n // fall through\n }\n throw new Error('Lighter TP/SL manual-recovery index is corrupt');\n };\n\n /**\n * Durably record a manual-recovery warning (doc + index entry).\n *\n * @param doc - The manual-recovery record.\n */\n readonly #writeTpslManualRecovery = async (\n doc: TpslManualRecovery,\n ): Promise<void> => {\n await withStorageMutex(this.#tpslManualIndexKey(), async () => {\n const index = await this.#readTpslManualIndex();\n if (\n !index.includes(doc.settlementKey) &&\n index.length >= LIGHTER_TPSL_MANUAL_RECOVERY_LIMIT\n ) {\n throw new Error(\n 'Lighter TP/SL manual-recovery index is full; refusing to hide a new recovery obligation',\n );\n }\n await this.#deps.diskCache.setItem(\n this.#tpslManualKey(doc.settlementKey),\n JSON.stringify({ version: 1, ...doc }),\n );\n if (!index.includes(doc.settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslManualIndexKey(),\n JSON.stringify([...index, doc.settlementKey]),\n );\n }\n });\n };\n\n /**\n * Load a manual-recovery record. Corruption THROWS (never null) so a\n * parked warning cannot silently vanish.\n *\n * @param settlementKey - Settlement identity.\n * @returns The record, or null when none is parked.\n */\n readonly #loadTpslManualRecovery = async (\n settlementKey: string,\n ): Promise<TpslManualRecovery | null> => {\n const raw = await this.#deps.diskCache.getItem(\n this.#tpslManualKey(settlementKey),\n );\n if (raw === null) {\n return null;\n }\n try {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (\n parsed.version === 1 &&\n typeof parsed.settlementKey === 'string' &&\n typeof parsed.symbol === 'string' &&\n typeof parsed.reason === 'string' &&\n parsed.reason.length <= 500 &&\n (parsed.priorIntent === 'replace' || parsed.priorIntent === 'remove') &&\n Array.isArray(parsed.priorTriggers) &&\n Array.isArray(parsed.survivingOrderIds) &&\n (parsed.survivingOrderIds as unknown[]).every(\n (id) => typeof id === 'string',\n ) &&\n typeof parsed.operationId === 'string' &&\n typeof parsed.recordedAt === 'number'\n ) {\n return {\n settlementKey: parsed.settlementKey,\n symbol: parsed.symbol,\n reason: parsed.reason,\n priorIntent: parsed.priorIntent,\n priorTriggers: parsed.priorTriggers as TpslPriorTrigger[],\n survivingOrderIds: parsed.survivingOrderIds as string[],\n operationId: parsed.operationId,\n recordedAt: parsed.recordedAt,\n };\n }\n } catch {\n // fall through to fail closed\n }\n throw new Error(\n `Lighter TP/SL manual-recovery record for ${settlementKey} is corrupt; resolve storage before proceeding`,\n );\n };\n\n /**\n * Clear a manual-recovery record — called ONLY after a successor\n * protection intent has authoritatively succeeded.\n *\n * @param settlementKey - Settlement identity.\n */\n readonly #clearTpslManualRecovery = async (\n settlementKey: string,\n ): Promise<void> => {\n await withStorageMutex(this.#tpslManualIndexKey(), async () => {\n const index = await this.#readTpslManualIndex();\n await this.#deps.diskCache.removeItem(this.#tpslManualKey(settlementKey));\n if (index.includes(settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslManualIndexKey(),\n JSON.stringify(index.filter((entry) => entry !== settlementKey)),\n );\n }\n });\n };\n\n /**\n * Persist a journal entry durably and ensure the index lists its key so\n * restart recovery can enumerate pending obligations without waiting\n * for the next mutation.\n *\n * @param settlementKey - Settlement identity.\n * @param journal - The journal entry.\n */\n readonly #persistTpslJournal = async (\n settlementKey: string,\n journal: TpslJournalState,\n ): Promise<void> => {\n // WRITER-SIDE capacity enforcement, mirrored from the loader: a\n // journal the loader would reject as malformed must never be written\n // in the first place. Throwing here aborts BEFORE the submission the\n // entry was journalling, with every older obligation intact.\n if (journal.priorTriggers.length > 4) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} would record too many prior triggers (${journal.priorTriggers.length} > 4); refusing the mutation`,\n );\n }\n if (journal.attempts.length > 40) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} would record too many attempts (${journal.attempts.length} > 40); refusing further submissions until pending obligations resolve`,\n );\n }\n // INDEX-FIRST: a dangling index entry (no journal behind it) is\n // safely prunable by recovery, whereas compensating a failed index\n // write by removing the journal could erase an EXISTING authoritative\n // journal holding already-accepted attempts. Any failure here aborts\n // BEFORE the next submission with every older obligation intact.\n // Index RMW under its OWN process-wide mutex: concurrent persists\n // for different settlement keys must never lose each other's entry.\n await withStorageMutex(this.#tpslJournalIndexKey(), async () => {\n const index = await this.#readTpslJournalIndex();\n if (!index.includes(settlementKey)) {\n if (index.length >= 64) {\n // NEVER evict a live obligation: fail the mutation before\n // submission instead.\n throw new Error(\n 'Lighter TP/SL journal index is full; refusing further protection changes until pending obligations resolve',\n );\n }\n await this.#deps.diskCache.setItem(\n this.#tpslJournalIndexKey(),\n JSON.stringify([...index, settlementKey]),\n );\n }\n });\n const baseKey = this.#tpslJournalKey(settlementKey);\n // The pointer read-modify-write is serialized PROCESS-WIDE: the\n // instance-local write lock cannot protect two live provider\n // instances sharing one disk cache.\n await withStorageMutex(baseKey, async () => {\n // COMPARE-AND-SWAP on the operation identity: a writer holding a\n // stale snapshot must never take over a DIFFERENT operation's\n // journal. (A missing journal is fine — first write of an op.)\n const currentRaw = await this.#deps.diskCache.getItem(baseKey);\n const pointerAlreadyOurs =\n currentRaw !== null &&\n parseTpslJournalPointer(currentRaw)?.operationId ===\n journal.operationId;\n // A DANGLING pointer (payload already resolved; only the base\n // removal failed) has no live owner — it is claimable, otherwise a\n // partial clear would block every future operation forever.\n let danglingPointer = false;\n if (currentRaw !== null) {\n const staleCheck = parseTpslJournalPointer(currentRaw);\n if (\n staleCheck !== null &&\n staleCheck.operationId !== journal.operationId\n ) {\n danglingPointer =\n (await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, staleCheck.operationId),\n )) === null;\n }\n }\n if (currentRaw !== null && !danglingPointer) {\n const pointer = parseTpslJournalPointer(currentRaw);\n let currentOperationId: unknown = pointer?.operationId ?? null;\n if (pointer === null) {\n try {\n currentOperationId = (\n JSON.parse(currentRaw) as { operationId?: unknown }\n ).operationId;\n } catch {\n // Corrupt current journal: fail closed below via mismatch.\n }\n }\n if (currentOperationId !== journal.operationId) {\n throw new Error(\n `Lighter TP/SL journal for ${settlementKey} belongs to a different operation; refusing a stale write`,\n );\n }\n }\n // Payload first, under the operation's OWN key — then the pointer.\n await this.#deps.diskCache.setItem(\n this.#tpslJournalOpKey(settlementKey, journal.operationId),\n JSON.stringify({\n version: 4,\n recordedAt: journal.recordedAt,\n operationId: journal.operationId,\n createdAt: journal.createdAt,\n nextAttemptId: journal.nextAttemptId,\n apiKeyIndex: this.#apiKeyIndex,\n intent: journal.intent,\n phase: journal.phase,\n priorGrouping: journal.priorGrouping,\n priorTriggers: journal.priorTriggers,\n attempts: journal.attempts,\n }),\n );\n try {\n await this.#deps.diskCache.setItem(\n baseKey,\n JSON.stringify({\n pointerVersion: 1,\n operationId: journal.operationId,\n }),\n );\n } catch (error) {\n // Pointer write failed on the FIRST persist of this operation:\n // remove the freshly written payload so no orphan accumulates.\n // (When an earlier persist already pointed here, the payload is\n // referenced durable state — keep it.)\n if (!pointerAlreadyOurs) {\n await this.#deps.diskCache\n .removeItem(\n this.#tpslJournalOpKey(settlementKey, journal.operationId),\n )\n .catch(() => undefined);\n }\n throw error;\n }\n });\n // A NEW pending obligation invalidates any \"recovery complete\"\n // marker recorded earlier in this session — otherwise later read\n // kicks would skip it until a restart or another mutation.\n this.#tpslRecoveryGeneration = -1;\n };\n\n /**\n * Resolve a settlement obligation everywhere — compare-and-swap on the\n * operation identity: a resolver holding a STALE snapshot must never\n * erase a NEWER operation's journal. Disk removal failures PROPAGATE\n * and the in-memory entry is retained: silently dropping only the\n * memory copy would leave a stale durable obligation to wedge a later\n * session.\n *\n * @param settlementKey - Settlement identity.\n * @param expectedOperationId - The operation this resolver settled;\n * null prunes only a dangling index entry with NO journal behind it.\n * @returns True when the obligation was cleared (or already gone);\n * false when a NEWER operation owns the journal (unresolved).\n */\n readonly #clearTpslJournal = async (\n settlementKey: string,\n expectedOperationId: string | null,\n ): Promise<boolean> => {\n const journalKey = this.#tpslJournalKey(settlementKey);\n const cleared = await withStorageMutex(journalKey, async () => {\n const currentRaw = await this.#deps.diskCache.getItem(journalKey);\n if (currentRaw === null) {\n // Already resolved (or never journalled): nothing left to clear.\n return true;\n }\n const pointer = parseTpslJournalPointer(currentRaw);\n if (pointer !== null) {\n if (expectedOperationId === null) {\n // Prune mode: only a DANGLING pointer may be pruned.\n const payloadRaw = await this.#deps.diskCache.getItem(\n this.#tpslJournalOpKey(settlementKey, pointer.operationId),\n );\n if (payloadRaw !== null) {\n return false;\n }\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n }\n if (pointer.operationId !== expectedOperationId) {\n // A NEWER operation owns the journal: remove only OUR OWN\n // payload (physically incapable of touching theirs) and\n // report the clear as unresolved.\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal clear refused: different operation',\n { settlementKey },\n );\n await this.#deps.diskCache\n .removeItem(\n this.#tpslJournalOpKey(settlementKey, expectedOperationId),\n )\n .catch(() => undefined);\n return false;\n }\n await this.#deps.diskCache.removeItem(\n this.#tpslJournalOpKey(settlementKey, expectedOperationId),\n );\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n }\n // Legacy inline journal at the base key.\n if (expectedOperationId === null) {\n return false;\n }\n let currentOperationId: unknown = null;\n try {\n const inline = JSON.parse(currentRaw) as {\n operationId?: unknown;\n version?: unknown;\n };\n currentOperationId =\n inline.operationId ??\n // Early schemas carry no operation id: the loader synthesizes\n // `legacy-v{n}` for their manual-remediation state — mirror it\n // so the explicit new intent can clear them.\n (inline.version === 1 || inline.version === 2\n ? `legacy-v${String(inline.version)}`\n : null);\n } catch {\n // Corrupt journal is never silently cleared.\n }\n if (currentOperationId !== expectedOperationId) {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal clear refused: different operation',\n { settlementKey },\n );\n return false;\n }\n await this.#deps.diskCache.removeItem(journalKey);\n return true;\n });\n if (!cleared) {\n return false;\n }\n // Index removal under the index mutex, RE-VERIFYING the journal is\n // still gone: a newer operation may have persisted (journal +\n // index entry) between our clear and this removal — removing the\n // entry then would blind restart recovery to a live obligation.\n // A storage READ failure here is AMBIGUITY, never absence: it\n // propagates (the index entry is retained and the settlement stays\n // unresolved) — guessing could orphan a live obligation.\n await withStorageMutex(this.#tpslJournalIndexKey(), async () => {\n const stillGone =\n (await this.#deps.diskCache.getItem(journalKey)) === null;\n if (!stillGone) {\n return;\n }\n const index = await this.#readTpslJournalIndex();\n if (index.includes(settlementKey)) {\n await this.#deps.diskCache.setItem(\n this.#tpslJournalIndexKey(),\n JSON.stringify(index.filter((entry) => entry !== settlementKey)),\n );\n }\n });\n const memoryEntry = this.#tpslUnsettled.get(settlementKey);\n if (\n memoryEntry === undefined ||\n expectedOperationId === null ||\n memoryEntry.operationId === expectedOperationId\n ) {\n this.#tpslUnsettled.delete(settlementKey);\n }\n return true;\n };\n\n /**\n * Targeted, cached, active-first inactive-history reader shared by the\n * mutation transition and recovery: terminal rows are immutable so they\n * cache across polls; page 1 per call; the deep cursor walk runs at\n * most ONCE per reader and stops when every target id is found.\n *\n * @param accountIndex - Captured account index.\n * @param authToken - Captured auth token.\n * @param generation - Captured session generation (fenced per read).\n * @param marketId - Market to scope inactive-history requests to.\n * @returns The reader closure.\n */\n readonly #makeInactiveReader = (\n accountIndex: number,\n authToken: string,\n generation: number,\n marketId: number,\n ): ((targetClientIds: number[]) => Promise<LighterApiOrder[]>) => {\n const terminalCache = new Map<string, LighterApiOrder>();\n let deepTraversalDone = false;\n return async (targetClientIds: number[]): Promise<LighterApiOrder[]> => {\n this.#assertSession(generation);\n const targets = targetClientIds.map(String);\n const missing = (): boolean =>\n targets.some((id) => !terminalCache.has(id));\n const ingest = (orders: LighterApiOrder[]): void => {\n for (const order of orders) {\n if (order.ownerAccountIndex === accountIndex) {\n terminalCache.set(String(order.clientOrderIndex), order);\n }\n }\n };\n const firstPage = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n 100,\n undefined,\n marketId,\n );\n this.#assertSession(generation);\n let rowsRead = firstPage.orders.length;\n if (rowsRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} rows; TP/SL recovery is still pending`,\n );\n }\n ingest(firstPage.orders);\n if (missing() && !deepTraversalDone) {\n let cursor = firstPage.nextCursor;\n const seenCursors = new Set<string>();\n let pagesRead = 1;\n while (cursor && missing()) {\n if (seenCursors.has(cursor)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history repeated cursor ${cursor} after ${rowsRead} rows; TP/SL recovery is still pending`,\n );\n }\n seenCursors.add(cursor);\n const response = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n 100,\n cursor,\n marketId,\n );\n this.#assertSession(generation);\n pagesRead += 1;\n if (\n response.orders.length === 0 &&\n response.nextCursor !== undefined\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history advanced without returning rows; TP/SL recovery is still pending`,\n );\n }\n if (pagesRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} pages; TP/SL recovery is still pending`,\n );\n }\n rowsRead += response.orders.length;\n if (rowsRead > LIGHTER_INACTIVE_HISTORY_ROW_LIMIT) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} inactive-order history exceeded ${LIGHTER_INACTIVE_HISTORY_ROW_LIMIT} rows (${rowsRead} rows returned); TP/SL recovery is still pending`,\n );\n }\n ingest(response.orders);\n cursor = response.nextCursor;\n }\n deepTraversalDone = !cursor || !missing();\n }\n return [...terminalCache.values()];\n };\n };\n\n /** Session generation whose journal recovery fully resolved. */\n #tpslRecoveryGeneration = -1;\n\n /** In-flight journal recovery (deduplicates concurrent triggers). */\n #tpslRecoveryInFlight: Promise<void> | null = null;\n\n /**\n * Detached, deduplicated recovery kick. Wired into signer setup AND the\n * public read paths: a recovery that returned unresolved (e.g. REST\n * visibility lag) must get another chance later in the SAME session,\n * not only at the next signer setup.\n */\n /** A kick arrived while a (possibly stale) recovery was in flight. */\n #tpslRecoveryKickPending = false;\n\n readonly #kickTpslRecovery = (): void => {\n if (this.#tpslRecoveryGeneration === this.#sessionGeneration) {\n return;\n }\n if (this.#tpslRecoveryInFlight) {\n // A stale-generation recovery may be finishing: remember this kick\n // so the CURRENT generation's journals are not silently skipped.\n this.#tpslRecoveryKickPending = true;\n return;\n }\n setTimeout(() => {\n this.#recoverPendingTpslJournals().catch((error) => {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal recovery failed',\n { error: String(error) },\n );\n });\n }, 0);\n };\n\n /**\n * Enumerate durable journal-index entries for the CURRENT identity and\n * recover each: reconcile, complete an interrupted replacement's stale\n * cancels when its created protection is live, then clear. Bounded and\n * deduplicated per session generation; unresolved entries stay for the\n * next attempt.\n */\n readonly #recoverPendingTpslJournals = async (): Promise<void> => {\n const generation = this.#sessionGeneration;\n if (this.#tpslRecoveryGeneration === generation) {\n return;\n }\n if (this.#tpslRecoveryInFlight) {\n await this.#tpslRecoveryInFlight;\n return;\n }\n this.#tpslRecoveryInFlight = (async (): Promise<void> => {\n try {\n // Index corruption/read failure PROPAGATES (logged by the hook):\n // silently treating it as empty would disable recovery entirely.\n const index = await this.#readTpslJournalIndex();\n if (index.length === 0) {\n this.#tpslRecoveryGeneration = generation;\n return;\n }\n const address = this.#boundAddress;\n if (!address) {\n return;\n }\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generation);\n const prefix = `${address}:${accountIndex}:${this.#apiKeyIndex}:`;\n let allResolved = true;\n for (const settlementKey of index) {\n if (!settlementKey.startsWith(prefix)) {\n continue;\n }\n const resolved = await this.#recoverTpslSymbol(\n settlementKey.slice(prefix.length),\n settlementKey,\n generation,\n accountIndex,\n ).catch((error) => {\n // Surface the exact cause (corruption, transport, session\n // fence) — the entry stays retryable, but never silently.\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL journal entry recovery failed',\n {\n settlementKey,\n error:\n error instanceof Error\n ? (error.stack ?? error.message)\n : String(error),\n },\n );\n return false;\n });\n if (!resolved) {\n allResolved = false;\n }\n }\n // Marked complete ONLY when everything resolved: unresolved or\n // errored entries stay retryable within this session.\n if (allResolved) {\n this.#tpslRecoveryGeneration = generation;\n }\n } finally {\n this.#tpslRecoveryInFlight = null;\n if (this.#tpslRecoveryKickPending) {\n this.#tpslRecoveryKickPending = false;\n this.#kickTpslRecovery();\n }\n }\n })();\n await this.#tpslRecoveryInFlight;\n };\n\n /**\n * Recover one pending TP/SL journal without any new protection intent.\n *\n * @param symbol - Market symbol from the settlement key.\n * @param settlementKey - Full settlement identity.\n * @param generation - Captured session generation.\n * @param accountIndex - Captured account index.\n * @returns True when the obligation fully resolved (journal cleared);\n * false when it remains pending and must be retried.\n */\n readonly #recoverTpslSymbol = async (\n symbol: string,\n settlementKey: string,\n generation: number,\n accountIndex: number,\n ): Promise<boolean> => {\n const markets = await this.#ensureMarkets();\n const market = markets.get(symbol);\n if (!market) {\n return false;\n }\n await this.#ensureSignerReady();\n this.#assertSession(generation);\n const authToken = await this.#getAuthToken();\n this.#assertSession(generation);\n return await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit): Promise<boolean> => {\n // The journal is loaded INSIDE the lock: a snapshot taken while\n // waiting for the lock could be superseded by a foreground\n // operation that settles it and journals a NEW one — acting on\n // the stale snapshot could erase the newer obligation.\n const journalEntry = await this.#loadTpslJournal(settlementKey);\n if (!journalEntry) {\n // Stale index entry with no journal behind it: prune.\n return await this.#clearTpslJournal(settlementKey, null).catch(\n () => false,\n );\n }\n const readActiveRaw = async (): Promise<LighterApiOrder[]> => {\n this.#assertSession(generation);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generation);\n return response.orders;\n };\n const readInactiveFor = this.#makeInactiveReader(\n accountIndex,\n authToken,\n generation,\n market.marketId,\n );\n return await this.#settleTpslObligation({\n settlementKey,\n symbol,\n journalEntry,\n market,\n accountIndex,\n authToken,\n generation,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n });\n },\n generation,\n );\n };\n\n /**\n * THE TP/SL obligation state machine — the single implementation run by\n * startup/read-path recovery AND by a direct foreground update that\n * finds a pending journal. Reconciles every attempt authoritatively,\n * then acts per durable intent and phase, and clears the journal ONLY\n * on a fully-settled outcome.\n *\n * @param context - Captured settlement context.\n * @param context.settlementKey - Full settlement identity.\n * @param context.symbol - Market symbol.\n * @param context.journalEntry - The pending journal.\n * @param context.market - Market integerization parameters.\n * @param context.market.marketId - Venue market id.\n * @param context.market.supportedSizeDecimals - Size integerization decimals.\n * @param context.market.supportedPriceDecimals - Price integerization decimals.\n * @param context.accountIndex - Captured account index.\n * @param context.authToken - Captured venue auth token.\n * @param context.generation - Captured session generation.\n * @param context.readActiveRaw - Session-fenced raw active reader.\n * @param context.readInactiveFor - Targeted inactive reader.\n * @param context.nextNonce - Lock-section nonce issuer.\n * @param context.submit - Lock-section submitter.\n * @returns True when fully resolved (journal cleared); false when the\n * obligation remains pending and must be retried.\n */\n readonly #settleTpslObligation = async (context: {\n settlementKey: string;\n symbol: string;\n journalEntry: TpslJournalState;\n market: {\n marketId: number;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n };\n accountIndex: number;\n authToken: string;\n generation: number;\n readActiveRaw: () => Promise<LighterApiOrder[]>;\n readInactiveFor: (targetClientIds: number[]) => Promise<LighterApiOrder[]>;\n nextNonce: () => Promise<number>;\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>;\n }): Promise<boolean> => {\n const { settlementKey } = context;\n // The ENTIRE same-settlement state machine is serialized\n // PROCESS-WIDE: two live providers resolving the same operation\n // could otherwise both choose and submit identical restores/cancels\n // and overwrite each other's attempt state.\n return await withProcessMutex(\n `lighterTpslSettle:${this.#isTestnet ? 'testnet' : 'mainnet'}:${settlementKey}`,\n async () => await this.#settleTpslObligationLocked(context),\n );\n };\n\n /**\n * The settlement machine body — MUST only run under the per-settlement\n * process mutex (see #settleTpslObligation).\n *\n * @param context - See #settleTpslObligation.\n * @param context.settlementKey - Full settlement identity.\n * @param context.symbol - Market symbol.\n * @param context.journalEntry - Caller's journal snapshot (reloaded).\n * @param context.market - Market integerization parameters.\n * @param context.market.marketId - Venue market id.\n * @param context.market.supportedSizeDecimals - Size decimals.\n * @param context.market.supportedPriceDecimals - Price decimals.\n * @param context.accountIndex - Captured account index.\n * @param context.authToken - Captured venue auth token.\n * @param context.generation - Captured session generation.\n * @param context.readActiveRaw - Session-fenced raw active reader.\n * @param context.readInactiveFor - Targeted inactive reader.\n * @param context.nextNonce - Lock-section nonce issuer.\n * @param context.submit - Lock-section submitter.\n * @returns See #settleTpslObligation.\n */\n readonly #settleTpslObligationLocked = async (context: {\n settlementKey: string;\n symbol: string;\n journalEntry: TpslJournalState;\n market: {\n marketId: number;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n };\n accountIndex: number;\n authToken: string;\n generation: number;\n readActiveRaw: () => Promise<LighterApiOrder[]>;\n readInactiveFor: (targetClientIds: number[]) => Promise<LighterApiOrder[]>;\n nextNonce: () => Promise<number>;\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>;\n }): Promise<boolean> => {\n const {\n settlementKey,\n symbol,\n market,\n accountIndex,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n } = context;\n // RELOAD inside the settlement mutex: the caller's snapshot may have\n // been superseded while waiting for the mutex — decisions must be\n // made on the CURRENT journal of the SAME operation only. Disk is\n // AUTHORITATIVE: absence means another resolver cleared it, so any\n // stale in-memory copy must be dropped, never resurrected.\n const journalEntry = await this.#loadTpslJournal(settlementKey);\n if (!journalEntry) {\n this.#tpslUnsettled.delete(settlementKey);\n return await this.#clearTpslJournal(settlementKey, null).catch(\n () => false,\n );\n }\n if (journalEntry.operationId !== context.journalEntry.operationId) {\n // A different operation owns the journal now: this resolver's\n // obligation no longer exists — report unresolved so the caller\n // re-evaluates against the fresh state.\n return false;\n }\n const reconciled = await this.#reconcilePriorTpsl(\n readActiveRaw,\n readInactiveFor,\n accountIndex,\n journalEntry,\n );\n if (reconciled === 'unresolved') {\n return false;\n }\n const persistEntry = async (): Promise<void> => {\n this.#tpslUnsettled.set(settlementKey, journalEntry);\n await this.#persistTpslJournal(settlementKey, journalEntry);\n };\n // Same journalled cancel discipline as the live transition.\n const submitRecoveryCancel = async (\n orderId: string,\n role: 'stale' | 'rollback',\n ): Promise<void> => {\n if (role === 'stale' && journalEntry.intent === 'replace') {\n journalEntry.phase = 'cancelling';\n }\n const cancelNonce = await nextNonce();\n const signedCancel = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, orderId, cancelNonce],\n });\n if (signedCancel.error) {\n throw new Error(\n `Failed to cancel trigger order ${orderId}: ${signedCancel.error}`,\n );\n }\n const cancelIdentity = requireSignedTxIdentity(signedCancel);\n const cancelAttempt: TpslCancelAttempt = {\n kind: 'cancel',\n attemptId: nextAttemptIdFor(journalEntry),\n nonce: cancelNonce,\n outcome: 'unknown',\n orderId,\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n role,\n };\n journalEntry.attempts.push(cancelAttempt);\n await persistEntry();\n await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signedCancel.txInfo,\n () => {\n cancelAttempt.outcome = 'accepted';\n },\n {\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n owner: journalEntry.operationId,\n },\n );\n };\n // Classify every journalled create leg on the books (reconcile\n // proved each attempt either landed or never can).\n const replacementIds = journalEntry.attempts\n .filter(\n (attempt): attempt is TpslCreateAttempt =>\n attempt.kind === 'create' && attempt.role === 'replacement',\n )\n .flatMap((attempt) => attempt.clientIds);\n const restoreAttempts = journalEntry.attempts.filter(\n (attempt): attempt is TpslCreateAttempt =>\n attempt.kind === 'create' && attempt.role === 'restore',\n );\n const allCreateIds = [\n ...replacementIds,\n ...restoreAttempts.flatMap((attempt) => attempt.clientIds),\n ];\n const rawActive = await readActiveRaw();\n const missingFromActive = allCreateIds.filter(\n (clientId) =>\n !rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const rawInactive =\n missingFromActive.length > 0\n ? await readInactiveFor(missingFromActive)\n : [];\n const stateOf = (clientId: number): 'active' | 'success' | 'failed' => {\n if (\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n )\n ) {\n return 'active';\n }\n const terminal = rawInactive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (!terminal) {\n // Reconcile proved never-landed: same outcome as failed.\n return 'failed';\n }\n const status = terminal.status.toLowerCase();\n const fullyExecuted =\n (status === 'filled' || status === 'executed') &&\n parseStrictDecimal(terminal.remainingBaseAmount) === 0;\n return fullyExecuted ? 'success' : 'failed';\n };\n const replacementStates = replacementIds.map(stateOf);\n const anySuccess = replacementStates.includes('success');\n const anyActive = replacementStates.includes('active');\n const anyFailed = replacementStates.includes('failed');\n const priorActive = (prior: TpslPriorTrigger): boolean =>\n rawActive.some((order) => String(order.orderIndex) === prior.orderId);\n const cancelledOrderIds: string[] = [];\n const createdClientIds: number[] = [];\n // Aggregation groups parallel to createdClientIds: one group per\n // create ATTEMPT (grouped OCO semantics within, independence across).\n const createdGroups: number[][] = [];\n const pushCreatedGroup = (group: number[]): void => {\n createdClientIds.push(...group);\n createdGroups.push(group);\n };\n const cancelPriorLeftovers = async (): Promise<void> => {\n // The replacement must STAY proven while the old protection is\n // removed: keep its live ids in the final expectation so a leg\n // terminal-failing DURING these cancels (the phase race) fails\n // this pass instead of clearing the journal naked. Grouped per\n // replacement ATTEMPT: an executed OCO leg legitimately\n // auto-cancels its sibling.\n for (const attempt of journalEntry.attempts) {\n if (attempt.kind !== 'create' || attempt.role !== 'replacement') {\n continue;\n }\n const activeLegs = attempt.clientIds.filter(\n (clientId) => stateOf(clientId) === 'active',\n );\n if (activeLegs.length > 0) {\n pushCreatedGroup(attempt.clientIds);\n }\n }\n for (const prior of journalEntry.priorTriggers) {\n if (priorActive(prior)) {\n await submitRecoveryCancel(prior.orderId, 'stale');\n cancelledOrderIds.push(prior.orderId);\n }\n }\n };\n const rollbackActiveJournalledLegs = async (\n legIds: number[],\n ): Promise<void> => {\n for (const clientId of legIds) {\n if (stateOf(clientId) !== 'active') {\n continue;\n }\n const survivor = rawActive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (survivor) {\n await submitRecoveryCancel(String(survivor.orderIndex), 'rollback');\n cancelledOrderIds.push(String(survivor.orderIndex));\n }\n }\n };\n const rollbackActiveReplacements = async (): Promise<void> =>\n await rollbackActiveJournalledLegs(replacementIds);\n // COMPACTION: proven-resolved attempts with no live effect and no\n // coverage are dropped so repeated retries can never dead-end at the\n // attempt cap: FAILED restore creates (never landed/terminal-failed)\n // and resolved cancels (target gone, or proven never-landed).\n const compactionNow = Date.now();\n journalEntry.attempts = journalEntry.attempts.filter((attempt) => {\n if (attempt.kind === 'create') {\n return (\n attempt.role !== 'restore' ||\n attempt.clientIds.some((clientId) => stateOf(clientId) !== 'failed')\n );\n }\n const targetGone = !rawActive.some(\n (order) => String(order.orderIndex) === attempt.orderId,\n );\n const provenNeverLanded =\n attempt.outcome === 'unknown' &&\n compactionNow > attempt.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS;\n // Accepted-but-terminal-FAILED cancels (venue status 0) landed\n // without mutating the books: proven-resolved, compactable.\n const landedTerminalFailed =\n getLighterTransactionOutcome(attempt.terminalStatus) === 'failed';\n return !(targetGone || provenNeverLanded || landedTerminalFailed);\n });\n // NO AUTOMATIC RESTORE: the venue exposes no atomic primitive that\n // could prove a re-created trigger attaches to the SAME position\n // lifecycle, so a fully-failed replacement after old cancels parks\n // the journal in a DURABLE 'manual' state — surfaced via\n // `getPendingManualRecoveries` and resolved only by an explicit NEW\n // protection intent from the user. Never restored, never silently\n // cleared.\n const parkManual = async (reason: string): Promise<boolean> => {\n // Survivors: prior triggers still on the books + replacement legs\n // still active — deliberately LEFT (only remaining protection).\n const survivingOrderIds = [\n ...new Set([\n ...journalEntry.priorTriggers\n .filter((prior) => priorActive(prior))\n .map((prior) => prior.orderId),\n ...rawActive\n .filter((order) =>\n replacementIds.some(\n (clientId) =>\n String(order.clientOrderIndex) === String(clientId),\n ),\n )\n .map((order) => String(order.orderIndex)),\n ]),\n ];\n // The DURABLE warning lives in its own doc; the journal slot is\n // released so a successor protection intent can run. The doc\n // clears only after a successor SUCCEEDS.\n await this.#writeTpslManualRecovery({\n settlementKey,\n symbol,\n reason,\n priorIntent: journalEntry.intent,\n priorTriggers: journalEntry.priorTriggers,\n survivingOrderIds,\n operationId: journalEntry.operationId,\n recordedAt: Date.now(),\n });\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL protection requires MANUAL re-establishment',\n { settlementKey, reason },\n );\n await this.#clearTpslJournal(settlementKey, journalEntry.operationId);\n return true;\n };\n if (journalEntry.phase === 'manual') {\n // Journal parked 'manual' by an earlier version: migrate the\n // warning into the dedicated durable doc.\n return await parkManual(\n 'TP/SL protection could not be safely re-established automatically (parked by an earlier session)',\n );\n }\n if (journalEntry.intent === 'remove') {\n // An intentional REMOVAL is never \"recovered\" by restoring the\n // cancelled protection: finish/reconcile the cancels exactly.\n for (const prior of journalEntry.priorTriggers) {\n if (priorActive(prior)) {\n await submitRecoveryCancel(prior.orderId, 'stale');\n cancelledOrderIds.push(prior.orderId);\n }\n }\n } else if (journalEntry.phase === 'creating') {\n // Old protection untouched. Nothing landed / everything failed\n // → the old set is still the only intent: just clear.\n if (replacementIds.length > 0 && (anySuccess || anyActive)) {\n if (!anySuccess && anyFailed) {\n // Partial OCO before old cancels: roll surviving legs back so\n // the OLD protection remains authoritative.\n await rollbackActiveReplacements();\n } else {\n // Replacement in force (or executed): finish the swap.\n await cancelPriorLeftovers();\n }\n }\n } else if (journalEntry.phase === 'cancelling') {\n if (anySuccess || (anyActive && !anyFailed)) {\n // Replacement fully won — finish cancelling the old protection.\n await cancelPriorLeftovers();\n } else {\n // Replacement fully failed (or degraded to a partial set) AFTER\n // old cancels began: the position's protection can no longer be\n // proven — park durably for MANUAL re-establishment. Any\n // surviving leg is deliberately LEFT (it is the only protection\n // remaining); nothing is restored.\n return await parkManual(\n 'Replacement TP/SL orders failed after the previous protection cancels began; the position may be under-protected',\n );\n }\n }\n if (cancelledOrderIds.length > 0 || createdClientIds.length > 0) {\n const settled = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n { createdClientIds, cancelledOrderIds },\n // PER-ATTEMPT groups: a grouped OCO replacement's executed leg\n // legitimately auto-cancels its sibling.\n { createdGroups },\n );\n // ONLY a fully-settled pass may clear; a replacement dying DURING\n // the old cancels parks for manual re-establishment.\n if (settled.outcome === 'timeout') {\n return false;\n }\n if (settled.outcome === 'created-terminal-failed') {\n return await parkManual(\n 'Replacement TP/SL order was cancelled or rejected by the venue after the previous protection was already removed',\n );\n }\n }\n // A refused clear (superseded by a newer operation) is UNRESOLVED —\n // never reported as success.\n return await this.#clearTpslJournal(\n settlementKey,\n journalEntry.operationId,\n );\n };\n\n /**\n * Reconcile a PRIOR transition's expectation before any new mutation.\n * Only created ids can cause duplicates from a stale snapshot, so they\n * must be accounted for (active or terminal). Cancelled ids are safe in\n * either state: still-active targets reappear in the fresh snapshot and\n * are re-cancelled.\n *\n * @param readActiveRaw - Strict raw active-orders reader.\n * @param readInactive - Targeted inactive-history reader (cached, bounded).\n * @param accountIndex - Captured account index.\n * @param entry - The recorded expectation.\n * @param entry.attempts - Journalled per-attempt submissions.\n * @param entry.recordedAt - When the journal was recorded (ms).\n * @returns 'resolved' when safe to proceed; 'unresolved' when an\n * ACCEPTED mutation is still not visible.\n */\n readonly #reconcilePriorTpsl = async (\n readActiveRaw: () => Promise<LighterApiOrder[]>,\n readInactive: (targetClientIds: number[]) => Promise<LighterApiOrder[]>,\n accountIndex: number,\n entry: { attempts: TpslAttempt[]; recordedAt: number },\n ): Promise<'resolved' | 'unresolved'> => {\n // Per-attempt reconciliation, authoritative and never time-guessed:\n // 1. Books first — a create is resolved when its ids are all\n // active/terminal, a cancel when its target left the active book.\n // 2. Otherwise the EXACT signed tx hash is looked up: a strict match\n // (hash + account + api key slot + nonce) proves the payload\n // reached the sequencer, so absence from the books can only be\n // visibility lag (keep blocking). A venue-confirmed not-found is\n // only never-landed once the signed ExpiredAt (+ clock slack) has\n // passed — the sequencer cannot accept an expired payload.\n const satisfiedOnBooks = (\n attempt: TpslAttempt,\n rawActive: LighterApiOrder[],\n rawInactive: LighterApiOrder[],\n ): boolean =>\n attempt.kind === 'create'\n ? attempt.clientIds.every(\n (clientId) =>\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ) ||\n rawInactive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n )\n : !rawActive.some(\n (order) => String(order.orderIndex) === attempt.orderId,\n );\n // Books can satisfy only OBSERVED-accepted attempts. An UNKNOWN\n // attempt's desired book state may hold for INDEPENDENT reasons (a\n // fill, an external cancel) while the signed payload could still\n // land later and consume its nonce — every unknown attempt must\n // resolve by exact hash identity or proven expiry.\n let rawActive: LighterApiOrder[] = [];\n let rawInactive: LighterApiOrder[] = [];\n for (let poll = 0; poll < LIGHTER_TPSL_SETTLE_ATTEMPTS; poll += 1) {\n const activeNow = await readActiveRaw();\n // ACTIVE-FIRST (see #awaitTpslVisibility): inactive history is only\n // consulted for create ids not already visible active.\n const createIdsMissingFromActive = entry.attempts\n .filter(\n (attempt): attempt is TpslCreateAttempt => attempt.kind === 'create',\n )\n .flatMap((attempt) => attempt.clientIds)\n .filter(\n (clientId) =>\n !activeNow.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const inactiveNow =\n createIdsMissingFromActive.length > 0\n ? await readInactive(createIdsMissingFromActive)\n : [];\n rawActive = activeNow;\n rawInactive = inactiveNow;\n // Poll the books through visibility lag for ALL attempts — book\n // convergence resolves accepted attempts directly and lets an\n // unknown-but-landed attempt pass its final identity check below.\n const anyUnsatisfied = entry.attempts.some(\n (attempt) => !satisfiedOnBooks(attempt, activeNow, inactiveNow),\n );\n if (!anyUnsatisfied) {\n break;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, LIGHTER_TPSL_SETTLE_POLL_MS),\n );\n }\n for (const attempt of entry.attempts) {\n if (\n attempt.outcome === 'accepted' &&\n satisfiedOnBooks(attempt, rawActive, rawInactive)\n ) {\n continue;\n }\n let lookedUp: LighterTxLookupResponse | null;\n try {\n lookedUp = await this.#clientService.getTx(attempt.txHash);\n } catch {\n // Lookup failure is AMBIGUOUS, never evidence of non-acceptance.\n return 'unresolved';\n }\n if (lookedUp !== null) {\n // The exact signed hash exists at the venue. With a matching\n // identity (hash + account + api key slot + nonce):\n // - terminal FAILED status (0) resolves the attempt\n // deterministically — the nonce was consumed but the books\n // were never mutated (the machine re-acts on book state);\n // - any other status with the books already reflecting the\n // attempt resolves it;\n // - otherwise it reached the sequencer but is not yet visible —\n // keep blocking. A NON-matching payload under this hash fails\n // closed identically, and is logged (signer/venue defect).\n const matchesIdentity =\n typeof lookedUp.hash === 'string' &&\n lookedUp.hash.toLowerCase().replace(/^0x/u, '') ===\n attempt.txHash.toLowerCase().replace(/^0x/u, '') &&\n lookedUp.accountIndex === accountIndex &&\n lookedUp.apiKeyIndex === this.#apiKeyIndex &&\n lookedUp.nonce === attempt.nonce;\n if (!matchesIdentity) {\n this.#deps.debugLogger.log(\n '[LighterProvider] TP/SL tx lookup identity mismatch; failing closed',\n { txHash: attempt.txHash },\n );\n return 'unresolved';\n }\n const transactionOutcome = getLighterTransactionOutcome(\n lookedUp.status,\n );\n if (transactionOutcome === 'failed') {\n // Record the terminal venue status durably (next persist):\n // compaction can then drop this attempt even though its target\n // may still be on the books.\n attempt.terminalStatus = lookedUp.status;\n continue;\n }\n if (satisfiedOnBooks(attempt, rawActive, rawInactive)) {\n continue;\n }\n // Executed proves the transaction landed, but the order books may\n // still lag. Keep the journal until the expected create/cancel state\n // is visible.\n return 'unresolved';\n }\n // Venue-confirmed not-found: only never-landed once the signed\n // payload can no longer be accepted.\n if (Date.now() <= attempt.expiresAt + LIGHTER_TX_EXPIRY_SLACK_MS) {\n return 'unresolved';\n }\n // Expired and venue-confirmed absent: authoritatively never landed —\n // its reserved nonce may be released UNLESS a later dispatch (a\n // retry) already consumed it (durable consumed watermark guards).\n await this.#releaseNonceReservationIfUnconsumed(\n accountIndex,\n attempt.nonce,\n );\n }\n return 'resolved';\n };\n\n /**\n * Release a session-global nonce reservation once a submission is\n * PROVEN never-landed. Only the topmost reservation can be safely\n * lowered; anything else stays reserved until proven in turn.\n *\n * @param accountIndex - Venue account index.\n * @param nonce - The proven-unconsumed nonce.\n */\n readonly #releaseNonceReservation = (\n accountIndex: number,\n nonce: number,\n ): void => {\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n if (this.#nonceReservations.get(reservationKey) === nonce + 1) {\n this.#nonceReservations.set(reservationKey, nonce);\n }\n };\n\n /**\n * Bounded poll until the venue reflects a TP/SL transition: every\n * created client id accounted for and every cancelled order id absent\n * from the active book.\n *\n * A created trigger can EXECUTE, expire, or be venue-cancelled before\n * the first poll (an immediate/crossed TP/SL never rests), so created\n * ids reconcile against the active book PLUS the inactive/terminal\n * history — otherwise the obligation could never resolve and would\n * permanently block the symbol.\n *\n * @param readActiveRaw - Strict raw active-orders reader (session-fenced).\n * @param readInactive - Targeted inactive-history reader (cached, bounded).\n * @param expectation - Ids the venue must account for.\n * @param expectation.createdClientIds - Client ids that must be active\n * or terminal.\n * @param expectation.cancelledOrderIds - Order ids that must leave the\n * active book.\n * @param options - Aggregation options.\n * @param options.createdGroups - Per-attempt aggregation groups over\n * the created ids (see inline doc).\n * @returns Outcome: 'settled' when every id is accounted for and no\n * created id failed ('executedCreated' marks created ids that reached a\n * SUCCESS terminal state — filled/executed — instead of resting\n * active); 'created-terminal-failed' when the venue reports a created\n * id cancelled/rejected/expired (the obligation RESOLVES — the caller\n * surfaces the failure but no permanent block remains); 'timeout' when\n * the bound elapsed unresolved.\n */\n readonly #awaitTpslVisibility = async (\n readActiveRaw: () => Promise<LighterApiOrder[]>,\n readInactive: (targetClientIds: number[]) => Promise<LighterApiOrder[]>,\n expectation: { createdClientIds: number[]; cancelledOrderIds: string[] },\n options: {\n /**\n * PER-ATTEMPT aggregation groups over `createdClientIds`: within a\n * group, grouped-OCO semantics hold (one fully executed leg\n * legitimately auto-cancels its sibling — the GROUP succeeded);\n * ACROSS groups every group must independently succeed or rest\n * active. Omitted: all created ids form one group (legacy grouped\n * semantics).\n */\n createdGroups?: number[][];\n } = {},\n ): Promise<\n | { outcome: 'settled'; executedCreated: boolean }\n | {\n outcome: 'created-terminal-failed';\n /** New legs still resting ACTIVE despite a failed sibling. */\n survivingActiveClientIds: number[];\n }\n | { outcome: 'timeout' }\n > => {\n for (\n let attempt = 0;\n attempt < LIGHTER_TPSL_SETTLE_ATTEMPTS;\n attempt += 1\n ) {\n const rawActive = await readActiveRaw();\n // ACTIVE-FIRST: only ids not already proven active need the\n // high-weight inactive-history lookup; a normal freshly-active\n // replacement performs ZERO inactive requests.\n const missingFromActive = expectation.createdClientIds.filter(\n (clientId) =>\n !rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n ),\n );\n const rawInactive =\n missingFromActive.length > 0\n ? await readInactive(missingFromActive)\n : [];\n // Per-id classification. Success is EXACT-whitelisted\n // ('filled'/'executed') AND requires a strictly ZERO remaining size\n // (a 'filled' row with remainder is not a proven execution);\n // everything else terminal — including unknown statuses — fails\n // CLOSED.\n const classified = expectation.createdClientIds.map((clientId) => {\n if (\n rawActive.some(\n (order) => String(order.clientOrderIndex) === String(clientId),\n )\n ) {\n return { clientId, state: 'active' as const };\n }\n const terminal = rawInactive.find(\n (order) => String(order.clientOrderIndex) === String(clientId),\n );\n if (!terminal) {\n return { clientId, state: 'missing' as const };\n }\n const status = terminal.status.toLowerCase();\n // STRICT remaining parse: a prefix-parsed '0oops' must never\n // count as a proven zero remainder.\n const fullyExecuted =\n (status === 'filled' || status === 'executed') &&\n parseStrictDecimal(terminal.remainingBaseAmount) === 0;\n return {\n clientId,\n state: fullyExecuted ? ('success' as const) : ('failed' as const),\n };\n });\n const createdAccounted = !classified.some(\n (entry) => entry.state === 'missing',\n );\n const cancelledGone = expectation.cancelledOrderIds.every(\n (orderId) =>\n !rawActive.some((order) => String(order.orderIndex) === orderId),\n );\n if (createdAccounted && cancelledGone) {\n // PER-GROUP aggregation: within a group one fully executed leg\n // auto-cancels its sibling (grouped OCO — the GROUP succeeded);\n // across groups each must independently succeed or rest active.\n const groups =\n options.createdGroups ??\n (expectation.createdClientIds.length > 0\n ? [expectation.createdClientIds]\n : []);\n const stateOfId = new Map(\n classified.map((entry) => [entry.clientId, entry.state]),\n );\n let anyGroupSuccess = false;\n const failedGroupActiveIds: number[] = [];\n let anyGroupFailed = false;\n for (const group of groups) {\n const states = group.map(\n (clientId) => stateOfId.get(clientId) ?? 'missing',\n );\n if (states.includes('success')) {\n anyGroupSuccess = true;\n continue;\n }\n if (states.includes('failed')) {\n anyGroupFailed = true;\n failedGroupActiveIds.push(\n ...group.filter(\n (clientId) => stateOfId.get(clientId) === 'active',\n ),\n );\n }\n }\n if (anyGroupFailed) {\n return {\n outcome: 'created-terminal-failed',\n survivingActiveClientIds: failedGroupActiveIds,\n };\n }\n return { outcome: 'settled', executedCreated: anyGroupSuccess };\n }\n await new Promise((resolve) =>\n setTimeout(resolve, LIGHTER_TPSL_SETTLE_POLL_MS),\n );\n }\n return { outcome: 'timeout' };\n };\n\n /**\n * Throws when the session generation moved past the captured one — used\n * after every await in account-bound async work so a delayed account-A\n * step can never mutate account-B's session.\n *\n * @param generation - Generation captured when the work started.\n */\n readonly #assertSession = (generation: number): void => {\n if (this.#isDisconnected) {\n throw new Error(\n 'Operation cancelled: the Lighter provider was disconnected',\n );\n }\n if (generation !== this.#sessionGeneration) {\n throw new Error(\n 'Operation cancelled: the wallet switched accounts (or the signer reset) while this operation was in flight',\n );\n }\n // The generation only advances when some provider call rebinds; also\n // notice a wallet switch nothing has observed yet. Account-bound work\n // must never run without a binding: every legitimate flow (including\n // headless l1Address and configured-index setups) binds first, so a\n // null binding here means the wallet was deselected — fail closed even\n // when a configured account index could still resolve.\n if (this.#boundAddress === null) {\n throw new Error(\n 'Operation cancelled: no wallet account is bound to the venue session',\n );\n }\n let address: string | null = null;\n try {\n address = this.#walletService.getUserAddress().toLowerCase();\n } catch {\n address = null;\n }\n if (address !== this.#boundAddress) {\n if (address === null) {\n // Deselected: nothing to rebind to yet.\n this.#invalidateSessionState();\n this.#teardownStream();\n } else {\n // Unobserved switch: rebind properly (invalidates caches and\n // rebuilds stream channels for the new account) before cancelling\n // the stale operation.\n this.#ensureSessionBinding();\n }\n throw new Error(\n 'Operation cancelled: the wallet switched accounts (or the signer reset) while this operation was in flight',\n );\n }\n };\n\n /** Drop every cache derived from the previously bound account. */\n readonly #invalidateSessionState = (): void => {\n this.#sessionGeneration += 1;\n this.#boundAddress = null;\n this.#accountIndex = null;\n this.#signerReadyPromise = null;\n this.#authToken = null;\n this.#clearBridgeOwnership();\n // #tpslUnsettled survives (address+accountIndex+symbol keyed): a\n // reselect of the same account must still reconcile its pending ids.\n };\n\n /**\n * Create the WASM signer client and register the venue key if the\n * account's key slot does not hold it yet. Deduplicated.\n *\n * @returns Resolves when the signer session is ready.\n */\n readonly #ensureSignerReady = async (): Promise<void> => {\n this.#ensureSessionBinding();\n this.#assertSession(this.#sessionGeneration);\n if (this.#signerReadyPromise) {\n return await this.#signerReadyPromise;\n }\n const generation = this.#sessionGeneration;\n const setupPromise = this.#setupSigner(generation);\n this.#signerReadyPromise = setupPromise;\n try {\n return await setupPromise;\n } catch (error) {\n // Only clear the promise WE installed — a newer session may already\n // have replaced it, and an old rejection must not tear that down.\n if (this.#signerReadyPromise === setupPromise) {\n this.#signerReadyPromise = null;\n }\n throw error;\n }\n };\n\n readonly #setupSigner = async (generation: number): Promise<void> => {\n const bridge = this.#getSignerBridge();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generation);\n const chainId = getLighterChainId(this.#clientService.network);\n // The WASM client is a singleton inside the bridge host and the venue\n // key registration is a nonce-consuming write. Both therefore run\n // INSIDE the venue write lock: a stale previous-account setup aborts at\n // the lock's fence before it can touch the bridge, and no other\n // account's setup or write can interleave with this critical section.\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n const nonce = await nextNonce();\n this.#assertSession(generation);\n const created = await bridge.createClient({\n chainId,\n accountIndex,\n nonce,\n apiKeyIndex: this.#apiKeyIndex,\n });\n if (created.error || !created.success) {\n throw new Error(\n `Lighter signer client creation failed: ${created.error ?? 'unknown'}`,\n );\n }\n this.#assertSession(generation);\n this.#venuePublicKey = created.pk;\n // Record bridge-client OWNERSHIP: the WASM client is a singleton\n // per bridge, so every later write section re-establishes it\n // when another identity has since overwritten it.\n this.#signerIdentity = `${this.#clientService.network}:${accountIndex}:${this.#apiKeyIndex}`;\n // Re-establishment passes only public session metadata. The client\n // owns and restores the venue key inside the bridge.\n this.#signerRecreateParams = { chainId, accountIndex };\n bridgeClientOwners.set(this.#rawSignerBridge(), this.#signerIdentity);\n\n // Register the venue key when the slot does not hold it yet. The\n // bridge returns only public registration data; the client-owned\n // venue private key never crosses into Core.\n const registered = await this.#isVenueKeyRegistered(accountIndex);\n this.#assertSession(generation);\n if (!registered) {\n await this.#registerVenueKey(\n accountIndex,\n created.body,\n generation,\n nextNonce,\n submit,\n );\n this.#assertSession(generation);\n }\n },\n generation,\n );\n // AUTOMATIC bounded recovery: pending TP/SL journals must be\n // reconciled at startup/reconnect, not only when the next mutation\n // happens to run. Detached so it awaits THIS setup's resolved promise\n // instead of deadlocking on it.\n this.#kickTpslRecovery();\n };\n\n readonly #isVenueKeyRegistered = async (\n accountIndex: number,\n ): Promise<boolean> => {\n // Query all slots. Lighter returns `api key not found` when a missing\n // slot is requested directly, which would make first-time registration\n // impossible. The all-slots response is successful and represents an\n // unused slot by omitting it from `apiKeys`.\n const response = await this.#clientService.getApiKeys(accountIndex);\n const configuredSlot = response.apiKeys.find(\n (key) => key.apiKeyIndex === this.#apiKeyIndex,\n );\n if (!configuredSlot) {\n return false;\n }\n const normalizeKey = (key: string | null): string =>\n (key ?? '').replace(/^0x/u, '').toLowerCase();\n if (\n normalizeKey(configuredSlot.publicKey) ===\n normalizeKey(this.#venuePublicKey)\n ) {\n return true;\n }\n throw new Error(\n `Lighter API key slot ${String(this.#apiKeyIndex)} already contains a different key; automatic replacement is disabled because personal_sign output is not guaranteed to be byte-identical across signer implementations or devices`,\n );\n };\n\n readonly #registerVenueKey = async (\n accountIndex: number,\n changePubKeyBody: string,\n generation: number,\n nextNonce: () => Promise<number>,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ): Promise<void> => {\n const bridge = this.#getSignerBridge();\n // The ChangePubKey plaintext from _createClient embeds the nonce used at\n // client creation; sign it with the user's L1 account (EIP-191). Every\n // await is fenced and the submission goes through the lock's fenced\n // submit — a stale registration can never reach the venue.\n const l1Signature =\n await this.#walletService.signPersonalMessage(changePubKeyBody);\n this.#assertSession(generation);\n const nonce = await nextNonce();\n this.#assertSession(generation);\n const signed = await bridge.execute({\n function: '_signChangePubKey',\n params: [accountIndex, l1Signature, nonce, this.#apiKeyIndex],\n });\n if (signed.error) {\n throw new Error(`Lighter ChangePubKey signing failed: ${signed.error}`);\n }\n this.#assertSession(generation);\n const result = await submit(\n LIGHTER_TX_TYPE_CHANGE_PUB_KEY,\n signed.txInfo,\n undefined,\n extractDispatchIdentity(signed),\n );\n this.#deps.debugLogger.log('[LighterProvider] Venue key registered', {\n accountIndex,\n apiKeyIndex: this.#apiKeyIndex,\n txHash: result.txHash,\n });\n };\n\n /**\n * Mint (or reuse) an auth token for authenticated REST reads.\n *\n * @returns Auth token string.\n */\n /** Tail of the serialized venue-write chain (see #withVenueNonce). */\n #writeChain: Promise<void> = Promise.resolve();\n\n /** Every client order id this instance has issued (collision set). */\n readonly #issuedClientOrderIds = new Set<number>();\n\n /**\n * Atomically reserve unique client order indexes.\n *\n * The venue requires client_order_index to be UNIQUE ACROSS ALL MARKETS\n * for the account (official Get Started docs) and does not require\n * monotonicity. Ids are uniform random draws over the uint48 space\n * (two 24-bit draws, exact in float space) with a per-instance\n * collision set and retry: within an instance duplicates are\n * impossible; across simultaneous instances/devices a single pair\n * collides with probability 1/2^48 (~3.6e-15) and the birthday bound\n * over n total ids is ~n(n-1)/2^49 — about 1.8e-7 after ten thousand\n * orders, versus the 1% per-pair risk of the previous 100-lane scheme.\n *\n * @param count - How many ids to reserve.\n * @returns The reserved ids.\n */\n readonly #allocateClientOrderIndexes = (count: number): number[] => {\n const ids: number[] = [];\n // Bounded: a degenerate randomness source (or an absurdly full\n // collision set) must surface as an error, never a synchronous spin.\n // 100 attempts per id makes accidental exhaustion unreachable in\n // practice (collision odds per draw stay astronomically small).\n let attempts = 0;\n const maxAttempts = count * 100;\n while (ids.length < count) {\n if (attempts >= maxAttempts) {\n throw new Error(\n `Unable to allocate a unique Lighter client order id after ${maxAttempts} attempts`,\n );\n }\n attempts += 1;\n const [high, low] = randomUint24Pair();\n const candidate = high * 2 ** 24 + low;\n if (candidate === 0 || this.#issuedClientOrderIds.has(candidate)) {\n continue;\n }\n this.#issuedClientOrderIds.add(candidate);\n ids.push(candidate);\n }\n return ids;\n };\n\n /**\n * Serialize a nonce-consuming venue write.\n *\n * Lighter nonces are strictly ordered per key slot; two interleaved\n * fetch→submit pairs (e.g. the controller's per-item batch fallbacks\n * running concurrently) would sign with the same nonce and get one\n * rejection. Every write acquires the chain, fetches a fresh nonce\n * inside it, and submits before the next write's fetch runs. A section\n * queued under a wallet account that has since been switched away from\n * refuses to run — a delayed account-A write must never execute inside\n * account-B's session.\n *\n * @param accountIndex - Account whose key-slot nonce is consumed.\n * @param section - Work to run exclusively; fetch nonces via the\n * provided helper (each call returns the next fresh nonce).\n * @param generationAtIntent - Session generation captured when the\n * caller's intent was formed (defaults to now).\n * @returns The section's result.\n */\n readonly #withVenueWriteLock = async <Result>(\n accountIndex: number,\n section: (\n nextNonce: () => Promise<number>,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ) => Promise<Result>,\n generationAtIntent = this.#sessionGeneration,\n ): Promise<Result> => {\n const criticalSection = async (): Promise<Result> => {\n this.#assertSession(generationAtIntent);\n // Every unresolved prior dispatch (this session OR a previous one —\n // the ledger is durable) must resolve before this section may issue\n // nonces: a restart would otherwise reuse a consumed-but-lagging\n // nonce, and a proven never-landed dispatch must release its nonce.\n await this.#resolveNonceLedger(accountIndex);\n this.#assertSession(generationAtIntent);\n // Monotonic nonce reservation: the venue's nextNonce endpoint can\n // LAG accepted submissions. The floor is SESSION-GLOBAL per\n // accountIndex:apiKeyIndex — a queued/next lock section (any\n // symbol, any operation) must never be handed a nonce an earlier\n // submission may have consumed, even when that submission's\n // response was lost. Reservation advances at DISPATCH (a signing\n // failure never burns a nonce the venue still expects); a proven\n // never-landed submission releases it again via reconciliation.\n const reservationKey = `${accountIndex}:${this.#apiKeyIndex}`;\n let lastIssuedNonce: number | null = null;\n const nextNonce = async (): Promise<number> => {\n // Re-fenced on every fetch AND after it resolves: the account can\n // switch between the section's own await points, not only while it\n // sat in the queue.\n this.#assertSession(generationAtIntent);\n const nonceResponse = await this.#clientService.getNextNonce(\n accountIndex,\n this.#apiKeyIndex,\n );\n this.#assertSession(generationAtIntent);\n const reservedFloor = this.#nonceReservations.get(reservationKey);\n const issued =\n reservedFloor === undefined\n ? nonceResponse.nonce\n : Math.max(nonceResponse.nonce, reservedFloor);\n lastIssuedNonce = issued;\n return issued;\n };\n // BRIDGE OWNERSHIP: the WASM client is a singleton per bridge —\n // another provider (different account/network sharing the bridge)\n // may have overwritten it since our setup. Re-establish OUR client\n // before any signing in this section. (During initial setup the\n // identity is not yet recorded; setup itself creates the client.)\n if (\n this.#signerIdentity !== null &&\n this.#signerRecreateParams !== null &&\n bridgeClientOwners.get(this.#rawSignerBridge()) !== this.#signerIdentity\n ) {\n await this.#reestablishSignerClient(\n generationAtIntent,\n await nextNonce(),\n );\n }\n const submit = async (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ): Promise<LighterSendTxResponse> => {\n // Last fence before anything reaches the venue: a switch that\n // happened while SIGNING must abort before submission.\n this.#assertSession(generationAtIntent);\n // Record the dispatch DURABLY BEFORE anything else: a failed\n // ledger read/write means NO dispatch and an UNTOUCHED memory\n // floor — the nonce stays safely unissued at the venue. The\n // identity comes from the SIGNING RESULT (pinned WASM contract:\n // txInfo never carries the hash).\n let ledgerEntry: LighterNonceLedgerDoc['entries'][number] | null = null;\n if (lastIssuedNonce !== null) {\n // COMPLETE identity is REQUIRED before anything reaches the\n // wire: a hashless dispatch could never be proven absent, so a\n // response loss would wedge writes until the venue advances.\n if (\n identity?.txHash === null ||\n identity?.expiresAt === null ||\n identity === undefined\n ) {\n throw new Error(\n 'Lighter dispatch refused: the signing result did not provide a complete transaction identity (hash + expiry)',\n );\n }\n ledgerEntry = {\n nonce: lastIssuedNonce,\n txHash: identity.txHash,\n expiresAt: identity.expiresAt,\n kind: txType,\n intent: identity.intent ?? `txType:${txType}`,\n owner: identity.owner ?? null,\n };\n const appendedEntry = ledgerEntry;\n await this.#withLedgerLock(accountIndex, async () => {\n const doc = await this.#readNonceLedger(accountIndex);\n if (doc.entries.length >= 16) {\n throw new Error(\n 'Too many unresolved Lighter dispatches; refusing further writes until they resolve',\n );\n }\n await this.#writeNonceLedger(accountIndex, {\n consumedFloor: doc.consumedFloor,\n entries: [...doc.entries, appendedEntry],\n recovered: doc.recovered,\n });\n });\n // Only AFTER the durable append: reserve in memory — from this\n // point the venue may consume the nonce even if the response\n // never arrives.\n this.#nonceReservations.set(reservationKey, lastIssuedNonce + 1);\n }\n // EVERY error path below keeps the durable entry — a coded venue\n // or HTTP error can mask a commit, so nothing short of an exact\n // authoritative reconciliation may release the nonce.\n const response: LighterSendTxResponse =\n await this.#clientService.sendTx(txType, txInfo);\n // Acceptance bookkeeping runs SYNCHRONOUSLY before anything can\n // fail: a switch during network submission must cancel the\n // operation, never the record of an accepted venue mutation.\n onAccepted?.();\n // POST-SEND ORDER: evaluate the session fence BEFORE the ledger\n // entry transitions, then commit the transition ATOMICALLY in\n // ONE write under the ledger lock — fence pass → consumed/\n // removed; fence fail → recovered(SUCCEEDED). If that single\n // write fails, the ORIGINAL unresolved entry remains the durable\n // record and every retry stays blocked; the only durable proof\n // of the accepted mutation is never consumed first and\n // quarantined second.\n let fenceError: unknown = null;\n try {\n this.#assertSession(generationAtIntent);\n } catch (error) {\n fenceError = error;\n }\n if (ledgerEntry !== null) {\n await this.#resolveEntryPostDispatch(\n accountIndex,\n ledgerEntry,\n fenceError !== null,\n ).catch(() => undefined);\n }\n if (fenceError !== null) {\n throw ensureError(fenceError, 'LighterProvider.submit');\n }\n return response;\n };\n return await section(nextNonce, submit);\n };\n // The ENTIRE nonce resolve→fetch→sign/append→dispatch sequence is\n // serialized PROCESS-WIDE per network+account+api-key slot: the\n // instance chain alone cannot stop a second live provider from\n // issuing the same nonce or interleaving ledger writes.\n const guardedSection = async (): Promise<Result> =>\n await withProcessMutex(\n `lighterVenueWrite:${this.#isTestnet ? 'testnet' : 'mainnet'}:${accountIndex}:${this.#apiKeyIndex}`,\n // INNERMOST: the bridge mutex — the WASM client is a singleton\n // per bridge, so ensure-correct-client + every sign of a section\n // are serialized across ALL providers sharing the bridge.\n async () =>\n await withProcessMutex(\n bridgeMutexKey(this.#rawSignerBridge()),\n criticalSection,\n ),\n );\n const run = this.#writeChain.then(guardedSection, guardedSection);\n this.#writeChain = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n };\n\n readonly #withVenueNonce = async <Result>(\n accountIndex: number,\n operation: (\n nonce: number,\n submit: (\n txType: number,\n txInfo: string,\n onAccepted?: () => void,\n identity?: {\n txHash: string | null;\n expiresAt: number | null;\n intent?: string;\n owner?: string | null;\n },\n ) => Promise<LighterSendTxResponse>,\n ) => Promise<Result>,\n generationAtIntent = this.#sessionGeneration,\n ): Promise<Result> =>\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => operation(await nextNonce(), submit),\n generationAtIntent,\n );\n\n /**\n * Re-create OUR venue client on the shared bridge after another\n * identity overwrote the singleton. MUST run while holding the bridge\n * mutex. The bridge owns key generation and persistence.\n *\n * @param generation - The caller's captured session generation.\n * @param nonce - A fresh venue nonce for the client creation.\n */\n readonly #reestablishSignerClient = async (\n generation: number,\n nonce: number,\n ): Promise<void> => {\n const recreateParams = this.#signerRecreateParams;\n const identity = this.#signerIdentity;\n if (recreateParams === null || identity === null) {\n throw new Error(\n 'Lighter signer client re-establishment attempted before setup',\n );\n }\n this.#assertSession(generation);\n const recreated = await this.#getSignerBridge().createClient({\n chainId: recreateParams.chainId,\n accountIndex: recreateParams.accountIndex,\n nonce,\n apiKeyIndex: this.#apiKeyIndex,\n });\n if (recreated.error || !recreated.success) {\n throw new Error(\n `Lighter signer client re-establishment failed: ${recreated.error ?? 'unknown'}`,\n );\n }\n this.#assertSession(generation);\n bridgeClientOwners.set(this.#rawSignerBridge(), identity);\n };\n\n readonly #getAuthToken = async (): Promise<string> => {\n this.#ensureSessionBinding();\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (this.#authToken && this.#authToken.deadline - nowSeconds > 60) {\n return this.#authToken.token;\n }\n const generation = this.#sessionGeneration;\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n // The auth-token mint is a singleton-client call like any other sign:\n // it runs under the BRIDGE LEASE, and re-establishes OUR client first\n // when another identity has since overwritten it — otherwise the\n // token would be minted by the wrong account's venue key.\n const token = await withProcessMutex(\n bridgeMutexKey(this.#rawSignerBridge()),\n async () => {\n if (\n this.#signerIdentity !== null &&\n this.#signerRecreateParams !== null &&\n bridgeClientOwners.get(this.#rawSignerBridge()) !==\n this.#signerIdentity\n ) {\n // Client creation is bridge-local: the read-only nonce fetch\n // seeds its tracking without dispatching anything.\n const nonceResponse = await this.#clientService.getNextNonce(\n this.#signerRecreateParams.accountIndex,\n this.#apiKeyIndex,\n );\n this.#assertSession(generation);\n await this.#reestablishSignerClient(generation, nonceResponse.nonce);\n }\n return await this.#getSignerBridge().execute({\n function: '_createAuthToken',\n params: [accountIndex, this.#apiKeyIndex],\n });\n },\n );\n if (token.error || !token.token) {\n throw new Error(\n `Lighter auth token creation failed: ${token.error ?? 'unknown'}`,\n );\n }\n // Rebind first so an unobserved external switch during the bridge call\n // advances the generation, then compare: a token minted under a binding\n // that no longer exists must never be cached — re-mint under the new\n // captured session instead.\n this.#ensureSessionBinding();\n if (generation !== this.#sessionGeneration) {\n return await this.#getAuthToken();\n }\n this.#authToken = { token: token.token, deadline: token.deadline };\n return token.token;\n };\n\n readonly #ensureMarkets = async (): Promise<\n Map<string, LighterOrderBookMeta>\n > => {\n if (this.#marketsBySymbol.size === 0) {\n await this.initialize();\n }\n return this.#marketsBySymbol;\n };\n\n // ============================================================================\n // Market Data Operations (Public Reads)\n // ============================================================================\n\n async getMarkets(_params?: GetMarketsParams): Promise<MarketInfo[]> {\n try {\n const markets = await this.#clientService.getOrderBooks();\n await this.#ensureMarketMargins();\n return markets\n .filter((market) => market.marketType === 'perp')\n .flatMap((market) => {\n const margins = this.#marginBySymbol.get(market.symbol);\n if (!margins) {\n // #ensureMarketMargins deliberately omits inactive rows whose\n // retired risk metadata cannot produce a canonical MarketInfo.\n if (market.status === 'inactive') {\n return [];\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n const adapted = adaptMarketFromLighter(\n market,\n deriveLighterMaxLeverage(margins.minInitial, market.symbol),\n );\n // minBaseAmount and minQuoteAmount are maker-only. Market and\n // IOC orders can use one base-size tick, so the public universal\n // minimum must report that tick rather than the maker floor.\n delete adapted.minimumOrderSize;\n if (margins?.lastTradePrice && margins.lastTradePrice > 0) {\n const oneTickUsd =\n margins.lastTradePrice / 10 ** market.supportedSizeDecimals;\n if (Number.isFinite(oneTickUsd) && oneTickUsd > 0) {\n adapted.minimumOrderSize = oneTickUsd;\n }\n }\n return [adapted];\n });\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getMarkets',\n );\n this.#deps.debugLogger.log('[LighterProvider] getMarkets failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getMarkets'),\n });\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n throw caughtError;\n }\n return [];\n }\n }\n\n async getMarketDataWithPrices(): Promise<PerpsMarketData[]> {\n try {\n const response = await this.#clientService.getOrderBookDetails();\n return response.orderBookDetails\n .filter((detail) => detail.marketType === 'perp')\n .filter((detail) => !isInactiveMarketWithoutUsableRiskMetadata(detail))\n .map((detail) =>\n adaptMarketDataFromLighter(detail, this.#deps.marketDataFormatters),\n );\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getMarketDataWithPrices',\n );\n this.#deps.debugLogger.log(\n '[LighterProvider] getMarketDataWithPrices failed',\n {\n error: String(wrappedError),\n ...this.#getErrorContext('getMarketDataWithPrices'),\n },\n );\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n throw caughtError;\n }\n return [];\n }\n }\n\n // ============================================================================\n // Account Operations\n // ============================================================================\n\n async getPositions(_params?: GetPositionsParams): Promise<Position[]> {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n // Risk metadata is required for every returned position. A transport\n // failure must reject instead of looking like an authoritative empty\n // account.\n await this.#ensureMarketMargins();\n try {\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n this.#assertSession(generation);\n const account = response.accounts[0];\n if (!account?.positions) {\n return [];\n }\n // Adapt BEFORE filtering: the adapter strict-validates raw numeric\n // sizes, and a prefix-parsing filter would silently drop (or keep)\n // malformed entries like '0oops' before validation could fire.\n return account.positions\n .map((position) =>\n adaptPositionFromLighter(\n position,\n this.#maxLeverageForPosition(position),\n ),\n )\n .filter((position) => parseFloat(position.size) !== 0);\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates and venue-data integrity failures must surface,\n // never degrade into empty state that can preserve stale views.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getPositions',\n );\n this.#deps.debugLogger.log('[LighterProvider] getPositions failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getPositions'),\n });\n return [];\n }\n }\n\n async getAccountState(\n _params?: GetAccountStateParams,\n ): Promise<AccountState> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n // A delayed response for the previous account must never surface as\n // the current account's state.\n this.#assertSession(generation);\n const account = response.accounts[0];\n if (!account) {\n return EMPTY_ACCOUNT_STATE;\n }\n return adaptAccountStateFromLighter(account);\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates and venue-data integrity failures must surface,\n // never degrade into empty state that can preserve stale views.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getAccountState',\n );\n this.#deps.debugLogger.log('[LighterProvider] getAccountState failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getAccountState'),\n });\n return EMPTY_ACCOUNT_STATE;\n }\n }\n\n /**\n * STRICT active-orders read: any REST/auth failure THROWS. Mutation\n * flows (TP/SL replacement/removal) must use this — treating a swallowed\n * [] as authoritative would let them \"succeed\" while cancelling nothing.\n *\n * @returns Adapted open orders.\n */\n readonly #readOpenOrdersStrict = async (): Promise<Order[]> => {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n // The index and the token must belong to the SAME session — never\n // pair the previous account's index with the new account's token.\n this.#assertSession(generation);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generation);\n return response.orders.map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n };\n\n async getOpenOrders(_params?: GetOrdersParams): Promise<Order[]> {\n // Public reads re-kick pending journal recovery (deduped, detached).\n this.#kickTpslRecovery();\n try {\n return await this.#readOpenOrdersStrict();\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates must surface, never degrade into empty state.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getOpenOrders',\n );\n this.#deps.debugLogger.log('[LighterProvider] getOpenOrders failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getOpenOrders'),\n });\n return [];\n }\n }\n\n async getOrders(\n params?: GetOrdersParams,\n _options?: PerpsReadOptions,\n ): Promise<Order[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n this.#assertSession(generation);\n await this.#ensureMarkets();\n const response = await this.#clientService.getInactiveOrders(\n accountIndex,\n authToken,\n );\n // Both legs (historical + open) must come from one session — a\n // switch mid-way would merge account A's history with B's orders.\n this.#assertSession(generation);\n const historical = (response.orders ?? []).map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n // Full lifecycle: open orders first, then the historical states.\n const open = await this.getOpenOrders(params);\n // getOpenOrders swallows its own cancellation into []; the merge must\n // still refuse to pair A's history with B's session.\n this.#assertSession(generation);\n return [...open, ...historical];\n } catch (caughtError) {\n if (\n this.#isUnsupportedCapabilityError(caughtError) ||\n this.#isDataIntegrityError(caughtError)\n ) {\n // Capability gates must surface, never degrade into empty state.\n throw caughtError;\n }\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.getOrders',\n );\n this.#deps.debugLogger.log('[LighterProvider] getOrders failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('getOrders'),\n });\n return [];\n }\n }\n\n async getCurrentAccountId(): Promise<CaipAccountId> {\n const address = this.#walletService.getUserAddress();\n const chainId = getLighterChainId(this.#clientService.network);\n return `eip155:${chainId}:${address}` as CaipAccountId;\n }\n\n // ============================================================================\n // Trading Operations (POC: limit/market place + cancel)\n // ============================================================================\n\n /**\n * Apply the leverage the caller requested with the order.\n *\n * Lighter models leverage as a per-market account setting (UpdateLeverage,\n * tx 20; initial margin fraction in hundredths of a percent), not an order\n * field. The venue rejects the update while a position or resting order\n * exists on the market, so in that case the request is skipped with a log\n * (matching the already-set leverage is not an error).\n *\n * @param accountIndex - Lighter account index.\n * @param market - Market metadata for the order being placed.\n * @param params - The original order params carrying `leverage`.\n */\n /**\n * Decide whether the caller's requested leverage needs a venue update.\n *\n * @param params - The order params carrying `leverage`.\n * @returns The UpdateLeverage margin fraction (hundredths of a percent)\n * to sign, or null when no change is needed.\n */\n readonly #resolveLeverageIntent = async (\n params: OrderParams,\n ): Promise<number | null> => {\n const requested = params.leverage;\n if (requested === undefined) {\n return null;\n }\n // Venue state decides, never the caller's possibly-stale\n // existingPositionLeverage snapshot.\n const positions = await this.getPositions();\n const held = positions.find(\n (position) => position.symbol === params.symbol,\n );\n if (\n held?.leverage?.value !== undefined &&\n Math.abs(held.leverage.value - requested) < 0.5\n ) {\n // Requested leverage already in effect — intent satisfied.\n return null;\n }\n // Otherwise sign the update inside the placement's own write lock. If\n // the market has a position or resting order the venue rejects it with\n // a clear error, failing the placement instead of silently trading at\n // a leverage the caller did not ask for.\n return Math.round(10_000 / requested);\n };\n\n async placeOrder(\n params: OrderParams,\n inheritedGeneration?: number,\n ): Promise<OrderResult> {\n // Tracks a COMMITTED leverage change so an order failing afterwards\n // reports the partial venue state explicitly instead of implying no\n // mutation happened.\n let leverageCommitted = false;\n try {\n if (params.marginMode !== undefined) {\n return {\n success: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n if (params.orderType !== 'limit' && params.orderType !== 'market') {\n return { success: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n // User intent is never silently dropped: fields this venue path does\n // not execute are rejected so the caller can adapt, not surprised.\n if (params.takeProfitPrice || params.stopLossPrice) {\n return {\n success: false,\n error:\n 'Lighter does not support TP/SL attached at placement; place the order, then call updatePositionTPSL',\n };\n }\n if (params.timeInForce === 'ALO') {\n return {\n success: false,\n error: 'Lighter placement does not support post-only (ALO) yet',\n };\n }\n const leverageError = lighterLeverageError(params.leverage);\n if (leverageError) {\n return { success: false, error: leverageError };\n }\n // Bind the write to the wallet account it was INITIATED under; if the\n // wallet switches before the queued critical section runs, it aborts.\n // A composite caller (closePosition) passes ITS generation so the\n // whole read-then-write sequence shares one intent identity.\n this.#ensureSessionBinding();\n const generationAtIntent = inheritedGeneration ?? this.#sessionGeneration;\n this.#assertSession(generationAtIntent);\n // All intent validation below uses PUBLIC market data only; signer\n // and account setup are deferred until it passes so invalid intent\n // causes zero bridge calls (no client creation or key registration\n // side effects).\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n if (params.orderType === 'limit' && !params.price) {\n return { success: false, error: 'Limit order requires a price' };\n }\n if (params.leverage !== undefined) {\n // Authoritative metadata REQUIRED: the display fallback (global\n // 50x) must never approve leverage for a market whose published\n // bound is unavailable.\n const maxLeverage = await this.#requireMarketMaxLeverage(params.symbol);\n if (maxLeverage === null) {\n return {\n success: false,\n error: `Cannot validate leverage for ${params.symbol}: venue margin metadata unavailable`,\n };\n }\n if (params.leverage > maxLeverage) {\n return {\n success: false,\n error: `Invalid leverage ${params.leverage}: exceeds the ${params.symbol} maximum of ${maxLeverage}x`,\n };\n }\n }\n\n // Slippage tolerance: caller basis points win, then the deprecated\n // decimal field, then the venue-conventional 5%.\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? (params.slippage ?? 0.05)\n : params.maxSlippageBps / 10_000;\n // The reference price sizes the order; market orders additionally get\n // a protection price offset by the slippage tolerance. They are kept\n // separate so usdAmount sizing is never distorted by the protection\n // offset.\n let referencePrice: number;\n if (params.orderType === 'limit') {\n // STRICT full-string parse: '90000USD' prefix-parses under\n // parseFloat and must never become signed intent.\n const parsedLimitPrice = parseFinitePositive(params.price ?? '');\n if (parsedLimitPrice === null) {\n return {\n success: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n referencePrice = parsedLimitPrice;\n } else {\n referencePrice = parseFloat(\n params.price ?? String(params.currentPrice ?? 0),\n );\n }\n let executionPrice = referencePrice;\n if (params.orderType === 'market') {\n const resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n if (resolved.error !== null) {\n return { success: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n params.isBuy,\n slippageFraction,\n );\n }\n // Finite AND positive: 'Infinity' passes a bare > 0 check but would\n // corrupt integerization/signing downstream.\n if (\n !Number.isFinite(referencePrice) ||\n !(referencePrice > 0) ||\n !Number.isFinite(executionPrice) ||\n !(executionPrice > 0)\n ) {\n return {\n success: false,\n error: 'Unable to resolve a finite execution price for the order',\n };\n }\n // USD is the source of truth when provided (hybrid sizing contract),\n // converted at the reference price — not the protection price. A\n // provided-but-invalid usdAmount is an error, never a silent fallback\n // to the size field.\n let requestedSize: number;\n if (params.usdAmount === undefined) {\n const parsedSize = parseFinitePositive(params.size);\n if (parsedSize === null) {\n return { success: false, error: 'Order size must be positive' };\n }\n requestedSize = parsedSize;\n } else {\n const usdAmount = parseFinitePositive(params.usdAmount);\n if (usdAmount === null) {\n return {\n success: false,\n error: `Invalid usdAmount ${params.usdAmount}: must be a positive number`,\n };\n }\n // A USD amount is approximate by contract (converted at the\n // reference price), so it is snapped onto the venue size grid the\n // way wire integerization will round it — an explicit size string\n // is exact user intent and is never adjusted here.\n requestedSize = snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n );\n }\n if (!(requestedSize > 0)) {\n return { success: false, error: 'Order size must be positive' };\n }\n if (params.usdAmount === undefined) {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n fromLighterInteger(requestedSizeInt, market.supportedSizeDecimals) !==\n requestedSize\n ) {\n return {\n success: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n }\n const minSize = isLighterMakerOrder(params)\n ? computeLighterMinOrderSize(market, referencePrice)\n : 0;\n if (minSize > 0 && requestedSize < minSize) {\n // Only a LIVE-VERIFIED full close may be bumped to the venue\n // minimum: reduce-only execution clamps to the position, so no\n // extra exposure results and dust positions stay closable. The\n // isFullClose flag is a hint, never trusted — a partial close\n // bumped to the minimum would close more than the caller asked.\n const verifiedFullClose = params.reduceOnly\n ? await this.#isVerifiedFullClose(params.symbol, requestedSize)\n : false;\n if (!verifiedFullClose) {\n return {\n success: false,\n error: `Order size ${requestedSize} is below the Lighter minimum of ${minSize} ${params.symbol}`,\n };\n }\n }\n const size =\n minSize > 0 ? Math.max(requestedSize, minSize) : requestedSize;\n\n // Wire-format integerization runs BEFORE signer setup: overflow and\n // sub-tick rejections throw here, still with zero bridge calls.\n const priceInt = toSignerWirePriceInteger(\n executionPrice,\n market.supportedPriceDecimals,\n );\n const sizeInt = toSignerWireInteger(size, market.supportedSizeDecimals);\n\n const leverageImfHundredths = await this.#resolveLeverageIntent(params);\n // Margin mode is sent only with an explicit leverage update. An\n // omitted leverage leaves both leverage and margin mode unchanged;\n // an explicit update preserves an existing position's venue mode and\n // uses isolated only for a flat market.\n const leverageMarginMode =\n leverageImfHundredths === null\n ? null\n : await this.#resolveMarginModeForSymbol(params.symbol);\n\n // Intent validated — only now do signer and account setup run.\n // Re-fence FIRST: the preflight awaited public/account reads during\n // which the wallet may have switched, and a stale intent must never\n // create or register the new account's venue key.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generationAtIntent);\n const [clientOrderIndex] = this.#allocateClientOrderIndexes(1);\n\n // Leverage update and order placement share ONE lock acquisition so a\n // concurrent write can never interleave between the caller's leverage\n // intent and the order that depends on it.\n const result = await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n if (leverageImfHundredths !== null && leverageMarginMode !== null) {\n const signedLeverage = await this.#getSignerBridge().execute({\n function: '_signUpdateLeverage',\n // Contract: [accountIndex, marketId, imfHundredths,\n // marginMode, nonce] — exactly five params.\n params: [\n accountIndex,\n market.marketId,\n leverageImfHundredths,\n leverageMarginMode,\n await nextNonce(),\n ],\n });\n if (signedLeverage.error) {\n throw new Error(\n `Lighter leverage update failed: ${signedLeverage.error}`,\n );\n }\n await submit(\n LIGHTER_TX_TYPE_UPDATE_LEVERAGE,\n signedLeverage.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signedLeverage),\n intent: `updateLeverage:${params.symbol}:${String(params.leverage)}`,\n },\n );\n leverageCommitted = true;\n }\n const signed = await this.#getSignerBridge().execute({\n function: '_signCreateOrder',\n params: [\n accountIndex,\n market.marketId,\n clientOrderIndex,\n String(sizeInt),\n String(priceInt),\n params.isBuy ? 0 : 1,\n params.orderType === 'limit'\n ? LIGHTER_ORDER_TYPE_LIMIT\n : LIGHTER_ORDER_TYPE_MARKET,\n params.orderType === 'limit' && params.timeInForce !== 'IOC'\n ? LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME\n : LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n params.reduceOnly ? 1 : 0,\n String(LIGHTER_NO_TRIGGER_PRICE),\n // GTT orders auto-expire in 28 days (signer sentinel -1);\n // IOC orders must carry a zero expiry.\n params.orderType === 'limit' && params.timeInForce !== 'IOC'\n ? LIGHTER_ORDER_EXPIRY_NONE\n : 0,\n await nextNonce(),\n ],\n });\n if (signed.error) {\n throw new Error(`Lighter order signing failed: ${signed.error}`);\n }\n return await submit(\n LIGHTER_TX_TYPE_CREATE_ORDER,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `placeOrder:${params.symbol}:${clientOrderIndex}`,\n },\n );\n },\n generationAtIntent,\n );\n\n this.#deps.debugLogger.log('[LighterProvider] Order placed', {\n symbol: params.symbol,\n clientOrderIndex,\n txHash: result.txHash,\n });\n\n return {\n success: true,\n orderId: String(clientOrderIndex),\n submittedSize: String(size),\n providerId: 'lighter',\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.placeOrder',\n );\n this.#deps.debugLogger.log('[LighterProvider] placeOrder failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('placeOrder', { symbol: params.symbol }),\n });\n // PARTIAL VENUE STATE is contract-visible: a committed leverage\n // change followed by an order failure must never imply \"nothing\n // happened\".\n const partialPrefix = leverageCommitted\n ? `PARTIAL STATE: leverage for ${params.symbol} was already updated to ${String(params.leverage)}x before the order failed. `\n : '';\n return {\n success: false,\n error: `${partialPrefix}${wrappedError.message}`,\n ...(leverageCommitted\n ? { partialState: { leverageUpdated: Number(params.leverage) } }\n : {}),\n };\n }\n }\n\n async cancelOrder(\n params: CancelOrderParams,\n inheritedGeneration?: number,\n ): Promise<CancelOrderResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = inheritedGeneration ?? this.#sessionGeneration;\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n\n await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, params.orderId, nonce],\n });\n if (signed.error) {\n throw new Error(`Lighter cancel signing failed: ${signed.error}`);\n }\n return await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `cancelOrder:${params.symbol}:${params.orderId}`,\n },\n );\n },\n generationAtIntent,\n );\n\n return {\n success: true,\n orderId: params.orderId,\n providerId: 'lighter',\n };\n } catch (caughtError) {\n const wrappedError = ensureError(\n caughtError,\n 'LighterProvider.cancelOrder',\n );\n this.#deps.debugLogger.log('[LighterProvider] cancelOrder failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('cancelOrder', { symbol: params.symbol }),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n // ============================================================================\n // Trading Operations (POC: stubbed)\n // ============================================================================\n\n async editOrder(_params: EditOrderParams): Promise<OrderResult> {\n // ModifyOrder (tx 17) is accepted by the venue's sendTx but the resting\n // order keeps its original price — an execution no-op we have raised\n // with Lighter. Reporting success here would misrepresent user intent,\n // so the operation refuses until the venue behavior is resolved.\n // Callers can cancel + re-place instead.\n return {\n success: false,\n error:\n 'Lighter order editing is unavailable: the venue currently accepts but does not apply ModifyOrder. Cancel and re-place the order instead.',\n };\n }\n\n /**\n * Resolve the FRESH venue reference price for a market-order sizing,\n * with the same fail-closed and drift semantics as execution — shared\n * by placement and close validation so they can never disagree.\n *\n * @param symbol - Market symbol.\n * @param slippageFraction - Caller slippage tolerance (fraction).\n * @param priceAtCalculation - Caller's sizing snapshot, if any.\n * @returns The fresh reference price, or the exact execution error.\n */\n readonly #resolveMarketReferencePrice = async (\n symbol: string,\n slippageFraction: number,\n priceAtCalculation?: number,\n ): Promise<\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string }\n > => {\n // Numeric intent validates fail-closed BEFORE any drift math. A\n // non-finite/non-positive snapshot makes the drift comparison NaN\n // (silently bypassing protection), and a tolerance at or above 100%\n // derives a zero-or-negative protection price on sells.\n if (\n !Number.isFinite(slippageFraction) ||\n slippageFraction < 0 ||\n slippageFraction >= 1\n ) {\n return {\n referencePrice: null,\n error: `Invalid slippage tolerance ${slippageFraction * 10_000} bps: must be at least 0 and below 10000`,\n };\n }\n if (\n priceAtCalculation !== undefined &&\n (!Number.isFinite(priceAtCalculation) || !(priceAtCalculation > 0))\n ) {\n return {\n referencePrice: null,\n error: `Invalid price snapshot ${priceAtCalculation}: must be a positive finite number`,\n };\n }\n // Always a FRESH venue price: the caller's currentPrice is the same\n // snapshot as priceAtCalculation, and a drift check that compares a\n // snapshot to itself would never fire.\n const details = await this.#clientService.getOrderBookDetails();\n const freshPrice =\n details.orderBookDetails.find((entry) => entry.symbol === symbol)\n ?.lastTradePrice ?? 0;\n if (!Number.isFinite(freshPrice) || !(freshPrice > 0)) {\n // Fail closed: falling back to the caller's snapshot would let the\n // drift check compare that snapshot to itself.\n return {\n referencePrice: null,\n error: `No live venue price available for ${symbol}; refusing to size a market order`,\n };\n }\n if (\n priceAtCalculation !== undefined &&\n priceAtCalculation > 0 &&\n Math.abs(freshPrice - priceAtCalculation) / priceAtCalculation >\n slippageFraction\n ) {\n return {\n referencePrice: null,\n error: `Price moved beyond the ${(slippageFraction * 100).toFixed(2)}% slippage tolerance since sizing`,\n };\n }\n return { referencePrice: freshPrice, error: null };\n };\n\n /**\n * Validate the shape of a close request (shared by validateClosePosition\n * and closePosition so validation can never approve a close the\n * execution path refuses).\n *\n * @param params - Close request.\n * @returns Error message, or null when the shape is acceptable.\n */\n /**\n * The mobile close sheet sends a FULL close as an EMPTY size string\n * (`size: sizeToClose || ''`); HyperLiquid and TradingService treat a\n * falsy size as \"no explicit size\", so this venue honors the same\n * contract — an empty/whitespace size or usdAmount means full close,\n * never a validation failure.\n *\n * @param params - Raw close request.\n * @returns The request with empty-string sizing normalized to absent.\n */\n readonly #normalizeCloseParams = (\n params: ClosePositionParams,\n ): ClosePositionParams => ({\n ...params,\n size: params.size?.trim() ? params.size : undefined,\n usdAmount: params.usdAmount?.trim() ? params.usdAmount : undefined,\n });\n\n readonly #validateCloseShape = (\n params: ClosePositionParams,\n ): string | null => {\n const closeOrderType = params.orderType ?? 'market';\n if (closeOrderType !== 'market' && closeOrderType !== 'limit') {\n return `Lighter cannot close with a ${closeOrderType} order; use market or limit`;\n }\n if (closeOrderType === 'limit' && !params.price) {\n return 'Limit close requires a price';\n }\n if (\n params.usdAmount !== undefined &&\n parseFinitePositive(params.usdAmount) === null\n ) {\n // Finite REQUIRED: a non-finite usdAmount must never fall back to\n // held-size validation while execution forwards the infinite USD\n // into placement.\n return `Invalid usdAmount ${params.usdAmount}: must be a positive number`;\n }\n // closePosition forwards an explicit size to placement, which rejects\n // non-finite or non-positive values; validation must match.\n if (\n params.usdAmount === undefined &&\n params.size !== undefined &&\n parseFinitePositive(params.size) === null\n ) {\n return 'Order size must be positive';\n }\n return null;\n };\n\n /**\n * Live check whether a below-minimum reduce-only request is actually a\n * full close of the held position (shared by placement and validation).\n *\n * @param symbol - Market symbol.\n * @param requestedSize - Requested base size.\n * @returns True when the live position verifies a full close.\n */\n readonly #isVerifiedFullClose = async (\n symbol: string,\n requestedSize: number,\n ): Promise<boolean> => {\n const positions = await this.getPositions();\n const held = Math.abs(\n parseFloat(\n positions.find((entry) => entry.symbol === symbol)?.size ?? '0',\n ),\n );\n // Exact match (float epsilon only): closePosition forwards the precise\n // live size, and anything less is a deliberate partial that a min-size\n // bump would silently over-close.\n return held > 0 && requestedSize >= held * (1 - 1e-9);\n };\n\n async closePosition(rawParams: ClosePositionParams): Promise<OrderResult> {\n const params = this.#normalizeCloseParams(rawParams);\n try {\n // One intent identity from the position read through the final write:\n // an account switch mid-sequence aborts instead of trading the new\n // account with sizing derived from the old one.\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const closeOrderType = params.orderType ?? 'market';\n const shapeError = this.#validateCloseShape(params);\n if (shapeError) {\n return { success: false, error: shapeError };\n }\n const positions = await this.getPositions();\n this.#assertSession(generationAtIntent);\n const position = positions.find(\n (entry) => entry.symbol === params.symbol,\n );\n if (!position) {\n return {\n success: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n const signedSize = parseFloat(position.size);\n const explicitSizing =\n params.size !== undefined || params.usdAmount !== undefined;\n const closeSize = params.size ?? String(Math.abs(signedSize));\n // Reduce-only order on the opposite side; the caller's full sizing\n // and protection intent (usdAmount, slippage, price snapshot, limit\n // price) rides through the placement path unchanged.\n return await this.placeOrder(\n {\n symbol: params.symbol,\n isBuy: signedSize < 0,\n size: closeSize,\n usdAmount: params.usdAmount,\n orderType: closeOrderType,\n price: params.price,\n reduceOnly: true,\n // Without explicit sizing this is a full close and must never be\n // rejected by the minimum-notional check on a dust position.\n isFullClose: !explicitSizing,\n currentPrice: params.currentPrice,\n priceAtCalculation: params.priceAtCalculation,\n maxSlippageBps: params.maxSlippageBps,\n },\n generationAtIntent,\n );\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.closePosition');\n this.#deps.debugLogger.log('[LighterProvider] closePosition failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('closePosition'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async updatePositionTPSL(\n params: UpdatePositionTPSLParams,\n ): Promise<OrderResult> {\n try {\n // Partial TP/SL sizes are NOT wired to this venue path: it always\n // covers the full position. Silently ignoring a requested partial\n // size would close the entire position when the trigger fires, so\n // the request is refused before any read, signer setup or mutation.\n if (\n params.takeProfitSize !== undefined ||\n params.stopLossSize !== undefined\n ) {\n return {\n success: false,\n error:\n 'Lighter TP/SL covers the full position: partial takeProfitSize/stopLossSize are not supported',\n };\n }\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n // The lifecycle boundary is captured BEFORE the position read: a\n // fill landing DURING the read belongs to the operation's window\n // and must count as lifecycle evidence.\n const lifecycleBoundary = Date.now();\n const positions = await this.getPositions();\n const position = positions.find(\n (entry) => entry.symbol === params.symbol,\n );\n if (!position) {\n return {\n success: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n\n // FULL local preflight: construct the entire deterministic\n // replacement payload BEFORE signer setup, the open-orders read and\n // any cancellation. Everything that can fail locally — venue\n // position-size parsing/integerization, trigger/execution price\n // parsing/integerization, bounded client-id allocation — must fail\n // while the existing protection is still in place.\n const wantsReplacement =\n Boolean(params.takeProfitPrice) || Boolean(params.stopLossPrice);\n let singleOrderPayload: LighterCreateOrderWireParams | null = null;\n let groupedOrderPayload: LighterGroupedOrderWireParams | null = null;\n let createdClientIds: number[] = [];\n let createdIdsNeedingFinalCheck: number[] = [];\n let preflightPositionWireSize: number | null = null;\n let preflightPositionSign: 1 | -1 | null = null;\n if (wantsReplacement) {\n // getPositions does not validate venue sizes; a non-finite or\n // sub-tick size must abort here, not after the cancels.\n const signedSize = parseFloat(position.size);\n if (!Number.isFinite(signedSize) || signedSize === 0) {\n return {\n success: false,\n error: `Invalid live position size ${position.size} for ${params.symbol}`,\n };\n }\n const isLong = signedSize > 0;\n const coverSize = Math.abs(signedSize);\n const sizeInt = toSignerWireInteger(\n coverSize,\n market.supportedSizeDecimals,\n );\n preflightPositionWireSize = sizeInt;\n preflightPositionSign = isLong ? 1 : -1;\n // Closing side is opposite the position; trigger market orders\n // execute at a protection price 5% beyond the trigger in the taker\n // direction.\n const isAsk = isLong ? 1 : 0;\n const orderIntents: {\n orderType: number;\n raw: string;\n label: string;\n }[] = [];\n if (params.takeProfitPrice) {\n orderIntents.push({\n orderType: LIGHTER_ORDER_TYPE_TAKE_PROFIT,\n raw: params.takeProfitPrice,\n label: 'takeProfitPrice',\n });\n }\n if (params.stopLossPrice) {\n orderIntents.push({\n orderType: LIGHTER_ORDER_TYPE_STOP_LOSS,\n raw: params.stopLossPrice,\n label: 'stopLossPrice',\n });\n }\n const validatedOrders: {\n orderType: number;\n execInt: number;\n triggerInt: number;\n }[] = [];\n for (const intent of orderIntents) {\n const trigger = parseFinitePositive(intent.raw);\n if (trigger === null) {\n return {\n success: false,\n error: `Invalid ${intent.label} ${intent.raw}: must be a positive number`,\n };\n }\n const execution = isLong ? trigger * 0.95 : trigger * 1.05;\n validatedOrders.push({\n orderType: intent.orderType,\n execInt: toSignerWirePriceInteger(\n execution,\n market.supportedPriceDecimals,\n ),\n triggerInt: toSignerWirePriceInteger(\n trigger,\n market.supportedPriceDecimals,\n ),\n });\n }\n // Only the ids actually required: allocation attempts are bounded\n // and a degenerate RNG must exhaust BEFORE any cancellation.\n const clientOrderIds = this.#allocateClientOrderIndexes(\n validatedOrders.length,\n );\n createdClientIds = clientOrderIds;\n // VENUE CONTRACT (proven live: 'GroupingType is not valid'):\n // CreateGroupedOrders only accepts grouping types 1/2/3 and OCO\n // requires two siblings, so a SINGLE TP or SL must be an ordinary\n // CreateOrder trigger; grouped OCO is reserved for both together.\n const wireOrders = validatedOrders.map(\n (entry, index): LighterCreateOrderWireParams => {\n const clientOrderIndex = clientOrderIds[index];\n if (clientOrderIndex === undefined) {\n throw new Error(\n 'Lighter TP/SL preflight did not allocate a client order id',\n );\n }\n return [\n market.marketId,\n clientOrderIndex,\n String(sizeInt),\n String(entry.execInt),\n isAsk,\n entry.orderType,\n LIGHTER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,\n 1,\n String(entry.triggerInt),\n // Trigger orders rest until fired: the signer expands the -1\n // sentinel to the 28-day default expiry.\n LIGHTER_ORDER_EXPIRY_NONE,\n ];\n },\n );\n const [first, second] = wireOrders;\n if (first === undefined) {\n throw new Error('Lighter TP/SL preflight produced no trigger order');\n }\n if (second === undefined) {\n singleOrderPayload = first;\n } else {\n groupedOrderPayload = [...first, ...second];\n }\n }\n\n // Re-fence BEFORE signer setup: the preflight awaited public reads\n // during which the wallet may have switched, and a stale intent must\n // never create or register the new account's venue key.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n this.#assertSession(generationAtIntent);\n // Pre-mint the auth token OUTSIDE the write lock: #getAuthToken can\n // trigger signer setup, and signer setup queues on the write chain —\n // calling any setup-capable helper from inside the held section\n // would self-deadlock after a bridge reset or unobserved switch.\n const authToken = await this.#getAuthToken();\n this.#assertSession(generationAtIntent);\n // Settlement identity: pending expectations are keyed by the\n // captured normalized address + account index + symbol so another\n // account can never consume (or be blocked by) this account's ids,\n // while a same-account bridge reset or switch-away-and-back retains\n // the reconciliation obligation.\n // Includes the API KEY SLOT: nonces are per key slot, so a journal\n // recorded under one slot must never be reconciled under another.\n const settlementKey = `${this.#boundAddress ?? 'unbound'}:${accountIndex}:${this.#apiKeyIndex}:${params.symbol}`;\n\n // The ENTIRE snapshot -> create -> cancel lifecycle runs as ONE\n // serialized transition on the account's write chain. Two concurrent\n // replacements would otherwise both snapshot the same old trigger,\n // each create a new set, and each cancel only the original — leaving\n // both protection sets live; a concurrent remove could miss a\n // just-created replacement. Cancels are INLINED (not this.cancelOrder)\n // so no nested lock acquisition can deadlock; nonce serialization is\n // preserved because every nonce comes from this section's nextNonce.\n await this.#withVenueWriteLock(\n accountIndex,\n async (nextNonce, submit) => {\n // STRICT direct read with the CAPTURED account/auth/generation:\n // a swallowed [] would make remove \"succeed\" cancelling nothing;\n // a setup-capable helper here could self-deadlock (see auth\n // pre-mint above). Session fences on every read.\n const readActiveRaw = async (): Promise<LighterApiOrder[]> => {\n this.#assertSession(generationAtIntent);\n const response = await this.#clientService.getActiveOrders(\n accountIndex,\n authToken,\n );\n this.#assertSession(generationAtIntent);\n return response.orders;\n };\n // Shared targeted inactive reader (cached, active-first callers,\n // one bounded deep cursor walk per section, market-scoped).\n const readInactiveFor = this.#makeInactiveReader(\n accountIndex,\n authToken,\n generationAtIntent,\n market.marketId,\n );\n\n // VENUE LINEARIZABILITY: if a previous TP/SL transition's\n // settlement never became visible, run it through the SAME\n // obligation state machine as startup recovery — a pending\n // 'cancelling'/'restoring' journal may owe a rollback or a\n // RESTORE, and merely reconciling-then-clearing it here would\n // erase that obligation and leave the position naked.\n // Pending obligations survive provider death via the durable\n // journal. DISK IS AUTHORITATIVE: absence means the obligation\n // was resolved (possibly by another provider) — a stale\n // in-memory copy is dropped, never resurrected.\n const unsettled = await this.#loadTpslJournal(settlementKey);\n if (unsettled === null) {\n this.#tpslUnsettled.delete(settlementKey);\n }\n if (unsettled) {\n const resolved = await this.#settleTpslObligation({\n settlementKey,\n symbol: params.symbol,\n journalEntry: unsettled,\n market,\n accountIndex,\n authToken,\n generation: generationAtIntent,\n readActiveRaw,\n readInactiveFor,\n nextNonce,\n submit,\n });\n if (!resolved) {\n // Keep both records for the next attempt.\n this.#tpslUnsettled.set(settlementKey, unsettled);\n throw new Error(\n `Lighter TP/SL settlement for ${params.symbol} is unresolved; refusing further protection changes until the venue reflects the previous update`,\n );\n }\n // The machine may have PARKED the obligation into the\n // durable manual-recovery doc (releasing the journal slot).\n // The doc is NOT cleared here: only this operation's own\n // SUCCESS — the successor protection authoritatively in\n // force — clears the warning below.\n this.#assertSession(generationAtIntent);\n }\n\n const rawOrders = await readActiveRaw();\n const openOrders = rawOrders.map((order) =>\n adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n ),\n );\n const staleTriggers = openOrders.filter(\n (order) =>\n order.symbol === params.symbol &&\n order.reduceOnly &&\n (Boolean(order.orderType?.includes('stop')) ||\n Boolean(order.orderType?.includes('take')) ||\n order.isTrigger === true),\n );\n // The prior triggers' EXACT wire intents ride along with the\n // journal: a crash can still restore/rollback faithfully. A\n // stale trigger that CANNOT be faithfully restored (unknown\n // venue type/TIF) refuses the whole mutation BEFORE any cancel\n // or create — coercing its semantics on restore is worse than\n // rejecting the update.\n const priorTriggers: TpslPriorTrigger[] = [];\n for (const stale of staleTriggers) {\n const rawRow = rawOrders.find(\n (order) => String(order.orderIndex) === stale.orderId,\n );\n const priorIntent = rawRow\n ? mapRawTriggerToPriorIntent(rawRow, market)\n : null;\n if (!priorIntent) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: existing trigger order ${stale.orderId} cannot be faithfully restored (unsupported type/time-in-force), so it will not be cancelled`,\n );\n }\n priorTriggers.push(priorIntent);\n }\n // OCO grouping is decided by the VENUE'S OWN linkage fields —\n // never inferred from \"one TP plus one SL\". Linkage FAILS\n // CLOSED: ANY dangling or one-sided linkage (parent, to_cancel\n // or to_trigger references that do not form an exact mutual\n // two-leg pair among the triggers being replaced) is an order\n // relationship this integration cannot faithfully re-establish\n // — the mutation is refused BEFORE anything is touched, never\n // classified independent.\n const staleRawRows = staleTriggers.map((stale) =>\n rawOrders.find(\n (order) => String(order.orderIndex) === stale.orderId,\n ),\n );\n // LIVE-VENUE contract (probed): ABSENT linkage is the string\n // sentinel '0' (parent_order_id, to_trigger_order_id_*), never\n // an empty string.\n const linkageSet = (value: string | undefined): boolean =>\n typeof value === 'string' && value.length > 0 && value !== '0';\n const hasAnyLinkage = (row: LighterApiOrder | undefined): boolean =>\n row !== undefined &&\n (linkageSet(row.toCancelOrderId0) ||\n linkageSet(row.parentOrderId) ||\n (typeof row.parentOrderIndex === 'number' &&\n row.parentOrderIndex > 0) ||\n linkageSet(row.toTriggerOrderId0) ||\n linkageSet(row.toTriggerOrderId1));\n const rowLinksTo = (\n source: LighterApiOrder | undefined,\n target: LighterApiOrder | undefined,\n ): boolean =>\n source !== undefined &&\n target !== undefined &&\n linkageSet(source.toCancelOrderId0) &&\n [String(target.orderIndex), target.orderId ?? ''].includes(\n source.toCancelOrderId0 as string,\n );\n const mutualPair =\n priorTriggers.length === 2 &&\n rowLinksTo(staleRawRows[0], staleRawRows[1]) &&\n rowLinksTo(staleRawRows[1], staleRawRows[0]) &&\n // A mutual pair must not ALSO carry parent/OTO relations.\n staleRawRows.every(\n (row) =>\n row !== undefined &&\n !(\n linkageSet(row.parentOrderId) ||\n (typeof row.parentOrderIndex === 'number' &&\n row.parentOrderIndex > 0) ||\n linkageSet(row.toTriggerOrderId0) ||\n linkageSet(row.toTriggerOrderId1)\n ),\n );\n if (!mutualPair && staleRawRows.some(hasAnyLinkage)) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: an existing trigger carries venue linkage (OCO/OTO/parent) this integration cannot faithfully re-establish, so it will not be cancelled`,\n );\n }\n const priorGrouping: 'oco' | 'independent' = mutualPair\n ? 'oco'\n : 'independent';\n if (priorGrouping === 'oco') {\n // Pinned grouped invariants (same closing side, size AND\n // expiry): a linked pair violating them cannot be faithfully\n // re-signed as one group — refuse BEFORE touching it.\n if (\n priorTriggers[0].side !== priorTriggers[1].side ||\n parseStrictDecimal(priorTriggers[0].remainingSize) !==\n parseStrictDecimal(priorTriggers[1].remainingSize) ||\n priorTriggers[0].orderExpiry !== priorTriggers[1].orderExpiry\n ) {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} refused: the existing linked OCO pair cannot be faithfully restored as a group, so it will not be cancelled`,\n );\n }\n }\n // Per-attempt mutation journal, persisted incrementally.\n // RESPONSE-LOSS safety: every attempt is recorded UNKNOWN with\n // its own venue nonce BEFORE submission (the venue may commit\n // even when the response is lost), flips to accepted inside\n // onAccepted (pre-fence), and reconciliation disambiguates each\n // attempt individually via books + nonce.\n const journal: TpslJournalState = {\n attempts: [],\n recordedAt: Date.now(),\n // Collision-resistant across processes: time + counter + two\n // independent random draws (~104 bits of entropy).\n operationId: `op-${Date.now().toString(36)}-${(this.#tpslOperationCounter += 1).toString(36)}-${randomIdSuffix()}`,\n createdAt: lifecycleBoundary,\n nextAttemptId: 1,\n intent: wantsReplacement ? 'replace' : 'remove',\n phase: 'creating',\n priorGrouping,\n priorTriggers,\n };\n const persistJournal = async (): Promise<void> => {\n journal.recordedAt = Date.now();\n await this.#persistTpslJournal(settlementKey, journal);\n };\n // Sign+journal+submit one tracked cancel (stale protection or a\n // rollback of a surviving replacement leg).\n const submitTrackedCancel = async (\n orderId: string,\n role: 'stale' | 'rollback',\n ): Promise<void> => {\n if (role === 'stale' && journal.intent === 'replace') {\n // Durable phase transition BEFORE the old protection is\n // touched: a crash from here on may require a RESTORE.\n // (A 'remove' journal never restores — phase is moot.)\n journal.phase = 'cancelling';\n }\n const cancelNonce = await nextNonce();\n const signedCancel = await this.#getSignerBridge().execute({\n function: '_signCancelOrder',\n params: [accountIndex, market.marketId, orderId, cancelNonce],\n });\n if (signedCancel.error) {\n throw new Error(\n `Failed to cancel trigger order ${orderId}: ${signedCancel.error}`,\n );\n }\n const cancelIdentity = requireSignedTxIdentity(signedCancel);\n const cancelAttempt: TpslCancelAttempt = {\n kind: 'cancel',\n attemptId: nextAttemptIdFor(journal),\n nonce: cancelNonce,\n outcome: 'unknown',\n orderId,\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n role,\n };\n journal.attempts.push(cancelAttempt);\n this.#tpslUnsettled.set(settlementKey, journal);\n await persistJournal();\n await submit(\n LIGHTER_TX_TYPE_CANCEL_ORDER,\n signedCancel.txInfo,\n () => {\n cancelAttempt.outcome = 'accepted';\n },\n {\n txHash: cancelIdentity.txHash,\n expiresAt: cancelIdentity.expiresAt,\n owner: journal.operationId,\n },\n );\n };\n\n // CREATE FIRST, cancel after: if signing or submission of the\n // new protection fails, the old triggers were never touched and\n // the position is never left naked. The temporary overlap is\n // safe — both sets are reduce-only and clamp to the position.\n if (\n wantsReplacement &&\n (singleOrderPayload !== null || groupedOrderPayload !== null)\n ) {\n // The public preflight position read occurred before signer\n // setup and write serialization. Re-read the raw venue position\n // inside the held transition immediately before any create or\n // cancel signature: an intervening fill or side flip would make\n // the captured cover payload under-sized or wrong-sided.\n this.#assertSession(generationAtIntent);\n const liveAccount =\n await this.#clientService.getAccountByIndex(accountIndex);\n this.#assertSession(generationAtIntent);\n const livePosition = liveAccount.accounts[0]?.positions?.find(\n (entry) => entry.symbol === params.symbol,\n );\n const liveMagnitude = livePosition\n ? parseStrictDecimal(livePosition.position)\n : null;\n let liveWireSize: number | null = null;\n if (\n liveMagnitude !== null &&\n Number.isFinite(liveMagnitude) &&\n liveMagnitude > 0 &&\n (livePosition?.sign === 1 || livePosition?.sign === -1)\n ) {\n try {\n liveWireSize = toSignerWireInteger(\n liveMagnitude,\n market.supportedSizeDecimals,\n );\n } catch {\n liveWireSize = null;\n }\n }\n if (\n liveWireSize === null ||\n liveWireSize !== preflightPositionWireSize ||\n livePosition?.sign !== preflightPositionSign\n ) {\n throw new Error(\n `Lighter position changed before TP/SL signing for ${params.symbol}; refresh and retry protection against the current position`,\n );\n }\n const createNonce = await nextNonce();\n // A lone trigger is an ordinary CreateOrder (same wire\n // layout); only a TP+SL pair uses the grouped OCO transaction.\n let signed: LighterTxResult;\n let isSingleTrigger = false;\n if (singleOrderPayload === null) {\n if (groupedOrderPayload === null) {\n throw new Error('Lighter TP/SL preflight payload is missing');\n }\n signed = await this.#getSignerBridge().execute({\n function: '_signCreateGroupedOrders',\n params: [\n accountIndex,\n LIGHTER_GROUPING_ONE_CANCELS_THE_OTHER,\n 2,\n ...groupedOrderPayload,\n createNonce,\n ],\n });\n } else {\n isSingleTrigger = true;\n signed = await this.#getSignerBridge().execute({\n function: '_signCreateOrder',\n params: [accountIndex, ...singleOrderPayload, createNonce],\n });\n }\n if (signed.error) {\n throw new Error(signed.error);\n }\n // UNKNOWN recorded BEFORE the wire — in memory AND durably\n // (awaited): a transport failure after venue commit, or\n // provider/process death, must still leave a reconciliation\n // obligation resolvable by EXACT tx hash. A failed durable\n // write, or a signing result without hash/expiry, aborts the\n // mutation before submission.\n const createIdentity = requireSignedTxIdentity(signed);\n const createAttempt: TpslCreateAttempt = {\n kind: 'create',\n attemptId: nextAttemptIdFor(journal),\n nonce: createNonce,\n outcome: 'unknown',\n clientIds: [...createdClientIds],\n txHash: createIdentity.txHash,\n expiresAt: createIdentity.expiresAt,\n role: 'replacement',\n };\n journal.attempts.push(createAttempt);\n this.#tpslUnsettled.set(settlementKey, journal);\n await persistJournal();\n await submit(\n isSingleTrigger\n ? LIGHTER_TX_TYPE_CREATE_ORDER\n : LIGHTER_TX_TYPE_CREATE_GROUPED_ORDERS,\n signed.txInfo,\n () => {\n // Acceptance OBSERVED (pre-fence): absence from the books\n // can now only mean visibility lag, never never-landed.\n createAttempt.outcome = 'accepted';\n },\n {\n txHash: createIdentity.txHash,\n expiresAt: createIdentity.expiresAt,\n owner: journal.operationId,\n },\n );\n\n // PHASE BARRIER: prove the replacement is on the venue's books\n // BEFORE touching the old protection. An accepted create can\n // be asynchronously rejected/venue-cancelled; cancelling stale\n // triggers first would strip valid protection and discover it\n // afterwards.\n const createVisibility = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n {\n createdClientIds,\n cancelledOrderIds: [],\n },\n );\n if (createVisibility.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n if (createVisibility.outcome === 'created-terminal-failed') {\n // The replacement (or one OCO leg) failed before the old\n // protection was touched. ROLL BACK any leg still resting\n // active so the venue returns to exactly the prior\n // protection, then resolve the obligation for a retry.\n if (createVisibility.survivingActiveClientIds.length > 0) {\n const activeNow = await readActiveRaw();\n const survivorOrderIds: string[] = [];\n for (const clientId of createVisibility.survivingActiveClientIds) {\n const survivor = activeNow.find(\n (order) =>\n String(order.clientOrderIndex) === String(clientId),\n );\n if (survivor) {\n survivorOrderIds.push(String(survivor.orderIndex));\n await submitTrackedCancel(\n String(survivor.orderIndex),\n 'rollback',\n );\n }\n }\n const rollback = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n { createdClientIds: [], cancelledOrderIds: survivorOrderIds },\n );\n if (rollback.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n }\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n throw new Error(\n `Lighter replacement TP/SL for ${params.symbol} was cancelled or rejected by the venue before becoming active; the existing protection was left untouched`,\n );\n }\n // Barrier-proved TERMINAL success is immutable: skip those ids\n // in the final settlement check (no duplicate high-weight\n // inactive read); active-at-barrier ids are still re-verified\n // there (they can terminal-fail before the cancels settle).\n createdIdsNeedingFinalCheck = createVisibility.executedCreated\n ? []\n : createdClientIds;\n if (createVisibility.executedCreated) {\n // The trigger EXECUTED before activation was observed (an\n // immediate/crossed TP/SL): not a failure — the position may\n // already be closed. Stale triggers below are still cleaned\n // up as reduce-only leftovers.\n this.#deps.debugLogger.log(\n '[LighterProvider] replacement trigger executed immediately',\n { symbol: params.symbol },\n );\n }\n }\n\n for (const order of staleTriggers) {\n await submitTrackedCancel(order.orderId, 'stale');\n }\n\n // Await authoritative visibility of the CANCELS before releasing\n // the lock (created ids were proven at the phase barrier): the\n // next queued transition must never snapshot a stale book.\n if (journal.attempts.length > 0) {\n const settled = await this.#awaitTpslVisibility(\n readActiveRaw,\n readInactiveFor,\n {\n // Barrier-proved terminal successes are immutable and\n // excluded; active-at-barrier ids are re-verified.\n createdClientIds: createdIdsNeedingFinalCheck,\n cancelledOrderIds: journal.attempts\n .filter(\n (attempt): attempt is TpslCancelAttempt =>\n attempt.kind === 'cancel',\n )\n .map((attempt) => attempt.orderId),\n },\n );\n if (settled.outcome === 'timeout') {\n throw new Error(\n `Lighter TP/SL update for ${params.symbol} was submitted but its settlement is not yet visible; further protection changes are blocked until the venue reflects it`,\n );\n }\n if (settled.outcome === 'created-terminal-failed') {\n // Active at the phase barrier but venue-cancelled/rejected\n // AFTER the old protection was already cancelled. The\n // venue exposes no atomic primitive that could prove a\n // re-created trigger attaches to the same position\n // lifecycle, so nothing is auto-restored: the warning\n // parks DURABLY in the manual-recovery doc (surfaced via\n // getPendingManualRecoveries) and any surviving leg is\n // deliberately left as the only remaining protection.\n const rawNow = await readActiveRaw();\n const survivingOrderIds = rawNow\n .filter((order) =>\n journal.attempts.some(\n (attempt) =>\n attempt.kind === 'create' &&\n attempt.clientIds.some(\n (clientId) =>\n String(order.clientOrderIndex) === String(clientId),\n ),\n ),\n )\n .map((order) => String(order.orderIndex));\n await this.#writeTpslManualRecovery({\n settlementKey,\n symbol: params.symbol,\n reason:\n 'Replacement TP/SL order was cancelled or rejected by the venue after the previous protection was already removed',\n priorIntent: journal.intent,\n priorTriggers: journal.priorTriggers,\n survivingOrderIds,\n operationId: journal.operationId,\n recordedAt: Date.now(),\n });\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n this.#assertSession(generationAtIntent);\n throw new Error(\n `Lighter replacement TP/SL for ${params.symbol} was cancelled or rejected by the venue after the previous protection was already removed; the position's protection could NOT be safely re-established automatically — MANUAL re-establishment is required (a new explicit TP/SL update resolves this state)`,\n );\n }\n await this.#clearTpslJournal(settlementKey, journal.operationId);\n // A switch DURING the final journal-clear await must not let\n // stale A protection report success under B.\n this.#assertSession(generationAtIntent);\n }\n // ONLY here — the successor protection intent authoritatively\n // in force (created and settled, or removal completed) — may a\n // parked manual-recovery warning for this symbol be cleared. A\n // failed successor leaves the warning untouched.\n await this.#clearTpslManualRecovery(settlementKey);\n this.#assertSession(generationAtIntent);\n },\n generationAtIntent,\n );\n return { success: true };\n } catch (error) {\n const wrappedError = ensureError(\n error,\n 'LighterProvider.updatePositionTPSL',\n );\n this.#deps.debugLogger.log(\n '[LighterProvider] updatePositionTPSL failed',\n {\n error: String(wrappedError),\n ...this.#getErrorContext('updatePositionTPSL'),\n },\n );\n return { success: false, error: wrappedError.message };\n }\n }\n\n async updateMargin(params: UpdateMarginParams): Promise<MarginResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n success: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n // Strict full-string parse: '5USD' must not prefix-parse into\n // signed intent. Signed values are meaningful here (add/remove).\n const amount = parseStrictDecimal(params.amount) ?? Number.NaN;\n if (!Number.isFinite(amount) || amount === 0) {\n return {\n success: false,\n error: 'updateMargin requires a non-zero amount',\n };\n }\n // USDC uses 6 decimals. Integerize BEFORE signer setup so a huge\n // finite amount fails closed with zero bridge calls instead of\n // raw-scaling to an unsafe integer inside signer params.\n const marginAmountInt = toSignerWireInteger(Math.abs(amount), 6);\n // Re-fence before signer setup: the market lookup above awaited, and\n // a stale intent must never initialize the new account's signer.\n this.#assertSession(generationAtIntent);\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n // USDC uses 6 decimals; direction 1 adds isolated margin, 0 removes it\n // (types/txtypes/constants.go: RemoveFromIsolatedMargin=0, Add=1).\n await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signUpdateMargin',\n params: [\n accountIndex,\n market.marketId,\n marginAmountInt,\n amount > 0 ? 1 : 0,\n nonce,\n ],\n });\n if (signed.error) {\n throw new Error(signed.error);\n }\n return await submit(\n LIGHTER_TX_TYPE_UPDATE_MARGIN,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `updateMargin:${params.symbol}:${params.amount}`,\n },\n );\n },\n generationAtIntent,\n );\n return { success: true };\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.updateMargin');\n this.#deps.debugLogger.log('[LighterProvider] updateMargin failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('updateMargin'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n async withdraw(params: WithdrawParams): Promise<WithdrawResult> {\n try {\n this.#ensureSessionBinding();\n const generationAtIntent = this.#sessionGeneration;\n const amount = parseFinitePositive(params.amount);\n if (amount === null) {\n return { success: false, error: 'withdraw requires a positive amount' };\n }\n // Enforce the advertised route minimum: getWithdrawalRoutes reports\n // minWithdrawUsdc, and signing below it would either burn a nonce on\n // a venue rejection or strand dust.\n const minWithdraw = parseFloat(\n LIGHTER_BRIDGE_CONFIG[this.#isTestnet ? 'testnet' : 'mainnet']\n .minWithdrawUsdc,\n );\n if (amount < minWithdraw) {\n return {\n success: false,\n error: `Withdrawal amount ${params.amount} is below the Lighter minimum of ${minWithdraw} USDC`,\n };\n }\n // USDC uses 6 decimals on zkLighter. Integerize BEFORE signer setup:\n // overflow/sub-tick amounts fail closed with zero bridge calls,\n // matching validateWithdrawal exactly.\n const assetAmount = String(toSignerWireInteger(amount, 6));\n await this.#ensureSignerReady();\n const accountIndex = await this.#ensureAccountIndex();\n const result = await this.#withVenueNonce(\n accountIndex,\n async (nonce, submit) => {\n const signed = await this.#getSignerBridge().execute({\n function: '_signWithdraw',\n params: [\n accountIndex,\n LIGHTER_USDC_ASSET_INDEX,\n 0,\n assetAmount,\n nonce,\n ],\n });\n if (signed.error) {\n throw new Error(signed.error);\n }\n return await submit(\n LIGHTER_TX_TYPE_WITHDRAW,\n signed.txInfo,\n undefined,\n {\n ...extractDispatchIdentity(signed),\n intent: `withdraw:${params.amount}`,\n },\n );\n },\n generationAtIntent,\n );\n return { success: true, txHash: result.txHash };\n } catch (error) {\n const wrappedError = ensureError(error, 'LighterProvider.withdraw');\n this.#deps.debugLogger.log('[LighterProvider] withdraw failed', {\n error: String(wrappedError),\n ...this.#getErrorContext('withdraw'),\n });\n return { success: false, error: wrappedError.message };\n }\n }\n\n // ============================================================================\n // History Operations (POC: stubbed)\n // ============================================================================\n\n async getOrderFills(\n params?: GetOrderFillsParams,\n _options?: PerpsReadOptions,\n ): Promise<OrderFill[]> {\n return await this.#getOrderFillsForQuery(params);\n }\n\n readonly #getOrderFillsForQuery = async (\n params?: LighterFillQuery,\n ): Promise<OrderFill[]> => {\n const selectedAddress = this.#walletService.getUserAddress().toLowerCase();\n const requestedAddress =\n params?.user?.toLowerCase() ??\n params?.accountId?.split(':').at(-1)?.toLowerCase();\n if (requestedAddress && requestedAddress !== selectedAddress) {\n throw new Error(\n 'Lighter fill history can only query the selected wallet account',\n );\n }\n if (params?.aggregateByTime) {\n throw new Error('Lighter fill history does not support aggregateByTime');\n }\n if (\n params?.startTime !== undefined &&\n params.endTime !== undefined &&\n params.startTime > params.endTime\n ) {\n throw new Error('Lighter fill history startTime must not exceed endTime');\n }\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const token = await this.#getAuthToken();\n const markets = await this.#ensureMarkets();\n const requestedLimit = Math.min(Math.max(params?.limit ?? 50, 1), 100);\n const marketId = params?.symbol\n ? markets.get(params.symbol)?.marketId\n : undefined;\n if (params?.symbol && marketId === undefined) {\n return [];\n }\n const needsPaging =\n params?.startTime !== undefined ||\n params?.endTime !== undefined ||\n params?.symbol !== undefined;\n const pageLimit = needsPaging ? 100 : requestedLimit;\n const fills: OrderFill[] = [];\n let cursor: string | undefined;\n let reachedStartBoundary = false;\n for (let page = 0; page < 100; page += 1) {\n const { trades, nextCursor } = await this.#clientService.getTrades(\n accountIndex,\n token,\n { limit: pageLimit, cursor, marketId },\n );\n this.#assertSession(generation);\n for (const trade of trades) {\n const fill = adaptFillFromLighterTrade(\n trade,\n this.#marketsById.get(trade.marketId)?.symbol ??\n String(trade.marketId),\n accountIndex,\n );\n if (\n (params?.startTime === undefined ||\n fill.timestamp >= params.startTime) &&\n (params?.endTime === undefined || fill.timestamp <= params.endTime)\n ) {\n fills.push(fill);\n }\n if (\n params?.startTime !== undefined &&\n fill.timestamp < params.startTime\n ) {\n reachedStartBoundary = true;\n }\n }\n cursor = nextCursor;\n if (\n fills.length >= requestedLimit ||\n cursor === undefined ||\n trades.length === 0 ||\n reachedStartBoundary\n ) {\n return fills.slice(0, requestedLimit);\n }\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} fill history pagination did not reach the requested boundary`,\n );\n } catch (error) {\n this.#deps.debugLogger.log('[LighterProvider] getOrderFills failed', {\n error: String(error),\n });\n throw error;\n }\n };\n\n async getOrFetchFills(params?: GetOrFetchFillsParams): Promise<OrderFill[]> {\n return await this.#getOrderFillsForQuery(params);\n }\n\n async getHistoricalPortfolio(\n _params?: GetHistoricalPortfolioParams,\n ): Promise<HistoricalPortfolioResult> {\n // Capability-gated: the venue's PnLEntry carries trade, pool, spot, and\n // staking flows; reconstructing account value from the trade flows\n // alone is materially wrong for accounts using the other routes, and\n // no captured payload proves the full-flow semantics. Reporting a\n // plausible number would show false daily history — fail explicitly.\n throw new Error(\n 'Historical portfolio is unavailable for Lighter: account-value reconstruction requires pool/spot/staking flow semantics that are not yet verified against the venue',\n );\n }\n\n async getFunding(\n _params?: GetFundingParams,\n _options?: PerpsReadOptions,\n ): Promise<Funding[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const token = await this.#getAuthToken();\n await this.#ensureMarkets();\n const response = await this.#clientService.getPositionFundings(\n accountIndex,\n token,\n );\n this.#assertSession(generation);\n return response.positionFundings.map((entry) => ({\n symbol:\n this.#marketsById.get(entry.marketId)?.symbol ??\n String(entry.marketId),\n // `change` is the signed USDC funding flow for the account's side.\n amountUsd: entry.change,\n rate: entry.rate,\n timestamp: entry.timestamp * 1000,\n }));\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log('[LighterProvider] getFunding failed', {\n error: String(error),\n });\n return [];\n }\n }\n\n async getUserNonFundingLedgerUpdates(params?: {\n accountId?: string;\n startTime?: number;\n endTime?: number;\n }): Promise<RawLedgerUpdate[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n const l1Address = this.#walletService.getUserAddress();\n const [deposits, withdraws, transfers] = await Promise.all([\n this.#clientService.getDepositHistory(\n accountIndex,\n l1Address,\n authToken,\n ),\n this.#clientService.getWithdrawHistory(accountIndex, authToken),\n this.#clientService.getTransferHistory(accountIndex, authToken),\n ]);\n const updates: RawLedgerUpdate[] = [\n ...(deposits.deposits ?? []).map((entry) => ({\n hash: entry.l1TxHash,\n time: entry.timestamp,\n delta: { type: 'deposit', usdc: entry.amount },\n })),\n ...(withdraws.withdraws ?? []).map((entry) => ({\n hash: entry.l1TxHash,\n time: entry.timestamp,\n delta: { type: 'withdraw', usdc: `-${entry.amount}` },\n })),\n ...(transfers.transfers ?? []).map((entry) => ({\n hash: entry.txHash,\n time: entry.timestamp,\n delta: adaptLighterTransferDelta(entry),\n })),\n ].sort((first, second) => second.time - first.time);\n const { startTime, endTime } = params ?? {};\n this.#assertSession(generation);\n return updates.filter(\n (update) =>\n (startTime === undefined || update.time >= startTime) &&\n (endTime === undefined || update.time <= endTime),\n );\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log(\n '[LighterProvider] getUserNonFundingLedgerUpdates failed',\n { error: String(error) },\n );\n return [];\n }\n }\n\n async getUserHistory(params?: {\n accountId?: CaipAccountId;\n startTime?: number;\n endTime?: number;\n }): Promise<UserHistoryItem[]> {\n try {\n this.#ensureSessionBinding();\n const generation = this.#sessionGeneration;\n const accountIndex = await this.#ensureAccountIndex();\n const authToken = await this.#getAuthToken();\n const l1Address = this.#walletService.getUserAddress();\n const [deposits, withdraws] = await Promise.all([\n this.#clientService.getDepositHistory(\n accountIndex,\n l1Address,\n authToken,\n ),\n this.#clientService.getWithdrawHistory(accountIndex, authToken),\n ]);\n const toStatus = (venueStatus: string): UserHistoryItem['status'] => {\n if (venueStatus === 'completed') {\n return 'completed';\n }\n return venueStatus === 'failed' ? 'failed' : 'pending';\n };\n const items: UserHistoryItem[] = [\n ...(deposits.deposits ?? []).map((entry) => ({\n id: `deposit-${entry.id}`,\n timestamp: entry.timestamp,\n type: 'deposit' as const,\n amount: entry.amount,\n asset: 'USDC',\n txHash: entry.l1TxHash,\n status: toStatus(entry.status),\n details: { source: 'lighter' },\n })),\n ...(withdraws.withdraws ?? []).map((entry) => ({\n id: `withdrawal-${entry.id}`,\n timestamp: entry.timestamp,\n type: 'withdrawal' as const,\n amount: entry.amount,\n asset: 'USDC',\n txHash: entry.l1TxHash,\n status: toStatus(entry.status),\n details: { source: 'lighter' },\n })),\n ].sort((first, second) => second.timestamp - first.timestamp);\n const { startTime, endTime } = params ?? {};\n this.#assertSession(generation);\n return items.filter(\n (item) =>\n (startTime === undefined || item.timestamp >= startTime) &&\n (endTime === undefined || item.timestamp <= endTime),\n );\n } catch (error) {\n if (this.#mustSurfaceReadError(error)) {\n // Capability gates must surface, never degrade into empty state.\n throw error;\n }\n this.#deps.debugLogger.log('[LighterProvider] getUserHistory failed', {\n error: String(error),\n });\n return [];\n }\n }\n\n // ============================================================================\n // Validation (POC: minimal)\n // ============================================================================\n\n async validateDeposit(\n _params: DepositParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n return { isValid: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n\n async validateOrder(\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n // ONE error-to-invalid boundary: a validator RESOLVES, never rejects,\n // whichever awaited venue read fails (markets, margin metadata, fresh\n // price, live positions, data integrity).\n try {\n return await this.#validateOrderChecks(params);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n\n readonly #validateOrderChecks = async (\n params: OrderParams,\n ): Promise<{ isValid: boolean; error?: string }> => {\n if (params.marginMode !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_MARGIN_MODE_UNSUPPORTED,\n };\n }\n // Mirrors placeOrder's own rejections so validation never approves an\n // order shape the placement path would refuse.\n if (params.orderType !== 'limit' && params.orderType !== 'market') {\n return { isValid: false, error: LIGHTER_NOT_SUPPORTED_ERROR };\n }\n if (params.takeProfitPrice || params.stopLossPrice) {\n return {\n isValid: false,\n error:\n 'Lighter does not support TP/SL attached at placement; place the order, then call updatePositionTPSL',\n };\n }\n if (params.timeInForce === 'ALO') {\n return {\n isValid: false,\n error: 'Lighter placement does not support post-only (ALO) yet',\n };\n }\n if (params.orderType === 'limit' && !params.price) {\n return { isValid: false, error: 'Limit order requires a price' };\n }\n if (params.orderType === 'limit' && params.price !== undefined) {\n // Strict finite parity with placement, LIMIT ONLY: 'Infinity' and\n // prefix-numeric strings ('90000USD') both parse under a bare\n // parseFloat check but placement refuses them. Market placement\n // ignores params.price entirely (fresh venue price), so rejecting\n // it here would fail orders placement accepts.\n if (parseFinitePositive(params.price) === null) {\n return {\n isValid: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n }\n const leverageError = lighterLeverageError(params.leverage);\n if (leverageError) {\n return { isValid: false, error: leverageError };\n }\n let usdAmount: number | undefined;\n if (params.usdAmount !== undefined) {\n const parsedUsd = parseFinitePositive(params.usdAmount);\n if (parsedUsd === null) {\n return {\n isValid: false,\n error: `Invalid usdAmount ${params.usdAmount}: must be a positive number`,\n };\n }\n usdAmount = parsedUsd;\n }\n const hasUsdSizing = usdAmount !== undefined;\n if (!hasUsdSizing && parseFinitePositive(params.size) === null) {\n return { isValid: false, error: 'Order size must be positive' };\n }\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n isValid: false,\n error: `Unknown Lighter market: ${params.symbol}`,\n };\n }\n if (params.leverage !== undefined) {\n // Same authoritative-metadata requirement as placement.\n const maxLeverage = await this.#requireMarketMaxLeverage(params.symbol);\n if (maxLeverage === null) {\n return {\n isValid: false,\n error: `Cannot validate leverage for ${params.symbol}: venue margin metadata unavailable`,\n };\n }\n if (params.leverage > maxLeverage) {\n return {\n isValid: false,\n error: `Invalid leverage ${params.leverage}: exceeds the ${params.symbol} maximum of ${maxLeverage}x`,\n };\n }\n }\n // Reference-price parity with placement: a MARKET order sizes at the\n // FRESH venue price through the SAME resolver (fail-closed missing\n // price, snapshot and slippage intent validation, drift) — the\n // caller's price/currentPrice is never trusted for min-size. A LIMIT\n // order sizes at the caller's (finite-validated) price. The EXECUTION\n // price is derived through the same helper placement signs with, so\n // the wire-range check below inspects the exact signed value.\n let referencePrice: number;\n let executionPrice: number;\n if (params.orderType === 'market') {\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? (params.slippage ?? 0.05)\n : params.maxSlippageBps / 10_000;\n // A validator must RESOLVE to an invalid result, never reject: the\n // fresh-price lookup can throw on REST failure.\n let resolved:\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string };\n try {\n resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n if (resolved.error !== null) {\n return { isValid: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n params.isBuy,\n slippageFraction,\n );\n } else {\n referencePrice = parseFloat(\n params.price ?? String(params.currentPrice ?? 0),\n );\n executionPrice = referencePrice;\n }\n if (referencePrice > 0) {\n // USD-derived sizes snap onto the venue grid (placement parity);\n // explicit size strings stay verbatim.\n const requestedSize =\n usdAmount === undefined\n ? parseFloat(params.size)\n : snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n );\n if (usdAmount === undefined) {\n try {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n fromLighterInteger(\n requestedSizeInt,\n market.supportedSizeDecimals,\n ) !== requestedSize\n ) {\n return {\n isValid: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n const minSize = isLighterMakerOrder(params)\n ? computeLighterMinOrderSize(market, referencePrice)\n : 0;\n if (minSize > 0 && requestedSize < minSize) {\n // EXACTLY the placement rule: only reduce-only orders may bump to\n // the venue minimum, and only when the live position verifies a\n // full close; isFullClose remains an untrusted hint. The live read\n // can THROW (capability gates, venue-data integrity): a validator\n // must resolve to an explicit invalid result, never reject.\n let verifiedFullClose = false;\n if (params.reduceOnly) {\n try {\n verifiedFullClose = await this.#isVerifiedFullClose(\n params.symbol,\n requestedSize,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder')\n .message,\n };\n }\n }\n if (!verifiedFullClose) {\n return {\n isValid: false,\n error: `Order size ${requestedSize} is below the Lighter minimum of ${minSize} ${params.symbol}`,\n };\n }\n }\n // Wire-format parity: placement integerizes size and the\n // slippage-adjusted EXECUTION price; toLighterInteger throws on\n // safe-integer overflow and wire-zero there; surface the identical\n // error here so validation never approves an order the signer path\n // refuses (a safe reference can still overflow after +5%).\n try {\n toSignerWireInteger(requestedSize, market.supportedSizeDecimals);\n toSignerWirePriceInteger(executionPrice, market.supportedPriceDecimals);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateOrder').message,\n };\n }\n }\n return { isValid: true };\n };\n\n async validateClosePosition(\n params: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n // Same single error-to-invalid boundary as validateOrder.\n try {\n return await this.#validateClosePositionChecks(params);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n }\n\n readonly #validateClosePositionChecks = async (\n rawParams: ClosePositionParams,\n ): Promise<{ isValid: boolean; error?: string }> => {\n const params = this.#normalizeCloseParams(rawParams);\n // Same shape rules the execution path enforces.\n const shapeError = this.#validateCloseShape(params);\n if (shapeError) {\n return { isValid: false, error: shapeError };\n }\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n if (!market) {\n return {\n isValid: false,\n error: `Unknown Lighter market ${params.symbol}`,\n };\n }\n // Live sizing parity with closePosition→placeOrder: a validator that\n // approves a close the execution path rejects is worse than none.\n // Capability and data-integrity errors from the read surface as an\n // explicit invalid result, never an exception or a silent empty.\n let positions: Position[];\n try {\n positions = await this.getPositions();\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n const signedHeld = parseFloat(\n positions.find((entry) => entry.symbol === params.symbol)?.size ?? '0',\n );\n const held = Math.abs(signedHeld);\n if (held === 0) {\n return {\n isValid: false,\n error: `No open Lighter position for ${params.symbol}`,\n };\n }\n // Order-type-specific pricing, matching execution exactly: a LIMIT\n // close is sized at the caller's price (which must be a finite\n // positive number — never silently replaced by a live price the\n // execution path would not use); a MARKET close resolves the FRESH\n // venue price through the SAME helper as placement, inheriting its\n // fail-closed missing-price and drift semantics.\n let referencePrice: number;\n let executionPrice: number;\n if ((params.orderType ?? 'market') === 'limit') {\n const parsedLimitPrice = parseFinitePositive(params.price ?? '');\n if (parsedLimitPrice === null) {\n return {\n isValid: false,\n error: `Invalid limit price ${params.price}: must be a positive number`,\n };\n }\n referencePrice = parsedLimitPrice;\n executionPrice = referencePrice;\n } else {\n const slippageFraction =\n params.maxSlippageBps === undefined\n ? 0.05\n : params.maxSlippageBps / 10_000;\n // Same validator contract as validateOrder: REST failures resolve.\n let resolved:\n | { referencePrice: number; error: null }\n | { referencePrice: null; error: string };\n try {\n resolved = await this.#resolveMarketReferencePrice(\n params.symbol,\n slippageFraction,\n params.priceAtCalculation,\n );\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n if (resolved.error !== null) {\n return { isValid: false, error: resolved.error };\n }\n referencePrice = resolved.referencePrice;\n // Closing is the opposite side: a SHORT closes with a BUY, whose\n // +slippage protection price is what placement actually signs.\n executionPrice = deriveLighterExecutionPrice(\n referencePrice,\n signedHeld < 0,\n slippageFraction,\n );\n }\n if (referencePrice > 0) {\n const usdAmount = parseFloat(params.usdAmount ?? '');\n // USD-derived sizes snap onto the venue grid (placement parity);\n // explicit size strings stay verbatim.\n const requestedSize =\n Number.isFinite(usdAmount) && usdAmount > 0\n ? snapToLighterSizeGrid(\n usdAmount / referencePrice,\n market.supportedSizeDecimals,\n )\n : parseFloat(params.size ?? String(held));\n const hasExplicitSize =\n params.usdAmount === undefined && params.size !== undefined;\n // Wire-format parity with the placement path closePosition uses:\n // the EXECUTION price is what gets integerized and signed.\n try {\n const requestedSizeInt = toSignerWireInteger(\n requestedSize,\n market.supportedSizeDecimals,\n );\n if (\n hasExplicitSize &&\n fromLighterInteger(requestedSizeInt, market.supportedSizeDecimals) !==\n requestedSize\n ) {\n return {\n isValid: false,\n error: `Order size ${params.size} does not align with the Lighter size grid`,\n };\n }\n toSignerWirePriceInteger(executionPrice, market.supportedPriceDecimals);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateClosePosition')\n .message,\n };\n }\n }\n return { isValid: true };\n };\n\n async validateWithdrawal(\n params: WithdrawParams,\n ): Promise<{ isValid: boolean; error?: string }> {\n const amount = parseFinitePositive(params.amount ?? '');\n if (amount === null) {\n return { isValid: false, error: 'Withdrawal amount must be positive' };\n }\n // Advertised route-minimum parity with withdraw.\n const minWithdraw = parseFloat(\n LIGHTER_BRIDGE_CONFIG[this.#isTestnet ? 'testnet' : 'mainnet']\n .minWithdrawUsdc,\n );\n if (amount < minWithdraw) {\n return {\n isValid: false,\n error: `Withdrawal amount ${params.amount} is below the Lighter minimum of ${minWithdraw} USDC`,\n };\n }\n // Scaled wire-range parity with withdraw's own integerization.\n try {\n toSignerWireInteger(amount, 6);\n } catch (error) {\n return {\n isValid: false,\n error: ensureError(error, 'LighterProvider.validateWithdrawal').message,\n };\n }\n return { isValid: true };\n }\n\n // ============================================================================\n // Calculations (POC: coarse)\n // ============================================================================\n\n async calculateLiquidationPrice(\n params: LiquidationPriceParams,\n ): Promise<string> {\n // Cross liquidation is account-wide and cannot be derived truthfully\n // from this per-position input. Live positions carry the venue's\n // authoritative liquidationPrice; previews support isolated only.\n if (params.marginType === 'cross') {\n throw new Error(\n 'Lighter cross-margin liquidation previews require account-wide collateral and position inputs that are unavailable',\n );\n }\n const { entryPrice, leverage, direction } = params;\n if (\n !isFinite(entryPrice) ||\n !isFinite(leverage) ||\n entryPrice <= 0 ||\n leverage <= 0\n ) {\n return '0.00';\n }\n const maintenanceFraction = await this.calculateMaintenanceMargin({\n asset: params.asset ?? '',\n });\n const initialMargin = 1 / leverage;\n if (initialMargin <= maintenanceFraction) {\n throw new Error(\n `Invalid leverage: ${leverage}x cannot cover the ${maintenanceFraction * 100}% maintenance requirement`,\n );\n }\n const side = direction === 'long' ? 1 : -1;\n const marginAvailable = initialMargin - maintenanceFraction;\n const denominator = 1 - maintenanceFraction * side;\n if (Math.abs(denominator) < 0.0001) {\n return String(entryPrice);\n }\n const liquidationPrice =\n entryPrice - (side * marginAvailable * entryPrice) / denominator;\n return String(Math.max(0, liquidationPrice));\n }\n\n async calculateMaintenanceMargin(\n params: MaintenanceMarginParams,\n ): Promise<number> {\n // The venue publishes per-market maintenance margin fractions\n // (hundredths of a percent, e.g. 240 = 2.4%) in orderBookDetails.\n await this.#ensureMarketMargins();\n const maintenance = this.#marginBySymbol.get(params.asset)?.maintenance;\n if (maintenance && maintenance > 0) {\n return maintenance / 10_000;\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} maintenance margin metadata unavailable for ${params.asset || 'unknown market'}`,\n );\n }\n\n /**\n * Margin mode the venue will accept for a leverage update on this\n * market: an existing position's current mode (the venue refuses mode\n * changes while a position is open; a missing field means the venue\n * default, cross), otherwise ISOLATED — the only mode the app manages.\n *\n * @param symbol - Market symbol.\n * @returns The wire margin mode for UpdateLeverage.\n */\n readonly #resolveMarginModeForSymbol = async (\n symbol: string,\n ): Promise<number> => {\n try {\n const accountIndex = await this.#ensureAccountIndex();\n const response =\n await this.#clientService.getAccountByIndex(accountIndex);\n const row = response.accounts?.[0]?.positions?.find(\n (position) =>\n position.symbol === symbol && parseFloat(position.position) !== 0,\n );\n if (row) {\n return row.marginMode ?? LIGHTER_MARGIN_MODE_CROSS;\n }\n } catch {\n // Fall through: prefer isolated; a wrong guess surfaces as an\n // explicit venue rejection of the leverage update, never as state.\n }\n return LIGHTER_MARGIN_MODE_ISOLATED;\n };\n\n /** Per-market margin fractions + last price from orderBookDetails. */\n readonly #marginBySymbol = new Map<string, LighterMarginMetadata>();\n\n /**\n * Synchronous per-market max leverage from the authoritative margin cache.\n *\n * Inactive markets cannot increase exposure. When Lighter has retired their\n * risk metadata, the position's current leverage is therefore the highest\n * leverage that can be reported without inventing a tradable venue limit.\n *\n * @param position - Position carrying the market id and current margin.\n * @returns Max leverage for the market.\n * @throws If the market identity or margin metadata is unavailable.\n */\n readonly #maxLeverageForPosition = (\n position: Pick<LighterApiPosition, 'marketId' | 'initialMarginFraction'>,\n ): number => {\n const { marketId } = position;\n const symbol = this.#marketsById.get(marketId)?.symbol;\n const metadata =\n (symbol ? this.#marginBySymbol.get(symbol) : undefined) ??\n [...this.#marginBySymbol.values()].find(\n (entry) => entry.marketId === marketId,\n );\n if (metadata) {\n return deriveLighterMaxLeverage(metadata.minInitial, marketId);\n }\n if (this.#marketsById.get(marketId)?.status === 'inactive') {\n const marginFraction = parseStrictDecimal(position.initialMarginFraction);\n const currentLeverage =\n marginFraction !== null && marginFraction > 0\n ? Math.round(100 / marginFraction)\n : 0;\n if (Number.isSafeInteger(currentLeverage) && currentLeverage > 0) {\n return currentLeverage;\n }\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} margin metadata unavailable for market ${marketId}`,\n );\n };\n\n /**\n * Authoritative per-market max leverage for trading validation. This returns\n * null when venue metadata is missing or unreadable so placement can return\n * its validation result instead of throwing.\n *\n * @param symbol - Market symbol.\n * @returns The published max leverage, or null when unavailable.\n */\n readonly #requireMarketMaxLeverage = async (\n symbol: string,\n ): Promise<number | null> => {\n try {\n await this.#ensureMarketMargins();\n } catch {\n return null;\n }\n const metadata = this.#marginBySymbol.get(symbol);\n if (!metadata) {\n return null;\n }\n try {\n return deriveLighterMaxLeverage(metadata.minInitial, symbol);\n } catch {\n return null;\n }\n };\n\n /** When the margin-metadata cache was last refreshed (0 = never). */\n #marginFetchedAt = 0;\n\n /** In-flight authoritative margin refresh, shared by the stale epoch. */\n #marginRefreshInFlight: Promise<void> | null = null;\n\n readonly #ensureMarketMargins = async (): Promise<void> => {\n // TTL refresh: metadata cached once for the whole session would keep\n // validating leverage against a stale (possibly higher) max. On\n // expiry the fetch re-runs; if it fails, the throw propagates and\n // every authoritative risk caller fails closed until a later retry.\n if (\n this.#marginBySymbol.size > 0 &&\n Date.now() - this.#marginFetchedAt < LIGHTER_MARGIN_METADATA_TTL_MS\n ) {\n return;\n }\n // ONE authoritative request per stale epoch: overlapping independent\n // fetches can resolve out of order, letting a DELAYED older payload\n // overwrite a fresher cap for a full TTL. A rejection propagates to\n // every waiter of this epoch (fail closed) and clears the in-flight\n // slot in finally so a later call can retry.\n if (!this.#marginRefreshInFlight) {\n this.#marginRefreshInFlight = (async (): Promise<void> => {\n try {\n const details = await this.#clientService.getOrderBookDetails();\n if (this.#isDisconnected) {\n return;\n }\n // Atomic replacement: set()-ing into the old map would let a\n // symbol REMOVED from fresh metadata keep its stale cap forever.\n // The timestamp only advances on success.\n const fresh = new Map<string, LighterMarginMetadata>();\n for (const detail of details.orderBookDetails) {\n if (isInactiveMarketWithoutUsableRiskMetadata(detail)) {\n continue;\n }\n if (detail.minInitialMarginFraction !== undefined) {\n deriveLighterMaxLeverage(\n detail.minInitialMarginFraction,\n detail.symbol,\n );\n }\n if (\n detail.maintenanceMarginFraction !== undefined &&\n (!Number.isSafeInteger(detail.maintenanceMarginFraction) ||\n detail.maintenanceMarginFraction < 1 ||\n detail.maintenanceMarginFraction > 10_000)\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid maintenance margin fraction for market ${detail.symbol}`,\n );\n }\n fresh.set(detail.symbol, {\n marketId: detail.marketId,\n minInitial: detail.minInitialMarginFraction,\n maintenance: detail.maintenanceMarginFraction,\n lastTradePrice: detail.lastTradePrice,\n });\n }\n this.#marginBySymbol.clear();\n for (const [symbol, entry] of fresh) {\n this.#marginBySymbol.set(symbol, entry);\n }\n this.#marginFetchedAt = Date.now();\n } finally {\n this.#marginRefreshInFlight = null;\n }\n })();\n }\n await this.#marginRefreshInFlight;\n };\n\n async getMaxLeverage(asset: string): Promise<number> {\n // The venue publishes per-market minimum initial margin fractions\n // (hundredths of a percent): 400 → 25x. Missing metadata is unavailable,\n // never evidence that the global maximum applies to this market.\n await this.#ensureMarketMargins();\n const metadata = this.#marginBySymbol.get(asset);\n if (metadata) {\n return deriveLighterMaxLeverage(metadata.minInitial, asset);\n }\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} margin metadata unavailable for ${asset}`,\n );\n }\n\n async calculateFees(\n params: FeeCalculationParams,\n ): Promise<FeeCalculationResult> {\n // The market metadata's zero fee is only true for Standard accounts —\n // resolve and gate the account tier first so a Premium account can\n // never be quoted a false zero (throws for Premium/unverified).\n await this.#ensureAccountIndex();\n // Sourced from the venue's own per-market metadata rather than assumed:\n // Lighter standard accounts currently report 0 maker/taker fees.\n const markets = await this.#ensureMarkets();\n const market = markets.get(params.symbol);\n const feeRate = parseFloat(\n (params.isMaker ? market?.makerFee : market?.takerFee) ?? '0',\n );\n const amount = parseFloat(params.amount ?? '0');\n return {\n feeRate,\n feeAmount: Number.isFinite(amount) ? amount * feeRate : 0,\n protocolFeeRate: feeRate,\n metamaskFeeRate: 0,\n // Structurally zero on this venue, not a waiver applied to a real fee.\n chargesMetamaskBuilderFee: false,\n };\n }\n\n async previewPositionModify(\n _params: PositionModifyPreviewParams,\n ): Promise<PositionModifyPreviewResult> {\n return { status: 'unsupported', reason: 'provider' };\n }\n\n // ============================================================================\n // Live subscriptions over Lighter WebSocket channels, with REST polling\n // only as the price-stream fallback when no WebSocket transport exists.\n // ============================================================================\n\n subscribeToPrices(params: SubscribePricesParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#priceSubscribers.add(params);\n if (this.#lastPriceBySymbol.size > 0) {\n this.#deliverPrices(params, [...this.#lastPriceBySymbol.values()]);\n }\n this.#requestChannel('market_stats/all');\n this.#ensureStream();\n return () => {\n this.#priceSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOICaps(params: SubscribeOICapsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#oiCapSubscribers.add(params);\n this.#requestChannel('market_stats/all');\n this.#ensureStream();\n return () => {\n this.#oiCapSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToAccount(params: SubscribeAccountParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#accountSubscribers.add(params);\n this.#ensureAccountChannels();\n return () => {\n this.#accountSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToPositions(params: SubscribePositionsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#positionSubscribers.add(params);\n if (this.#wsPositions.size > 0) {\n params.callback([...this.#wsPositions.values()]);\n }\n this.#ensureAccountChannels();\n return () => {\n this.#positionSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOrders(params: SubscribeOrdersParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#orderSubscribers.add(params);\n if (this.#wsOrders.size > 0) {\n params.callback([...this.#wsOrders.values()]);\n }\n this.#ensureAccountChannels();\n return () => {\n this.#orderSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n subscribeToOrderFills(params: SubscribeOrderFillsParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#fillSubscribers.add(params);\n this.#ensureAccountChannels();\n return () => {\n this.#fillSubscribers.delete(params);\n this.#releaseChannelIfUnused();\n };\n }\n\n // ============================================================================\n // Shared WebSocket stream manager (market_stats / user_stats /\n // account_all_positions / account_all_orders), REST polling fallback for\n // prices when no WebSocket implementation is available.\n // ============================================================================\n\n /**\n * Resolve the Lighter account index and request the account-scoped\n * channels. When the venue definitively reports no Lighter account,\n * account-scoped subscribers receive an empty emission.\n */\n readonly #ensureAccountChannels = (): void => {\n if (this.#isDisconnected) {\n return;\n }\n if (this.#accountChannelsPromise) {\n this.#ensureStream();\n return;\n }\n const generation = this.#sessionGeneration;\n let channelsRequested = false;\n const setupPromise = (async (): Promise<void> => {\n try {\n // Warm the margin cache before any WS position frame is adapted.\n await this.#ensureMarketMargins().catch(() => undefined);\n const accountIndex = await this.#ensureAccountIndex();\n // Address-aware: an EXTERNAL switch during the lookup (with no other\n // provider call to advance the generation) must also stop these\n // channels from being requested for the old account. The rebind\n // inside the binding call triggers its own rebuild for the new one.\n // Fails closed when no wallet account is bound — a configured\n // account index alone must never subscribe user channels.\n this.#assertSession(generation);\n this.#requestChannel(`user_stats/${accountIndex}`);\n this.#requestChannel(`account_all_positions/${accountIndex}`);\n this.#requestChannel(`account_all_trades/${accountIndex}`);\n channelsRequested = true;\n try {\n const auth = await this.#getAuthToken();\n this.#assertSession(generation);\n this.#requestChannel(`account_all_orders/${accountIndex}`, auth);\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] orders channel skipped (no auth token)',\n { error: String(error) },\n );\n // Setup failures are not authoritative empty order state. Account\n // switches and deselection already emit their synchronous reset.\n channelsRequested = false;\n }\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] account channels unavailable',\n { error: String(error) },\n );\n // A venue-confirmed absent account is authoritative empty state for\n // this exact wallet binding. It must settle initial subscribers so\n // clients do not render loading skeletons forever. All other failures\n // preserve the last snapshot: transport, malformed data, auth and\n // capability errors cannot prove that the account is empty.\n this.#ensureSessionBinding();\n if (\n error instanceof LighterAccountNotFoundError &&\n generation === this.#sessionGeneration\n ) {\n this.#emitAccountBindingReset();\n }\n // An aborted previous-account setup has no authority over the new\n // session. Current-session failures also preserve the last known data.\n // Transport, auth, capability, and integrity failures are not\n // authoritative empty account state. Explicit account switches and\n // deselection already emit their synchronous reset.\n }\n })();\n this.#accountChannelsPromise = setupPromise;\n // A setup that never requested channels (no wallet account yet, or an\n // aborted switch) must not satisfy future ensure calls — clear it so\n // the next bind retries, without clobbering a newer session's promise.\n setupPromise\n .then(() => {\n if (\n !channelsRequested &&\n this.#accountChannelsPromise === setupPromise\n ) {\n this.#accountChannelsPromise = null;\n }\n return undefined;\n })\n .catch(() => undefined);\n this.#ensureStream();\n };\n\n readonly #hasAnySubscriber = (): boolean => {\n return (\n this.#priceSubscribers.size > 0 ||\n this.#oiCapSubscribers.size > 0 ||\n this.#accountSubscribers.size > 0 ||\n this.#positionSubscribers.size > 0 ||\n this.#orderSubscribers.size > 0 ||\n this.#fillSubscribers.size > 0 ||\n [...this.#orderBookSubscribers.values()].some(\n (subscribers) => subscribers.size > 0,\n ) ||\n [...this.#candleSubscribers.values()].some(\n (subscribers) => subscribers.size > 0,\n )\n );\n };\n\n readonly #requestChannel = (channel: string, auth?: string): void => {\n if (this.#isDisconnected) {\n return;\n }\n if (this.#wsWantedChannels.has(channel)) {\n return;\n }\n this.#wsWantedChannels.set(channel, { auth });\n if (this.#priceWs && this.#priceWs.readyState === 1) {\n this.#sendSubscribe(channel, auth);\n }\n };\n\n readonly #sendSubscribe = (channel: string, auth?: string): void => {\n this.#priceWs?.send(\n JSON.stringify(\n auth\n ? { type: 'subscribe', channel, auth }\n : { type: 'subscribe', channel },\n ),\n );\n };\n\n readonly #releaseChannelIfUnused = (): void => {\n if (!this.#hasAnySubscriber()) {\n this.#teardownStream();\n }\n };\n\n readonly #ensureStream = (): void => {\n if (this.#isDisconnected || this.#priceWs || this.#pricePollTimer) {\n return;\n }\n if (this.#webSocketCtor) {\n this.#connectWs();\n } else {\n this.#startPricePolling();\n }\n };\n\n readonly #connectWs = (): void => {\n if (this.#isDisconnected || !this.#webSocketCtor) {\n return;\n }\n const url = getLighterWsEndpoint(this.#isTestnet ? 'testnet' : 'mainnet');\n const WebSocketCtor = this.#webSocketCtor;\n const ws = new WebSocketCtor(url);\n this.#priceWs = ws;\n this.#setConnectionState(WebSocketConnectionState.Connecting);\n\n ws.onopen = (): void => {\n if (this.#isDisconnected) {\n try {\n ws.close();\n } catch {\n // The transport may already have closed during disconnect.\n }\n return;\n }\n // Observe any external switch first, then drop if this socket was\n // replaced (by that rebind or an earlier one).\n this.#ensureSessionBinding();\n if (this.#priceWs !== ws) {\n return;\n }\n const generationAtOpen = this.#sessionGeneration;\n this.#wsReconnectAttempts = 0;\n this.#setConnectionState(WebSocketConnectionState.Connected);\n for (const [channel, meta] of this.#wsWantedChannels) {\n if (meta.auth) {\n // Auth tokens are short-lived; a reconnect after the deadline must\n // re-mint instead of replaying the token captured at subscribe\n // time. #getAuthToken reuses the cached token while it is fresh.\n this.#getAuthToken()\n .then((freshToken) => {\n // The async continuation may resolve after an account switch\n // replaced the socket or the channel set: never reinsert a\n // stale channel or pair it with the new session's token.\n if (\n this.#priceWs !== ws ||\n generationAtOpen !== this.#sessionGeneration ||\n !this.#wsWantedChannels.has(channel)\n ) {\n return undefined;\n }\n this.#wsWantedChannels.set(channel, { auth: freshToken });\n this.#sendSubscribe(channel, freshToken);\n return undefined;\n })\n .catch((error) => {\n this.#deps.debugLogger.log(\n '[LighterProvider] auth channel resubscribe failed',\n { channel, error: String(error) },\n );\n });\n } else {\n this.#sendSubscribe(channel, meta.auth);\n }\n }\n // The server closes idle sockets; any frame under 2 minutes keeps it up.\n // Unconditional replacement: `??=` would keep a timer bound to a dead\n // socket when a new one opens before the old socket's onclose fired.\n this.#clearKeepalive();\n this.#wsKeepaliveTimer = setInterval(() => {\n try {\n ws.send(JSON.stringify({ type: 'ping' }));\n } catch {\n // Socket closing; onclose handles recovery.\n }\n }, 60_000);\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream connected (ws)',\n { url, channels: [...this.#wsWantedChannels.keys()] },\n );\n };\n\n ws.onmessage = (event: { data: unknown }): void => {\n try {\n if (this.#isDisconnected) {\n return;\n }\n // Re-run the live binding first: an EXTERNAL account switch that no\n // provider call has observed yet must tear this socket down (the\n // rebind replaces it) before any frame routes into current UI.\n this.#ensureSessionBinding();\n // Frames from a socket that was replaced (account rebind, reconnect)\n // must never reach the router — they carry the previous session's data.\n if (this.#priceWs !== ws) {\n return;\n }\n this.#handleWsMessage(String(event.data));\n } catch (error) {\n // WebSocket callbacks run on the host event loop. Venue-data\n // integrity failures (and any other malformed frame failure) must\n // drop the whole frame rather than throw globally or emit partial\n // account/position state.\n this.#deps.debugLogger.log(\n '[LighterProvider] dropped malformed WebSocket frame',\n { error: String(error) },\n );\n }\n };\n\n ws.onclose = (): void => {\n if (this.#priceWs !== ws) {\n return;\n }\n this.#priceWs = null;\n this.#clearKeepalive();\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n if (this.#hasAnySubscriber()) {\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream closed; reconnecting in 5s',\n );\n this.#wsReconnectAttempts += 1;\n this.#wsReconnectTimer = setTimeout((): void => {\n this.#wsReconnectTimer = null;\n this.#ensureStream();\n }, 5_000);\n }\n };\n\n ws.onerror = (): void => {\n this.#deps.debugLogger.log('[LighterProvider] price stream ws error');\n };\n };\n\n readonly #handleWsMessage = (raw: string): void => {\n let message: LighterWsMarketStatsMessage & LighterWsAccountMessage;\n try {\n message = convertKeysToCamelCase(JSON.parse(raw)) as typeof message;\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] price stream message parse failed',\n { error: String(error) },\n );\n return;\n }\n const type = message.type ?? '';\n if (type.includes('market_stats') && message.marketStats) {\n const timestamp = message.timestamp ?? Date.now();\n const updates = Object.values(message.marketStats).map((stat) =>\n adaptPriceUpdateFromLighterWsStat(stat, timestamp),\n );\n this.#dispatchPriceUpdates(updates);\n this.#dispatchOICaps(Object.values(message.marketStats));\n return;\n }\n if (type.includes('user_stats') && message.stats) {\n const accountState = adaptAccountStateFromLighterUserStats(message.stats);\n for (const subscriber of this.#accountSubscribers) {\n try {\n subscriber.callback(accountState);\n } catch (error) {\n this.#logSubscriberError('account', error);\n }\n }\n return;\n }\n if (type.includes('account_all_positions') && message.positions) {\n const isSnapshot = type.startsWith('subscribed');\n const nextPositions = isSnapshot\n ? new Map<number, Position>()\n : new Map(this.#wsPositions);\n for (const [marketId, position] of Object.entries(message.positions)) {\n const adapted = adaptPositionFromLighter(\n position,\n this.#maxLeverageForPosition(position),\n );\n if (parseFloat(adapted.size) === 0) {\n nextPositions.delete(Number(marketId));\n } else {\n nextPositions.set(Number(marketId), adapted);\n }\n }\n this.#wsPositions.clear();\n for (const [marketId, position] of nextPositions) {\n this.#wsPositions.set(marketId, position);\n }\n const positions = [...this.#wsPositions.values()];\n for (const subscriber of this.#positionSubscribers) {\n try {\n subscriber.callback(positions);\n } catch (error) {\n this.#logSubscriberError('positions', error);\n }\n }\n return;\n }\n if (type.includes('order_book')) {\n this.#handleOrderBookMessage(type, message as LighterWsOrderBookMessage);\n return;\n }\n if (type.includes('candle')) {\n this.#handleCandleMessage(message as LighterWsCandleMessage);\n return;\n }\n if (type.includes('account_all_trades')) {\n this.#handleTradesMessage(message as LighterWsTradesMessage);\n return;\n }\n if (type.includes('account_all_orders') && message.orders) {\n const isSnapshot = type.startsWith('subscribed');\n const nextOrders = isSnapshot\n ? new Map<string, Order>()\n : new Map(this.#wsOrders);\n for (const marketOrders of Object.values(message.orders)) {\n for (const order of marketOrders) {\n const adapted = adaptOrderFromLighter(\n order,\n this.#marketsById.get(order.marketIndex)?.symbol ??\n String(order.marketIndex),\n );\n const isOpen =\n adapted.status === 'queued' || adapted.status === 'open';\n if (isOpen) {\n nextOrders.set(adapted.orderId, adapted);\n } else {\n nextOrders.delete(adapted.orderId);\n }\n }\n }\n this.#wsOrders.clear();\n for (const [orderId, order] of nextOrders) {\n this.#wsOrders.set(orderId, order);\n }\n this.#emitToOrderSubscribers([...this.#wsOrders.values()]);\n }\n };\n\n /**\n * Apply an order_book snapshot/delta and fan the assembled book out.\n *\n * @param type - Message type (subscribed = full snapshot, update = delta).\n * @param message - Camelized order_book payload.\n */\n readonly #handleOrderBookMessage = (\n type: string,\n message: LighterWsOrderBookMessage,\n ): void => {\n const channel = message.channel ?? '';\n const marketId = Number(channel.split(':')[1] ?? Number.NaN);\n if (!Number.isFinite(marketId) || !message.orderBook) {\n return;\n }\n const { nonce, beginNonce } = message.orderBook;\n if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce)) {\n return;\n }\n const currentState = this.#orderBookState.get(marketId);\n let nextState: LighterOrderBookState;\n if (type.startsWith('subscribed')) {\n nextState = { bids: new Map(), asks: new Map(), nonce };\n } else if (\n !currentState ||\n typeof beginNonce !== 'number' ||\n !Number.isSafeInteger(beginNonce) ||\n beginNonce !== currentState.nonce\n ) {\n // A delta cannot be applied to an unknown or discontinuous base.\n // Drop the local book and request a new subscribed snapshot.\n this.#orderBookState.delete(marketId);\n const channelName = `order_book/${marketId}`;\n if (this.#priceWs?.readyState === 1) {\n this.#priceWs.send(\n JSON.stringify({ type: 'unsubscribe', channel: channelName }),\n );\n this.#sendSubscribe(channelName);\n }\n return;\n } else {\n nextState = {\n bids: new Map(currentState.bids),\n asks: new Map(currentState.asks),\n nonce: currentState.nonce,\n };\n }\n for (const side of ['bids', 'asks'] as const) {\n for (const level of message.orderBook[side] ?? []) {\n const price = parseStrictDecimal(level?.price);\n const size = parseStrictDecimal(level?.size);\n if (\n price === null ||\n !Number.isFinite(price) ||\n price <= 0 ||\n size === null ||\n !Number.isFinite(size) ||\n size < 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} malformed order-book level`,\n );\n }\n if (size === 0) {\n nextState[side].delete(level.price);\n } else {\n nextState[side].set(level.price, level.size);\n }\n }\n }\n nextState.nonce = nonce;\n this.#orderBookState.set(marketId, nextState);\n const subscribers = this.#orderBookSubscribers.get(marketId);\n if (!subscribers || subscribers.size === 0) {\n return;\n }\n // Levels must carry the FULL OrderBookLevel contract. The depth chart\n // draws Y-coordinates from parseFloat(level.total): a bare {price, size}\n // level renders as an SVG path full of NaN and crashes the native path\n // parser (found live on device, RNSVGPathParser InvalidNumber).\n const toContractLevels = (\n entries: [string, string][],\n ): OrderBookLevel[] => {\n let cumulativeSize = 0;\n let cumulativeNotional = 0;\n return entries.map(([price, size]) => {\n const sizeNum = Number(size);\n const notional = Number(price) * sizeNum;\n cumulativeSize += sizeNum;\n cumulativeNotional += notional;\n return {\n price,\n size,\n total: String(cumulativeSize),\n notional: String(notional),\n totalNotional: String(cumulativeNotional),\n };\n });\n };\n for (const subscriber of subscribers) {\n const levels = subscriber.levels ?? 10;\n const bids = toContractLevels(\n [...nextState.bids.entries()]\n .sort((a, b) => Number(b[0]) - Number(a[0]))\n .slice(0, levels),\n );\n const asks = toContractLevels(\n [...nextState.asks.entries()]\n .sort((a, b) => Number(a[0]) - Number(b[0]))\n .slice(0, levels),\n );\n const bestBid = Number(bids[0]?.price ?? '0');\n const bestAsk = Number(asks[0]?.price ?? '0');\n const mid = bestBid > 0 && bestAsk > 0 ? (bestBid + bestAsk) / 2 : 0;\n const maxTotal = Math.max(\n Number(bids[bids.length - 1]?.total ?? '0'),\n Number(asks[asks.length - 1]?.total ?? '0'),\n );\n const book: OrderBookData = {\n bids,\n asks,\n spread: String(bestAsk - bestBid),\n spreadPercentage:\n mid > 0 ? String(((bestAsk - bestBid) / mid) * 100) : '0',\n midPrice: String(mid),\n lastUpdated: Date.now(),\n maxTotal: String(maxTotal),\n };\n try {\n subscriber.callback(book);\n } catch (error) {\n this.#logSubscriberError('orderBook', error);\n }\n }\n };\n\n /**\n * Merge live candle updates into the cached series and fan out.\n *\n * @param message - Camelized candle payload.\n */\n readonly #handleCandleMessage = (message: LighterWsCandleMessage): void => {\n const channel = message.channel ?? '';\n const [, marketIdRaw, resolution] = channel.split(':');\n const key = `${marketIdRaw}:${resolution}`;\n const series = this.#candleSeries.get(key);\n const subscribers = this.#candleSubscribers.get(key);\n if (!series || !subscribers || subscribers.size === 0) {\n return;\n }\n for (const candle of message.candles ?? []) {\n const mapped = toFiniteCandle(candle);\n if (mapped) {\n series.set(mapped.time, mapped);\n }\n }\n const candles = [...series.values()].sort((a, b) => a.time - b.time);\n for (const subscriber of subscribers) {\n try {\n subscriber.callback({\n symbol: subscriber.symbol,\n interval: subscriber.interval,\n candles,\n });\n } catch (error) {\n this.#logSubscriberError('candles', error);\n }\n }\n };\n\n /**\n * Adapt live account trades into OrderFill emissions.\n *\n * @param message - Camelized account_all_trades payload.\n */\n readonly #handleTradesMessage = (message: LighterWsTradesMessage): void => {\n if (this.#fillSubscribers.size === 0) {\n return;\n }\n const isSnapshot = (message.type ?? '').startsWith('subscribed');\n const fills: OrderFill[] = [];\n let droppedUnsupportedFill = false;\n for (const marketTrades of Object.values(message.trades ?? {})) {\n for (const trade of marketTrades) {\n const symbol =\n this.#marketsById.get(trade.marketId)?.symbol ??\n String(trade.marketId);\n // One adapter serves REST history and the live stream so pnl,\n // fees, and direction vocabulary can never diverge between them.\n // A capability-refused fill (unverified nonzero fee) must never be\n // rendered with a false zero fee, nor crash the event handler.\n try {\n fills.push(\n adaptFillFromLighterTrade(trade, symbol, this.#accountIndex ?? -1),\n );\n } catch (error) {\n droppedUnsupportedFill = true;\n this.#deps.debugLogger.log(\n '[LighterProvider] dropped unsupported fill from stream',\n { tradeId: trade.tradeId, error: String(error) },\n );\n }\n }\n }\n if (fills.length === 0 && !isSnapshot) {\n return;\n }\n // A snapshot that lost fills to a capability refusal is PARTIAL:\n // emitting it would overwrite valid cached history with false\n // emptiness. Preserve what subscribers already have; REST reads\n // surface the capability error explicitly.\n if (isSnapshot && droppedUnsupportedFill) {\n this.#deps.debugLogger.log(\n '[LighterProvider] withholding partial fills snapshot (unsupported fills present)',\n );\n return;\n }\n for (const subscriber of this.#fillSubscribers) {\n try {\n subscriber.callback(fills, isSnapshot);\n } catch (error) {\n this.#logSubscriberError('fills', error);\n }\n }\n };\n\n readonly #dispatchOICaps = (stats: LighterWsMarketStat[]): void => {\n if (this.#oiCapSubscribers.size === 0) {\n return;\n }\n const capped = stats\n .filter((stat) => {\n const openInterest = parseFloat(stat.openInterest ?? '0');\n const limit = parseFloat(\n (stat as { openInterestLimit?: string }).openInterestLimit ?? '0',\n );\n return limit > 0 && openInterest >= limit;\n })\n .map((stat) => stat.symbol);\n for (const subscriber of this.#oiCapSubscribers) {\n try {\n subscriber.callback(capped);\n } catch (error) {\n this.#logSubscriberError('oiCaps', error);\n }\n }\n };\n\n readonly #emitToOrderSubscribers = (orders: Order[]): void => {\n if (this.#isDisconnected) {\n return;\n }\n for (const subscriber of this.#orderSubscribers) {\n try {\n subscriber.callback(orders);\n } catch (error) {\n this.#logSubscriberError('orders', error);\n }\n }\n };\n\n readonly #logSubscriberError = (channel: string, error: unknown): void => {\n this.#deps.debugLogger.log(\n `[LighterProvider] ${channel} subscriber callback failed`,\n { error: String(error) },\n );\n };\n\n readonly #startPricePolling = (): void => {\n if (this.#isDisconnected || this.#pricePollTimer) {\n return;\n }\n const poll = (): void => {\n this.#emitPolledPrices().catch((error: unknown) => {\n this.#deps.debugLogger.log('[LighterProvider] price poll failed', {\n error: String(error),\n });\n });\n };\n this.#pricePollTimer = setInterval(poll, LIGHTER_PRICE_POLLING_INTERVAL_MS);\n this.#setConnectionState(WebSocketConnectionState.Connected);\n poll();\n };\n\n /**\n * REST fallback: fetch market stats once and fan them out.\n */\n readonly #emitPolledPrices = async (): Promise<void> => {\n if (this.#priceSubscribers.size === 0) {\n return;\n }\n const response = await this.#clientService.getOrderBookDetails();\n if (this.#isDisconnected) {\n return;\n }\n const timestamp = Date.now();\n const updates = (response.orderBookDetails ?? []).map((detail) =>\n adaptPriceUpdateFromLighter(detail, timestamp),\n );\n this.#dispatchPriceUpdates(updates);\n };\n\n /**\n * Fan price updates out to every subscriber, honoring symbol filters.\n *\n * @param updates - Adapted price updates for this cycle.\n */\n readonly #dispatchPriceUpdates = (updates: PriceUpdate[]): void => {\n if (this.#isDisconnected || updates.length === 0) {\n return;\n }\n for (const update of updates) {\n this.#lastPriceBySymbol.set(update.symbol, update);\n }\n for (const subscriber of this.#priceSubscribers) {\n this.#deliverPrices(subscriber, updates);\n }\n };\n\n readonly #deliverPrices = (\n subscriber: SubscribePricesParams,\n updates: PriceUpdate[],\n ): void => {\n if (this.#isDisconnected) {\n return;\n }\n const filtered =\n subscriber.symbols.length > 0\n ? updates.filter((update) => subscriber.symbols.includes(update.symbol))\n : updates;\n if (filtered.length === 0) {\n return;\n }\n try {\n subscriber.callback(filtered);\n } catch (error) {\n this.#logSubscriberError('prices', error);\n }\n };\n\n readonly #clearKeepalive = (): void => {\n if (this.#wsKeepaliveTimer) {\n clearInterval(this.#wsKeepaliveTimer);\n this.#wsKeepaliveTimer = null;\n }\n };\n\n readonly #teardownStream = (): void => {\n if (this.#pricePollTimer) {\n clearInterval(this.#pricePollTimer);\n this.#pricePollTimer = null;\n }\n if (this.#wsReconnectTimer) {\n clearTimeout(this.#wsReconnectTimer);\n this.#wsReconnectTimer = null;\n }\n this.#clearKeepalive();\n this.#wsWantedChannels.clear();\n this.#accountChannelsPromise = null;\n this.#wsPositions.clear();\n this.#wsOrders.clear();\n this.#orderBookState.clear();\n this.#candleSeries.clear();\n this.#lastPriceBySymbol.clear();\n if (this.#priceWs) {\n const ws = this.#priceWs;\n this.#priceWs = null;\n try {\n ws.close();\n } catch {\n // Socket may already be closed.\n }\n }\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n };\n\n subscribeToCandles(params: SubscribeCandlesParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n let released = false;\n let seriesKey: string | null = null;\n const resolution = LIGHTER_SUPPORTED_RESOLUTIONS.has(params.interval)\n ? params.interval\n : '15m';\n this.#ensureMarkets()\n .then(async (markets) => {\n const market = markets.get(params.symbol);\n if (this.#isDisconnected || !market || released) {\n return undefined;\n }\n seriesKey = `${market.marketId}:${resolution}`;\n // Seed with history so charts render immediately, then let the WS\n // candle channel keep the series live.\n const seeded = await this.fetchHistoricalCandles({\n symbol: params.symbol,\n interval: params.interval,\n limit: 120,\n });\n if (this.#isDisconnected || released) {\n return undefined;\n }\n const series = new Map<number, CandleStick>();\n for (const candle of seeded.candles) {\n series.set(candle.time, candle);\n }\n this.#candleSeries.set(seriesKey, series);\n let subscribers = this.#candleSubscribers.get(seriesKey);\n if (!subscribers) {\n subscribers = new Set();\n this.#candleSubscribers.set(seriesKey, subscribers);\n }\n subscribers.add(params);\n params.callback(seeded);\n this.#requestChannel(`candle/${market.marketId}/${resolution}`);\n this.#ensureStream();\n return undefined;\n })\n .catch((error: unknown) => {\n this.#deps.debugLogger.log('[LighterProvider] candle seed failed', {\n error: String(error),\n });\n });\n return () => {\n released = true;\n if (seriesKey !== null) {\n this.#candleSubscribers.get(seriesKey)?.delete(params);\n }\n this.#releaseChannelIfUnused();\n };\n }\n\n readonly fetchHistoricalCandles = async (options: {\n symbol: string;\n interval: CandlePeriod;\n limit?: number;\n endTime?: number;\n }): Promise<CandleData> => {\n const empty: CandleData = {\n symbol: options.symbol,\n interval: options.interval,\n candles: [],\n };\n try {\n const markets = await this.#ensureMarkets();\n const market = markets.get(options.symbol);\n if (!market) {\n return empty;\n }\n const resolution = LIGHTER_SUPPORTED_RESOLUTIONS.has(options.interval)\n ? options.interval\n : '15m';\n const intervalMs =\n LIGHTER_RESOLUTION_MS[resolution] ?? LIGHTER_RESOLUTION_MS['15m'];\n const limit = options.limit ?? 120;\n const endTimestamp = options.endTime ?? Date.now();\n const startTimestamp = endTimestamp - intervalMs * limit;\n const response = await this.#clientService.getCandles(\n market.marketId,\n resolution,\n startTimestamp,\n endTimestamp,\n limit,\n );\n return {\n symbol: options.symbol,\n interval: options.interval,\n candles: (response.c ?? []).flatMap((candle) => {\n const mapped = toFiniteCandle(candle);\n return mapped ? [mapped] : [];\n }),\n };\n } catch (error) {\n this.#deps.debugLogger.log(\n '[LighterProvider] fetchHistoricalCandles failed',\n { error: String(error) },\n );\n return empty;\n }\n };\n\n subscribeToOrderBook(params: SubscribeOrderBookParams): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n let released = false;\n let marketId: number | null = null;\n this.#ensureMarkets()\n .then((markets) => {\n const market = markets.get(params.symbol);\n if (this.#isDisconnected || !market || released) {\n return undefined;\n }\n marketId = market.marketId;\n let subscribers = this.#orderBookSubscribers.get(marketId);\n if (!subscribers) {\n subscribers = new Set();\n this.#orderBookSubscribers.set(marketId, subscribers);\n }\n subscribers.add(params);\n this.#requestChannel(`order_book/${marketId}`);\n this.#ensureStream();\n return undefined;\n })\n .catch((error: unknown) => {\n if (!this.#isDisconnected && !released) {\n params.onError?.(ensureError(error));\n }\n });\n return () => {\n released = true;\n if (marketId !== null) {\n this.#orderBookSubscribers.get(marketId)?.delete(params);\n }\n this.#releaseChannelIfUnused();\n };\n }\n\n setLiveDataConfig(_config: Partial<LiveDataConfig>): void {\n // POC: no live data configuration\n }\n\n getWebSocketConnectionState(): WebSocketConnectionState {\n // REST-polling transport has no socket to report on; treat an active\n // poll loop as connected so callers don't tear down live subscriptions.\n if (!this.#webSocketCtor) {\n return this.#pricePollTimer\n ? WebSocketConnectionState.Connected\n : WebSocketConnectionState.Disconnected;\n }\n return this.#connectionState;\n }\n\n subscribeToConnectionState(\n listener: (\n state: WebSocketConnectionState,\n reconnectionAttempt: number,\n ) => void,\n ): () => void {\n if (this.#isDisconnected) {\n return NOOP_UNSUBSCRIBE;\n }\n this.#connectionListeners.add(listener);\n listener(this.getWebSocketConnectionState(), this.#wsReconnectAttempts);\n return (): void => {\n this.#connectionListeners.delete(listener);\n };\n }\n\n async reconnect(): Promise<void> {\n if (this.#isDisconnected) {\n return;\n }\n const ws = this.#priceWs;\n if (ws) {\n // Detach first so the onclose handler's 5s backoff never races the\n // immediate reconnect below.\n this.#priceWs = null;\n this.#clearKeepalive();\n try {\n ws.close();\n } catch {\n // Socket may already be closed.\n }\n this.#setConnectionState(WebSocketConnectionState.Disconnected);\n }\n if (this.#wsReconnectTimer) {\n clearTimeout(this.#wsReconnectTimer);\n this.#wsReconnectTimer = null;\n }\n if (this.#hasAnySubscriber()) {\n this.#ensureStream();\n }\n }\n\n // ============================================================================\n // Asset Routes\n // ============================================================================\n\n /**\n * The venue's USDC bridge route for the active network, in AssetRoute\n * shape. Facts sourced live from `layer1BasicInfo` + venue docs (see\n * LIGHTER_BRIDGE_CONFIG).\n *\n * @param minAmount - Which venue minimum applies (deposit vs withdrawal).\n * @returns Single-element route list.\n */\n readonly #bridgeRoute = (minAmount: string): AssetRoute[] => {\n // Only the MAINNET bridge is ever advertised: the effective-testnet\n // branches return [] before reaching here (devnet L1 unreachable).\n const bridge = LIGHTER_BRIDGE_CONFIG.mainnet;\n return [\n {\n assetId:\n `${bridge.chainId}/erc20:${bridge.usdcContract}/default` as AssetRoute['assetId'],\n chainId: bridge.chainId as AssetRoute['chainId'],\n contractAddress: bridge.bridgeContract as AssetRoute['contractAddress'],\n constraints: { minAmount },\n },\n ];\n };\n\n getDepositRoutes(_params?: GetSupportedPathsParams): AssetRoute[] {\n // DepositService currently builds an ERC-20 transfer, while Lighter\n // requires approval plus a call to the bridge proxy's deposit method.\n // Do not advertise a route until that provider-owned transaction builder\n // exists and has integration coverage.\n return [];\n }\n\n getWithdrawalRoutes(params?: GetSupportedPathsParams): AssetRoute[] {\n // Same devnet-L1 reality and fail-closed network binding as deposits.\n const isTestnet = this.#isTestnet || params?.isTestnet === true;\n if (isTestnet) {\n return [];\n }\n return this.#bridgeRoute(LIGHTER_BRIDGE_CONFIG.mainnet.minWithdrawUsdc);\n }\n\n // ============================================================================\n // Block Explorer\n // ============================================================================\n\n getBlockExplorerUrl(address?: string): string {\n const baseUrl = this.#isTestnet\n ? LIGHTER_TESTNET_EXPLORER_URL\n : LIGHTER_MAINNET_EXPLORER_URL;\n return address ? `${baseUrl}/address/${address}` : baseUrl;\n }\n}\n"]}
|