@drift-labs/sdk 0.2.0-master.0 → 0.2.0-master.11

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 (121) hide show
  1. package/lib/admin.d.ts +8 -5
  2. package/lib/admin.js +43 -11
  3. package/lib/clearingHouse.d.ts +28 -18
  4. package/lib/clearingHouse.js +366 -143
  5. package/lib/clearingHouseUser.d.ts +2 -2
  6. package/lib/clearingHouseUser.js +8 -17
  7. package/lib/config.js +1 -1
  8. package/lib/constants/banks.js +9 -2
  9. package/lib/constants/numericConstants.d.ts +2 -0
  10. package/lib/constants/numericConstants.js +3 -1
  11. package/lib/factory/bigNum.d.ts +8 -2
  12. package/lib/factory/bigNum.js +14 -6
  13. package/lib/idl/clearing_house.json +805 -202
  14. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  15. package/lib/index.d.ts +3 -2
  16. package/lib/index.js +7 -2
  17. package/lib/math/amm.d.ts +6 -1
  18. package/lib/math/amm.js +124 -41
  19. package/lib/math/auction.js +4 -1
  20. package/lib/math/orders.d.ts +2 -2
  21. package/lib/math/orders.js +18 -11
  22. package/lib/math/position.js +3 -1
  23. package/lib/math/repeg.js +1 -1
  24. package/lib/math/trade.d.ts +1 -1
  25. package/lib/math/trade.js +7 -10
  26. package/lib/orderParams.d.ts +14 -5
  27. package/lib/orderParams.js +8 -96
  28. package/lib/orders.d.ts +1 -2
  29. package/lib/orders.js +6 -85
  30. package/lib/slot/SlotSubscriber.d.ts +7 -0
  31. package/lib/slot/SlotSubscriber.js +3 -0
  32. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
  33. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
  34. package/lib/tx/utils.js +1 -1
  35. package/lib/types.d.ts +137 -14
  36. package/lib/types.js +53 -1
  37. package/lib/util/computeUnits.js +1 -1
  38. package/package.json +3 -3
  39. package/src/accounts/bulkAccountLoader.js +197 -0
  40. package/src/accounts/bulkUserSubscription.js +33 -0
  41. package/src/accounts/fetch.js +29 -0
  42. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  43. package/src/accounts/pollingOracleSubscriber.js +93 -0
  44. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  45. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  46. package/src/accounts/types.js +10 -0
  47. package/src/accounts/utils.js +7 -0
  48. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  49. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  50. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  51. package/src/addresses/marketAddresses.js +26 -0
  52. package/src/addresses/pda.js +104 -0
  53. package/src/admin.ts +66 -14
  54. package/src/assert/assert.js +9 -0
  55. package/src/clearingHouse.ts +558 -230
  56. package/src/clearingHouseUser.ts +12 -23
  57. package/src/config.ts +1 -1
  58. package/src/constants/banks.ts +9 -2
  59. package/src/constants/numericConstants.ts +2 -0
  60. package/src/events/eventList.js +77 -0
  61. package/src/events/eventSubscriber.js +139 -0
  62. package/src/events/fetchLogs.js +50 -0
  63. package/src/events/pollingLogProvider.js +64 -0
  64. package/src/events/sort.js +44 -0
  65. package/src/events/txEventCache.js +71 -0
  66. package/src/events/types.js +20 -0
  67. package/src/events/webSocketLogProvider.js +41 -0
  68. package/src/examples/makeTradeExample.js +80 -0
  69. package/src/factory/bigNum.js +364 -0
  70. package/src/factory/bigNum.ts +26 -9
  71. package/src/factory/oracleClient.js +20 -0
  72. package/src/idl/clearing_house.json +805 -202
  73. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  74. package/src/index.js +100 -0
  75. package/src/index.ts +3 -2
  76. package/src/math/amm.js +369 -0
  77. package/src/math/amm.ts +207 -52
  78. package/src/math/auction.js +42 -0
  79. package/src/math/auction.ts +5 -1
  80. package/src/math/bankBalance.js +75 -0
  81. package/src/math/conversion.js +11 -0
  82. package/src/math/funding.js +248 -0
  83. package/src/math/market.js +57 -0
  84. package/src/math/oracles.js +26 -0
  85. package/src/math/orders.js +110 -0
  86. package/src/math/orders.ts +17 -13
  87. package/src/math/position.js +140 -0
  88. package/src/math/position.ts +5 -1
  89. package/src/math/repeg.js +128 -0
  90. package/src/math/repeg.ts +2 -1
  91. package/src/math/state.js +15 -0
  92. package/src/math/trade.js +253 -0
  93. package/src/math/trade.ts +23 -25
  94. package/src/math/utils.js +0 -1
  95. package/src/mockUSDCFaucet.js +280 -0
  96. package/src/oracles/oracleClientCache.js +19 -0
  97. package/src/oracles/pythClient.js +46 -0
  98. package/src/oracles/quoteAssetOracleClient.js +32 -0
  99. package/src/oracles/switchboardClient.js +69 -0
  100. package/src/oracles/types.js +2 -0
  101. package/src/orderParams.js +20 -0
  102. package/src/orderParams.ts +20 -141
  103. package/src/orders.js +134 -0
  104. package/src/orders.ts +7 -131
  105. package/src/slot/SlotSubscriber.js +39 -0
  106. package/src/slot/SlotSubscriber.ts +11 -1
  107. package/src/token/index.js +38 -0
  108. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
  109. package/src/tx/retryTxSender.js +188 -0
  110. package/src/tx/types.js +2 -0
  111. package/src/tx/utils.js +17 -0
  112. package/src/tx/utils.ts +1 -1
  113. package/src/types.js +114 -0
  114. package/src/types.ts +132 -16
  115. package/src/userName.js +20 -0
  116. package/src/util/computeUnits.ts +1 -1
  117. package/src/util/promiseTimeout.js +14 -0
  118. package/src/util/tps.js +27 -0
  119. package/src/wallet.js +35 -0
  120. package/src/util/computeUnits.js +0 -17
  121. package/src/util/computeUnits.js.map +0 -1
