@lifi/perps-sdk 33.0.1 → 33.2.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.
Files changed (140) hide show
  1. package/README.md +151 -1
  2. package/dist/cjs/index.d.ts +9 -4
  3. package/dist/cjs/index.d.ts.map +1 -1
  4. package/dist/cjs/index.js +16 -5
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/math/fills.d.ts +2 -0
  7. package/dist/cjs/math/fills.d.ts.map +1 -1
  8. package/dist/cjs/math/fills.js +77 -16
  9. package/dist/cjs/math/fills.js.map +1 -1
  10. package/dist/cjs/math/funding.d.ts +4 -0
  11. package/dist/cjs/math/funding.d.ts.map +1 -0
  12. package/dist/cjs/math/funding.js +17 -0
  13. package/dist/cjs/math/funding.js.map +1 -0
  14. package/dist/cjs/math/position.d.ts +1 -0
  15. package/dist/cjs/math/position.d.ts.map +1 -1
  16. package/dist/cjs/math/position.js +10 -9
  17. package/dist/cjs/math/position.js.map +1 -1
  18. package/dist/cjs/services/getFundingAverages.d.ts +9 -0
  19. package/dist/cjs/services/getFundingAverages.d.ts.map +1 -0
  20. package/dist/cjs/services/getFundingAverages.js +12 -0
  21. package/dist/cjs/services/getFundingAverages.js.map +1 -0
  22. package/dist/cjs/services/getFundingHistory.d.ts +10 -0
  23. package/dist/cjs/services/getFundingHistory.d.ts.map +1 -0
  24. package/dist/cjs/services/getFundingHistory.js +13 -0
  25. package/dist/cjs/services/getFundingHistory.js.map +1 -0
  26. package/dist/cjs/transport/fetchWithRetry.d.ts +1 -0
  27. package/dist/cjs/transport/fetchWithRetry.d.ts.map +1 -1
  28. package/dist/cjs/transport/fetchWithRetry.js +5 -1
  29. package/dist/cjs/transport/fetchWithRetry.js.map +1 -1
  30. package/dist/cjs/transport/request.d.ts.map +1 -1
  31. package/dist/cjs/transport/request.js +26 -23
  32. package/dist/cjs/transport/request.js.map +1 -1
  33. package/dist/cjs/types/api.d.ts +1 -0
  34. package/dist/cjs/types/api.d.ts.map +1 -1
  35. package/dist/cjs/version.d.ts +1 -1
  36. package/dist/cjs/version.js +1 -1
  37. package/dist/cjs/websocket/PerpsWsClient.d.ts +2 -2
  38. package/dist/cjs/websocket/PerpsWsClient.d.ts.map +1 -1
  39. package/dist/cjs/websocket/PerpsWsClient.js +2 -2
  40. package/dist/cjs/websocket/PerpsWsClient.js.map +1 -1
  41. package/dist/cjs/websocket/WsProviderBase.d.ts +8 -4
  42. package/dist/cjs/websocket/WsProviderBase.d.ts.map +1 -1
  43. package/dist/cjs/websocket/WsProviderBase.js +86 -14
  44. package/dist/cjs/websocket/WsProviderBase.js.map +1 -1
  45. package/dist/cjs/websocket/types.d.ts +2 -1
  46. package/dist/cjs/websocket/types.d.ts.map +1 -1
  47. package/dist/cjs/websocket/wsLog.d.ts +1 -0
  48. package/dist/cjs/websocket/wsLog.d.ts.map +1 -1
  49. package/dist/cjs/websocket/wsLog.js +3 -0
  50. package/dist/cjs/websocket/wsLog.js.map +1 -1
  51. package/dist/esm/index.d.ts +9 -4
  52. package/dist/esm/index.d.ts.map +1 -1
  53. package/dist/esm/index.js +6 -3
  54. package/dist/esm/index.js.map +1 -1
  55. package/dist/esm/math/fills.d.ts +26 -0
  56. package/dist/esm/math/fills.d.ts.map +1 -1
  57. package/dist/esm/math/fills.js +103 -15
  58. package/dist/esm/math/fills.js.map +1 -1
  59. package/dist/esm/math/funding.d.ts +16 -0
  60. package/dist/esm/math/funding.d.ts.map +1 -0
  61. package/dist/esm/math/funding.js +25 -0
  62. package/dist/esm/math/funding.js.map +1 -0
  63. package/dist/esm/math/position.d.ts +1 -0
  64. package/dist/esm/math/position.d.ts.map +1 -1
  65. package/dist/esm/math/position.js +1 -1
  66. package/dist/esm/math/position.js.map +1 -1
  67. package/dist/esm/services/getFundingAverages.d.ts +22 -0
  68. package/dist/esm/services/getFundingAverages.d.ts.map +1 -0
  69. package/dist/esm/services/getFundingAverages.js +16 -0
  70. package/dist/esm/services/getFundingAverages.js.map +1 -0
  71. package/dist/esm/services/getFundingHistory.d.ts +24 -0
  72. package/dist/esm/services/getFundingHistory.d.ts.map +1 -0
  73. package/dist/esm/services/getFundingHistory.js +17 -0
  74. package/dist/esm/services/getFundingHistory.js.map +1 -0
  75. package/dist/esm/transport/fetchWithRetry.d.ts +9 -0
  76. package/dist/esm/transport/fetchWithRetry.d.ts.map +1 -1
  77. package/dist/esm/transport/fetchWithRetry.js +12 -1
  78. package/dist/esm/transport/fetchWithRetry.js.map +1 -1
  79. package/dist/esm/transport/request.d.ts.map +1 -1
  80. package/dist/esm/transport/request.js +29 -24
  81. package/dist/esm/transport/request.js.map +1 -1
  82. package/dist/esm/types/api.d.ts +2 -0
  83. package/dist/esm/types/api.d.ts.map +1 -1
  84. package/dist/esm/version.d.ts +1 -1
  85. package/dist/esm/version.js +1 -1
  86. package/dist/esm/websocket/PerpsWsClient.d.ts +5 -9
  87. package/dist/esm/websocket/PerpsWsClient.d.ts.map +1 -1
  88. package/dist/esm/websocket/PerpsWsClient.js +5 -9
  89. package/dist/esm/websocket/PerpsWsClient.js.map +1 -1
  90. package/dist/esm/websocket/WsProviderBase.d.ts +29 -5
  91. package/dist/esm/websocket/WsProviderBase.d.ts.map +1 -1
  92. package/dist/esm/websocket/WsProviderBase.js +108 -14
  93. package/dist/esm/websocket/WsProviderBase.js.map +1 -1
  94. package/dist/esm/websocket/types.d.ts +6 -3
  95. package/dist/esm/websocket/types.d.ts.map +1 -1
  96. package/dist/esm/websocket/wsLog.d.ts +5 -0
  97. package/dist/esm/websocket/wsLog.d.ts.map +1 -1
  98. package/dist/esm/websocket/wsLog.js +7 -0
  99. package/dist/esm/websocket/wsLog.js.map +1 -1
  100. package/dist/types/index.d.ts +9 -4
  101. package/dist/types/index.d.ts.map +1 -1
  102. package/dist/types/math/fills.d.ts +26 -0
  103. package/dist/types/math/fills.d.ts.map +1 -1
  104. package/dist/types/math/funding.d.ts +16 -0
  105. package/dist/types/math/funding.d.ts.map +1 -0
  106. package/dist/types/math/position.d.ts +1 -0
  107. package/dist/types/math/position.d.ts.map +1 -1
  108. package/dist/types/services/getFundingAverages.d.ts +22 -0
  109. package/dist/types/services/getFundingAverages.d.ts.map +1 -0
  110. package/dist/types/services/getFundingHistory.d.ts +24 -0
  111. package/dist/types/services/getFundingHistory.d.ts.map +1 -0
  112. package/dist/types/transport/fetchWithRetry.d.ts +9 -0
  113. package/dist/types/transport/fetchWithRetry.d.ts.map +1 -1
  114. package/dist/types/transport/request.d.ts.map +1 -1
  115. package/dist/types/types/api.d.ts +2 -0
  116. package/dist/types/types/api.d.ts.map +1 -1
  117. package/dist/types/version.d.ts +1 -1
  118. package/dist/types/websocket/PerpsWsClient.d.ts +5 -9
  119. package/dist/types/websocket/PerpsWsClient.d.ts.map +1 -1
  120. package/dist/types/websocket/WsProviderBase.d.ts +29 -5
  121. package/dist/types/websocket/WsProviderBase.d.ts.map +1 -1
  122. package/dist/types/websocket/types.d.ts +6 -3
  123. package/dist/types/websocket/types.d.ts.map +1 -1
  124. package/dist/types/websocket/wsLog.d.ts +5 -0
  125. package/dist/types/websocket/wsLog.d.ts.map +1 -1
  126. package/package.json +2 -2
  127. package/src/index.ts +17 -1
  128. package/src/math/fills.ts +141 -14
  129. package/src/math/funding.ts +43 -0
  130. package/src/math/position.ts +1 -1
  131. package/src/services/getFundingAverages.ts +39 -0
  132. package/src/services/getFundingHistory.ts +45 -0
  133. package/src/transport/fetchWithRetry.ts +18 -1
  134. package/src/transport/request.ts +35 -30
  135. package/src/types/api.ts +2 -0
  136. package/src/version.ts +1 -1
  137. package/src/websocket/PerpsWsClient.ts +12 -9
  138. package/src/websocket/WsProviderBase.ts +135 -20
  139. package/src/websocket/types.ts +8 -3
  140. package/src/websocket/wsLog.ts +10 -0
