@lifi/perps-sdk 0.0.0-preview-abcdac5a → 0.0.0-preview-1e136edd

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 (52) hide show
  1. package/README.md +13 -0
  2. package/dist/cjs/index.d.ts +2 -2
  3. package/dist/cjs/index.d.ts.map +1 -1
  4. package/dist/cjs/index.js +7 -3
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/math/position.d.ts +22 -0
  7. package/dist/cjs/math/position.d.ts.map +1 -1
  8. package/dist/cjs/math/position.js +93 -8
  9. package/dist/cjs/math/position.js.map +1 -1
  10. package/dist/cjs/types/deposit.d.ts +3 -3
  11. package/dist/cjs/types/deposit.d.ts.map +1 -1
  12. package/dist/cjs/types/provider.d.ts +4 -1
  13. package/dist/cjs/types/provider.d.ts.map +1 -1
  14. package/dist/cjs/version.d.ts +1 -1
  15. package/dist/cjs/version.js +1 -1
  16. package/dist/esm/index.d.ts +2 -2
  17. package/dist/esm/index.d.ts.map +1 -1
  18. package/dist/esm/index.js +1 -1
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/math/position.d.ts +71 -10
  21. package/dist/esm/math/position.d.ts.map +1 -1
  22. package/dist/esm/math/position.js +140 -18
  23. package/dist/esm/math/position.js.map +1 -1
  24. package/dist/esm/services/getGasRecommendation.d.ts +2 -2
  25. package/dist/esm/services/getGasRecommendation.js +1 -1
  26. package/dist/esm/types/deposit.d.ts +9 -8
  27. package/dist/esm/types/deposit.d.ts.map +1 -1
  28. package/dist/esm/types/provider.d.ts +20 -7
  29. package/dist/esm/types/provider.d.ts.map +1 -1
  30. package/dist/esm/utils/depositAssets.d.ts +3 -3
  31. package/dist/esm/utils/depositAssets.js +3 -3
  32. package/dist/esm/version.d.ts +1 -1
  33. package/dist/esm/version.js +1 -1
  34. package/dist/types/index.d.ts +2 -2
  35. package/dist/types/index.d.ts.map +1 -1
  36. package/dist/types/math/position.d.ts +71 -10
  37. package/dist/types/math/position.d.ts.map +1 -1
  38. package/dist/types/services/getGasRecommendation.d.ts +2 -2
  39. package/dist/types/types/deposit.d.ts +9 -8
  40. package/dist/types/types/deposit.d.ts.map +1 -1
  41. package/dist/types/types/provider.d.ts +20 -7
  42. package/dist/types/types/provider.d.ts.map +1 -1
  43. package/dist/types/utils/depositAssets.d.ts +3 -3
  44. package/dist/types/version.d.ts +1 -1
  45. package/package.json +2 -2
  46. package/src/index.ts +5 -1
  47. package/src/math/position.ts +176 -19
  48. package/src/services/getGasRecommendation.ts +2 -2
  49. package/src/types/deposit.ts +9 -8
  50. package/src/types/provider.ts +20 -6
  51. package/src/utils/depositAssets.ts +3 -3
  52. package/src/version.ts +1 -1
@@ -15,13 +15,21 @@ import {
15
15
  type PerpsMarket,
16
16
  type Position,
17
17
  PositionMarginAdjustment,
18
+ PositionSide,
18
19
  } from '@lifi/perps-types'
20
+ import {
21
+ absDecimalString,
22
+ divideDecimalString,
23
+ multiplyDecimalString,
24
+ } from '../decimal/arithmetic.js'
19
25
  import { DivBig } from '../decimal/big.js'
26
+ import { isDecimalStringGreaterThan } from '../decimal/compare.js'
20
27
  import {
21
28
  bigToDecimalString,
22
29
  decimalStringToBig,
23
30
  decimalStringToDivBig,
24
31
  } from '../decimal/decimalStringToBig.js'
32
+ import { isDecimalString } from '../decimal/parse.js'
25
33
  import { invalidInput } from '../errors/invalidInput.js'
26
34
  import type { LiquidationEstimateParams } from '../types/provider.js'
27
35
  import { createSafeFunction } from '../utils/createSafeFunction.js'
