@lifi/perps-sdk-provider-lighter 49.0.0 → 50.0.0

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.
@@ -2,13 +2,13 @@ import type { PerpsMarketDisplay, Position } from '@lifi/perps-types';
2
2
  import type { LtAccountPosition } from '../types/index.js';
3
3
  /**
4
4
  * Display leverage from an IMF percent string: `100 / IMF` in exact decimal
5
- * arithmetic, rounded half-up to `LIGHTER_LEVERAGE_PRECISION`. The stored IMF
6
- * can make this differ from the requested leverage. Provider risk calculations
7
- * consume the original decimal IMF instead. `undefined` for a non-positive
5
+ * arithmetic, rounded half-up to the given precision (two decimals by default).
6
+ * The stored IMF can make this differ from the requested leverage.
7
+ * Returns `undefined` for a non-positive
8
8
  * or unparsable IMF.
9
9
  * @public
10
10
  */
11
- export declare const leverageFromImf: (imf: string) => string | undefined;
11
+ export declare const leverageFromImf: (imf: string, precision?: number) => string | undefined;
12
12
  /**
13
13
  * Display leverage from an integer IMF on `LIGHTER_IMF_PERCENT_SCALE`, the
14
14
  * unit of trade rows and order-book details: `500` is 5.00%, so 20x.
@@ -16,6 +16,10 @@ export declare const leverageFromImf: (imf: string) => string | undefined;
16
16
  * fraction a `StrictInt`, so the scale division is exact.
17
17
  */
18
18
  export declare const leverageFromScaledImf: (imf: number) => string | undefined;
