@lifi/perps-sdk 32.0.0 → 33.0.1

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 (41) hide show
  1. package/README.md +49 -1
  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 -4
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/math/position.d.ts +2 -0
  7. package/dist/cjs/math/position.d.ts.map +1 -1
  8. package/dist/cjs/math/position.js +55 -0
  9. package/dist/cjs/math/position.js.map +1 -1
  10. package/dist/cjs/version.d.ts +1 -1
  11. package/dist/cjs/version.js +1 -1
  12. package/dist/cjs/websocket/WsProviderBase.d.ts +5 -1
  13. package/dist/cjs/websocket/WsProviderBase.d.ts.map +1 -1
  14. package/dist/cjs/websocket/WsProviderBase.js +34 -1
  15. package/dist/cjs/websocket/WsProviderBase.js.map +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 +2 -2
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/math/position.d.ts +14 -0
  21. package/dist/esm/math/position.d.ts.map +1 -1
  22. package/dist/esm/math/position.js +65 -0
  23. package/dist/esm/math/position.js.map +1 -1
  24. package/dist/esm/version.d.ts +1 -1
  25. package/dist/esm/version.js +1 -1
  26. package/dist/esm/websocket/WsProviderBase.d.ts +18 -1
  27. package/dist/esm/websocket/WsProviderBase.d.ts.map +1 -1
  28. package/dist/esm/websocket/WsProviderBase.js +46 -0
  29. package/dist/esm/websocket/WsProviderBase.js.map +1 -1
  30. package/dist/types/index.d.ts +2 -2
  31. package/dist/types/index.d.ts.map +1 -1
  32. package/dist/types/math/position.d.ts +14 -0
  33. package/dist/types/math/position.d.ts.map +1 -1
  34. package/dist/types/version.d.ts +1 -1
  35. package/dist/types/websocket/WsProviderBase.d.ts +18 -1
  36. package/dist/types/websocket/WsProviderBase.d.ts.map +1 -1
  37. package/package.json +2 -2
  38. package/src/index.ts +3 -0
  39. package/src/math/position.ts +106 -0
  40. package/src/version.ts +1 -1
  41. package/src/websocket/WsProviderBase.ts +65 -1
package/src/index.ts CHANGED
@@ -110,6 +110,7 @@ export {
110
110
  safeResolveCloseSize,
111
111
  } from './math/order.js'
