@drift-labs/sdk 2.82.0-beta.1 → 2.82.0-beta.3

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/VERSION CHANGED
@@ -1 +1 @@
1
- 2.82.0-beta.1
1
+ 2.82.0-beta.3
@@ -650,7 +650,8 @@ export declare class DriftClient {
650
650
  requestRemoveInsuranceFundStake(marketIndex: number, amount: BN, txParams?: TxParams): Promise<TransactionSignature>;
651
651
  cancelRequestRemoveInsuranceFundStake(marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
652
652
  removeInsuranceFundStake(marketIndex: number, collateralAccountPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
653
- settleRevenueToInsuranceFund(marketIndex: number): Promise<TransactionSignature>;
653
+ settleRevenueToInsuranceFund(spotMarketIndex: number, subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
654
+ getSettleRevenueToInsuranceFundIx(spotMarketIndex: number, subAccountId?: number): Promise<TransactionInstruction>;
654
655
  resolvePerpPnlDeficit(spotMarketIndex: number, perpMarketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
655
656
  getResolvePerpPnlDeficitIx(spotMarketIndex: number, perpMarketIndex: number): Promise<TransactionInstruction>;
656
657
  getDepositIntoSpotMarketRevenuePoolIx(marketIndex: number, amount: BN, userTokenAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
@@ -3465,14 +3465,19 @@ class DriftClient {
3465
3465
  const { txSig } = await this.sendTransaction(tx, additionalSigners, this.opts);
3466
3466
  return txSig;
3467
3467
  }
3468
- async settleRevenueToInsuranceFund(marketIndex) {
3469
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
3468
+ async settleRevenueToInsuranceFund(spotMarketIndex, subAccountId, txParams) {
3469
+ const tx = await this.buildTransaction(await this.getSettleRevenueToInsuranceFundIx(spotMarketIndex, subAccountId), txParams);
3470
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
3471
+ return txSig;
3472
+ }
3473
+ async getSettleRevenueToInsuranceFundIx(spotMarketIndex, subAccountId) {
3474
+ const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
3470
3475
  const remainingAccounts = this.getRemainingAccounts({
3471
- userAccounts: [this.getUserAccount()],
3476
+ userAccounts: [this.getUserAccount(subAccountId)],
3472
3477
  useMarketLastSlotCache: true,
3473
- writableSpotMarketIndexes: [marketIndex],
3478
+ writableSpotMarketIndexes: [spotMarketIndex],
3474
3479
  });
3475
- const ix = await this.program.instruction.settleRevenueToInsuranceFund(marketIndex, {
3480
+ const ix = await this.program.instruction.settleRevenueToInsuranceFund(spotMarketIndex, {
3476
3481
  accounts: {
3477
3482
  state: await this.getStatePublicKey(),
3478
3483
  spotMarket: spotMarketAccount.pubkey,
@@ -3483,9 +3488,7 @@ class DriftClient {
3483
3488
  },
3484
3489
  remainingAccounts,
3485
3490
  });
3486
- const tx = await this.buildTransaction(ix);
3487
- const { txSig } = await this.sendTransaction(tx, [], this.opts);
3488
- return txSig;
3491
+ return ix;
3489
3492
  }
3490
3493
  async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, txParams) {
3491
3494
  const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex), txParams), [], this.opts);
@@ -1,3 +1,3 @@
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 { DriftPriorityFeeLevels } from './heliusPriorityFeeMethod';
2
+ export type DriftPriorityFeeResponse = DriftPriorityFeeLevels[];
3
+ 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
  }
@@ -9,6 +9,12 @@ export declare enum HeliusPriorityLevel {
9
9
  export type HeliusPriorityFeeLevels = {
10
10
  [key in HeliusPriorityLevel]: number;
11
11
  };
12
+ export type DriftPriorityFeeLevels = {
13
+ [key in HeliusPriorityLevel]: number;
14
+ } & {
15
+ marketType: 'perp' | 'spot';
16
+ marketIndex: number;
17
+ };
12
18
  export type HeliusPriorityFeeResponse = {
13
19
  jsonrpc: string;
14
20
  result: {
@@ -1,12 +1,8 @@
1
1
  import { Connection, PublicKey } from '@solana/web3.js';
2
- import { PriorityFeeMethod, PriorityFeeStrategy, PriorityFeeSubscriberConfig } from './types';
2
+ import { DriftMarketInfo, PriorityFeeMethod, PriorityFeeStrategy, PriorityFeeSubscriberConfig } from './types';
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
- };
10
6
  export declare class PriorityFeeSubscriber {
11
7
  connection: Connection;
12
8
  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 { DriftPriorityFeeLevels } from './heliusPriorityFeeMethod';
2
+ import { DriftMarketInfo, 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
4
  import { 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
  }
@@ -11,9 +11,13 @@ export declare enum PriorityFeeMethod {
11
11
  HELIUS = "helius",
12
12
  DRIFT = "drift"
13
13
  }
14
+ export type DriftMarketInfo = {
15
+ marketType: string;
16
+ marketIndex: number;
17
+ };
14
18
  export type PriorityFeeSubscriberConfig = {
15
19
  connection?: Connection;
16
- frequencyMs: number;
20
+ frequencyMs?: number;
17
21
  addresses?: PublicKey[];
18
22
  driftMarkets?: DriftMarketInfo[];
19
23
  customStrategy?: PriorityFeeStrategy;
@@ -24,3 +28,8 @@ export type PriorityFeeSubscriberConfig = {
24
28
  maxFeeMicroLamports?: number;
25
29
  priorityFeeMultiplier?: number;
26
30
  };
31
+ export type PriorityFeeSubscriberMapConfig = {
32
+ frequencyMs?: number;
33
+ driftMarkets?: DriftMarketInfo[];
34
+ driftPriorityFeeEndpoint: string;
35
+ };
@@ -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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.82.0-beta.1",
3
+ "version": "2.82.0-beta.3",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -1,8 +1,12 @@
1
1
  import { Commitment, Connection } from '@solana/web3.js';
2
2
 
3
3
  export type BlockhashSubscriberConfig = {
4
+ /// rpcUrl to poll block hashes from, one of rpcUrl or Connection must provided
4
5
  rpcUrl?: string;
6
+ /// connection to poll block hashes from, one of rpcUrl or Connection must provided
5
7
  connection?: Connection;
8
+ /// commitment to poll block hashes with, default is 'confirmed'
6
9
  commitment?: Commitment;
10
+ /// interval to poll block hashes, default is 1000 ms
7
11
  updateIntervalMs?: number;
8
12
  };
@@ -6488,18 +6488,33 @@ export class DriftClient {
6488
6488
  }
6489
6489
 
6490
6490
  public async settleRevenueToInsuranceFund(
6491
- marketIndex: number
6491
+ spotMarketIndex: number,
6492
+ subAccountId?: number,
6493
+ txParams?: TxParams
6492
6494
  ): Promise<TransactionSignature> {
6493
- const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
6495
+ const tx = await this.buildTransaction(
6496
+ await this.getSettleRevenueToInsuranceFundIx(
6497
+ spotMarketIndex,
6498
+ subAccountId
6499
+ ),
6500
+ txParams
6501
+ );
6502
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
6503
+ return txSig;
6504
+ }
6494
6505
 
6506
+ public async getSettleRevenueToInsuranceFundIx(
6507
+ spotMarketIndex: number,
6508
+ subAccountId?: number
6509
+ ): Promise<TransactionInstruction> {
6510
+ const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
6495
6511
  const remainingAccounts = this.getRemainingAccounts({
6496
- userAccounts: [this.getUserAccount()],
6512
+ userAccounts: [this.getUserAccount(subAccountId)],
6497
6513
  useMarketLastSlotCache: true,
6498
- writableSpotMarketIndexes: [marketIndex],
6514
+ writableSpotMarketIndexes: [spotMarketIndex],
6499
6515
  });
6500
-
6501
6516
  const ix = await this.program.instruction.settleRevenueToInsuranceFund(
6502
- marketIndex,
6517
+ spotMarketIndex,
6503
6518
  {
6504
6519
  accounts: {
6505
6520
  state: await this.getStatePublicKey(),
@@ -6512,11 +6527,7 @@ export class DriftClient {
6512
6527
  remainingAccounts,
6513
6528
  }
6514
6529
  );
6515
-
6516
- const tx = await this.buildTransaction(ix);
6517
-
6518
- const { txSig } = await this.sendTransaction(tx, [], this.opts);
6519
- return txSig;
6530
+ return ix;
6520
6531
  }
6521
6532
 
6522
6533
  public async resolvePerpPnlDeficit(
@@ -1,18 +1,18 @@
1
1
  import fetch from 'node-fetch';
2
- import { HeliusPriorityFeeLevels } from './heliusPriorityFeeMethod';
2
+ import { DriftPriorityFeeLevels } from './heliusPriorityFeeMethod';
3
3
 
4
- export type DriftPriorityFeeResponse = HeliusPriorityFeeLevels[];
4
+ export type DriftPriorityFeeResponse = DriftPriorityFeeLevels[];
5
5
 
6
6
  export async function fetchDriftPriorityFee(
7
7
  url: string,
8
8
  marketTypes: string[],
9
- marketIndexs: number[]
9
+ marketIndexes: number[]
10
10
  ): Promise<DriftPriorityFeeResponse> {
11
11
  try {
12
12
  const response = await fetch(
13
13
  `${url}/batchPriorityFees?marketType=${marketTypes.join(
14
14
  ','
15
- )}&marketIndex=${marketIndexs.join(',')}`
15
+ )}&marketIndex=${marketIndexes.join(',')}`
16
16
  );
17
17
  if (!response.ok) {
18
18
  throw new Error(`HTTP error! status: ${response.status}`);
@@ -13,6 +13,13 @@ export type HeliusPriorityFeeLevels = {
13
13
  [key in HeliusPriorityLevel]: number;
14
14
  };
15
15
 
16
+ export type DriftPriorityFeeLevels = {
17
+ [key in HeliusPriorityLevel]: number;
18
+ } & {
19
+ marketType: 'perp' | 'spot';
20
+ marketIndex: number;
21
+ };
22
+
16
23
  export type HeliusPriorityFeeResponse = {
17
24
  jsonrpc: string;
18
25
  result: {
@@ -1,5 +1,7 @@
1
1
  import { Connection, PublicKey } from '@solana/web3.js';
2
2
  import {
3
+ DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS,
4
+ DriftMarketInfo,
3
5
  PriorityFeeMethod,
4
6
  PriorityFeeStrategy,
5
7
  PriorityFeeSubscriberConfig,
@@ -14,11 +16,6 @@ import {
14
16
  } from './heliusPriorityFeeMethod';
15
17
  import { fetchDriftPriorityFee } from './driftPriorityFeeMethod';
16
18
 
17
- export type DriftMarketInfo = {
18
- marketType: string;
19
- marketIndex: number;
20
- };
21
-
22
19
  export class PriorityFeeSubscriber {
23
20
  connection: Connection;
24
21
  frequencyMs: number;
@@ -46,7 +43,8 @@ export class PriorityFeeSubscriber {
46
43
 
47
44
  public constructor(config: PriorityFeeSubscriberConfig) {
48
45
  this.connection = config.connection;
49
- this.frequencyMs = config.frequencyMs;
46
+ this.frequencyMs =
47
+ config.frequencyMs ?? DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
50
48
  this.addresses = config.addresses
51
49
  ? config.addresses.map((address) => address.toBase58())
52
50
  : [];
@@ -0,0 +1,112 @@
1
+ import {
2
+ DriftPriorityFeeResponse,
3
+ fetchDriftPriorityFee,
4
+ } from './driftPriorityFeeMethod';
5
+ import { DriftPriorityFeeLevels } from './heliusPriorityFeeMethod';
6
+ import {
7
+ DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS,
8
+ DriftMarketInfo,
9
+ PriorityFeeSubscriberMapConfig,
10
+ } from './types';
11
+
12
+ /**
13
+ * takes advantage of /batchPriorityFees endpoint from drift hosted priority fee service
14
+ */
15
+ export class PriorityFeeSubscriberMap {
16
+ frequencyMs: number;
17
+ intervalId?: ReturnType<typeof setTimeout>;
18
+
19
+ driftMarkets?: DriftMarketInfo[];
20
+ driftPriorityFeeEndpoint?: string;
21
+ feesMap: Map<string, Map<number, DriftPriorityFeeLevels>>; // marketType -> marketIndex -> priority fee
22
+
23
+ public constructor(config: PriorityFeeSubscriberMapConfig) {
24
+ this.frequencyMs = config.frequencyMs;
25
+ this.frequencyMs =
26
+ config.frequencyMs ?? DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS;
27
+ this.driftPriorityFeeEndpoint = config.driftPriorityFeeEndpoint;
28
+ this.driftMarkets = config.driftMarkets;
29
+ this.feesMap = new Map<string, Map<number, DriftPriorityFeeLevels>>();
30
+ this.feesMap.set('perp', new Map<number, DriftPriorityFeeLevels>());
31
+ this.feesMap.set('spot', new Map<number, DriftPriorityFeeLevels>());
32
+ }
33
+
34
+ private updateFeesMap(driftPriorityFeeResponse: DriftPriorityFeeResponse) {
35
+ driftPriorityFeeResponse.forEach((fee: DriftPriorityFeeLevels) => {
36
+ this.feesMap.get(fee.marketType)!.set(fee.marketIndex, fee);
37
+ });
38
+ }
39
+
40
+ public async subscribe(): Promise<void> {
41
+ if (this.intervalId) {
42
+ return;
43
+ }
44
+
45
+ await this.load();
46
+ this.intervalId = setInterval(this.load.bind(this), this.frequencyMs);
47
+ }
48
+
49
+ public async unsubscribe(): Promise<void> {
50
+ if (this.intervalId) {
51
+ clearInterval(this.intervalId);
52
+ this.intervalId = undefined;
53
+ }
54
+ }
55
+
56
+ public async load(): Promise<void> {
57
+ try {
58
+ if (!this.driftMarkets) {
59
+ return;
60
+ }
61
+ const fees = await fetchDriftPriorityFee(
62
+ this.driftPriorityFeeEndpoint!,
63
+ this.driftMarkets.map((m) => m.marketType),
64
+ this.driftMarkets.map((m) => m.marketIndex)
65
+ );
66
+ this.updateFeesMap(fees);
67
+ } catch (e) {
68
+ console.error('Error fetching drift priority fees', e);
69
+ }
70
+ }
71
+
72
+ public updateMarketTypeAndIndex(driftMarkets: DriftMarketInfo[]) {
73
+ this.driftMarkets = driftMarkets;
74
+ }
75
+
76
+ public getPriorityFees(
77
+ marketType: string,
78
+ marketIndex: number
79
+ ): DriftPriorityFeeLevels | undefined {
80
+ return this.feesMap.get(marketType)?.get(marketIndex);
81
+ }
82
+ }
83
+
84
+ /** Example usage:
85
+ async function main() {
86
+ const driftMarkets: DriftMarketInfo[] = [
87
+ { marketType: 'perp', marketIndex: 0 },
88
+ { marketType: 'perp', marketIndex: 1 },
89
+ { marketType: 'spot', marketIndex: 2 }
90
+ ];
91
+
92
+ const subscriber = new PriorityFeeSubscriberMap({
93
+ driftPriorityFeeEndpoint: 'https://dlob.drift.trade',
94
+ frequencyMs: 5000,
95
+ driftMarkets
96
+ });
97
+ await subscriber.subscribe();
98
+
99
+ for (let i = 0; i < 20; i++) {
100
+ await new Promise(resolve => setTimeout(resolve, 1000));
101
+ driftMarkets.forEach(market => {
102
+ const fees = subscriber.getPriorityFees(market.marketType, market.marketIndex);
103
+ console.log(`Priority fees for ${market.marketType} market ${market.marketIndex}:`, fees);
104
+ });
105
+ }
106
+
107
+
108
+ await subscriber.unsubscribe();
109
+ }
110
+
111
+ main().catch(console.error);
112
+ */
@@ -1,9 +1,10 @@
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
4
  import { DriftPriorityFeeResponse } from './driftPriorityFeeMethod';
6
5
 
6
+ export const DEFAULT_PRIORITY_FEE_MAP_FREQUENCY_MS = 10_000;
7
+
7
8
  export interface PriorityFeeStrategy {
8
9
  // calculate the priority fee for a given set of samples.
9
10
  // expect samples to be sorted in descending order (by slot)
@@ -21,11 +22,16 @@ export enum PriorityFeeMethod {
21
22
  DRIFT = 'drift',
22
23
  }
23
24
 
25
+ export type DriftMarketInfo = {
26
+ marketType: string;
27
+ marketIndex: number;
28
+ };
29
+
24
30
  export type PriorityFeeSubscriberConfig = {
25
31
  /// rpc connection, optional if using priorityFeeMethod.HELIUS
26
32
  connection?: Connection;
27
33
  /// frequency to make RPC calls to update priority fee samples, in milliseconds
28
- frequencyMs: number;
34
+ frequencyMs?: number;
29
35
  /// addresses you plan to write lock, used to determine priority fees
30
36
  addresses?: PublicKey[];
31
37
  /// drift market type and index, optionally provide at initialization time if using priorityFeeMethod.DRIFT
@@ -45,3 +51,12 @@ export type PriorityFeeSubscriberConfig = {
45
51
  /// multiplier applied to priority fee before maxFeeMicroLamports, defaults to 1.0
46
52
  priorityFeeMultiplier?: number;
47
53
  };
54
+
55
+ export type PriorityFeeSubscriberMapConfig = {
56
+ /// frequency to make RPC calls to update priority fee samples, in milliseconds
57
+ frequencyMs?: number;
58
+ /// drift market type and associated market index to query
59
+ driftMarkets?: DriftMarketInfo[];
60
+ /// url for drift cached priority fee endpoint
61
+ driftPriorityFeeEndpoint: string;
62
+ };
@@ -142,6 +142,10 @@ export const mockAMM: AMM = {
142
142
  bidQuoteAssetReserve: new BN(0),
143
143
  askBaseAssetReserve: new BN(0),
144
144
  askQuoteAssetReserve: new BN(0),
145
+
146
+ netUnsettledFundingPnl: new BN(0),
147
+ quoteAssetAmountWithUnsettledLp: new BN(0),
148
+ referencePriceOffset: 0,
145
149
  };
146
150
 
147
151
  export const mockPerpMarkets: Array<PerpMarketAccount> = [