19
+ /** ROE percentage from entry notional and the exact basis-point initial margin fraction. */
20
+ export declare const calculateRoe: (position: Position) => string | undefined;
21
+ /** Recalculate mark fields and ROE from the retained IMF without changing the input or snapshot margin. */
22
+ export declare const remarkPosition: (position: Position, markPrice: string) => Position;
19
23
  /**
20
24
  * Map a raw Lighter account position to the generic Position type. A row with
21
25
  * an invalid size gives `undefined`. An invalid position value or a
@@ -1 +1 @@
1
- {"version":3,"file":"mapPosition.d.ts","sourceRoot":"","sources":["../../../src/utils/mapPosition.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAOrE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAG1D;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,KAAK,MAAM,KAAG,MAAM,GAAG,SAQtD,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,KAAK,MAAM,KAAG,MAAM,GAAG,SAO5D,CAAA;AAsBD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GACtB,KAAK,iBAAiB,EACtB,QAAQ,kBAAkB,KACzB,QAAQ,GAAG,SAoDb,CAAA"}
1
+ {"version":3,"file":"mapPosition.d.ts","sourceRoot":"","sources":["../../../src/utils/mapPosition.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAQrE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAG1D;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAC1B,KAAK,MAAM,EACX,kBAAsC,KACrC,MAAM,GAAG,SAQX,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,KAAK,MAAM,KAAG,MAAM,GAAG,SAO5D,CAAA;AAED,4FAA4F;AAC5F,eAAO,MAAM,YAAY,GAAI,UAAU,QAAQ,KAAG,MAAM,GAAG,SAyB1D,CAAA;AAED,2GAA2G;AAC3G,eAAO,MAAM,cAAc,GACzB,UAAU,QAAQ,EAClB,WAAW,MAAM,KAChB,QAUF,CAAA;AAsBD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GACtB,KAAK,iBAAiB,EACtB,QAAQ,kBAAkB,KACzB,QAAQ,GAAG,SAmEb,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/perps-sdk-provider-lighter",
3
- "version": "49.0.0",
3
+ "version": "50.0.0",
4
4
  "description": "Lighter provider plugin for @lifi/perps-sdk",
5
5
  "homepage": "https://github.com/lifinance/perps-sdk",
6
6
  "bugs": {
@@ -43,11 +43,11 @@
43
43
  ],
44
44
  "dependencies": {
45
45
  "big.js": "^7.0.1",
46
- "@lifi/perps-types": "^30.0.0"
46
+ "@lifi/perps-types": "^30.1.0"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "viem": ">=2.57.11 <2.57.12",
50
- "@lifi/perps-sdk": "^35.0.0"
50
+ "@lifi/perps-sdk": "^36.0.0"
51
51
  },
52
52
  "publishConfig": {
53
53
  "access": "public"
@@ -15,6 +15,7 @@ import {
15
15
  isDecimalStringGreaterThan,
16
16
  isSpotCategory,
17
17
  localStorageAdapter,
18
+ multiplyDecimalString,
18
19
  numberToDecimalString,
19
20
  PerpsError,
20
21
  type PerpsProviderPlugin,
@@ -98,6 +99,8 @@ import {
98
99
  LIGHTER_CLIENT_ORDER_INDEX_ID_PREFIX,
99
100
  LIGHTER_FEE_TICK_SCALE,
100
101
  LIGHTER_HISTORY_PAGE_SIZE,
102
+ LIGHTER_IMF_PERCENT_SCALE,
103
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
101
104
  LIGHTER_LEVERAGE_PRECISION,
102
105
  LIGHTER_MAINNET_DEPLOYMENT,
103
106
  LIGHTER_RH_DEPLOYMENT,
@@ -160,7 +163,6 @@ import {
160
163
  fetchDetailedAccount,
161
164
  LIGHTER_MARKET_SLIPPAGE_PERCENT,
162
165
  type LighterFastWithdrawal,
163
- leverageFromImf,
164
166
  lighterAsset,
165
167
  lighterFastWithdrawal,
166
168
  lighterWithdrawableBalances,
@@ -175,6 +177,7 @@ import {
175
177
  toIsoFromMs,
176
178
  toIsoFromSeconds,
177
179
  } from './utils/index.js'
180
+ import { calculateRoe, remarkPosition } from './utils/mapPosition.js'
178
181
  import {
179
182
  fetchRegisteredApiKey,
180
183
  normalizeLighterPublicKey,
@@ -947,9 +950,17 @@ export const createLighterProvider = (
947
950
  `The backend market '${marketId}' carries no positive Lighter default leverage`
948
951
  )
949
952
  }
953
+ const orderLeverage = numberToDecimalString(leverage)
954
+ const initialMarginFractionBps = calculateLeverageImf(orderLeverage)
950
955
  return {
951
956
  marginMode: MarginMode.CROSS,
952
- leverage: numberToDecimalString(leverage),
957
+ leverage: orderLeverage,
958
+ displayLeverage: roundDecimalString(
959
+ divideDecimalString('10000', initialMarginFractionBps),
960
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
961
+ 'round'
962
+ ),
963
+ initialMarginFractionBps,
953
964
  }
954
965
  }
955
966
 
@@ -1472,26 +1483,37 @@ export const createLighterProvider = (
1472
1483
  const row = account?.positions.find(
1473
1484
  (p) => String(p.market_id) === marketId
1474
1485
  )
1475
- // An unparsable IMF throws; a non-positive one means no stored setting.
1476
- const leverage =
1477
- row === undefined
1478
- ? undefined
1479
- : leverageFromImf(
1480
- unknownToDecimalString(
1481
- row.initial_margin_fraction,
1482
- 'initial_margin_fraction',
1483
- providerKey
1484
- )
1485
- )
1486
- if (row === undefined || leverage === undefined) {
1486
+ if (row === undefined) {
1487
+ return resolveDefaultMarketSettings(marketId)
1488
+ }
1489
+ const imf = unknownToDecimalString(
1490
+ row.initial_margin_fraction,
1491
+ 'initial_margin_fraction',
1492
+ providerKey
1493
+ )
1494
+ if (!isDecimalStringGreaterThan(imf, '0')) {
1487
1495
  return resolveDefaultMarketSettings(marketId)
1488
1496
  }
1497
+ const decodedLeverage = divideDecimalString('100', imf)
1489
1498
  return {
1490
1499
  marginMode:
1491
1500
  row.margin_mode === LT_MARGIN_MODE_ISOLATED
1492
1501
  ? MarginMode.ISOLATED
1493
1502
  : MarginMode.CROSS,
1494
- leverage,
1503
+ leverage: roundDecimalString(
1504
+ decodedLeverage,
1505
+ LIGHTER_LEVERAGE_PRECISION,
1506
+ 'round'
1507
+ ),
1508
+ displayLeverage: roundDecimalString(
1509
+ decodedLeverage,
1510
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
1511
+ 'round'
1512
+ ),
1513
+ initialMarginFractionBps: multiplyDecimalString(
1514
+ imf,
1515
+ String(LIGHTER_IMF_PERCENT_SCALE)
1516
+ ),
1495
1517
  }
1496
1518
  },
1497
1519
 
@@ -2002,27 +2024,39 @@ export const createLighterProvider = (
2002
2024
 
2003
2025
  snapOrderSize,
2004
2026
 
2027
+ calculateRoe,
2028
+
2029
+ remarkPosition,
2030
+
2005
2031
  isLeverageEqual(requested, reported) {
2006
- if (
2007
- compareDecimalStrings(
2008
- requested,
2009
- roundDecimalString(requested, LIGHTER_LEVERAGE_PRECISION, 'truncate')
2010
- ) !== 0
2011
- ) {
2032
+ if (!isDecimalStringGreaterThan(requested, '0')) {
2012
2033
  throw new PerpsError(
2013
2034
  PerpsErrorCode.ValidationError,
2014
- `Lighter requested leverage must use at most ${LIGHTER_LEVERAGE_PRECISION} decimal places`
2035
+ 'Leverage must be above zero'
2015
2036
  )
2016
2037
  }
2017
2038
  const requestedImf = calculateLeverageImf(requested)
2018
- const reportedImf = calculateLeverageImf(reported)
2019
- if (requestedImf === '0' || reportedImf === '0') {
2039
+ if (requestedImf === '0') {
2040
+ throw new PerpsError(
2041
+ PerpsErrorCode.ValidationError,
2042
+ `Lighter requested leverage '${requested}' is too high to encode a positive IMF`
2043
+ )
2044
+ }
2045
+ const reportedImf = reported.initialMarginFractionBps
2046
+ if (
2047
+ reportedImf === undefined ||
2048
+ !isDecimalStringGreaterThan(reportedImf, '0') ||
2049
+ compareDecimalStrings(
2050
+ reportedImf,
2051
+ roundDecimalString(reportedImf, 0, 'truncate')
2052
+ ) !== 0
2053
+ ) {
2020
2054
  throw new PerpsError(
2021
2055
  PerpsErrorCode.ValidationError,
2022
- 'Lighter leverage must produce a positive IMF'
2056
+ 'Lighter reported IMF must be a positive integer'
2023
2057
  )
2024
2058
  }
2025
- return requestedImf === reportedImf
2059
+ return compareDecimalStrings(requestedImf, reportedImf) === 0
2026
2060
  },
2027
2061
 
2028
2062
  // A Lighter modify keeps the order type: ModifyOrderTxReq has no Type.
package/src/constants.ts CHANGED
@@ -183,14 +183,16 @@ export const DEFAULT_TRADES_LIMIT = 50
183
183
  export const LIGHTER_FEE_TICK_SCALE = 1_000_000
184
184
 
185
185
  /**
186
- * Decimal places a client may use for Lighter leverage. Lighter stores
187
- * leverage as an integer basis-point IMF (`round(10000 / leverage)`), and at
188
- * this precision a read-back leverage always re-saves the same IMF.
186
+ * Decimal places for leverage submission, order-compatible reads, and fill conversion.
187
+ * Native-IMF comparison does not use this limit.
189
188
  *
190
189
  * @public
191
190
  */