package/src/math/fills.ts CHANGED
@@ -4,14 +4,24 @@ import {
4
4
  FillClassification,
5
5
  OrderSide,
6
6
  } from '@lifi/perps-types'
7
- import Big from 'big.js'
8
7
  import {
8
+ absDecimalString,
9
+ addDecimalString,
9
10
  addDecimalStrings,
10
11
  divideDecimalString,
11
12
  multiplyDecimalString,
13
+ subtractDecimalString,
12
14
  } from '../decimal/arithmetic.js'
13
- import { isDecimalStringGreaterThan } from '../decimal/compare.js'
15
+ import {
16
+ compareDecimalStrings,
17
+ isDecimalStringGreaterThan,
18
+ isDecimalStringZero,
19
+ } from '../decimal/compare.js'
14
20
  import { isDecimalString } from '../decimal/parse.js'
21
+ import {
22
+ calculateInitialMarginRoe,
23
+ isPositiveDecimalString,
24
+ } from './position.js'
15
25
 
16
26
  /**
17
27
  * Re-exported fill taxonomy used by {@link classifyFillFromPosition}.
@@ -41,36 +51,37 @@ export function classifyFillFromPosition(
41
51
  ? FillClassification.BUY
42
52
  : FillClassification.SELL
43
53
  }
44
- const start = new Big(startPosition)
45
- const size = new Big(sz)
46
- const end = side === OrderSide.BUY ? start.plus(size) : start.minus(size)
54
+ const end =
55
+ side === OrderSide.BUY
56
+ ? addDecimalString(startPosition, sz)
57
+ : subtractDecimalString(startPosition, sz)
47
58
 
48
- if (start.eq(0)) {
49
- return end.gt(0)
59
+ if (isDecimalStringZero(startPosition)) {
60
+ return isDecimalStringGreaterThan(end, '0')
50
61
  ? FillClassification.OPENED_LONG
51
62
  : FillClassification.OPENED_SHORT
52
63
  }
53
64
 
54
- if (start.gt(0)) {
55
- if (end.eq(0)) {
65
+ if (isDecimalStringGreaterThan(startPosition, '0')) {
66
+ if (isDecimalStringZero(end)) {
56
67
  return FillClassification.CLOSED_LONG
57
68
  }
58
- if (end.lt(0)) {
69
+ if (compareDecimalStrings(end, '0') < 0) {
59
70
  return FillClassification.SWITCHED_SHORT
60
71
  }
61
- if (end.gt(start)) {
72
+ if (isDecimalStringGreaterThan(end, startPosition)) {
62
73
  return FillClassification.INCREASED_LONG
63
74
  }
64
75
  return FillClassification.REDUCED_LONG
65
76
  }
66
77
 
67
- if (end.eq(0)) {
78
+ if (isDecimalStringZero(end)) {
68
79
  return FillClassification.CLOSED_SHORT
69
80
  }
70
- if (end.gt(0)) {
81
+ if (isDecimalStringGreaterThan(end, '0')) {
71
82
  return FillClassification.SWITCHED_LONG
72
83
  }
73
- if (end.lt(start)) {
84
+ if (compareDecimalStrings(end, startPosition) < 0) {
74
85
  return FillClassification.INCREASED_SHORT
75
86
  }
76
87
  return FillClassification.REDUCED_SHORT
@@ -99,3 +110,119 @@ export function calculateAverageFillPrice(
99
110
  )
100
111
  return divideDecimalString(notional, totalSize)
101
112
  }
113
+
114
+ const CLOSING_CLASSIFICATIONS: ReadonlySet<FillClassification> = new Set([
115
+ FillClassification.REDUCED_LONG,
116
+ FillClassification.REDUCED_SHORT,
117
+ FillClassification.CLOSED_LONG,
118
+ FillClassification.CLOSED_SHORT,
119
+ FillClassification.SWITCHED_LONG,
120
+ FillClassification.SWITCHED_SHORT,
121
+ ])
122
+
123
+ // Without `startPosition` a flip hides how much of the fill closed.
124
+ const FULL_SIZE_CLOSING_CLASSIFICATIONS: ReadonlySet<FillClassification> =
125
+ new Set([
126
+ FillClassification.REDUCED_LONG,
127
+ FillClassification.REDUCED_SHORT,
128
+ FillClassification.CLOSED_LONG,
129
+ FillClassification.CLOSED_SHORT,
130
+ ])
131
+
132
+ /**
133
+ * Part of a fill that reduced the position held before it:
134
+ * `min(|startPosition|, size)`. Without `startPosition`, the full `size` of a
135
+ * reducing or closing fill.
136
+ *
137
+ * @returns `undefined` for a fill that opens, increases or trades spot, for a
138
+ * flip without `startPosition`, when `size` is not a positive decimal
139
+ * string, or when `startPosition` is zero or not a decimal string. Never
140
+ * throws.
141
+ * @public
142
+ */
143
+ export function calculateFillClosedSize(
144
+ fill: Pick<Fill, 'size' | 'startPosition' | 'classification'>
145
+ ): DecimalString | undefined {
146
+ const { size, startPosition, classification } = fill
147
+ if (!isPositiveDecimalString(size)) {
148
+ return undefined
149
+ }
150
+ if (startPosition === undefined) {
151
+ return FULL_SIZE_CLOSING_CLASSIFICATIONS.has(classification)
152
+ ? size
153
+ : undefined
154
+ }
155
+ if (
156
+ !CLOSING_CLASSIFICATIONS.has(classification) ||
157
+ !isDecimalString(startPosition) ||
158
+ isDecimalStringZero(startPosition)
159
+ ) {
160
+ return undefined
161
+ }
162
+ const heldSize = absDecimalString(startPosition)
163
+ return isDecimalStringGreaterThan(size, heldSize) ? heldSize : size
164
+ }
165
+
166
+ // A sell closes a long: pnl = (price − entry) × closedSize. A buy closes a short.
167
+ const calculateEntryPriceFromPnl = (
168
+ fill: Fill,
169
+ pnl: DecimalString | undefined,
170
+ closedSize: DecimalString
171
+ ): DecimalString | undefined => {
172
+ if (!isDecimalString(pnl) || !isPositiveDecimalString(fill.price)) {
173
+ return undefined
174
+ }
175
+ const pnlPerUnit = divideDecimalString(pnl, closedSize)
176
+ const entryPrice =
177
+ fill.side === OrderSide.SELL
178
+ ? subtractDecimalString(fill.price, pnlPerUnit)
179
+ : addDecimalString(fill.price, pnlPerUnit)
180
+ return isDecimalStringGreaterThan(entryPrice, '0') ? entryPrice : undefined
181
+ }
182
+
183
+ /**
184
+ * Complete a fill with `closedSize`, `entryPrice` and `returnOnEquity`. A
185
+ * positive `entryPrice` on the input stays; otherwise it comes from
186
+ * `realizedPnl`, `closedSize` and `price`. ROE comes from
187
+ * `calculateInitialMarginRoe`, and a `null` `realizedPnl` counts as zero.
188
+ * A fill without a closed part gives none of the three fields.
189
+ *
190
+ * @param leverage - Leverage for the ROE: `Fill.leverage` when the venue sends
191
+ * it, else the current setting of the market. No ROE when it is not a
192
+ * positive decimal string.
193
+ * @returns A new fill. Never throws or warns.
194
+ * @public
195
+ */
196
+ export function buildFill(
197
+ fill: Fill,
198
+ leverage: DecimalString | undefined
199
+ ): Fill {
200
+ const {
201
+ closedSize: _closedSize,
202
+ entryPrice: inputEntryPrice,
203
+ returnOnEquity: _returnOnEquity,
204
+ ...fields
205
+ } = fill
206
+ const closedSize = calculateFillClosedSize(fill)
207
+ if (closedSize === undefined) {
208
+ return fields
209
+ }
210
+ const built: Fill = { ...fields, closedSize }
211
+ const pnl = fill.realizedPnl === null ? '0' : fill.realizedPnl
212
+ const entryPrice = isPositiveDecimalString(inputEntryPrice)
213
+ ? inputEntryPrice
214
+ : calculateEntryPriceFromPnl(fill, pnl, closedSize)
215
+ if (entryPrice === undefined) {
216
+ return built
217
+ }
218
+ built.entryPrice = entryPrice
219
+ if (isDecimalString(pnl) && isPositiveDecimalString(leverage)) {
220
+ built.returnOnEquity = calculateInitialMarginRoe(
221
+ pnl,
222
+ closedSize,
223
+ entryPrice,
224
+ leverage
225
+ )
226
+ }
227
+ return built
228
+ }
@@ -0,0 +1,43 @@
1
+ import type { DecimalString } from '@lifi/perps-types'
2
+ import {
3
+ divideDecimalString,
4
+ multiplyDecimalString,
5
+ } from '../decimal/arithmetic.js'
6
+ import { numberToDecimalString } from '../decimal/convert.js'
7
+ import { invalidInput } from '../errors/invalidInput.js'
8
+ import { createSafeFunction } from '../utils/createSafeFunction.js'
9
+
10
+ const SECONDS_PER_YEAR = String(365 * 24 * 60 * 60)
11
+
12
+ /**
13
+ * Simple APR of a funding rate: `rate × (365 days in seconds ÷ ratePeriodSeconds)`,
14
+ * as a signed fraction. It does not compound.
15
+ *
16
+ * @param rate - Funding rate as a fraction for one rate period, for example
17
+ * `MarketContext.funding.rate` or a settled funding average.
18
+ * @param ratePeriodSeconds - `Provider.funding.ratePeriodSeconds`.
19
+ * @throws {PerpsError} `ValidationError` when `rate` does not match the
20
+ * decimal pattern, or `ratePeriodSeconds` is not a finite number above zero.
21
+ * @public
22
+ */
23
+ export function annualizeFundingRate(
24
+ rate: DecimalString,
25
+ ratePeriodSeconds: number
26
+ ): DecimalString {
27
+ if (!Number.isFinite(ratePeriodSeconds) || ratePeriodSeconds <= 0) {
28
+ throw invalidInput(
29
+ 'ratePeriodSeconds',
30
+ `must be a finite number above zero, got ${ratePeriodSeconds}`
31
+ )
32
+ }
33
+ return divideDecimalString(
34
+ multiplyDecimalString(rate, SECONDS_PER_YEAR),
35
+ numberToDecimalString(ratePeriodSeconds)
36
+ )
37
+ }
38
+
39
+ /** @public */
40
+ export const safeAnnualizeFundingRate = createSafeFunction(
41
+ 'annualizeFundingRate',
42
+ annualizeFundingRate
43
+ )
@@ -596,7 +596,7 @@ export function isPositionMarginRemovable(position: Position): boolean {
596
596
  )
