@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.
- package/README.md +151 -1
- package/dist/cjs/index.d.ts +9 -4
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +16 -5
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/math/fills.d.ts +2 -0
- package/dist/cjs/math/fills.d.ts.map +1 -1
- package/dist/cjs/math/fills.js +77 -16
- package/dist/cjs/math/fills.js.map +1 -1
- package/dist/cjs/math/funding.d.ts +4 -0
- package/dist/cjs/math/funding.d.ts.map +1 -0
- package/dist/cjs/math/funding.js +17 -0
- package/dist/cjs/math/funding.js.map +1 -0
- package/dist/cjs/math/position.d.ts +1 -0
- package/dist/cjs/math/position.d.ts.map +1 -1
- package/dist/cjs/math/position.js +10 -9
- package/dist/cjs/math/position.js.map +1 -1
- package/dist/cjs/services/getFundingAverages.d.ts +9 -0
- package/dist/cjs/services/getFundingAverages.d.ts.map +1 -0
- package/dist/cjs/services/getFundingAverages.js +12 -0
- package/dist/cjs/services/getFundingAverages.js.map +1 -0
- package/dist/cjs/services/getFundingHistory.d.ts +10 -0
- package/dist/cjs/services/getFundingHistory.d.ts.map +1 -0
- package/dist/cjs/services/getFundingHistory.js +13 -0
- package/dist/cjs/services/getFundingHistory.js.map +1 -0
- package/dist/cjs/transport/fetchWithRetry.d.ts +1 -0
- package/dist/cjs/transport/fetchWithRetry.d.ts.map +1 -1
- package/dist/cjs/transport/fetchWithRetry.js +5 -1
- package/dist/cjs/transport/fetchWithRetry.js.map +1 -1
- package/dist/cjs/transport/request.d.ts.map +1 -1
- package/dist/cjs/transport/request.js +26 -23
- package/dist/cjs/transport/request.js.map +1 -1
- package/dist/cjs/types/api.d.ts +1 -0
- package/dist/cjs/types/api.d.ts.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/websocket/PerpsWsClient.d.ts +2 -2
- package/dist/cjs/websocket/PerpsWsClient.d.ts.map +1 -1
- package/dist/cjs/websocket/PerpsWsClient.js +2 -2
- package/dist/cjs/websocket/PerpsWsClient.js.map +1 -1
- package/dist/cjs/websocket/WsProviderBase.d.ts +8 -4
- package/dist/cjs/websocket/WsProviderBase.d.ts.map +1 -1
- package/dist/cjs/websocket/WsProviderBase.js +86 -14
- package/dist/cjs/websocket/WsProviderBase.js.map +1 -1
- package/dist/cjs/websocket/types.d.ts +2 -1
- package/dist/cjs/websocket/types.d.ts.map +1 -1
- package/dist/cjs/websocket/wsLog.d.ts +1 -0
- package/dist/cjs/websocket/wsLog.d.ts.map +1 -1
- package/dist/cjs/websocket/wsLog.js +3 -0
- package/dist/cjs/websocket/wsLog.js.map +1 -1
- package/dist/esm/index.d.ts +9 -4
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +6 -3
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/math/fills.d.ts +26 -0
- package/dist/esm/math/fills.d.ts.map +1 -1
- package/dist/esm/math/fills.js +103 -15
- package/dist/esm/math/fills.js.map +1 -1
- package/dist/esm/math/funding.d.ts +16 -0
- package/dist/esm/math/funding.d.ts.map +1 -0
- package/dist/esm/math/funding.js +25 -0
- package/dist/esm/math/funding.js.map +1 -0
- package/dist/esm/math/position.d.ts +1 -0
- package/dist/esm/math/position.d.ts.map +1 -1
- package/dist/esm/math/position.js +1 -1
- package/dist/esm/math/position.js.map +1 -1
- package/dist/esm/services/getFundingAverages.d.ts +22 -0
- package/dist/esm/services/getFundingAverages.d.ts.map +1 -0
- package/dist/esm/services/getFundingAverages.js +16 -0
- package/dist/esm/services/getFundingAverages.js.map +1 -0
- package/dist/esm/services/getFundingHistory.d.ts +24 -0
- package/dist/esm/services/getFundingHistory.d.ts.map +1 -0
- package/dist/esm/services/getFundingHistory.js +17 -0
- package/dist/esm/services/getFundingHistory.js.map +1 -0
- package/dist/esm/transport/fetchWithRetry.d.ts +9 -0
- package/dist/esm/transport/fetchWithRetry.d.ts.map +1 -1
- package/dist/esm/transport/fetchWithRetry.js +12 -1
- package/dist/esm/transport/fetchWithRetry.js.map +1 -1
- package/dist/esm/transport/request.d.ts.map +1 -1
- package/dist/esm/transport/request.js +29 -24
- package/dist/esm/transport/request.js.map +1 -1
- package/dist/esm/types/api.d.ts +2 -0
- package/dist/esm/types/api.d.ts.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/websocket/PerpsWsClient.d.ts +5 -9
- package/dist/esm/websocket/PerpsWsClient.d.ts.map +1 -1
- package/dist/esm/websocket/PerpsWsClient.js +5 -9
- package/dist/esm/websocket/PerpsWsClient.js.map +1 -1
- package/dist/esm/websocket/WsProviderBase.d.ts +29 -5
- package/dist/esm/websocket/WsProviderBase.d.ts.map +1 -1
- package/dist/esm/websocket/WsProviderBase.js +108 -14
- package/dist/esm/websocket/WsProviderBase.js.map +1 -1
- package/dist/esm/websocket/types.d.ts +6 -3
- package/dist/esm/websocket/types.d.ts.map +1 -1
- package/dist/esm/websocket/wsLog.d.ts +5 -0
- package/dist/esm/websocket/wsLog.d.ts.map +1 -1
- package/dist/esm/websocket/wsLog.js +7 -0
- package/dist/esm/websocket/wsLog.js.map +1 -1
- package/dist/types/index.d.ts +9 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/math/fills.d.ts +26 -0
- package/dist/types/math/fills.d.ts.map +1 -1
- package/dist/types/math/funding.d.ts +16 -0
- package/dist/types/math/funding.d.ts.map +1 -0
- package/dist/types/math/position.d.ts +1 -0
- package/dist/types/math/position.d.ts.map +1 -1
- package/dist/types/services/getFundingAverages.d.ts +22 -0
- package/dist/types/services/getFundingAverages.d.ts.map +1 -0
- package/dist/types/services/getFundingHistory.d.ts +24 -0
- package/dist/types/services/getFundingHistory.d.ts.map +1 -0
- package/dist/types/transport/fetchWithRetry.d.ts +9 -0
- package/dist/types/transport/fetchWithRetry.d.ts.map +1 -1
- package/dist/types/transport/request.d.ts.map +1 -1
- package/dist/types/types/api.d.ts +2 -0
- package/dist/types/types/api.d.ts.map +1 -1
- package/dist/types/version.d.ts +1 -1
- package/dist/types/websocket/PerpsWsClient.d.ts +5 -9
- package/dist/types/websocket/PerpsWsClient.d.ts.map +1 -1
- package/dist/types/websocket/WsProviderBase.d.ts +29 -5
- package/dist/types/websocket/WsProviderBase.d.ts.map +1 -1
- package/dist/types/websocket/types.d.ts +6 -3
- package/dist/types/websocket/types.d.ts.map +1 -1
- package/dist/types/websocket/wsLog.d.ts +5 -0
- package/dist/types/websocket/wsLog.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +17 -1
- package/src/math/fills.ts +141 -14
- package/src/math/funding.ts +43 -0
- package/src/math/position.ts +1 -1
- package/src/services/getFundingAverages.ts +39 -0
- package/src/services/getFundingHistory.ts +45 -0
- package/src/transport/fetchWithRetry.ts +18 -1
- package/src/transport/request.ts +35 -30
- package/src/types/api.ts +2 -0
- package/src/version.ts +1 -1
- package/src/websocket/PerpsWsClient.ts +12 -9
- package/src/websocket/WsProviderBase.ts +135 -20
- package/src/websocket/types.ts +8 -3
- 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 {
|
|
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
|
|
45
|
-
|
|
46
|
-
|
|
54
|
+
const end =
|
|
55
|
+
side === OrderSide.BUY
|
|
56
|
+
? addDecimalString(startPosition, sz)
|
|
57
|
+
: subtractDecimalString(startPosition, sz)
|
|
47
58
|
|
|
48
|
-
if (
|
|
49
|
-
return end
|
|
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 (
|
|
55
|
-
if (end
|
|
65
|
+
if (isDecimalStringGreaterThan(startPosition, '0')) {
|
|
66
|
+
if (isDecimalStringZero(end)) {
|
|
56
67
|
return FillClassification.CLOSED_LONG
|
|
57
68
|
}
|
|
58
|
-
if (end
|
|
69
|
+
if (compareDecimalStrings(end, '0') < 0) {
|
|
59
70
|
return FillClassification.SWITCHED_SHORT
|
|
60
71
|
}
|
|
61
|
-
if (end
|
|
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
|
|
78
|
+
if (isDecimalStringZero(end)) {
|
|
68
79
|
return FillClassification.CLOSED_SHORT
|
|
69
80
|
}
|
|
70
|
-
if (end
|
|
81
|
+
if (isDecimalStringGreaterThan(end, '0')) {
|
|
71
82
|
return FillClassification.SWITCHED_LONG
|
|
72
83
|
}
|
|
73
|
-
if (end
|
|
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
|
+
)
|
package/src/math/position.ts
CHANGED
|
@@ -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 (
|
|
77
|
+
if (isAbortRejection(error, signal)) {
|
|
61
78
|
throw error
|
|
62
79
|
}
|
|
63
80
|
networkError = error
|
package/src/transport/request.ts
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
93
|
+
response = await fetchWithRetry(url, finalOptions, {
|
|
92
94
|
policy,
|
|
93
95
|
fetchImpl: config.fetch,
|
|
94
|
-
signal
|
|
96
|
+
signal,
|
|
95
97
|
})
|
|
96
98
|
const responseReceivedAt = onResponse ? Date.now() : 0
|
|
97
99
|
|
|
98
|
-
if (
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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 (
|
|
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,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
|
|
185
|
-
*
|
|
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(
|
|
202
|
+
return provider.subscribe(
|
|
203
|
+
sub,
|
|
204
|
+
listener as SubscriptionListener,
|
|
205
|
+
onStatus,
|
|
206
|
+
onError
|
|
207
|
+
)
|
|
205
208
|
}
|
|
206
209
|
|
|
207
210
|
/**
|