-
Notifications
You must be signed in to change notification settings - Fork 4
/
IndexerClient.ts
492 lines (443 loc) · 15.5 KB
/
IndexerClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import {
ProductEngineType,
QUOTE_PRODUCT_ID,
} from '@vertex-protocol/contracts';
import { toBigDecimal } from '@vertex-protocol/utils';
import { IndexerBaseClient } from './IndexerBaseClient';
import {
BaseIndexerPaginatedEvent,
GetIndexerPaginatedInterestFundingPaymentsResponse,
GetIndexerPaginatedLeaderboardParams,
GetIndexerPaginatedLeaderboardResponse,
GetIndexerPaginatedOrdersParams,
GetIndexerPaginatedOrdersResponse,
GetIndexerPaginatedRewardsParams,
GetIndexerPaginatedRewardsResponse,
GetIndexerSubaccountCollateralEventsParams,
GetIndexerSubaccountCollateralEventsResponse,
GetIndexerSubaccountInterestFundingPaymentsParams,
GetIndexerSubaccountLiquidationEventsParams,
GetIndexerSubaccountLiquidationEventsResponse,
GetIndexerSubaccountLpEventsParams,
GetIndexerSubaccountLpEventsResponse,
GetIndexerSubaccountMatchEventParams,
GetIndexerSubaccountMatchEventsResponse,
GetIndexerSubaccountSettlementEventsParams,
GetIndexerSubaccountSettlementEventsResponse,
IndexerCollateralEvent,
IndexerEventPerpStateSnapshot,
IndexerEventSpotStateSnapshot,
IndexerEventWithTx,
IndexerLiquidationEvent,
IndexerLpEvent,
IndexerSettlementEvent,
PaginatedIndexerEventsResponse,
} from './types';
export class IndexerClient extends IndexerBaseClient {
async getPaginatedSubaccountMatchEvents(
params: GetIndexerSubaccountMatchEventParams,
): Promise<GetIndexerSubaccountMatchEventsResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
} = params;
const limit = requestedLimit + 1;
const events = await this.getMatchEvents({
startCursor,
limit,
subaccount: { subaccountName, subaccountOwner },
productIds: params.productIds,
});
return this.getPaginationEventsResponse(events, requestedLimit);
}
async getPaginatedSubaccountLpEvents(
params: GetIndexerSubaccountLpEventsParams,
): Promise<GetIndexerSubaccountLpEventsResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
} = params;
// There are 2 events per mint/burn for spot - one associated with the product & the other with the quote
// There is only 1 event per mint/burn for perp - associated with the product, where the quote delta is encoded in vQuote
const limit = requestedLimit + 1;
const baseResponse = await this.getEvents({
startCursor,
eventTypes: ['mint_lp', 'burn_lp'],
limit: {
type: 'txs',
value: limit,
},
subaccount: { subaccountName, subaccountOwner },
});
// Now aggregate results by the submission index, use map to maintain insertion order
const eventsBySubmissionIdx = new Map<string, IndexerLpEvent>();
baseResponse.forEach((event) => {
const mappedEvent = (() => {
const existingEvent = eventsBySubmissionIdx.get(event.submissionIndex);
if (existingEvent) {
return existingEvent;
}
const newEvent: IndexerLpEvent = {
// These fields will be updated properly later
lpDelta: toBigDecimal(0),
baseDelta: toBigDecimal(0),
quoteDelta: toBigDecimal(0),
baseSnapshot: event.state,
quoteSnapshot: undefined,
timestamp: event.timestamp,
submissionIndex: event.submissionIndex,
};
eventsBySubmissionIdx.set(event.submissionIndex, newEvent);
return newEvent;
})();
const balanceDelta = event.state.postBalance.amount.minus(
event.state.preBalance.amount,
);
const lpBalanceDelta = event.state.postBalance.lpAmount.minus(
event.state.preBalance.lpAmount,
);
// Perp - this should be the only relevant event
if (event.state.type === ProductEngineType.PERP) {
mappedEvent.lpDelta = lpBalanceDelta;
mappedEvent.baseDelta = balanceDelta;
mappedEvent.quoteDelta = event.state.postBalance.vQuoteBalance.minus(
event.state.preBalance.vQuoteBalance,
);
mappedEvent.baseSnapshot = event.state;
return;
}
// Quote
if (event.state.market.productId === QUOTE_PRODUCT_ID) {
mappedEvent.quoteDelta = balanceDelta;
mappedEvent.quoteSnapshot = event.state;
return;
}
// Spot
mappedEvent.lpDelta = lpBalanceDelta;
mappedEvent.baseDelta = balanceDelta;
mappedEvent.baseSnapshot = event.state;
});
// Force cast to get rid of the `Partial`
const events = Array.from(eventsBySubmissionIdx.values());
return this.getPaginationEventsResponse(events, requestedLimit);
}
async getPaginatedSubaccountCollateralEvents(
params: GetIndexerSubaccountCollateralEventsParams,
): Promise<GetIndexerSubaccountCollateralEventsResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
} = params;
const limit = requestedLimit + 1;
const baseResponse = await this.getEvents({
startCursor,
eventTypes: params.eventTypes ?? [
'deposit_collateral',
'withdraw_collateral',
],
limit: {
type: 'txs',
value: limit,
},
subaccount: { subaccountName, subaccountOwner },
});
const events = baseResponse.map((event): IndexerCollateralEvent => {
if (event.state.type !== ProductEngineType.SPOT) {
throw Error('Incorrect event state for collateral event');
}
return {
timestamp: event.timestamp,
submissionIndex: event.submissionIndex,
snapshot: event.state,
amount: event.state.postBalance.amount.minus(
event.state.preBalance.amount,
),
newAmount: event.state.postBalance.amount,
};
});
return this.getPaginationEventsResponse(events, requestedLimit);
}
async getPaginatedSubaccountOrders(
params: GetIndexerPaginatedOrdersParams,
): Promise<GetIndexerPaginatedOrdersResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
productIds,
} = params;
const limit = requestedLimit + 1;
const baseResponse = await this.getOrders({
startCursor,
subaccount: { subaccountName, subaccountOwner },
limit,
productIds,
});
// Same pagination meta logic as events, but duplicate for now as this return type is slightly different
const truncatedOrders = baseResponse.slice(0, requestedLimit);
const hasMore = baseResponse.length > truncatedOrders.length;
return {
meta: {
hasMore,
nextCursor: baseResponse[truncatedOrders.length]?.submissionIndex,
},
orders: truncatedOrders,
};
}
async getPaginatedSubaccountSettlementEvents(
params: GetIndexerSubaccountSettlementEventsParams,
): Promise<GetIndexerSubaccountSettlementEventsResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
} = params;
// Each settlement has a quote & perp balance change, so 2 events per settlement tx
const limit = requestedLimit + 1;
const baseResponse = await this.getEvents({
startCursor,
eventTypes: ['settle_pnl'],
limit: {
type: 'txs',
value: limit,
},
subaccount: { subaccountName, subaccountOwner },
});
const events = baseResponse
.map((event): IndexerSettlementEvent | undefined => {
if (event.state.market.productId === QUOTE_PRODUCT_ID) {
return;
}
if (event.state.type !== ProductEngineType.PERP) {
throw Error('Incorrect event state for settlement event');
}
return {
timestamp: event.timestamp,
submissionIndex: event.submissionIndex,
snapshot: event.state,
// Spot quote delta = -vQuote delta
quoteDelta: event.state.preBalance.vQuoteBalance.minus(
event.state.postBalance.vQuoteBalance,
),
};
})
.filter((event): event is IndexerSettlementEvent => !!event);
return this.getPaginationEventsResponse(events, requestedLimit);
}
async getPaginatedSubaccountLiquidationEvents(
params: GetIndexerSubaccountLiquidationEventsParams,
): Promise<GetIndexerSubaccountLiquidationEventsResponse> {
const {
startCursor,
limit: requestedLimit,
subaccountName,
subaccountOwner,
} = params;
// There is 1 event emitted per product, including quote
// However, if the balance change is 0, then the liquidation did not touch the product
// A tx operates on a given health group, so only a spot & its associated perp can be actually liquidated within a single tx
// with an associated quote balance change
const limit = requestedLimit + 1;
const baseResponse = await this.getEvents({
startCursor,
eventTypes: ['liquidate_subaccount'],
limit: {
type: 'txs',
value: limit,
},
subaccount: { subaccountName, subaccountOwner },
});
// Now aggregate results by the submission index, use map to maintain insertion order
const eventsBySubmissionIdx = new Map<
string,
Partial<IndexerLiquidationEvent>
>();
baseResponse.forEach((event) => {
const mappedEvent = (() => {
const existingEvent = eventsBySubmissionIdx.get(event.submissionIndex);
if (existingEvent) {
return existingEvent;
}
const newEvent: Partial<IndexerLiquidationEvent> = {
lps: [],
perp: undefined,
spot: undefined,
quote: undefined,
timestamp: event.timestamp,
submissionIndex: event.submissionIndex,
};
return newEvent;
})();
// The original balance is the negated delta
const balanceDelta = event.state.postBalance.amount.minus(
event.state.preBalance.amount,
);
const lpBalanceDelta = event.state.postBalance.lpAmount.minus(
event.state.preBalance.lpAmount,
);
// Event without balance change - not part of this liq
// However, we could have zero balance changes for the quote product if this was a partial liquidation
if (
balanceDelta.isZero() &&
lpBalanceDelta.isZero() &&
event.state.market.productId !== QUOTE_PRODUCT_ID
) {
return;
}
if (!lpBalanceDelta.isZero()) {
// LP Decomposition
mappedEvent.lps?.push({
amountLpDecomposed: lpBalanceDelta.negated(),
underlyingBalanceDelta: balanceDelta,
indexerEvent: event,
});
} else {
// Actual underlying balance change
if (event.state.type === ProductEngineType.PERP) {
mappedEvent.perp = {
amountLiquidated: balanceDelta.negated(),
// This cast is safe because we're checking for event.state.type
indexerEvent:
event as IndexerEventWithTx<IndexerEventPerpStateSnapshot>,
};
} else if (event.state.market.productId === QUOTE_PRODUCT_ID) {
mappedEvent.quote = {
balanceDelta,
indexerEvent:
event as IndexerEventWithTx<IndexerEventSpotStateSnapshot>,
};
} else {
mappedEvent.spot = {
amountLiquidated: balanceDelta.negated(),
indexerEvent:
event as IndexerEventWithTx<IndexerEventSpotStateSnapshot>,
};
}
}
// Valid liq, so set into map
eventsBySubmissionIdx.set(event.submissionIndex, mappedEvent);
});
// Force cast to get rid of the `Partial`
const events = Array.from(
eventsBySubmissionIdx.values(),
) as IndexerLiquidationEvent[];
return this.getPaginationEventsResponse(events, requestedLimit);
}
/**
* Get all interest funding payments for a given subaccount with the standard pagination response
* This is a simple wrapper over the underlying `getInterestFundingPayments` function. Very little
* additional processing is needed because the endpoint is well structured for pagination
*
* @param params
*/
async getPaginatedSubaccountInterestFundingPayments(
params: GetIndexerSubaccountInterestFundingPaymentsParams,
): Promise<GetIndexerPaginatedInterestFundingPaymentsResponse> {
const { limit, productIds, startCursor, subaccountName, subaccountOwner } =
params;
const baseResponse = await this.getInterestFundingPayments({
limit,
productIds,
startCursor,
subaccount: {
subaccountName,
subaccountOwner,
},
});
return {
...baseResponse,
meta: {
hasMore: baseResponse.nextCursor != null,
nextCursor: baseResponse.nextCursor ?? undefined,
},
};
}
/**
* Paginated rewards query that paginates on epoch number.
*
* @param params
*/
async getPaginatedRewards(
params: GetIndexerPaginatedRewardsParams,
): Promise<GetIndexerPaginatedRewardsResponse> {
const requestedLimit = params.limit;
const baseResponse = await this.getRewards({
address: params.address,
// Query for 1 more epoch for proper pagination
limit: requestedLimit + 1,
// Start cursor is the next epoch number
start: Number(params.startCursor),
});
// Truncate the response to the requested limit
return {
...baseResponse,
epochs: baseResponse.epochs.slice(0, requestedLimit),
meta: {
hasMore: baseResponse.epochs.length > requestedLimit,
// Next cursor is the epoch number of the (requestedLimit+1)th item
nextCursor: baseResponse.epochs[requestedLimit]?.epoch.toFixed(),
},
};
}
/**
* Paginated leaderboard query that paginates on rank number.
*
* @param params
*/
async getPaginatedLeaderboard(
params: GetIndexerPaginatedLeaderboardParams,
): Promise<GetIndexerPaginatedLeaderboardResponse> {
const requestedLimit = params.limit;
const baseResponse = await this.getLeaderboard({
contestId: params.contestId,
rankType: params.rankType,
// Query for 1 more result for proper pagination
limit: requestedLimit + 1,
// Start cursor is the next rank number
startCursor: params.startCursor,
});
return {
...baseResponse,
// Truncate the response to the requested limit
participants: baseResponse.participants.slice(0, requestedLimit),
meta: {
hasMore: baseResponse.participants.length > requestedLimit,
// Next cursor is the rank number of the (requestedLimit+1)th item
nextCursor:
params.rankType == 'pnl'
? baseResponse.participants[requestedLimit]?.pnlRank.toFixed()
: baseResponse.participants[requestedLimit]?.roiRank.toFixed(),
},
};
}
/**
* A util function to generate the standard pagination response for events
* @param events
* @param requestedLimit given by consumers of the SDK
* @private
*/
private getPaginationEventsResponse<T extends BaseIndexerPaginatedEvent>(
events: T[],
requestedLimit: number,
): PaginatedIndexerEventsResponse<T> {
const truncatedEvents = events.slice(0, requestedLimit);
const hasMore = events.length > truncatedEvents.length;
return {
events: truncatedEvents,
meta: {
hasMore,
// We want the NEXT available cursor, so we use the first event after the truncation cutoff
// If len(events) === len(truncatedEvents), there are no more entries and this is undefined
nextCursor: events[truncatedEvents.length]?.submissionIndex,
},
};
}
}