597
597
  }
598
598
 
599
- const isPositiveDecimalString = (value: unknown): value is string =>
599
+ export const isPositiveDecimalString = (value: unknown): value is string =>
600
600
  isDecimalString(value) && isDecimalStringGreaterThan(value, '0')
601
601
 
602
602
  /** Complete a position, retaining explicit venue value and ROE.
@@ -0,0 +1,39 @@
1
+ import type { FundingAveragesResponse } from '@lifi/perps-types'
2
+ import { buildUrl, request } from '../transport/request.js'
3
+ import type { SDKRequestOptions } from '../types/config.js'
4
+ import type { PerpsSDKClient } from '../types/provider.js'
5
+
6
+ /**
7
+ * Parameters for {@link getFundingAverages}.
8
+ *
9
+ * @public
10
+ */
11
+ export interface GetFundingAveragesParams {
12
+ provider: string
13
+ /** Optional filter of opaque `Market.id`s (not display symbols). */
14
+ marketIds?: string[]
15
+ }
16
+
17
+ /**
18
+ * Get the settled funding averages (8h, 24h, 3d, 7d) for markets, optionally
19
+ * filtered by `Market.id`. The rates are raw hourly fractions, not an APR.
20
+ *
21
+ * @throws {PerpsError} On backend error responses, network, or parsing errors.
22
+ * @public
23
+ */
24
+ export async function getFundingAverages(
25
+ client: PerpsSDKClient,
26
+ params: GetFundingAveragesParams,
27
+ options?: SDKRequestOptions
28
+ ): Promise<FundingAveragesResponse> {
29
+ const url = buildUrl(`${client.config.apiUrl}/fundingAverages`, {
30
+ provider: params.provider,
31
+ marketIds: params.marketIds?.join(','),
32
+ })
33
+ return request<FundingAveragesResponse>(
34
+ client.config,
35
+ url,
36
+ { provider: params.provider },
37
+ options
38
+ )
39
+ }
@@ -0,0 +1,45 @@
1
+ import type {
2
+ FundingHistoryRange,
3
+ FundingHistoryResponse,
4
+ } from '@lifi/perps-types'
5
+ import { buildUrl, request } from '../transport/request.js'
6
+ import type { SDKRequestOptions } from '../types/config.js'
7
+ import type { PerpsSDKClient } from '../types/provider.js'
8
+
9
+ /**
10
+ * Parameters for {@link getFundingHistory}.
11
+ *
12
+ * @public
13
+ */
14
+ export interface GetFundingHistoryParams {
15
+ provider: string
16
+ /** Opaque provider `Market.id`, not a display symbol. */
17
+ marketId: string
18
+ /** Pick from the provider's `Provider.fundingHistoryRanges`. */
19
+ range: FundingHistoryRange
20
+ }
21
+
22
+ /**
23
+ * Get the settled funding history of a market, oldest bucket first. The rates
24
+ * are raw hourly fractions, not an APR.
25
+ *
26
+ * @throws {PerpsError} On backend, network, or parsing errors.
27
+ * @public
28
+ */
29
+ export async function getFundingHistory(
30
+ client: PerpsSDKClient,
31
+ params: GetFundingHistoryParams,
32
+ options?: SDKRequestOptions
33
+ ): Promise<FundingHistoryResponse> {
34
+ const url = buildUrl(`${client.config.apiUrl}/fundingHistory`, {
35
+ provider: params.provider,
36
+ marketId: params.marketId,
37
+ range: params.range,
38
+ })
39
+ return request<FundingHistoryResponse>(
40
+ client.config,
41
+ url,
42
+ { provider: params.provider },
43
+ options
44
+ )
45
+ }
@@ -27,6 +27,23 @@ export function isAbortError(error: unknown): boolean {
27
27
  return error instanceof Error && error.name === 'AbortError'
28
28
  }
