@metamask-previews/perps-controller 17.1.0-preview-d27fd1d8f → 17.1.0-preview-7aac301dc

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 CHANGED
@@ -12,6 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
12
12
  - Bump `@metamask/utils` from `^11.12.0` to `^12.0.0` ([#10192](https://github.com/MetaMask/core/pull/10192))
13
13
  - Bump `uuid` from `^9.0.1` to `^11.1.1` ([#10243](https://github.com/MetaMask/core/pull/10243))
14
14
 
15
+ ### Fixed
16
+
17
+ - Normalize Lighter order timestamps from seconds to milliseconds for client date displays. ([#10187](https://github.com/MetaMask/core/pull/10187))
18
+ - Accept omitted Lighter fill PnL only when the account's validated pre-trade position is zero; retain strict PnL validation for existing positions and malformed supplied values. ([#10187](https://github.com/MetaMask/core/pull/10187))
19
+
15
20
  ## [17.1.0]
16
21
 
17
22
  ### Added
@@ -556,9 +556,9 @@ export type LighterRestTrade = {
556
556
  bidAccountId: number;
557
557
  isMakerAsk: boolean;
558
558
  timestamp: number;
559
- /** Realized pnl for the ask-side account, signed USDC. */
559
+ /** Realized pnl for the ask-side account, signed USDC; may be omitted on opens from flat. */
560
560
  askAccountPnl?: string;
561
- /** Realized pnl for the bid-side account, signed USDC. */
561
+ /** Realized pnl for the bid-side account, signed USDC; may be omitted on opens from flat. */
562
562
  bidAccountPnl?: string;
563
563
  /**
564
564
  * Taker/maker fees, present when nonzero. The official model types them
@@ -668,6 +668,7 @@ export type LighterApiOrder = {
668
668
  reduceOnly: number | boolean;
669
669
  status: string;
670
670
  orderExpiry: number;
671
+ /** Unix seconds from order endpoints, unlike millisecond trade timestamps. */
671
672
  timestamp: number;
672
673
  /**
673
674
  * Trigger level for stop-loss/take-profit orders. Note `price` on a
@@ -1 +1 @@
1
- {"version":3,"file":"lighter-types.d.ts","sourceRoot":"","sources":["../../src/types/lighter-types.ts"],"names":[],"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-1 +1 @@
1
- {"version":3,"file":"lighter-types.js","sourceRoot":"","sources":["../../src/types/lighter-types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG","sourcesContent":["/**\n * Lighter Protocol Type Definitions\n *\n * Types for the zkLighter REST API, the Go/WASM signer bridge, and\n * provider configuration. No SDK dependency — shapes are derived from\n * the public API (https://apidocs.lighter.xyz) and the reference\n * WebView bridge (elliottech/lighter-go, `web-wasm` branch).\n */\n\n// ============================================================================\n// Network Configuration Types\n// ============================================================================\n\n/**\n * Lighter Network type - mainnet or testnet\n */\nexport type LighterNetwork = 'mainnet' | 'testnet';\n\n/**\n * Lighter endpoint configuration for a single network\n */\nexport type LighterEndpointConfig = {\n http: string;\n ws: string;\n};\n\n/**\n * Lighter endpoints for all networks\n */\nexport type LighterEndpoints = {\n mainnet: LighterEndpointConfig;\n testnet: LighterEndpointConfig;\n};\n\n// ============================================================================\n// Signer Bridge (WASM seam)\n// ============================================================================\n\n/**\n * A single call into the Lighter Go/WASM signer.\n *\n * Mirrors the postMessage protocol of the reference React Native WebView\n * bridge (`{ function, params }`), so a WebView-backed bridge on mobile and\n * an in-process WASM bridge in Node are interchangeable implementations.\n */\nexport type LighterCreateOrderWireParams = [\n marketId: number,\n clientOrderIndex: number,\n baseAmount: string,\n price: string,\n isAsk: number,\n orderType: number,\n timeInForce: number,\n reduceOnly: number,\n triggerPrice: string,\n orderExpiry: number,\n];\n\nexport type LighterGroupedOrderWireParams = [\n ...first: LighterCreateOrderWireParams,\n ...second: LighterCreateOrderWireParams,\n];\n\nexport type LighterCreateClientWireParams = [\n chainId: number,\n accountIndex: number,\n nonce: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignChangePubKeyWireParams = [\n accountIndex: number,\n l1Signature: string,\n nonce: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignCreateOrderWireParams = [\n accountIndex: number,\n ...order: LighterCreateOrderWireParams,\n nonce: number,\n];\n\nexport type LighterSignCreateGroupedOrdersWireParams = [\n accountIndex: number,\n groupingType: number,\n orderCount: 2,\n ...orders: LighterGroupedOrderWireParams,\n nonce: number,\n];\n\nexport type LighterSignCancelOrderWireParams = [\n accountIndex: number,\n marketId: number,\n orderId: string,\n nonce: number,\n];\n\nexport type LighterSignUpdateLeverageWireParams = [\n accountIndex: number,\n marketId: number,\n leverageImfHundredths: number,\n marginMode: number,\n nonce: number,\n];\n\nexport type LighterSignUpdateMarginWireParams = [\n accountIndex: number,\n marketId: number,\n amount: number,\n direction: number,\n nonce: number,\n];\n\nexport type LighterSignWithdrawWireParams = [\n accountIndex: number,\n assetIndex: number,\n routeType: number,\n amount: string,\n nonce: number,\n];\n\nexport type LighterCreateAuthTokenWireParams = [\n accountIndex: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignerOperationDefinition<\n Params extends unknown[],\n Result,\n> = {\n params: Params;\n result: Result;\n};\n\nexport type LighterSignerOperationMap = {\n _createClient: LighterSignerOperationDefinition<\n LighterCreateClientWireParams,\n LighterCreateClientResult\n >;\n _signChangePubKey: LighterSignerOperationDefinition<\n LighterSignChangePubKeyWireParams,\n LighterSignChangePubKeyResult\n >;\n _signCreateOrder: LighterSignerOperationDefinition<\n LighterSignCreateOrderWireParams,\n LighterTxResult\n >;\n _signCreateGroupedOrders: LighterSignerOperationDefinition<\n LighterSignCreateGroupedOrdersWireParams,\n LighterTxResult\n >;\n _signCancelOrder: LighterSignerOperationDefinition<\n LighterSignCancelOrderWireParams,\n LighterTxResult\n >;\n _signUpdateLeverage: LighterSignerOperationDefinition<\n LighterSignUpdateLeverageWireParams,\n LighterTxResult\n >;\n _signUpdateMargin: LighterSignerOperationDefinition<\n LighterSignUpdateMarginWireParams,\n LighterTxResult\n >;\n _signWithdraw: LighterSignerOperationDefinition<\n LighterSignWithdrawWireParams,\n LighterTxResult\n >;\n _createAuthToken: LighterSignerOperationDefinition<\n LighterCreateAuthTokenWireParams,\n LighterCreateAuthTokenResult\n >;\n};\n\nexport type LighterSignerOperation = keyof LighterSignerOperationMap;\n\nexport type LighterWasmCall<\n Operation extends LighterSignerOperation = LighterSignerOperation,\n> = Operation extends LighterSignerOperation\n ? {\n function: Operation;\n params: LighterSignerOperationMap[Operation]['params'];\n }\n : never;\n\nexport type LighterSignerResult<Operation extends LighterSignerOperation> =\n LighterSignerOperationMap[Operation]['result'];\n\n/** Public metadata needed to create or restore a client-owned venue signer. */\nexport type LighterCreateClientParams = {\n chainId: number;\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n};\n\n/**\n * Transport-agnostic seam to the Lighter Go/WASM signer.\n *\n * Implementations:\n * - Mobile: off-screen WebView loading the locally-bundled\n * `wasm-wrapper.standalone.html`, dispatching calls via postMessage.\n * - Node (e2e): in-process `WebAssembly.instantiate` via Go's `wasm_exec.js`.\n */\nexport type LighterSignerBridge = {\n /**\n * Create or restore the client-owned venue signer. The implementation owns\n * key generation and persistence; Core never receives the seed or private\n * key.\n *\n * @param params - Public venue/session metadata required by the signer.\n */\n createClient(\n params: LighterCreateClientParams,\n ): Promise<LighterCreateClientResult>;\n\n /**\n * Execute one WASM signer call and resolve with its result object.\n *\n * @param call - The function name and positional params to invoke.\n */\n execute<Operation extends LighterSignerOperation>(\n call: LighterWasmCall<Operation>,\n ): Promise<LighterSignerResult<Operation>>;\n\n /**\n * Optional subscription to bridge resets (WebView reload / process\n * loss). The provider uses it to invalidate its cached signer session\n * IMMEDIATELY instead of learning about the reset from the next failed\n * trading call.\n *\n * @param listener - Invoked on every reset.\n * @returns Unsubscribe function.\n */\n onReset?(listener: () => void): () => void;\n\n /**\n * Optional hook to re-arm the bridge after a reload (WebView remount).\n */\n reset?(): void;\n};\n\n// ============================================================================\n// WASM signer response shapes (from lighter-go react-native/src/lighterSdk.ts)\n// ============================================================================\n\n/**\n * Response of `_createClient` / `_createClientByPrv`.\n */\nexport type LighterCreateClientResult = {\n success: boolean;\n /** Venue public key, hex (80 chars / 40 bytes, Schnorr over ECgFp5). */\n pk: string;\n pubKeySuccess: boolean;\n /**\n * ChangePubKey plaintext body to be signed with EIP-191 `personal_sign`\n * by the user's L1 (EVM) account.\n */\n body: string;\n error?: string;\n};\n\n/**\n * Response of `_signChangePubKey`.\n */\nexport type LighterSignChangePubKeyResult = {\n /** Serialized L2 transaction JSON (includes the injected `L1Sig`). */\n txInfo: string;\n /**\n * Signed transaction hash (pinned WASM contract: the signing RESULT\n * carries the hash; `txInfo` never does). Required for the durable\n * dispatch ledger's exact-identity reconciliation.\n */\n txHash?: string;\n error?: string;\n};\n\n/**\n * Response of `_createAuthToken`.\n */\nexport type LighterCreateAuthTokenResult = {\n token: string;\n deadline: number;\n error?: string;\n};\n\n/**\n * Response of signing functions returning a full L2 transaction\n * (`_signCreateOrder`, `_signCancelOrder`, ...).\n */\nexport type LighterTxResult = {\n txInfo: string;\n txHash?: string;\n error?: string;\n};\n\n// ============================================================================\n// Auth Configuration\n// ============================================================================\n\n/**\n * Signs an EIP-191 personal message and resolves with the 65-byte signature\n * as a 0x-prefixed hex string. Injected for headless use; when a messenger\n * is available the wallet service routes through\n * `KeyringController:signPersonalMessage` instead.\n */\nexport type LighterPersonalSigner = (message: string) => Promise<string>;\n\n/**\n * Lighter auth/config passed at construction time.\n */\nexport type LighterAuthConfig = {\n /** Whether the Lighter provider is enabled via local override. */\n enabled?: boolean;\n /** Lighter account index (assigned at first deposit). */\n accountIndex?: number;\n /** API key slot to register/use (0-254). */\n apiKeyIndex?: number;\n /** L1 address owning the Lighter account. */\n l1Address?: string;\n /** Headless personal_sign implementation for L1 ChangePubKey approval. */\n personalSigner?: LighterPersonalSigner;\n};\n\n// ============================================================================\n// REST API response shapes (subset used by the POC)\n//\n// The zkLighter wire format is snake_case; LighterClientService converts\n// keys to camelCase at the fetch boundary so these parsed shapes follow\n// package conventions.\n// ============================================================================\n\n/**\n * One market entry from `GET /api/v1/orderBooks`.\n */\nexport type LighterOrderBookMeta = {\n symbol: string;\n marketId: number;\n marketType: string;\n status: string;\n takerFee: string;\n makerFee: string;\n minBaseAmount: string;\n minQuoteAmount: string;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n supportedQuoteDecimals: number;\n};\n\n/**\n * Response of `GET /api/v1/orderBooks`.\n */\nexport type LighterOrderBooksResponse = {\n code: number;\n orderBooks: LighterOrderBookMeta[];\n};\n\n/**\n * Market stats from `GET /api/v1/orderBookDetails`.\n */\nexport type LighterOrderBookDetail = LighterOrderBookMeta & {\n lastTradePrice: number;\n /** Default initial margin fraction, hundredths of a percent (666 = 6.66%). */\n defaultInitialMarginFraction?: number;\n /** Minimum initial margin fraction, hundredths of a percent (400 → 25x max). */\n minInitialMarginFraction?: number;\n /** Maintenance margin fraction, hundredths of a percent (240 = 2.4%). */\n maintenanceMarginFraction?: number;\n dailyTradesCount: number;\n dailyBaseTokenVolume: number;\n dailyQuoteTokenVolume: number;\n dailyPriceLow: number;\n dailyPriceHigh: number;\n dailyPriceChange: number;\n openInterest: number;\n dailyChart: Record<string, number>;\n};\n\n/**\n * Response of `GET /api/v1/orderBookDetails`.\n */\nexport type LighterOrderBookDetailsResponse = {\n code: number;\n orderBookDetails: LighterOrderBookDetail[];\n};\n\n/**\n * One sub-account from `GET /api/v1/accountsByL1Address` or `account`.\n */\nexport type LighterSubAccount = {\n code: number;\n accountType: number;\n index: number;\n l1Address: string;\n cancelAllTime: number;\n totalOrderCount: number;\n pendingOrderCount: number;\n status: number;\n collateral: string;\n availableBalance: string;\n positions?: LighterApiPosition[];\n};\n\n/**\n * Identity fields returned by `GET /api/v1/accountsByL1Address`.\n *\n * Lighter's address-discovery endpoint may leave balance fields empty even\n * though the full `account` endpoint returns validated decimal values. Account\n * discovery only consumes these identity fields; financial reads continue to\n * use {@link LighterSubAccount} and its stricter response validation.\n */\nexport type LighterAccountSummary = Pick<\n LighterSubAccount,\n 'accountType' | 'index' | 'l1Address'\n>;\n\n/**\n * Response of `GET /api/v1/accountsByL1Address`.\n */\nexport type LighterAccountsByL1AddressResponse = {\n code: number;\n message?: string;\n l1Address: string;\n subAccounts: LighterAccountSummary[];\n};\n\n/**\n * Response of `GET /api/v1/account` (`by=index`).\n */\nexport type LighterAccountResponse = {\n code: number;\n message?: string;\n accounts: LighterSubAccount[];\n};\n\n/**\n * One position inside an account payload.\n */\nexport type LighterApiPosition = {\n marketId: number;\n symbol: string;\n initialMarginFraction: string;\n openOrderCount: number;\n /** 1 = long, -1 = short (sign convention per API). */\n sign: number;\n position: string;\n avgEntryPrice: string;\n positionValue: string;\n unrealizedPnl: string;\n realizedPnl: string;\n liquidationPrice: string;\n /** 0 = cross, 1 = isolated. Older captures omit it (venue default cross). */\n marginMode?: number;\n};\n\n/**\n * One API key entry from `GET /api/v1/apikeys`.\n */\nexport type LighterApiKey = {\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n publicKey: string;\n};\n\n/**\n * Response of `GET /api/v1/apikeys`.\n */\nexport type LighterApiKeysResponse = {\n code: number;\n message?: string;\n apiKeys: LighterApiKey[];\n};\n\n/**\n * Response of `GET /api/v1/nextNonce`.\n */\nexport type LighterNextNonceResponse = {\n code: number;\n message?: string;\n nonce: number;\n};\n\n/**\n * Response of `GET /api/v1/tx?by=hash&value=...` (EnrichedTx). Only the\n * identity fields the settlement reconciler verifies are typed; a\n * successful exact-hash match proves the signed payload reached the\n * sequencer.\n */\nexport type LighterTxLookupResponse = {\n code: number;\n message?: string;\n hash: string;\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n status: number;\n};\n\n/**\n * Response of `POST /api/v1/sendTx`.\n */\nexport type LighterSendTxResponse = {\n code: number;\n message?: string;\n txHash: string;\n};\n\n/**\n * One market entry from the `market_stats/all` WebSocket channel\n * (`subscribed/market_stats` snapshot and `update/market_stats` deltas),\n * after snake→camel conversion at the socket boundary.\n */\nexport type LighterWsMarketStat = {\n symbol: string;\n marketId: number;\n indexPrice: string;\n markPrice: string;\n midPrice: string;\n bestAskPrice: string;\n bestBidPrice: string;\n lastTradePrice: string;\n openInterest: string;\n fundingRate: string;\n currentFundingRate?: string;\n dailyQuoteTokenVolume: number;\n dailyPriceChange: number;\n};\n\n/**\n * Envelope of a `market_stats` WebSocket message (post-camelization).\n */\nexport type LighterWsMarketStatsMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n marketStats?: Record<string, LighterWsMarketStat>;\n};\n\n/**\n * Stats block of a `user_stats/{account_index}` WebSocket message\n * (post-camelization). Live-verified against testnet account 28.\n */\nexport type LighterWsUserStats = {\n collateral: string;\n portfolioValue: string;\n leverage: string;\n availableBalance: string;\n marginUsage: string;\n buyingPower: string;\n};\n\n/**\n * Generic account-channel WebSocket envelope (post-camelization):\n * `user_stats` carries `stats`, `account_all_positions` carries `positions`\n * (same field shape as the REST account payload), `account_all_orders`\n * carries `orders` keyed by market id.\n */\nexport type LighterWsAccountMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n stats?: LighterWsUserStats;\n positions?: Record<string, LighterApiPosition>;\n orders?: Record<string, LighterApiOrder[]>;\n};\n\n/**\n * Minimal structural WebSocket surface the Lighter stream manager uses.\n * Structural (rather than the DOM/Node `WebSocket` type) so platforms and\n * tests can supply any compatible implementation.\n */\nexport type LighterWebSocketLike = {\n readyState: number;\n send(data: string): void;\n close(): void;\n onopen: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n};\n\n/**\n * Constructor for {@link LighterWebSocketLike} transports.\n */\nexport type LighterWebSocketCtor = new (url: string) => LighterWebSocketLike;\n\n/**\n * `order_book/{market_id}` WebSocket payload (post-camelization).\n * `subscribed/*` carries a full snapshot; `update/*` carries deltas where\n * `size: \"0.000\"` removes a level.\n */\nexport type LighterWsOrderBookMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n orderBook?: {\n /** Last nonce represented by this snapshot or delta. */\n nonce?: number;\n /** Previous book nonce required before applying an update. */\n beginNonce?: number;\n bids?: { price: string; size: string }[];\n asks?: { price: string; size: string }[];\n };\n};\n\n/**\n * `candle/{market_id}/{resolution}` WebSocket payload (post-camelization,\n * candle entries keep the compact t/o/h/l/c/v wire keys).\n */\nexport type LighterWsCandleMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n candles?: LighterCandle[];\n};\n\n/**\n * One trade entry from the `account_all_trades/{account_index}` channel\n * (post-camelization).\n */\nexport type LighterWsTrade = {\n tradeId: number;\n marketId: number;\n size: string;\n price: string;\n askId: number;\n bidId: number;\n askAccountId: number;\n bidAccountId: number;\n isMakerAsk: boolean;\n timestamp: number;\n /** Realized pnl per side — same wire shape as the REST trade payload. */\n askAccountPnl?: string;\n bidAccountPnl?: string;\n /** Fees, present when nonzero; unit unproven — see LighterRestTrade. */\n takerFee?: number | string;\n makerFee?: number | string;\n takerPositionSizeBefore?: string;\n makerPositionSizeBefore?: string;\n takerPositionSignChanged?: boolean;\n makerPositionSignChanged?: boolean;\n};\n\n/**\n * `account_all_trades/{account_index}` WebSocket payload (post-camelization).\n */\nexport type LighterWsTradesMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n trades?: Record<string, LighterWsTrade[]>;\n};\n\n/**\n * One trade from `GET /api/v1/trades` (post-camelization).\n */\nexport type LighterRestTrade = {\n tradeId: number;\n txHash: string;\n type: string;\n marketId: number;\n size: string;\n price: string;\n usdAmount: string;\n askId: number;\n bidId: number;\n askAccountId: number;\n bidAccountId: number;\n isMakerAsk: boolean;\n timestamp: number;\n /** Realized pnl for the ask-side account, signed USDC. */\n askAccountPnl?: string;\n /** Realized pnl for the bid-side account, signed USDC. */\n bidAccountPnl?: string;\n /**\n * Taker/maker fees, present when nonzero. The official model types them\n * as StrictInt with NO documented unit or scale; until a captured\n * nonzero payload proves one, adapters must treat these as unavailable.\n */\n takerFee?: number | string;\n makerFee?: number | string;\n /** Position size (absolute) of each side before the trade executed. */\n takerPositionSizeBefore: string;\n makerPositionSizeBefore: string;\n /** Whether the side's position sign changed (crossed or left zero). */\n takerPositionSignChanged: boolean;\n makerPositionSignChanged: boolean;\n};\n\n/**\n * Response of `GET /api/v1/trades`.\n */\nexport type LighterTradesResponse = {\n code: number;\n message?: string;\n nextCursor?: string;\n trades: LighterRestTrade[];\n};\n\n/** Query parameters supported by the Lighter trades endpoint. */\nexport type LighterTradesQuery = {\n limit: number;\n cursor?: string;\n from?: number;\n marketId?: number;\n};\n\n/**\n * One entry from `GET /api/v1/positionFunding` (post-camelization).\n */\nexport type LighterPositionFunding = {\n timestamp: number;\n marketId: number;\n fundingId: number;\n change: string;\n rate: string;\n positionSize: string;\n positionSide: string;\n};\n\n/**\n * Response of `GET /api/v1/positionFunding`.\n */\nexport type LighterPositionFundingsResponse = {\n code: number;\n message?: string;\n positionFundings: LighterPositionFunding[];\n};\n\n/**\n * One record from `GET /api/v1/pnl` (post-camelization).\n */\nexport type LighterPnlRecord = {\n timestamp: number;\n tradePnl: number;\n inflow: number;\n outflow: number;\n volume: number;\n};\n\n/**\n * Response of `GET /api/v1/pnl`.\n */\nexport type LighterPnlResponse = {\n code: number;\n message?: string;\n resolution?: string;\n pnl?: LighterPnlRecord[];\n};\n\n/**\n * One candle from `GET /api/v1/candles` (compact wire keys: t/o/h/l/c/v).\n */\nexport type LighterCandle = {\n t: number;\n o: number;\n h: number;\n l: number;\n c: number;\n v: number;\n};\n\n/**\n * Response of `GET /api/v1/candles`.\n */\nexport type LighterCandlesResponse = {\n code: number;\n message?: string;\n /** Resolution echo (e.g. `15m`). */\n r?: string;\n /** Ascending candle series. */\n c?: LighterCandle[];\n};\n\n/**\n * One order from `GET /api/v1/accountActiveOrders`.\n */\nexport type LighterApiOrder = {\n orderIndex: number;\n clientOrderIndex: number;\n marketIndex: number;\n ownerAccountIndex: number;\n initialBaseAmount: string;\n remainingBaseAmount: string;\n price: string;\n isAsk: boolean;\n type: string;\n timeInForce: string;\n reduceOnly: number | boolean;\n status: string;\n orderExpiry: number;\n timestamp: number;\n /**\n * Trigger level for stop-loss/take-profit orders. Note `price` on a\n * trigger order is the ±5% protection EXECUTION price, not this level.\n */\n triggerPrice?: string;\n /** Venue string order id (linkage fields reference this form). */\n orderId?: string;\n /** OCO/linkage: parent order references. */\n parentOrderIndex?: number;\n parentOrderId?: string;\n /** OCO linkage: the sibling this order auto-cancels when it fires. */\n toCancelOrderId0?: string;\n toTriggerOrderId0?: string;\n toTriggerOrderId1?: string;\n};\n\n/**\n * Response of `GET /api/v1/accountActiveOrders`.\n */\nexport type LighterActiveOrdersResponse = {\n code: number;\n message?: string;\n orders: LighterApiOrder[];\n};\n\n/**\n * Response of `GET /api/v1/accountInactiveOrders` (historical order\n * lifecycle: filled / canceled orders, newest first, cursor-paged).\n */\nexport type LighterInactiveOrdersResponse = {\n code: number;\n message?: string;\n nextCursor?: string;\n orders: LighterApiOrder[];\n};\n\n/**\n * One entry of `GET /api/v1/deposit/history` (camelized).\n */\nexport type LighterDepositHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n timestamp: number;\n status: string;\n l1TxHash: string;\n};\n\n/**\n * Response of `GET /api/v1/deposit/history`.\n */\nexport type LighterDepositHistoryResponse = {\n code: number;\n message?: string;\n deposits: LighterDepositHistoryItem[];\n cursor?: string;\n};\n\n/**\n * One entry of `GET /api/v1/withdraw/history` (camelized).\n */\nexport type LighterWithdrawHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n timestamp: number;\n status: string;\n type: string;\n l1TxHash: string;\n};\n\n/**\n * Response of `GET /api/v1/withdraw/history`.\n */\nexport type LighterWithdrawHistoryResponse = {\n code: number;\n message?: string;\n withdraws: LighterWithdrawHistoryItem[];\n cursor?: string;\n};\n\nexport type LighterTransferType = 'L2TransferInflow' | 'L2TransferOutflow';\n\n/**\n * One entry of `GET /api/v1/transfer/history` (camelized).\n */\nexport type LighterTransferHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n fee: string;\n timestamp: number;\n type: LighterTransferType;\n fromL1Address: string;\n toL1Address: string;\n fromAccountIndex: number;\n toAccountIndex: number;\n txHash: string;\n};\n\n/**\n * Response of `GET /api/v1/transfer/history`.\n */\nexport type LighterTransferHistoryResponse = {\n code: number;\n message?: string;\n transfers: LighterTransferHistoryItem[];\n cursor?: string;\n};\n"]}
1
+ {"version":3,"file":"lighter-types.js","sourceRoot":"","sources":["../../src/types/lighter-types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG","sourcesContent":["/**\n * Lighter Protocol Type Definitions\n *\n * Types for the zkLighter REST API, the Go/WASM signer bridge, and\n * provider configuration. No SDK dependency — shapes are derived from\n * the public API (https://apidocs.lighter.xyz) and the reference\n * WebView bridge (elliottech/lighter-go, `web-wasm` branch).\n */\n\n// ============================================================================\n// Network Configuration Types\n// ============================================================================\n\n/**\n * Lighter Network type - mainnet or testnet\n */\nexport type LighterNetwork = 'mainnet' | 'testnet';\n\n/**\n * Lighter endpoint configuration for a single network\n */\nexport type LighterEndpointConfig = {\n http: string;\n ws: string;\n};\n\n/**\n * Lighter endpoints for all networks\n */\nexport type LighterEndpoints = {\n mainnet: LighterEndpointConfig;\n testnet: LighterEndpointConfig;\n};\n\n// ============================================================================\n// Signer Bridge (WASM seam)\n// ============================================================================\n\n/**\n * A single call into the Lighter Go/WASM signer.\n *\n * Mirrors the postMessage protocol of the reference React Native WebView\n * bridge (`{ function, params }`), so a WebView-backed bridge on mobile and\n * an in-process WASM bridge in Node are interchangeable implementations.\n */\nexport type LighterCreateOrderWireParams = [\n marketId: number,\n clientOrderIndex: number,\n baseAmount: string,\n price: string,\n isAsk: number,\n orderType: number,\n timeInForce: number,\n reduceOnly: number,\n triggerPrice: string,\n orderExpiry: number,\n];\n\nexport type LighterGroupedOrderWireParams = [\n ...first: LighterCreateOrderWireParams,\n ...second: LighterCreateOrderWireParams,\n];\n\nexport type LighterCreateClientWireParams = [\n chainId: number,\n accountIndex: number,\n nonce: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignChangePubKeyWireParams = [\n accountIndex: number,\n l1Signature: string,\n nonce: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignCreateOrderWireParams = [\n accountIndex: number,\n ...order: LighterCreateOrderWireParams,\n nonce: number,\n];\n\nexport type LighterSignCreateGroupedOrdersWireParams = [\n accountIndex: number,\n groupingType: number,\n orderCount: 2,\n ...orders: LighterGroupedOrderWireParams,\n nonce: number,\n];\n\nexport type LighterSignCancelOrderWireParams = [\n accountIndex: number,\n marketId: number,\n orderId: string,\n nonce: number,\n];\n\nexport type LighterSignUpdateLeverageWireParams = [\n accountIndex: number,\n marketId: number,\n leverageImfHundredths: number,\n marginMode: number,\n nonce: number,\n];\n\nexport type LighterSignUpdateMarginWireParams = [\n accountIndex: number,\n marketId: number,\n amount: number,\n direction: number,\n nonce: number,\n];\n\nexport type LighterSignWithdrawWireParams = [\n accountIndex: number,\n assetIndex: number,\n routeType: number,\n amount: string,\n nonce: number,\n];\n\nexport type LighterCreateAuthTokenWireParams = [\n accountIndex: number,\n apiKeyIndex: number,\n];\n\nexport type LighterSignerOperationDefinition<\n Params extends unknown[],\n Result,\n> = {\n params: Params;\n result: Result;\n};\n\nexport type LighterSignerOperationMap = {\n _createClient: LighterSignerOperationDefinition<\n LighterCreateClientWireParams,\n LighterCreateClientResult\n >;\n _signChangePubKey: LighterSignerOperationDefinition<\n LighterSignChangePubKeyWireParams,\n LighterSignChangePubKeyResult\n >;\n _signCreateOrder: LighterSignerOperationDefinition<\n LighterSignCreateOrderWireParams,\n LighterTxResult\n >;\n _signCreateGroupedOrders: LighterSignerOperationDefinition<\n LighterSignCreateGroupedOrdersWireParams,\n LighterTxResult\n >;\n _signCancelOrder: LighterSignerOperationDefinition<\n LighterSignCancelOrderWireParams,\n LighterTxResult\n >;\n _signUpdateLeverage: LighterSignerOperationDefinition<\n LighterSignUpdateLeverageWireParams,\n LighterTxResult\n >;\n _signUpdateMargin: LighterSignerOperationDefinition<\n LighterSignUpdateMarginWireParams,\n LighterTxResult\n >;\n _signWithdraw: LighterSignerOperationDefinition<\n LighterSignWithdrawWireParams,\n LighterTxResult\n >;\n _createAuthToken: LighterSignerOperationDefinition<\n LighterCreateAuthTokenWireParams,\n LighterCreateAuthTokenResult\n >;\n};\n\nexport type LighterSignerOperation = keyof LighterSignerOperationMap;\n\nexport type LighterWasmCall<\n Operation extends LighterSignerOperation = LighterSignerOperation,\n> = Operation extends LighterSignerOperation\n ? {\n function: Operation;\n params: LighterSignerOperationMap[Operation]['params'];\n }\n : never;\n\nexport type LighterSignerResult<Operation extends LighterSignerOperation> =\n LighterSignerOperationMap[Operation]['result'];\n\n/** Public metadata needed to create or restore a client-owned venue signer. */\nexport type LighterCreateClientParams = {\n chainId: number;\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n};\n\n/**\n * Transport-agnostic seam to the Lighter Go/WASM signer.\n *\n * Implementations:\n * - Mobile: off-screen WebView loading the locally-bundled\n * `wasm-wrapper.standalone.html`, dispatching calls via postMessage.\n * - Node (e2e): in-process `WebAssembly.instantiate` via Go's `wasm_exec.js`.\n */\nexport type LighterSignerBridge = {\n /**\n * Create or restore the client-owned venue signer. The implementation owns\n * key generation and persistence; Core never receives the seed or private\n * key.\n *\n * @param params - Public venue/session metadata required by the signer.\n */\n createClient(\n params: LighterCreateClientParams,\n ): Promise<LighterCreateClientResult>;\n\n /**\n * Execute one WASM signer call and resolve with its result object.\n *\n * @param call - The function name and positional params to invoke.\n */\n execute<Operation extends LighterSignerOperation>(\n call: LighterWasmCall<Operation>,\n ): Promise<LighterSignerResult<Operation>>;\n\n /**\n * Optional subscription to bridge resets (WebView reload / process\n * loss). The provider uses it to invalidate its cached signer session\n * IMMEDIATELY instead of learning about the reset from the next failed\n * trading call.\n *\n * @param listener - Invoked on every reset.\n * @returns Unsubscribe function.\n */\n onReset?(listener: () => void): () => void;\n\n /**\n * Optional hook to re-arm the bridge after a reload (WebView remount).\n */\n reset?(): void;\n};\n\n// ============================================================================\n// WASM signer response shapes (from lighter-go react-native/src/lighterSdk.ts)\n// ============================================================================\n\n/**\n * Response of `_createClient` / `_createClientByPrv`.\n */\nexport type LighterCreateClientResult = {\n success: boolean;\n /** Venue public key, hex (80 chars / 40 bytes, Schnorr over ECgFp5). */\n pk: string;\n pubKeySuccess: boolean;\n /**\n * ChangePubKey plaintext body to be signed with EIP-191 `personal_sign`\n * by the user's L1 (EVM) account.\n */\n body: string;\n error?: string;\n};\n\n/**\n * Response of `_signChangePubKey`.\n */\nexport type LighterSignChangePubKeyResult = {\n /** Serialized L2 transaction JSON (includes the injected `L1Sig`). */\n txInfo: string;\n /**\n * Signed transaction hash (pinned WASM contract: the signing RESULT\n * carries the hash; `txInfo` never does). Required for the durable\n * dispatch ledger's exact-identity reconciliation.\n */\n txHash?: string;\n error?: string;\n};\n\n/**\n * Response of `_createAuthToken`.\n */\nexport type LighterCreateAuthTokenResult = {\n token: string;\n deadline: number;\n error?: string;\n};\n\n/**\n * Response of signing functions returning a full L2 transaction\n * (`_signCreateOrder`, `_signCancelOrder`, ...).\n */\nexport type LighterTxResult = {\n txInfo: string;\n txHash?: string;\n error?: string;\n};\n\n// ============================================================================\n// Auth Configuration\n// ============================================================================\n\n/**\n * Signs an EIP-191 personal message and resolves with the 65-byte signature\n * as a 0x-prefixed hex string. Injected for headless use; when a messenger\n * is available the wallet service routes through\n * `KeyringController:signPersonalMessage` instead.\n */\nexport type LighterPersonalSigner = (message: string) => Promise<string>;\n\n/**\n * Lighter auth/config passed at construction time.\n */\nexport type LighterAuthConfig = {\n /** Whether the Lighter provider is enabled via local override. */\n enabled?: boolean;\n /** Lighter account index (assigned at first deposit). */\n accountIndex?: number;\n /** API key slot to register/use (0-254). */\n apiKeyIndex?: number;\n /** L1 address owning the Lighter account. */\n l1Address?: string;\n /** Headless personal_sign implementation for L1 ChangePubKey approval. */\n personalSigner?: LighterPersonalSigner;\n};\n\n// ============================================================================\n// REST API response shapes (subset used by the POC)\n//\n// The zkLighter wire format is snake_case; LighterClientService converts\n// keys to camelCase at the fetch boundary so these parsed shapes follow\n// package conventions.\n// ============================================================================\n\n/**\n * One market entry from `GET /api/v1/orderBooks`.\n */\nexport type LighterOrderBookMeta = {\n symbol: string;\n marketId: number;\n marketType: string;\n status: string;\n takerFee: string;\n makerFee: string;\n minBaseAmount: string;\n minQuoteAmount: string;\n supportedSizeDecimals: number;\n supportedPriceDecimals: number;\n supportedQuoteDecimals: number;\n};\n\n/**\n * Response of `GET /api/v1/orderBooks`.\n */\nexport type LighterOrderBooksResponse = {\n code: number;\n orderBooks: LighterOrderBookMeta[];\n};\n\n/**\n * Market stats from `GET /api/v1/orderBookDetails`.\n */\nexport type LighterOrderBookDetail = LighterOrderBookMeta & {\n lastTradePrice: number;\n /** Default initial margin fraction, hundredths of a percent (666 = 6.66%). */\n defaultInitialMarginFraction?: number;\n /** Minimum initial margin fraction, hundredths of a percent (400 → 25x max). */\n minInitialMarginFraction?: number;\n /** Maintenance margin fraction, hundredths of a percent (240 = 2.4%). */\n maintenanceMarginFraction?: number;\n dailyTradesCount: number;\n dailyBaseTokenVolume: number;\n dailyQuoteTokenVolume: number;\n dailyPriceLow: number;\n dailyPriceHigh: number;\n dailyPriceChange: number;\n openInterest: number;\n dailyChart: Record<string, number>;\n};\n\n/**\n * Response of `GET /api/v1/orderBookDetails`.\n */\nexport type LighterOrderBookDetailsResponse = {\n code: number;\n orderBookDetails: LighterOrderBookDetail[];\n};\n\n/**\n * One sub-account from `GET /api/v1/accountsByL1Address` or `account`.\n */\nexport type LighterSubAccount = {\n code: number;\n accountType: number;\n index: number;\n l1Address: string;\n cancelAllTime: number;\n totalOrderCount: number;\n pendingOrderCount: number;\n status: number;\n collateral: string;\n availableBalance: string;\n positions?: LighterApiPosition[];\n};\n\n/**\n * Identity fields returned by `GET /api/v1/accountsByL1Address`.\n *\n * Lighter's address-discovery endpoint may leave balance fields empty even\n * though the full `account` endpoint returns validated decimal values. Account\n * discovery only consumes these identity fields; financial reads continue to\n * use {@link LighterSubAccount} and its stricter response validation.\n */\nexport type LighterAccountSummary = Pick<\n LighterSubAccount,\n 'accountType' | 'index' | 'l1Address'\n>;\n\n/**\n * Response of `GET /api/v1/accountsByL1Address`.\n */\nexport type LighterAccountsByL1AddressResponse = {\n code: number;\n message?: string;\n l1Address: string;\n subAccounts: LighterAccountSummary[];\n};\n\n/**\n * Response of `GET /api/v1/account` (`by=index`).\n */\nexport type LighterAccountResponse = {\n code: number;\n message?: string;\n accounts: LighterSubAccount[];\n};\n\n/**\n * One position inside an account payload.\n */\nexport type LighterApiPosition = {\n marketId: number;\n symbol: string;\n initialMarginFraction: string;\n openOrderCount: number;\n /** 1 = long, -1 = short (sign convention per API). */\n sign: number;\n position: string;\n avgEntryPrice: string;\n positionValue: string;\n unrealizedPnl: string;\n realizedPnl: string;\n liquidationPrice: string;\n /** 0 = cross, 1 = isolated. Older captures omit it (venue default cross). */\n marginMode?: number;\n};\n\n/**\n * One API key entry from `GET /api/v1/apikeys`.\n */\nexport type LighterApiKey = {\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n publicKey: string;\n};\n\n/**\n * Response of `GET /api/v1/apikeys`.\n */\nexport type LighterApiKeysResponse = {\n code: number;\n message?: string;\n apiKeys: LighterApiKey[];\n};\n\n/**\n * Response of `GET /api/v1/nextNonce`.\n */\nexport type LighterNextNonceResponse = {\n code: number;\n message?: string;\n nonce: number;\n};\n\n/**\n * Response of `GET /api/v1/tx?by=hash&value=...` (EnrichedTx). Only the\n * identity fields the settlement reconciler verifies are typed; a\n * successful exact-hash match proves the signed payload reached the\n * sequencer.\n */\nexport type LighterTxLookupResponse = {\n code: number;\n message?: string;\n hash: string;\n accountIndex: number;\n apiKeyIndex: number;\n nonce: number;\n status: number;\n};\n\n/**\n * Response of `POST /api/v1/sendTx`.\n */\nexport type LighterSendTxResponse = {\n code: number;\n message?: string;\n txHash: string;\n};\n\n/**\n * One market entry from the `market_stats/all` WebSocket channel\n * (`subscribed/market_stats` snapshot and `update/market_stats` deltas),\n * after snake→camel conversion at the socket boundary.\n */\nexport type LighterWsMarketStat = {\n symbol: string;\n marketId: number;\n indexPrice: string;\n markPrice: string;\n midPrice: string;\n bestAskPrice: string;\n bestBidPrice: string;\n lastTradePrice: string;\n openInterest: string;\n fundingRate: string;\n currentFundingRate?: string;\n dailyQuoteTokenVolume: number;\n dailyPriceChange: number;\n};\n\n/**\n * Envelope of a `market_stats` WebSocket message (post-camelization).\n */\nexport type LighterWsMarketStatsMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n marketStats?: Record<string, LighterWsMarketStat>;\n};\n\n/**\n * Stats block of a `user_stats/{account_index}` WebSocket message\n * (post-camelization). Live-verified against testnet account 28.\n */\nexport type LighterWsUserStats = {\n collateral: string;\n portfolioValue: string;\n leverage: string;\n availableBalance: string;\n marginUsage: string;\n buyingPower: string;\n};\n\n/**\n * Generic account-channel WebSocket envelope (post-camelization):\n * `user_stats` carries `stats`, `account_all_positions` carries `positions`\n * (same field shape as the REST account payload), `account_all_orders`\n * carries `orders` keyed by market id.\n */\nexport type LighterWsAccountMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n stats?: LighterWsUserStats;\n positions?: Record<string, LighterApiPosition>;\n orders?: Record<string, LighterApiOrder[]>;\n};\n\n/**\n * Minimal structural WebSocket surface the Lighter stream manager uses.\n * Structural (rather than the DOM/Node `WebSocket` type) so platforms and\n * tests can supply any compatible implementation.\n */\nexport type LighterWebSocketLike = {\n readyState: number;\n send(data: string): void;\n close(): void;\n onopen: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n};\n\n/**\n * Constructor for {@link LighterWebSocketLike} transports.\n */\nexport type LighterWebSocketCtor = new (url: string) => LighterWebSocketLike;\n\n/**\n * `order_book/{market_id}` WebSocket payload (post-camelization).\n * `subscribed/*` carries a full snapshot; `update/*` carries deltas where\n * `size: \"0.000\"` removes a level.\n */\nexport type LighterWsOrderBookMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n orderBook?: {\n /** Last nonce represented by this snapshot or delta. */\n nonce?: number;\n /** Previous book nonce required before applying an update. */\n beginNonce?: number;\n bids?: { price: string; size: string }[];\n asks?: { price: string; size: string }[];\n };\n};\n\n/**\n * `candle/{market_id}/{resolution}` WebSocket payload (post-camelization,\n * candle entries keep the compact t/o/h/l/c/v wire keys).\n */\nexport type LighterWsCandleMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n candles?: LighterCandle[];\n};\n\n/**\n * One trade entry from the `account_all_trades/{account_index}` channel\n * (post-camelization).\n */\nexport type LighterWsTrade = {\n tradeId: number;\n marketId: number;\n size: string;\n price: string;\n askId: number;\n bidId: number;\n askAccountId: number;\n bidAccountId: number;\n isMakerAsk: boolean;\n timestamp: number;\n /** Realized pnl per side — same wire shape as the REST trade payload. */\n askAccountPnl?: string;\n bidAccountPnl?: string;\n /** Fees, present when nonzero; unit unproven — see LighterRestTrade. */\n takerFee?: number | string;\n makerFee?: number | string;\n takerPositionSizeBefore?: string;\n makerPositionSizeBefore?: string;\n takerPositionSignChanged?: boolean;\n makerPositionSignChanged?: boolean;\n};\n\n/**\n * `account_all_trades/{account_index}` WebSocket payload (post-camelization).\n */\nexport type LighterWsTradesMessage = {\n type: string;\n channel?: string;\n timestamp?: number;\n trades?: Record<string, LighterWsTrade[]>;\n};\n\n/**\n * One trade from `GET /api/v1/trades` (post-camelization).\n */\nexport type LighterRestTrade = {\n tradeId: number;\n txHash: string;\n type: string;\n marketId: number;\n size: string;\n price: string;\n usdAmount: string;\n askId: number;\n bidId: number;\n askAccountId: number;\n bidAccountId: number;\n isMakerAsk: boolean;\n timestamp: number;\n /** Realized pnl for the ask-side account, signed USDC; may be omitted on opens from flat. */\n askAccountPnl?: string;\n /** Realized pnl for the bid-side account, signed USDC; may be omitted on opens from flat. */\n bidAccountPnl?: string;\n /**\n * Taker/maker fees, present when nonzero. The official model types them\n * as StrictInt with NO documented unit or scale; until a captured\n * nonzero payload proves one, adapters must treat these as unavailable.\n */\n takerFee?: number | string;\n makerFee?: number | string;\n /** Position size (absolute) of each side before the trade executed. */\n takerPositionSizeBefore: string;\n makerPositionSizeBefore: string;\n /** Whether the side's position sign changed (crossed or left zero). */\n takerPositionSignChanged: boolean;\n makerPositionSignChanged: boolean;\n};\n\n/**\n * Response of `GET /api/v1/trades`.\n */\nexport type LighterTradesResponse = {\n code: number;\n message?: string;\n nextCursor?: string;\n trades: LighterRestTrade[];\n};\n\n/** Query parameters supported by the Lighter trades endpoint. */\nexport type LighterTradesQuery = {\n limit: number;\n cursor?: string;\n from?: number;\n marketId?: number;\n};\n\n/**\n * One entry from `GET /api/v1/positionFunding` (post-camelization).\n */\nexport type LighterPositionFunding = {\n timestamp: number;\n marketId: number;\n fundingId: number;\n change: string;\n rate: string;\n positionSize: string;\n positionSide: string;\n};\n\n/**\n * Response of `GET /api/v1/positionFunding`.\n */\nexport type LighterPositionFundingsResponse = {\n code: number;\n message?: string;\n positionFundings: LighterPositionFunding[];\n};\n\n/**\n * One record from `GET /api/v1/pnl` (post-camelization).\n */\nexport type LighterPnlRecord = {\n timestamp: number;\n tradePnl: number;\n inflow: number;\n outflow: number;\n volume: number;\n};\n\n/**\n * Response of `GET /api/v1/pnl`.\n */\nexport type LighterPnlResponse = {\n code: number;\n message?: string;\n resolution?: string;\n pnl?: LighterPnlRecord[];\n};\n\n/**\n * One candle from `GET /api/v1/candles` (compact wire keys: t/o/h/l/c/v).\n */\nexport type LighterCandle = {\n t: number;\n o: number;\n h: number;\n l: number;\n c: number;\n v: number;\n};\n\n/**\n * Response of `GET /api/v1/candles`.\n */\nexport type LighterCandlesResponse = {\n code: number;\n message?: string;\n /** Resolution echo (e.g. `15m`). */\n r?: string;\n /** Ascending candle series. */\n c?: LighterCandle[];\n};\n\n/**\n * One order from `GET /api/v1/accountActiveOrders`.\n */\nexport type LighterApiOrder = {\n orderIndex: number;\n clientOrderIndex: number;\n marketIndex: number;\n ownerAccountIndex: number;\n initialBaseAmount: string;\n remainingBaseAmount: string;\n price: string;\n isAsk: boolean;\n type: string;\n timeInForce: string;\n reduceOnly: number | boolean;\n status: string;\n orderExpiry: number;\n /** Unix seconds from order endpoints, unlike millisecond trade timestamps. */\n timestamp: number;\n /**\n * Trigger level for stop-loss/take-profit orders. Note `price` on a\n * trigger order is the ±5% protection EXECUTION price, not this level.\n */\n triggerPrice?: string;\n /** Venue string order id (linkage fields reference this form). */\n orderId?: string;\n /** OCO/linkage: parent order references. */\n parentOrderIndex?: number;\n parentOrderId?: string;\n /** OCO linkage: the sibling this order auto-cancels when it fires. */\n toCancelOrderId0?: string;\n toTriggerOrderId0?: string;\n toTriggerOrderId1?: string;\n};\n\n/**\n * Response of `GET /api/v1/accountActiveOrders`.\n */\nexport type LighterActiveOrdersResponse = {\n code: number;\n message?: string;\n orders: LighterApiOrder[];\n};\n\n/**\n * Response of `GET /api/v1/accountInactiveOrders` (historical order\n * lifecycle: filled / canceled orders, newest first, cursor-paged).\n */\nexport type LighterInactiveOrdersResponse = {\n code: number;\n message?: string;\n nextCursor?: string;\n orders: LighterApiOrder[];\n};\n\n/**\n * One entry of `GET /api/v1/deposit/history` (camelized).\n */\nexport type LighterDepositHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n timestamp: number;\n status: string;\n l1TxHash: string;\n};\n\n/**\n * Response of `GET /api/v1/deposit/history`.\n */\nexport type LighterDepositHistoryResponse = {\n code: number;\n message?: string;\n deposits: LighterDepositHistoryItem[];\n cursor?: string;\n};\n\n/**\n * One entry of `GET /api/v1/withdraw/history` (camelized).\n */\nexport type LighterWithdrawHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n timestamp: number;\n status: string;\n type: string;\n l1TxHash: string;\n};\n\n/**\n * Response of `GET /api/v1/withdraw/history`.\n */\nexport type LighterWithdrawHistoryResponse = {\n code: number;\n message?: string;\n withdraws: LighterWithdrawHistoryItem[];\n cursor?: string;\n};\n\nexport type LighterTransferType = 'L2TransferInflow' | 'L2TransferOutflow';\n\n/**\n * One entry of `GET /api/v1/transfer/history` (camelized).\n */\nexport type LighterTransferHistoryItem = {\n id: string;\n assetId: number;\n amount: string;\n fee: string;\n timestamp: number;\n type: LighterTransferType;\n fromL1Address: string;\n toL1Address: string;\n fromAccountIndex: number;\n toAccountIndex: number;\n txHash: string;\n};\n\n/**\n * Response of `GET /api/v1/transfer/history`.\n */\nexport type LighterTransferHistoryResponse = {\n code: number;\n message?: string;\n transfers: LighterTransferHistoryItem[];\n cursor?: string;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"lighterAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,OAAO,KAAK,EACV,YAAY,EACZ,oBAAoB,EACpB,UAAU,EACV,KAAK,EACL,SAAS,EACT,eAAe,EACf,QAAQ,EACR,WAAW,EAEZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,2BAA2B,CAAC;AA+CnC;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,oBAAoB,EAC5B,WAAW,EAAE,MAAM,GAClB,UAAU,CAeZ;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,sBAAsB,EAC9B,UAAU,EAAE,oBAAoB,GAC/B,eAAe,CAmCjB;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,sBAAsB,EAC9B,SAAS,EAAE,MAAM,GAChB,WAAW,CAUb;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAC/C,IAAI,EAAE,mBAAmB,EACzB,SAAS,EAAE,MAAM,GAChB,WAAW,CAqBb;AAED;;;;;GAKG;AACH,wBAAgB,qCAAqC,CACnD,KAAK,EAAE,kBAAkB,GACxB,YAAY,CAwBd;AAED;;;;;;;;GAQG;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,KAAK,EAAE,OAA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e,CAmCjB;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,sBAAsB,EAC9B,SAAS,EAAE,MAAM,GAChB,WAAW,CAUb;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAC/C,IAAI,EAAE,mBAAmB,EACzB,SAAS,EAAE,MAAM,GAChB,WAAW,CAqBb;AAED;;;;;GAKG;AACH,wBAAgB,qCAAqC,CACnD,KAAK,EAAE,kBAAkB,GACxB,YAAY,CAwBd;AAED;;;;;;;;GAQG;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,OAAO,GAAG,SAAS,CAAC;IACjC,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,MAAM,CAuBT;AAkCD,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,gBAAgB,GAAG,cAAc,EACxC,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GACnB,SAAS,CAsIX;AAMD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,kBAAkB,EAC5B,WAAW,GAAE,MAA6B,GACzC,QAAQ,CA8DV;AAMD;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,iBAAiB,GACzB,YAAY,CAgCd;AA0CD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,MAAM,GACb,KAAK,CAyEP"}
@@ -303,13 +303,6 @@ export function adaptFillFromLighterTrade(trade, symbol, accountIndex) {
303
303
  throw new Error(`${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} nonzero fee in trade ${trade.tradeId}: fee unit is unverified`);
304
304
  }
305
305
  const fee = '0';
306
- const pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;
307
- const parsedPnl = parseLighterStrictDecimal(pnl);
308
- if (typeof pnl !== 'string' ||
309
- parsedPnl === null ||
310
- !Number.isFinite(parsedPnl)) {
311
- throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`);
312
- }
313
306
  const isBuy = !accountIsAsk;
314
307
  // The account's maker/taker role selects the matching pre-trade position
315
308
  // context. Missing context is rejected above instead of becoming neutral
@@ -327,6 +320,16 @@ export function adaptFillFromLighterTrade(trade, symbol, accountIndex) {
327
320
  typeof signChanged !== 'boolean') {
328
321
  throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid position context`);
329
322
  }
323
+ const accountPnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;
324
+ // The venue omits PnL on opens from flat. Only a validated zero pre-trade
325
+ // position proves zero realized PnL; never assume it for an existing position.
326
+ const pnl = accountPnl === undefined && positionBefore === 0 ? '0' : accountPnl;
327
+ const parsedPnl = parseLighterStrictDecimal(pnl);
328
+ if (typeof pnl !== 'string' ||
329
+ parsedPnl === null ||
330
+ !Number.isFinite(parsedPnl)) {
331
+ throw new Error(`${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`);
332
+ }
330
333
  const direction = deriveLighterFillDirection({
331
334
  isBuy,
332
335
  size,
@@ -554,7 +557,9 @@ export function adaptOrderFromLighter(order, symbol) {
554
557
  filledSize: String(filled),
555
558
  remainingSize: order.remainingBaseAmount,
556
559
  status: adaptOrderStatus(order.status),
557
- timestamp: order.timestamp,
560
+ // Order endpoints report seconds; preserve already-normalized millisecond
561
+ // inputs. Trade timestamps are a separate millisecond wire contract.
562
+ timestamp: order.timestamp < 1e12 ? order.timestamp * 1000 : order.timestamp,
558
563
  reduceOnly: Boolean(order.reduceOnly),
559
564
  providerId: 'lighter',
560
565
  };
@@ -1 +1 @@
1
- {"version":3,"file":"lighterAdapter.js","sourceR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CAAC,UAAU,CAAC;QACjC,MAAM;QACN,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK;QAClC,SAAS,EACP,WAAW,EAAE,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1E,GAAG,CAAC,WAAW;YACb,CAAC,CAAC;gBACE,gBAAgB,EAAE,WAAW,CAAC,gBAAgB;gBAC9C,iBAAiB,EAAE,WAAW,CAAC,QAAQ;aACxC;YACH,CAAC,CAAC,EAAE,CAAC;QACP,SAAS;QACT,IAAI,EAAE,KAAK,CAAC,mBAAmB;QAC/B,YAAY,EAAE,KAAK,CAAC,iBAAiB;QACrC,mEAAmE;QACnE,iDAAiD;QACjD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,GAAG,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC;QACvD,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1B,aAAa,EAAE,KAAK,CAAC,mBAAmB;QACxC,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC;QACtC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;QACrC,UAAU,EAAE,SAAS;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Lighter API Adapter Utilities\n *\n * Adapters transforming zkLighter REST payloads into the MetaMask Perps API\n * canonical types. Portable: no mobile-specific imports; formatters are\n * injected via the MarketDataFormatters interface.\n *\n * Key differences from HyperLiquid:\n * - Prices/sizes are human-readable decimal strings in REST responses, but\n * integers scaled by `supported_*_decimals` on the signing path.\n * - Position side is a `sign` field (1 = long, -1 = short).\n * - USDC collateral, single margin mode per account in the POC (cross).\n */\n\nimport {\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport type {\n AccountState,\n MarketDataFormatters,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n PriceUpdate,\n TriggerOrderType,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterOrderBookDetail,\n LighterOrderBookMeta,\n LighterRestTrade,\n LighterWsTrade,\n LighterSubAccount,\n LighterWsMarketStat,\n LighterWsUserStats,\n} from '../types/lighter-types.js';\n\n/**\n * Parse an account-state number at the untrusted venue boundary. Account\n * balances feed trading availability and must never accept prefix parses or\n * propagate NaN/Infinity into canonical state.\n *\n * @param value - Raw venue decimal string.\n * @param field - Field identity for the integrity error.\n * @returns A finite, fully parsed number.\n */\nfunction parseStrictAccountDecimal(value: string, field: string): number {\n const parsed = parseLighterStrictDecimal(value);\n if (parsed === null || !Number.isFinite(parsed)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} ${field} '${String(value)}'`,\n );\n }\n return parsed;\n}\n\n/**\n * Format a price change value with sign prefix.\n *\n * @param change - The price change value to format.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns The formatted change string with sign and dollar symbol.\n */\nfunction formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change) || change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n\n// ============================================================================\n// Market Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter order book meta entry into canonical MarketInfo.\n *\n * @param market - Market metadata from `GET /api/v1/orderBooks`.\n * @param maxLeverage - Verified per-market leverage from margin metadata.\n * @returns MetaMask Perps API market info object.\n */\nexport function adaptMarketFromLighter(\n market: LighterOrderBookMeta,\n maxLeverage: number,\n): MarketInfo {\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n return {\n name: market.symbol,\n szDecimals: market.supportedSizeDecimals,\n maxLeverage,\n marginTableId: 0, // Lighter does not use margin tables\n minimumOrderSize: parseFloat(market.minQuoteAmount),\n providerId: 'lighter',\n ...(market.status === 'active' ? {} : { isDelisted: true as const }),\n };\n}\n\n/**\n * Transform a Lighter order book detail into UI-ready PerpsMarketData.\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns MetaMask Perps API market data object.\n */\nexport function adaptMarketDataFromLighter(\n detail: LighterOrderBookDetail,\n formatters: MarketDataFormatters,\n): PerpsMarketData {\n const { minInitialMarginFraction } = detail;\n if (\n !Number.isFinite(minInitialMarginFraction) ||\n minInitialMarginFraction === undefined ||\n minInitialMarginFraction <= 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${detail.symbol}`,\n );\n }\n const price = detail.lastTradePrice ?? 0;\n const changePercent = detail.dailyPriceChange ?? 0;\n // dailyPriceChange is a percentage; recover the absolute change.\n const changeAbs =\n changePercent === 0 ? 0 : (price * changePercent) / (100 + changePercent);\n\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid authoritative leverage for ${detail.symbol}`,\n );\n }\n return {\n symbol: detail.symbol,\n name: detail.symbol,\n maxLeverage: `${maxLeverage}x`,\n price: formatters.formatPerpsFiat(price, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: formatChange(changeAbs, formatters),\n change24hPercent: `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`,\n volume: formatters.formatVolume(detail.dailyQuoteTokenVolume ?? 0),\n openInterest: formatters.formatVolume(detail.openInterest ?? 0),\n };\n}\n\n/**\n * Transform a Lighter order book detail into a canonical PriceUpdate for\n * price-stream subscribers (REST polling stands in for a WS feed in the POC).\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighter(\n detail: LighterOrderBookDetail,\n timestamp: number,\n): PriceUpdate {\n return {\n symbol: detail.symbol,\n price: String(detail.lastTradePrice ?? 0),\n timestamp,\n percentChange24h: String(detail.dailyPriceChange ?? 0),\n volume24h: detail.dailyQuoteTokenVolume ?? 0,\n openInterest: detail.openInterest ?? 0,\n isTradable: detail.status === 'active',\n };\n}\n\n/**\n * Transform a `market_stats` WebSocket entry into a canonical PriceUpdate.\n * Richer than the REST fallback: carries mid/bid/ask, mark price, and funding.\n *\n * @param stat - Market stats entry from the `market_stats/all` WS channel.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighterWsStat(\n stat: LighterWsMarketStat,\n timestamp: number,\n): PriceUpdate {\n const bestBid = parseFloat(stat.bestBidPrice);\n const bestAsk = parseFloat(stat.bestAskPrice);\n const spread =\n Number.isFinite(bestBid) && Number.isFinite(bestAsk)\n ? String(bestAsk - bestBid)\n : undefined;\n return {\n symbol: stat.symbol,\n price: stat.midPrice,\n timestamp,\n percentChange24h: String(stat.dailyPriceChange ?? 0),\n bestBid: stat.bestBidPrice,\n bestAsk: stat.bestAskPrice,\n spread,\n markPrice: stat.markPrice,\n funding: parseFloat(stat.currentFundingRate ?? stat.fundingRate ?? '0'),\n openInterest: parseFloat(stat.openInterest ?? '0'),\n volume24h: stat.dailyQuoteTokenVolume ?? 0,\n isTradable: true,\n };\n}\n\n/**\n * Transform a `user_stats` WebSocket stats block into canonical AccountState.\n *\n * @param stats - Stats block from the `user_stats/{account_index}` channel.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighterUserStats(\n stats: LighterWsUserStats,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n stats.collateral,\n 'WebSocket collateral',\n );\n const available = parseStrictAccountDecimal(\n stats.availableBalance,\n 'WebSocket available balance',\n );\n const portfolioValue = parseStrictAccountDecimal(\n stats.portfolioValue,\n 'WebSocket portfolio value',\n );\n return {\n totalBalance: String(portfolioValue),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n marginUsed: String(Math.max(collateral - available, 0)),\n unrealizedPnl: String(portfolioValue - collateral),\n returnOnEquity:\n collateral > 0\n ? String(((portfolioValue - collateral) / collateral) * 100)\n : '0',\n };\n}\n\n/**\n * Transform a Lighter trade (REST `/trades` or WS `account_all_trades`) into\n * a canonical OrderFill from the perspective of `accountIndex`.\n *\n * @param trade - Trade entry (post-camelization).\n * @param symbol - Market symbol resolved from the market id.\n * @param accountIndex - The account whose perspective determines the side.\n * @returns MetaMask Perps API order fill object.\n */\n/**\n * Derive the lifecycle direction of a fill from the venue's\n * position-before context, in the vocabulary client transforms consume\n * (`Open Long`, `Close Short`, `Long > Short`, ...).\n *\n * The venue reports the side's ABSOLUTE position size before the trade and\n * whether its sign changed. Combined with the trade side that is enough:\n * buying reduces shorts and opens longs; selling reduces longs and opens\n * shorts. A partial fill with no sign change is disambiguated by realized\n * pnl (closing realizes pnl, opening does not). Without position context\n * the side-only `Buy`/`Sell` vocabulary is used.\n *\n * @param context - Trade side, size, and position-before data.\n * @param context.isBuy - Whether our side bought.\n * @param context.size - Trade size (base units, absolute).\n * @param context.positionBefore - Our side's absolute position size before.\n * @param context.signChanged - Whether our side's position sign changed.\n * @param context.pnl - Realized pnl for our side.\n * @returns Client-facing direction string.\n */\nexport function deriveLighterFillDirection(context: {\n isBuy: boolean;\n size: number;\n positionBefore: number;\n signChanged: boolean | undefined;\n pnl: number;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore) || signChanged === undefined) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n if (signChanged) {\n // Crossed past zero → flipped; landed exactly on zero → full close.\n if (size > positionBefore * 1.000001) {\n return isBuy ? 'Short > Long' : 'Long > Short';\n }\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Partial fill on an existing position: realized pnl proves it reduced.\n if (pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero-pnl partial with no sign change is genuinely ambiguous from this\n // payload (a break-even partial close and an add both fit): fall back to\n // the side-only vocabulary instead of asserting Open without evidence.\n return isBuy ? 'Buy' : 'Sell';\n}\n\n/**\n * Parse one optional venue fee without treating malformed supplied values as\n * an omitted zero.\n *\n * @param value - Raw maker or taker fee.\n * @param tradeId - Trade identity for error context.\n * @param role - Fee role for error context.\n * @returns The finite nonnegative fee, with undefined mapped to venue-zero.\n */\nfunction parseLighterTradeFee(\n value: unknown,\n tradeId: number,\n role: 'maker' | 'taker',\n): number {\n let parsed: number | null;\n if (value === undefined) {\n parsed = 0;\n } else if (typeof value === 'number') {\n parsed = value;\n } else if (typeof value === 'string') {\n parsed = parseLighterStrictDecimal(value);\n } else {\n parsed = null;\n }\n if (parsed === null || !Number.isFinite(parsed) || parsed < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${tradeId} has invalid ${role} fee`,\n );\n }\n return parsed;\n}\n\nexport function adaptFillFromLighterTrade(\n trade: LighterRestTrade | LighterWsTrade,\n symbol: string,\n accountIndex: number,\n): OrderFill {\n const identifiers = [\n ['trade id', trade.tradeId],\n ['market id', trade.marketId],\n ['ask id', trade.askId],\n ['bid id', trade.bidId],\n ['ask account id', trade.askAccountId],\n ['bid account id', trade.bidAccountId],\n ] as const;\n for (const [field, value] of identifiers) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${String(trade.tradeId)} has invalid ${field}`,\n );\n }\n }\n const accountIsAsk = trade.askAccountId === accountIndex;\n const accountIsBid = trade.bidAccountId === accountIndex;\n if (accountIsAsk === accountIsBid) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} account ${accountIndex} is not an unambiguous participant in trade ${trade.tradeId}`,\n );\n }\n const size = parseLighterStrictDecimal(trade.size);\n const price = parseLighterStrictDecimal(trade.price);\n if (size === null || !Number.isFinite(size) || size <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid size`,\n );\n }\n if (price === null || !Number.isFinite(price) || price <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid price`,\n );\n }\n if (!Number.isSafeInteger(trade.timestamp) || trade.timestamp < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid timestamp`,\n );\n }\n if (typeof trade.isMakerAsk !== 'boolean') {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing maker-role context`,\n );\n }\n // Our side's role decides which fee applies; the venue includes the fee\n // fields only when nonzero (zero is the current standard-account truth).\n const accountIsMaker = accountIsAsk === trade.isMakerAsk;\n // Standard accounts (the only supported type — the provider gates\n // Premium at account resolution) pay zero fees, so zero is venue truth.\n // A PRESENT nonzero fee ON OUR SIDE contradicts that gate and its wire\n // unit is unverified: refusing loudly beats silently coercing a real fee\n // to $0. A valid nonzero counterparty fee is allowed, but malformed\n // supplied counterparty data still invalidates the venue row.\n const makerFee = parseLighterTradeFee(trade.makerFee, trade.tradeId, 'maker');\n const takerFee = parseLighterTradeFee(trade.takerFee, trade.tradeId, 'taker');\n const ourFeeNumeric = accountIsMaker ? makerFee : takerFee;\n if (ourFeeNumeric !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} nonzero fee in trade ${trade.tradeId}: fee unit is unverified`,\n );\n }\n const fee = '0';\n const pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n const parsedPnl = parseLighterStrictDecimal(pnl);\n if (\n typeof pnl !== 'string' ||\n parsedPnl === null ||\n !Number.isFinite(parsedPnl)\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`,\n );\n }\n const isBuy = !accountIsAsk;\n // The account's maker/taker role selects the matching pre-trade position\n // context. Missing context is rejected above instead of becoming neutral\n // history that looks authoritative.\n const positionBeforeRaw = accountIsMaker\n ? trade.makerPositionSizeBefore\n : trade.takerPositionSizeBefore;\n const positionBefore = parseLighterStrictDecimal(positionBeforeRaw);\n const signChanged = accountIsMaker\n ? trade.makerPositionSignChanged\n : trade.takerPositionSignChanged;\n if (\n positionBefore === null ||\n !Number.isFinite(positionBefore) ||\n positionBefore < 0 ||\n typeof signChanged !== 'boolean'\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid position context`,\n );\n }\n const direction = deriveLighterFillDirection({\n isBuy,\n size,\n positionBefore,\n signChanged,\n pnl: parsedPnl,\n });\n // Signed pre-trade position, derivable whenever the direction proved the\n // orientation: closing/flipping a long means it was +before, a short\n // -before; opens start from zero. Clients size flip displays from this.\n let startPosition: string | undefined;\n if (direction.startsWith('Open')) {\n startPosition = '0';\n } else if (direction === 'Close Long' || direction === 'Long > Short') {\n startPosition = String(positionBefore);\n } else if (direction === 'Close Short' || direction === 'Short > Long') {\n startPosition = String(-positionBefore);\n }\n return {\n orderId: String(accountIsAsk ? trade.askId : trade.bidId),\n symbol,\n side: accountIsAsk ? 'sell' : 'buy',\n size: trade.size,\n price: trade.price,\n // The venue reports realized pnl per side of the trade.\n pnl,\n direction,\n ...(startPosition === undefined ? {} : { startPosition }),\n fee,\n feeToken: 'USDC',\n timestamp: trade.timestamp,\n // Lets clients apply venue-specific presentation rules (e.g. the\n // ambiguous side-only vocabulary) without guessing the source.\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Position Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter account position into canonical Position.\n *\n * @param position - Position entry from an account payload.\n * @param maxLeverage - Per-market max leverage (venue margin fractions).\n * @returns MetaMask Perps API position object.\n */\nexport function adaptPositionFromLighter(\n position: LighterApiPosition,\n maxLeverage: number = LIGHTER_MAX_LEVERAGE,\n): Position {\n // Venue-input integrity boundary: the REST layer type-casts JSON without\n // runtime validation, and a prefix-parsed '0.1oops' would become a\n // canonical '0.1' that TP/SL cover-sizing and close paths then SIGN.\n // The documented representation is a NONNEGATIVE magnitude with sign\n // exactly 1 or -1: a negative magnitude with sign 1 would flip the\n // canonical direction and make close/TPSL act opposite the real\n // position; sign 0/2/'1' would be silently coerced by a > 0 ternary.\n const magnitude = parseLighterStrictDecimal(position.position);\n if (magnitude === null || !Number.isFinite(magnitude) || magnitude < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position size '${position.position}' for ${position.symbol}`,\n );\n }\n // The documented contract is sign EXACTLY 1 or -1, including for flat\n // positions (zero magnitudes are filtered downstream); anything else is\n // malformed venue data, never something to coerce.\n if (position.sign !== 1 && position.sign !== -1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position sign '${String(position.sign)}' for ${position.symbol}`,\n );\n }\n const size = magnitude * position.sign;\n const positionValue = parseFloat(position.positionValue);\n const marginFraction = parseFloat(position.initialMarginFraction);\n // initialMarginFraction is a percentage (e.g. \"20\" => 5x leverage).\n const leverageValue =\n marginFraction > 0 ? Math.round(100 / marginFraction) : 1;\n const marginUsed =\n marginFraction > 0 ? (positionValue * marginFraction) / 100 : positionValue;\n const unrealizedPnl = parseFloat(position.unrealizedPnl);\n const liquidationPrice = parseFloat(position.liquidationPrice);\n\n return {\n symbol: position.symbol,\n size: String(size),\n entryPrice: position.avgEntryPrice,\n positionValue: position.positionValue,\n unrealizedPnl: position.unrealizedPnl,\n marginUsed: String(marginUsed),\n leverage: {\n // Older venue captures omit marginMode and therefore retain the\n // historical cross default. Current payloads use 1 for isolated.\n type: position.marginMode === 1 ? 'isolated' : 'cross',\n value: leverageValue,\n },\n liquidationPrice:\n isNaN(liquidationPrice) || liquidationPrice === 0\n ? null\n : position.liquidationPrice,\n maxLeverage,\n returnOnEquity:\n marginUsed > 0 ? String((unrealizedPnl / marginUsed) * 100) : '0',\n cumulativeFunding: {\n allTime: '0',\n sinceOpen: '0',\n sinceChange: '0',\n },\n takeProfitCount: 0,\n stopLossCount: 0,\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Account Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter sub-account into canonical AccountState.\n *\n * @param account - Sub-account payload from `account`/`accountsByL1Address`.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighter(\n account: LighterSubAccount,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n account.collateral,\n 'REST collateral',\n );\n const available = parseStrictAccountDecimal(\n account.availableBalance,\n 'REST available balance',\n );\n const positions = account.positions ?? [];\n const unrealizedPnl = positions.reduce(\n (sum, position) =>\n sum +\n parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n ),\n 0,\n );\n const marginUsed = Math.max(collateral - available, 0);\n const totalBalance = collateral + unrealizedPnl;\n\n return {\n totalBalance: String(totalBalance),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n marginUsed: String(marginUsed),\n unrealizedPnl: String(unrealizedPnl),\n returnOnEquity:\n marginUsed > 0 ? String((unrealizedPnl / marginUsed) * 100) : '0',\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Order Transformation\n// ============================================================================\n\n/**\n * Map a Lighter order status string onto the canonical status union.\n *\n * @param status - Raw status from the Lighter API.\n * @returns Canonical order status.\n */\nfunction adaptOrderStatus(status: string): Order['status'] {\n switch (status) {\n case 'open':\n case 'pending':\n case 'in-progress':\n return 'open';\n case 'filled':\n return 'filled';\n case 'canceled':\n case 'cancelled':\n case 'canceled-post-only':\n case 'canceled-reduce-only':\n case 'canceled-position-not-allowed':\n case 'canceled-margin-not-allowed':\n case 'canceled-too-much-slippage':\n case 'canceled-not-enough-liquidity':\n case 'canceled-self-trade':\n case 'canceled-expired':\n case 'canceled-oco':\n case 'canceled-child':\n case 'canceled-liquidation':\n case 'canceled-invalid-balance':\n return 'canceled';\n default:\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown order status '${status}'`,\n );\n }\n}\n\n/**\n * Transform a Lighter active order into canonical Order.\n *\n * @param order - Order entry from `GET /api/v1/accountActiveOrders`.\n * @param symbol - Market symbol for the order's `marketIndex`.\n * @returns MetaMask Perps API order object.\n */\nexport function adaptOrderFromLighter(\n order: LighterApiOrder,\n symbol: string,\n): Order {\n const original = parseFloat(order.initialBaseAmount);\n const remaining = parseFloat(order.remainingBaseAmount);\n const filled = Math.max(original - remaining, 0);\n\n const isTrigger = !['market', 'limit'].includes(order.type);\n const triggerPrice =\n order.triggerPrice !== undefined && parseFloat(order.triggerPrice) > 0\n ? order.triggerPrice\n : undefined;\n // Semantic trigger typing: without it, a TP/SL renders as a generic\n // Limit order in clients. Venue trigger orders execute market-on-trigger\n // (IOC with a protection price), the -limit variants rest at a price.\n const triggerTypeMeta: Record<\n string,\n {\n orderType: 'market' | 'limit';\n triggerOrderType: TriggerOrderType;\n detailed: string;\n }\n > = {\n 'take-profit': {\n orderType: 'market',\n triggerOrderType: 'take_profit_market',\n detailed: 'Take Profit Market',\n },\n 'stop-loss': {\n orderType: 'market',\n triggerOrderType: 'stop_market',\n detailed: 'Stop Market',\n },\n 'take-profit-limit': {\n orderType: 'limit',\n triggerOrderType: 'take_profit_limit',\n detailed: 'Take Profit Limit',\n },\n 'stop-loss-limit': {\n orderType: 'limit',\n triggerOrderType: 'stop_limit',\n detailed: 'Stop Limit',\n },\n };\n const triggerMeta = triggerTypeMeta[order.type];\n\n return {\n orderId: String(order.orderIndex),\n symbol,\n side: order.isAsk ? 'sell' : 'buy',\n orderType:\n triggerMeta?.orderType ?? (order.type === 'market' ? 'market' : 'limit'),\n ...(triggerMeta\n ? {\n triggerOrderType: triggerMeta.triggerOrderType,\n detailedOrderType: triggerMeta.detailed,\n }\n : {}),\n isTrigger,\n size: order.remainingBaseAmount,\n originalSize: order.initialBaseAmount,\n // On trigger orders `price` is the ±5% protection EXECUTION price;\n // the user-facing TP/SL level is `triggerPrice`.\n price: order.price,\n ...(triggerPrice === undefined ? {} : { triggerPrice }),\n filledSize: String(filled),\n remainingSize: order.remainingBaseAmount,\n status: adaptOrderStatus(order.status),\n timestamp: order.timestamp,\n reduceOnly: Boolean(order.reduceOnly),\n providerId: 'lighter',\n };\n}\n"]}
1
+ {"version":3,"file":"lighterAdapter.js","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,qCAAqC,EACrC,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAwBvC;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,KAAa,EAAE,KAAa;IAC7D,MAAM,MAAM,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,GAAG,6BAA6B,IAAI,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,GAAG,CAC/D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,YAAY,CACnB,MAAc,EACd,UAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI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,iBAAiB;QACrC,mEAAmE;QACnE,iDAAiD;QACjD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,GAAG,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC;QACvD,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1B,aAAa,EAAE,KAAK,CAAC,mBAAmB;QACxC,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC;QACtC,0EAA0E;QAC1E,qEAAqE;QACrE,SAAS,EACP,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS;QACnE,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;QACrC,UAAU,EAAE,SAAS;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Lighter API Adapter Utilities\n *\n * Adapters transforming zkLighter REST payloads into the MetaMask Perps API\n * canonical types. Portable: no mobile-specific imports; formatters are\n * injected via the MarketDataFormatters interface.\n *\n * Key differences from HyperLiquid:\n * - Prices/sizes are human-readable decimal strings in REST responses, but\n * integers scaled by `supported_*_decimals` on the signing path.\n * - Position side is a `sign` field (1 = long, -1 = short).\n * - USDC collateral, single margin mode per account in the POC (cross).\n */\n\nimport {\n LIGHTER_DATA_INTEGRITY_PREFIX,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport type {\n AccountState,\n MarketDataFormatters,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n PriceUpdate,\n TriggerOrderType,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterApiPosition,\n LighterOrderBookDetail,\n LighterOrderBookMeta,\n LighterRestTrade,\n LighterWsTrade,\n LighterSubAccount,\n LighterWsMarketStat,\n LighterWsUserStats,\n} from '../types/lighter-types.js';\n\n/**\n * Parse an account-state number at the untrusted venue boundary. Account\n * balances feed trading availability and must never accept prefix parses or\n * propagate NaN/Infinity into canonical state.\n *\n * @param value - Raw venue decimal string.\n * @param field - Field identity for the integrity error.\n * @returns A finite, fully parsed number.\n */\nfunction parseStrictAccountDecimal(value: string, field: string): number {\n const parsed = parseLighterStrictDecimal(value);\n if (parsed === null || !Number.isFinite(parsed)) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} ${field} '${String(value)}'`,\n );\n }\n return parsed;\n}\n\n/**\n * Format a price change value with sign prefix.\n *\n * @param change - The price change value to format.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns The formatted change string with sign and dollar symbol.\n */\nfunction formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change) || change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n\n// ============================================================================\n// Market Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter order book meta entry into canonical MarketInfo.\n *\n * @param market - Market metadata from `GET /api/v1/orderBooks`.\n * @param maxLeverage - Verified per-market leverage from margin metadata.\n * @returns MetaMask Perps API market info object.\n */\nexport function adaptMarketFromLighter(\n market: LighterOrderBookMeta,\n maxLeverage: number,\n): MarketInfo {\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${market.symbol}`,\n );\n }\n return {\n name: market.symbol,\n szDecimals: market.supportedSizeDecimals,\n maxLeverage,\n marginTableId: 0, // Lighter does not use margin tables\n minimumOrderSize: parseFloat(market.minQuoteAmount),\n providerId: 'lighter',\n ...(market.status === 'active' ? {} : { isDelisted: true as const }),\n };\n}\n\n/**\n * Transform a Lighter order book detail into UI-ready PerpsMarketData.\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param formatters - Injectable formatters for platform-agnostic formatting.\n * @returns MetaMask Perps API market data object.\n */\nexport function adaptMarketDataFromLighter(\n detail: LighterOrderBookDetail,\n formatters: MarketDataFormatters,\n): PerpsMarketData {\n const { minInitialMarginFraction } = detail;\n if (\n !Number.isFinite(minInitialMarginFraction) ||\n minInitialMarginFraction === undefined ||\n minInitialMarginFraction <= 0\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} missing authoritative leverage for ${detail.symbol}`,\n );\n }\n const price = detail.lastTradePrice ?? 0;\n const changePercent = detail.dailyPriceChange ?? 0;\n // dailyPriceChange is a percentage; recover the absolute change.\n const changeAbs =\n changePercent === 0 ? 0 : (price * changePercent) / (100 + changePercent);\n\n const maxLeverage = Math.floor(10_000 / minInitialMarginFraction);\n if (!Number.isSafeInteger(maxLeverage) || maxLeverage <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} invalid authoritative leverage for ${detail.symbol}`,\n );\n }\n return {\n symbol: detail.symbol,\n name: detail.symbol,\n maxLeverage: `${maxLeverage}x`,\n price: formatters.formatPerpsFiat(price, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: formatChange(changeAbs, formatters),\n change24hPercent: `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`,\n volume: formatters.formatVolume(detail.dailyQuoteTokenVolume ?? 0),\n openInterest: formatters.formatVolume(detail.openInterest ?? 0),\n };\n}\n\n/**\n * Transform a Lighter order book detail into a canonical PriceUpdate for\n * price-stream subscribers (REST polling stands in for a WS feed in the POC).\n *\n * @param detail - Market stats from `GET /api/v1/orderBookDetails`.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighter(\n detail: LighterOrderBookDetail,\n timestamp: number,\n): PriceUpdate {\n return {\n symbol: detail.symbol,\n price: String(detail.lastTradePrice ?? 0),\n timestamp,\n percentChange24h: String(detail.dailyPriceChange ?? 0),\n volume24h: detail.dailyQuoteTokenVolume ?? 0,\n openInterest: detail.openInterest ?? 0,\n isTradable: detail.status === 'active',\n };\n}\n\n/**\n * Transform a `market_stats` WebSocket entry into a canonical PriceUpdate.\n * Richer than the REST fallback: carries mid/bid/ask, mark price, and funding.\n *\n * @param stat - Market stats entry from the `market_stats/all` WS channel.\n * @param timestamp - Update timestamp (injected for determinism in tests).\n * @returns MetaMask Perps API price update object.\n */\nexport function adaptPriceUpdateFromLighterWsStat(\n stat: LighterWsMarketStat,\n timestamp: number,\n): PriceUpdate {\n const bestBid = parseFloat(stat.bestBidPrice);\n const bestAsk = parseFloat(stat.bestAskPrice);\n const spread =\n Number.isFinite(bestBid) && Number.isFinite(bestAsk)\n ? String(bestAsk - bestBid)\n : undefined;\n return {\n symbol: stat.symbol,\n price: stat.midPrice,\n timestamp,\n percentChange24h: String(stat.dailyPriceChange ?? 0),\n bestBid: stat.bestBidPrice,\n bestAsk: stat.bestAskPrice,\n spread,\n markPrice: stat.markPrice,\n funding: parseFloat(stat.currentFundingRate ?? stat.fundingRate ?? '0'),\n openInterest: parseFloat(stat.openInterest ?? '0'),\n volume24h: stat.dailyQuoteTokenVolume ?? 0,\n isTradable: true,\n };\n}\n\n/**\n * Transform a `user_stats` WebSocket stats block into canonical AccountState.\n *\n * @param stats - Stats block from the `user_stats/{account_index}` channel.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighterUserStats(\n stats: LighterWsUserStats,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n stats.collateral,\n 'WebSocket collateral',\n );\n const available = parseStrictAccountDecimal(\n stats.availableBalance,\n 'WebSocket available balance',\n );\n const portfolioValue = parseStrictAccountDecimal(\n stats.portfolioValue,\n 'WebSocket portfolio value',\n );\n return {\n totalBalance: String(portfolioValue),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n marginUsed: String(Math.max(collateral - available, 0)),\n unrealizedPnl: String(portfolioValue - collateral),\n returnOnEquity:\n collateral > 0\n ? String(((portfolioValue - collateral) / collateral) * 100)\n : '0',\n };\n}\n\n/**\n * Transform a Lighter trade (REST `/trades` or WS `account_all_trades`) into\n * a canonical OrderFill from the perspective of `accountIndex`.\n *\n * @param trade - Trade entry (post-camelization).\n * @param symbol - Market symbol resolved from the market id.\n * @param accountIndex - The account whose perspective determines the side.\n * @returns MetaMask Perps API order fill object.\n */\n/**\n * Derive the lifecycle direction of a fill from the venue's\n * position-before context, in the vocabulary client transforms consume\n * (`Open Long`, `Close Short`, `Long > Short`, ...).\n *\n * The venue reports the side's ABSOLUTE position size before the trade and\n * whether its sign changed. Combined with the trade side that is enough:\n * buying reduces shorts and opens longs; selling reduces longs and opens\n * shorts. A partial fill with no sign change is disambiguated by realized\n * pnl (closing realizes pnl, opening does not). Without position context\n * the side-only `Buy`/`Sell` vocabulary is used.\n *\n * @param context - Trade side, size, and position-before data.\n * @param context.isBuy - Whether our side bought.\n * @param context.size - Trade size (base units, absolute).\n * @param context.positionBefore - Our side's absolute position size before.\n * @param context.signChanged - Whether our side's position sign changed.\n * @param context.pnl - Realized pnl for our side.\n * @returns Client-facing direction string.\n */\nexport function deriveLighterFillDirection(context: {\n isBuy: boolean;\n size: number;\n positionBefore: number;\n signChanged: boolean | undefined;\n pnl: number;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore) || signChanged === undefined) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n if (signChanged) {\n // Crossed past zero → flipped; landed exactly on zero → full close.\n if (size > positionBefore * 1.000001) {\n return isBuy ? 'Short > Long' : 'Long > Short';\n }\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Partial fill on an existing position: realized pnl proves it reduced.\n if (pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero-pnl partial with no sign change is genuinely ambiguous from this\n // payload (a break-even partial close and an add both fit): fall back to\n // the side-only vocabulary instead of asserting Open without evidence.\n return isBuy ? 'Buy' : 'Sell';\n}\n\n/**\n * Parse one optional venue fee without treating malformed supplied values as\n * an omitted zero.\n *\n * @param value - Raw maker or taker fee.\n * @param tradeId - Trade identity for error context.\n * @param role - Fee role for error context.\n * @returns The finite nonnegative fee, with undefined mapped to venue-zero.\n */\nfunction parseLighterTradeFee(\n value: unknown,\n tradeId: number,\n role: 'maker' | 'taker',\n): number {\n let parsed: number | null;\n if (value === undefined) {\n parsed = 0;\n } else if (typeof value === 'number') {\n parsed = value;\n } else if (typeof value === 'string') {\n parsed = parseLighterStrictDecimal(value);\n } else {\n parsed = null;\n }\n if (parsed === null || !Number.isFinite(parsed) || parsed < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${tradeId} has invalid ${role} fee`,\n );\n }\n return parsed;\n}\n\nexport function adaptFillFromLighterTrade(\n trade: LighterRestTrade | LighterWsTrade,\n symbol: string,\n accountIndex: number,\n): OrderFill {\n const identifiers = [\n ['trade id', trade.tradeId],\n ['market id', trade.marketId],\n ['ask id', trade.askId],\n ['bid id', trade.bidId],\n ['ask account id', trade.askAccountId],\n ['bid account id', trade.bidAccountId],\n ] as const;\n for (const [field, value] of identifiers) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${String(trade.tradeId)} has invalid ${field}`,\n );\n }\n }\n const accountIsAsk = trade.askAccountId === accountIndex;\n const accountIsBid = trade.bidAccountId === accountIndex;\n if (accountIsAsk === accountIsBid) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} account ${accountIndex} is not an unambiguous participant in trade ${trade.tradeId}`,\n );\n }\n const size = parseLighterStrictDecimal(trade.size);\n const price = parseLighterStrictDecimal(trade.price);\n if (size === null || !Number.isFinite(size) || size <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid size`,\n );\n }\n if (price === null || !Number.isFinite(price) || price <= 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid price`,\n );\n }\n if (!Number.isSafeInteger(trade.timestamp) || trade.timestamp < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} has invalid timestamp`,\n );\n }\n if (typeof trade.isMakerAsk !== 'boolean') {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing maker-role context`,\n );\n }\n // Our side's role decides which fee applies; the venue includes the fee\n // fields only when nonzero (zero is the current standard-account truth).\n const accountIsMaker = accountIsAsk === trade.isMakerAsk;\n // Standard accounts (the only supported type — the provider gates\n // Premium at account resolution) pay zero fees, so zero is venue truth.\n // A PRESENT nonzero fee ON OUR SIDE contradicts that gate and its wire\n // unit is unverified: refusing loudly beats silently coercing a real fee\n // to $0. A valid nonzero counterparty fee is allowed, but malformed\n // supplied counterparty data still invalidates the venue row.\n const makerFee = parseLighterTradeFee(trade.makerFee, trade.tradeId, 'maker');\n const takerFee = parseLighterTradeFee(trade.takerFee, trade.tradeId, 'taker');\n const ourFeeNumeric = accountIsMaker ? makerFee : takerFee;\n if (ourFeeNumeric !== 0) {\n throw new Error(\n `${LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX} nonzero fee in trade ${trade.tradeId}: fee unit is unverified`,\n );\n }\n const fee = '0';\n const isBuy = !accountIsAsk;\n // The account's maker/taker role selects the matching pre-trade position\n // context. Missing context is rejected above instead of becoming neutral\n // history that looks authoritative.\n const positionBeforeRaw = accountIsMaker\n ? trade.makerPositionSizeBefore\n : trade.takerPositionSizeBefore;\n const positionBefore = parseLighterStrictDecimal(positionBeforeRaw);\n const signChanged = accountIsMaker\n ? trade.makerPositionSignChanged\n : trade.takerPositionSignChanged;\n if (\n positionBefore === null ||\n !Number.isFinite(positionBefore) ||\n positionBefore < 0 ||\n typeof signChanged !== 'boolean'\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid position context`,\n );\n }\n const accountPnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n // The venue omits PnL on opens from flat. Only a validated zero pre-trade\n // position proves zero realized PnL; never assume it for an existing position.\n const pnl =\n accountPnl === undefined && positionBefore === 0 ? '0' : accountPnl;\n const parsedPnl = parseLighterStrictDecimal(pnl);\n if (\n typeof pnl !== 'string' ||\n parsedPnl === null ||\n !Number.isFinite(parsedPnl)\n ) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} trade ${trade.tradeId} is missing valid account pnl`,\n );\n }\n const direction = deriveLighterFillDirection({\n isBuy,\n size,\n positionBefore,\n signChanged,\n pnl: parsedPnl,\n });\n // Signed pre-trade position, derivable whenever the direction proved the\n // orientation: closing/flipping a long means it was +before, a short\n // -before; opens start from zero. Clients size flip displays from this.\n let startPosition: string | undefined;\n if (direction.startsWith('Open')) {\n startPosition = '0';\n } else if (direction === 'Close Long' || direction === 'Long > Short') {\n startPosition = String(positionBefore);\n } else if (direction === 'Close Short' || direction === 'Short > Long') {\n startPosition = String(-positionBefore);\n }\n return {\n orderId: String(accountIsAsk ? trade.askId : trade.bidId),\n symbol,\n side: accountIsAsk ? 'sell' : 'buy',\n size: trade.size,\n price: trade.price,\n // The venue reports realized pnl per side of the trade.\n pnl,\n direction,\n ...(startPosition === undefined ? {} : { startPosition }),\n fee,\n feeToken: 'USDC',\n timestamp: trade.timestamp,\n // Lets clients apply venue-specific presentation rules (e.g. the\n // ambiguous side-only vocabulary) without guessing the source.\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Position Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter account position into canonical Position.\n *\n * @param position - Position entry from an account payload.\n * @param maxLeverage - Per-market max leverage (venue margin fractions).\n * @returns MetaMask Perps API position object.\n */\nexport function adaptPositionFromLighter(\n position: LighterApiPosition,\n maxLeverage: number = LIGHTER_MAX_LEVERAGE,\n): Position {\n // Venue-input integrity boundary: the REST layer type-casts JSON without\n // runtime validation, and a prefix-parsed '0.1oops' would become a\n // canonical '0.1' that TP/SL cover-sizing and close paths then SIGN.\n // The documented representation is a NONNEGATIVE magnitude with sign\n // exactly 1 or -1: a negative magnitude with sign 1 would flip the\n // canonical direction and make close/TPSL act opposite the real\n // position; sign 0/2/'1' would be silently coerced by a > 0 ternary.\n const magnitude = parseLighterStrictDecimal(position.position);\n if (magnitude === null || !Number.isFinite(magnitude) || magnitude < 0) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position size '${position.position}' for ${position.symbol}`,\n );\n }\n // The documented contract is sign EXACTLY 1 or -1, including for flat\n // positions (zero magnitudes are filtered downstream); anything else is\n // malformed venue data, never something to coerce.\n if (position.sign !== 1 && position.sign !== -1) {\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} position sign '${String(position.sign)}' for ${position.symbol}`,\n );\n }\n const size = magnitude * position.sign;\n const positionValue = parseFloat(position.positionValue);\n const marginFraction = parseFloat(position.initialMarginFraction);\n // initialMarginFraction is a percentage (e.g. \"20\" => 5x leverage).\n const leverageValue =\n marginFraction > 0 ? Math.round(100 / marginFraction) : 1;\n const marginUsed =\n marginFraction > 0 ? (positionValue * marginFraction) / 100 : positionValue;\n const unrealizedPnl = parseFloat(position.unrealizedPnl);\n const liquidationPrice = parseFloat(position.liquidationPrice);\n\n return {\n symbol: position.symbol,\n size: String(size),\n entryPrice: position.avgEntryPrice,\n positionValue: position.positionValue,\n unrealizedPnl: position.unrealizedPnl,\n marginUsed: String(marginUsed),\n leverage: {\n // Older venue captures omit marginMode and therefore retain the\n // historical cross default. Current payloads use 1 for isolated.\n type: position.marginMode === 1 ? 'isolated' : 'cross',\n value: leverageValue,\n },\n liquidationPrice:\n isNaN(liquidationPrice) || liquidationPrice === 0\n ? null\n : position.liquidationPrice,\n maxLeverage,\n returnOnEquity:\n marginUsed > 0 ? String((unrealizedPnl / marginUsed) * 100) : '0',\n cumulativeFunding: {\n allTime: '0',\n sinceOpen: '0',\n sinceChange: '0',\n },\n takeProfitCount: 0,\n stopLossCount: 0,\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Account Transformation\n// ============================================================================\n\n/**\n * Transform a Lighter sub-account into canonical AccountState.\n *\n * @param account - Sub-account payload from `account`/`accountsByL1Address`.\n * @returns MetaMask Perps API account state object.\n */\nexport function adaptAccountStateFromLighter(\n account: LighterSubAccount,\n): AccountState {\n const collateral = parseStrictAccountDecimal(\n account.collateral,\n 'REST collateral',\n );\n const available = parseStrictAccountDecimal(\n account.availableBalance,\n 'REST available balance',\n );\n const positions = account.positions ?? [];\n const unrealizedPnl = positions.reduce(\n (sum, position) =>\n sum +\n parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n ),\n 0,\n );\n const marginUsed = Math.max(collateral - available, 0);\n const totalBalance = collateral + unrealizedPnl;\n\n return {\n totalBalance: String(totalBalance),\n spendableBalance: String(available),\n withdrawableBalance: String(available),\n marginUsed: String(marginUsed),\n unrealizedPnl: String(unrealizedPnl),\n returnOnEquity:\n marginUsed > 0 ? String((unrealizedPnl / marginUsed) * 100) : '0',\n providerId: 'lighter',\n };\n}\n\n// ============================================================================\n// Order Transformation\n// ============================================================================\n\n/**\n * Map a Lighter order status string onto the canonical status union.\n *\n * @param status - Raw status from the Lighter API.\n * @returns Canonical order status.\n */\nfunction adaptOrderStatus(status: string): Order['status'] {\n switch (status) {\n case 'open':\n case 'pending':\n case 'in-progress':\n return 'open';\n case 'filled':\n return 'filled';\n case 'canceled':\n case 'cancelled':\n case 'canceled-post-only':\n case 'canceled-reduce-only':\n case 'canceled-position-not-allowed':\n case 'canceled-margin-not-allowed':\n case 'canceled-too-much-slippage':\n case 'canceled-not-enough-liquidity':\n case 'canceled-self-trade':\n case 'canceled-expired':\n case 'canceled-oco':\n case 'canceled-child':\n case 'canceled-liquidation':\n case 'canceled-invalid-balance':\n return 'canceled';\n default:\n throw new Error(\n `${LIGHTER_DATA_INTEGRITY_PREFIX} unknown order status '${status}'`,\n );\n }\n}\n\n/**\n * Transform a Lighter active order into canonical Order.\n *\n * @param order - Order entry from `GET /api/v1/accountActiveOrders`.\n * @param symbol - Market symbol for the order's `marketIndex`.\n * @returns MetaMask Perps API order object.\n */\nexport function adaptOrderFromLighter(\n order: LighterApiOrder,\n symbol: string,\n): Order {\n const original = parseFloat(order.initialBaseAmount);\n const remaining = parseFloat(order.remainingBaseAmount);\n const filled = Math.max(original - remaining, 0);\n\n const isTrigger = !['market', 'limit'].includes(order.type);\n const triggerPrice =\n order.triggerPrice !== undefined && parseFloat(order.triggerPrice) > 0\n ? order.triggerPrice\n : undefined;\n // Semantic trigger typing: without it, a TP/SL renders as a generic\n // Limit order in clients. Venue trigger orders execute market-on-trigger\n // (IOC with a protection price), the -limit variants rest at a price.\n const triggerTypeMeta: Record<\n string,\n {\n orderType: 'market' | 'limit';\n triggerOrderType: TriggerOrderType;\n detailed: string;\n }\n > = {\n 'take-profit': {\n orderType: 'market',\n triggerOrderType: 'take_profit_market',\n detailed: 'Take Profit Market',\n },\n 'stop-loss': {\n orderType: 'market',\n triggerOrderType: 'stop_market',\n detailed: 'Stop Market',\n },\n 'take-profit-limit': {\n orderType: 'limit',\n triggerOrderType: 'take_profit_limit',\n detailed: 'Take Profit Limit',\n },\n 'stop-loss-limit': {\n orderType: 'limit',\n triggerOrderType: 'stop_limit',\n detailed: 'Stop Limit',\n },\n };\n const triggerMeta = triggerTypeMeta[order.type];\n\n return {\n orderId: String(order.orderIndex),\n symbol,\n side: order.isAsk ? 'sell' : 'buy',\n orderType:\n triggerMeta?.orderType ?? (order.type === 'market' ? 'market' : 'limit'),\n ...(triggerMeta\n ? {\n triggerOrderType: triggerMeta.triggerOrderType,\n detailedOrderType: triggerMeta.detailed,\n }\n : {}),\n isTrigger,\n size: order.remainingBaseAmount,\n originalSize: order.initialBaseAmount,\n // On trigger orders `price` is the ±5% protection EXECUTION price;\n // the user-facing TP/SL level is `triggerPrice`.\n price: order.price,\n ...(triggerPrice === undefined ? {} : { triggerPrice }),\n filledSize: String(filled),\n remainingSize: order.remainingBaseAmount,\n status: adaptOrderStatus(order.status),\n // Order endpoints report seconds; preserve already-normalized millisecond\n // inputs. Trade timestamps are a separate millisecond wire contract.\n timestamp:\n order.timestamp < 1e12 ? order.timestamp * 1000 : order.timestamp,\n reduceOnly: Boolean(order.reduceOnly),\n providerId: 'lighter',\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/perps-controller",
3
- "version": "17.1.0-preview-d27fd1d8f",
3
+ "version": "17.1.0-preview-7aac301dc",
4
4
  "description": "Controller for perpetual trading functionality in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -87,7 +87,7 @@
87
87
  "@metamask/network-controller": "^37.0.0",
88
88
  "@metamask/profile-sync-controller": "^32.1.1",
89
89
  "@metamask/remote-feature-flag-controller": "^7.0.0",
90
- "@metamask/transaction-controller": "^70.0.1",
90
+ "@metamask/transaction-controller": "^70.1.0",
91
91
  "@types/jest": "^30.0.0",
92
92
  "@typescript/native": "npm:typescript@^7.0.2",
93
93
  "deepmerge": "^4.2.2",