@lifi/perps-sdk-provider-lighter 48.0.1 → 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`, so the value a
6
- * client reads is the value it saved. Provider risk calculations consume the
7
- * original decimal IMF instead. `undefined` for a non-positive or unparsable
8
- * IMF.
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
+ * 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": "48.0.1",
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": "^34.0.1"
50
+ "@lifi/perps-sdk": "^36.0.0"
51
51
  },
52
52
  "publishConfig": {
53
53
  "access": "public"
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  ACTIVE_ORDER_STATUSES,
3
3
  calculateTransferable,
4
+ compareDecimalStrings,
4
5
  type DepositFlow,
5
6
  divideDecimalString,
6
7
  estimateLiquidationPriceAtMarketRate,
@@ -14,6 +15,7 @@ import {
14
15
  isDecimalStringGreaterThan,
15
16
  isSpotCategory,
16
17
  localStorageAdapter,
18
+ multiplyDecimalString,
17
19
  numberToDecimalString,
18
20
  PerpsError,
19
21
  type PerpsProviderPlugin,
@@ -36,6 +38,7 @@ import {
36
38
  paginateActivity,
37
39
  resolveQuote,
38
40
  resolveRetryPolicy,
41
+ roundDecimalString,
39
42
  type SDKRequestOptions,
40
43
  type SignActionsContext,
41
44
  type SignActionsResult,
@@ -96,6 +99,9 @@ import {
96
99
  LIGHTER_CLIENT_ORDER_INDEX_ID_PREFIX,
97
100
  LIGHTER_FEE_TICK_SCALE,
98
101
  LIGHTER_HISTORY_PAGE_SIZE,
102
+ LIGHTER_IMF_PERCENT_SCALE,
103
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
104
+ LIGHTER_LEVERAGE_PRECISION,
99
105
  LIGHTER_MAINNET_DEPLOYMENT,
100
106
  LIGHTER_RH_DEPLOYMENT,
101
107
  type LighterDeployment,
@@ -157,7 +163,6 @@ import {
157
163
  fetchDetailedAccount,
158
164
  LIGHTER_MARKET_SLIPPAGE_PERCENT,
159
165
  type LighterFastWithdrawal,
160
- leverageFromImf,
161
166
  lighterAsset,
162
167
  lighterFastWithdrawal,
163
168
  lighterWithdrawableBalances,
@@ -172,6 +177,7 @@ import {
172
177
  toIsoFromMs,
173
178
  toIsoFromSeconds,
174
179
  } from './utils/index.js'
180
+ import { calculateRoe, remarkPosition } from './utils/mapPosition.js'
175
181
  import {
176
182
  fetchRegisteredApiKey,
177
183
  normalizeLighterPublicKey,
@@ -193,6 +199,10 @@ const tickToFeeString = (tick: number): string =>
193
199
  numberToDecimalString(LIGHTER_FEE_TICK_SCALE)
194
200
  )
195
201
 
202
+ // UpdateLeverage stores a half-up integer initial margin fraction in basis points.
203
+ const calculateLeverageImf = (leverage: string): string =>
204
+ roundDecimalString(divideDecimalString('10000', leverage), 0, 'round')
205
+
196
206
  const projectFeeTier = (
197
207
  limits: LtAccountLimits
198
208
  ): { maker: string; taker: string } => ({
@@ -940,9 +950,17 @@ export const createLighterProvider = (
940
950
  `The backend market '${marketId}' carries no positive Lighter default leverage`
941
951
  )
942
952
  }
953
+ const orderLeverage = numberToDecimalString(leverage)
954
+ const initialMarginFractionBps = calculateLeverageImf(orderLeverage)
943
955
  return {
944
956
  marginMode: MarginMode.CROSS,
945
- leverage: numberToDecimalString(leverage),
957
+ leverage: orderLeverage,
958
+ displayLeverage: roundDecimalString(
959
+ divideDecimalString('10000', initialMarginFractionBps),
960
+ LIGHTER_LEVERAGE_DISPLAY_PRECISION,
961
+ 'round'
962
+ ),
963
+ initialMarginFractionBps,
946
964
  }
947
965
  }
948
966
 
@@ -1465,26 +1483,37 @@ export const createLighterProvider = (
1465
1483
  const row = account?.positions.find(
1466
1484
  (p) => String(p.market_id) === marketId
1467
1485
  )
1468
- // An unparsable IMF throws; a non-positive one means no stored setting.
1469
- const leverage =
1470
- row === undefined
1471
- ? undefined
1472
- : leverageFromImf(
1473
- unknownToDecimalString(
1474
- row.initial_margin_fraction,
1475
- 'initial_margin_fraction',
1476
- providerKey
1477
- )
1478
- )
1479
- 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')) {
1480
1495
  return resolveDefaultMarketSettings(marketId)
1481
1496
  }
1497
+ const decodedLeverage = divideDecimalString('100', imf)
1482
1498
  return {
1483
1499
  marginMode:
1484
1500
  row.margin_mode === LT_MARGIN_MODE_ISOLATED
1485
1501
  ? MarginMode.ISOLATED
1486
1502
  : MarginMode.CROSS,
1487
- 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
+ ),
1488
1517
  }
1489
1518
  },
1490
1519
 
@@ -1995,6 +2024,41 @@ export const createLighterProvider = (
1995
2024
 
1996
2025
  snapOrderSize,
1997
2026
 
2027
+ calculateRoe,
2028
+
2029
+ remarkPosition,
2030
+
2031
+ isLeverageEqual(requested, reported) {
2032
+ if (!isDecimalStringGreaterThan(requested, '0')) {
2033
+ throw new PerpsError(
2034
+ PerpsErrorCode.ValidationError,
2035
+ 'Leverage must be above zero'
2036
+ )
2037
+ }
2038
+ const requestedImf = calculateLeverageImf(requested)
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
+ ) {
2054
+ throw new PerpsError(
2055
+ PerpsErrorCode.ValidationError,
2056
+ 'Lighter reported IMF must be a positive integer'
2057
+ )
2058
+ }
2059
+ return compareDecimalStrings(requestedImf, reportedImf) === 0
2060
+ },
2061
+
1998
2062
  // A Lighter modify keeps the order type: ModifyOrderTxReq has no Type.
1999
2063
  triggerOrders: {
2000
2064
  modifyCanChangeType: false,
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`, so the value a
28
- * client reads is the value it saved. Provider risk calculations consume the
29
- * original decimal IMF instead. `undefined` for a non-positive or unparsable
30
- * IMF.
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
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
  }