@metamask-previews/perps-controller 23.1.0-preview-d0ecc4dd6 → 23.1.0-preview-fe3c580ff

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +35 -0
  3. package/dist/PerpsController-method-action-types.d.ts +96 -7
  4. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -1
  6. package/dist/PerpsController.d.ts +131 -52
  7. package/dist/PerpsController.d.ts.map +1 -1
  8. package/dist/PerpsController.js +854 -54
  9. package/dist/PerpsController.js.map +1 -1
  10. package/dist/constants/lighterConfig.d.ts +4 -0
  11. package/dist/constants/lighterConfig.d.ts.map +1 -1
  12. package/dist/constants/lighterConfig.js +4 -0
  13. package/dist/constants/lighterConfig.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/perpsErrorCodes.d.ts +1 -0
  18. package/dist/perpsErrorCodes.d.ts.map +1 -1
  19. package/dist/perpsErrorCodes.js +2 -0
  20. package/dist/perpsErrorCodes.js.map +1 -1
  21. package/dist/providers/AggregatedPerpsProvider.d.ts +31 -1
  22. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  23. package/dist/providers/AggregatedPerpsProvider.js +250 -38
  24. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  25. package/dist/providers/HyperLiquidProvider.d.ts +20 -1
  26. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  27. package/dist/providers/HyperLiquidProvider.js +227 -67
  28. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  29. package/dist/providers/LighterProvider.d.ts +3 -1
  30. package/dist/providers/LighterProvider.d.ts.map +1 -1
  31. package/dist/providers/LighterProvider.js +100 -2
  32. package/dist/providers/LighterProvider.js.map +1 -1
  33. package/dist/routing/isPerpsProviderType.d.ts +10 -0
  34. package/dist/routing/isPerpsProviderType.d.ts.map +1 -0
  35. package/dist/routing/isPerpsProviderType.js +11 -0
  36. package/dist/routing/isPerpsProviderType.js.map +1 -0
  37. package/dist/routing/resolveTradeConfigProviderKey.d.ts +22 -0
  38. package/dist/routing/resolveTradeConfigProviderKey.d.ts.map +1 -0
  39. package/dist/routing/resolveTradeConfigProviderKey.js +25 -0
  40. package/dist/routing/resolveTradeConfigProviderKey.js.map +1 -0
  41. package/dist/selectors.d.ts +35 -233
  42. package/dist/selectors.d.ts.map +1 -1
  43. package/dist/selectors.js +36 -13
  44. package/dist/selectors.js.map +1 -1
  45. package/dist/services/HyperLiquidClientService.d.ts +26 -0
  46. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  47. package/dist/services/HyperLiquidClientService.js +73 -0
  48. package/dist/services/HyperLiquidClientService.js.map +1 -1
  49. package/dist/services/LighterClientService.d.ts +9 -1
  50. package/dist/services/LighterClientService.d.ts.map +1 -1
  51. package/dist/services/LighterClientService.js +32 -1
  52. package/dist/services/LighterClientService.js.map +1 -1
  53. package/dist/services/MarketDataService.d.ts.map +1 -1
  54. package/dist/services/MarketDataService.js +12 -6
  55. package/dist/services/MarketDataService.js.map +1 -1
  56. package/dist/services/ServiceContext.d.ts +15 -3
  57. package/dist/services/ServiceContext.d.ts.map +1 -1
  58. package/dist/services/ServiceContext.js.map +1 -1
  59. package/dist/services/TradingService.d.ts +3 -1
  60. package/dist/services/TradingService.d.ts.map +1 -1
  61. package/dist/services/TradingService.js +9 -4
  62. package/dist/services/TradingService.js.map +1 -1
  63. package/dist/types/hyperliquid-types.d.ts +2 -1
  64. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  65. package/dist/types/hyperliquid-types.js.map +1 -1
  66. package/dist/types/index.d.ts +125 -2
  67. package/dist/types/index.d.ts.map +1 -1
  68. package/dist/types/index.js.map +1 -1
  69. package/dist/types/lighter-types.d.ts +31 -0
  70. package/dist/types/lighter-types.d.ts.map +1 -1
  71. package/dist/types/lighter-types.js.map +1 -1
  72. package/dist/utils/hyperLiquidAdapter.d.ts +14 -2
  73. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  74. package/dist/utils/hyperLiquidAdapter.js +41 -0
  75. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  76. package/dist/utils/lighterAdapter.d.ts +13 -1
  77. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  78. package/dist/utils/lighterAdapter.js +47 -0
  79. package/dist/utils/lighterAdapter.js.map +1 -1
  80. package/dist/utils/publicTrades.d.ts +30 -0
  81. package/dist/utils/publicTrades.d.ts.map +1 -0
  82. package/dist/utils/publicTrades.js +45 -0
  83. package/dist/utils/publicTrades.js.map +1 -0
  84. package/package.json +1 -1