@@ -88,6 +96,52 @@ export function calculateRoe(pnl: string, margin: string): string {
88
96
  /** @public */
89
97
  export const safeCalculateRoe = createSafeFunction('calculateRoe', calculateRoe)
90
98
 
99
+ /**
100
+ * Calculate ROE as `pnl × leverage ÷ (|size| × entryPrice) × 100`.
101
+ * @throws {PerpsError} `ValidationError` for malformed inputs, zero `size`,
102
+ * or non-positive `entryPrice` and `leverage`.
103
+ * @public
104
+ */
105
+ export function calculateInitialMarginRoe(
106
+ pnl: string,
107
+ size: string,
108
+ entryPrice: string,
109
+ leverage: string
110
+ ): string {
111
+ for (const [parameter, value] of [
112
+ ['pnl', pnl],
113
+ ['size', size],
114
+ ['entryPrice', entryPrice],
115
+ ['leverage', leverage],
116
+ ] as const) {
117
+ if (!isDecimalString(value)) {
118
+ throw invalidInput(parameter, 'must be a decimal string')
119
+ }
120
+ }
121
+ const absoluteSize = absDecimalString(size)
122
+ if (!isDecimalStringGreaterThan(absoluteSize, '0')) {
123
+ throw invalidInput('size', 'must not be zero')
124
+ }
125
+ if (!isDecimalStringGreaterThan(entryPrice, '0')) {
126
+ throw invalidInput('entryPrice', 'must be positive')
127
+ }
128
+ if (!isDecimalStringGreaterThan(leverage, '0')) {
129
+ throw invalidInput('leverage', 'must be positive')
130
+ }
131
+ const numerator = multiplyDecimalString(pnl, leverage)
132
+ const denominator = multiplyDecimalString(absoluteSize, entryPrice)
133
+ return multiplyDecimalString(
134
+ divideDecimalString(numerator, denominator),
135
+ '100'
136
+ )
137
+ }
138
+
139
+ /** @public */
140
+ export const safeCalculateInitialMarginRoe = createSafeFunction(
141
+ 'calculateInitialMarginRoe',
142
+ calculateInitialMarginRoe
143
+ )
144
+
91
145
  /**
92
146
  * Required margin: `notionalValue ÷ leverage`.
93
147
  *
@@ -174,16 +228,27 @@ export const safeCalculateEffectiveLeverage = createSafeFunction(
174
228
  * margin_available = entryPrice × (1 / leverage - mmr)
175
229
  * liq_price = entryPrice - side × margin_available / (1 - mmr × side)
176
230
  *
231
+ * With `current`, the order of `size` adds to that position on the same side.
232
+ * The equity of the blended position at `entryPrice` is `current.margin`, the
233
+ * PnL of `current` at `entryPrice`, and the margin of the order. The margin
234
+ * available is that equity minus the maintenance margin of the blended size,
235
+ * and the formula above divides it by the blended size.
236
+ *
177
237
  * For existing positions, prefer `Position.liquidationPrice` from the venue.
178
238
  *
179
239
  * @param maintenanceMarginRate - Venue maintenance margin rate as a fraction
180
240
  * (`'0.01'` = 1%).
181
- * @returns The estimate, or `undefined` when `1 / leverage` is at or below
182
- * `maintenanceMarginRate`: the position opens at or past liquidation, so
183
- * the model has no price on the correct side of entry.
241
+ * @param size - Order size as a non-negative magnitude. Read only with
242
+ * `current`.
243
+ * @param current - Open isolated position on the same side that the order
244
+ * adds to. `margin` is its collateral net of unrealized PnL.
245
+ * @returns The estimate, or `undefined` when the margin above the
246
+ * maintenance requirement is not positive: the position opens at or past
247
+ * liquidation, so the model has no price on the correct side of entry.
184
248
  * @throws {PerpsError} `ValidationError` when an input does not match the
185
- * decimal pattern, `leverage` is zero, or `maintenanceMarginRate` gives a
186
- * zero denominator (`1` for a long, `-1` for a short).
249
+ * decimal pattern, `leverage` is zero, `maintenanceMarginRate` gives a
250
+ * zero denominator (`1` for a long, `-1` for a short), `current` comes
251
+ * without `size`, or `current.size + size` is not positive.
187
252
  * @public
188
253
  */
189
254
  export function estimateLiquidationPrice(params: {
@@ -191,6 +256,8 @@ export function estimateLiquidationPrice(params: {
191
256
  leverage: string
192
257
  isLong: boolean
193
258
  maintenanceMarginRate: string
259
+ size?: string
260
+ current?: { size: string; entryPrice: string; margin: string }
194
261
  }): string | undefined {
195
262
  const entryPrice = decimalStringToBig(params.entryPrice)
196
263
  const leverage = decimalStringToBig(params.leverage)
@@ -206,13 +273,38 @@ export function estimateLiquidationPrice(params: {
206
273
  `must not be ${params.isLong ? '1' : '-1'} for this side`
207
274
  )
208
275
  }
209
- const marginFractionAvailable = new DivBig(1).div(leverage).minus(mmr)
210
- if (marginFractionAvailable.lte(0)) {
276
+ if (params.current === undefined) {
277
+ const marginFractionAvailable = new DivBig(1).div(leverage).minus(mmr)
278
+ if (marginFractionAvailable.lte(0)) {
279
+ return undefined
280
+ }
281
+ const marginAvailable = marginFractionAvailable.times(entryPrice)
282
+ return bigToDecimalString(
283
+ entryPrice.minus(marginAvailable.times(side).div(denominator))
284
+ )
285
+ }
286
+ if (params.size === undefined) {
287
+ throw invalidInput('size', 'is required with `current`')
288
+ }
289
+ const addSize = decimalStringToBig(params.size)
290
+ const currentSize = decimalStringToBig(params.current.size)
291
+ const currentEntry = decimalStringToBig(params.current.entryPrice)
292
+ const currentMargin = decimalStringToBig(params.current.margin)
293
+ const totalSize = currentSize.plus(addSize)
294
+ if (totalSize.lte(0)) {
295
+ throw invalidInput('size + current.size', 'must be positive')
296
+ }
297
+ const equity = currentMargin
298
+ .plus(currentSize.times(entryPrice.minus(currentEntry)).times(side))
299
+ .plus(new DivBig(entryPrice).times(addSize).div(leverage))
300
+ const marginAvailablePerUnit = new DivBig(equity)
301
+ .minus(mmr.times(totalSize).times(entryPrice))
302
+ .div(totalSize)
303
+ if (marginAvailablePerUnit.lte(0)) {
211
304
  return undefined
212
305
  }
213
- const marginAvailable = marginFractionAvailable.times(entryPrice)
214
306
  return bigToDecimalString(
215
- entryPrice.minus(marginAvailable.times(side).div(denominator))
307
+ entryPrice.minus(marginAvailablePerUnit.times(side).div(denominator))
216
308
  )
217
309
  }
218
310
 
@@ -223,28 +315,93 @@ export const safeEstimateLiquidationPrice = createSafeFunction(
223
315
  )
224
316
 
225
317
  /**
226
- * Estimate the liquidation price of a new isolated position from the flat
227
- * `market.maintenanceMarginRate`.
318
+ * Estimate the liquidation price of the isolated position that an order
319
+ * leaves: a new position, or the blend of the order into `params.position`.
320
+ * The venue callbacks run only after the margin-mode and side checks pass.
228
321
  *
229
- * @returns The estimate, or `undefined` when the market carries no
230
- * `maintenanceMarginRate` or {@link estimateLiquidationPrice} gives
322
+ * @param venue.maintenanceMarginRate - Venue maintenance margin rate as a
323
+ * fraction (`'0.01'` = 1%).
324
+ * @param venue.positionCollateral - Collateral of `position`, net of
325
+ * unrealized PnL. It depends on the venue meaning of `Position.marginUsed`.
326
+ * @returns The estimate, or `undefined` when the order or the position is
327
+ * cross (the liquidation depends on the whole account), when the order
328
+ * reduces the position, or when {@link estimateLiquidationPrice} gives
231
329
  * `undefined`.
232
- * @throws {PerpsError} `ValidationError` on an input that
330
+ * @throws {PerpsError} `ValidationError` when `params.position` comes
331
+ * without `params.size`, or on an input that
233
332
  * {@link estimateLiquidationPrice} rejects.
234
333
  * @public
235
334
  */
236
- export function estimateLiquidationPriceAtMarketRate(
237
- market: PerpsMarket,
238
- params: LiquidationEstimateParams
335
+ export function estimateOrderLiquidationPrice(
336
+ params: LiquidationEstimateParams,
337
+ venue: {
338
+ maintenanceMarginRate: () => string
339
+ positionCollateral: (position: Position) => string
340
+ }
239
341
  ): string | undefined {
240
- if (market.maintenanceMarginRate === undefined) {
342
+ const { position } = params
343
+ if (
344
+ params.marginMode === MarginMode.CROSS ||
345
+ position?.marginMode === MarginMode.CROSS ||
346
+ (position !== undefined &&
347
+ (position.side === PositionSide.LONG) !== params.isLong)
348
+ ) {
241
349
  return undefined
242
350
  }
351
+ const maintenanceMarginRate = venue.maintenanceMarginRate()
352
+ if (position === undefined) {
353
+ return estimateLiquidationPrice({
354
+ entryPrice: params.entryPrice,
355
+ leverage: params.leverage,
356
+ isLong: params.isLong,
357
+ maintenanceMarginRate,
358
+ size: params.size,
359
+ })
360
+ }
361
+ const margin = venue.positionCollateral(position)
362
+ if (params.size === undefined) {
363
+ throw invalidInput('size', 'is required with `position`')
364
+ }
243
365
  return estimateLiquidationPrice({
244
366
  entryPrice: params.entryPrice,
245
367
  leverage: params.leverage,
246
368
  isLong: params.isLong,
247
- maintenanceMarginRate: market.maintenanceMarginRate,
369
+ maintenanceMarginRate,
370
+ size: params.size,
371
+ current: { size: position.size, entryPrice: position.entryPrice, margin },
372
+ })
373
+ }
374
+
375
+ /** @public */
376
+ export const safeEstimateOrderLiquidationPrice = createSafeFunction(
377
+ 'estimateOrderLiquidationPrice',
378
+ estimateOrderLiquidationPrice
379
+ )
380
+
381
+ /**
382
+ * Estimate the liquidation price of the isolated position that an order
383
+ * leaves, from the flat `market.maintenanceMarginRate`. The collateral of the
384
+ * position is `position.marginUsed`, so the venue `marginUsed` must exclude
385
+ * the unrealized PnL, as Lighter `allocated_margin` does.
386
+ *
387
+ * @returns The estimate, or `undefined` when the market carries no
388
+ * `maintenanceMarginRate`, or as {@link estimateOrderLiquidationPrice}
389
+ * documents.
390
+ * @throws {PerpsError} `ValidationError` as {@link estimateOrderLiquidationPrice}
391
+ * documents.
392
+ * @public
393
+ */
394
+ export function estimateLiquidationPriceAtMarketRate(
395
+ market: PerpsMarket,
396
+ params: LiquidationEstimateParams
397
+ ): string | undefined {
398
+ const { maintenanceMarginRate } = market
399
+ if (maintenanceMarginRate === undefined) {
400
+ return undefined
401
+ }
402
+ return estimateOrderLiquidationPrice(params, {
403
+ maintenanceMarginRate: () => maintenanceMarginRate,
404
+ positionCollateral: (position) => position.marginUsed,
248
405
  })
249
406
  }
250
407
 
@@ -17,13 +17,13 @@ export const LIFI_API_URL = 'https://li.quest/v1'
17
17
  * @public
18
18
  */
19
19
  export interface GetGasRecommendationParams {
20
- /** Chain to hold native gas on — a `firstDepositPipeline` flow's `chainId`. */
20
+ /** Chain to hold native gas on — a `venueDepositPipeline` flow's `chainId`. */
21
21
  chainId: number
22
22
  }
23
23
 
24
24
  /**
25
25
  * How much native gas LI.FI suggests holding on `params.chainId` to transact
26
- * there, for seeding the gas leg of a first-deposit pipeline. Read straight
26
+ * there, for seeding the gas leg of a venue-deposit pipeline. Read straight
27
27
  * from the LI.FI API by the user's client.
28
28
  *
29
29
  * @returns The suggestion, with `available: false` and no amounts on a chain
@@ -37,20 +37,21 @@ export interface DepositFlowLifiSwap {
37
37
  }
38
38
 
39
39
  /**
40
- * Fund an address that has no venue account yet. Collateral and the native gas
41
- * to broadcast with are both needed on `chainId`, where the venue's
42
- * {@link ActionType.DEPOSIT} action stages the on-chain legs that open the
43
- * account.
40
+ * Fund an address that has no venue account yet, or an existing account on a
41
+ * venue whose collateral no LI.FI route credits directly. Collateral and the
42
+ * native gas to broadcast with are both needed on `chainId`, where the venue's
43
+ * {@link ActionType.DEPOSIT} action stages the on-chain legs that credit the
44
+ * account and open it when none exists.
44
45
  *
45
46
  * @public
46
47
  */
47
- export interface DepositFlowFirstDepositPipeline {
48
- kind: 'firstDepositPipeline'
48
+ export interface DepositFlowVenueDepositPipeline {
49
+ kind: 'venueDepositPipeline'
49
50
  /** Chain on which the deposit legs broadcast; the wallet must be switched here. */
50
51
  chainId: number
51
52
  /** Native gas asset needed to broadcast the deposit legs. */
52
53
  gasAsset: DeclaredDepositAsset
53
- /** Collateral asset credited by the first deposit. */
54
+ /** Collateral asset the venue deposit credits. */
54
55
  collateral: DeclaredDepositAsset
55
56
  /** Action type used to stage the deposit pipeline. */
56
57
  bridgeAction: ActionType.DEPOSIT
@@ -77,5 +78,5 @@ export interface DepositFlowSetupRequired {
77
78
  */
78
79
  export type DepositFlow =
79
80
  | DepositFlowLifiSwap
80
- | DepositFlowFirstDepositPipeline
81
+ | DepositFlowVenueDepositPipeline
81
82
  | DepositFlowSetupRequired
@@ -11,6 +11,7 @@ import type {
11
11
  AvailableToTrade,
12
12
  DecimalString,
13
13
  FillsResponse,
14
+ MarginMode,
14
15
  Market,
15
16
  MarketRef,
16
17
  MarketSettings,
@@ -160,7 +161,8 @@ export interface ActionSignerContribution {
160
161
  }
161
162
 
162
163
  /**
163
- * Inputs for {@link PerpsProviderPlugin.estimateLiquidationPrice}:
164
+ * Inputs for {@link PerpsProviderPlugin.estimateLiquidationPrice}: the order
165
+ * and, when the order adds to one, the open position on the market.
164
166
  * `leverage` is the user-selected leverage for the new position, `isLong`
165
167
  * carries direction.
166
168
  *
@@ -172,6 +174,14 @@ export interface LiquidationEstimateParams {
172
174
  leverage: string
173
175
  /** `true` for long, `false` for short. */
174
176
  isLong: boolean
177
+ marginMode: MarginMode
178
+ /**
179
+ * Order size in base-asset units. The estimate reads it only with
180
+ * `position`, to blend the order into that position.
181
+ */
182
+ size?: DecimalString
183
+ /** Open position on the market that the order joins. */
184
+ position?: Position
175
185
  }
176
186
 
177
187
  /**
@@ -633,16 +643,20 @@ export interface PerpsProviderPlugin {
633
643
  }
634
644
 
635
645
  /**
636
- * Estimate the liquidation price of a new isolated position on `market`
637
- * using the venue's margin model. A preview helper — for existing
646
+ * Estimate the liquidation price of the position that the order leaves on
647
+ * `market` using the venue's margin model: a new position, or the blend of
648
+ * the order into `params.position`. A preview helper — for existing
638
649
  * positions, prefer `Position.liquidationPrice` from the venue. Pure —
639
650
  * does no I/O.
640
651
  *
641
652
  * @returns The estimated liquidation price, or `undefined` when `market`
642
- * lacks the margin metadata the model needs or `leverage` leaves no
643
- * margin above the maintenance requirement.
653
+ * lacks the margin metadata the model needs, `leverage` leaves no
654
+ * margin above the maintenance requirement, or the venue model cannot
655
+ * give a correct price for the margin mode and position, such as a cross
656
+ * position whose liquidation depends on the whole account.
644
657
  * @throws {PerpsError} `ValidationError` when an input does not match the
645
- * decimal pattern or is degenerate, such as a zero leverage.
658
+ * decimal pattern or is degenerate, such as a zero leverage or a
659
+ * `position` without a `size`.
646
660
  */
647
661
  estimateLiquidationPrice(
648
662
  market: PerpsMarket,
@@ -3,7 +3,7 @@ import { zeroAddress } from 'viem'
3
3
  import type { DeclaredDepositAsset } from '../types/deposit.js'
4
4
 
5
5
  /**
6
- * USDC on Ethereum mainnet — the collateral leg of Lighter's first-deposit
6
+ * USDC on Ethereum mainnet — the collateral leg of Lighter's venue-deposit
7
7
  * pipeline, and the token Ondo's provisioned deposit address is funded in.
8
8
  *
9
9
  * @public
@@ -15,7 +15,7 @@ export const ETHEREUM_USDC: DeclaredDepositAsset = {
15
15
  }
16
16
 
17
17
  /**
18
- * Ether on Ethereum mainnet, to broadcast the first-deposit pipeline's legs
18
+ * Ether on Ethereum mainnet, to broadcast the venue-deposit pipeline's legs
19
19
  * with.
20
20
  *
21
21
  * @public
@@ -65,7 +65,7 @@ export const ROBINHOOD_USDG: DeclaredDepositAsset = {
65
65
  }
66
66
 
67
67
  /**
68
- * Ether on Robinhood Chain, to broadcast the Robinhood first-deposit pipeline's
68
+ * Ether on Robinhood Chain, to broadcast the Robinhood venue-deposit pipeline's
69
69
  * legs with.
70
70
  *
71
71
  * @public
package/src/version.ts CHANGED
@@ -10,4 +10,4 @@ export const name = '@lifi/perps-sdk'
10
10
  *
11
11
  * @public
12
12
  */
13
- export const version = '0.0.0-preview-abcdac5a'
13
+ export const version = '0.0.0-preview-1e136edd'