@drift-labs/sdk 0.2.0-master.22 → 0.2.0-master.25
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/lib/addresses/pda.d.ts +4 -0
- package/lib/addresses/pda.js +27 -1
- package/lib/admin.d.ts +3 -0
- package/lib/admin.js +36 -10
- package/lib/clearingHouse.d.ts +11 -2
- package/lib/clearingHouse.js +140 -5
- package/lib/clearingHouseUser.d.ts +3 -1
- package/lib/clearingHouseUser.js +11 -9
- package/lib/config.js +1 -1
- package/lib/constants/banks.d.ts +2 -0
- package/lib/constants/banks.js +9 -0
- package/lib/constants/numericConstants.d.ts +2 -0
- package/lib/constants/numericConstants.js +4 -1
- package/lib/events/eventSubscriber.d.ts +4 -2
- package/lib/events/eventSubscriber.js +16 -9
- package/lib/events/fetchLogs.d.ts +10 -1
- package/lib/events/fetchLogs.js +27 -7
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +6 -2
- package/lib/events/sort.js +7 -10
- package/lib/events/types.d.ts +4 -2
- package/lib/events/types.js +2 -0
- package/lib/examples/makeTradeExample.js +13 -1
- package/lib/idl/clearing_house.json +1081 -173
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -0
- package/lib/math/amm.d.ts +3 -1
- package/lib/math/amm.js +41 -3
- package/lib/math/insurance.d.ts +4 -0
- package/lib/math/insurance.js +27 -0
- package/lib/math/margin.d.ts +1 -1
- package/lib/math/margin.js +5 -7
- package/lib/math/position.js +1 -1
- package/lib/types.d.ts +79 -24
- package/lib/types.js +7 -4
- package/package.json +1 -1
- package/src/addresses/pda.ts +56 -0
- package/src/admin.ts +64 -18
- package/src/clearingHouse.ts +230 -10
- package/src/clearingHouseUser.ts +16 -11
- package/src/config.ts +1 -1
- package/src/constants/banks.ts +16 -0
- package/src/constants/numericConstants.ts +4 -0
- package/src/events/eventSubscriber.ts +20 -12
- package/src/events/fetchLogs.ts +35 -8
- package/src/events/pollingLogProvider.ts +10 -2
- package/src/events/sort.ts +10 -14
- package/src/events/types.ts +7 -1
- package/src/examples/makeTradeExample.ts +20 -1
- package/src/idl/clearing_house.json +1081 -173
- package/src/index.ts +2 -0
- package/src/math/amm.ts +67 -2
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +3 -10
- package/src/math/position.ts +2 -2
- package/src/types.ts +83 -24
- package/src/events/eventSubscriber.js +0 -139
- package/src/events/sort.js +0 -44
package/src/index.ts
CHANGED
|
@@ -30,6 +30,7 @@ export * from './factory/oracleClient';
|
|
|
30
30
|
export * from './factory/bigNum';
|
|
31
31
|
export * from './events/types';
|
|
32
32
|
export * from './events/eventSubscriber';
|
|
33
|
+
export * from './events/fetchLogs';
|
|
33
34
|
export * from './math/auction';
|
|
34
35
|
export * from './math/conversion';
|
|
35
36
|
export * from './math/funding';
|
|
@@ -41,6 +42,7 @@ export * from './math/trade';
|
|
|
41
42
|
export * from './math/orders';
|
|
42
43
|
export * from './math/repeg';
|
|
43
44
|
export * from './math/margin';
|
|
45
|
+
export * from './math/insurance';
|
|
44
46
|
export * from './orderParams';
|
|
45
47
|
export * from './slot/SlotSubscriber';
|
|
46
48
|
export * from './wallet';
|
package/src/math/amm.ts
CHANGED
|
@@ -308,6 +308,51 @@ export function calculateAmmReservesAfterSwap(
|
|
|
308
308
|
return [newQuoteAssetReserve, newBaseAssetReserve];
|
|
309
309
|
}
|
|
310
310
|
|
|
311
|
+
export function calculateMarketOpenBidAsk(
|
|
312
|
+
baseAssetReserve: BN,
|
|
313
|
+
minBaseAssetReserve: BN,
|
|
314
|
+
maxBaseAssetReserve: BN
|
|
315
|
+
): [BN, BN] {
|
|
316
|
+
// open orders
|
|
317
|
+
let openAsks;
|
|
318
|
+
if (maxBaseAssetReserve > baseAssetReserve) {
|
|
319
|
+
openAsks = maxBaseAssetReserve.sub(baseAssetReserve).mul(new BN(-1));
|
|
320
|
+
} else {
|
|
321
|
+
openAsks = ZERO;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
let openBids;
|
|
325
|
+
if (minBaseAssetReserve < baseAssetReserve) {
|
|
326
|
+
openBids = baseAssetReserve.sub(minBaseAssetReserve);
|
|
327
|
+
} else {
|
|
328
|
+
openBids = ZERO;
|
|
329
|
+
}
|
|
330
|
+
return [openBids, openAsks];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export function calculateInventoryScale(
|
|
334
|
+
netBaseAssetAmount: BN,
|
|
335
|
+
baseAssetReserve: BN,
|
|
336
|
+
minBaseAssetReserve: BN,
|
|
337
|
+
maxBaseAssetReserve: BN
|
|
338
|
+
): number {
|
|
339
|
+
// inventory skew
|
|
340
|
+
const [openBids, openAsks] = calculateMarketOpenBidAsk(
|
|
341
|
+
baseAssetReserve,
|
|
342
|
+
minBaseAssetReserve,
|
|
343
|
+
maxBaseAssetReserve
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
const totalLiquidity = BN.max(openBids.abs().add(openAsks.abs()), new BN(1));
|
|
347
|
+
const inventoryScale =
|
|
348
|
+
BN.min(netBaseAssetAmount.abs(), totalLiquidity)
|
|
349
|
+
.mul(BID_ASK_SPREAD_PRECISION.mul(new BN(5)))
|
|
350
|
+
.div(totalLiquidity)
|
|
351
|
+
.toNumber() / BID_ASK_SPREAD_PRECISION.toNumber();
|
|
352
|
+
|
|
353
|
+
return inventoryScale;
|
|
354
|
+
}
|
|
355
|
+
|
|
311
356
|
export function calculateEffectiveLeverage(
|
|
312
357
|
baseSpread: number,
|
|
313
358
|
quoteAssetReserve: BN,
|
|
@@ -353,7 +398,10 @@ export function calculateSpreadBN(
|
|
|
353
398
|
pegMultiplier: BN,
|
|
354
399
|
netBaseAssetAmount: BN,
|
|
355
400
|
markPrice: BN,
|
|
356
|
-
totalFeeMinusDistributions: BN
|
|
401
|
+
totalFeeMinusDistributions: BN,
|
|
402
|
+
baseAssetReserve: BN,
|
|
403
|
+
minBaseAssetReserve: BN,
|
|
404
|
+
maxBaseAssetReserve: BN
|
|
357
405
|
): [number, number] {
|
|
358
406
|
let longSpread = baseSpread / 2;
|
|
359
407
|
let shortSpread = baseSpread / 2;
|
|
@@ -374,6 +422,20 @@ export function calculateSpreadBN(
|
|
|
374
422
|
|
|
375
423
|
const MAX_INVENTORY_SKEW = 5;
|
|
376
424
|
|
|
425
|
+
const inventoryScale = calculateInventoryScale(
|
|
426
|
+
netBaseAssetAmount,
|
|
427
|
+
baseAssetReserve,
|
|
428
|
+
minBaseAssetReserve,
|
|
429
|
+
maxBaseAssetReserve
|
|
430
|
+
);
|
|
431
|
+
const inventorySpreadScale = Math.min(MAX_INVENTORY_SKEW, 1 + inventoryScale);
|
|
432
|
+
|
|
433
|
+
if (netBaseAssetAmount.gt(ZERO)) {
|
|
434
|
+
longSpread *= inventorySpreadScale;
|
|
435
|
+
} else if (netBaseAssetAmount.lt(ZERO)) {
|
|
436
|
+
shortSpread *= inventorySpreadScale;
|
|
437
|
+
}
|
|
438
|
+
|
|
377
439
|
const effectiveLeverage = calculateEffectiveLeverage(
|
|
378
440
|
baseSpread,
|
|
379
441
|
quoteAssetReserve,
|
|
@@ -447,7 +509,10 @@ export function calculateSpread(
|
|
|
447
509
|
amm.pegMultiplier,
|
|
448
510
|
amm.netBaseAssetAmount,
|
|
449
511
|
markPrice,
|
|
450
|
-
amm.totalFeeMinusDistributions
|
|
512
|
+
amm.totalFeeMinusDistributions,
|
|
513
|
+
amm.baseAssetReserve,
|
|
514
|
+
amm.minBaseAssetReserve,
|
|
515
|
+
amm.maxBaseAssetReserve
|
|
451
516
|
);
|
|
452
517
|
|
|
453
518
|
let spread: number;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ONE, ZERO } from '../constants/numericConstants';
|
|
2
|
+
import { BN } from '../index';
|
|
3
|
+
|
|
4
|
+
export function stakeAmountToShares(
|
|
5
|
+
amount: BN,
|
|
6
|
+
totalIfShares: BN,
|
|
7
|
+
insuranceFundVaultBalance: BN
|
|
8
|
+
): BN {
|
|
9
|
+
let nShares: BN;
|
|
10
|
+
if (insuranceFundVaultBalance.gt(ZERO)) {
|
|
11
|
+
nShares = amount.mul(totalIfShares).div(insuranceFundVaultBalance);
|
|
12
|
+
} else {
|
|
13
|
+
nShares = amount;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return nShares;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function unstakeSharesToAmount(
|
|
20
|
+
nShares: BN,
|
|
21
|
+
totalIfShares: BN,
|
|
22
|
+
insuranceFundVaultBalance: BN
|
|
23
|
+
): BN {
|
|
24
|
+
let amount: BN;
|
|
25
|
+
if (totalIfShares.gt(ZERO)) {
|
|
26
|
+
amount = BN.max(
|
|
27
|
+
ZERO,
|
|
28
|
+
nShares.mul(insuranceFundVaultBalance).div(totalIfShares).sub(ONE)
|
|
29
|
+
);
|
|
30
|
+
} else {
|
|
31
|
+
amount = ZERO;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return amount;
|
|
35
|
+
}
|
package/src/math/margin.ts
CHANGED
|
@@ -92,22 +92,15 @@ export function calculateOraclePriceForPerpMargin(
|
|
|
92
92
|
return marginPrice;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
export function
|
|
95
|
+
export function calculateBaseAssetValueWithOracle(
|
|
96
96
|
market: MarketAccount,
|
|
97
97
|
marketPosition: UserPosition,
|
|
98
98
|
oraclePriceData: OraclePriceData
|
|
99
99
|
): BN {
|
|
100
|
-
|
|
101
|
-
marketPosition,
|
|
102
|
-
market,
|
|
103
|
-
oraclePriceData
|
|
104
|
-
);
|
|
105
|
-
const baseAssetValue = marketPosition.baseAssetAmount
|
|
100
|
+
return marketPosition.baseAssetAmount
|
|
106
101
|
.abs()
|
|
107
|
-
.mul(
|
|
102
|
+
.mul(oraclePriceData.price)
|
|
108
103
|
.div(AMM_TO_QUOTE_PRECISION_RATIO.mul(MARK_PRICE_PRECISION));
|
|
109
|
-
|
|
110
|
-
return baseAssetValue;
|
|
111
104
|
}
|
|
112
105
|
|
|
113
106
|
export function calculateWorstCaseBaseAssetAmount(
|
package/src/math/position.ts
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
getSwapDirection,
|
|
19
19
|
} from './amm';
|
|
20
20
|
|
|
21
|
-
import {
|
|
21
|
+
import { calculateBaseAssetValueWithOracle } from './margin';
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* calculateBaseAssetValue
|
|
@@ -99,7 +99,7 @@ export function calculatePositionPNL(
|
|
|
99
99
|
return marketPosition.quoteAssetAmount;
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
const baseAssetValue =
|
|
102
|
+
const baseAssetValue = calculateBaseAssetValueWithOracle(
|
|
103
103
|
market,
|
|
104
104
|
marketPosition,
|
|
105
105
|
oraclePriceData
|
package/src/types.ts
CHANGED
|
@@ -58,9 +58,6 @@ export class OrderAction {
|
|
|
58
58
|
|
|
59
59
|
export class OrderActionExplanation {
|
|
60
60
|
static readonly NONE = { none: {} };
|
|
61
|
-
static readonly BREACHED_MARGIN_REQUIREMENT = {
|
|
62
|
-
breachedMarginRequirement: {},
|
|
63
|
-
};
|
|
64
61
|
static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
|
|
65
62
|
oraclePriceBreachedLimitPrice: {},
|
|
66
63
|
};
|
|
@@ -151,15 +148,37 @@ export type CurveRecord = {
|
|
|
151
148
|
tradeId: BN;
|
|
152
149
|
};
|
|
153
150
|
|
|
151
|
+
export type LPRecord = {
|
|
152
|
+
ts: BN;
|
|
153
|
+
user: PublicKey;
|
|
154
|
+
action: LPAction;
|
|
155
|
+
nShares: BN;
|
|
156
|
+
marketIndex: BN;
|
|
157
|
+
deltaBaseAssetAmount: BN;
|
|
158
|
+
deltaQuoteAssetAmount: BN;
|
|
159
|
+
pnl: BN;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
export class LPAction {
|
|
163
|
+
static readonly ADD_LIQUIDITY = { addLiquidity: {} };
|
|
164
|
+
static readonly REMOVE_LIQUIDITY = { removeLiquidity: {} };
|
|
165
|
+
static readonly SETTLE_LIQUIDITY = { settleLiquidity: {} };
|
|
166
|
+
}
|
|
167
|
+
|
|
154
168
|
export type FundingRateRecord = {
|
|
155
169
|
ts: BN;
|
|
156
170
|
recordId: BN;
|
|
157
171
|
marketIndex: BN;
|
|
158
172
|
fundingRate: BN;
|
|
173
|
+
fundingRateLong: BN;
|
|
174
|
+
fundingRateShort: BN;
|
|
159
175
|
cumulativeFundingRateLong: BN;
|
|
160
176
|
cumulativeFundingRateShort: BN;
|
|
161
177
|
oraclePriceTwap: BN;
|
|
162
178
|
markPriceTwap: BN;
|
|
179
|
+
periodRevenue: BN;
|
|
180
|
+
netBaseAssetAmount: BN;
|
|
181
|
+
netUnsettledLpBaseAssetAmount: BN;
|
|
163
182
|
};
|
|
164
183
|
|
|
165
184
|
export type FundingPaymentRecord = {
|
|
@@ -214,6 +233,7 @@ export type LiquidatePerpRecord = {
|
|
|
214
233
|
oraclePrice: BN;
|
|
215
234
|
baseAssetAmount: BN;
|
|
216
235
|
quoteAssetAmount: BN;
|
|
236
|
+
lpShares: BN;
|
|
217
237
|
userPnl: BN;
|
|
218
238
|
liquidatorPnl: BN;
|
|
219
239
|
canceledOrdersFee: BN;
|
|
@@ -274,27 +294,41 @@ export type SettlePnlRecord = {
|
|
|
274
294
|
|
|
275
295
|
export type OrderRecord = {
|
|
276
296
|
ts: BN;
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
297
|
+
user: PublicKey;
|
|
298
|
+
order: Order;
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
export type OrderActionRecord = {
|
|
302
|
+
ts: BN;
|
|
283
303
|
action: OrderAction;
|
|
284
304
|
actionExplanation: OrderActionExplanation;
|
|
285
|
-
filler: PublicKey;
|
|
286
|
-
fillRecordId: BN;
|
|
287
305
|
marketIndex: BN;
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
306
|
+
filler: PublicKey | null;
|
|
307
|
+
fillerReward: BN | null;
|
|
308
|
+
fillRecordId: BN | null;
|
|
309
|
+
referrer: PublicKey | null;
|
|
310
|
+
baseAssetAmountFilled: BN | null;
|
|
311
|
+
quoteAssetAmountFilled: BN | null;
|
|
312
|
+
takerPnl: BN | null;
|
|
313
|
+
makerPnl: BN | null;
|
|
314
|
+
takerFee: BN | null;
|
|
315
|
+
makerRebate: BN | null;
|
|
316
|
+
referrerReward: BN | null;
|
|
317
|
+
refereeDiscount: BN | null;
|
|
318
|
+
quoteAssetAmountSurplus: BN | null;
|
|
319
|
+
taker: PublicKey | null;
|
|
320
|
+
takerOrderId: BN | null;
|
|
321
|
+
takerOrderBaseAssetAmount: BN | null;
|
|
322
|
+
takerOrderBaseAssetAmountFilled: BN | null;
|
|
323
|
+
takerOrderQuoteAssetAmountFilled: BN | null;
|
|
324
|
+
takerOrderFee: BN | null;
|
|
325
|
+
maker: PublicKey | null;
|
|
326
|
+
makerOrderId: BN | null;
|
|
327
|
+
makerOrderBaseAssetAmount: BN | null;
|
|
328
|
+
makerOrderBaseAssetAmountFilled: BN | null;
|
|
329
|
+
makerOrderQuoteAssetAmountFilled: BN | null;
|
|
330
|
+
makerOrderFee: BN | null;
|
|
294
331
|
oraclePrice: BN;
|
|
295
|
-
referrer: PublicKey;
|
|
296
|
-
referrerReward: BN;
|
|
297
|
-
refereeDiscount: BN;
|
|
298
332
|
};
|
|
299
333
|
|
|
300
334
|
export type StateAccount = {
|
|
@@ -303,8 +337,6 @@ export type StateAccount = {
|
|
|
303
337
|
exchangePaused: boolean;
|
|
304
338
|
adminControlsPrices: boolean;
|
|
305
339
|
insuranceVault: PublicKey;
|
|
306
|
-
insuranceVaultAuthority: PublicKey;
|
|
307
|
-
insuranceVaultNonce: number;
|
|
308
340
|
marginRatioInitial: BN;
|
|
309
341
|
marginRatioMaintenance: BN;
|
|
310
342
|
marginRatioPartial: BN;
|
|
@@ -326,6 +358,8 @@ export type StateAccount = {
|
|
|
326
358
|
numberOfMarkets: BN;
|
|
327
359
|
numberOfBanks: BN;
|
|
328
360
|
minOrderQuoteAssetAmount: BN;
|
|
361
|
+
signer: PublicKey;
|
|
362
|
+
signerNonce: number;
|
|
329
363
|
maxAuctionDuration: number;
|
|
330
364
|
minAuctionDuration: number;
|
|
331
365
|
};
|
|
@@ -355,8 +389,18 @@ export type BankAccount = {
|
|
|
355
389
|
pubkey: PublicKey;
|
|
356
390
|
mint: PublicKey;
|
|
357
391
|
vault: PublicKey;
|
|
358
|
-
|
|
359
|
-
|
|
392
|
+
|
|
393
|
+
insuranceFundVault: PublicKey;
|
|
394
|
+
insuranceWithdrawEscrowPeriod: BN;
|
|
395
|
+
revenuePool: PoolBalance;
|
|
396
|
+
|
|
397
|
+
totalIfShares: BN;
|
|
398
|
+
userIfShares: BN;
|
|
399
|
+
|
|
400
|
+
userIfFactor: BN;
|
|
401
|
+
totalIfFactor: BN;
|
|
402
|
+
liquidationIfFactor: BN;
|
|
403
|
+
|
|
360
404
|
decimals: number;
|
|
361
405
|
optimalUtilization: BN;
|
|
362
406
|
optimalBorrowRate: BN;
|
|
@@ -416,6 +460,7 @@ export type AMM = {
|
|
|
416
460
|
cumulativeFeePerLp: BN;
|
|
417
461
|
cumulativeNetBaseAssetAmountPerLp: BN;
|
|
418
462
|
userLpShares: BN;
|
|
463
|
+
netUnsettledLpBaseAssetAmount: BN;
|
|
419
464
|
minimumQuoteAssetTradeSize: BN;
|
|
420
465
|
baseAssetAmountStepSize: BN;
|
|
421
466
|
maxBaseAssetAmountRatio: number;
|
|
@@ -439,6 +484,7 @@ export type AMM = {
|
|
|
439
484
|
maxSpread: number;
|
|
440
485
|
marketPosition: UserPosition;
|
|
441
486
|
marketPositionPerLp: UserPosition;
|
|
487
|
+
ammJitIntensity: number;
|
|
442
488
|
maxBaseAssetReserve: BN;
|
|
443
489
|
minBaseAssetReserve: BN;
|
|
444
490
|
};
|
|
@@ -478,6 +524,7 @@ export type UserStatsAccount = {
|
|
|
478
524
|
isReferrer: boolean;
|
|
479
525
|
totalReferrerReward: BN;
|
|
480
526
|
authority: PublicKey;
|
|
527
|
+
quoteAssetInsuranceFundStake: BN;
|
|
481
528
|
};
|
|
482
529
|
|
|
483
530
|
export type UserAccount = {
|
|
@@ -664,3 +711,15 @@ export type OrderFillerRewardStructure = {
|
|
|
664
711
|
};
|
|
665
712
|
|
|
666
713
|
export type MarginCategory = 'Initial' | 'Maintenance';
|
|
714
|
+
|
|
715
|
+
export type InsuranceFundStake = {
|
|
716
|
+
bankIndex: BN;
|
|
717
|
+
authority: PublicKey;
|
|
718
|
+
|
|
719
|
+
ifShares: BN;
|
|
720
|
+
ifBase: BN;
|
|
721
|
+
|
|
722
|
+
lastWithdrawRequestShares: BN;
|
|
723
|
+
lastWithdrawRequestValue: BN;
|
|
724
|
+
lastWithdrawRequestTs: BN;
|
|
725
|
+
};
|
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.EventSubscriber = void 0;
|
|
13
|
-
const types_1 = require("./types");
|
|
14
|
-
const txEventCache_1 = require("./txEventCache");
|
|
15
|
-
const eventList_1 = require("./eventList");
|
|
16
|
-
const pollingLogProvider_1 = require("./pollingLogProvider");
|
|
17
|
-
const fetchLogs_1 = require("./fetchLogs");
|
|
18
|
-
const webSocketLogProvider_1 = require("./webSocketLogProvider");
|
|
19
|
-
const events_1 = require("events");
|
|
20
|
-
const sort_1 = require("./sort");
|
|
21
|
-
class EventSubscriber {
|
|
22
|
-
constructor(connection, program, options = types_1.DefaultEventSubscriptionOptions) {
|
|
23
|
-
this.connection = connection;
|
|
24
|
-
this.program = program;
|
|
25
|
-
this.options = options;
|
|
26
|
-
this.awaitTxPromises = new Map();
|
|
27
|
-
this.awaitTxResolver = new Map();
|
|
28
|
-
this.options = Object.assign({}, types_1.DefaultEventSubscriptionOptions, options);
|
|
29
|
-
this.txEventCache = new txEventCache_1.TxEventCache(this.options.maxTx);
|
|
30
|
-
this.eventListMap = new Map();
|
|
31
|
-
for (const eventType of this.options.eventTypes) {
|
|
32
|
-
this.eventListMap.set(eventType, new eventList_1.EventList(eventType, this.options.maxEventsPerType, sort_1.getSortFn(this.options.orderBy, this.options.orderDir, eventType), this.options.orderDir));
|
|
33
|
-
}
|
|
34
|
-
this.eventEmitter = new events_1.EventEmitter();
|
|
35
|
-
if (this.options.logProviderConfig.type === 'websocket') {
|
|
36
|
-
this.logProvider = new webSocketLogProvider_1.WebSocketLogProvider(this.connection, this.program.programId, this.options.commitment);
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
this.logProvider = new pollingLogProvider_1.PollingLogProvider(this.connection, this.program.programId, options.commitment, this.options.logProviderConfig.frequency);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
subscribe() {
|
|
43
|
-
if (this.logProvider.isSubscribed()) {
|
|
44
|
-
return true;
|
|
45
|
-
}
|
|
46
|
-
this.fetchPreviousTx().catch((e) => {
|
|
47
|
-
console.error('Error fetching previous txs in event subscriber');
|
|
48
|
-
console.error(e);
|
|
49
|
-
});
|
|
50
|
-
return this.logProvider.subscribe((txSig, slot, logs) => {
|
|
51
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
handleTxLogs(txSig, slot, logs) {
|
|
55
|
-
if (this.txEventCache.has(txSig)) {
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
const wrappedEvents = this.parseEventsFromLogs(txSig, slot, logs);
|
|
59
|
-
for (const wrappedEvent of wrappedEvents) {
|
|
60
|
-
this.eventListMap.get(wrappedEvent.eventType).insert(wrappedEvent);
|
|
61
|
-
this.eventEmitter.emit('newEvent', wrappedEvent);
|
|
62
|
-
}
|
|
63
|
-
if (this.awaitTxPromises.has(txSig)) {
|
|
64
|
-
this.awaitTxPromises.delete(txSig);
|
|
65
|
-
this.awaitTxResolver.get(txSig)();
|
|
66
|
-
this.awaitTxResolver.delete(txSig);
|
|
67
|
-
}
|
|
68
|
-
this.txEventCache.add(txSig, wrappedEvents);
|
|
69
|
-
}
|
|
70
|
-
fetchPreviousTx() {
|
|
71
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
72
|
-
if (!this.options.untilTx) {
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
let txFetched = 0;
|
|
76
|
-
let beforeTx = undefined;
|
|
77
|
-
const untilTx = this.options.untilTx;
|
|
78
|
-
while (txFetched < this.options.maxTx) {
|
|
79
|
-
const response = yield fetchLogs_1.fetchLogs(this.connection, this.program.programId, this.options.commitment === 'finalized' ? 'finalized' : 'confirmed', beforeTx, untilTx);
|
|
80
|
-
if (response === undefined) {
|
|
81
|
-
break;
|
|
82
|
-
}
|
|
83
|
-
txFetched += response.transactionLogs.length;
|
|
84
|
-
beforeTx = response.earliestTx;
|
|
85
|
-
for (const { txSig, slot, logs } of response.transactionLogs) {
|
|
86
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
unsubscribe() {
|
|
92
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
93
|
-
return yield this.logProvider.unsubscribe();
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
parseEventsFromLogs(txSig, slot, logs) {
|
|
97
|
-
const records = [];
|
|
98
|
-
// @ts-ignore
|
|
99
|
-
this.program._events._eventParser.parseLogs(logs, (event) => {
|
|
100
|
-
const expectRecordType = this.eventListMap.has(event.name);
|
|
101
|
-
if (expectRecordType) {
|
|
102
|
-
event.data.txSig = txSig;
|
|
103
|
-
event.data.slot = slot;
|
|
104
|
-
event.data.eventType = event.name;
|
|
105
|
-
records.push(event.data);
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
return records;
|
|
109
|
-
}
|
|
110
|
-
awaitTx(txSig) {
|
|
111
|
-
if (this.awaitTxPromises.has(txSig)) {
|
|
112
|
-
return this.awaitTxPromises.get(txSig);
|
|
113
|
-
}
|
|
114
|
-
if (this.txEventCache.has(txSig)) {
|
|
115
|
-
return Promise.resolve();
|
|
116
|
-
}
|
|
117
|
-
const promise = new Promise((resolve) => {
|
|
118
|
-
this.awaitTxResolver.set(txSig, resolve);
|
|
119
|
-
});
|
|
120
|
-
this.awaitTxPromises.set(txSig, promise);
|
|
121
|
-
return promise;
|
|
122
|
-
}
|
|
123
|
-
getEventList(eventType) {
|
|
124
|
-
return this.eventListMap.get(eventType);
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* This requires the EventList be cast to an array, which requires reallocation of memory.
|
|
128
|
-
* Would bias to using getEventList over getEvents
|
|
129
|
-
*
|
|
130
|
-
* @param eventType
|
|
131
|
-
*/
|
|
132
|
-
getEventsArray(eventType) {
|
|
133
|
-
return this.eventListMap.get(eventType).toArray();
|
|
134
|
-
}
|
|
135
|
-
getEventsByTx(txSig) {
|
|
136
|
-
return this.txEventCache.get(txSig);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
exports.EventSubscriber = EventSubscriber;
|
package/src/events/sort.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getSortFn = void 0;
|
|
4
|
-
const index_1 = require("../index");
|
|
5
|
-
function clientSortAscFn() {
|
|
6
|
-
return 'less than';
|
|
7
|
-
}
|
|
8
|
-
function clientSortDescFn() {
|
|
9
|
-
return 'greater than';
|
|
10
|
-
}
|
|
11
|
-
function defaultBlockchainSortFn(currentEvent, newEvent) {
|
|
12
|
-
return currentEvent.slot <= newEvent.slot ? 'less than' : 'greater than';
|
|
13
|
-
}
|
|
14
|
-
function orderRecordSortFn(currentEvent, newEvent) {
|
|
15
|
-
const currentEventMarketIndex = !currentEvent.maker.equals(index_1.PublicKey.default)
|
|
16
|
-
? currentEvent.makerOrder.marketIndex
|
|
17
|
-
: currentEvent.takerOrder.marketIndex;
|
|
18
|
-
const newEventMarketIndex = !newEvent.maker.equals(index_1.PublicKey.default)
|
|
19
|
-
? newEvent.makerOrder.marketIndex
|
|
20
|
-
: newEvent.takerOrder.marketIndex;
|
|
21
|
-
if (!currentEventMarketIndex.eq(newEventMarketIndex)) {
|
|
22
|
-
return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
|
|
23
|
-
}
|
|
24
|
-
if (currentEvent.fillRecordId.gt(index_1.ZERO) && newEvent.fillRecordId.gt(index_1.ZERO)) {
|
|
25
|
-
return currentEvent.fillRecordId.lte(newEvent.fillRecordId)
|
|
26
|
-
? 'less than'
|
|
27
|
-
: 'greater than';
|
|
28
|
-
}
|
|
29
|
-
else {
|
|
30
|
-
return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function getSortFn(orderBy, orderDir, eventType) {
|
|
34
|
-
if (orderBy === 'client') {
|
|
35
|
-
return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
|
|
36
|
-
}
|
|
37
|
-
switch (eventType) {
|
|
38
|
-
case 'OrderRecord':
|
|
39
|
-
return orderRecordSortFn;
|
|
40
|
-
default:
|
|
41
|
-
return defaultBlockchainSortFn;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
exports.getSortFn = getSortFn;
|