112
112
  export {
113
+ buildPosition,
113
114
  calculateEffectiveLeverage,
114
115
  calculateInitialMarginRoe,
115
116
  calculateLiquidationDistance,
@@ -126,6 +127,7 @@ export {
126
127
  estimateUnrealizedPnl,
127
128
  isPositionMarginAdjustable,
128
129
  isPositionMarginRemovable,
130
+ remarkPosition,
129
131
  safeCalculateEffectiveLeverage,
130
132
  safeCalculateInitialMarginRoe,
131
133
  safeCalculateLiquidationDistance,
@@ -370,6 +372,7 @@ export type {
370
372
  } from './websocket/types.js'
371
373
  export {
372
374
  WS_CHANNEL_TEARDOWN_LINGER_MS,
375
+ WS_MARKETS_CONTEXT_INTERVAL_MS,
373
376
  WsProviderBase,
374
377
  } from './websocket/WsProviderBase.js'
375
378
  export { wsLog } from './websocket/wsLog.js'
@@ -24,6 +24,7 @@ import {
24
24
  } from '../decimal/arithmetic.js'
25
25
  import { DivBig } from '../decimal/big.js'
26
26
  import { isDecimalStringGreaterThan } from '../decimal/compare.js'
27
+ import { roundDecimalString } from '../decimal/convert.js'
27
28
  import {
28
29
  bigToDecimalString,
29
30
  decimalStringToBig,
@@ -594,3 +595,108 @@ export function isPositionMarginRemovable(position: Position): boolean {
594
595
  PositionMarginAdjustment.ADD_AND_REMOVE
595
596
  )
596
597
  }
598
+
599
+ const isPositiveDecimalString = (value: unknown): value is string =>
600
+ isDecimalString(value) && isDecimalStringGreaterThan(value, '0')
601
+
602
+ /** Complete a position, retaining explicit venue value and ROE.
603
+ * Calculated ROE uses the entry notional ÷ the current leverage: `|size| × entryPrice ÷ leverage`.
604
+ * Rebuild leverage and liquidation distance with half-up rounding to two decimals.
605
+ * Unusable inputs omit calculated fields. Never throws or warns.
606
+ * @public
607
+ */
608
+ export function buildPosition(position: Position): Position {
609
+ const {
610
+ effectiveLeverage: _effectiveLeverage,
611
+ liquidationDistance: _liquidationDistance,
612
+ ...fields
613
+ } = position
614
+ const built: Position = fields
615
+ const {
616
+ size,
617
+ entryPrice,
618
+ leverage,
619
+ markPrice,
620
+ liquidationPrice,
621
+ unrealizedPnl,
622
+ marginUsed,
623
+ } = position
624
+ const hasMarkPrice = isPositiveDecimalString(markPrice)
625
+ const hasMargin = isPositiveDecimalString(marginUsed)
626
+ if (
627
+ built.positionValue === undefined &&
628
+ hasMarkPrice &&
629
+ isDecimalString(size)
630
+ ) {
631
+ built.positionValue = calculateNotionalValue(size, markPrice)
632
+ }
633
+ if (
634
+ built.returnOnEquity === undefined &&
635
+ isDecimalString(unrealizedPnl) &&
636
+ isPositiveDecimalString(size) &&
637
+ isPositiveDecimalString(entryPrice) &&
638
+ isPositiveDecimalString(leverage)
639
+ ) {
640
+ built.returnOnEquity = calculateInitialMarginRoe(
641
+ unrealizedPnl,
642
+ size,
643
+ entryPrice,
644
+ leverage
645
+ )
646
+ }
647
+ if (hasMargin && isDecimalString(built.positionValue)) {
648
+ built.effectiveLeverage = roundDecimalString(
649
+ calculateEffectiveLeverage({
650
+ positionValueUsd: built.positionValue,
651
+ marginUsd: marginUsed,
652
+ }),
653
+ 2,
654
+ 'round'
655
+ )
656
+ }
657
+ if (hasMarkPrice && isPositiveDecimalString(liquidationPrice)) {
658
+ built.liquidationDistance = roundDecimalString(
659
+ calculateLiquidationDistance({
660
+ liquidationPrice,
661
+ currentPrice: markPrice,
662
+ }),
663
+ 2,
664
+ 'round'
665
+ )
666
+ }
667
+ return built
668
+ }
669
+
670
+ /** Recalculate mark-dependent fields. ROE uses the entry notional ÷ the leverage, and
671
+ * effective leverage uses the input snapshot's margin.
672
+ * Invalid marks return the input. Invalid entry prices or sizes retain its PnL.
673
+ * The input is unchanged, and valid marks return a new position.
674
+ * @public
675
+ */
676
+ export function remarkPosition(
677
+ position: Position,
678
+ markPrice: string
679
+ ): Position {
680
+ if (!isPositiveDecimalString(markPrice)) {
681
+ return position
682
+ }
683
+ const {
684
+ positionValue: _positionValue,
685
+ returnOnEquity: _returnOnEquity,
686
+ ...fields
687
+ } = position
688
+ const { entryPrice, size } = position
689
+ return buildPosition({
690
+ ...fields,
691
+ markPrice,
692
+ unrealizedPnl:
693
+ isPositiveDecimalString(entryPrice) && isDecimalString(size)
694
+ ? estimateUnrealizedPnl({
695
+ entryPrice,
696
+ markPrice,
697
+ size,
698
+ isLong: position.side === PositionSide.LONG,
699
+ })
700
+ : position.unrealizedPnl,
701
+ })
702
+ }
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 = '32.0.0'
13
+ export const version = '33.0.1'
@@ -1,4 +1,8 @@
1
- import type { Subscription, SubscriptionEvent } from '@lifi/perps-types'
1
+ import type {
2
+ MarketContext,
3
+ Subscription,
4
+ SubscriptionEvent,
5
+ } from '@lifi/perps-types'
2
6
  import type {
3
7
  ProviderGetQuoteParams,
4
8
  QuoteListener,
@@ -22,6 +26,14 @@ import { wsLog } from './wsLog.js'
22
26
  */
23
27
  export const WS_CHANNEL_TEARDOWN_LINGER_MS = 250
24
28
 
29
+ /**
30
+ * Minimum gap between two `marketsContext` deliveries on one provider. Wire
31
+ * frames inside the gap coalesce; the newest one is delivered when it ends.
32
+ *
33
+ * @public
34
+ */
35
+ export const WS_MARKETS_CONTEXT_INTERVAL_MS = 1_000
36
+
25
37
  interface ChannelEntry {
26
38
  /**
27
39
  * Per-listener ref count — a `Map`, not a `Set`, because the same listener
@@ -35,6 +47,10 @@ interface ChannelEntry {
35
47
  opening?: Promise<() => void>
36
48
  /** Deferred-teardown timer, set on the 1→0 transition; cleared if re-subscribed within the linger. */
37
49
  pendingTeardown?: ReturnType<typeof setTimeout>
50
+ /** `marketsContext` gap timer, set on each delivery and cleared with the channel; the next delivery waits for it. */
51
+ throttle?: ReturnType<typeof setTimeout>
52
+ /** Newest `marketsContext` snapshot producer that arrived inside the gap. */
53
+ pendingSnapshot?: () => Record<string, MarketContext>
38
54
  }
39
55
 
40
56
  /**
@@ -159,6 +175,7 @@ export abstract class WsProviderBase<TSub = unknown> implements WsProvider {
159
175
  if (entry.pendingTeardown !== undefined) {
160
176
  clearTimeout(entry.pendingTeardown)
161
177
  }
178
+ this.cancelPendingMarketsContext(entry)
162
179
  }
163
180
  this.onClose()
164
181
  this.rws.close()
@@ -182,6 +199,50 @@ export abstract class WsProviderBase<TSub = unknown> implements WsProvider {
182
199
  }
183
200
  }
184
201
 
202
+ /**
203
+ * Deliver the all-markets context map to the `marketsContext` listeners,
204
+ * at most once per {@link WS_MARKETS_CONTEXT_INTERVAL_MS}. The first call
205
+ * after the channel opens delivers at once. Calls inside the gap keep only
206
+ * the newest `snapshot`, which runs when the gap ends, so one delivered
207
+ * event costs one map build regardless of the wire rate.
208
+ */
209
+ protected emitMarketsContext(
210
+ snapshot: () => Record<string, MarketContext>
211
+ ): void {
212
+ const key = this.toKey({ channel: 'marketsContext', dex: this.providerKey })
213
+ const entry = this.channels.get(key)
214
+ if (entry === undefined || entry.listeners.size === 0) {
215
+ return
216
+ }
217
+ if (entry.throttle !== undefined) {
218
+ entry.pendingSnapshot = snapshot
219
+ return
220
+ }
221
+ this.deliverMarketsContext(key, entry, snapshot)
222
+ }
223
+
224
+ private deliverMarketsContext(
225
+ key: string,
226
+ entry: ChannelEntry,
227
+ snapshot: () => Record<string, MarketContext>
228
+ ): void {
229
+ entry.pendingSnapshot = undefined
230
+ entry.throttle = setTimeout(() => {
231
+ entry.throttle = undefined
232
+ const pending = entry.pendingSnapshot
233
+ if (pending !== undefined && this.channels.get(key) === entry) {
234
+ this.deliverMarketsContext(key, entry, pending)
235
+ }
236
+ }, WS_MARKETS_CONTEXT_INTERVAL_MS)
237
+ this.emit(key, { channel: 'marketsContext', data: snapshot() })
238
+ }
239
+
240
+ private cancelPendingMarketsContext(entry: ChannelEntry): void {
241
+ clearTimeout(entry.throttle)
242
+ entry.throttle = undefined
243
+ entry.pendingSnapshot = undefined
244
+ }
245
+
185
246
  /**
186
247
  * Tear `key` off the wire immediately if no listener holds it — i.e. it is
187
248
  * lingering in the deferred-teardown window (or its open is still
@@ -201,6 +262,7 @@ export abstract class WsProviderBase<TSub = unknown> implements WsProvider {
201
262
  if (entry.pendingTeardown !== undefined) {
202
263
  clearTimeout(entry.pendingTeardown)
203
264
  }
265
+ this.cancelPendingMarketsContext(entry)
204
266
  entry.teardown?.()
205
267
  this.channels.delete(key)
206
268
  return true
@@ -365,6 +427,7 @@ export abstract class WsProviderBase<TSub = unknown> implements WsProvider {
365
427
  if (entry.listeners.size > 0) {
366
428
  return
367
429
  }
430
+ entry.pendingSnapshot = undefined
368
431
 
369
432
  if (entry.teardown === undefined) {
370
433
  // Open not resolved yet — acquireChannel's post-open check unwinds it.
@@ -386,6 +449,7 @@ export abstract class WsProviderBase<TSub = unknown> implements WsProvider {
386
449
  e.pendingTeardown = undefined
387
450
  return
388
451
  }
452
+ this.cancelPendingMarketsContext(e)
389
453
  e.teardown?.()
390
454
  this.channels.delete(key)
391
455
  }, WS_CHANNEL_TEARDOWN_LINGER_MS)