@drift-labs/sdk 2.55.0-beta.4 → 2.56.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.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.55.0-beta.4
1
+ 2.56.0-beta.1
@@ -1470,7 +1470,7 @@ class DriftClient {
1470
1470
  const { signedVersionedMarketOrderTx, signedVersionedFillTx, signedCancelExistingOrdersTx, signedSettlePnlTx, } = await (0, utils_1.getSignedTransactionMap)(
1471
1471
  //@ts-ignore
1472
1472
  this.provider.wallet, allPossibleTxs, txKeys);
1473
- const { txSig, slot } = await this.txSender.sendRawTransaction(signedVersionedMarketOrderTx.serialize(), this.opts);
1473
+ const { txSig, slot } = await this.sendTransaction(signedVersionedMarketOrderTx, [], this.opts, true);
1474
1474
  this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
1475
1475
  return {
1476
1476
  txSig,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.54.0",
2
+ "version": "2.55.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -47,7 +47,7 @@ export declare function calculateEntryPrice(userPosition: PerpPosition): BN;
47
47
  * @param userPosition
48
48
  * @returns Precision: PRICE_PRECISION (10^10)
49
49
  */
50
- export declare function calculateCostBasis(userPosition: PerpPosition): BN;
50
+ export declare function calculateCostBasis(userPosition: PerpPosition, includeSettledPnl?: boolean): BN;
51
51
  export declare function findDirectionToClose(userPosition: PerpPosition): PositionDirection;
52
52
  export declare function positionCurrentDirection(userPosition: PerpPosition): PositionDirection;
53
53
  export declare function isEmptyPosition(userPosition: PerpPosition): boolean;
@@ -162,11 +162,12 @@ exports.calculateEntryPrice = calculateEntryPrice;
162
162
  * @param userPosition
163
163
  * @returns Precision: PRICE_PRECISION (10^10)
164
164
  */
165
- function calculateCostBasis(userPosition) {
165
+ function calculateCostBasis(userPosition, includeSettledPnl = false) {
166
166
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
167
167
  return numericConstants_1.ZERO;
168
168
  }
169
169
  return userPosition.quoteAssetAmount
170
+ .add(includeSettledPnl ? userPosition.settledPnl : numericConstants_1.ZERO)
170
171
  .mul(numericConstants_1.PRICE_PRECISION)
171
172
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
172
173
  .div(userPosition.baseAssetAmount)
@@ -34,24 +34,30 @@ class PriorityFeeSubscriber {
34
34
  this.intervalId = setInterval(this.load.bind(this), this.frequencyMs);
35
35
  }
36
36
  async load() {
37
- // @ts-ignore
38
- const rpcJSONResponse = await this.connection._rpcRequest('getRecentPrioritizationFees', [this.addresses]);
39
- const results = rpcJSONResponse === null || rpcJSONResponse === void 0 ? void 0 : rpcJSONResponse.result;
40
- if (!results.length)
37
+ try {
38
+ // @ts-ignore
39
+ const rpcJSONResponse = await this.connection._rpcRequest('getRecentPrioritizationFees', [this.addresses]);
40
+ const results = rpcJSONResponse === null || rpcJSONResponse === void 0 ? void 0 : rpcJSONResponse.result;
41
+ if (!results.length)
42
+ return;
43
+ // # Sort and filter results based on the slot lookback setting
44
+ const descResults = results.sort((a, b) => b.slot - a.slot);
45
+ const mostRecentResult = descResults[0];
46
+ const cutoffSlot = mostRecentResult.slot - this.lookbackDistance;
47
+ const resultsToUse = descResults.filter((result) => result.slot >= cutoffSlot);
48
+ // # Handle results
49
+ this.latestPriorityFee = mostRecentResult.prioritizationFee;
50
+ this.lastSlotSeen = mostRecentResult.slot;
51
+ this.lastAvgStrategyResult = this.averageStrategy.calculate(resultsToUse);
52
+ this.lastMaxStrategyResult = this.maxStrategy.calculate(resultsToUse);
53
+ if (this.customStrategy) {
54
+ this.lastCustomStrategyResult =
55
+ this.customStrategy.calculate(resultsToUse);
56
+ }
57
+ }
58
+ catch (err) {
59
+ // It's possible to get here with "TypeError: failed to fetch"
41
60
  return;
42
- // # Sort and filter results based on the slot lookback setting
43
- const descResults = results.sort((a, b) => b.slot - a.slot);
44
- const mostRecentResult = descResults[0];
45
- const cutoffSlot = mostRecentResult.slot - this.lookbackDistance;
46
- const resultsToUse = descResults.filter((result) => result.slot >= cutoffSlot);
47
- // # Handle results
48
- this.latestPriorityFee = mostRecentResult.prioritizationFee;
49
- this.lastSlotSeen = mostRecentResult.slot;
50
- this.lastAvgStrategyResult = this.averageStrategy.calculate(resultsToUse);
51
- this.lastMaxStrategyResult = this.maxStrategy.calculate(resultsToUse);
52
- if (this.customStrategy) {
53
- this.lastCustomStrategyResult =
54
- this.customStrategy.calculate(resultsToUse);
55
61
  }
56
62
  }
57
63
  async unsubscribe() {
@@ -10,13 +10,15 @@ export declare abstract class BaseTxSender implements TxSender {
10
10
  additionalConnections: Connection[];
11
11
  timeoutCount: number;
12
12
  confirmationStrategy: ConfirmationStrategy;
13
- constructor({ connection, wallet, opts, timeout, additionalConnections, confirmationStrategy, }: {
13
+ additionalTxSenderCallbacks: ((base58EncodedTx: string) => void)[];
14
+ constructor({ connection, wallet, opts, timeout, additionalConnections, confirmationStrategy, additionalTxSenderCallbacks, }: {
14
15
  connection: Connection;
15
16
  wallet: IWallet;
16
17
  opts?: ConfirmOptions;
17
18
  timeout?: number;
18
19
  additionalConnections?: any;
19
20
  confirmationStrategy?: ConfirmationStrategy;
21
+ additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
20
22
  });
21
23
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions, preSigned?: boolean, extraConfirmationOptions?: ExtraConfirmationOptions): Promise<TxSigAndSlot>;
22
24
  prepareTx(tx: Transaction, additionalSigners: Array<Signer>, opts: ConfirmOptions): Promise<Transaction>;
@@ -11,7 +11,7 @@ const assert_1 = __importDefault(require("assert"));
11
11
  const bs58_1 = __importDefault(require("bs58"));
12
12
  const DEFAULT_TIMEOUT = 35000;
13
13
  class BaseTxSender {
14
- constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, }) {
14
+ constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks, }) {
15
15
  this.timeoutCount = 0;
16
16
  this.connection = connection;
17
17
  this.wallet = wallet;
@@ -19,6 +19,7 @@ class BaseTxSender {
19
19
  this.timeout = timeout;
20
20
  this.additionalConnections = additionalConnections;
21
21
  this.confirmationStrategy = confirmationStrategy;
22
+ this.additionalTxSenderCallbacks = additionalTxSenderCallbacks;
22
23
  }
23
24
  async send(tx, additionalSigners, opts, preSigned, extraConfirmationOptions) {
24
25
  if (additionalSigners === undefined) {
@@ -202,6 +203,7 @@ class BaseTxSender {
202
203
  });
203
204
  }
204
205
  sendToAdditionalConnections(rawTx, opts) {
206
+ var _a;
205
207
  this.additionalConnections.map((connection) => {
206
208
  connection.sendRawTransaction(rawTx, opts).catch((e) => {
207
209
  console.error(
@@ -210,6 +212,9 @@ class BaseTxSender {
210
212
  console.error(e);
211
213
  });
212
214
  });
215
+ (_a = this.additionalTxSenderCallbacks) === null || _a === void 0 ? void 0 : _a.map((callback) => {
216
+ callback(bs58_1.default.encode(rawTx));
217
+ });
213
218
  }
214
219
  addAdditionalConnection(newConnection) {
215
220
  const alreadyUsingConnection = this.additionalConnections.filter((connection) => {
@@ -14,7 +14,7 @@ export declare class RetryTxSender extends BaseTxSender {
14
14
  retrySleep: number;
15
15
  additionalConnections: Connection[];
16
16
  timoutCount: number;
17
- constructor({ connection, wallet, opts, timeout, retrySleep, additionalConnections, confirmationStrategy, }: {
17
+ constructor({ connection, wallet, opts, timeout, retrySleep, additionalConnections, confirmationStrategy, additionalTxSenderCallbacks, }: {
18
18
  connection: Connection;
19
19
  wallet: IWallet;
20
20
  opts?: ConfirmOptions;
@@ -22,6 +22,7 @@ export declare class RetryTxSender extends BaseTxSender {
22
22
  retrySleep?: number;
23
23
  additionalConnections?: any;
24
24
  confirmationStrategy?: ConfirmationStrategy;
25
+ additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
25
26
  });
26
27
  sleep(reference: ResolveReference): Promise<void>;
27
28
  sendRawTransaction(rawTransaction: Buffer | Uint8Array, opts: ConfirmOptions): Promise<TxSigAndSlot>;
@@ -7,7 +7,7 @@ const baseTxSender_1 = require("./baseTxSender");
7
7
  const DEFAULT_TIMEOUT = 35000;
8
8
  const DEFAULT_RETRY = 8000;
9
9
  class RetryTxSender extends baseTxSender_1.BaseTxSender {
10
- constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, }) {
10
+ constructor({ connection, wallet, opts = anchor_1.AnchorProvider.defaultOptions(), timeout = DEFAULT_TIMEOUT, retrySleep = DEFAULT_RETRY, additionalConnections = new Array(), confirmationStrategy = types_1.ConfirmationStrategy.Combo, additionalTxSenderCallbacks = [], }) {
11
11
  super({
12
12
  connection,
13
13
  wallet,
@@ -15,6 +15,7 @@ class RetryTxSender extends baseTxSender_1.BaseTxSender {
15
15
  timeout,
16
16
  additionalConnections,
17
17
  confirmationStrategy,
18
+ additionalTxSenderCallbacks,
18
19
  });
19
20
  this.timoutCount = 0;
20
21
  this.connection = connection;
package/lib/user.js CHANGED
@@ -1825,10 +1825,11 @@ class User {
1825
1825
  perpPnl: [],
1826
1826
  };
1827
1827
  for (const perpPosition of this.getActivePerpPositions()) {
1828
+ const settledLpPosition = this.getPerpPositionWithLPSettle(perpPosition.marketIndex, perpPosition)[0];
1828
1829
  const perpMarket = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
1829
1830
  const oraclePriceData = this.driftClient.getOraclePriceDataAndSlot(perpMarket.amm.oracle).data;
1830
1831
  const oraclePrice = oraclePriceData.price;
1831
- const worstCaseBaseAmount = (0, margin_1.calculateWorstCaseBaseAssetAmount)(perpPosition);
1832
+ const worstCaseBaseAmount = (0, margin_1.calculateWorstCaseBaseAssetAmount)(settledLpPosition);
1832
1833
  const marginRatio = new _1.BN((0, _1.calculateMarketMarginRatio)(perpMarket, worstCaseBaseAmount.abs(), marginCategory, this.getUserAccount().maxMarginRatio));
1833
1834
  const quoteSpotMarket = this.driftClient.getSpotMarketAccount(perpMarket.quoteSpotMarketIndex);
1834
1835
  const quoteOraclePriceData = this.driftClient.getOraclePriceDataAndSlot(quoteSpotMarket.oracle).data;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "2.55.0-beta.4",
3
+ "version": "2.56.0-beta.1",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -2690,9 +2690,11 @@ export class DriftClient {
2690
2690
  txKeys
2691
2691
  );
2692
2692
 
2693
- const { txSig, slot } = await this.txSender.sendRawTransaction(
2694
- signedVersionedMarketOrderTx.serialize(),
2695
- this.opts
2693
+ const { txSig, slot } = await this.sendTransaction(
2694
+ signedVersionedMarketOrderTx,
2695
+ [],
2696
+ this.opts,
2697
+ true
2696
2698
  );
2697
2699
  this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
2698
2700
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.54.0",
2
+ "version": "2.55.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -237,12 +237,16 @@ export function calculateEntryPrice(userPosition: PerpPosition): BN {
237
237
  * @param userPosition
238
238
  * @returns Precision: PRICE_PRECISION (10^10)
239
239
  */
240
- export function calculateCostBasis(userPosition: PerpPosition): BN {
240
+ export function calculateCostBasis(
241
+ userPosition: PerpPosition,
242
+ includeSettledPnl = false
243
+ ): BN {
241
244
  if (userPosition.baseAssetAmount.eq(ZERO)) {
242
245
  return ZERO;
243
246
  }
244
247
 
245
248
  return userPosition.quoteAssetAmount
249
+ .add(includeSettledPnl ? userPosition.settledPnl : ZERO)
246
250
  .mul(PRICE_PRECISION)
247
251
  .mul(AMM_TO_QUOTE_PRECISION_RATIO)
248
252
  .div(userPosition.baseAssetAmount)
@@ -57,35 +57,40 @@ export class PriorityFeeSubscriber {
57
57
  }
58
58
 
59
59
  public async load(): Promise<void> {
60
- // @ts-ignore
61
- const rpcJSONResponse: any = await this.connection._rpcRequest(
62
- 'getRecentPrioritizationFees',
63
- [this.addresses]
64
- );
60
+ try {
61
+ // @ts-ignore
62
+ const rpcJSONResponse: any = await this.connection._rpcRequest(
63
+ 'getRecentPrioritizationFees',
64
+ [this.addresses]
65
+ );
65
66
 
66
- const results: { slot: number; prioritizationFee: number }[] =
67
- rpcJSONResponse?.result;
67
+ const results: { slot: number; prioritizationFee: number }[] =
68
+ rpcJSONResponse?.result;
68
69
 
69
- if (!results.length) return;
70
+ if (!results.length) return;
70
71
 
71
- // # Sort and filter results based on the slot lookback setting
72
- const descResults = results.sort((a, b) => b.slot - a.slot);
73
- const mostRecentResult = descResults[0];
74
- const cutoffSlot = mostRecentResult.slot - this.lookbackDistance;
72
+ // # Sort and filter results based on the slot lookback setting
73
+ const descResults = results.sort((a, b) => b.slot - a.slot);
74
+ const mostRecentResult = descResults[0];
75
+ const cutoffSlot = mostRecentResult.slot - this.lookbackDistance;
75
76
 
76
- const resultsToUse = descResults.filter(
77
- (result) => result.slot >= cutoffSlot
78
- );
77
+ const resultsToUse = descResults.filter(
78
+ (result) => result.slot >= cutoffSlot
79
+ );
79
80
 
80
- // # Handle results
81
- this.latestPriorityFee = mostRecentResult.prioritizationFee;
82
- this.lastSlotSeen = mostRecentResult.slot;
81
+ // # Handle results
82
+ this.latestPriorityFee = mostRecentResult.prioritizationFee;
83
+ this.lastSlotSeen = mostRecentResult.slot;
83
84
 
84
- this.lastAvgStrategyResult = this.averageStrategy.calculate(resultsToUse);
85
- this.lastMaxStrategyResult = this.maxStrategy.calculate(resultsToUse);
86
- if (this.customStrategy) {
87
- this.lastCustomStrategyResult =
88
- this.customStrategy.calculate(resultsToUse);
85
+ this.lastAvgStrategyResult = this.averageStrategy.calculate(resultsToUse);
86
+ this.lastMaxStrategyResult = this.maxStrategy.calculate(resultsToUse);
87
+ if (this.customStrategy) {
88
+ this.lastCustomStrategyResult =
89
+ this.customStrategy.calculate(resultsToUse);
90
+ }
91
+ } catch (err) {
92
+ // It's possible to get here with "TypeError: failed to fetch"
93
+ return;
89
94
  }
90
95
  }
91
96
 
@@ -34,6 +34,7 @@ export abstract class BaseTxSender implements TxSender {
34
34
  additionalConnections: Connection[];
35
35
  timeoutCount = 0;
36
36
  confirmationStrategy: ConfirmationStrategy;
37
+ additionalTxSenderCallbacks: ((base58EncodedTx: string) => void)[];
37
38
 
38
39
  public constructor({
39
40
  connection,
@@ -42,6 +43,7 @@ export abstract class BaseTxSender implements TxSender {
42
43
  timeout = DEFAULT_TIMEOUT,
43
44
  additionalConnections = new Array<Connection>(),
44
45
  confirmationStrategy = ConfirmationStrategy.Combo,
46
+ additionalTxSenderCallbacks,
45
47
  }: {
46
48
  connection: Connection;
47
49
  wallet: IWallet;
@@ -49,6 +51,7 @@ export abstract class BaseTxSender implements TxSender {
49
51
  timeout?: number;
50
52
  additionalConnections?;
51
53
  confirmationStrategy?: ConfirmationStrategy;
54
+ additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
52
55
  }) {
53
56
  this.connection = connection;
54
57
  this.wallet = wallet;
@@ -56,6 +59,7 @@ export abstract class BaseTxSender implements TxSender {
56
59
  this.timeout = timeout;
57
60
  this.additionalConnections = additionalConnections;
58
61
  this.confirmationStrategy = confirmationStrategy;
62
+ this.additionalTxSenderCallbacks = additionalTxSenderCallbacks;
59
63
  }
60
64
 
61
65
  async send(
@@ -333,6 +337,9 @@ export abstract class BaseTxSender implements TxSender {
333
337
  console.error(e);
334
338
  });
335
339
  });
340
+ this.additionalTxSenderCallbacks?.map((callback) => {
341
+ callback(bs58.encode(rawTx));
342
+ });
336
343
  }
337
344
 
338
345
  public addAdditionalConnection(newConnection: Connection): void {
@@ -28,6 +28,7 @@ export class RetryTxSender extends BaseTxSender {
28
28
  retrySleep = DEFAULT_RETRY,
29
29
  additionalConnections = new Array<Connection>(),
30
30
  confirmationStrategy = ConfirmationStrategy.Combo,
31
+ additionalTxSenderCallbacks = [],
31
32
  }: {
32
33
  connection: Connection;
33
34
  wallet: IWallet;
@@ -36,6 +37,7 @@ export class RetryTxSender extends BaseTxSender {
36
37
  retrySleep?: number;
37
38
  additionalConnections?;
38
39
  confirmationStrategy?: ConfirmationStrategy;
40
+ additionalTxSenderCallbacks?: ((base58EncodedTx: string) => void)[];
39
41
  }) {
40
42
  super({
41
43
  connection,
@@ -44,6 +46,7 @@ export class RetryTxSender extends BaseTxSender {
44
46
  timeout,
45
47
  additionalConnections,
46
48
  confirmationStrategy,
49
+ additionalTxSenderCallbacks,
47
50
  });
48
51
  this.connection = connection;
49
52
  this.wallet = wallet;
package/src/user.ts CHANGED
@@ -3293,6 +3293,10 @@ export class User {
3293
3293
  };
3294
3294
 
3295
3295
  for (const perpPosition of this.getActivePerpPositions()) {
3296
+ const settledLpPosition = this.getPerpPositionWithLPSettle(
3297
+ perpPosition.marketIndex,
3298
+ perpPosition
3299
+ )[0];
3296
3300
  const perpMarket = this.driftClient.getPerpMarketAccount(
3297
3301
  perpPosition.marketIndex
3298
3302
  );
@@ -3301,7 +3305,7 @@ export class User {
3301
3305
  ).data;
3302
3306
  const oraclePrice = oraclePriceData.price;
3303
3307
  const worstCaseBaseAmount =
3304
- calculateWorstCaseBaseAssetAmount(perpPosition);
3308
+ calculateWorstCaseBaseAssetAmount(settledLpPosition);
3305
3309
 
3306
3310
  const marginRatio = new BN(
3307
3311
  calculateMarketMarginRatio(