@drift-labs/sdk 2.131.0-beta.9 → 2.131.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.131.0-beta.9
1
+ 2.131.0-beta.13
@@ -427,8 +427,25 @@ export declare class DriftClient {
427
427
  getCancelOrderIx(orderId?: number, subAccountId?: number): Promise<TransactionInstruction>;
428
428
  cancelOrderByUserId(userOrderId: number, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
429
429
  getCancelOrderByUserIdIx(userOrderId: number, subAccountId?: number): Promise<TransactionInstruction>;
430
- cancelOrdersByIds(orderIds?: number[], txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
431
- getCancelOrdersByIdsIx(orderIds?: number[], subAccountId?: number): Promise<TransactionInstruction>;
430
+ /**
431
+ * Sends a transaction to cancel the provided order ids.
432
+ *
433
+ * @param orderIds - The order ids to cancel.
434
+ * @param txParams - The transaction parameters.
435
+ * @param subAccountId - The sub account id to cancel the orders for.
436
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
437
+ * @returns The transaction signature.
438
+ */
439
+ cancelOrdersByIds(orderIds?: number[], txParams?: TxParams, subAccountId?: number, user?: User): Promise<TransactionSignature>;
440
+ /**
441
+ * Returns the transaction instruction to cancel the provided order ids.
442
+ *
443
+ * @param orderIds - The order ids to cancel.
444
+ * @param subAccountId - The sub account id to cancel the orders for.
445
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
446
+ * @returns The transaction instruction to cancel the orders.
447
+ */
448
+ getCancelOrdersByIdsIx(orderIds?: number[], subAccountId?: number, user?: User): Promise<TransactionInstruction>;
432
449
  cancelOrders(marketType?: MarketType, marketIndex?: number, direction?: PositionDirection, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
433
450
  getCancelOrdersIx(marketType: MarketType | null, marketIndex: number | null, direction: PositionDirection | null, subAccountId?: number): Promise<TransactionInstruction>;
434
451
  cancelAndPlaceOrders(cancelOrderParams: {
@@ -659,6 +676,12 @@ export declare class DriftClient {
659
676
  maxTs?: BN;
660
677
  policy?: number;
661
678
  }, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
679
+ /**
680
+ * @param orderParams: The parameters for the order to modify.
681
+ * @param subAccountId: Optional - The subaccount ID of the user to modify the order for.
682
+ * @param userPublicKey: Optional - The public key of the user to modify the order for. This takes precedence over subAccountId.
683
+ * @returns
684
+ */
662
685
  getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }: {
663
686
  orderId: number;
664
687
  newDirection?: PositionDirection;
@@ -675,7 +698,7 @@ export declare class DriftClient {
675
698
  bitFlags?: number;
676
699
  maxTs?: BN;
677
700
  policy?: number;
678
- }, subAccountId?: number): Promise<TransactionInstruction>;
701
+ }, subAccountId?: number, userPublicKey?: PublicKey): Promise<TransactionInstruction>;
679
702
  /**
680
703
  * Modifies an open order by closing it and replacing it with a new order.
681
704
  * @param orderParams.userOrderId: The open order to modify
@@ -2273,20 +2273,39 @@ class DriftClient {
2273
2273
  remainingAccounts,
2274
2274
  });
2275
2275
  }
2276
- async cancelOrdersByIds(orderIds, txParams, subAccountId) {
2277
- const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersByIdsIx(orderIds, subAccountId), txParams), [], this.opts);
2276
+ /**
2277
+ * Sends a transaction to cancel the provided order ids.
2278
+ *
2279
+ * @param orderIds - The order ids to cancel.
2280
+ * @param txParams - The transaction parameters.
2281
+ * @param subAccountId - The sub account id to cancel the orders for.
2282
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
2283
+ * @returns The transaction signature.
2284
+ */
2285
+ async cancelOrdersByIds(orderIds, txParams, subAccountId, user) {
2286
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersByIdsIx(orderIds, subAccountId, user), txParams), [], this.opts);
2278
2287
  return txSig;
2279
2288
  }
2280
- async getCancelOrdersByIdsIx(orderIds, subAccountId) {
2281
- const user = await this.getUserAccountPublicKey(subAccountId);
2289
+ /**
2290
+ * Returns the transaction instruction to cancel the provided order ids.
2291
+ *
2292
+ * @param orderIds - The order ids to cancel.
2293
+ * @param subAccountId - The sub account id to cancel the orders for.
2294
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
2295
+ * @returns The transaction instruction to cancel the orders.
2296
+ */
2297
+ async getCancelOrdersByIdsIx(orderIds, subAccountId, user) {
2298
+ var _a, _b;
2299
+ const userAccountPubKey = (_a = user === null || user === void 0 ? void 0 : user.userAccountPublicKey) !== null && _a !== void 0 ? _a : (await this.getUserAccountPublicKey(subAccountId));
2300
+ const userAccount = (_b = user === null || user === void 0 ? void 0 : user.getUserAccount()) !== null && _b !== void 0 ? _b : this.getUserAccount(subAccountId);
2282
2301
  const remainingAccounts = this.getRemainingAccounts({
2283
- userAccounts: [this.getUserAccount(subAccountId)],
2302
+ userAccounts: [userAccount],
2284
2303
  useMarketLastSlotCache: true,
2285
2304
  });
2286
2305
  return await this.program.instruction.cancelOrdersByIds(orderIds, {
2287
2306
  accounts: {
2288
2307
  state: await this.getStatePublicKey(),
2289
- user,
2308
+ user: userAccountPubKey,
2290
2309
  authority: this.wallet.publicKey,
2291
2310
  },
2292
2311
  remainingAccounts,
@@ -3698,8 +3717,14 @@ class DriftClient {
3698
3717
  const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getModifyOrderIx(orderParams, subAccountId), txParams), [], this.opts);
3699
3718
  return txSig;
3700
3719
  }
3701
- async getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }, subAccountId) {
3702
- const user = await this.getUserAccountPublicKey(subAccountId);
3720
+ /**
3721
+ * @param orderParams: The parameters for the order to modify.
3722
+ * @param subAccountId: Optional - The subaccount ID of the user to modify the order for.
3723
+ * @param userPublicKey: Optional - The public key of the user to modify the order for. This takes precedence over subAccountId.
3724
+ * @returns
3725
+ */
3726
+ async getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }, subAccountId, userPublicKey) {
3727
+ const user = userPublicKey !== null && userPublicKey !== void 0 ? userPublicKey : (await this.getUserAccountPublicKey(subAccountId));
3703
3728
  const remainingAccounts = this.getRemainingAccounts({
3704
3729
  userAccounts: [this.getUserAccount(subAccountId)],
3705
3730
  useMarketLastSlotCache: true,
@@ -5146,7 +5171,7 @@ class DriftClient {
5146
5171
  userAccounts: [userAccount],
5147
5172
  })
5148
5173
  : undefined;
5149
- const ix = await this.program.instruction.disableUserHighLeverageMode({
5174
+ const ix = await this.program.instruction.disableUserHighLeverageMode(false, {
5150
5175
  accounts: {
5151
5176
  state: await this.getStatePublicKey(),
5152
5177
  user,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.130.0",
2
+ "version": "2.131.0",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
@@ -17,7 +17,7 @@ export declare function calculateOraclePriceForPerpMargin(perpPosition: PerpPosi
17
17
  * @param oraclePriceData
18
18
  * @param includeOpenOrders
19
19
  */
20
- export declare function calculateBaseAssetValueWithOracle(market: PerpMarketAccount, perpPosition: PerpPosition, oraclePriceData: OraclePriceData, includeOpenOrders?: boolean): BN;
20
+ export declare function calculateBaseAssetValueWithOracle(market: PerpMarketAccount, perpPosition: PerpPosition, oraclePriceData: Pick<OraclePriceData, 'price'>, includeOpenOrders?: boolean): BN;
21
21
  export declare function calculateWorstCaseBaseAssetAmount(perpPosition: PerpPosition, perpMarket: PerpMarketAccount, oraclePrice: BN): BN;
22
22
  export declare function calculateWorstCasePerpLiabilityValue(perpPosition: PerpPosition, perpMarket: PerpMarketAccount, oraclePrice: BN): {
23
23
  worstCaseBaseAssetAmount: BN;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebsocketSubscription = void 0;
4
4
  const memcmp_1 = require("../memcmp");
5
- const webSocketProgramAccountSubscriberV2_1 = require("../accounts/webSocketProgramAccountSubscriberV2");
5
+ const webSocketProgramAccountSubscriber_1 = require("../accounts/webSocketProgramAccountSubscriber");
6
6
  class WebsocketSubscription {
7
7
  constructor({ orderSubscriber, commitment, skipInitialLoad = false, resubOpts, resyncIntervalMs, decoded = true, }) {
8
8
  this.orderSubscriber = orderSubscriber;
@@ -16,7 +16,7 @@ class WebsocketSubscription {
16
16
  if (this.subscriber) {
17
17
  return;
18
18
  }
19
- this.subscriber = new webSocketProgramAccountSubscriberV2_1.WebSocketProgramAccountSubscriberV2('OrderSubscriber', 'User', this.orderSubscriber.driftClient.program, this.orderSubscriber.decodeFn, {
19
+ this.subscriber = new webSocketProgramAccountSubscriber_1.WebSocketProgramAccountSubscriber('OrderSubscriber', 'User', this.orderSubscriber.driftClient.program, this.orderSubscriber.decodeFn, {
20
20
  filters: [(0, memcmp_1.getUserFilter)(), (0, memcmp_1.getNonIdleUserFilter)()],
21
21
  commitment: this.commitment,
22
22
  }, this.resubOpts);
@@ -103,21 +103,21 @@ export declare class User {
103
103
  * calculates Buying Power = free collateral / initial margin ratio
104
104
  * @returns : Precision QUOTE_PRECISION
105
105
  */
106
- getPerpBuyingPower(marketIndex: number, collateralBuffer?: BN, enterHighLeverageMode?: boolean): BN;
107
- getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex: number, freeCollateral: BN, baseAssetAmount: BN, enterHighLeverageMode?: boolean): BN;
106
+ getPerpBuyingPower(marketIndex: number, collateralBuffer?: BN, enterHighLeverageMode?: any): BN;
107
+ getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex: number, freeCollateral: BN, baseAssetAmount: BN, enterHighLeverageMode?: any): BN;
108
108
  /**
109
109
  * calculates Free Collateral = Total collateral - margin requirement
110
110
  * @returns : Precision QUOTE_PRECISION
111
111
  */
112
- getFreeCollateral(marginCategory?: MarginCategory, enterHighLeverageMode?: boolean): BN;
112
+ getFreeCollateral(marginCategory?: MarginCategory, enterHighLeverageMode?: any): BN;
113
113
  /**
114
114
  * @returns The margin requirement of a certain type (Initial or Maintenance) in USDC. : QUOTE_PRECISION
115
115
  */
116
- getMarginRequirement(marginCategory: MarginCategory, liquidationBuffer?: BN, strict?: boolean, includeOpenOrders?: boolean, enteringHighLeverage?: boolean): BN;
116
+ getMarginRequirement(marginCategory: MarginCategory, liquidationBuffer?: BN, strict?: boolean, includeOpenOrders?: boolean, enteringHighLeverage?: any): BN;
117
117
  /**
118
118
  * @returns The initial margin requirement in USDC. : QUOTE_PRECISION
119
119
  */
120
- getInitialMarginRequirement(enterHighLeverageMode?: boolean): BN;
120
+ getInitialMarginRequirement(enterHighLeverageMode?: any): BN;
121
121
  /**
122
122
  * @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
123
123
  */
@@ -167,7 +167,7 @@ export declare class User {
167
167
  * @returns : number (value from [0, 100])
168
168
  */
169
169
  getHealth(): number;
170
- calculateWeightedPerpPositionLiability(perpPosition: PerpPosition, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, enteringHighLeverage?: boolean): BN;
170
+ calculateWeightedPerpPositionLiability(perpPosition: PerpPosition, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, enteringHighLeverage?: any): BN;
171
171
  /**
172
172
  * calculates position value of a single perp market in margin system
173
173
  * @returns : Precision QUOTE_PRECISION
@@ -177,12 +177,12 @@ export declare class User {
177
177
  * calculates sum of position value across all positions in margin system
178
178
  * @returns : Precision QUOTE_PRECISION
179
179
  */
180
- getTotalPerpPositionLiability(marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, enteringHighLeverage?: boolean): BN;
180
+ getTotalPerpPositionLiability(marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, enteringHighLeverage?: any): BN;
181
181
  /**
182
182
  * calculates position value based on oracle
183
183
  * @returns : Precision QUOTE_PRECISION
184
184
  */
185
- getPerpPositionValue(marketIndex: number, oraclePriceData: OraclePriceData, includeOpenOrders?: boolean): BN;
185
+ getPerpPositionValue(marketIndex: number, oraclePriceData: Pick<OraclePriceData, 'price'>, includeOpenOrders?: boolean): BN;
186
186
  /**
187
187
  * calculates position liabiltiy value in margin system
188
188
  * @returns : Precision QUOTE_PRECISION
@@ -230,7 +230,7 @@ export declare class User {
230
230
  * @param enterHighLeverageMode can pass this as true to calculate max leverage if the user was to enter high leverage mode
231
231
  * @returns : Precision TEN_THOUSAND
232
232
  */
233
- getMaxLeverageForPerp(perpMarketIndex: number, _marginCategory?: MarginCategory, isLp?: boolean, enterHighLeverageMode?: boolean): BN;
233
+ getMaxLeverageForPerp(perpMarketIndex: number, _marginCategory?: MarginCategory, isLp?: boolean, enterHighLeverageMode?: any): BN;
234
234
  /**
235
235
  * calculates max allowable leverage exceeding hitting requirement category
236
236
  * @param spotMarketIndex
@@ -273,9 +273,9 @@ export declare class User {
273
273
  * @param offsetCollateral // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)
274
274
  * @returns Precision : PRICE_PRECISION
275
275
  */
276
- liquidationPrice(marketIndex: number, positionBaseSizeChange?: BN, estimatedEntryPrice?: BN, marginCategory?: MarginCategory, includeOpenOrders?: boolean, offsetCollateral?: BN, enteringHighLeverage?: boolean): BN;
277
- calculateEntriesEffectOnFreeCollateral(market: PerpMarketAccount, oraclePrice: BN, perpPosition: PerpPosition, positionBaseSizeChange: BN, estimatedEntryPrice: BN, includeOpenOrders: boolean, enteringHighLeverage?: boolean, marginCategory?: MarginCategory): BN;
278
- calculateFreeCollateralDeltaForPerp(market: PerpMarketAccount, perpPosition: PerpPosition, positionBaseSizeChange: BN, oraclePrice: BN, marginCategory?: MarginCategory, includeOpenOrders?: boolean, enteringHighLeverage?: boolean): BN | undefined;
276
+ liquidationPrice(marketIndex: number, positionBaseSizeChange?: BN, estimatedEntryPrice?: BN, marginCategory?: MarginCategory, includeOpenOrders?: boolean, offsetCollateral?: BN, enteringHighLeverage?: any): BN;
277
+ calculateEntriesEffectOnFreeCollateral(market: PerpMarketAccount, oraclePrice: BN, perpPosition: PerpPosition, positionBaseSizeChange: BN, estimatedEntryPrice: BN, includeOpenOrders: boolean, enteringHighLeverage?: any, marginCategory?: MarginCategory): BN;
278
+ calculateFreeCollateralDeltaForPerp(market: PerpMarketAccount, perpPosition: PerpPosition, positionBaseSizeChange: BN, oraclePrice: BN, marginCategory?: MarginCategory, includeOpenOrders?: boolean, enteringHighLeverage?: any): BN | undefined;
279
279
  calculateFreeCollateralDeltaForSpot(market: SpotMarketAccount, signedTokenAmount: BN, marginCategory?: MarginCategory): BN;
280
280
  /**
281
281
  * Calculates the estimated liquidation price for a position after closing a quote amount of the position.
@@ -295,7 +295,7 @@ export declare class User {
295
295
  * @param isLp
296
296
  * @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION
297
297
  */
298
- getMaxTradeSizeUSDCForPerp(targetMarketIndex: number, tradeSide: PositionDirection, isLp?: boolean, enterHighLeverageMode?: boolean): {
298
+ getMaxTradeSizeUSDCForPerp(targetMarketIndex: number, tradeSide: PositionDirection, isLp?: boolean, enterHighLeverageMode?: any): {
299
299
  tradeSize: BN;
300
300
  oppositeSideTradeSize: BN;
301
301
  };
@@ -426,7 +426,7 @@ class User {
426
426
  * calculates Buying Power = free collateral / initial margin ratio
427
427
  * @returns : Precision QUOTE_PRECISION
428
428
  */
429
- getPerpBuyingPower(marketIndex, collateralBuffer = numericConstants_1.ZERO, enterHighLeverageMode = false) {
429
+ getPerpBuyingPower(marketIndex, collateralBuffer = numericConstants_1.ZERO, enterHighLeverageMode = undefined) {
430
430
  const perpPosition = this.getPerpPositionWithLPSettle(marketIndex, undefined, true)[0];
431
431
  const perpMarket = this.driftClient.getPerpMarketAccount(marketIndex);
432
432
  const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
@@ -436,7 +436,7 @@ class User {
436
436
  const freeCollateral = this.getFreeCollateral('Initial', enterHighLeverageMode).sub(collateralBuffer);
437
437
  return this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, worstCaseBaseAssetAmount, enterHighLeverageMode);
438
438
  }
439
- getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, baseAssetAmount, enterHighLeverageMode = false) {
439
+ getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, baseAssetAmount, enterHighLeverageMode = undefined) {
440
440
  const marginRatio = (0, market_1.calculateMarketMarginRatio)(this.driftClient.getPerpMarketAccount(marketIndex), baseAssetAmount, 'Initial', this.getUserAccount().maxMarginRatio, enterHighLeverageMode || this.isHighLeverageMode('Initial'));
441
441
  return freeCollateral.mul(numericConstants_1.MARGIN_PRECISION).div(new anchor_1.BN(marginRatio));
442
442
  }
@@ -444,7 +444,7 @@ class User {
444
444
  * calculates Free Collateral = Total collateral - margin requirement
445
445
  * @returns : Precision QUOTE_PRECISION
446
446
  */
447
- getFreeCollateral(marginCategory = 'Initial', enterHighLeverageMode = false) {
447
+ getFreeCollateral(marginCategory = 'Initial', enterHighLeverageMode = undefined) {
448
448
  const totalCollateral = this.getTotalCollateral(marginCategory, true);
449
449
  const marginRequirement = marginCategory === 'Initial'
450
450
  ? this.getInitialMarginRequirement(enterHighLeverageMode)
@@ -455,13 +455,13 @@ class User {
455
455
  /**
456
456
  * @returns The margin requirement of a certain type (Initial or Maintenance) in USDC. : QUOTE_PRECISION
457
457
  */
458
- getMarginRequirement(marginCategory, liquidationBuffer, strict = false, includeOpenOrders = true, enteringHighLeverage = false) {
458
+ getMarginRequirement(marginCategory, liquidationBuffer, strict = false, includeOpenOrders = true, enteringHighLeverage = undefined) {
459
459
  return this.getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders, strict, enteringHighLeverage).add(this.getSpotMarketLiabilityValue(undefined, marginCategory, liquidationBuffer, includeOpenOrders, strict));
460
460
  }
461
461
  /**
462
462
  * @returns The initial margin requirement in USDC. : QUOTE_PRECISION
463
463
  */
464
- getInitialMarginRequirement(enterHighLeverageMode = false) {
464
+ getInitialMarginRequirement(enterHighLeverageMode = undefined) {
465
465
  return this.getMarginRequirement('Initial', undefined, true, undefined, enterHighLeverageMode);
466
466
  }
467
467
  /**
@@ -749,7 +749,7 @@ class User {
749
749
  }
750
750
  return health;
751
751
  }
752
- calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, enteringHighLeverage = false) {
752
+ calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, enteringHighLeverage = undefined) {
753
753
  const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
754
754
  if (perpPosition.lpShares.gt(numericConstants_1.ZERO)) {
755
755
  // is an lp, clone so we dont mutate the position
@@ -771,7 +771,11 @@ class User {
771
771
  liabilityValue = (0, margin_1.calculatePerpLiabilityValue)(baseAssetAmount, valuationPrice, (0, types_1.isVariant)(market.contractType, 'prediction'));
772
772
  }
773
773
  if (marginCategory) {
774
- let marginRatio = new anchor_1.BN((0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, this.getUserAccount().maxMarginRatio, this.isHighLeverageMode(marginCategory) || enteringHighLeverage));
774
+ const userCustomMargin = this.getUserAccount().maxMarginRatio;
775
+ let marginRatio = new anchor_1.BN((0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, enteringHighLeverage === false
776
+ ? Math.max(market.marginRatioInitial, userCustomMargin)
777
+ : userCustomMargin, this.isHighLeverageMode(marginCategory) ||
778
+ enteringHighLeverage === true));
775
779
  if (liquidationBuffer !== undefined) {
776
780
  marginRatio = marginRatio.add(liquidationBuffer);
777
781
  }
@@ -817,7 +821,7 @@ class User {
817
821
  * calculates sum of position value across all positions in margin system
818
822
  * @returns : Precision QUOTE_PRECISION
819
823
  */
820
- getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders, strict = false, enteringHighLeverage = false) {
824
+ getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders, strict = false, enteringHighLeverage = undefined) {
821
825
  return this.getActivePerpPositions().reduce((totalPerpValue, perpPosition) => {
822
826
  const baseAssetValue = this.calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict, enteringHighLeverage);
823
827
  return totalPerpValue.add(baseAssetValue);
@@ -984,7 +988,7 @@ class User {
984
988
  * @param enterHighLeverageMode can pass this as true to calculate max leverage if the user was to enter high leverage mode
985
989
  * @returns : Precision TEN_THOUSAND
986
990
  */
987
- getMaxLeverageForPerp(perpMarketIndex, _marginCategory = 'Initial', isLp = false, enterHighLeverageMode = false) {
991
+ getMaxLeverageForPerp(perpMarketIndex, _marginCategory = 'Initial', isLp = false, enterHighLeverageMode = undefined) {
988
992
  const market = this.driftClient.getPerpMarketAccount(perpMarketIndex);
989
993
  const marketPrice = this.driftClient.getOracleDataForPerpMarket(perpMarketIndex).price;
990
994
  const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
@@ -1166,7 +1170,7 @@ class User {
1166
1170
  * @param offsetCollateral // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)
1167
1171
  * @returns Precision : PRICE_PRECISION
1168
1172
  */
1169
- liquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO, estimatedEntryPrice = numericConstants_1.ZERO, marginCategory = 'Maintenance', includeOpenOrders = false, offsetCollateral = numericConstants_1.ZERO, enteringHighLeverage = false) {
1173
+ liquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO, estimatedEntryPrice = numericConstants_1.ZERO, marginCategory = 'Maintenance', includeOpenOrders = false, offsetCollateral = numericConstants_1.ZERO, enteringHighLeverage = undefined) {
1170
1174
  const totalCollateral = this.getTotalCollateral(marginCategory, false, includeOpenOrders);
1171
1175
  const marginRequirement = this.getMarginRequirement(marginCategory, undefined, false, includeOpenOrders, enteringHighLeverage);
1172
1176
  let freeCollateral = anchor_1.BN.max(numericConstants_1.ZERO, totalCollateral.sub(marginRequirement)).add(offsetCollateral);
@@ -1211,7 +1215,7 @@ class User {
1211
1215
  }
1212
1216
  return liqPrice;
1213
1217
  }
1214
- calculateEntriesEffectOnFreeCollateral(market, oraclePrice, perpPosition, positionBaseSizeChange, estimatedEntryPrice, includeOpenOrders, enteringHighLeverage = false, marginCategory = 'Maintenance') {
1218
+ calculateEntriesEffectOnFreeCollateral(market, oraclePrice, perpPosition, positionBaseSizeChange, estimatedEntryPrice, includeOpenOrders, enteringHighLeverage = undefined, marginCategory = 'Maintenance') {
1215
1219
  let freeCollateralChange = numericConstants_1.ZERO;
1216
1220
  // update free collateral to account for change in pnl from new position
1217
1221
  if (!estimatedEntryPrice.eq(numericConstants_1.ZERO) &&
@@ -1248,7 +1252,10 @@ class User {
1248
1252
  baseAssetAmount = perpPosition.baseAssetAmount;
1249
1253
  liabilityValue = (0, margin_1.calculatePerpLiabilityValue)(baseAssetAmount, oraclePrice, (0, types_1.isVariant)(market.contractType, 'prediction'));
1250
1254
  }
1251
- const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, this.getUserAccount().maxMarginRatio, this.isHighLeverageMode(marginCategory) || enteringHighLeverage);
1255
+ const userCustomMargin = this.getUserAccount().maxMarginRatio;
1256
+ const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, enteringHighLeverage === false
1257
+ ? Math.max(market.marginRatioInitial, userCustomMargin)
1258
+ : userCustomMargin, this.isHighLeverageMode(marginCategory) || enteringHighLeverage === true);
1252
1259
  return liabilityValue.mul(new anchor_1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION);
1253
1260
  };
1254
1261
  const freeCollateralConsumptionBefore = calculateMarginRequirement(perpPosition);
@@ -1257,14 +1264,17 @@ class User {
1257
1264
  const freeCollateralConsumptionAfter = calculateMarginRequirement(perpPositionAfter);
1258
1265
  return freeCollateralChange.sub(freeCollateralConsumptionAfter.sub(freeCollateralConsumptionBefore));
1259
1266
  }
1260
- calculateFreeCollateralDeltaForPerp(market, perpPosition, positionBaseSizeChange, oraclePrice, marginCategory = 'Maintenance', includeOpenOrders = false, enteringHighLeverage = false) {
1267
+ calculateFreeCollateralDeltaForPerp(market, perpPosition, positionBaseSizeChange, oraclePrice, marginCategory = 'Maintenance', includeOpenOrders = false, enteringHighLeverage = undefined) {
1261
1268
  const baseAssetAmount = includeOpenOrders
1262
1269
  ? (0, margin_2.calculateWorstCaseBaseAssetAmount)(perpPosition, market, oraclePrice)
1263
1270
  : perpPosition.baseAssetAmount;
1264
1271
  // zero if include orders == false
1265
1272
  const orderBaseAssetAmount = baseAssetAmount.sub(perpPosition.baseAssetAmount);
1266
1273
  const proposedBaseAssetAmount = baseAssetAmount.add(positionBaseSizeChange);
1267
- const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, proposedBaseAssetAmount.abs(), marginCategory, this.getUserAccount().maxMarginRatio, this.isHighLeverageMode(marginCategory) || enteringHighLeverage);
1274
+ const userCustomMargin = this.getUserAccount().maxMarginRatio;
1275
+ const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, proposedBaseAssetAmount.abs(), marginCategory, enteringHighLeverage === false
1276
+ ? Math.max(market.marginRatioInitial, userCustomMargin)
1277
+ : userCustomMargin, this.isHighLeverageMode(marginCategory) || enteringHighLeverage === true);
1268
1278
  const marginRatioQuotePrecision = new anchor_1.BN(marginRatio)
1269
1279
  .mul(numericConstants_1.QUOTE_PRECISION)
1270
1280
  .div(numericConstants_1.MARGIN_PRECISION);
@@ -1353,7 +1363,7 @@ class User {
1353
1363
  * @param isLp
1354
1364
  * @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION
1355
1365
  */
1356
- getMaxTradeSizeUSDCForPerp(targetMarketIndex, tradeSide, isLp = false, enterHighLeverageMode = false) {
1366
+ getMaxTradeSizeUSDCForPerp(targetMarketIndex, tradeSide, isLp = false, enterHighLeverageMode = undefined) {
1357
1367
  let tradeSize = numericConstants_1.ZERO;
1358
1368
  let oppositeSideTradeSize = numericConstants_1.ZERO;
1359
1369
  const currentPosition = this.getPerpPositionWithLPSettle(targetMarketIndex, undefined, true)[0] ||
@@ -1772,7 +1782,7 @@ class User {
1772
1782
  }
1773
1783
  getUserFeeTier(marketType, now) {
1774
1784
  const state = this.driftClient.getStateAccount();
1775
- let feeTierIndex = 0;
1785
+ const feeTierIndex = 0;
1776
1786
  if ((0, types_1.isVariant)(marketType, 'perp')) {
1777
1787
  if (this.isHighLeverageMode('Initial')) {
1778
1788
  return state.perpFeeStructure.feeTiers[0];
@@ -1782,28 +1792,43 @@ class User {
1782
1792
  .getAccount();
1783
1793
  const total30dVolume = (0, trade_1.getUser30dRollingVolumeEstimate)(userStatsAccount, now);
1784
1794
  const stakedGovAssetAmount = userStatsAccount.ifStakedGovTokenAmount;
1785
- const volumeTiers = [
1786
- new anchor_1.BN(100000000).mul(numericConstants_1.QUOTE_PRECISION),
1787
- new anchor_1.BN(50000000).mul(numericConstants_1.QUOTE_PRECISION),
1795
+ const volumeThresholds = [
1796
+ new anchor_1.BN(2000000).mul(numericConstants_1.QUOTE_PRECISION),
1788
1797
  new anchor_1.BN(10000000).mul(numericConstants_1.QUOTE_PRECISION),
1789
- new anchor_1.BN(5000000).mul(numericConstants_1.QUOTE_PRECISION),
1790
- new anchor_1.BN(1000000).mul(numericConstants_1.QUOTE_PRECISION),
1798
+ new anchor_1.BN(20000000).mul(numericConstants_1.QUOTE_PRECISION),
1799
+ new anchor_1.BN(100000000).mul(numericConstants_1.QUOTE_PRECISION),
1800
+ new anchor_1.BN(200000000).mul(numericConstants_1.QUOTE_PRECISION),
1791
1801
  ];
1792
- const stakedTiers = [
1793
- new anchor_1.BN(120000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1794
- new anchor_1.BN(100000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1795
- new anchor_1.BN(25000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1796
- new anchor_1.BN(10000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1802
+ const stakeThresholds = [
1797
1803
  new anchor_1.BN(1000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1804
+ new anchor_1.BN(10000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1805
+ new anchor_1.BN(50000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1806
+ new anchor_1.BN(100000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
1807
+ new anchor_1.BN(250000 - 5).mul(numericConstants_1.QUOTE_PRECISION),
1798
1808
  ];
1799
- for (let i = 0; i < volumeTiers.length; i++) {
1800
- if (total30dVolume.gte(volumeTiers[i]) ||
1801
- stakedGovAssetAmount.gte(stakedTiers[i])) {
1802
- feeTierIndex = 5 - i;
1809
+ const stakeBenefitFrac = [0, 5, 10, 20, 30, 40];
1810
+ let feeTierIndex = 5;
1811
+ for (let i = 0; i < volumeThresholds.length; i++) {
1812
+ if (total30dVolume.lt(volumeThresholds[i])) {
1813
+ feeTierIndex = i;
1803
1814
  break;
1804
1815
  }
1805
1816
  }
1806
- return state.perpFeeStructure.feeTiers[feeTierIndex];
1817
+ let stakeBenefitIndex = 5;
1818
+ for (let i = 0; i < stakeThresholds.length; i++) {
1819
+ if (stakedGovAssetAmount.lt(stakeThresholds[i])) {
1820
+ stakeBenefitIndex = i;
1821
+ break;
1822
+ }
1823
+ }
1824
+ const stakeBenefit = stakeBenefitFrac[stakeBenefitIndex];
1825
+ const tier = { ...state.perpFeeStructure.feeTiers[feeTierIndex] };
1826
+ if (stakeBenefit > 0) {
1827
+ tier.feeNumerator = (tier.feeNumerator * (100 - stakeBenefit)) / 100;
1828
+ tier.makerRebateNumerator =
1829
+ (tier.makerRebateNumerator * (100 + stakeBenefit)) / 100;
1830
+ }
1831
+ return tier;
1807
1832
  }
1808
1833
  return state.spotFeeStructure.feeTiers[feeTierIndex];
1809
1834
  }
@@ -427,8 +427,25 @@ export declare class DriftClient {
427
427
  getCancelOrderIx(orderId?: number, subAccountId?: number): Promise<TransactionInstruction>;
428
428
  cancelOrderByUserId(userOrderId: number, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
429
429
  getCancelOrderByUserIdIx(userOrderId: number, subAccountId?: number): Promise<TransactionInstruction>;
430
- cancelOrdersByIds(orderIds?: number[], txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
431
- getCancelOrdersByIdsIx(orderIds?: number[], subAccountId?: number): Promise<TransactionInstruction>;
430
+ /**
431
+ * Sends a transaction to cancel the provided order ids.
432
+ *
433
+ * @param orderIds - The order ids to cancel.
434
+ * @param txParams - The transaction parameters.
435
+ * @param subAccountId - The sub account id to cancel the orders for.
436
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
437
+ * @returns The transaction signature.
438
+ */
439
+ cancelOrdersByIds(orderIds?: number[], txParams?: TxParams, subAccountId?: number, user?: User): Promise<TransactionSignature>;
440
+ /**
441
+ * Returns the transaction instruction to cancel the provided order ids.
442
+ *
443
+ * @param orderIds - The order ids to cancel.
444
+ * @param subAccountId - The sub account id to cancel the orders for.
445
+ * @param user - The user to cancel the orders for. If provided, it will be prioritized over the subAccountId.
446
+ * @returns The transaction instruction to cancel the orders.
447
+ */
448
+ getCancelOrdersByIdsIx(orderIds?: number[], subAccountId?: number, user?: User): Promise<TransactionInstruction>;
432
449
  cancelOrders(marketType?: MarketType, marketIndex?: number, direction?: PositionDirection, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
433
450
  getCancelOrdersIx(marketType: MarketType | null, marketIndex: number | null, direction: PositionDirection | null, subAccountId?: number): Promise<TransactionInstruction>;
434
451
  cancelAndPlaceOrders(cancelOrderParams: {
@@ -659,6 +676,12 @@ export declare class DriftClient {
659
676
  maxTs?: BN;
660
677
  policy?: number;
661
678
  }, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
679
+ /**
680
+ * @param orderParams: The parameters for the order to modify.
681
+ * @param subAccountId: Optional - The subaccount ID of the user to modify the order for.
682
+ * @param userPublicKey: Optional - The public key of the user to modify the order for. This takes precedence over subAccountId.
683
+ * @returns
684
+ */
662
685
  getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, bitFlags, maxTs, policy, }: {
663
686
  orderId: number;
664
687
  newDirection?: PositionDirection;
@@ -675,7 +698,7 @@ export declare class DriftClient {
675
698
  bitFlags?: number;
676
699
  maxTs?: BN;
677
700
  policy?: number;
678
- }, subAccountId?: number): Promise<TransactionInstruction>;
701
+ }, subAccountId?: number, userPublicKey?: PublicKey): Promise<TransactionInstruction>;
679
702
  /**
680
703
  * Modifies an open order by closing it and replacing it with a new order.
681
704
  * @param orderParams.userOrderId: The open order to modify