@drift-labs/sdk 2.83.0-beta.1 → 2.83.0-beta.10

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 (52) hide show
  1. package/VERSION +1 -1
  2. package/lib/adminClient.d.ts +2 -2
  3. package/lib/adminClient.js +7 -9
  4. package/lib/clock/clockSubscriber.d.ts +4 -2
  5. package/lib/clock/clockSubscriber.js +8 -2
  6. package/lib/decode/phoenix.d.ts +6 -0
  7. package/lib/decode/phoenix.js +159 -0
  8. package/lib/driftClient.d.ts +5 -2
  9. package/lib/driftClient.js +92 -47
  10. package/lib/idl/drift.json +63 -0
  11. package/lib/index.d.ts +1 -0
  12. package/lib/index.js +1 -0
  13. package/lib/math/market.js +4 -1
  14. package/lib/phoenix/phoenixSubscriber.d.ts +2 -0
  15. package/lib/phoenix/phoenixSubscriber.js +15 -2
  16. package/lib/priorityFee/priorityFeeSubscriber.js +1 -1
  17. package/lib/tx/baseTxSender.d.ts +5 -2
  18. package/lib/tx/baseTxSender.js +30 -1
  19. package/lib/tx/fastSingleTxSender.d.ts +1 -1
  20. package/lib/tx/fastSingleTxSender.js +1 -0
  21. package/lib/tx/forwardOnlyTxSender.d.ts +1 -1
  22. package/lib/tx/retryTxSender.d.ts +1 -1
  23. package/lib/tx/retryTxSender.js +1 -0
  24. package/lib/tx/txHandler.d.ts +2 -0
  25. package/lib/tx/txHandler.js +16 -9
  26. package/lib/tx/types.d.ts +2 -1
  27. package/lib/tx/whileValidTxSender.d.ts +1 -1
  28. package/lib/tx/whileValidTxSender.js +1 -0
  29. package/lib/types.d.ts +9 -0
  30. package/lib/types.js +6 -1
  31. package/lib/util/computeUnits.d.ts +7 -1
  32. package/lib/util/computeUnits.js +31 -1
  33. package/package.json +1 -1
  34. package/src/adminClient.ts +12 -10
  35. package/src/clock/clockSubscriber.ts +12 -4
  36. package/src/decode/phoenix.ts +207 -0
  37. package/src/driftClient.ts +188 -104
  38. package/src/idl/drift.json +63 -0
  39. package/src/index.ts +1 -0
  40. package/src/math/market.ts +4 -1
  41. package/src/phoenix/phoenixSubscriber.ts +15 -3
  42. package/src/priorityFee/priorityFeeSubscriber.ts +1 -1
  43. package/src/tx/baseTxSender.ts +59 -2
  44. package/src/tx/fastSingleTxSender.ts +2 -1
  45. package/src/tx/forwardOnlyTxSender.ts +1 -1
  46. package/src/tx/retryTxSender.ts +4 -1
  47. package/src/tx/txHandler.ts +19 -7
  48. package/src/tx/types.ts +11 -0
  49. package/src/tx/whileValidTxSender.ts +4 -1
  50. package/src/types.ts +6 -0
  51. package/src/util/computeUnits.ts +43 -1
  52. package/tests/decode/phoenix.ts +71 -0
@@ -5,8 +5,10 @@ const web3_js_1 = require("@solana/web3.js");
5
5
  const phoenix_sdk_1 = require("@ellipsis-labs/phoenix-sdk");
6
6
  const numericConstants_1 = require("../constants/numericConstants");
7
7
  const anchor_1 = require("@coral-xyz/anchor");