29
29
 
30
+ /**
31
+ * True when `error` is a caller cancellation of a request that `signal`
32
+ * controls: an {@link isAbortError} rejection, or the abort reason of `signal`,
33
+ * such as a custom `Error` or the `TimeoutError` of `AbortSignal.timeout()`.
34
+ * A different rejection stays a failure, also when `signal` aborts later.
35
+ *
36
+ * @public
37
+ */
38
+ export function isAbortRejection(
39
+ error: unknown,
40
+ signal: AbortSignal | undefined
41
+ ): boolean {
42
+ return (
43
+ isAbortError(error) || (signal?.aborted === true && error === signal.reason)
44
+ )
45
+ }
46
+
30
47
  /**
31
48
  * Wrap `fetch` with policy-driven retry. Honors `Retry-After` (when present
32
49
  * and `respectRetryAfter` is true), otherwise falls back to exponential
@@ -57,7 +74,7 @@ export async function fetchWithRetry(
57
74
  try {
58
75
  response = await fetchImpl(input, mergedInit)
59
76
  } catch (error) {
60
- if (isAbortError(error)) {
77
+ if (isAbortRejection(error, signal)) {
61
78
  throw error
62
79
  }
63
80
  networkError = error
@@ -4,7 +4,7 @@ import { PerpsError } from '../errors/PerpsError.js'
4
4
  import type { PerpsBaseConfig, SDKRequestOptions } from '../types/config.js'
5
5
  import { version } from '../version.js'
6
6
  import { errorCodeFromStatus } from './errorCodeFromStatus.js'
7
- import { fetchWithRetry, isAbortError } from './fetchWithRetry.js'
7
+ import { fetchWithRetry, isAbortRejection } from './fetchWithRetry.js'
8
8
  import {
9
9
  LIFI_REQUEST_KEY,
10
10
  LIFI_RETRY_DEFAULTS,
@@ -86,48 +86,28 @@ export async function request<T>(
86
86
  finalOptions = await config.requestInterceptor(url, finalOptions)
87
87
  }
88
88
 
89
+ const signal = sdkOptions?.signal ?? finalOptions.signal ?? undefined
90
+ let response: Response
89
91
  try {
90
92
  const requestStartedAt = onResponse ? Date.now() : 0
91
- const response = await fetchWithRetry(url, finalOptions, {
93
+ response = await fetchWithRetry(url, finalOptions, {
92
94
  policy,
93
95
  fetchImpl: config.fetch,
94
- signal: sdkOptions?.signal ?? finalOptions.signal ?? undefined,
96
+ signal,
95
97
  })
96
98
  const responseReceivedAt = onResponse ? Date.now() : 0
97
99
 
98
- if (!response.ok) {
99
- let body: PerpsErrorBody | undefined
100
- try {
101
- body = await response.json()
102
- } catch {}
103
-
104
- const fallbackMessage = `Request failed with status code ${response.status}`
105
- if (
106
- body &&
107
- typeof body.code === 'number' &&
108
- typeof body.message === 'string'
109
- ) {
110
- const error = new PerpsError(body.code, body.message)
111
- error.tool = body.tool ?? 'unknown'
112
- throw error
113
- }
114
- const error = new PerpsError(
115
- errorCodeFromStatus(response.status, PerpsErrorCode.DefaultError),
116
- fallbackMessage
117
- )
118
- error.tool = 'unknown'
119
- throw error
100
+ if (response.ok) {
101
+ const data = (await response.json()) as T
102
+ onResponse?.(response.headers, requestStartedAt, responseReceivedAt)
103
+ return data
120
104
  }
121
-
122
- const data = (await response.json()) as T
123
- onResponse?.(response.headers, requestStartedAt, responseReceivedAt)
124
- return data
125
105
  } catch (error) {
126
106
  if (error instanceof PerpsError) {
127
107
  throw error
128
108
  }
129
109
 
130
- if (isAbortError(error)) {
110
+ if (isAbortRejection(error, signal)) {
131
111
  throw error
132
112
  }
133
113
 
@@ -136,6 +116,31 @@ export async function request<T>(
136
116
  error instanceof Error ? error.message : 'Request failed'
137
117
  )
138
118
  }
119
+
120
+ // The non-2xx body read sits outside the catch above, so a failed read (an
121
+ // abort or a reset stream) rejects with its own error.
122
+ const text = await response.text()
123
+ let body: PerpsErrorBody | undefined
124
+ try {
125
+ body = JSON.parse(text)
126
+ } catch {}
127
+
128
+ const fallbackMessage = `Request failed with status code ${response.status}`
129
+ if (
130
+ body &&
131
+ typeof body.code === 'number' &&
132
+ typeof body.message === 'string'
133
+ ) {
134
+ const error = new PerpsError(body.code, body.message)
135
+ error.tool = body.tool ?? 'unknown'
136
+ throw error
137
+ }
138
+ const error = new PerpsError(
139
+ errorCodeFromStatus(response.status, PerpsErrorCode.DefaultError),
140
+ fallbackMessage
141
+ )
142
+ error.tool = 'unknown'
143
+ throw error
139
144
  }
140
145
 
141
146
  /**
package/src/types/api.ts CHANGED
@@ -249,6 +249,8 @@ export interface ModifyOrdersParams {
249
249
  address: Address
250
250
  /** Provider-specific order modifications. */