@@ -12,6 +12,7 @@
12
12
  * - USDC collateral, single margin mode per account in the POC (cross).
13
13
  */
14
14
  import { LIGHTER_DATA_INTEGRITY_PREFIX, LIGHTER_MARGIN_MODE_ISOLATED, LIGHTER_MAX_LEVERAGE, LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX, parseLighterStrictDecimal, } from '../constants/lighterConfig.js';
15
+ import { buildPublicTrade, sortPublicTradesNewestFirst, } from './publicTrades.js';
15
16
  /**
16
17
  * Parse an account-state number at the untrusted venue boundary. Account
17
18
  * balances feed trading availability and must never accept prefix parses or
@@ -261,6 +262,52 @@ function parseLighterTradeFee(value, tradeId, role) {
261
262
  }
262
263
  return parsed;
263
264
  }
265
+ /**
266
+ * Adapt Lighter public trades (REST `recentTrades` or the `trade/{market_id}`
267
+ * channel, camelized) to {@link PublicTrade}, newest first. Trades for
268
+ * another market and malformed trades are dropped. A maker ask means the
269
+ * taker (aggressor) bought.
270
+ *
271
+ * @param trades - Camelized venue trades.
272
+ * @param marketId - Requested market; other markets are dropped.
273
+ * @param symbol - Symbol to stamp on each trade.
274
+ * @returns The trades for the market, newest first.
275
+ */
276
+ export function adaptPublicTradesFromLighter(trades, marketId, symbol) {
277
+ const adapted = [];
278
+ for (const raw of trades) {
279
+ if (raw === null || typeof raw !== 'object') {
280
+ continue;
281
+ }
282
+ const trade = raw;
283
+ if (trade.marketId !== marketId || typeof trade.isMakerAsk !== 'boolean') {
284
+ continue;
285
+ }
286
+ let id;
287
+ if (typeof trade.tradeIdStr === 'string') {
288
+ id = trade.tradeIdStr;
289
+ }
290
+ else if (typeof trade.tradeId === 'number' &&
291
+ Number.isSafeInteger(trade.tradeId) &&
292
+ trade.tradeId >= 0) {
293
+ id = String(trade.tradeId);
294
+ }
295
+ const publicTrade = buildPublicTrade({
296
+ id,
297
+ symbol,
298
+ price: trade.price,
299
+ size: trade.size,
300
+ side: trade.isMakerAsk ? 'buy' : 'sell',
301
+ timestamp: trade.timestamp,
302
+ txHash: typeof trade.txHash === 'string' ? trade.txHash : undefined,
303
+ providerId: 'lighter',
304
+ });
305
+ if (publicTrade) {
306
+ adapted.push(publicTrade);
307
+ }
308
+ }
309
+ return sortPublicTradesNewestFirst(adapted);
310
+ }
264
311
  export function adaptFillFromLighterTrade(trade, symbol, accountIndex) {
265
312
  const identifiers = [
266
313
  ['trade id', trade.tradeId],
@@ -1 +1 @@
1
- {"version":3,"file":"lighterAdapter.js","sourceRoot":"","sources":["../../src/utils/lighterAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,qCAAqC,EACrC,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAyBvC;;;;;;;;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/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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,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_MARGIN_MODE_ISOLATED,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport type {\n AccountState,\n CrossMarginSummary,\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 priceDecimals: market.supportedPriceDecimals,\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, or undefined when omitted.\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 | undefined;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n // A flat baseline proves an open. On an existing position, nonzero\n // realized PnL proves reduction; otherwise an omitted flag is ambiguous.\n if (signChanged === undefined && (pnl === undefined || pnl === 0)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (\n signChanged ||\n (signChanged === undefined && pnl !== undefined && pnl !== 0)\n ) {\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 !== undefined && pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero or unknown pnl with no sign change is 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. Omitted sign-change flags retain an unknown direction for\n // existing positions; malformed supplied context still fails closed.\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 (signChanged !== undefined && 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 pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n // Omitted amounts remain unknown, including closes and flips. Position\n // context can establish direction without establishing the realized amount.\n const parsedPnl =\n pnl === undefined ? undefined : parseLighterStrictDecimal(pnl);\n if (\n parsedPnl === null ||\n (pnl !== undefined &&\n (typeof pnl !== 'string' || !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 // Lighter's unique execution id, validated as a safe non-negative\n // integer above. Order id alone cannot separate two fills of one order.\n fillId: String(trade.tradeId),\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 === undefined ? {} : { 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 * Margin a Lighter position uses: its value times the initial margin\n * fraction, a percentage (e.g. \"20\" => 5x leverage).\n *\n * @param positionValue - Position value in USDC.\n * @param initialMarginFraction - Initial margin fraction, in percent.\n * @returns Margin used in USDC; the full value when no fraction is set.\n */\nfunction deriveLighterPositionMarginUsed(\n positionValue: number,\n initialMarginFraction: number,\n): number {\n return initialMarginFraction > 0\n ? (positionValue * initialMarginFraction) / 100\n : positionValue;\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 = deriveLighterPositionMarginUsed(\n positionValue,\n marginFraction,\n );\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 // A fraction (0.1 = 10%), the unit Hyperliquid positions use.\n returnOnEquity: marginUsed > 0 ? String(unrealizedPnl / marginUsed) : '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 * Build the cross-margin summary from a Lighter sub-account's positions.\n *\n * Open cross positions contribute their value to notional, their margin to\n * margin used and value times the market's maintenance fraction to\n * maintenance margin. Account value is the total balance less isolated\n * positions' unrealized PnL.\n *\n * @param account - Sub-account payload from `account`.\n * @param totalBalance - The account's adapted total balance.\n * @param getMaintenanceFraction - Maintenance margin fraction (0.024 = 2.4%)\n * for a market symbol, or undefined when the market has none.\n * @returns The cross-margin summary, or undefined when the payload omits\n * positions or an open cross position's market has no maintenance fraction.\n */\nexport function adaptCrossMarginSummaryFromLighter(\n account: LighterSubAccount,\n totalBalance: string,\n getMaintenanceFraction: (symbol: string) => number | undefined,\n): CrossMarginSummary | undefined {\n // Omitted positions are not evidence of zero exposure.\n if (!account.positions) {\n return undefined;\n }\n let isolatedUnrealizedPnl = 0;\n let notional = 0;\n let marginUsed = 0;\n let maintenanceMargin = 0;\n for (const position of account.positions) {\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n if (position.marginMode === LIGHTER_MARGIN_MODE_ISOLATED) {\n isolatedUnrealizedPnl += unrealizedPnl;\n continue;\n }\n const size = parseStrictAccountDecimal(\n position.position,\n `REST position size for ${position.symbol}`,\n );\n if (size === 0) {\n continue;\n }\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n const initialMarginFraction = parseStrictAccountDecimal(\n position.initialMarginFraction,\n `REST initial margin fraction for ${position.symbol}`,\n );\n const maintenanceFraction = getMaintenanceFraction(position.symbol);\n if (maintenanceFraction === undefined) {\n return undefined;\n }\n notional += positionValue;\n marginUsed += deriveLighterPositionMarginUsed(\n positionValue,\n initialMarginFraction,\n );\n maintenanceMargin += positionValue * maintenanceFraction;\n }\n return {\n accountValue: String(\n parseStrictAccountDecimal(totalBalance, 'total balance') -\n isolatedUnrealizedPnl,\n ),\n maintenanceMargin: String(maintenanceMargin),\n marginUsed: String(marginUsed),\n notional: String(notional),\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 */\nexport function 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 // Canceled orders have zero remaining size even when nothing filled.\n const filled =\n order.filledBaseAmount === undefined\n ? Math.max(original - remaining, 0)\n : parseFloat(order.filledBaseAmount);\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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AC,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_MARGIN_MODE_ISOLATED,\n LIGHTER_MAX_LEVERAGE,\n LIGHTER_UNSUPPORTED_CAPABILITY_PREFIX,\n parseLighterStrictDecimal,\n} from '../constants/lighterConfig.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketDataFormatters,\n MarketInfo,\n Order,\n OrderFill,\n PerpsMarketData,\n Position,\n PriceUpdate,\n PublicTrade,\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';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.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 priceDecimals: market.supportedPriceDecimals,\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, or undefined when omitted.\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 | undefined;\n}): string {\n const { isBuy, size, positionBefore, signChanged, pnl } = context;\n if (!Number.isFinite(positionBefore)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (positionBefore === 0) {\n return isBuy ? 'Open Long' : 'Open Short';\n }\n // A flat baseline proves an open. On an existing position, nonzero\n // realized PnL proves reduction; otherwise an omitted flag is ambiguous.\n if (signChanged === undefined && (pnl === undefined || pnl === 0)) {\n return isBuy ? 'Buy' : 'Sell';\n }\n if (\n signChanged ||\n (signChanged === undefined && pnl !== undefined && pnl !== 0)\n ) {\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 !== undefined && pnl !== 0) {\n return isBuy ? 'Close Short' : 'Close Long';\n }\n // Zero or unknown pnl with no sign change is 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\n/**\n * Adapt Lighter public trades (REST `recentTrades` or the `trade/{market_id}`\n * channel, camelized) to {@link PublicTrade}, newest first. Trades for\n * another market and malformed trades are dropped. A maker ask means the\n * taker (aggressor) bought.\n *\n * @param trades - Camelized venue trades.\n * @param marketId - Requested market; other markets are dropped.\n * @param symbol - Symbol to stamp on each trade.\n * @returns The trades for the market, newest first.\n */\nexport function adaptPublicTradesFromLighter(\n trades: readonly unknown[],\n marketId: number,\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const raw of trades) {\n if (raw === null || typeof raw !== 'object') {\n continue;\n }\n const trade = raw as Partial<Record<string, unknown>>;\n if (trade.marketId !== marketId || typeof trade.isMakerAsk !== 'boolean') {\n continue;\n }\n let id: string | undefined;\n if (typeof trade.tradeIdStr === 'string') {\n id = trade.tradeIdStr;\n } else if (\n typeof trade.tradeId === 'number' &&\n Number.isSafeInteger(trade.tradeId) &&\n trade.tradeId >= 0\n ) {\n id = String(trade.tradeId);\n }\n const publicTrade = buildPublicTrade({\n id,\n symbol,\n price: trade.price,\n size: trade.size,\n side: trade.isMakerAsk ? 'buy' : 'sell',\n timestamp: trade.timestamp,\n txHash: typeof trade.txHash === 'string' ? trade.txHash : undefined,\n providerId: 'lighter',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\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. Omitted sign-change flags retain an unknown direction for\n // existing positions; malformed supplied context still fails closed.\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 (signChanged !== undefined && 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 pnl = accountIsAsk ? trade.askAccountPnl : trade.bidAccountPnl;\n // Omitted amounts remain unknown, including closes and flips. Position\n // context can establish direction without establishing the realized amount.\n const parsedPnl =\n pnl === undefined ? undefined : parseLighterStrictDecimal(pnl);\n if (\n parsedPnl === null ||\n (pnl !== undefined &&\n (typeof pnl !== 'string' || !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 // Lighter's unique execution id, validated as a safe non-negative\n // integer above. Order id alone cannot separate two fills of one order.\n fillId: String(trade.tradeId),\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 === undefined ? {} : { 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 * Margin a Lighter position uses: its value times the initial margin\n * fraction, a percentage (e.g. \"20\" => 5x leverage).\n *\n * @param positionValue - Position value in USDC.\n * @param initialMarginFraction - Initial margin fraction, in percent.\n * @returns Margin used in USDC; the full value when no fraction is set.\n */\nfunction deriveLighterPositionMarginUsed(\n positionValue: number,\n initialMarginFraction: number,\n): number {\n return initialMarginFraction > 0\n ? (positionValue * initialMarginFraction) / 100\n : positionValue;\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 = deriveLighterPositionMarginUsed(\n positionValue,\n marginFraction,\n );\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 // A fraction (0.1 = 10%), the unit Hyperliquid positions use.\n returnOnEquity: marginUsed > 0 ? String(unrealizedPnl / marginUsed) : '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 * Build the cross-margin summary from a Lighter sub-account's positions.\n *\n * Open cross positions contribute their value to notional, their margin to\n * margin used and value times the market's maintenance fraction to\n * maintenance margin. Account value is the total balance less isolated\n * positions' unrealized PnL.\n *\n * @param account - Sub-account payload from `account`.\n * @param totalBalance - The account's adapted total balance.\n * @param getMaintenanceFraction - Maintenance margin fraction (0.024 = 2.4%)\n * for a market symbol, or undefined when the market has none.\n * @returns The cross-margin summary, or undefined when the payload omits\n * positions or an open cross position's market has no maintenance fraction.\n */\nexport function adaptCrossMarginSummaryFromLighter(\n account: LighterSubAccount,\n totalBalance: string,\n getMaintenanceFraction: (symbol: string) => number | undefined,\n): CrossMarginSummary | undefined {\n // Omitted positions are not evidence of zero exposure.\n if (!account.positions) {\n return undefined;\n }\n let isolatedUnrealizedPnl = 0;\n let notional = 0;\n let marginUsed = 0;\n let maintenanceMargin = 0;\n for (const position of account.positions) {\n const unrealizedPnl = parseStrictAccountDecimal(\n position.unrealizedPnl,\n `REST unrealized PnL for ${position.symbol}`,\n );\n if (position.marginMode === LIGHTER_MARGIN_MODE_ISOLATED) {\n isolatedUnrealizedPnl += unrealizedPnl;\n continue;\n }\n const size = parseStrictAccountDecimal(\n position.position,\n `REST position size for ${position.symbol}`,\n );\n if (size === 0) {\n continue;\n }\n const positionValue = parseStrictAccountDecimal(\n position.positionValue,\n `REST position value for ${position.symbol}`,\n );\n const initialMarginFraction = parseStrictAccountDecimal(\n position.initialMarginFraction,\n `REST initial margin fraction for ${position.symbol}`,\n );\n const maintenanceFraction = getMaintenanceFraction(position.symbol);\n if (maintenanceFraction === undefined) {\n return undefined;\n }\n notional += positionValue;\n marginUsed += deriveLighterPositionMarginUsed(\n positionValue,\n initialMarginFraction,\n );\n maintenanceMargin += positionValue * maintenanceFraction;\n }\n return {\n accountValue: String(\n parseStrictAccountDecimal(totalBalance, 'total balance') -\n isolatedUnrealizedPnl,\n ),\n maintenanceMargin: String(maintenanceMargin),\n marginUsed: String(marginUsed),\n notional: String(notional),\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 */\nexport function 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 // Canceled orders have zero remaining size even when nothing filled.\n const filled =\n order.filledBaseAmount === undefined\n ? Math.max(original - remaining, 0)\n : parseFloat(order.filledBaseAmount);\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"]}
@@ -0,0 +1,30 @@
1
+ import type { PerpsProviderType, PublicTrade } from '../types/index.js';
2
+ /**
3
+ * Venue fields of one public trade, before validation.
4
+ */
5
+ export type PublicTradeFields = {
6
+ id: unknown;
7
+ symbol: string;
8
+ price: unknown;
9
+ size: unknown;
10
+ side: PublicTrade['side'] | null;
11
+ timestamp: unknown;
12
+ txHash?: string;
13
+ providerId: PerpsProviderType;
14
+ };
15
+ /**
16
+ * Build a {@link PublicTrade} from venue fields, or null when a field is
17
+ * malformed. Public feeds skip a malformed trade instead of failing the batch.
18
+ *
19
+ * @param fields - Venue fields mapped to the shared names.
20
+ * @returns The trade, or null.
21
+ */
22
+ export declare function buildPublicTrade(fields: PublicTradeFields): PublicTrade | null;
23
+ /**
24
+ * Order trades newest first, the order every provider returns.
25
+ *
26
+ * @param trades - Trades to sort (not mutated).
27
+ * @returns A new array, newest first.
28
+ */
29
+ export declare function sortPublicTradesNewestFirst(trades: readonly PublicTrade[]): PublicTrade[];
30
+ //# sourceMappingURL=publicTrades.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicTrades.d.ts","sourceRoot":"","sources":["../../src/utils/publicTrades.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGxE;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,EAAE,EAAE,OAAO,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IACjC,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,iBAAiB,CAAC;CAC/B,CAAC;AAOF;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,iBAAiB,GACxB,WAAW,GAAG,IAAI,CAyBpB;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,SAAS,WAAW,EAAE,GAC7B,WAAW,EAAE,CAEf"}
@@ -0,0 +1,45 @@
1
+ import { parseFiniteDecimal } from './stringParseUtils.js';
2
+ const isPositiveDecimal = (value) => {
3
+ const parsed = parseFiniteDecimal(value);
4
+ return parsed !== null && parsed > 0;
5
+ };
6
+ /**
7
+ * Build a {@link PublicTrade} from venue fields, or null when a field is
8
+ * malformed. Public feeds skip a malformed trade instead of failing the batch.
9
+ *
10
+ * @param fields - Venue fields mapped to the shared names.
11
+ * @returns The trade, or null.
12
+ */
13
+ export function buildPublicTrade(fields) {
14
+ const { id, symbol, price, size, side, timestamp, txHash, providerId } = fields;
15
+ if (typeof id !== 'string' ||
16
+ id.length === 0 ||
17
+ !isPositiveDecimal(price) ||
18
+ !isPositiveDecimal(size) ||
19
+ side === null ||
20
+ typeof timestamp !== 'number' ||
21
+ !Number.isSafeInteger(timestamp) ||
22
+ timestamp <= 0) {
23
+ return null;
24
+ }
25
+ return {
26
+ id,
27
+ symbol,
28
+ price,
29
+ size,
30
+ side,
31
+ timestamp,
32
+ ...(txHash ? { txHash } : {}),
33
+ providerId,
34
+ };
35
+ }
36
+ /**
37
+ * Order trades newest first, the order every provider returns.
38
+ *
39
+ * @param trades - Trades to sort (not mutated).
40
+ * @returns A new array, newest first.
41
+ */
42
+ export function sortPublicTradesNewestFirst(trades) {
43
+ return [...trades].sort((a, b) => b.timestamp - a.timestamp);
44
+ }
45
+ //# sourceMappingURL=publicTrades.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publicTrades.js","sourceRoot":"","sources":["../../src/utils/publicTrades.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAgB3D,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAmB,EAAE;IAC5D,MAAM,MAAM,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,MAAM,KAAK,IAAI,IAAI,MAAM,GAAG,CAAC,CAAC;AACvC,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAC9B,MAAyB;IAEzB,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,GACpE,MAAM,CAAC;IACT,IACE,OAAO,EAAE,KAAK,QAAQ;QACtB,EAAE,CAAC,MAAM,KAAK,CAAC;QACf,CAAC,iBAAiB,CAAC,KAAK,CAAC;QACzB,CAAC,iBAAiB,CAAC,IAAI,CAAC;QACxB,IAAI,KAAK,IAAI;QACb,OAAO,SAAS,KAAK,QAAQ;QAC7B,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC;QAChC,SAAS,IAAI,CAAC,EACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO;QACL,EAAE;QACF,MAAM;QACN,KAAK;QACL,IAAI;QACJ,IAAI;QACJ,SAAS;QACT,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7B,UAAU;KACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAA8B;IAE9B,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { PerpsProviderType, PublicTrade } from '../types/index.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\n/**\n * Venue fields of one public trade, before validation.\n */\nexport type PublicTradeFields = {\n id: unknown;\n symbol: string;\n price: unknown;\n size: unknown;\n side: PublicTrade['side'] | null;\n timestamp: unknown;\n txHash?: string;\n providerId: PerpsProviderType;\n};\n\nconst isPositiveDecimal = (value: unknown): value is string => {\n const parsed = parseFiniteDecimal(value);\n return parsed !== null && parsed > 0;\n};\n\n/**\n * Build a {@link PublicTrade} from venue fields, or null when a field is\n * malformed. Public feeds skip a malformed trade instead of failing the batch.\n *\n * @param fields - Venue fields mapped to the shared names.\n * @returns The trade, or null.\n */\nexport function buildPublicTrade(\n fields: PublicTradeFields,\n): PublicTrade | null {\n const { id, symbol, price, size, side, timestamp, txHash, providerId } =\n fields;\n if (\n typeof id !== 'string' ||\n id.length === 0 ||\n !isPositiveDecimal(price) ||\n !isPositiveDecimal(size) ||\n side === null ||\n typeof timestamp !== 'number' ||\n !Number.isSafeInteger(timestamp) ||\n timestamp <= 0\n ) {\n return null;\n }\n return {\n id,\n symbol,\n price,\n size,\n side,\n timestamp,\n ...(txHash ? { txHash } : {}),\n providerId,\n };\n}\n\n/**\n * Order trades newest first, the order every provider returns.\n *\n * @param trades - Trades to sort (not mutated).\n * @returns A new array, newest first.\n */\nexport function sortPublicTradesNewestFirst(\n trades: readonly PublicTrade[],\n): PublicTrade[] {\n return [...trades].sort((a, b) => b.timestamp - a.timestamp);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/perps-controller",
3
- "version": "23.1.0-preview-d0ecc4dd6",
3
+ "version": "23.1.0-preview-fe3c580ff",
4
4
  "description": "Controller for perpetual trading functionality in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",