8
+ const phoenix_1 = require("../decode/phoenix");
8
9
  class PhoenixSubscriber {
9
10
  constructor(config) {
11
+ var _a;
10
12
  this.connection = config.connection;
11
13
  this.programId = config.programId;
12
14
  this.marketAddress = config.marketAddress;
@@ -19,6 +21,7 @@ class PhoenixSubscriber {
19
21
  }
20
22
  this.lastSlot = 0;
21
23
  this.lastUnixTimestamp = 0;
24
+ this.fastDecode = (_a = config.fastDecode) !== null && _a !== void 0 ? _a : true;
22
25
  }
23
26
  async subscribe() {
24
27
  if (this.subscribed) {
@@ -34,7 +37,12 @@ class PhoenixSubscriber {
34
37
  if (this.subscriptionType === 'websocket') {
35
38
  this.marketCallbackId = this.connection.onAccountChange(this.marketAddress, (accountInfo, _ctx) => {
36
39
  try {
37
- this.market = this.market.reload(accountInfo.data);
40
+ if (this.fastDecode) {
41
+ this.market.data = (0, phoenix_1.fastDecode)(accountInfo.data);
42
+ }
43
+ else {
44
+ this.market = this.market.reload(accountInfo.data);
45
+ }
38
46
  }
39
47
  catch {
40
48
  console.error('Failed to reload Phoenix market data');
@@ -56,7 +64,12 @@ class PhoenixSubscriber {
56
64
  try {
57
65
  this.lastSlot = slot;
58
66
  if (buffer) {
59
- this.market = this.market.reload(buffer);
67
+ if (this.fastDecode) {
68
+ this.market.data = (0, phoenix_1.fastDecode)(buffer);
69
+ }
70
+ else {
71
+ this.market = this.market.reload(buffer);
72
+ }
60
73
  }
61
74
  }
62
75
  catch {
@@ -63,8 +63,8 @@ class PriorityFeeSubscriber {
63
63
  if (this.intervalId) {
64
64
  return;
65
65
  }
66
+ this.intervalId = setInterval(this.load.bind(this), this.frequencyMs); // we set the intervalId first, preventing a side effect of unsubscribing failing during the race condition where unsubscribes happens before subscribe is finished
66
67
  await this.load();
67
- this.intervalId = setInterval(this.load.bind(this), this.frequencyMs);
68
68
  }
69
69
  async loadForSolana() {
70
70
  const samples = await (0, solanaPriorityFeeMethod_1.fetchSolanaPriorityFee)(this.connection, this.lookbackDistance, this.addresses);
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import { ConfirmationStrategy, TxSender, TxSigAndSlot } from './types';
3
- import { Commitment, ConfirmOptions, RpcResponseAndContext, Signer, SignatureResult, Transaction, TransactionSignature, Connection, VersionedTransaction } from '@solana/web3.js';
3
+ import { Commitment, ConfirmOptions, RpcResponseAndContext, Signer, SignatureResult, Transaction, TransactionSignature, Connection, VersionedTransaction, TransactionInstruction, AddressLookupTableAccount, BlockhashWithExpiryBlockHeight } from '@solana/web3.js';
4
4
  import { TxHandler } from './txHandler';
5
5
  import { IWallet } from '../types';
6
6
  export declare abstract class BaseTxSender implements TxSender {
@@ -21,10 +21,11 @@ export declare abstract class BaseTxSender implements TxSender {
21
21
  additionalConnections?: any;
22
22
  confirmationStrategy?: ConfirmationStrategy;
23
23
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
24
- txHandler: TxHandler;
24
+ txHandler?: TxHandler;
25
25
  });
26
26
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
27
27
  prepareTx(tx: Transaction, additionalSigners: Array<Signer>, opts: ConfirmOptions, preSigned?: boolean): Promise<Transaction>;
28
+ getVersionedTransaction(ixs: TransactionInstruction[], lookupTableAccounts: AddressLookupTableAccount[], _additionalSigners?: Array<Signer>, opts?: ConfirmOptions, blockhash?: BlockhashWithExpiryBlockHeight): Promise<VersionedTransaction>;
28
29
  sendVersionedTransaction(tx: VersionedTransaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
29
30
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
30
31
  simulateTransaction(tx: VersionedTransaction): Promise<boolean>;
@@ -36,4 +37,6 @@ export declare abstract class BaseTxSender implements TxSender {
36
37
  sendToAdditionalConnections(rawTx: Buffer | Uint8Array, opts: ConfirmOptions): void;
37
38
  addAdditionalConnection(newConnection: Connection): void;
38
39
  getTimeoutCount(): number;
40
+ checkConfirmationResultForError(txSig: string, result: RpcResponseAndContext<SignatureResult>): Promise<void>;
41
+ reportTransactionError(txSig: string): Promise<any>;
39
42
  }
@@ -5,9 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BaseTxSender = void 0;
7
7
  const types_1 = require("./types");
8
+ const web3_js_1 = require("@solana/web3.js");
8
9
  const anchor_1 = require("@coral-xyz/anchor");
9
10
  const assert_1 = __importDefault(require("assert"));
10
11
  const bs58_1 = __importDefault(require("bs58"));
12
+ const txHandler_1 = require("./txHandler");
11
13
  const DEFAULT_TIMEOUT = 35000;
12
14
  const NOT_CONFIRMED_ERROR_CODE = -1001;
13
15
  class BaseTxSender {
@@ -20,7 +22,12 @@ class BaseTxSender {
20
22
  this.additionalConnections = additionalConnections;
21
23
  this.confirmationStrategy = confirmationStrategy;
22
24
  this.additionalTxSenderCallbacks = additionalTxSenderCallbacks;
23
- this.txHandler = txHandler;
25
+ this.txHandler =
26
+ txHandler !== null && txHandler !== void 0 ? txHandler : new txHandler_1.TxHandler({
27
+ connection: this.connection,
28
+ wallet: this.wallet,
29
+ confirmationOptions: this.opts,
30
+ });
24
31
  }
25
32
  async send(tx, additionalSigners, opts, preSigned) {
26
33
  if (additionalSigners === undefined) {
@@ -35,6 +42,9 @@ class BaseTxSender {
35
42
  async prepareTx(tx, additionalSigners, opts, preSigned) {
36
43
  return this.txHandler.prepareTx(tx, additionalSigners, undefined, opts, preSigned);
37
44
  }
45
+ async getVersionedTransaction(ixs, lookupTableAccounts, _additionalSigners, opts, blockhash) {
46
+ return this.txHandler.generateVersionedTransaction(blockhash, ixs, lookupTableAccounts, this.wallet);
47
+ }
38
48
  async sendVersionedTransaction(tx, additionalSigners, opts, preSigned) {
39
49
  let signedTx;
40
50
  if (preSigned) {
@@ -211,5 +221,24 @@ class BaseTxSender {
211
221
  getTimeoutCount() {
212
222
  return this.timeoutCount;
213
223
  }
224
+ async checkConfirmationResultForError(txSig, result) {
225
+ if (result.value.err) {
226
+ await this.reportTransactionError(txSig);
227
+ }
228
+ return;
229
+ }
230
+ async reportTransactionError(txSig) {
231
+ var _a, _b;
232
+ const transactionResult = await this.connection.getTransaction(txSig, {
233
+ maxSupportedTransactionVersion: 0,
234
+ });
235
+ if (!((_a = transactionResult === null || transactionResult === void 0 ? void 0 : transactionResult.meta) === null || _a === void 0 ? void 0 : _a.err)) {
236
+ return undefined;
237
+ }
238
+ const logs = transactionResult.meta.logMessages;
239
+ const lastLog = logs[logs.length - 1];
240
+ const friendlyMessage = (_b = lastLog === null || lastLog === void 0 ? void 0 : lastLog.match(/(failed:) (.+)/)) === null || _b === void 0 ? void 0 : _b[2];
241
+ throw new web3_js_1.SendTransactionError(`Transaction Failed${friendlyMessage ? `: ${friendlyMessage}` : ''}`, transactionResult.meta.logMessages);
242
+ }
214
243
  }
215
244
  exports.BaseTxSender = BaseTxSender;
@@ -27,7 +27,7 @@ export declare class FastSingleTxSender extends BaseTxSender {
27
27
  skipConfirmation?: boolean;
28
28
  blockhashCommitment?: Commitment;
29
29
  confirmationStrategy?: ConfirmationStrategy;
30
- txHandler: TxHandler;
30
+ txHandler?: TxHandler;
31
31
  });
32
32
  startBlockhashRefreshLoop(): void;
33
33
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
@@ -54,6 +54,7 @@ class FastSingleTxSender extends baseTxSender_1.BaseTxSender {
54
54
  if (!this.skipConfirmation) {
55
55
  try {
56
56
  const result = await this.confirmTransaction(txid, opts.commitment);
57
+ await this.checkConfirmationResultForError(txid, result);
57
58
  slot = result.context.slot;
58
59
  }
59
60
  catch (e) {
@@ -23,7 +23,7 @@ export declare class ForwardOnlyTxSender extends BaseTxSender {
23
23
  retrySleep?: number;
24
24
  confirmationStrategy?: ConfirmationStrategy;
25
25
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
26
- txHandler: TxHandler;
26
+ txHandler?: TxHandler;
27
27
  });
28
28
  sleep(reference: ResolveReference): Promise<void>;
29
29
  sendToAdditionalConnections(rawTx: Buffer | Uint8Array, _opts: ConfirmOptions): void;
@@ -24,7 +24,7 @@ export declare class RetryTxSender extends BaseTxSender {
24
24
  additionalConnections?: any;
25
25
  confirmationStrategy?: ConfirmationStrategy;
26
26
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
27
- txHandler: TxHandler;
27
+ txHandler?: TxHandler;
28
28
  });
29
29
  sleep(reference: ResolveReference): Promise<void>;
30
30
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
@@ -63,6 +63,7 @@ class RetryTxSender extends baseTxSender_1.BaseTxSender {
63
63
  let slot;
64
64
  try {
65
65
  const result = await this.confirmTransaction(txid, opts.commitment);
66
+ await this.checkConfirmationResultForError(txid, result);
66
67
  slot = result.context.slot;
67
68
  // eslint-disable-next-line no-useless-catch
68
69
  }
@@ -22,6 +22,7 @@ export declare class TxHandler {
22
22
  private connection;
23
23
  private wallet;
24
24
  private confirmationOptions;
25
+ private preSignedCb?;
25
26
  private onSignedCb?;
26
27
  constructor(props: {
27
28
  connection: Connection;
@@ -30,6 +31,7 @@ export declare class TxHandler {
30
31
  opts?: {
31
32
  returnBlockHeightsWithSignedTxCallbackData?: boolean;
32
33
  onSignedCb?: (txSigs: DriftClientMetricsEvents['txSigned']) => void;
34
+ preSignedCb?: () => void;
33
35
  };
34
36
  });
35
37
  private addHashAndExpiryToLookup;
@@ -7,13 +7,14 @@ exports.TxHandler = exports.COMPUTE_UNITS_DEFAULT = void 0;
7
7
  const web3_js_1 = require("@solana/web3.js");
8
8
  const txParamProcessor_1 = require("./txParamProcessor");
9
9
  const bs58_1 = __importDefault(require("bs58"));
10
+ const computeUnits_1 = require("../util/computeUnits");
10
11
  exports.COMPUTE_UNITS_DEFAULT = 200000;
11
12
  /**
12
13
  * This class is responsible for creating and signing transactions.
13
14
  */
14
15
  class TxHandler {
15
16
  constructor(props) {
16
- var _a, _b, _c;
17
+ var _a, _b, _c, _d;
17
18
  this.blockHashToLastValidBlockHeightLookup = {};
18
19
  this.returnBlockHeightsWithSignedTxCallbackData = false;
19
20
  this.getProps = (wallet, confirmationOpts) => [wallet !== null && wallet !== void 0 ? wallet : this.wallet, confirmationOpts !== null && confirmationOpts !== void 0 ? confirmationOpts : this.confirmationOptions];
@@ -24,6 +25,7 @@ class TxHandler {
24
25
  this.returnBlockHeightsWithSignedTxCallbackData =
25
26
  (_b = (_a = props.opts) === null || _a === void 0 ? void 0 : _a.returnBlockHeightsWithSignedTxCallbackData) !== null && _b !== void 0 ? _b : false;
26
27
  this.onSignedCb = (_c = props.opts) === null || _c === void 0 ? void 0 : _c.onSignedCb;
28
+ this.preSignedCb = (_d = props.opts) === null || _d === void 0 ? void 0 : _d.preSignedCb;
27
29
  }
28
30
  addHashAndExpiryToLookup(hashAndExpiry) {
29
31
  if (!this.returnBlockHeightsWithSignedTxCallbackData)
@@ -88,12 +90,14 @@ class TxHandler {
88
90
  }
89
91
  }
90
92
  async signTx(tx, additionalSigners, wallet) {
93
+ var _a;
91
94
  [wallet] = this.getProps(wallet);
92
95
  additionalSigners
93
96
  .filter((s) => s !== undefined)
94
97
  .forEach((kp) => {
95
98
  tx.partialSign(kp);
96
99
  });
100
+ (_a = this.preSignedCb) === null || _a === void 0 ? void 0 : _a.call(this);
97
101
  const signedTx = await wallet.signTransaction(tx);
98
102
  // Turn txSig Buffer into base58 string
99
103
  const txSig = this.getTxSigFromSignedTx(signedTx);
@@ -107,6 +111,7 @@ class TxHandler {
107
111
  return signedTx;
108
112
  }
109
113
  async signVersionedTx(tx, additionalSigners, recentBlockHash, wallet) {
114
+ var _a;
110
115
  [wallet] = this.getProps(wallet);
111
116
  if (recentBlockHash) {
112
117
  tx.message.recentBlockhash = recentBlockHash.blockhash;
@@ -115,6 +120,7 @@ class TxHandler {
115
120
  additionalSigners === null || additionalSigners === void 0 ? void 0 : additionalSigners.filter((s) => s !== undefined).forEach((kp) => {
116
121
  tx.sign([kp]);
117
122
  });
123
+ (_a = this.preSignedCb) === null || _a === void 0 ? void 0 : _a.call(this);
118
124
  //@ts-ignore
119
125
  const signedTx = (await wallet.signTransaction(tx));
120
126
  // Turn txSig Buffer into base58 string
@@ -248,26 +254,25 @@ class TxHandler {
248
254
  ...processedTxParams,
249
255
  };
250
256
  }
257
+ const instructionsArray = Array.isArray(instructions)
258
+ ? instructions
259
+ : [instructions];
260
+ const { hasSetComputeUnitLimitIx, hasSetComputeUnitPriceIx } = (0, computeUnits_1.containsComputeUnitIxs)(instructionsArray);
251
261
  // # Create Tx Instructions
252
262
  const allIx = [];
253
263
  const computeUnits = baseTxParams === null || baseTxParams === void 0 ? void 0 : baseTxParams.computeUnits;
254
- if (computeUnits !== 200000) {
264
+ if (computeUnits > 0 && !hasSetComputeUnitLimitIx) {
255
265
  allIx.push(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
256
266
  units: computeUnits,
257
267
  }));
258
268
  }
259
269
  const computeUnitsPrice = baseTxParams === null || baseTxParams === void 0 ? void 0 : baseTxParams.computeUnitsPrice;
260
- if (computeUnitsPrice !== 0) {
270
+ if (computeUnitsPrice > 0 && !hasSetComputeUnitPriceIx) {
261
271
  allIx.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({
262
272
  microLamports: computeUnitsPrice,
263
273
  }));
264
274
  }
265
- if (Array.isArray(instructions)) {
266
- allIx.push(...instructions);
267
- }
268
- else {
269
- allIx.push(instructions);
270
- }
275
+ allIx.push(...instructionsArray);
271
276
  const recentBlockHash = (_a = props === null || props === void 0 ? void 0 : props.recentBlockHash) !== null && _a !== void 0 ? _a : (await this.getLatestBlockhashForTransaction());
272
277
  // # Create and return Transaction
273
278
  if (txVersion === 'legacy') {
@@ -352,6 +357,7 @@ class TxHandler {
352
357
  * @returns
353
358
  */
354
359
  async getSignedTransactionMap(txsToSign, keys, wallet) {
360
+ var _a;
355
361
  [wallet] = this.getProps(wallet);
356
362
  const signedTxMap = {};
357
363
  const keysWithTx = [];
@@ -363,6 +369,7 @@ class TxHandler {
363
369
  keysWithTx.push(keys[index]);
364
370
  }
365
371
  });
372
+ (_a = this.preSignedCb) === null || _a === void 0 ? void 0 : _a.call(this);
366
373
  const signedTxs = await wallet.signAllTransactions(txsToSign
367
374
  .map((tx) => {
368
375
  return tx;
package/lib/tx/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { ConfirmOptions, Signer, Transaction, TransactionSignature, VersionedTransaction } from '@solana/web3.js';
2
+ import { AddressLookupTableAccount, BlockhashWithExpiryBlockHeight, ConfirmOptions, Signer, Transaction, TransactionInstruction, TransactionSignature, VersionedTransaction } from '@solana/web3.js';
3
3
  import { IWallet } from '../types';
4
4
  export declare enum ConfirmationStrategy {
5
5
  WebSocket = "websocket",
@@ -14,6 +14,7 @@ export interface TxSender {
14
14
  wallet: IWallet;
15
15
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
16
16
  sendVersionedTransaction(tx: VersionedTransaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean): Promise<TxSigAndSlot>;
17
+ getVersionedTransaction(ixs: TransactionInstruction[], lookupTableAccounts: AddressLookupTableAccount[], additionalSigners?: Array<Signer>, opts?: ConfirmOptions, blockhash?: BlockhashWithExpiryBlockHeight): Promise<VersionedTransaction>;
17
18
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
18
19
  simulateTransaction(tx: VersionedTransaction): Promise<boolean>;
19
20
  getTimeoutCount(): number;
@@ -28,7 +28,7 @@ export declare class WhileValidTxSender extends BaseTxSender {
28
28
  additionalConnections?: any;
29
29
  additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
30
30
  blockhashCommitment?: Commitment;
31
- txHandler: TxHandler;
31
+ txHandler?: TxHandler;
32
32
  });
33
33
  sleep(reference: ResolveReference): Promise<void>;
34
34
  prepareTx(tx: Transaction, additionalSigners: Array<Signer>, opts: ConfirmOptions, preSigned?: boolean): Promise<Transaction>;
@@ -105,6 +105,7 @@ class WhileValidTxSender extends baseTxSender_1.BaseTxSender {
105
105
  lastValidBlockHeight,
106
106
  blockhash,
107
107
  }, opts.commitment);
108
+ await this.checkConfirmationResultForError(txid, result);
108
109
  slot = result.context.slot;
109
110
  // eslint-disable-next-line no-useless-catch
110
111
  }
package/lib/types.d.ts CHANGED
@@ -354,6 +354,14 @@ export declare class StakeAction {
354
354
  stakeTransfer: {};
355
355
  };
356
356
  }
357
+ export declare class SettlePnlMode {
358
+ static readonly TRY_SETTLE: {
359
+ trySettle: {};
360
+ };
361
+ static readonly MUST_SETTLE: {
362
+ mustSettle: {};
363
+ };
364
+ }
357
365
  export declare function isVariant(object: unknown, type: string): boolean;
358
366
  export declare function isOneOfVariant(object: unknown, types: string[]): boolean;
359
367
  export declare function getVariant(object: unknown): string;
@@ -1201,6 +1209,7 @@ export type HealthComponent = {
1201
1209
  };
1202
1210
  export interface DriftClientMetricsEvents {
1203
1211
  txSigned: SignedTxData[];
1212
+ preTxSigned: void;
1204
1213
  }
1205
1214
  export type SignedTxData = {
1206
1215
  txSig: string;
package/lib/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SwapReduceOnly = exports.DefaultOrderParams = exports.ModifyOrderPolicy = exports.PostOnlyParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.getVariant = exports.isOneOfVariant = exports.isVariant = exports.StakeAction = exports.SpotFulfillmentConfigStatus = exports.SettlePnlExplanation = exports.DepositExplanation = exports.SpotFulfillmentStatus = exports.SpotFulfillmentType = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderStatus = exports.MarketType = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.SpotBalanceType = exports.SwapDirection = exports.AssetTier = exports.ContractTier = exports.ContractType = exports.UserStatus = exports.InsuranceFundOperation = exports.SpotOperation = exports.PerpOperation = exports.MarketStatus = exports.ExchangeStatus = void 0;
3
+ exports.SwapReduceOnly = exports.DefaultOrderParams = exports.ModifyOrderPolicy = exports.PostOnlyParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.getVariant = exports.isOneOfVariant = exports.isVariant = exports.SettlePnlMode = exports.StakeAction = exports.SpotFulfillmentConfigStatus = exports.SettlePnlExplanation = exports.DepositExplanation = exports.SpotFulfillmentStatus = exports.SpotFulfillmentType = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderStatus = exports.MarketType = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.SpotBalanceType = exports.SwapDirection = exports.AssetTier = exports.ContractTier = exports.ContractType = exports.UserStatus = exports.InsuranceFundOperation = exports.SpotOperation = exports.PerpOperation = exports.MarketStatus = exports.ExchangeStatus = void 0;
4
4
  const _1 = require(".");
5
5
  // # Utility Types / Enums / Constants
6
6
  var ExchangeStatus;
@@ -233,6 +233,11 @@ StakeAction.UNSTAKE_CANCEL_REQUEST = { unstakeCancelRequest: {} };
233
233
  StakeAction.UNSTAKE = { unstake: {} };
234
234
  StakeAction.UNSTAKE_TRANSFER = { unstakeTransfer: {} };
235
235
  StakeAction.STAKE_TRANSFER = { stakeTransfer: {} };
236
+ class SettlePnlMode {
237
+ }
238
+ exports.SettlePnlMode = SettlePnlMode;
239
+ SettlePnlMode.TRY_SETTLE = { trySettle: {} };
240
+ SettlePnlMode.MUST_SETTLE = { mustSettle: {} };
236
241
  function isVariant(object, type) {
237
242
  return object.hasOwnProperty(type);
238
243
  }
@@ -1,2 +1,8 @@
1
- import { Connection, Finality, PublicKey } from '@solana/web3.js';
1
+ import { Connection, Finality, PublicKey, TransactionInstruction } from '@solana/web3.js';
2
2
  export declare function findComputeUnitConsumption(programId: PublicKey, connection: Connection, txSignature: string, commitment?: Finality): Promise<number[]>;
3
+ export declare function isSetComputeUnitsIx(ix: TransactionInstruction): boolean;
4
+ export declare function isSetComputeUnitPriceIx(ix: TransactionInstruction): boolean;
5
+ export declare function containsComputeUnitIxs(ixs: TransactionInstruction[]): {
6
+ hasSetComputeUnitLimitIx: boolean;
7
+ hasSetComputeUnitPriceIx: boolean;
8
+ };
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findComputeUnitConsumption = void 0;
3
+ exports.containsComputeUnitIxs = exports.isSetComputeUnitPriceIx = exports.isSetComputeUnitsIx = exports.findComputeUnitConsumption = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
4
5
  async function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
5
6
  const tx = await connection.getTransaction(txSignature, { commitment });
6
7
  const computeUnits = [];
@@ -14,3 +15,32 @@ async function findComputeUnitConsumption(programId, connection, txSignature, co
14
15
  return computeUnits;
15
16
  }
16
17
  exports.findComputeUnitConsumption = findComputeUnitConsumption;
18
+ function isSetComputeUnitsIx(ix) {
19
+ // Compute budget program discriminator is first byte
20
+ // 2: set compute unit limit
21
+ // 3: set compute unit price
22
+ if (ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId) &&
23
+ ix.data.at(0) === 2) {
24
+ return true;
25
+ }
26
+ return false;
27
+ }
28
+ exports.isSetComputeUnitsIx = isSetComputeUnitsIx;
29
+ function isSetComputeUnitPriceIx(ix) {
30
+ // Compute budget program discriminator is first byte
31
+ // 2: set compute unit limit
32
+ // 3: set compute unit price
33
+ if (ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId) &&
34
+ ix.data.at(0) === 3) {
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+ exports.isSetComputeUnitPriceIx = isSetComputeUnitPriceIx;
40
+ function containsComputeUnitIxs(ixs) {
41
+ return {
42
+ hasSetComputeUnitLimitIx: ixs.some(isSetComputeUnitsIx),
43
+ hasSetComputeUnitPriceIx: ixs.some(isSetComputeUnitPriceIx),
44
+ };
45
+ }
46
+ exports.containsComputeUnitIxs = containsComputeUnitIxs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.83.0-beta.1",
3
+ "version": "2.83.0-beta.10",
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);
@@ -14,12 +14,20 @@ export interface ClockSubscriberEvent {
14
14
  }
15
15
 
16
16
  export class ClockSubscriber {
17
- private latestSlot: number;
18
- currentTs: number;
17
+ private _latestSlot: number;
18
+ private _currentTs: number;
19
19
  private subscriptionId: number;
20
20
  commitment: Commitment;
21
21
  eventEmitter: StrictEventEmitter<EventEmitter, ClockSubscriberEvent>;
22
22
 
23
+ public get latestSlot(): number {
24
+ return this._latestSlot;
25
+ }
26
+
27
+ public get currentTs(): number {
28
+ return this._currentTs;
29
+ }
30
+
23
31
  // Reconnection
24
32
  private timeoutId?: NodeJS.Timeout;
25
33
  private resubTimeoutMs?: number;
@@ -54,8 +62,8 @@ export class ClockSubscriber {
54
62
  clearTimeout(this.timeoutId);
55
63
  this.setTimeout();
56
64
  }
57
- this.latestSlot = context.slot;
58
- this.currentTs = new BN(
65
+ this._latestSlot = context.slot;
66
+ this._currentTs = new BN(
59
67
  acctInfo.data.subarray(32, 39),
60
68
  undefined,
61
69
  'le'