251
251
  modifications: ModifyOrderInput[]
252
+ /** Market context for per-market order ids; use the order's opaque `market.id`. */
253
+ assetId?: string
252
254
  }
253
255
 
254
256
  /**
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 = '33.0.1'
13
+ export const version = '33.2.0'
@@ -10,6 +10,7 @@ import type { PerpsSDKClient, QuoteListener } from '../types/provider.js'
10
10
  import { cachePromise } from './cachePromise.js'
11
11
  import type {
12
12
  EventForSubscription,
13
+ SubscriptionErrorListener,
13
14
  SubscriptionListener,
14
15
  WsConnectionStatus,
15
16
  WsProvider,
@@ -181,14 +182,10 @@ export class PerpsWsClient {
181
182
  }
182
183
 
183
184
  /**
184
- * Subscribe to a WebSocket channel, lazily creating the provider's WS
185
- * connection. Returns an unsubscribe function.
185
+ * Subscribe to a WebSocket channel and resolve to an unsubscribe after local registration.
186
+ * Initial failures reject the promise. Later failures invoke `onError`.
187
+ * Registration and socket status do not confirm account authorization.
186
188
  *
187
- * @param onStatus - Optional listener for the underlying connection's
188
- * health. Fires `reconnecting` on a transient drop and the terminal
189
- * `disconnected` once auto-reconnect is abandoned, so consumers can
190
- * surface a reconnecting/disconnected state instead of silently showing
191
- * stale data.
192
189
  * @throws {PerpsError} When no WS provider factory is registered for the
193
190
  * subscription's `dex`.
194
191
  * @public
@@ -196,12 +193,18 @@ export class PerpsWsClient {
196
193
  async subscribe<S extends Subscription>(
197
194
  sub: S,
198
195
  listener: (event: EventForSubscription<S>) => void,
199
- onStatus?: WsStatusListener
196
+ onStatus?: WsStatusListener,
197
+ onError?: SubscriptionErrorListener
200
198
  ): Promise<() => void> {
201
199
  const providerKey = sub.dex
202
200
  const provider = await this.getOrCreateProvider(providerKey)
203
201
  provider.reconnect()
204
- return provider.subscribe(sub, listener as SubscriptionListener, onStatus)
202
+ return provider.subscribe(
203
+ sub,
204
+ listener as SubscriptionListener,
205
+ onStatus,
206
+ onError
207
+ )
205
208
  }
206
209
 
207
210
  /**