@drift-labs/sdk 2.82.0-beta.2 → 2.82.0-beta.20

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 (127) hide show
  1. package/README.md +65 -47
  2. package/VERSION +1 -1
  3. package/lib/accounts/types.d.ts +4 -3
  4. package/lib/accounts/webSocketAccountSubscriber.d.ts +3 -3
  5. package/lib/accounts/webSocketAccountSubscriber.js +16 -9
  6. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +3 -3
  7. package/lib/accounts/webSocketDriftClientAccountSubscriber.js +5 -5
  8. package/lib/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +2 -2
  9. package/lib/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +5 -3
  10. package/lib/accounts/webSocketProgramAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/webSocketProgramAccountSubscriber.js +15 -9
  12. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +3 -3
  13. package/lib/accounts/webSocketUserAccountSubscriber.js +3 -3
  14. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +3 -3
  15. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +3 -3
  16. package/lib/auctionSubscriber/auctionSubscriber.d.ts +2 -2
  17. package/lib/auctionSubscriber/auctionSubscriber.js +3 -3
  18. package/lib/auctionSubscriber/types.d.ts +1 -0
  19. package/lib/clock/clockSubscriber.d.ts +29 -0
  20. package/lib/clock/clockSubscriber.js +74 -0
  21. package/lib/constants/perpMarkets.js +2 -2
  22. package/lib/constants/spotMarkets.js +11 -0
  23. package/lib/dlob/DLOB.js +2 -2
  24. package/lib/dlob/orderBookLevels.js +1 -0
  25. package/lib/driftClient.d.ts +21 -14
  26. package/lib/driftClient.js +192 -255
  27. package/lib/driftClientConfig.d.ts +3 -0
  28. package/lib/index.d.ts +2 -0
  29. package/lib/index.js +2 -0
  30. package/lib/jupiter/jupiterClient.d.ts +2 -1
  31. package/lib/jupiter/jupiterClient.js +10 -6
  32. package/lib/math/exchangeStatus.d.ts +2 -2
  33. package/lib/math/orders.d.ts +1 -1
  34. package/lib/math/orders.js +2 -2
  35. package/lib/orderSubscriber/OrderSubscriber.js +6 -3
  36. package/lib/orderSubscriber/WebsocketSubscription.d.ts +4 -3
  37. package/lib/orderSubscriber/WebsocketSubscription.js +3 -3
  38. package/lib/orderSubscriber/types.d.ts +1 -0
  39. package/lib/priorityFee/driftPriorityFeeMethod.d.ts +13 -3
  40. package/lib/priorityFee/driftPriorityFeeMethod.js +2 -2
  41. package/lib/priorityFee/index.d.ts +2 -0
  42. package/lib/priorityFee/index.js +2 -0
  43. package/lib/priorityFee/priorityFeeSubscriber.d.ts +1 -4
  44. package/lib/priorityFee/priorityFeeSubscriber.js +5 -4
  45. package/lib/priorityFee/priorityFeeSubscriberMap.d.ts +48 -0
  46. package/lib/priorityFee/priorityFeeSubscriberMap.js +88 -0
  47. package/lib/priorityFee/types.d.ts +8 -3
  48. package/lib/priorityFee/types.js +2 -1
  49. package/lib/tx/baseTxSender.d.ts +8 -6
  50. package/lib/tx/baseTxSender.js +9 -51
  51. package/lib/tx/fastSingleTxSender.d.ts +6 -6
  52. package/lib/tx/fastSingleTxSender.js +3 -31
  53. package/lib/tx/forwardOnlyTxSender.d.ts +4 -2
  54. package/lib/tx/forwardOnlyTxSender.js +2 -1
  55. package/lib/tx/retryTxSender.d.ts +4 -2
  56. package/lib/tx/retryTxSender.js +2 -1
  57. package/lib/tx/txHandler.d.ts +138 -0
  58. package/lib/tx/txHandler.js +396 -0
  59. package/lib/tx/txParamProcessor.d.ts +6 -10
  60. package/lib/tx/txParamProcessor.js +13 -17
  61. package/lib/tx/types.d.ts +8 -7
  62. package/lib/tx/types.js +12 -1
  63. package/lib/tx/whileValidTxSender.d.ts +7 -6
  64. package/lib/tx/whileValidTxSender.js +7 -28
  65. package/lib/types.d.ts +24 -4
  66. package/lib/types.js +10 -1
  67. package/lib/user.d.ts +0 -10
  68. package/lib/user.js +6 -29
  69. package/lib/userConfig.d.ts +1 -0
  70. package/lib/userMap/WebsocketSubscription.d.ts +4 -3
  71. package/lib/userMap/WebsocketSubscription.js +3 -3
  72. package/lib/userMap/userMap.js +4 -1
  73. package/lib/userMap/userMapConfig.d.ts +1 -0
  74. package/lib/userStats.js +6 -3
  75. package/lib/userStatsConfig.d.ts +1 -0
  76. package/lib/util/chainClock.d.ts +17 -0
  77. package/lib/util/chainClock.js +29 -0
  78. package/package.json +3 -3
  79. package/src/accounts/types.ts +5 -4
  80. package/src/accounts/webSocketAccountSubscriber.ts +35 -23
  81. package/src/accounts/webSocketDriftClientAccountSubscriber.ts +7 -6
  82. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +6 -4
  83. package/src/accounts/webSocketProgramAccountSubscriber.ts +32 -22
  84. package/src/accounts/webSocketUserAccountSubscriber.ts +5 -4
  85. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +5 -4
  86. package/src/auctionSubscriber/auctionSubscriber.ts +10 -4
  87. package/src/auctionSubscriber/types.ts +1 -0
  88. package/src/clock/clockSubscriber.ts +113 -0
  89. package/src/constants/perpMarkets.ts +2 -2
  90. package/src/constants/spotMarkets.ts +13 -0
  91. package/src/dlob/DLOB.ts +2 -2
  92. package/src/dlob/orderBookLevels.ts +2 -0
  93. package/src/driftClient.ts +295 -386
  94. package/src/driftClientConfig.ts +3 -0
  95. package/src/index.ts +2 -0
  96. package/src/jupiter/jupiterClient.ts +15 -6
  97. package/src/math/exchangeStatus.ts +2 -1
  98. package/src/math/orders.ts +3 -2
  99. package/src/orderSubscriber/OrderSubscriber.ts +4 -1
  100. package/src/orderSubscriber/WebsocketSubscription.ts +6 -5
  101. package/src/orderSubscriber/types.ts +1 -0
  102. package/src/priorityFee/driftPriorityFeeMethod.ts +16 -4
  103. package/src/priorityFee/index.ts +2 -0
  104. package/src/priorityFee/priorityFeeSubscriber.ts +7 -7
  105. package/src/priorityFee/priorityFeeSubscriberMap.ts +112 -0
  106. package/src/priorityFee/types.ts +16 -3
  107. package/src/tx/baseTxSender.ts +29 -79
  108. package/src/tx/fastSingleTxSender.ts +10 -55
  109. package/src/tx/forwardOnlyTxSender.ts +5 -1
  110. package/src/tx/retryTxSender.ts +5 -1
  111. package/src/tx/txHandler.ts +625 -0
  112. package/src/tx/txParamProcessor.ts +16 -28
  113. package/src/tx/types.ts +14 -18
  114. package/src/tx/whileValidTxSender.ts +24 -48
  115. package/src/types.ts +26 -2
  116. package/src/user.ts +7 -32
  117. package/src/userConfig.ts +1 -0
  118. package/src/userMap/WebsocketSubscription.ts +6 -5
  119. package/src/userMap/userMap.ts +4 -1
  120. package/src/userMap/userMapConfig.ts +1 -0
  121. package/src/userStats.ts +4 -1
  122. package/src/userStatsConfig.ts +1 -0
  123. package/src/util/chainClock.ts +41 -0
  124. package/tests/dlob/helpers.ts +3 -0
  125. package/lib/tx/utils.d.ts +0 -6
  126. package/lib/tx/utils.js +0 -39
  127. package/src/tx/utils.ts +0 -64
