@drift-labs/sdk 2.95.0-beta.9 → 2.96.0-beta.0

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.95.0-beta.9
1
+ 2.96.0-beta.0
@@ -24,8 +24,10 @@ export declare class PollingDriftClientAccountSubscriber implements DriftClientA
24
24
  state?: DataAndSlot<StateAccount>;
25
25
  perpMarket: Map<number, DataAndSlot<PerpMarketAccount>>;
26
26
  perpOracleMap: Map<number, PublicKey>;
27
+ perpOracleStringMap: Map<number, string>;
27
28
  spotMarket: Map<number, DataAndSlot<SpotMarketAccount>>;
28
29
  spotOracleMap: Map<number, PublicKey>;
30
+ spotOracleStringMap: Map<number, string>;
29
31
  oracles: Map<string, DataAndSlot<OraclePriceData>>;
30
32
  user?: DataAndSlot<UserAccount>;
31
33
  private isSubscribing;
@@ -58,7 +60,7 @@ export declare class PollingDriftClientAccountSubscriber implements DriftClientA
58
60
  getMarketAccountsAndSlots(): DataAndSlot<PerpMarketAccount>[];
59
61
  getSpotMarketAccountAndSlot(marketIndex: number): DataAndSlot<SpotMarketAccount> | undefined;
60
62
  getSpotMarketAccountsAndSlots(): DataAndSlot<SpotMarketAccount>[];
61
- getOraclePriceDataAndSlot(oraclePublicKey: PublicKey): DataAndSlot<OraclePriceData> | undefined;
63
+ getOraclePriceDataAndSlot(oraclePublicKey: PublicKey | string): DataAndSlot<OraclePriceData> | undefined;
62
64
  getOraclePriceDataAndSlotForPerpMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
63
65
  getOraclePriceDataAndSlotForSpotMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
64
66
  updateAccountLoaderPollingFrequency(pollingFrequency: number): void;
@@ -9,6 +9,7 @@ const web3_js_1 = require("@solana/web3.js");
9
9
  const oracleClientCache_1 = require("../oracles/oracleClientCache");
10
10
  const quoteAssetOracleClient_1 = require("../oracles/quoteAssetOracleClient");
11
11
  const config_1 = require("../config");
12
+ const ORACLE_DEFAULT_KEY = web3_js_1.PublicKey.default.toBase58();
12
13
  class PollingDriftClientAccountSubscriber {
13
14
  constructor(program, accountLoader, perpMarketIndexes, spotMarketIndexes, oracleInfos, shouldFindAllMarketsAndOracles) {
14
15
  this.oracleClientCache = new oracleClientCache_1.OracleClientCache();
@@ -16,8 +17,10 @@ class PollingDriftClientAccountSubscriber {
16
17
  this.oraclesToPoll = new Map();
17
18
  this.perpMarket = new Map();
18
19
  this.perpOracleMap = new Map();
20
+ this.perpOracleStringMap = new Map();
19
21
  this.spotMarket = new Map();
20
22
  this.spotOracleMap = new Map();
23
+ this.spotOracleStringMap = new Map();
21
24
  this.oracles = new Map();
22
25
  this.isSubscribing = false;
23
26
  this.isSubscribed = false;
@@ -300,6 +303,7 @@ class PollingDriftClientAccountSubscriber {
300
303
  }));
301
304
  }
302
305
  this.perpOracleMap.set(perpMarketIndex, oracle);
306
+ this.perpOracleStringMap.set(perpMarketIndex, oracle.toBase58());
303
307
  }
304
308
  await Promise.all(oraclePromises);
305
309
  }
@@ -317,6 +321,7 @@ class PollingDriftClientAccountSubscriber {
317
321
  }));
318
322
  }
319
323
  this.spotOracleMap.set(spotMarketIndex, oracle);
324
+ this.spotOracleStringMap.set(spotMarketIndex, oracle.toBase58());
320
325
  }
321
326
  await Promise.all(oraclePromises);
322
327
  }
@@ -343,17 +348,21 @@ class PollingDriftClientAccountSubscriber {
343
348
  }