192
191
  export const LIGHTER_LEVERAGE_PRECISION = 2
193
192
 
193
+ /** Decimal places for Lighter position and market-setting display leverage. */
194
+ export const LIGHTER_LEVERAGE_DISPLAY_PRECISION = 1
195
+
194
196
  /**
195
197
  * Scale of the integer `initial_margin_fraction` values Lighter publishes on
196
198
  * trade rows and order-book details: the integer is a percent times 100, so
@@ -1,11 +1,17 @@
1
1
  import {
2
2
  absDecimalString,
3
3
  buildPosition,
4
+ calculateRoe as calculateMarginRoe,
5
+ calculateNotionalValue,
6
+ compareDecimalStrings,
4
7
  createWarnOnce,
5
8
  divideDecimalString,
6
9
  isDecimalString,
10
+ isDecimalStringGreaterThan,
7
11
  isDecimalStringZero,
8
12
  multiplyDecimalString,
13
+ remarkPositionValues,
14
+ roundDecimalString,
9
15
  safeDivideDecimalString,
10
16
  safeIsDecimalStringGreaterThan,
11
17
  safeNumberToDecimalString,
@@ -16,6 +22,7 @@ import type { PerpsMarketDisplay, Position } from '@lifi/perps-types'
16
22
  import { MarginMode, PositionSide } from '@lifi/perps-types'
17
23
  import {
18
24
  LIGHTER_IMF_PERCENT_SCALE,
25
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
19
26
  LIGHTER_LEVERAGE_PRECISION,
20
27
  LIGHTER_PROVIDER_KEY,
21
28
  } from '../constants.js'
@@ -24,20 +31,23 @@ import { LT_MARGIN_MODE_ISOLATED } from '../types/index.js'
24
31
 
25
32
  /**
26
33
  * Display leverage from an IMF percent string: `100 / IMF` in exact decimal
27
- * arithmetic, rounded half-up to `LIGHTER_LEVERAGE_PRECISION`. The stored IMF
28
- * can make this differ from the requested leverage. Provider risk calculations
29
- * consume the original decimal IMF instead. `undefined` for a non-positive
34
+ * arithmetic, rounded half-up to the given precision (two decimals by default).
35
+ * The stored IMF can make this differ from the requested leverage.
36
+ * Returns `undefined` for a non-positive
30
37
  * or unparsable IMF.
31
38
  * @public
32
39
  */
