@drift-labs/sdk 2.31.1-beta.2 → 2.31.1-beta.21

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 (51) hide show
  1. package/VERSION +1 -1
  2. package/lib/accounts/mockUserAccountSubscriber.d.ts +23 -0
  3. package/lib/accounts/mockUserAccountSubscriber.js +31 -0
  4. package/lib/constants/perpMarkets.js +20 -0
  5. package/lib/dlob/orderBookLevels.js +2 -2
  6. package/lib/driftClient.d.ts +57 -4
  7. package/lib/driftClient.js +244 -205
  8. package/lib/driftClientConfig.d.ts +2 -1
  9. package/lib/idl/drift.json +31 -1
  10. package/lib/index.d.ts +2 -0
  11. package/lib/index.js +2 -0
  12. package/lib/marinade/index.d.ts +11 -0
  13. package/lib/marinade/index.js +36 -0
  14. package/lib/marinade/types.d.ts +1963 -0
  15. package/lib/marinade/types.js +1965 -0
  16. package/lib/math/spotBalance.d.ts +9 -2
  17. package/lib/math/spotBalance.js +54 -6
  18. package/lib/math/superStake.d.ts +22 -0
  19. package/lib/math/superStake.js +108 -0
  20. package/lib/math/tiers.d.ts +4 -0
  21. package/lib/math/tiers.js +52 -0
  22. package/lib/tx/retryTxSender.d.ts +12 -3
  23. package/lib/tx/retryTxSender.js +22 -22
  24. package/lib/tx/types.d.ts +2 -2
  25. package/lib/user.d.ts +10 -1
  26. package/lib/user.js +39 -8
  27. package/lib/userConfig.d.ts +4 -0
  28. package/lib/userStats.js +4 -1
  29. package/lib/userStatsConfig.d.ts +2 -0
  30. package/package.json +1 -1
  31. package/src/accounts/mockUserAccountSubscriber.ts +53 -0
  32. package/src/config.ts +2 -2
  33. package/src/constants/perpMarkets.ts +20 -0
  34. package/src/dlob/orderBookLevels.ts +3 -2
  35. package/src/driftClient.ts +440 -224
  36. package/src/driftClientConfig.ts +2 -1
  37. package/src/idl/drift.json +31 -1
  38. package/src/index.ts +2 -0
  39. package/src/marinade/idl/idl.json +1962 -0
  40. package/src/marinade/index.ts +64 -0
  41. package/src/marinade/types.ts +3925 -0
  42. package/src/math/spotBalance.ts +83 -5
  43. package/src/math/superStake.ts +148 -0
  44. package/src/math/tiers.ts +44 -0
  45. package/src/tx/retryTxSender.ts +39 -35
  46. package/src/tx/types.ts +2 -2
  47. package/src/user.ts +63 -12
  48. package/src/userConfig.ts +5 -0
  49. package/src/userStats.ts +4 -0
  50. package/src/userStatsConfig.ts +3 -0
  51. package/tests/spot/test.ts +156 -0
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.31.1-beta.2
1
+ 2.31.1-beta.21
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ import { DataAndSlot, UserAccountEvents, UserAccountSubscriber } from './types';
3
+ import { PublicKey } from '@solana/web3.js';
4
+ import StrictEventEmitter from 'strict-event-emitter-types';
5
+ import { EventEmitter } from 'events';
6
+ import { UserAccount } from '../types';
7
+ export declare class MockUserAccountSubscriber implements UserAccountSubscriber {
8
+ isSubscribed: boolean;
9
+ eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
10
+ userAccountPublicKey: PublicKey;
11
+ callbackId?: string;
12
+ errorCallbackId?: string;
13
+ user: DataAndSlot<UserAccount>;
14
+ constructor(userAccountPublicKey: PublicKey, data: UserAccount, slot: number);
15
+ subscribe(_userAccount?: UserAccount): Promise<boolean>;
16
+ addToAccountLoader(): Promise<void>;
17
+ fetch(): Promise<void>;
18
+ doesAccountExist(): boolean;
19
+ unsubscribe(): Promise<void>;
20
+ assertIsSubscribed(): void;
21
+ getUserAccountAndSlot(): DataAndSlot<UserAccount>;
22
+ updateData(userAccount: UserAccount, slot: number): void;
23
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MockUserAccountSubscriber = void 0;
4
+ const events_1 = require("events");
5
+ class MockUserAccountSubscriber {
6
+ constructor(userAccountPublicKey, data, slot) {
7
+ this.isSubscribed = true;
8
+ this.eventEmitter = new events_1.EventEmitter();
9
+ this.userAccountPublicKey = userAccountPublicKey;
10
+ this.user = { data, slot };
11
+ }
12
+ async subscribe(_userAccount) {
13
+ return true;
14
+ }
15
+ async addToAccountLoader() { }
16
+ async fetch() { }
17
+ doesAccountExist() {
18
+ return this.user !== undefined;
19
+ }
20
+ async unsubscribe() { }
21
+ assertIsSubscribed() { }
22
+ getUserAccountAndSlot() {
23
+ return this.user;
24
+ }
25
+ updateData(userAccount, slot) {
26
+ this.user = { data: userAccount, slot };
27
+ this.eventEmitter.emit('userAccountUpdate', userAccount);
28
+ this.eventEmitter.emit('update');
29
+ }
30
+ }
31
+ exports.MockUserAccountSubscriber = MockUserAccountSubscriber;
@@ -124,6 +124,16 @@ exports.DevnetPerpMarkets = [
124
124
  launchTs: 1683125906000,
125
125
  oracleSource: __1.OracleSource.PYTH,
126
126
  },
127
+ {
128
+ fullName: 'RNDR',
129
+ category: ['Infra'],
130
+ symbol: 'RNDR-PERP',
131
+ baseAssetSymbol: 'RNDR',
132
+ marketIndex: 12,
133
+ oracle: new web3_js_1.PublicKey('C2QvUPBiU3fViSyqA4nZgGyYqLgYf9PRpd8B8oLoo48w'),
134
+ launchTs: 1683125906000,
135
+ oracleSource: __1.OracleSource.PYTH,
136
+ },
127
137
  ];