344
349
  getOraclePriceDataAndSlot(oraclePublicKey) {
345
350
  this.assertIsSubscribed();
346
- if (oraclePublicKey.equals(web3_js_1.PublicKey.default)) {
351
+ const oracleString = typeof oraclePublicKey === 'string'
352
+ ? oraclePublicKey
353
+ : oraclePublicKey.toBase58();
354
+ if (oracleString === ORACLE_DEFAULT_KEY) {
347
355
  return {
348
356
  data: quoteAssetOracleClient_1.QUOTE_ORACLE_PRICE_DATA,
349
357
  slot: 0,
350
358
  };
351
359
  }
352
- return this.oracles.get(oraclePublicKey.toString());
360
+ return this.oracles.get(oracleString);
353
361
  }
354
362
  getOraclePriceDataAndSlotForPerpMarket(marketIndex) {
355
363
  const perpMarketAccount = this.getMarketAccountAndSlot(marketIndex);
356
364
  const oracle = this.perpOracleMap.get(marketIndex);
365
+ const oracleString = this.perpOracleStringMap.get(marketIndex);
357
366
  if (!perpMarketAccount || !oracle) {
358
367
  return undefined;
359
368
  }
@@ -361,11 +370,12 @@ class PollingDriftClientAccountSubscriber {
361
370
  // If the oracle has changed, we need to update the oracle map in background
362
371
  this.setPerpOracleMap();
363
372
  }
364
- return this.getOraclePriceDataAndSlot(oracle);
373
+ return this.getOraclePriceDataAndSlot(oracleString);
365
374
  }
366
375
  getOraclePriceDataAndSlotForSpotMarket(marketIndex) {
367
376
  const spotMarketAccount = this.getSpotMarketAccountAndSlot(marketIndex);
368
377
  const oracle = this.spotOracleMap.get(marketIndex);
378
+ const oracleString = this.spotOracleStringMap.get(marketIndex);
369
379
  if (!spotMarketAccount || !oracle) {
370
380
  return undefined;
371
381
  }
@@ -373,7 +383,7 @@ class PollingDriftClientAccountSubscriber {
373
383
  // If the oracle has changed, we need to update the oracle map in background
374
384
  this.setSpotOracleMap();
375
385
  }
376
- return this.getOraclePriceDataAndSlot(oracle);
386
+ return this.getOraclePriceDataAndSlot(oracleString);
377
387
  }
378
388
  updateAccountLoaderPollingFrequency(pollingFrequency) {
379
389
  this.accountLoader.updatePollingFrequency(pollingFrequency);
@@ -45,7 +45,7 @@ export interface DriftClientAccountSubscriber {
45
45
  getMarketAccountsAndSlots(): DataAndSlot<PerpMarketAccount>[];
46
46
  getSpotMarketAccountAndSlot(marketIndex: number): DataAndSlot<SpotMarketAccount> | undefined;
47
47
  getSpotMarketAccountsAndSlots(): DataAndSlot<SpotMarketAccount>[];
48
- getOraclePriceDataAndSlot(oraclePublicKey: PublicKey): DataAndSlot<OraclePriceData> | undefined;
48
+ getOraclePriceDataAndSlot(oraclePublicKey: PublicKey | string): DataAndSlot<OraclePriceData> | undefined;
49
49
  getOraclePriceDataAndSlotForPerpMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
50
50
  getOraclePriceDataAndSlotForSpotMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
51
51
  updateAccountLoaderPollingFrequency?: (pollingFrequency: number) => void;
@@ -22,14 +22,21 @@ export declare class WebSocketDriftClientAccountSubscriber implements DriftClien
22
22
  stateAccountSubscriber?: AccountSubscriber<StateAccount>;
23
23
  perpMarketAccountSubscribers: Map<number, AccountSubscriber<PerpMarketAccount>>;
24
24
  perpOracleMap: Map<number, PublicKey>;
25
+ perpOracleStringMap: Map<number, string>;
25
26
  spotMarketAccountSubscribers: Map<number, AccountSubscriber<SpotMarketAccount>>;
26
27
  spotOracleMap: Map<number, PublicKey>;
28
+ spotOracleStringMap: Map<number, string>;
27
29
  oracleSubscribers: Map<string, AccountSubscriber<OraclePriceData>>;
30
+ initialPerpMarketAccountData: Map<number, PerpMarketAccount>;
31
+ initialSpotMarketAccountData: Map<number, SpotMarketAccount>;
32
+ initialOraclePriceData: Map<string, OraclePriceData>;
28
33
  private isSubscribing;
29
34
  private subscriptionPromise;
30
35
  private subscriptionPromiseResolver;
31
36
  constructor(program: Program, perpMarketIndexes: number[], spotMarketIndexes: number[], oracleInfos: OracleInfo[], shouldFindAllMarketsAndOracles: boolean, resubOpts?: ResubOpts, commitment?: Commitment);
32
37
  subscribe(): Promise<boolean>;
38
+ setInitialData(): Promise<void>;
39
+ removeInitialData(): void;
33
40
  subscribeToPerpMarketAccounts(): Promise<boolean>;
34
41
  subscribeToPerpMarketAccount(marketIndex: number): Promise<boolean>;
35
42
  subscribeToSpotMarketAccounts(): Promise<boolean>;
@@ -52,7 +59,7 @@ export declare class WebSocketDriftClientAccountSubscriber implements DriftClien
52
59
  getMarketAccountsAndSlots(): DataAndSlot<PerpMarketAccount>[];
53
60
  getSpotMarketAccountAndSlot(marketIndex: number): DataAndSlot<SpotMarketAccount> | undefined;
54
61
  getSpotMarketAccountsAndSlots(): DataAndSlot<SpotMarketAccount>[];
55
- getOraclePriceDataAndSlot(oraclePublicKey: PublicKey): DataAndSlot<OraclePriceData> | undefined;
62
+ getOraclePriceDataAndSlot(oraclePublicKey: PublicKey | string): DataAndSlot<OraclePriceData> | undefined;
56
63
  getOraclePriceDataAndSlotForPerpMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
57
64
  getOraclePriceDataAndSlotForSpotMarket(marketIndex: number): DataAndSlot<OraclePriceData> | undefined;
58
65
  }
@@ -9,13 +9,16 @@ const web3_js_1 = require("@solana/web3.js");
9
9
  const oracleClientCache_1 = require("../oracles/oracleClientCache");
10
10
  const quoteAssetOracleClient_1 = require("../oracles/quoteAssetOracleClient");
11
11
  const config_1 = require("../config");
12
+ const ORACLE_DEFAULT_KEY = web3_js_1.PublicKey.default.toBase58();
12
13
  class WebSocketDriftClientAccountSubscriber {
13
14
  constructor(program, perpMarketIndexes, spotMarketIndexes, oracleInfos, shouldFindAllMarketsAndOracles, resubOpts, commitment) {
14
15
  this.oracleClientCache = new oracleClientCache_1.OracleClientCache();
15
16
  this.perpMarketAccountSubscribers = new Map();
16
17
  this.perpOracleMap = new Map();
18
+ this.perpOracleStringMap = new Map();
17
19
  this.spotMarketAccountSubscribers = new Map();
18
20
  this.spotOracleMap = new Map();
21
+ this.spotOracleStringMap = new Map();
19
22
  this.oracleSubscribers = new Map();
20
23
  this.isSubscribing = false;
21
24
  this.isSubscribed = false;
@@ -40,10 +43,13 @@ class WebSocketDriftClientAccountSubscriber {
40
43
  this.subscriptionPromiseResolver = res;
41
44
  });
42
45
  if (this.shouldFindAllMarketsAndOracles) {
43
- const { perpMarketIndexes, spotMarketIndexes, oracleInfos } = await (0, config_1.findAllMarketAndOracles)(this.program);
46
+ const { perpMarketIndexes, perpMarketAccounts, spotMarketIndexes, spotMarketAccounts, oracleInfos, } = await (0, config_1.findAllMarketAndOracles)(this.program);
44
47
  this.perpMarketIndexes = perpMarketIndexes;
45
48
  this.spotMarketIndexes = spotMarketIndexes;
46
49
  this.oracleInfos = oracleInfos;
50
+ // front run and set the initial data here to save extra gma call in set initial data
51
+ this.initialPerpMarketAccountData = new Map(perpMarketAccounts.map((market) => [market.marketIndex, market]));
52
+ this.initialSpotMarketAccountData = new Map(spotMarketAccounts.map((market) => [market.marketIndex, market]));
47
53
  }
48
54
  const statePublicKey = await (0, pda_1.getDriftStateAccountPublicKey)(this.program.programId);
49
55
  // create and activate main state account subscription
@@ -52,6 +58,8 @@ class WebSocketDriftClientAccountSubscriber {
52
58
  this.eventEmitter.emit('stateAccountUpdate', data);
53
59
  this.eventEmitter.emit('update');
54
60
  });
61
+ // set initial data to avoid spamming getAccountInfo calls in webSocketAccountSubscriber
62
+ await this.setInitialData();
55
63
  await Promise.all([
56
64
  // subscribe to market accounts
57
65
  this.subscribeToPerpMarketAccounts(),
@@ -65,8 +73,48 @@ class WebSocketDriftClientAccountSubscriber {
65
73
  this.isSubscribing = false;
66
74
  this.isSubscribed = true;
67
75
  this.subscriptionPromiseResolver(true);
76
+ // delete initial data
77
+ this.removeInitialData();
68
78
  return true;
69
79
  }
80
+ async setInitialData() {
81
+ const connection = this.program.provider.connection;
82
+ if (!this.initialPerpMarketAccountData) {
83
+ const perpMarketPublicKeys = this.perpMarketIndexes.map((marketIndex) => (0, pda_1.getPerpMarketPublicKeySync)(this.program.programId, marketIndex));
84
+ const perpMarketAccountInfos = await connection.getMultipleAccountsInfo(perpMarketPublicKeys);
85
+ this.initialPerpMarketAccountData = new Map(perpMarketAccountInfos
86
+ .filter((accountInfo) => !!accountInfo)
87
+ .map((accountInfo) => {
88
+ const perpMarket = this.program.coder.accounts.decode('PerpMarket', accountInfo.data);
89
+ return [perpMarket.marketIndex, perpMarket];
90
+ }));
91
+ }
92
+ if (!this.initialSpotMarketAccountData) {
93
+ const spotMarketPublicKeys = this.spotMarketIndexes.map((marketIndex) => (0, pda_1.getSpotMarketPublicKeySync)(this.program.programId, marketIndex));
94
+ const spotMarketAccountInfos = await connection.getMultipleAccountsInfo(spotMarketPublicKeys);
95
+ this.initialSpotMarketAccountData = new Map(spotMarketAccountInfos
96
+ .filter((accountInfo) => !!accountInfo)
97
+ .map((accountInfo) => {
98
+ const spotMarket = this.program.coder.accounts.decode('SpotMarket', accountInfo.data);
99
+ return [spotMarket.marketIndex, spotMarket];
100
+ }));
101
+ }
102
+ const oracleAccountInfos = await connection.getMultipleAccountsInfo(this.oracleInfos.map((oracleInfo) => oracleInfo.publicKey));
103
+ this.initialOraclePriceData = new Map(this.oracleInfos.reduce((result, oracleInfo, i) => {
104
+ if (!oracleAccountInfos[i]) {
105
+ return result;
106
+ }
107
+ const oracleClient = this.oracleClientCache.get(oracleInfo.source, connection, this.program);
108
+ const oraclePriceData = oracleClient.getOraclePriceDataFromBuffer(oracleAccountInfos[i].data);
109
+ result.push([oracleInfo.publicKey.toString(), oraclePriceData]);
110
+ return result;
111
+ }, []));
112
+ }
113
+ removeInitialData() {
114
+ this.initialPerpMarketAccountData = new Map();
115
+ this.initialSpotMarketAccountData = new Map();
116
+ this.initialOraclePriceData = new Map();
117
+ }
70
118
  async subscribeToPerpMarketAccounts() {
71
119
  await Promise.all(this.perpMarketIndexes.map((marketIndex) => this.subscribeToPerpMarketAccount(marketIndex)));
72
120
  return true;
@@ -74,6 +122,7 @@ class WebSocketDriftClientAccountSubscriber {
74
122
  async subscribeToPerpMarketAccount(marketIndex) {
75
123
  const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, marketIndex);
76
124
  const accountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('perpMarket', this.program, perpMarketPublicKey, undefined, this.resubOpts, this.commitment);
125
+ accountSubscriber.setData(this.initialPerpMarketAccountData.get(marketIndex));
77
126
  await accountSubscriber.subscribe((data) => {
78
127
  this.eventEmitter.emit('perpMarketAccountUpdate', data);
79
128
  this.eventEmitter.emit('update');
@@ -88,6 +137,7 @@ class WebSocketDriftClientAccountSubscriber {
88
137
  async subscribeToSpotMarketAccount(marketIndex) {
89
138
  const marketPublicKey = await (0, pda_1.getSpotMarketPublicKey)(this.program.programId, marketIndex);
90
139
  const accountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('spotMarket', this.program, marketPublicKey, undefined, this.resubOpts, this.commitment);
140
+ accountSubscriber.setData(this.initialSpotMarketAccountData.get(marketIndex));
91
141
  await accountSubscriber.subscribe((data) => {
92
142
  this.eventEmitter.emit('spotMarketAccountUpdate', data);
93
143
  this.eventEmitter.emit('update');
@@ -102,15 +152,20 @@ class WebSocketDriftClientAccountSubscriber {
102
152
  return true;
103
153
  }
104
154
  async subscribeToOracle(oracleInfo) {
155
+ const oracleString = oracleInfo.publicKey.toString();
105
156
  const client = this.oracleClientCache.get(oracleInfo.source, this.program.provider.connection, this.program);
106
157
  const accountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('oracle', this.program, oracleInfo.publicKey, (buffer) => {
107
158
  return client.getOraclePriceDataFromBuffer(buffer);
108
159
  }, this.resubOpts, this.commitment);
160
+ const initialOraclePriceData = this.initialOraclePriceData.get(oracleString);
161
+ if (initialOraclePriceData) {
162
+ accountSubscriber.setData(initialOraclePriceData);
163
+ }
109
164
  await accountSubscriber.subscribe((data) => {
110
165
  this.eventEmitter.emit('oraclePriceUpdate', oracleInfo.publicKey, data);
111
166
  this.eventEmitter.emit('update');
112
167
  });
113
- this.oracleSubscribers.set(oracleInfo.publicKey.toString(), accountSubscriber);
168
+ this.oracleSubscribers.set(oracleString, accountSubscriber);
114
169
  return true;
115
170
  }
116
171
  async unsubscribeFromMarketAccounts() {
@@ -170,7 +225,7 @@ class WebSocketDriftClientAccountSubscriber {
170
225
  const perpMarkets = this.getMarketAccountsAndSlots();
171
226
  const addOraclePromises = [];
172
227
  for (const perpMarket of perpMarkets) {
173
- if (!perpMarket) {
228
+ if (!perpMarket || !perpMarket.data) {
174
229
  continue;
175
230
  }
176
231
  const perpMarketAccount = perpMarket.data;
@@ -183,6 +238,7 @@ class WebSocketDriftClientAccountSubscriber {
183
238
  }));
184
239
  }
185
240
  this.perpOracleMap.set(perpMarketIndex, oracle);
241
+ this.perpOracleStringMap.set(perpMarketIndex, oracle.toBase58());
186
242
  }
187
243
  await Promise.all(addOraclePromises);
188
244
  }
@@ -190,7 +246,7 @@ class WebSocketDriftClientAccountSubscriber {
190
246
  const spotMarkets = this.getSpotMarketAccountsAndSlots();
191
247
  const addOraclePromises = [];
192
248
  for (const spotMarket of spotMarkets) {
193
- if (!spotMarket) {
249
+ if (!spotMarket || !spotMarket.data) {
194
250
  continue;
195
251
  }
196
252
  const spotMarketAccount = spotMarket.data;
@@ -203,6 +259,7 @@ class WebSocketDriftClientAccountSubscriber {
203
259
  }));
204
260
  }
205
261
  this.spotOracleMap.set(spotMarketIndex, oracle);
262
+ this.spotOracleStringMap.set(spotMarketIndex, oracle.toBase58());
206
263
  }
207
264
  await Promise.all(addOraclePromises);
208
265
  }
@@ -231,17 +288,21 @@ class WebSocketDriftClientAccountSubscriber {
231
288
  }
232
289
  getOraclePriceDataAndSlot(oraclePublicKey) {
233
290
  this.assertIsSubscribed();
234
- if (oraclePublicKey.equals(web3_js_1.PublicKey.default)) {
291
+ const oracleString = typeof oraclePublicKey === 'string'
292
+ ? oraclePublicKey
293
+ : oraclePublicKey.toBase58();
294
+ if (oracleString === ORACLE_DEFAULT_KEY) {
235
295
  return {
236
296
  data: quoteAssetOracleClient_1.QUOTE_ORACLE_PRICE_DATA,
237
297
  slot: 0,
238
298
  };
239
299
  }
240
- return this.oracleSubscribers.get(oraclePublicKey.toString()).dataAndSlot;
300
+ return this.oracleSubscribers.get(oracleString).dataAndSlot;
241
301
  }
242
302
  getOraclePriceDataAndSlotForPerpMarket(marketIndex) {
243
303
  const perpMarketAccount = this.getMarketAccountAndSlot(marketIndex);
244
304
  const oracle = this.perpOracleMap.get(marketIndex);
305
+ const oracleString = this.perpOracleStringMap.get(marketIndex);
245
306
  if (!perpMarketAccount || !oracle) {
246
307
  return undefined;
247
308
  }
@@ -249,11 +310,12 @@ class WebSocketDriftClientAccountSubscriber {
249
310
  // If the oracle has changed, we need to update the oracle map in background
250
311
  this.setPerpOracleMap();
251
312
  }
252
- return this.getOraclePriceDataAndSlot(oracle);
313
+ return this.getOraclePriceDataAndSlot(oracleString);
253
314
  }
254
315
  getOraclePriceDataAndSlotForSpotMarket(marketIndex) {
255
316
  const spotMarketAccount = this.getSpotMarketAccountAndSlot(marketIndex);
256
317
  const oracle = this.spotOracleMap.get(marketIndex);
318
+ const oracleString = this.spotOracleStringMap.get(marketIndex);
257
319
  if (!spotMarketAccount || !oracle) {
258
320
  return undefined;
259
321
  }
@@ -261,7 +323,7 @@ class WebSocketDriftClientAccountSubscriber {
261
323
  // If the oracle has changed, we need to update the oracle map in background
262
324
  this.setSpotOracleMap();
263
325
  }
264
- return this.getOraclePriceDataAndSlot(oracle);
326
+ return this.getOraclePriceDataAndSlot(oracleString);
265
327
  }
266
328
  }
267
329
  exports.WebSocketDriftClientAccountSubscriber = WebSocketDriftClientAccountSubscriber;
@@ -9,7 +9,9 @@ export declare function getUserAccountPublicKey(programId: PublicKey, authority:
9
9
  export declare function getUserAccountPublicKeySync(programId: PublicKey, authority: PublicKey, subAccountId?: number): PublicKey;
10
10
  export declare function getUserStatsAccountPublicKey(programId: PublicKey, authority: PublicKey): PublicKey;
11
11
  export declare function getPerpMarketPublicKey(programId: PublicKey, marketIndex: number): Promise<PublicKey>;
12
+ export declare function getPerpMarketPublicKeySync(programId: PublicKey, marketIndex: number): PublicKey;
12
13
  export declare function getSpotMarketPublicKey(programId: PublicKey, marketIndex: number): Promise<PublicKey>;
14
+ export declare function getSpotMarketPublicKeySync(programId: PublicKey, marketIndex: number): PublicKey;
13
15
  export declare function getSpotMarketVaultPublicKey(programId: PublicKey, marketIndex: number): Promise<PublicKey>;
14
16
  export declare function getInsuranceFundVaultPublicKey(programId: PublicKey, marketIndex: number): Promise<PublicKey>;
15
17
  export declare function getInsuranceFundStakeAccountPublicKey(programId: PublicKey, authority: PublicKey, marketIndex: number): PublicKey;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getTokenProgramForSpotMarket = exports.getPythPullOraclePublicKey = exports.getPrelaunchOraclePublicKey = exports.getProtocolIfSharesTransferConfigPublicKey = exports.getReferrerNamePublicKeySync = exports.getOpenbookV2FulfillmentConfigPublicKey = exports.getPhoenixFulfillmentConfigPublicKey = exports.getSerumFulfillmentConfigPublicKey = exports.getSerumSignerPublicKey = exports.getSerumOpenOrdersPublicKey = exports.getDriftSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getSpotMarketVaultPublicKey = exports.getSpotMarketPublicKey = exports.getPerpMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getDriftStateAccountPublicKey = exports.getDriftStateAccountPublicKeyAndNonce = void 0;
26
+ exports.getTokenProgramForSpotMarket = exports.getPythPullOraclePublicKey = exports.getPrelaunchOraclePublicKey = exports.getProtocolIfSharesTransferConfigPublicKey = exports.getReferrerNamePublicKeySync = exports.getOpenbookV2FulfillmentConfigPublicKey = exports.getPhoenixFulfillmentConfigPublicKey = exports.getSerumFulfillmentConfigPublicKey = exports.getSerumSignerPublicKey = exports.getSerumOpenOrdersPublicKey = exports.getDriftSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getSpotMarketVaultPublicKey = exports.getSpotMarketPublicKeySync = exports.getSpotMarketPublicKey = exports.getPerpMarketPublicKeySync = exports.getPerpMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getDriftStateAccountPublicKey = exports.getDriftStateAccountPublicKeyAndNonce = void 0;
27
27
  const web3_js_1 = require("@solana/web3.js");
28
28
  const anchor = __importStar(require("@coral-xyz/anchor"));
29
29
  const spl_token_1 = require("@solana/spl-token");
@@ -69,6 +69,13 @@ async function getPerpMarketPublicKey(programId, marketIndex) {
69
69
  ], programId))[0];
70
70
  }
71
71
  exports.getPerpMarketPublicKey = getPerpMarketPublicKey;
72
+ function getPerpMarketPublicKeySync(programId, marketIndex) {
73
+ return web3_js_1.PublicKey.findProgramAddressSync([
74
+ Buffer.from(anchor.utils.bytes.utf8.encode('perp_market')),
75
+ new anchor.BN(marketIndex).toArrayLike(Buffer, 'le', 2),
76
+ ], programId)[0];
77
+ }
78
+ exports.getPerpMarketPublicKeySync = getPerpMarketPublicKeySync;
72
79
  async function getSpotMarketPublicKey(programId, marketIndex) {
73
80
  return (await web3_js_1.PublicKey.findProgramAddress([
74
81
  Buffer.from(anchor.utils.bytes.utf8.encode('spot_market')),
@@ -76,6 +83,13 @@ async function getSpotMarketPublicKey(programId, marketIndex) {
76
83
  ], programId))[0];
77
84
  }
78
85
  exports.getSpotMarketPublicKey = getSpotMarketPublicKey;
86
+ function getSpotMarketPublicKeySync(programId, marketIndex) {
87
+ return web3_js_1.PublicKey.findProgramAddressSync([
88
+ Buffer.from(anchor.utils.bytes.utf8.encode('spot_market')),
89
+ new anchor.BN(marketIndex).toArrayLike(Buffer, 'le', 2),
90
+ ], programId)[0];
91
+ }
92
+ exports.getSpotMarketPublicKeySync = getSpotMarketPublicKeySync;
79
93
  async function getSpotMarketVaultPublicKey(programId, marketIndex) {
80
94
  return (await web3_js_1.PublicKey.findProgramAddress([
81
95
  Buffer.from(anchor.utils.bytes.utf8.encode('spot_market_vault')),
package/lib/config.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { PerpMarketAccount, SpotMarketAccount } from '.';
1
2
  import { PerpMarketConfig } from './constants/perpMarkets';
2
3
  import { SpotMarketConfig } from './constants/spotMarkets';
3
4
  import { OracleInfo } from './oracles/types';
@@ -44,7 +45,9 @@ export declare function getMarketsAndOraclesForSubscription(env: DriftEnv): {
44
45
  };
45
46
  export declare function findAllMarketAndOracles(program: Program): Promise<{
46
47
  perpMarketIndexes: number[];
48
+ perpMarketAccounts: PerpMarketAccount[];
47
49
  spotMarketIndexes: number[];
48
50
  oracleInfos: OracleInfo[];
51
+ spotMarketAccounts: SpotMarketAccount[];
49
52
  }>;
50
53
  export {};
package/lib/config.js CHANGED
@@ -106,7 +106,9 @@ async function findAllMarketAndOracles(program) {
106
106
  }
107
107
  return {
108
108
  perpMarketIndexes,
109
+ perpMarketAccounts: perpMarketProgramAccounts.map((account) => account.account),
109
110
  spotMarketIndexes,
111
+ spotMarketAccounts: spotMarketProgramAccounts.map((account) => account.account),
110
112
  oracleInfos: Array.from(oracleInfos.values()),
111
113
  };
112
114
  }
@@ -333,6 +333,16 @@ exports.MainnetSpotMarkets = [
333
333
  precisionExp: numericConstants_1.NINE,
334
334
  pythFeedId: '0xca3ba9a619a4b3755c10ac7d5e760275aa95e9823d38a84fedd416856cdba37c',
335
335
  },
336
+ {
337
+ symbol: 'BNSOL',
338
+ marketIndex: 25,
339
+ oracle: new web3_js_1.PublicKey('BAtFj4kQttZRVep3UZS2aZRDixkGYgWsbqTBVDbnSsPF'),
340
+ oracleSource: __1.OracleSource.PYTH_PULL,
341
+ mint: new web3_js_1.PublicKey('BNso1VUJnh4zcfpZa6986Ea66P6TCp59hvtNJ8b1X85'),
342
+ precision: numericConstants_1.LAMPORTS_PRECISION,
343
+ precisionExp: numericConstants_1.LAMPORTS_EXP,
344
+ pythFeedId: '0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d',
345
+ },
336
346
  ];
337
347
  exports.SpotMarkets = {
338
348
  devnet: exports.DevnetSpotMarkets,
@@ -309,7 +309,7 @@ class DriftClient {
309
309
  return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
310
310
  }
311
311
  getOraclePriceDataAndSlot(oraclePublicKey) {
312
- return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
312
+ return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey.toBase58());
313
313
  }
314
314
  async getSerumV3FulfillmentConfig(serumMarket) {
315
315
  const address = await (0, pda_1.getSerumFulfillmentConfigPublicKey)(this.program.programId, serumMarket);
@@ -1725,10 +1725,14 @@ class DriftClient {
1725
1725
  writablePerpMarketIndexes: [marketIndex],
1726
1726
  writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1727
1727
  });
1728
+ const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, marketIndex);
1728
1729
  return await this.program.instruction.settleExpiredMarket(marketIndex, {
1729
1730
  accounts: {
1730
1731
  state: await this.getStatePublicKey(),
1731
- authority: this.wallet.publicKey,
1732
+ admin: this.isSubscribed
1733
+ ? this.getStateAccount().admin
1734
+ : this.wallet.publicKey,
1735
+ perpMarket: perpMarketPublicKey,
1732
1736
  },
1733
1737
  remainingAccounts,
1734
1738
  });
@@ -7,23 +7,7 @@ const PROGRAM_DATA = 'Program data: ';
7
7
  const PROGRAM_LOG_START_INDEX = PROGRAM_LOG.length;
8
8
  const PROGRAM_DATA_START_INDEX = PROGRAM_DATA.length;
9
9
  function parseLogs(program, logs, programId = driftProgramId) {
10
- const events = [];
11
- const execution = new ExecutionContext();
12
- for (const log of logs) {
13
- if (log.startsWith('Log truncated')) {
14
- break;
15
- }
16
- const [event, newProgram, didPop] = handleLog(execution, log, program, programId);
17
- if (event) {
18
- events.push(event);
19
- }
20
- if (newProgram) {
21
- execution.push(newProgram);
22
- }
23
- if (didPop) {
24
- execution.pop();
25
- }
26
- }
10
+ const { events } = parseLogsWithRaw(program, logs, programId);
27
11
  return events;
28
12
  }
29
13
  exports.parseLogs = parseLogs;
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.94.0",
2
+ "version": "2.95.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -1606,15 +1606,20 @@
1606
1606
  {
1607
1607
  "name": "settleExpiredMarket",
1608
1608
  "accounts": [
1609
+ {
1610
+ "name": "admin",
1611
+ "isMut": false,
1612
+ "isSigner": true
1613
+ },
1609
1614
  {
1610
1615
  "name": "state",
1611
1616
  "isMut": false,
1612
1617
  "isSigner": false
1613
1618
  },
1614
1619
  {
1615
- "name": "authority",
1616
- "isMut": false,
1617
- "isSigner": true
1620
+ "name": "perpMarket",
1621
+ "isMut": true,
1622
+ "isSigner": false
1618
1623
  }
1619
1624
  ],
1620
1625
  "args": [
@@ -1,5 +1,7 @@
1
1
  /// <reference types="bn.js" />
2
- import { BN } from '../index';
2
+ import { BN, SpotMarketAccount } from '../index';
3
+ export declare function nextRevenuePoolSettleApr(spotMarket: SpotMarketAccount, vaultBalance: BN, // vault token amount
4
+ amount?: BN): number;
3
5
  export declare function stakeAmountToShares(amount: BN, totalIfShares: BN, insuranceFundVaultBalance: BN): BN;
4
6
  export declare function unstakeSharesToAmount(nShares: BN, totalIfShares: BN, insuranceFundVaultBalance: BN): BN;
5
7
  export declare function unstakeSharesToAmountWithOpenRequest(nShares: BN, withdrawRequestShares: BN, withdrawRequestAmount: BN, totalIfShares: BN, insuranceFundVaultBalance: BN): BN;
@@ -1,8 +1,38 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unstakeSharesToAmountWithOpenRequest = exports.unstakeSharesToAmount = exports.stakeAmountToShares = void 0;
3
+ exports.unstakeSharesToAmountWithOpenRequest = exports.unstakeSharesToAmount = exports.stakeAmountToShares = exports.nextRevenuePoolSettleApr = void 0;
4
4
  const numericConstants_1 = require("../constants/numericConstants");
5
5
  const index_1 = require("../index");
6
+ const spotBalance_1 = require("../math/spotBalance");
7
+ function nextRevenuePoolSettleApr(spotMarket, vaultBalance, // vault token amount
8
+ amount // delta token amount
9
+ ) {
10
+ const MAX_APR = new index_1.BN(10).mul(numericConstants_1.PERCENTAGE_PRECISION); // 1000% APR
11
+ // Conmputing the APR:
12
+ const revenuePoolBN = (0, spotBalance_1.getTokenAmount)(spotMarket.revenuePool.scaledBalance, spotMarket, index_1.SpotBalanceType.DEPOSIT);
13
+ const payoutRatio = 0.1;
14
+ const ratioForStakers = spotMarket.insuranceFund.totalFactor > 0 &&
15
+ spotMarket.insuranceFund.userFactor > 0 &&
16
+ spotMarket.insuranceFund.revenueSettlePeriod.gt(numericConstants_1.ZERO)
17
+ ? spotMarket.insuranceFund.userFactor /
18
+ spotMarket.insuranceFund.totalFactor
19
+ : 0;
20
+ // Settle periods from on-chain data:
21
+ const revSettlePeriod = spotMarket.insuranceFund.revenueSettlePeriod.toNumber() * 1000;
22
+ const settlesPerYear = 31536000000 / revSettlePeriod;
23
+ const projectedAnnualRev = revenuePoolBN
24
+ .muln(settlesPerYear)
25
+ .muln(payoutRatio);
26
+ const uncappedApr = vaultBalance.add(amount).eq(numericConstants_1.ZERO)
27
+ ? 0
28
+ : projectedAnnualRev.muln(1000).div(vaultBalance.add(amount)).toNumber() *
29
+ 100 *
30
+ 1000;
31
+ const cappedApr = Math.min(uncappedApr, MAX_APR.toNumber());
32
+ const nextApr = cappedApr * ratioForStakers;
33
+ return nextApr;
34
+ }
35
+ exports.nextRevenuePoolSettleApr = nextRevenuePoolSettleApr;
6
36
  function stakeAmountToShares(amount, totalIfShares, insuranceFundVaultBalance) {
7
37
  let nShares;
8
38
  if (insuranceFundVaultBalance.gt(numericConstants_1.ZERO)) {
@@ -62,9 +62,9 @@ export declare function calculateSpotMarketBorrowCapacity(spotMarketAccount: Spo
62
62
  totalCapacity: BN;
63
63
  remainingCapacity: BN;
64
64
  };
65
- export declare function calculateInterestRate(bank: SpotMarketAccount, delta?: BN): BN;
66
- export declare function calculateDepositRate(bank: SpotMarketAccount, delta?: BN): BN;
67
- export declare function calculateBorrowRate(bank: SpotMarketAccount, delta?: BN): BN;
65
+ export declare function calculateInterestRate(bank: SpotMarketAccount, delta?: BN, currentUtilization?: BN): BN;
66
+ export declare function calculateDepositRate(bank: SpotMarketAccount, delta?: BN, currentUtilization?: BN): BN;
67
+ export declare function calculateBorrowRate(bank: SpotMarketAccount, delta?: BN, currentUtilization?: BN): BN;
68
68
  export declare function calculateInterestAccumulated(bank: SpotMarketAccount, now: BN): {
69
69
  borrowInterest: BN;
70
70
  depositInterest: BN;
@@ -246,8 +246,8 @@ function calculateSpotMarketBorrowCapacity(spotMarketAccount, targetBorrowRate)
246
246
  return { totalCapacity, remainingCapacity };
247
247
  }
248
248
  exports.calculateSpotMarketBorrowCapacity = calculateSpotMarketBorrowCapacity;
249
- function calculateInterestRate(bank, delta = numericConstants_1.ZERO) {
250
- const utilization = calculateUtilization(bank, delta);
249
+ function calculateInterestRate(bank, delta = numericConstants_1.ZERO, currentUtilization = null) {
250
+ const utilization = currentUtilization || calculateUtilization(bank, delta);
251
251
  let interestRate;
252
252
  if (utilization.gt(new anchor_1.BN(bank.optimalUtilization))) {
253
253
  const surplusUtilization = utilization.sub(new anchor_1.BN(bank.optimalUtilization));
@@ -269,11 +269,11 @@ function calculateInterestRate(bank, delta = numericConstants_1.ZERO) {
269
269
  return anchor_1.BN.max(interestRate, new anchor_1.BN(bank.minBorrowRate).mul(numericConstants_2.PERCENTAGE_PRECISION.divn(200)));
270
270
  }
271
271
  exports.calculateInterestRate = calculateInterestRate;
272
- function calculateDepositRate(bank, delta = numericConstants_1.ZERO) {
272
+ function calculateDepositRate(bank, delta = numericConstants_1.ZERO, currentUtilization = null) {
273
273
  // positive delta => adding to deposit
274
274
  // negative delta => adding to borrow
275
- const utilization = calculateUtilization(bank, delta);
276
- const borrowRate = calculateBorrowRate(bank, delta);
275
+ const utilization = currentUtilization || calculateUtilization(bank, delta);
276
+ const borrowRate = calculateBorrowRate(bank, delta, utilization);
277
277
  const depositRate = borrowRate
278
278
  .mul(numericConstants_2.PERCENTAGE_PRECISION.sub(new anchor_1.BN(bank.insuranceFund.totalFactor)))
279
279
  .mul(utilization)
@@ -282,8 +282,8 @@ function calculateDepositRate(bank, delta = numericConstants_1.ZERO) {
282
282
  return depositRate;
283
283
  }
284
284
  exports.calculateDepositRate = calculateDepositRate;
285
- function calculateBorrowRate(bank, delta = numericConstants_1.ZERO) {
286
- return calculateInterestRate(bank, delta);
285
+ function calculateBorrowRate(bank, delta = numericConstants_1.ZERO, currentUtilization = null) {
286
+ return calculateInterestRate(bank, delta, currentUtilization);
287
287
  }
288
288
  exports.calculateBorrowRate = calculateBorrowRate;
289
289
  function calculateInterestAccumulated(bank, now) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.95.0-beta.9",
3
+ "version": "2.96.0-beta.0",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",