33
- export const leverageFromImf = (imf: string): string | undefined => {
40
+ export const leverageFromImf = (
41
+ imf: string,
42
+ precision = LIGHTER_LEVERAGE_PRECISION
43
+ ): string | undefined => {
34
44
  if (safeIsDecimalStringGreaterThan(imf, '0') !== true) {
35
45
  return undefined
36
46
  }
37
47
  const leverage = safeDivideDecimalString('100', imf)
38
48
  return leverage === undefined
39
49
  ? undefined
40
- : safeRoundDecimalString(leverage, LIGHTER_LEVERAGE_PRECISION, 'round')
50
+ : safeRoundDecimalString(leverage, precision, 'round')
41
51
  }
42
52
 
43
53
  /**
@@ -55,6 +65,50 @@ export const leverageFromScaledImf = (imf: number): string | undefined => {
55
65
  return percent === undefined ? undefined : leverageFromImf(percent)
56
66
  }
57
67
 
68
+ /** ROE percentage from entry notional and the exact basis-point initial margin fraction. */
69
+ export const calculateRoe = (position: Position): string | undefined => {
70
+ const { unrealizedPnl, size, entryPrice, initialMarginFractionBps } = position
71
+ if (
72
+ !isDecimalString(unrealizedPnl) ||
73
+ !isDecimalString(size) ||
74
+ !isDecimalStringGreaterThan(size, '0') ||
75
+ !isDecimalString(entryPrice) ||
76
+ !isDecimalStringGreaterThan(entryPrice, '0') ||
77
+ !isDecimalString(initialMarginFractionBps) ||
78
+ !isDecimalStringGreaterThan(initialMarginFractionBps, '0') ||
79
+ compareDecimalStrings(
80
+ initialMarginFractionBps,
81
+ roundDecimalString(initialMarginFractionBps, 0, 'truncate')
82
+ ) !== 0
83
+ ) {
84
+ return undefined
85
+ }
86
+ const margin = divideDecimalString(
87
+ multiplyDecimalString(
88
+ calculateNotionalValue(size, entryPrice),
89
+ initialMarginFractionBps
90
+ ),
91
+ '10000'
92
+ )
93
+ return calculateMarginRoe(unrealizedPnl, margin)
94
+ }
95
+
96
+ /** Recalculate mark fields and ROE from the retained IMF without changing the input or snapshot margin. */
97
+ export const remarkPosition = (
98
+ position: Position,
99
+ markPrice: string
100
+ ): Position => {
101
+ const remarked = remarkPositionValues(position, markPrice)
102
+ if (remarked === position) {
103
+ return position
104
+ }
105
+ const roe = calculateRoe(remarked)
106
+ if (roe !== undefined) {
107
+ remarked.returnOnEquity = roe
108
+ }
109
+ return remarked
110
+ }
111
+
58
112
  const skipPosition = (
59
113
  marketId: string,
60
114
  field: string,
@@ -102,7 +156,9 @@ export const mapPosition = (
102
156
  warnUnreadableField('position_value', pos.position_value)
103
157
  }
104
158
  const imf = pos.initial_margin_fraction
105
- const leverage = isDecimalString(imf) ? leverageFromImf(imf) : undefined
159
+ const leverage = isDecimalString(imf)
160
+ ? leverageFromImf(imf, LIGHTER_LEVERAGE_DISPLAY_PRECISION)
161
+ : undefined
106
162
  if (leverage === undefined) {
107
163
  warnUnreadableField('initial_margin_fraction', imf)
108
164
  }
@@ -115,7 +171,7 @@ export const mapPosition = (
115
171
  ? !isDecimalStringZero(liquidationPrice)
116
172
  : liquidationPrice !== ''
117
173
 
118
- return buildPosition({
174
+ const mapped = buildPosition({
119
175
  market,
120
176
  side: pos.sign >= 0 ? PositionSide.LONG : PositionSide.SHORT,
121
177
  size,
@@ -132,7 +188,15 @@ export const mapPosition = (
132
188
  ...(hasLiquidationPrice ? { liquidationPrice } : {}),
133
189
  unrealizedPnl: pos.unrealized_pnl,
134
190
  accruedFunding: pos.total_funding_paid_out ?? '0',
135
- ...(leverage === undefined ? {} : { leverage }),
191
+ ...(leverage === undefined
192
+ ? {}
193
+ : {
194
+ leverage,
195
+ initialMarginFractionBps: multiplyDecimalString(
196
+ imf,
197
+ String(LIGHTER_IMF_PERCENT_SCALE)
198
+ ),
199
+ }),
136
200
  marginUsed: isIsolated
137
201
  ? pos.allocated_margin
138
202
  : (initialMarginRequirement ?? '0'),
@@ -141,4 +205,9 @@ export const mapPosition = (
141
205
  : { initialMarginRequirement }),
142
206
  marginMode: isIsolated ? MarginMode.ISOLATED : MarginMode.CROSS,
143
207
  })
208
+ const roe = calculateRoe(mapped)
209
+ if (roe !== undefined) {
210
+ mapped.returnOnEquity = roe
211
+ }
212
+ return mapped
144
213
  }