@drift-labs/sdk 2.83.0-beta.9 → 2.84.0-beta.1

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.
@@ -15,7 +15,7 @@ class UserMap {
15
15
  * Constructs a new UserMap instance.
16
16
  */
17
17
  constructor(config) {
18
- var _a, _b, _c, _d;
18
+ var _a, _b, _c, _d, _e;
19
19
  this.userMap = new Map();
20
20
  this.stateAccountUpdateCallback = async (state) => {
21
21
  if (!state.numberOfSubAccounts.eq(this.lastNumberOfSubAccounts)) {
@@ -64,6 +64,9 @@ class UserMap {
64
64
  decodeFn,
65
65
  });
66
66
  }
67
+ this.syncConfig = (_e = config.syncConfig) !== null && _e !== void 0 ? _e : {
68
+ type: 'default',
69
+ };
67
70
  }
68
71
  async subscribe() {
69
72
  if (this.size() > 0) {
@@ -230,6 +233,14 @@ class UserMap {
230
233
  return userAuthKeys;
231
234
  }
232
235
  async sync() {
236
+ if (this.syncConfig.type === 'default') {
237
+ return this.defaultSync();
238
+ }
239
+ else {
240
+ return this.paginatedSync();
241
+ }
242
+ }
243
+ async defaultSync() {
233
244
  var _a;
234
245
  if (this.syncPromise) {
235
246
  return this.syncPromise;
@@ -298,6 +309,97 @@ class UserMap {
298
309
  this.syncPromise = undefined;
299
310
  }
300
311
  }
312
+ async paginatedSync() {
313
+ var _a, _b;
314
+ if (this.syncPromise) {
315
+ return this.syncPromise;
316
+ }
317
+ this.syncPromise = new Promise((resolve) => {
318
+ this.syncPromiseResolver = resolve;
319
+ });
320
+ try {
321
+ const accountsPrefetch = await this.connection.getProgramAccounts(this.driftClient.program.programId, {
322
+ dataSlice: { offset: 0, length: 0 },
323
+ filters: [
324
+ (0, memcmp_1.getUserFilter)(),
325
+ ...(!this.includeIdle ? [(0, memcmp_1.getNonIdleUserFilter)()] : []),
326
+ ],
327
+ });
328
+ const accountPublicKeys = accountsPrefetch.map((account) => account.pubkey);
329
+ const limitConcurrency = async (tasks, limit) => {
330
+ const executing = [];
331
+ const results = [];
332
+ for (let i = 0; i < tasks.length; i++) {
333
+ const executor = Promise.resolve().then(tasks[i]);
334
+ results.push(executor);
335
+ if (executing.length < limit) {
336
+ executing.push(executor);
337
+ executor.finally(() => {
338
+ const index = executing.indexOf(executor);
339
+ if (index > -1) {
340
+ executing.splice(index, 1);
341
+ }
342
+ });
343
+ }
344
+ else {
345
+ await Promise.race(executing);
346
+ }
347
+ }
348
+ return Promise.all(results);
349
+ };
350
+ const programAccountBufferMap = new Map();
351
+ // @ts-ignore
352
+ const chunkSize = (_a = this.syncConfig.chunkSize) !== null && _a !== void 0 ? _a : 100;
353
+ const tasks = [];
354
+ for (let i = 0; i < accountPublicKeys.length; i += chunkSize) {
355
+ const chunk = accountPublicKeys.slice(i, i + chunkSize);
356
+ tasks.push(async () => {
357
+ const accountInfos = await this.connection.getMultipleAccountsInfoAndContext(chunk, {
358
+ commitment: this.commitment,
359
+ });
360
+ const accountInfosSlot = accountInfos.context.slot;
361
+ for (let j = 0; j < accountInfos.value.length; j += 1) {
362
+ const accountInfo = accountInfos.value[j];
363
+ if (accountInfo === null)
364
+ continue;
365
+ const publicKeyString = chunk[j].toString();
366
+ const buffer = buffer_1.Buffer.from(accountInfo.data);
367
+ programAccountBufferMap.set(publicKeyString, buffer);
368
+ const decodedUser = this.decode('User', buffer);
369
+ const currAccountWithSlot = this.getWithSlot(publicKeyString);
370
+ if (currAccountWithSlot &&
371
+ currAccountWithSlot.slot <= accountInfosSlot) {
372
+ this.updateUserAccount(publicKeyString, decodedUser, accountInfosSlot);
373
+ }
374
+ else {
375
+ await this.addPubkey(new web3_js_1.PublicKey(publicKeyString), decodedUser, accountInfosSlot);
376
+ }
377
+ }
378
+ });
379
+ }
380
+ // @ts-ignore
381
+ const concurrencyLimit = (_b = this.syncConfig.concurrencyLimit) !== null && _b !== void 0 ? _b : 10;
382
+ await limitConcurrency(tasks, concurrencyLimit);
383
+ for (const [key] of this.entries()) {
384
+ if (!programAccountBufferMap.has(key)) {
385
+ const user = this.get(key);
386
+ if (user) {
387
+ await user.unsubscribe();
388
+ this.userMap.delete(key);
389
+ }
390
+ }
391
+ }
392
+ }
393
+ catch (err) {
394
+ console.error(`Error in UserMap.sync():`, err);
395
+ }
396
+ finally {
397
+ if (this.syncPromiseResolver) {
398
+ this.syncPromiseResolver();
399
+ }
400
+ this.syncPromise = undefined;
401
+ }
402
+ }
301
403
  async unsubscribe() {
302
404
  await this.subscription.unsubscribe();
303
405
  for (const [key, user] of this.entries()) {
@@ -3,6 +3,13 @@ import { DriftClient } from '../driftClient';
3
3
  export type UserAccountFilterCriteria = {
4
4
  hasOpenOrders: boolean;
5
5
  };
6
+ export type SyncConfig = {
7
+ type: 'default';
8
+ } | {
9
+ type: 'paginated';
10
+ chunkSize?: number;
11
+ concurrencyLimit?: number;
12
+ };
6
13
  export type UserMapConfig = {
7
14
  driftClient: DriftClient;
8
15
  connection?: Connection;
@@ -20,4 +27,5 @@ export type UserMapConfig = {
20
27
  includeIdle?: boolean;
21
28
  fastDecode?: boolean;
22
29
  disableSyncOnTotalAccountsChange?: boolean;
30
+ syncConfig?: SyncConfig;
23
31
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.83.0-beta.9",
3
+ "version": "2.84.0-beta.1",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -102,9 +102,11 @@ export class AdminClient extends DriftClient {
102
102
  orderTickSize = ONE,
103
103
  orderStepSize = ONE,
104
104
  ifTotalFactor = 0,
105
- name = DEFAULT_MARKET_NAME
105
+ name = DEFAULT_MARKET_NAME,
106
+ marketIndex?: number
106
107
  ): Promise<TransactionSignature> {
107
- const spotMarketIndex = this.getStateAccount().numberOfSpotMarkets;
108
+ const spotMarketIndex =
109
+ marketIndex ?? this.getStateAccount().numberOfSpotMarkets;
108
110
 
109
111
  const initializeIx = await this.getInitializeSpotMarketIx(
110
112
  mint,
@@ -127,15 +129,14 @@ export class AdminClient extends DriftClient {
127
129
  orderTickSize,
128
130
  orderStepSize,
129
131
  ifTotalFactor,
130
- name
132
+ name,
133
+ marketIndex
131
134
  );
132
135
 
133
136
  const tx = await this.buildTransaction(initializeIx);
134
137
 
135
138
  const { txSig } = await this.sendTransaction(tx, [], this.opts);
136
139
 
137
- // const { txSig } = await this.sendTransaction(initializeTx, [], this.opts);
138
-
139
140
  await this.accountSubscriber.addSpotMarket(spotMarketIndex);
140
141
  await this.accountSubscriber.addOracle({
141
142
  source: oracleSource,
@@ -167,9 +168,11 @@ export class AdminClient extends DriftClient {
167
168
  orderTickSize = ONE,
168
169
  orderStepSize = ONE,
169
170
  ifTotalFactor = 0,
170
- name = DEFAULT_MARKET_NAME
171
+ name = DEFAULT_MARKET_NAME,
172
+ marketIndex?: number
171
173
  ): Promise<TransactionInstruction> {
172
- const spotMarketIndex = this.getStateAccount().numberOfSpotMarkets;
174
+ const spotMarketIndex =
175
+ marketIndex ?? this.getStateAccount().numberOfSpotMarkets;
173
176
  const spotMarket = await getSpotMarketPublicKey(
174
177
  this.program.programId,
175
178
  spotMarketIndex
@@ -444,7 +447,7 @@ export class AdminClient extends DriftClient {
444
447
  await this.fetchAccounts();
445
448
  }
446
449
 
447
- await this.accountSubscriber.addPerpMarket(currentPerpMarketIndex);
450
+ await this.accountSubscriber.addPerpMarket(marketIndex);
448
451
  await this.accountSubscriber.addOracle({
449
452
  source: oracleSource,
450
453
  publicKey: priceOracle,
@@ -482,10 +485,9 @@ export class AdminClient extends DriftClient {
482
485
  ammJitIntensity = 0,
483
486
  name = DEFAULT_MARKET_NAME
484
487
  ): Promise<TransactionInstruction> {
485
- const currentPerpMarketIndex = this.getStateAccount().numberOfMarkets;
486
488
  const perpMarketPublicKey = await getPerpMarketPublicKey(
487
489
  this.program.programId,
488
- currentPerpMarketIndex
490
+ marketIndex
489
491
  );
490
492
 
491
493
  const nameBuffer = encodeName(name);
@@ -577,6 +577,26 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [
577
577
  launchTs: 1716595200000,
578
578
  oracleSource: OracleSource.SWITCHBOARD,
579
579
  },
580
+ {
581
+ fullName: 'Sanctum',
582
+ category: ['LST', 'Solana'],
583
+ symbol: 'CLOUD-PERP',
584
+ baseAssetSymbol: 'CLOUD',
585
+ marketIndex: 31,
586
+ oracle: new PublicKey('C7UxgCodaEy4yqwTe3a4QXfsG7LnpMGGQdEqaxDae4b8'),
587
+ launchTs: 1717597648000,
588
+ oracleSource: OracleSource.Prelaunch,
589
+ },
590
+ {
591
+ fullName: 'IO',
592
+ category: ['DePIN', 'Solana'],
593
+ symbol: 'IO-PERP',
594
+ baseAssetSymbol: 'IO',
595
+ marketIndex: 32,
596
+ oracle: new PublicKey('5sAqMGidMtztNFdUukyguz6jMFS8DvTmSUr4p5u5zsSg'),
597
+ launchTs: 1718021389000,
598
+ oracleSource: OracleSource.Prelaunch,
599
+ },
580
600
  ];
581
601
 
582
602
  export const PerpMarkets: { [key in DriftEnv]: PerpMarketConfig[] } = {
package/src/dlob/DLOB.ts CHANGED
@@ -76,7 +76,7 @@ type OrderBookCallback = () => void;
76
76
  * Receives a DLOBNode and is expected to return true if the node should
77
77
  * be taken into account when generating, or false otherwise.
78
78
  *
79
- * Currently used in getRestingLimitBids and getRestingLimitAsks.
79
+ * Currently used in functions that rely on getBestNode
80
80
  */
81
81
  export type DLOBFilterFcn = (node: DLOBNode) => boolean;
82
82
 
@@ -1046,7 +1046,8 @@ export class DLOB {
1046
1046
  marketIndex: number,
1047
1047
  marketType: MarketType,
1048
1048
  slot: number,
1049
- oraclePriceData: OraclePriceData
1049
+ oraclePriceData: OraclePriceData,
1050
+ filterFcn?: DLOBFilterFcn
1050
1051
  ): Generator<DLOBNode> {
1051
1052
  const marketTypeStr = getVariant(marketType) as MarketTypeStr;
1052
1053
  const orderLists = this.orderLists.get(marketTypeStr).get(marketIndex);
@@ -1067,7 +1068,8 @@ export class DLOB {
1067
1068
  slot,
1068
1069
  (bestNode, currentNode) => {
1069
1070
  return bestNode.order.slot.lt(currentNode.order.slot);
1070
- }
1071
+ },
1072
+ filterFcn
1071
1073
  );
1072
1074
  }
1073
1075
 
@@ -1075,7 +1077,8 @@ export class DLOB {
1075
1077
  marketIndex: number,
1076
1078
  marketType: MarketType,
1077
1079
  slot: number,
1078
- oraclePriceData: OraclePriceData
1080
+ oraclePriceData: OraclePriceData,
1081
+ filterFcn?: DLOBFilterFcn
1079
1082
  ): Generator<DLOBNode> {
1080
1083
  const marketTypeStr = getVariant(marketType) as MarketTypeStr;
1081
1084
  const orderLists = this.orderLists.get(marketTypeStr).get(marketIndex);
@@ -1096,7 +1099,8 @@ export class DLOB {
1096
1099
  slot,
1097
1100
  (bestNode, currentNode) => {
1098
1101
  return bestNode.order.slot.lt(currentNode.order.slot);
1099
- }
1102
+ },
1103
+ filterFcn
1100
1104
  );
1101
1105
  }
1102
1106
 
@@ -1241,7 +1245,8 @@ export class DLOB {
1241
1245
  fallbackAsk: BN | undefined,
1242
1246
  slot: number,
1243
1247
  marketType: MarketType,
1244
- oraclePriceData: OraclePriceData
1248
+ oraclePriceData: OraclePriceData,
1249
+ filterFcn?: DLOBFilterFcn
1245
1250
  ): Generator<DLOBNode> {
1246
1251
  if (isVariant(marketType, 'spot') && !oraclePriceData) {
1247
1252
  throw new Error('Must provide OraclePriceData to get spot asks');
@@ -1284,7 +1289,8 @@ export class DLOB {
1284
1289
  return bestNode
1285
1290
  .getPrice(oraclePriceData, slot)
1286
1291
  .lt(currentNode.getPrice(oraclePriceData, slot));
1287
- }
1292
+ },
1293
+ filterFcn
1288
1294
  );
1289
1295
  }
1290
1296
 
@@ -1293,7 +1299,8 @@ export class DLOB {
1293
1299
  fallbackBid: BN | undefined,
1294
1300
  slot: number,
1295
1301
  marketType: MarketType,
1296
- oraclePriceData: OraclePriceData
1302
+ oraclePriceData: OraclePriceData,
1303
+ filterFcn?: DLOBFilterFcn
1297
1304
  ): Generator<DLOBNode> {
1298
1305
  if (isVariant(marketType, 'spot') && !oraclePriceData) {
1299
1306
  throw new Error('Must provide OraclePriceData to get spot bids');
@@ -1336,7 +1343,8 @@ export class DLOB {
1336
1343
  return bestNode
1337
1344
  .getPrice(oraclePriceData, slot)
1338
1345
  .gt(currentNode.getPrice(oraclePriceData, slot));
1339
- }
1346
+ },
1347
+ filterFcn
1340
1348
  );
1341
1349
  }
1342
1350
 
@@ -5385,7 +5385,8 @@ export class DriftClient {
5385
5385
  marketIndexes: number[],
5386
5386
  opts?: {
5387
5387
  filterInvalidMarkets?: boolean;
5388
- }
5388
+ },
5389
+ txParams?: TxParams
5389
5390
  ): Promise<TransactionSignature> {
5390
5391
  const filterInvalidMarkets = opts?.filterInvalidMarkets;
5391
5392
 
@@ -5418,9 +5419,12 @@ export class DriftClient {
5418
5419
  // # Settle filtered market indexes
5419
5420
  const ixs = await this.getSettlePNLsIxs(users, marketIndexToSettle);
5420
5421
 
5421
- const tx = await this.buildTransaction(ixs, {
5422
- computeUnits: 1_400_000,
5423
- });
5422
+ const tx = await this.buildTransaction(
5423
+ ixs,
5424
+ txParams ?? {
5425
+ computeUnits: 1_400_000,
5426
+ }
5427
+ );
5424
5428
 
5425
5429
  const { txSig } = await this.sendTransaction(tx, [], this.opts);
5426
5430
  return txSig;
@@ -6774,7 +6778,7 @@ export class DriftClient {
6774
6778
  txVersion?: TransactionVersion,
6775
6779
  lookupTables?: AddressLookupTableAccount[],
6776
6780
  forceVersionedTransaction?: boolean,
6777
- recentBlockHash?: BlockhashWithExpiryBlockHeight
6781
+ recentBlockhash?: BlockhashWithExpiryBlockHeight
6778
6782
  ): Promise<Transaction | VersionedTransaction> {
6779
6783
  return this.txHandler.buildTransaction({
6780
6784
  instructions,
@@ -6786,7 +6790,7 @@ export class DriftClient {
6786
6790
  this.fetchMarketLookupTableAccount.bind(this),
6787
6791
  lookupTables,
6788
6792
  forceVersionedTransaction,
6789
- recentBlockHash,
6793
+ recentBlockhash,
6790
6794
  });
6791
6795
  }
6792
6796
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.82.0",
2
+ "version": "2.83.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -88,7 +88,7 @@ export function getAuctionPriceForOracleOffsetAuction(
88
88
  const deltaNumerator = BN.min(slotsElapsed, deltaDenominator);
89
89
 
90
90
  if (deltaDenominator.eq(ZERO)) {
91
- return oraclePrice.add(order.auctionEndPrice);
91
+ return BN.max(oraclePrice.add(order.auctionEndPrice), ONE);
92
92
  }
93
93
 
94
94
  let priceOffsetDelta;
@@ -111,7 +111,7 @@ export function getAuctionPriceForOracleOffsetAuction(
111
111
  priceOffset = order.auctionStartPrice.sub(priceOffsetDelta);
112
112
  }
113
113
 
114
- return oraclePrice.add(priceOffset);
114
+ return BN.max(oraclePrice.add(priceOffset), ONE);
115
115
  }
116
116
 
117
117
  export function deriveOracleAuctionParams({
@@ -7,7 +7,7 @@ import {
7
7
  Order,
8
8
  PositionDirection,
9
9
  } from '../types';
10
- import { ZERO, TWO } from '../constants/numericConstants';
10
+ import { ZERO, TWO, ONE } from '../constants/numericConstants';
11
11
  import { BN } from '@coral-xyz/anchor';
12
12
  import { OraclePriceData } from '../oracles/types';
13
13
  import {
@@ -160,7 +160,10 @@ export function getLimitPrice(
160
160
  if (hasAuctionPrice(order, slot)) {
161
161
  limitPrice = getAuctionPrice(order, slot, oraclePriceData.price);
162
162
  } else if (order.oraclePriceOffset !== 0) {
163
- limitPrice = oraclePriceData.price.add(new BN(order.oraclePriceOffset));
163
+ limitPrice = BN.max(
164
+ oraclePriceData.price.add(new BN(order.oraclePriceOffset)),
165
+ ONE
166
+ );
164
167
  } else if (order.price.eq(ZERO)) {
165
168
  limitPrice = fallbackPrice;
166
169
  } else {