128
138
  exports.MainnetPerpMarkets = [
129
139
  {
@@ -246,6 +256,16 @@ exports.MainnetPerpMarkets = [
246
256
  launchTs: 1683125906000,
247
257
  oracleSource: __1.OracleSource.PYTH,
248
258
  },
259
+ {
260
+ fullName: 'RNDR',
261
+ category: ['Infra'],
262
+ symbol: 'RNDR-PERP',
263
+ baseAssetSymbol: 'RNDR',
264
+ marketIndex: 12,
265
+ oracle: new web3_js_1.PublicKey('CYGfrBJB9HgLf9iZyN4aH5HvUAi2htQ4MjPxeXMf4Egn'),
266
+ launchTs: 1683125906000,
267
+ oracleSource: __1.OracleSource.PYTH,
268
+ },
249
269
  ];
250
270
  exports.PerpMarkets = {
251
271
  devnet: exports.DevnetPerpMarkets,
@@ -92,7 +92,7 @@ function getVammL2Generator({ marketAccount, oraclePriceData, numOrders, now, })
92
92
  pegMultiplier: updatedAmm.pegMultiplier,
93
93
  };
94
94
  const getL2Bids = function* () {
95
- while (numBids < numOrders) {
95
+ while (numBids < numOrders && baseSize.gt(__1.ZERO)) {
96
96
  const [afterSwapQuoteReserves, afterSwapBaseReserves] = (0, __1.calculateAmmReservesAfterSwap)(bidAmm, 'base', baseSize, __1.SwapDirection.ADD);
97
97
  const quoteSwapped = (0, __1.calculateQuoteAssetAmountSwapped)(bidAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(), bidAmm.pegMultiplier, __1.SwapDirection.ADD);
98
98
  const price = quoteSwapped.mul(__1.BASE_PRECISION).div(baseSize);
@@ -115,7 +115,7 @@ function getVammL2Generator({ marketAccount, oraclePriceData, numOrders, now, })
115
115
  pegMultiplier: updatedAmm.pegMultiplier,
116
116
  };
117
117
  const getL2Asks = function* () {
118
- while (numAsks < numOrders) {
118
+ while (numAsks < numOrders && askSize.gt(__1.ZERO)) {
119
119
  const [afterSwapQuoteReserves, afterSwapBaseReserves] = (0, __1.calculateAmmReservesAfterSwap)(askAmm, 'base', askSize, __1.SwapDirection.REMOVE);
120
120
  const quoteSwapped = (0, __1.calculateQuoteAssetAmountSwapped)(askAmm.quoteAssetReserve.sub(afterSwapQuoteReserves).abs(), askAmm.pegMultiplier, __1.SwapDirection.REMOVE);
121
121
  const price = quoteSwapped.mul(__1.BASE_PRECISION).div(askSize);
@@ -14,11 +14,12 @@ import { User } from './user';
14
14
  import { UserSubscriptionConfig } from './userConfig';
15
15
  import { UserStats } from './userStats';
16
16
  import { JupiterClient, Route, SwapMode } from './jupiter/jupiterClient';
17
+ import { UserStatsSubscriptionConfig } from './userStatsConfig';
17
18
  type RemainingAccountParams = {
18
19
  userAccounts: UserAccount[];
19
20
  writablePerpMarketIndexes?: number[];
20
21
  writableSpotMarketIndexes?: number[];
21
- readablePerpMarketIndex?: number;
22
+ readablePerpMarketIndex?: number | number[];
22
23
  readableSpotMarketIndexes?: number[];
23
24
  useMarketLastSlotCache?: boolean;
24
25
  };
@@ -36,12 +37,15 @@ export declare class DriftClient {
36
37
  userStats?: UserStats;
37
38
  activeSubAccountId: number;
38
39
  userAccountSubscriptionConfig: UserSubscriptionConfig;
40
+ userStatsAccountSubscriptionConfig: UserStatsSubscriptionConfig;
39
41
  accountSubscriber: DriftClientAccountSubscriber;
40
42
  eventEmitter: StrictEventEmitter<EventEmitter, DriftClientAccountEvents>;
41
43
  _isSubscribed: boolean;
42
44
  txSender: TxSender;
43
45
  perpMarketLastSlotCache: Map<number, number>;
44
46
  spotMarketLastSlotCache: Map<number, number>;
47
+ mustIncludePerpMarketIndexes: Set<number>;
48
+ mustIncludeSpotMarketIndexes: Set<number>;
45
49
  authority: PublicKey;
46
50
  marketLookupTable: PublicKey;
47
51
  lookupTableAccount: AddressLookupTableAccount;
@@ -49,6 +53,7 @@ export declare class DriftClient {
49
53
  authoritySubAccountMap?: Map<string, number[]>;
50
54
  skipLoadUsers?: boolean;
51
55
  txVersion: TransactionVersion;
56
+ txParams: TxParams;
52
57
  get isSubscribed(): boolean;
53
58
  set isSubscribed(val: boolean);
54
59
  constructor(config: DriftClientConfig);
@@ -111,6 +116,7 @@ export declare class DriftClient {
111
116
  initializeReferrerName(name: string): Promise<TransactionSignature>;
112
117
  updateUserName(name: string, subAccountId?: number): Promise<TransactionSignature>;
113
118
  updateUserCustomMarginRatio(marginRatio: number, subAccountId?: number): Promise<TransactionSignature>;
119
+ getUpdateUserMarginTradingEnabledIx(marginTradingEnabled: boolean, subAccountId?: number, userAccountPublicKey?: PublicKey): Promise<TransactionInstruction>;
114
120
  updateUserMarginTradingEnabled(marginTradingEnabled: boolean, subAccountId?: number): Promise<TransactionSignature>;
115
121
  updateUserDelegate(delegate: PublicKey, subAccountId?: number): Promise<TransactionSignature>;
116
122
  fetchAllUserAccounts(includeIdle?: boolean): Promise<ProgramAccount<UserAccount>[]>;
@@ -121,6 +127,7 @@ export declare class DriftClient {
121
127
  getReferrerNameAccountsForAuthority(authority: PublicKey): Promise<ReferrerNameAccount[]>;
122
128
  deleteUser(subAccountId?: number, txParams?: TxParams): Promise<TransactionSignature>;
123
129
  getUser(subAccountId?: number, authority?: PublicKey): User;
130
+ hasUser(subAccountId?: number, authority?: PublicKey): boolean;
124
131
  getUsers(): User[];
125
132
  getUserStats(): UserStats;
126
133
  fetchReferrerNameAccount(name: string): Promise<ReferrerNameAccount | undefined>;
@@ -158,7 +165,20 @@ export declare class DriftClient {
158
165
  * @param amount
159
166
  */
160
167
  convertToPricePrecision(amount: BN | number): BN;
168
+ /**
169
+ * Each drift instruction must include perp and sport market accounts in the ix remaining accounts.
170
+ * Use this function to force a subset of markets to be included in the remaining accounts for every ix
171
+ *
172
+ * @param perpMarketIndexes
173
+ * @param spotMarketIndexes
174
+ */
175
+ mustIncludeMarketsInIx({ perpMarketIndexes, spotMarketIndexes, }: {
176
+ perpMarketIndexes: number[];
177
+ spotMarketIndexes: number[];
178
+ }): void;
161
179
  getRemainingAccounts(params: RemainingAccountParams): AccountMeta[];
180
+ addPerpMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>, perpMarketAccountMap: Map<number, AccountMeta>): void;
181
+ addSpotMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>): void;
162
182
  getRemainingAccountMapsForUsers(userAccounts: UserAccount[]): {
163
183
  oracleAccountMap: Map<string, AccountMeta>;
164
184
  spotMarketAccountMap: Map<number, AccountMeta>;
@@ -185,10 +205,14 @@ export declare class DriftClient {
185
205
  deposit(amount: BN, marketIndex: number, associatedTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean): Promise<TransactionSignature>;
186
206
  getDepositInstruction(amount: BN, marketIndex: number, userTokenAccount: PublicKey, subAccountId?: number, reduceOnly?: boolean, userInitialized?: boolean): Promise<TransactionInstruction>;
187
207
  private checkIfAccountExists;
188
- private getWrappedSolAccountCreationIxs;
208
+ getWrappedSolAccountCreationIxs(amount: BN, includeRent?: boolean): Promise<{
209
+ ixs: anchor.web3.TransactionInstruction[];
210
+ signers: Signer[];
211
+ pubkey: PublicKey;
212
+ }>;
189
213
  getAssociatedTokenAccountCreationIx(tokenMintAddress: PublicKey, associatedTokenAddress: PublicKey): anchor.web3.TransactionInstruction;
190
214
  /**
191
- * Creates the Clearing House User account for a user, and deposits some initial collateral
215
+ * Creates the User account for a user, and deposits some initial collateral
192
216
  * @param amount
193
217
  * @param userTokenAccount
194
218
  * @param marketIndex
@@ -228,6 +252,7 @@ export declare class DriftClient {
228
252
  getRemovePerpLpSharesIx(marketIndex: number, sharesToBurn?: BN): Promise<TransactionInstruction>;
229
253
  addPerpLpShares(amount: BN, marketIndex: number, txParams?: TxParams): Promise<TransactionSignature>;
230
254
  getAddPerpLpSharesIx(amount: BN, marketIndex: number): Promise<TransactionInstruction>;
255
+ getQuoteValuePerLpShare(marketIndex: number): BN;
231
256
  /**
232
257
  * @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
233
258
  */
@@ -266,6 +291,8 @@ export declare class DriftClient {
266
291
  marketIndex?: number;
267
292
  direction?: PositionDirection;
268
293
  }, placeOrderParams: OrderParams[], txParams?: TxParams): Promise<TransactionSignature>;
294
+ placeOrders(params: OrderParams[], txParams?: TxParams): Promise<TransactionSignature>;
295
+ getPlaceOrdersIx(params: OrderParams[]): Promise<TransactionInstruction>;
269
296
  fillPerpOrder(userAccountPublicKey: PublicKey, user: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, txParams?: TxParams): Promise<TransactionSignature>;
270
297
  getFillPerpOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo): Promise<TransactionInstruction>;
271
298
  getRevertFillIx(): Promise<TransactionInstruction>;
@@ -301,6 +328,22 @@ export declare class DriftClient {
301
328
  reduceOnly?: SwapReduceOnly;
302
329
  txParams?: TxParams;
303
330
  }): Promise<TransactionSignature>;
331
+ getJupiterSwapIx({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, route, reduceOnly, userAccountPublicKey, }: {
332
+ jupiterClient: JupiterClient;
333
+ outMarketIndex: number;
334
+ inMarketIndex: number;
335
+ outAssociatedTokenAccount?: PublicKey;
336
+ inAssociatedTokenAccount?: PublicKey;
337
+ amount: BN;
338
+ slippageBps?: number;
339
+ swapMode?: SwapMode;
340
+ route?: Route;
341
+ reduceOnly?: SwapReduceOnly;
342
+ userAccountPublicKey?: PublicKey;
343
+ }): Promise<{
344
+ ixs: TransactionInstruction[];
345
+ lookupTables: AddressLookupTableAccount[];
346
+ }>;
304
347
  /**
305
348
  * Get the drift begin_swap and end_swap instructions
306
349
  *
@@ -310,8 +353,10 @@ export declare class DriftClient {
310
353
  * @param inTokenAccount the token account to move the tokens being sold
311
354
  * @param outTokenAccount the token account to receive the tokens being bought
312
355
  * @param limitPrice the limit price of the swap
356
+ * @param reduceOnly
357
+ * @param userAccountPublicKey optional, specify a custom userAccountPublicKey to use instead of getting the current user account; can be helpful if the account is being created within the current tx
313
358
  */
314
- getSwapIx({ outMarketIndex, inMarketIndex, amountIn, inTokenAccount, outTokenAccount, limitPrice, reduceOnly, }: {
359
+ getSwapIx({ outMarketIndex, inMarketIndex, amountIn, inTokenAccount, outTokenAccount, limitPrice, reduceOnly, userAccountPublicKey, }: {
315
360
  outMarketIndex: number;
316
361
  inMarketIndex: number;
317
362
  amountIn: BN;
@@ -319,10 +364,18 @@ export declare class DriftClient {
319
364
  outTokenAccount: PublicKey;
320
365
  limitPrice?: BN;
321
366
  reduceOnly?: SwapReduceOnly;
367
+ userAccountPublicKey?: PublicKey;
322
368
  }): Promise<{
323
369
  beginSwapIx: TransactionInstruction;
324
370
  endSwapIx: TransactionInstruction;
325
371
  }>;
372
+ stakeForMSOL({ amount }: {
373
+ amount: BN;
374
+ }): Promise<TxSigAndSlot>;
375
+ getStakeForMSOLIx({ amount, userAccountPublicKey, }: {
376
+ amount: BN;
377
+ userAccountPublicKey?: PublicKey;
378
+ }): Promise<TransactionInstruction[]>;
326
379
  triggerOrder(userAccountPublicKey: PublicKey, user: UserAccount, order: Order, txParams?: TxParams): Promise<TransactionSignature>;
327
380
  getTriggerOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Order): Promise<TransactionInstruction>;
328
381
  forceCancelOrders(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams): Promise<TransactionSignature>;