@@ -205,7 +205,7 @@ export class ClearingHouseUser {
205
205
  /**
206
206
  * @returns The partial margin requirement in USDC. : QUOTE_PRECISION
207
207
  */
208
- public getPartialMarginRequirement(): BN {
208
+ public getMaintenanceMarginRequirement(): BN {
209
209
  return this.getUserAccount()
210
210
  .positions.reduce((marginRequirement, marketPosition) => {
211
211
  const market = this.clearingHouse.getMarketAccount(
@@ -217,7 +217,7 @@ export class ClearingHouseUser {
217
217
  marketPosition,
218
218
  this.getOracleDataForMarket(market.marketIndex)
219
219
  )
220
- .mul(new BN(market.marginRatioPartial))
220
+ .mul(new BN(market.marginRatioMaintenance))
221
221
  .div(MARGIN_PRECISION)
222
222
  );
223
223
  }, ZERO)
@@ -514,9 +514,6 @@ export class ClearingHouseUser {
514
514
  case 'Maintenance':
515
515
  marginRatioCategory = market.marginRatioMaintenance;
516
516
  break;
517
- case 'Partial':
518
- marginRatioCategory = market.marginRatioPartial;
519
- break;
520
517
  default:
521
518
  marginRatioCategory = market.marginRatioInitial;
522
519
  break;
@@ -543,7 +540,8 @@ export class ClearingHouseUser {
543
540
 
544
541
  public canBeLiquidated(): [boolean, BN] {
545
542
  const totalCollateral = this.getTotalCollateral();
546
- const partialMaintenanceRequirement = this.getPartialMarginRequirement();
543
+ const partialMaintenanceRequirement =
544
+ this.getMaintenanceMarginRequirement();
547
545
  const marginRatio = this.getMarginRatio();
548
546
  const canLiquidate = totalCollateral.lt(partialMaintenanceRequirement);
549
547
  return [canLiquidate, marginRatio];
@@ -587,8 +585,7 @@ export class ClearingHouseUser {
587
585
  */
588
586
  public liquidationPrice(
589
587
  marketPosition: Pick<UserPosition, 'marketIndex'>,
590
- positionBaseSizeChange: BN = ZERO,
591
- partial = false
588
+ positionBaseSizeChange: BN = ZERO
592
589
  ): BN {
593
590
  // solves formula for example canBeLiquidated below
594
591
 
@@ -661,11 +658,7 @@ export class ClearingHouseUser {
661
658
  this.getOracleDataForMarket(market.marketIndex)
662
659
  );
663
660
  const marketMarginRequirement = positionValue
664
- .mul(
665
- partial
666
- ? new BN(market.marginRatioPartial)
667
- : new BN(market.marginRatioMaintenance)
668
- )
661
+ .mul(new BN(market.marginRatioMaintenance))
669
662
  .div(MARGIN_PRECISION);
670
663
  totalMarginRequirement = totalMarginRequirement.add(
671
664
  marketMarginRequirement
@@ -691,20 +684,17 @@ export class ClearingHouseUser {
691
684
  const marginRequirementAfterTrade =
692
685
  marginRequirementExcludingTargetMarket.add(
693
686
  proposedMarketPositionValue
694
- .mul(
695
- partial
696
- ? new BN(market.marginRatioPartial)
697
- : new BN(market.marginRatioMaintenance)
698
- )
687
+ .mul(new BN(market.marginRatioMaintenance))
699
688
  .div(MARGIN_PRECISION)
700
689
  );
701
690
  const freeCollateralAfterTrade = totalCollateral.sub(
702
691
  marginRequirementAfterTrade
703
692
  );
704
693
 
705
- const marketMaxLeverage = partial
706
- ? this.getMaxLeverage(proposedMarketPosition.marketIndex, 'Partial')
707
- : this.getMaxLeverage(proposedMarketPosition.marketIndex, 'Maintenance');
694
+ const marketMaxLeverage = this.getMaxLeverage(
695
+ proposedMarketPosition.marketIndex,
696
+ 'Maintenance'
697
+ );
708
698
 
709
699
  let priceDelta;
710
700
  if (proposedBaseAssetAmount.lt(ZERO)) {
@@ -777,8 +767,7 @@ export class ClearingHouseUser {
777
767
  {
778
768
  marketIndex: positionMarketIndex,
779
769
  },
780
- closeBaseAmount,
781
- true
770
+ closeBaseAmount
782
771
  );
783
772
  }
784
773
 
package/src/config.ts CHANGED
@@ -28,7 +28,7 @@ export const configs: { [key in DriftEnv]: DriftConfig } = {
28
28
  devnet: {
29
29
  ENV: 'devnet',
30
30
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
31
- CLEARING_HOUSE_PROGRAM_ID: 'GCuH76fb1rXc7bjFXNcnNvWSekLgzpsnMbc1Ng4FsGSs',
31
+ CLEARING_HOUSE_PROGRAM_ID: '4oyTJnAQ9FqJj1y9mPytbWsLeeHmBzGYfuFqypwyQvuh',
32
32
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
33
33
  MARKETS: DevnetMarkets,
34
34
  BANKS: DevnetBanks,
@@ -19,11 +19,18 @@ export const DevnetBanks: BankConfig[] = [
19
19
  mint: new PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
20
20
  },
21
21
  {
22
- symbol: 'BTC',
22
+ symbol: 'SOL',
23
23
  bankIndex: new BN(1),
24
+ oracle: new PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
25
+ oracleSource: OracleSource.PYTH,
26
+ mint: new PublicKey('So11111111111111111111111111111111111111112'),
27
+ },
28
+ {
29
+ symbol: 'BTC',
30
+ bankIndex: new BN(2),
24
31
  oracle: new PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
25
32
  oracleSource: OracleSource.PYTH,
26
- mint: new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr'),
33
+ mint: new PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
27
34
  },
28
35
  ];
29
36
 
@@ -28,6 +28,7 @@ export const BANK_BALANCE_PRECISION_EXP = new BN(6);
28
28
  export const BANK_BALANCE_PRECISION = new BN(10).pow(
29
29
  BANK_BALANCE_PRECISION_EXP
30
30
  );
31
+ export const LIQUIDATION_FEE_PRECISION = new BN(1000000);
31
32
 
32
33
  export const QUOTE_PRECISION = new BN(10).pow(QUOTE_PRECISION_EXP);
33
34
  export const MARK_PRICE_PRECISION = new BN(10).pow(MARK_PRICE_PRECISION_EXP);
@@ -43,6 +44,7 @@ export const BASE_PRECISION_EXP = AMM_RESERVE_PRECISION_EXP;
43
44
 
44
45
  export const AMM_TO_QUOTE_PRECISION_RATIO =
45
46
  AMM_RESERVE_PRECISION.div(QUOTE_PRECISION); // 10^7
47
+ export const PRICE_DIV_PEG = MARK_PRICE_PRECISION.div(PEG_PRECISION); //10^7
46
48
  export const PRICE_TO_QUOTE_PRECISION =
47
49
  MARK_PRICE_PRECISION.div(QUOTE_PRECISION);
48
50
  export const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO =
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventList = void 0;
4
+ class Node {
5
+ constructor(event, next, prev) {
6
+ this.event = event;
7
+ this.next = next;
8
+ this.prev = prev;
9
+ }
10
+ }
11
+ class EventList {
12
+ constructor(eventType, maxSize, sortFn, orderDirection) {
13
+ this.eventType = eventType;
14
+ this.maxSize = maxSize;
15
+ this.sortFn = sortFn;
16
+ this.orderDirection = orderDirection;
17
+ this.size = 0;
18
+ }
19
+ insert(event) {
20
+ this.size++;
21
+ const newNode = new Node(event);
22
+ if (this.head === undefined) {
23
+ this.head = this.tail = newNode;
24
+ return;
25
+ }
26
+ if (this.sortFn(this.head.event, newNode.event) ===
27
+ (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
28
+ this.head.prev = newNode;
29
+ newNode.next = this.head;
30
+ this.head = newNode;
31
+ }
32
+ else {
33
+ let currentNode = this.head;
34
+ while (currentNode.next !== undefined &&
35
+ this.sortFn(currentNode.next.event, newNode.event) !==
36
+ (this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
37
+ currentNode = currentNode.next;
38
+ }
39
+ newNode.next = currentNode.next;
40
+ if (currentNode.next !== undefined) {
41
+ newNode.next.prev = newNode;
42
+ }
43
+ currentNode.next = newNode;
44
+ newNode.prev = currentNode;
45
+ }
46
+ if (this.size > this.maxSize) {
47
+ this.detach();
48
+ }
49
+ }
50
+ detach() {
51
+ const node = this.tail;
52
+ if (node.prev !== undefined) {
53
+ node.prev.next = node.next;
54
+ }
55
+ else {
56
+ this.head = node.next;
57
+ }
58
+ if (node.next !== undefined) {
59
+ node.next.prev = node.prev;
60
+ }
61
+ else {
62
+ this.tail = node.prev;
63
+ }
64
+ this.size--;
65
+ }
66
+ toArray() {
67
+ return Array.from(this);
68
+ }
69
+ *[Symbol.iterator]() {
70
+ let node = this.head;
71
+ while (node) {
72
+ yield node.event;
73
+ node = node.next;
74
+ }
75
+ }
76
+ }
77
+ exports.EventList = EventList;
@@ -0,0 +1,139 @@
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;
@@ -0,0 +1,50 @@
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.fetchLogs = void 0;
13
+ function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const signatures = yield connection.getSignaturesForAddress(programId, {
16
+ before: beforeTx,
17
+ until: untilTx,
18
+ }, finality);
19
+ const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
20
+ const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
21
+ if (filteredSignatures.length === 0) {
22
+ return undefined;
23
+ }
24
+ const chunkedSignatures = chunk(filteredSignatures, 100);
25
+ const transactionLogs = (yield Promise.all(chunkedSignatures.map((chunk) => __awaiter(this, void 0, void 0, function* () {
26
+ const transactions = yield connection.getTransactions(chunk.map((confirmedSignature) => confirmedSignature.signature), finality);
27
+ return transactions.map((transaction) => {
28
+ return {
29
+ txSig: transaction.transaction.signatures[0],
30
+ slot: transaction.slot,
31
+ logs: transaction.meta.logMessages,
32
+ };
33
+ });
34
+ })))).flat();
35
+ const earliestTx = filteredSignatures[0].signature;
36
+ const mostRecentTx = filteredSignatures[filteredSignatures.length - 1].signature;
37
+ return {
38
+ transactionLogs: transactionLogs,
39
+ earliestTx: earliestTx,
40
+ mostRecentTx: mostRecentTx,
41
+ };
42
+ });
43
+ }
44
+ exports.fetchLogs = fetchLogs;
45
+ function chunk(array, size) {
46
+ return new Array(Math.ceil(array.length / size))
47
+ .fill(null)
48
+ .map((_, index) => index * size)
49
+ .map((begin) => array.slice(begin, begin + size));
50
+ }
@@ -0,0 +1,64 @@
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.PollingLogProvider = void 0;
13
+ const fetchLogs_1 = require("./fetchLogs");
14
+ class PollingLogProvider {
15
+ constructor(connection, programId, commitment, frequency = 15 * 1000) {
16
+ this.connection = connection;
17
+ this.programId = programId;
18
+ this.frequency = frequency;
19
+ this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
20
+ }
21
+ subscribe(callback) {
22
+ if (this.intervalId) {
23
+ return true;
24
+ }
25
+ this.intervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
26
+ if (this.mutex === 1) {
27
+ return;
28
+ }
29
+ this.mutex = 1;
30
+ try {
31
+ const response = yield fetchLogs_1.fetchLogs(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx);
32
+ if (response === undefined) {
33
+ return;
34
+ }
35
+ const { mostRecentTx, transactionLogs } = response;
36
+ for (const { txSig, slot, logs } of transactionLogs) {
37
+ callback(txSig, slot, logs);
38
+ }
39
+ this.mostRecentSeenTx = mostRecentTx;
40
+ }
41
+ catch (e) {
42
+ console.error('PollingLogProvider threw an Error');
43
+ console.error(e);
44
+ }
45
+ finally {
46
+ this.mutex = 0;
47
+ }
48
+ }), this.frequency);
49
+ return true;
50
+ }
51
+ isSubscribed() {
52
+ return this.intervalId !== undefined;
53
+ }
54
+ unsubscribe() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ if (this.intervalId !== undefined) {
57
+ clearInterval(this.intervalId);
58
+ this.intervalId = undefined;
59
+ }
60
+ return true;
61
+ });
62
+ }
63
+ }
64
+ exports.PollingLogProvider = PollingLogProvider;
@@ -0,0 +1,44 @@
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;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TxEventCache = void 0;
4
+ class Node {
5
+ constructor(key, value, next, prev) {
6
+ this.key = key;
7
+ this.value = value;
8
+ this.next = next;
9
+ this.prev = prev;
10
+ }
11
+ }
12
+ // lru cache
13
+ class TxEventCache {
14
+ constructor(maxTx = 1024) {
15
+ this.maxTx = maxTx;
16
+ this.size = 0;
17
+ this.cacheMap = {};
18
+ }
19
+ add(key, events) {
20
+ const existingNode = this.cacheMap[key];
21
+ if (existingNode) {
22
+ this.detach(existingNode);
23
+ this.size--;
24
+ }
25
+ else if (this.size === this.maxTx) {
26
+ delete this.cacheMap[this.tail.key];
27
+ this.detach(this.tail);
28
+ this.size--;
29
+ }
30
+ // Write to head of LinkedList
31
+ if (!this.head) {
32
+ this.head = this.tail = new Node(key, events);
33
+ }
34
+ else {
35
+ const node = new Node(key, events, this.head);
36
+ this.head.prev = node;
37
+ this.head = node;
38
+ }
39
+ // update cacheMap with LinkedList key and Node reference
40
+ this.cacheMap[key] = this.head;
41
+ this.size++;
42
+ }
43
+ has(key) {
44
+ return this.cacheMap.hasOwnProperty(key);
45
+ }
46
+ get(key) {
47
+ var _a;
48
+ return (_a = this.cacheMap[key]) === null || _a === void 0 ? void 0 : _a.value;
49
+ }
50
+ detach(node) {
51
+ if (node.prev !== undefined) {
52
+ node.prev.next = node.next;
53
+ }
54
+ else {
55
+ this.head = node.next;
56
+ }
57
+ if (node.next !== undefined) {
58
+ node.next.prev = node.prev;
59
+ }
60
+ else {
61
+ this.tail = node.prev;
62
+ }
63
+ }
64
+ clear() {
65
+ this.head = undefined;
66
+ this.tail = undefined;
67
+ this.size = 0;
68
+ this.cacheMap = {};
69
+ }
70
+ }
71
+ exports.TxEventCache = TxEventCache;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultEventSubscriptionOptions = void 0;
4
+ exports.DefaultEventSubscriptionOptions = {
5
+ eventTypes: [
6
+ 'DepositRecord',
7
+ 'FundingPaymentRecord',
8
+ 'LiquidationRecord',
9
+ 'OrderRecord',
10
+ 'FundingRateRecord',
11
+ ],
12
+ maxEventsPerType: 4096,
13
+ orderBy: 'blockchain',
14
+ orderDir: 'asc',
15
+ commitment: 'confirmed',
16
+ maxTx: 4096,
17
+ logProviderConfig: {
18
+ type: 'websocket',
19
+ },
20
+ };
@@ -0,0 +1,41 @@
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.WebSocketLogProvider = void 0;
13
+ class WebSocketLogProvider {
14
+ constructor(connection, programId, commitment) {
15
+ this.connection = connection;
16
+ this.programId = programId;
17
+ this.commitment = commitment;
18
+ }
19
+ subscribe(callback) {
20
+ if (this.subscriptionId) {
21
+ return true;
22
+ }
23
+ this.subscriptionId = this.connection.onLogs(this.programId, (logs, ctx) => {
24
+ callback(logs.signature, ctx.slot, logs.logs);
25
+ }, this.commitment);
26
+ return true;
27
+ }
28
+ isSubscribed() {
29
+ return this.subscriptionId !== undefined;
30
+ }
31
+ unsubscribe() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ if (this.subscriptionId !== undefined) {
34
+ yield this.connection.removeOnLogsListener(this.subscriptionId);
35
+ this.subscriptionId = undefined;
36
+ }
37
+ return true;
38
+ });
39
+ }
40
+ }
41
+ exports.WebSocketLogProvider = WebSocketLogProvider;