package/lib/index.d.ts CHANGED
@@ -101,4 +101,6 @@ export * from './auctionSubscriber/types';
101
101
  export * from './memcmp';
102
102
  export * from './decode/user';
103
103
  export * from './blockhashSubscriber';
104
+ export * from './util/chainClock';
105
+ export * from './clock/clockSubscriber';
104
106
  export { BN, PublicKey, pyth };
package/lib/index.js CHANGED
@@ -124,3 +124,5 @@ __exportStar(require("./auctionSubscriber/types"), exports);
124
124
  __exportStar(require("./memcmp"), exports);
125
125
  __exportStar(require("./decode/user"), exports);
126
126
  __exportStar(require("./blockhashSubscriber"), exports);
127
+ __exportStar(require("./util/chainClock"), exports);
128
+ __exportStar(require("./clock/clockSubscriber"), exports);
@@ -206,8 +206,9 @@ export declare class JupiterClient {
206
206
  url: string;
207
207
  connection: Connection;
208
208
  lookupTableCahce: Map<string, AddressLookupTableAccount>;
209
- constructor({ connection }: {
209
+ constructor({ connection, url }: {
210
210
  connection: Connection;
211
+ url?: string;
211
212
  });
212
213
  /**
213
214
  * ** @deprecated - use getQuote
@@ -7,10 +7,10 @@ exports.JupiterClient = void 0;
7
7
  const web3_js_1 = require("@solana/web3.js");
8
8
  const node_fetch_1 = __importDefault(require("node-fetch"));
9
9
  class JupiterClient {
10
- constructor({ connection }) {
11
- this.url = 'https://quote-api.jup.ag';
10
+ constructor({ connection, url }) {
12
11
  this.lookupTableCahce = new Map();
13
12
  this.connection = connection;
13
+ this.url = url !== null && url !== void 0 ? url : 'https://quote-api.jup.ag';
14
14
  }
15
15
  /**
16
16
  * ** @deprecated - use getQuote
@@ -31,7 +31,8 @@ class JupiterClient {
31
31
  swapMode,
32
32
  onlyDirectRoutes: onlyDirectRoutes.toString(),
33
33
  }).toString();
34
- const { data: routes } = await (await (0, node_fetch_1.default)(`${this.url}/v4/quote?${params}`)).json();
34
+ const apiVersionParam = this.url === 'https://quote-api.jup.ag' ? '/v4' : '';
35
+ const { data: routes } = await (await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/quote?${params}`)).json();
35
36
  return routes;
36
37
  }
37
38
  /**
@@ -58,7 +59,8 @@ class JupiterClient {
58
59
  if (swapMode === 'ExactOut') {
59
60
  params.delete('maxAccounts');
60
61
  }
61
- const quote = await (await (0, node_fetch_1.default)(`${this.url}/v6/quote?${params.toString()}`)).json();
62
+ const apiVersionParam = this.url === 'https://quote-api.jup.ag' ? '/v6' : '';
63
+ const quote = await (await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/quote?${params.toString()}`)).json();
62
64
  return quote;
63
65
  }
64
66
  /**
@@ -72,7 +74,8 @@ class JupiterClient {
72
74
  if (!quote) {
73
75
  throw new Error('Jupiter swap quote not provided. Please try again.');
74
76
  }
75
- const resp = await (await (0, node_fetch_1.default)(`${this.url}/v6/swap`, {
77
+ const apiVersionParam = this.url === 'https://quote-api.jup.ag' ? '/v6' : '';
78
+ const resp = await (await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/swap`, {
76
79
  method: 'POST',
77
80
  headers: {
78
81
  'Content-Type': 'application/json',
@@ -103,7 +106,8 @@ class JupiterClient {
103
106
  * @param slippageBps the slippage tolerance in basis points
104
107
  */
105
108
  async getSwapTransaction({ route, userPublicKey, slippageBps = 50, }) {
106
- const resp = await (await (0, node_fetch_1.default)(`${this.url}/v4/swap`, {
109
+ const apiVersionParam = this.url === 'https://quote-api.jup.ag' ? '/v4' : '';
110
+ const resp = await (await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/swap`, {
107
111
  method: 'POST',
108
112
  headers: {
109
113
  'Content-Type': 'application/json',
@@ -1,6 +1,6 @@
1
- import { PerpMarketAccount, PerpOperation, SpotMarketAccount, SpotOperation, StateAccount } from '../types';
1
+ import { PerpMarketAccount, PerpOperation, SpotMarketAccount, SpotOperation, StateAccount, InsuranceFundOperation } from '../types';
2
2
  export declare function exchangePaused(state: StateAccount): boolean;
3
3
  export declare function fillPaused(state: StateAccount, market: PerpMarketAccount | SpotMarketAccount): boolean;
4
4
  export declare function ammPaused(state: StateAccount, market: PerpMarketAccount | SpotMarketAccount): boolean;
5
- export declare function isOperationPaused(pausedOperations: number, operation: PerpOperation | SpotOperation): boolean;
5
+ export declare function isOperationPaused(pausedOperations: number, operation: PerpOperation | SpotOperation | InsuranceFundOperation): boolean;
6
6
  export declare function isAmmDrawdownPause(market: PerpMarketAccount): boolean;
@@ -14,7 +14,7 @@ export declare function hasAuctionPrice(order: Order, slot: number): boolean;
14
14
  export declare function isFillableByVAMM(order: Order, market: PerpMarketAccount, oraclePriceData: OraclePriceData, slot: number, ts: number, minAuctionDuration: number): boolean;
15
15
  export declare function calculateBaseAssetAmountForAmmToFulfill(order: Order, market: PerpMarketAccount, oraclePriceData: OraclePriceData, slot: number): BN;
16
16
  export declare function calculateBaseAssetAmountToFillUpToLimitPrice(order: Order, amm: AMM, limitPrice: BN, oraclePriceData: OraclePriceData): BN;
17
- export declare function isOrderExpired(order: Order, ts: number, enforceBuffer?: boolean): boolean;
17
+ export declare function isOrderExpired(order: Order, ts: number, enforceBuffer?: boolean, bufferSeconds?: number): boolean;
18
18
  export declare function isMarketOrder(order: Order): boolean;
19
19
  export declare function isLimitOrder(order: Order): boolean;
20
20
  export declare function mustBeTriggered(order: Order): boolean;
@@ -168,7 +168,7 @@ function isSameDirection(firstDirection, secondDirection) {
168
168
  return (((0, types_1.isVariant)(firstDirection, 'long') && (0, types_1.isVariant)(secondDirection, 'long')) ||
169
169
  ((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
170
170
  }
171
- function isOrderExpired(order, ts, enforceBuffer = false) {
171
+ function isOrderExpired(order, ts, enforceBuffer = false, bufferSeconds = 15) {
172
172
  if (mustBeTriggered(order) ||
173
173
  !(0, types_1.isVariant)(order.status, 'open') ||
174
174
  order.maxTs.eq(numericConstants_1.ZERO)) {
@@ -176,7 +176,7 @@ function isOrderExpired(order, ts, enforceBuffer = false) {
176
176
  }
177
177
  let maxTs;
178
178
  if (enforceBuffer && isLimitOrder(order)) {
179
- maxTs = order.maxTs.addn(15);
179
+ maxTs = order.maxTs.addn(bufferSeconds);
180
180
  }
181
181
  else {
182
182
  maxTs = order.maxTs;
@@ -12,7 +12,7 @@ const index_1 = require("../index");
12
12
  const user_1 = require("../decode/user");
13
13
  class OrderSubscriber {
14
14
  constructor(config) {
15
- var _a;
15
+ var _a, _b, _c;
16
16
  this.usersAccounts = new Map();
17
17
  this.driftClient = config.driftClient;
18
18
  this.commitment = config.subscriptionConfig.commitment || 'processed';
@@ -27,12 +27,15 @@ class OrderSubscriber {
27
27
  orderSubscriber: this,
28
28
  commitment: this.commitment,
29
29
  skipInitialLoad: config.subscriptionConfig.skipInitialLoad,
30
- resubTimeoutMs: config.subscriptionConfig.resubTimeoutMs,
30
+ resubOpts: {
31
+ resubTimeoutMs: (_a = config.subscriptionConfig) === null || _a === void 0 ? void 0 : _a.resubTimeoutMs,
32
+ logResubMessages: (_b = config.subscriptionConfig) === null || _b === void 0 ? void 0 : _b.logResubMessages,
33
+ },
31
34
  resyncIntervalMs: config.subscriptionConfig.resyncIntervalMs,
32
35
  decoded: config.decodeData,
33
36
  });
34
37
  }
35
- if ((_a = config.fastDecode) !== null && _a !== void 0 ? _a : true) {
38
+ if ((_c = config.fastDecode) !== null && _c !== void 0 ? _c : true) {
36
39
  this.decodeFn = (name, data) => (0, user_1.decodeUser)(data);
37
40
  }
38
41
  else {
@@ -1,19 +1,20 @@
1
1
  import { OrderSubscriber } from './OrderSubscriber';
2
2
  import { Commitment } from '@solana/web3.js';
3
+ import { ResubOpts } from '../accounts/types';
3
4
  export declare class WebsocketSubscription {
4
5
  private orderSubscriber;
5
6
  private commitment;
6
7
  private skipInitialLoad;
7
- private resubTimeoutMs?;
8
+ private resubOpts?;
8
9
  private resyncIntervalMs?;
9
10
  private subscriber?;
10
11
  private resyncTimeoutId?;
11
12
  private decoded?;
12
- constructor({ orderSubscriber, commitment, skipInitialLoad, resubTimeoutMs, resyncIntervalMs, decoded, }: {
13
+ constructor({ orderSubscriber, commitment, skipInitialLoad, resubOpts, resyncIntervalMs, decoded, }: {
13
14
  orderSubscriber: OrderSubscriber;
14
15
  commitment: Commitment;
15
16
  skipInitialLoad?: boolean;
16
- resubTimeoutMs?: number;
17
+ resubOpts?: ResubOpts;
17
18
  resyncIntervalMs?: number;
18
19
  decoded?: boolean;
19
20
  });
@@ -4,11 +4,11 @@ exports.WebsocketSubscription = void 0;
4
4
  const memcmp_1 = require("../memcmp");
5
5
  const webSocketProgramAccountSubscriber_1 = require("../accounts/webSocketProgramAccountSubscriber");
6
6
  class WebsocketSubscription {
7
- constructor({ orderSubscriber, commitment, skipInitialLoad = false, resubTimeoutMs, resyncIntervalMs, decoded = true, }) {
7
+ constructor({ orderSubscriber, commitment, skipInitialLoad = false, resubOpts, resyncIntervalMs, decoded = true, }) {
8
8
  this.orderSubscriber = orderSubscriber;
9
9
  this.commitment = commitment;
10
10
  this.skipInitialLoad = skipInitialLoad;
11
- this.resubTimeoutMs = resubTimeoutMs;
11
+ this.resubOpts = resubOpts;
12
12
  this.resyncIntervalMs = resyncIntervalMs;
13
13
  this.decoded = decoded;
14
14
  }
@@ -19,7 +19,7 @@ class WebsocketSubscription {
19
19
  this.subscriber = new webSocketProgramAccountSubscriber_1.WebSocketProgramAccountSubscriber('OrderSubscriber', 'User', this.orderSubscriber.driftClient.program, this.orderSubscriber.decodeFn, {
20
20
  filters: [(0, memcmp_1.getUserFilter)(), (0, memcmp_1.getNonIdleUserFilter)()],
21
21
  commitment: this.commitment,
22
- }, this.resubTimeoutMs);
22
+ }, this.resubOpts);
23
23
  await this.subscriber.subscribe((accountId, account, context, buffer) => {
24
24
  var _a;
25
25
  const userKey = accountId.toBase58();
@@ -11,6 +11,7 @@ export type OrderSubscriberConfig = {
11
11
  type: 'websocket';
12
12
  skipInitialLoad?: boolean;
13
13
  resubTimeoutMs?: number;
14
+ logResubMessages?: boolean;
14
15
  resyncIntervalMs?: number;
15
16
  commitment?: Commitment;
16
17
  };
@@ -1,3 +1,13 @@
1
- import { HeliusPriorityFeeLevels } from './heliusPriorityFeeMethod';
2
- export type DriftPriorityFeeResponse = HeliusPriorityFeeLevels[];
3
- export declare function fetchDriftPriorityFee(url: string, marketTypes: string[], marketIndexs: number[]): Promise<DriftPriorityFeeResponse>;
1
+ import { HeliusPriorityLevel } from './heliusPriorityFeeMethod';
2
+ export type DriftMarketInfo = {
3
+ marketType: string;
4
+ marketIndex: number;
5
+ };
6
+ export type DriftPriorityFeeLevels = {
7
+ [key in HeliusPriorityLevel]: number;
8
+ } & {
9
+ marketType: 'perp' | 'spot';
10
+ marketIndex: number;
11
+ };
12
+ export type DriftPriorityFeeResponse = DriftPriorityFeeLevels[];
13
+ export declare function fetchDriftPriorityFee(url: string, marketTypes: string[], marketIndexes: number[]): Promise<DriftPriorityFeeResponse>;
@@ -5,9 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.fetchDriftPriorityFee = void 0;
7
7
  const node_fetch_1 = __importDefault(require("node-fetch"));
8
- async function fetchDriftPriorityFee(url, marketTypes, marketIndexs) {
8
+ async function fetchDriftPriorityFee(url, marketTypes, marketIndexes) {
9
9
  try {
10
- const response = await (0, node_fetch_1.default)(`${url}/batchPriorityFees?marketType=${marketTypes.join(',')}&marketIndex=${marketIndexs.join(',')}`);
10
+ const response = await (0, node_fetch_1.default)(`${url}/batchPriorityFees?marketType=${marketTypes.join(',')}&marketIndex=${marketIndexes.join(',')}`);
11
11
  if (!response.ok) {
12
12
  throw new Error(`HTTP error! status: ${response.status}`);
13
13
  }
@@ -4,6 +4,8 @@ export * from './ewmaStrategy';
4
4
  export * from './maxOverSlotsStrategy';
5
5
  export * from './maxStrategy';
6
6
  export * from './priorityFeeSubscriber';
7
+ export * from './priorityFeeSubscriberMap';
7
8
  export * from './solanaPriorityFeeMethod';
8
9
  export * from './heliusPriorityFeeMethod';
10
+ export * from './driftPriorityFeeMethod';
9
11
  export * from './types';
@@ -20,6 +20,8 @@ __exportStar(require("./ewmaStrategy"), exports);
20
20
  __exportStar(require("./maxOverSlotsStrategy"), exports);
21
21
  __exportStar(require("./maxStrategy"), exports);
22
22
  __exportStar(require("./priorityFeeSubscriber"), exports);
23
+ __exportStar(require("./priorityFeeSubscriberMap"), exports);
23
24
  __exportStar(require("./solanaPriorityFeeMethod"), exports);
24
25
  __exportStar(require("./heliusPriorityFeeMethod"), exports);
26
+ __exportStar(require("./driftPriorityFeeMethod"), exports);
25
27
  __exportStar(require("./types"), exports);
@@ -3,10 +3,7 @@ import { PriorityFeeMethod, PriorityFeeStrategy, PriorityFeeSubscriberConfig } f
3
3
  import { AverageOverSlotsStrategy } from './averageOverSlotsStrategy';
4
4
  import { MaxOverSlotsStrategy } from './maxOverSlotsStrategy';
5
5
  import { HeliusPriorityFeeLevels, HeliusPriorityLevel } from './heliusPriorityFeeMethod';
6
- export type DriftMarketInfo = {
7
- marketType: string;
8
- marketIndex: number;
9
- };
6
+ import { DriftMarketInfo } from './driftPriorityFeeMethod';
10
7
  export declare class PriorityFeeSubscriber {
11
8
  connection: Connection;
12
9
  frequencyMs: number;
@@ -9,7 +9,7 @@ const heliusPriorityFeeMethod_1 = require("./heliusPriorityFeeMethod");
9
9
  const driftPriorityFeeMethod_1 = require("./driftPriorityFeeMethod");
10
10
  class PriorityFeeSubscriber {
11
11
  constructor(config) {
12
- var _a, _b;
12
+ var _a, _b, _c;
13
13
  this.averageStrategy = new averageOverSlotsStrategy_1.AverageOverSlotsStrategy();
14
14
  this.maxStrategy = new maxOverSlotsStrategy_1.MaxOverSlotsStrategy();
15
15
  this.priorityFeeMethod = types_1.PriorityFeeMethod.SOLANA;
@@ -19,7 +19,8 @@ class PriorityFeeSubscriber {
19
19
  this.lastMaxStrategyResult = 0;
20
20
  this.lastSlotSeen = 0;
21
21
  this.connection = config.connection;
22
- this.frequencyMs = config.frequencyMs;
22
+ this.frequencyMs =
23
+ (_a = config.frequencyMs) !== null && _a !== void 0 ? _a : types_1.DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
23
24
  this.addresses = config.addresses
24
25
  ? config.addresses.map((address) => address.toBase58())
25
26
  : [];
@@ -30,7 +31,7 @@ class PriorityFeeSubscriber {
30
31
  else {
31
32
  this.customStrategy = this.averageStrategy;
32
33
  }
33
- this.lookbackDistance = (_a = config.slotsToCheck) !== null && _a !== void 0 ? _a : 50;
34
+ this.lookbackDistance = (_b = config.slotsToCheck) !== null && _b !== void 0 ? _b : 50;
34
35
  if (config.priorityFeeMethod) {
35
36
  this.priorityFeeMethod = config.priorityFeeMethod;
36
37
  if (this.priorityFeeMethod === types_1.PriorityFeeMethod.HELIUS) {
@@ -56,7 +57,7 @@ class PriorityFeeSubscriber {
56
57
  }
57
58
  }
58
59
  this.maxFeeMicroLamports = config.maxFeeMicroLamports;
59
- this.priorityFeeMultiplier = (_b = config.priorityFeeMultiplier) !== null && _b !== void 0 ? _b : 1.0;
60
+ this.priorityFeeMultiplier = (_c = config.priorityFeeMultiplier) !== null && _c !== void 0 ? _c : 1.0;
60
61
  }
61
62
  async subscribe() {
62
63
  if (this.intervalId) {
@@ -0,0 +1,48 @@
1
+ import { DriftMarketInfo, DriftPriorityFeeLevels } from './driftPriorityFeeMethod';
2
+ import { PriorityFeeSubscriberMapConfig } from './types';
3
+ /**
4
+ * takes advantage of /batchPriorityFees endpoint from drift hosted priority fee service
5
+ */
6
+ export declare class PriorityFeeSubscriberMap {
7
+ frequencyMs: number;
8
+ intervalId?: ReturnType<typeof setTimeout>;
9
+ driftMarkets?: DriftMarketInfo[];
10
+ driftPriorityFeeEndpoint?: string;
11
+ feesMap: Map<string, Map<number, DriftPriorityFeeLevels>>;
12
+ constructor(config: PriorityFeeSubscriberMapConfig);
13
+ private updateFeesMap;
14
+ subscribe(): Promise<void>;
15
+ unsubscribe(): Promise<void>;
16
+ load(): Promise<void>;
17
+ updateMarketTypeAndIndex(driftMarkets: DriftMarketInfo[]): void;
18
+ getPriorityFees(marketType: string, marketIndex: number): DriftPriorityFeeLevels | undefined;
19
+ }
20
+ /** Example usage:
21
+ async function main() {
22
+ const driftMarkets: DriftMarketInfo[] = [
23
+ { marketType: 'perp', marketIndex: 0 },
24
+ { marketType: 'perp', marketIndex: 1 },
25
+ { marketType: 'spot', marketIndex: 2 }
26
+ ];
27
+
28
+ const subscriber = new PriorityFeeSubscriberMap({
29
+ driftPriorityFeeEndpoint: 'https://dlob.drift.trade',
30
+ frequencyMs: 5000,
31
+ driftMarkets
32
+ });
33
+ await subscriber.subscribe();
34
+
35
+ for (let i = 0; i < 20; i++) {
36
+ await new Promise(resolve => setTimeout(resolve, 1000));
37
+ driftMarkets.forEach(market => {
38
+ const fees = subscriber.getPriorityFees(market.marketType, market.marketIndex);
39
+ console.log(`Priority fees for ${market.marketType} market ${market.marketIndex}:`, fees);
40
+ });
41
+ }
42
+
43
+
44
+ await subscriber.unsubscribe();
45
+ }
46
+
47
+ main().catch(console.error);
48
+ */
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PriorityFeeSubscriberMap = void 0;
4
+ const driftPriorityFeeMethod_1 = require("./driftPriorityFeeMethod");
5
+ const types_1 = require("./types");
6
+ /**
7
+ * takes advantage of /batchPriorityFees endpoint from drift hosted priority fee service
8
+ */
9
+ class PriorityFeeSubscriberMap {
10
+ constructor(config) {
11
+ var _a;
12
+ this.frequencyMs = config.frequencyMs;
13
+ this.frequencyMs =
14
+ (_a = config.frequencyMs) !== null && _a !== void 0 ? _a : types_1.DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
15
+ this.driftPriorityFeeEndpoint = config.driftPriorityFeeEndpoint;
16
+ this.driftMarkets = config.driftMarkets;
17
+ this.feesMap = new Map();
18
+ this.feesMap.set('perp', new Map());
19
+ this.feesMap.set('spot', new Map());
20
+ }
21
+ updateFeesMap(driftPriorityFeeResponse) {
22
+ driftPriorityFeeResponse.forEach((fee) => {
23
+ this.feesMap.get(fee.marketType).set(fee.marketIndex, fee);
24
+ });
25
+ }
26
+ async subscribe() {
27
+ if (this.intervalId) {
28
+ return;
29
+ }
30
+ await this.load();
31
+ this.intervalId = setInterval(this.load.bind(this), this.frequencyMs);
32
+ }
33
+ async unsubscribe() {
34
+ if (this.intervalId) {
35
+ clearInterval(this.intervalId);
36
+ this.intervalId = undefined;
37
+ }
38
+ }
39
+ async load() {
40
+ try {
41
+ if (!this.driftMarkets) {
42
+ return;
43
+ }
44
+ const fees = await (0, driftPriorityFeeMethod_1.fetchDriftPriorityFee)(this.driftPriorityFeeEndpoint, this.driftMarkets.map((m) => m.marketType), this.driftMarkets.map((m) => m.marketIndex));
45
+ this.updateFeesMap(fees);
46
+ }
47
+ catch (e) {
48
+ console.error('Error fetching drift priority fees', e);
49
+ }
50
+ }
51
+ updateMarketTypeAndIndex(driftMarkets) {
52
+ this.driftMarkets = driftMarkets;
53
+ }
54
+ getPriorityFees(marketType, marketIndex) {
55
+ var _a;
56
+ return (_a = this.feesMap.get(marketType)) === null || _a === void 0 ? void 0 : _a.get(marketIndex);
57
+ }
58
+ }
59
+ exports.PriorityFeeSubscriberMap = PriorityFeeSubscriberMap;
60
+ /** Example usage:
61
+ async function main() {
62
+ const driftMarkets: DriftMarketInfo[] = [
63
+ { marketType: 'perp', marketIndex: 0 },
64
+ { marketType: 'perp', marketIndex: 1 },
65
+ { marketType: 'spot', marketIndex: 2 }
66
+ ];
67
+
68
+ const subscriber = new PriorityFeeSubscriberMap({
69
+ driftPriorityFeeEndpoint: 'https://dlob.drift.trade',
70
+ frequencyMs: 5000,
71
+ driftMarkets
72
+ });
73
+ await subscriber.subscribe();
74
+
75
+ for (let i = 0; i < 20; i++) {
76
+ await new Promise(resolve => setTimeout(resolve, 1000));
77
+ driftMarkets.forEach(market => {
78
+ const fees = subscriber.getPriorityFees(market.marketType, market.marketIndex);
79
+ console.log(`Priority fees for ${market.marketType} market ${market.marketIndex}:`, fees);
80
+ });
81
+ }
82
+
83
+
84
+ await subscriber.unsubscribe();
85
+ }
86
+
87
+ main().catch(console.error);
88
+ */
@@ -1,8 +1,8 @@
1
1
  import { Connection, PublicKey } from '@solana/web3.js';
2
2
  import { SolanaPriorityFeeResponse } from './solanaPriorityFeeMethod';
3
3
  import { HeliusPriorityFeeResponse } from './heliusPriorityFeeMethod';
4
- import { DriftMarketInfo } from './priorityFeeSubscriber';
5
- import { DriftPriorityFeeResponse } from './driftPriorityFeeMethod';
4
+ import { DriftMarketInfo, DriftPriorityFeeResponse } from './driftPriorityFeeMethod';
5
+ export declare const DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS = 10000;
6
6
  export interface PriorityFeeStrategy {
7
7
  calculate(samples: SolanaPriorityFeeResponse[] | HeliusPriorityFeeResponse | DriftPriorityFeeResponse): number;
8
8
  }
@@ -13,7 +13,7 @@ export declare enum PriorityFeeMethod {
13
13
  }
14
14
  export type PriorityFeeSubscriberConfig = {
15
15
  connection?: Connection;
16
- frequencyMs: number;
16
+ frequencyMs?: number;
17
17
  addresses?: PublicKey[];
18
18
  driftMarkets?: DriftMarketInfo[];
19
19
  customStrategy?: PriorityFeeStrategy;
@@ -24,3 +24,8 @@ export type PriorityFeeSubscriberConfig = {
24
24
  maxFeeMicroLamports?: number;
25
25
  priorityFeeMultiplier?: number;
26
26
  };
27
+ export type PriorityFeeSubscriberMapConfig = {
28
+ frequencyMs?: number;
29
+ driftMarkets?: DriftMarketInfo[];
30
+ driftPriorityFeeEndpoint: string;
31
+ };
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PriorityFeeMethod = void 0;
3
+ exports.PriorityFeeMethod = exports.DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS = void 0;
4
+ exports.DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS = 10000;
4
5
  var PriorityFeeMethod;
5
6
  (function (PriorityFeeMethod) {
6
7
  PriorityFeeMethod["SOLANA"] = "solana";
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
- import { ConfirmationStrategy, ExtraConfirmationOptions, TxSender, TxSigAndSlot } from './types';
3
- import { Commitment, ConfirmOptions, RpcResponseAndContext, Signer, SignatureResult, Transaction, TransactionSignature, Connection, VersionedTransaction, TransactionInstruction, AddressLookupTableAccount } from '@solana/web3.js';
2
+ import { ConfirmationStrategy, TxSender, TxSigAndSlot } from './types';
3
+ import { Commitment, ConfirmOptions, RpcResponseAndContext, Signer, SignatureResult, Transaction, TransactionSignature, Connection, VersionedTransaction } from '@solana/web3.js';
4
+ import { TxHandler } from './txHandler';
4
5
  import { IWallet } from '../types';
5
6
  export declare abstract class BaseTxSender implements TxSender {
6
7
  connection: Connection;
@@ -11,7 +12,8 @@ export declare abstract class BaseTxSender implements TxSender {
11
12
  timeoutCount: number;
12
13
  confirmationStrategy: ConfirmationStrategy;
13
14
  additionalTxSenderCallbacks: ((base58EncodedTx: string) => void)[];
14
- constructor({ connection, wallet, opts, timeout, additionalConnections, confirmationStrategy, additionalTxSenderCallbacks, }: {
15
+ txHandler: TxHandler;
16
+ constructor({ connection, wallet, opts, timeout, additionalConnections, confirmationStrategy, additionalTxSenderCallbacks, txHandler, }: {
15
17
  connection: Connection;
16
18
  wallet: IWallet;
17
19
  opts?: ConfirmOptions;
@@ -19,11 +21,11 @@ export declare abstract class BaseTxSender implements TxSender {
19
21
  additionalConnections?: any;
20
22
  confirmationStrategy?: ConfirmationStrategy;
21
23
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
24
+ txHandler: TxHandler;
22
25
  });
23
- send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean, extraConfirmationOptions?: ExtraConfirmationOptions): Promise<TxSigAndSlot>;
26
+ send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
24
27
  prepareTx(tx: Transaction, additionalSigners: Array<Signer>, opts: ConfirmOptions, preSigned?: boolean): Promise<Transaction>;
25
- getVersionedTransaction(ixs: TransactionInstruction[], lookupTableAccounts: AddressLookupTableAccount[], additionalSigners?: Array<Signer>, opts?: ConfirmOptions, blockhash?: string): Promise<VersionedTransaction>;
26
- sendVersionedTransaction(tx: VersionedTransaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean, extraConfirmationOptions?: ExtraConfirmationOptions): Promise<TxSigAndSlot>;
28
+ sendVersionedTransaction(tx: VersionedTransaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
27
29
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
28
30
  simulateTransaction(tx: VersionedTransaction): Promise<boolean>;
29
31
  confirmTransactionWebSocket(signature: TransactionSignature, commitment?: Commitment): Promise<RpcResponseAndContext<SignatureResult>>;
@@ -5,13 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BaseTxSender = void 0;
7
7
  const types_1 = require("./types");
8
- const web3_js_1 = require("@solana/web3.js");
9
8
  const anchor_1 = require("@coral-xyz/anchor");
10
9
  const assert_1 = __importDefault(require("assert"));
11
10
  const bs58_1 = __importDefault(require("bs58"));
12
11
  const DEFAULT_TIMEOUT = 35000;
12
+ const NOT_CONFIRMED_ERROR_CODE = -1001;
13
13
  class BaseTxSender {
14
- constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks, }) {
14
+ constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks, txHandler, }) {
15
15
  this.timeoutCount = 0;
16
16
  this.connection = connection;
17
17
  this.wallet = wallet;
@@ -20,8 +20,9 @@ class BaseTxSender {
20
20
  this.additionalConnections = additionalConnections;
21
21
  this.confirmationStrategy = confirmationStrategy;
22
22
  this.additionalTxSenderCallbacks = additionalTxSenderCallbacks;
23
+ this.txHandler = txHandler;
23
24
  }
24
- async send(tx, additionalSigners, opts, preSigned, extraConfirmationOptions) {
25
+ async send(tx, additionalSigners, opts, preSigned) {
25
26
  if (additionalSigners === undefined) {
26
27
  additionalSigners = [];
27
28
  }
@@ -29,48 +30,12 @@ class BaseTxSender {
29
30
  opts = this.opts;
30
31
  }
31
32
  const signedTx = await this.prepareTx(tx, additionalSigners, opts, preSigned);
32
- if (extraConfirmationOptions === null || extraConfirmationOptions === void 0 ? void 0 : extraConfirmationOptions.onSignedCb) {
33
- extraConfirmationOptions.onSignedCb();
34
- }
35
33
  return this.sendRawTransaction(signedTx.serialize(), opts);
36
34
  }
37
35
  async prepareTx(tx, additionalSigners, opts, preSigned) {
38
- if (preSigned) {
39
- return tx;
40
- }
41
- tx.feePayer = this.wallet.publicKey;
42
- tx.recentBlockhash = (await this.connection.getLatestBlockhash(opts.preflightCommitment)).blockhash;
43
- additionalSigners
44
- .filter((s) => s !== undefined)
45
- .forEach((kp) => {
46
- tx.partialSign(kp);
47
- });
48
- const signedTx = await this.wallet.signTransaction(tx);
49
- return signedTx;
36
+ return this.txHandler.prepareTx(tx, additionalSigners, undefined, opts, preSigned);
50
37
  }
51
- async getVersionedTransaction(ixs, lookupTableAccounts, additionalSigners, opts, blockhash) {
52
- if (additionalSigners === undefined) {
53
- additionalSigners = [];
54
- }
55
- if (opts === undefined) {
56
- opts = this.opts;
57
- }
58
- let recentBlockhash = '';
59
- if (blockhash) {
60
- recentBlockhash = blockhash;
61
- }
62
- else {
63
- recentBlockhash = (await this.connection.getLatestBlockhash(opts.preflightCommitment)).blockhash;
64
- }
65
- const message = new web3_js_1.TransactionMessage({
66
- payerKey: this.wallet.publicKey,
67
- recentBlockhash,
68
- instructions: ixs,
69
- }).compileToV0Message(lookupTableAccounts);
70
- const tx = new web3_js_1.VersionedTransaction(message);
71
- return tx;
72
- }
73
- async sendVersionedTransaction(tx, additionalSigners, opts, preSigned, extraConfirmationOptions) {
38
+ async sendVersionedTransaction(tx, additionalSigners, opts, preSigned) {
74
39
  let signedTx;
75
40
  if (preSigned) {
76
41
  signedTx = tx;
@@ -82,14 +47,7 @@ class BaseTxSender {
82
47
  signedTx = tx;
83
48
  }
84
49
  else {
85
- additionalSigners === null || additionalSigners === void 0 ? void 0 : additionalSigners.filter((s) => s !== undefined).forEach((kp) => {
86
- tx.sign([kp]);
87
- });
88
- // @ts-ignore
89
- signedTx = await this.wallet.signTransaction(tx);
90
- }
91
- if (extraConfirmationOptions === null || extraConfirmationOptions === void 0 ? void 0 : extraConfirmationOptions.onSignedCb) {
92
- extraConfirmationOptions.onSignedCb();
50
+ signedTx = await this.txHandler.signVersionedTx(tx, additionalSigners, undefined, this.wallet);
93
51
  }
94
52
  if (opts === undefined) {
95
53
  opts = this.opts;
@@ -181,7 +139,7 @@ class BaseTxSender {
181
139
  }
182
140
  this.timeoutCount += 1;
183
141
  const duration = (Date.now() - start) / 1000;
184
- throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
142
+ throw new types_1.TxSendError(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`, NOT_CONFIRMED_ERROR_CODE);
185
143
  }
186
144
  return response;
187
145
  }
@@ -203,7 +161,7 @@ class BaseTxSender {
203
161
  // Transaction not confirmed within 30 seconds
204
162
  this.timeoutCount += 1;
205
163
  const duration = (Date.now() - start) / 1000;
206
- throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
164
+ throw new types_1.TxSendError(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`, NOT_CONFIRMED_ERROR_CODE);
207
165
  }
208
166
  async confirmTransaction(signature, commitment) {
209
167
  if (this.confirmationStrategy === types_1.ConfirmationStrategy.WebSocket ||