@drift-labs/sdk 0.2.0-master.36 → 0.2.0-master.37

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.
@@ -4,7 +4,7 @@ exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const types_1 = require("../types");
7
- const market_1 = require("./market");
7
+ const amm_1 = require("./amm");
8
8
  /**
9
9
  *
10
10
  * @param market
@@ -32,7 +32,8 @@ async function calculateAllEstimatedFundingRate(market, oraclePriceData, periodA
32
32
  const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
33
33
  const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
34
34
  const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
35
- const baseAssetPriceWithMantissa = (0, market_1.calculateReservePrice)(market, oraclePriceData);
35
+ const [bid, ask] = (0, amm_1.calculateBidAskPrice)(market.amm, oraclePriceData);
36
+ const baseAssetPriceWithMantissa = bid.add(ask).div(new anchor_1.BN(2));
36
37
  const markTwapWithMantissa = markTwapTimeSinceLastUpdate
37
38
  .mul(lastMarkTwapWithMantissa)
38
39
  .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
@@ -63,10 +63,10 @@ function calculateMarketMarginRatio(market, size, marginCategory) {
63
63
  let marginRatio;
64
64
  switch (marginCategory) {
65
65
  case 'Initial':
66
- marginRatio = (0, margin_1.calculateSizePremiumLiabilityWeight)(size, market.imfFactor, new anchor_1.BN(market.marginRatioInitial), numericConstants_1.MARGIN_PRECISION).toNumber();
66
+ marginRatio = (0, margin_1.calculateSizePremiumLiabilityWeight)(size, new anchor_1.BN(market.imfFactor), new anchor_1.BN(market.marginRatioInitial), numericConstants_1.MARGIN_PRECISION).toNumber();
67
67
  break;
68
68
  case 'Maintenance':
69
- marginRatio = (0, margin_1.calculateSizePremiumLiabilityWeight)(size, market.imfFactor, new anchor_1.BN(market.marginRatioMaintenance), numericConstants_1.MARGIN_PRECISION).toNumber();
69
+ marginRatio = (0, margin_1.calculateSizePremiumLiabilityWeight)(size, new anchor_1.BN(market.imfFactor), new anchor_1.BN(market.marginRatioMaintenance), numericConstants_1.MARGIN_PRECISION).toNumber();
70
70
  break;
71
71
  }
72
72
  return marginRatio;
@@ -85,7 +85,7 @@ function calculateUnrealizedAssetWeight(market, quoteSpotMarket, unrealizedPnl,
85
85
  .div(netUnsettledPnl);
86
86
  }
87
87
  }
88
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(unrealizedPnl, market.unrealizedPnlImfFactor, assetWeight);
88
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(unrealizedPnl, new anchor_1.BN(market.unrealizedPnlImfFactor), assetWeight);
89
89
  break;
90
90
  case 'Maintenance':
91
91
  assetWeight = new anchor_1.BN(market.unrealizedPnlMaintenanceAssetWeight);
@@ -103,9 +103,7 @@ function calculateNetUserPnl(perpMarket, oraclePriceData) {
103
103
  .mul(oraclePriceData.price)
104
104
  .div(numericConstants_1.BASE_PRECISION)
105
105
  .div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
106
- const netUserCostBasis = perpMarket.amm.quoteAssetAmountLong
107
- .add(perpMarket.amm.quoteAssetAmountShort)
108
- .sub(perpMarket.amm.cumulativeSocialLoss);
106
+ const netUserCostBasis = perpMarket.amm.quoteAssetAmount;
109
107
  const netUserPnl = netUserPositionValue.add(netUserCostBasis);
110
108
  return netUserPnl;
111
109
  }
@@ -33,7 +33,13 @@ export declare function positionIsAvailable(position: PerpPosition): boolean;
33
33
  /**
34
34
  *
35
35
  * @param userPosition
36
- * @returns Precision: PRICE_PRECISION (10^10)
36
+ * @returns Precision: PRICE_PRECISION (10^6)
37
+ */
38
+ export declare function calculateBreakEvenPrice(userPosition: PerpPosition): BN;
39
+ /**
40
+ *
41
+ * @param userPosition
42
+ * @returns Precision: PRICE_PRECISION (10^6)
37
43
  */
38
44
  export declare function calculateEntryPrice(userPosition: PerpPosition): BN;
39
45
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateCostBasis = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculateClaimablePnl = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateCostBasis = exports.calculateEntryPrice = exports.calculateBreakEvenPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculateClaimablePnl = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
4
  const __1 = require("../");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  const types_1 = require("../types");
@@ -131,7 +131,23 @@ exports.positionIsAvailable = positionIsAvailable;
131
131
  /**
132
132
  *
133
133
  * @param userPosition
134
- * @returns Precision: PRICE_PRECISION (10^10)
134
+ * @returns Precision: PRICE_PRECISION (10^6)
135
+ */
136
+ function calculateBreakEvenPrice(userPosition) {
137
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
138
+ return numericConstants_1.ZERO;
139
+ }
140
+ return userPosition.quoteBreakEvenAmount
141
+ .mul(numericConstants_1.PRICE_PRECISION)
142
+ .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
143
+ .div(userPosition.baseAssetAmount)
144
+ .abs();
145
+ }
146
+ exports.calculateBreakEvenPrice = calculateBreakEvenPrice;
147
+ /**
148
+ *
149
+ * @param userPosition
150
+ * @returns Precision: PRICE_PRECISION (10^6)
135
151
  */
136
152
  function calculateEntryPrice(userPosition) {
137
153
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
@@ -56,13 +56,13 @@ function calculateAssetWeight(balanceAmount, spotMarket, marginCategory) {
56
56
  let assetWeight;
57
57
  switch (marginCategory) {
58
58
  case 'Initial':
59
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialAssetWeight);
59
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, new anchor_1.BN(spotMarket.imfFactor), new anchor_1.BN(spotMarket.initialAssetWeight));
60
60
  break;
61
61
  case 'Maintenance':
62
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceAssetWeight);
62
+ assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, new anchor_1.BN(spotMarket.imfFactor), new anchor_1.BN(spotMarket.maintenanceAssetWeight));
63
63
  break;
64
64
  default:
65
- assetWeight = spotMarket.initialAssetWeight;
65
+ assetWeight = new anchor_1.BN(spotMarket.initialAssetWeight);
66
66
  break;
67
67
  }
68
68
  return assetWeight;
@@ -82,10 +82,10 @@ function calculateLiabilityWeight(balanceAmount, spotMarket, marginCategory) {
82
82
  let assetWeight;
83
83
  switch (marginCategory) {
84
84
  case 'Initial':
85
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.initialLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
85
+ assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, new anchor_1.BN(spotMarket.imfFactor), new anchor_1.BN(spotMarket.initialLiabilityWeight), numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
86
86
  break;
87
87
  case 'Maintenance':
88
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, spotMarket.imfFactor, spotMarket.maintenanceLiabilityWeight, numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
88
+ assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, new anchor_1.BN(spotMarket.imfFactor), new anchor_1.BN(spotMarket.maintenanceLiabilityWeight), numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
89
89
  break;
90
90
  default:
91
91
  assetWeight = spotMarket.initialLiabilityWeight;
package/lib/types.d.ts CHANGED
@@ -517,15 +517,16 @@ export declare type PerpMarketAccount = {
517
517
  pubkey: PublicKey;
518
518
  name: number[];
519
519
  amm: AMM;
520
- numberOfUsers: BN;
520
+ numberOfUsersWithBase: number;
521
+ numberOfUsers: number;
521
522
  marginRatioInitial: number;
522
523
  marginRatioMaintenance: number;
523
524
  nextFillRecordId: BN;
524
525
  pnlPool: PoolBalance;
525
- liquidatorFee: BN;
526
- ifLiquidationFee: BN;
527
- imfFactor: BN;
528
- unrealizedPnlImfFactor: BN;
526
+ liquidatorFee: number;
527
+ ifLiquidationFee: number;
528
+ imfFactor: number;
529
+ unrealizedPnlImfFactor: number;
529
530
  unrealizedPnlMaxImbalance: BN;
530
531
  unrealizedPnlInitialAssetWeight: number;
531
532
  unrealizedPnlMaintenanceAssetWeight: number;
@@ -575,7 +576,7 @@ export declare type SpotMarketAccount = {
575
576
  userFactor: number;
576
577
  };
577
578
  revenuePool: PoolBalance;
578
- ifLiquidationFee: BN;
579
+ ifLiquidationFee: number;
579
580
  decimals: number;
580
581
  optimalUtilization: number;
581
582
  optimalBorrowRate: number;
@@ -587,12 +588,12 @@ export declare type SpotMarketAccount = {
587
588
  maxTokenDeposits: BN;
588
589
  lastInterestTs: BN;
589
590
  lastTwapTs: BN;
590
- initialAssetWeight: BN;
591
- maintenanceAssetWeight: BN;
592
- initialLiabilityWeight: BN;
593
- maintenanceLiabilityWeight: BN;
594
- liquidatorFee: BN;
595
- imfFactor: BN;
591
+ initialAssetWeight: number;
592
+ maintenanceAssetWeight: number;
593
+ initialLiabilityWeight: number;
594
+ maintenanceLiabilityWeight: number;
595
+ liquidatorFee: number;
596
+ imfFactor: number;
596
597
  withdrawGuardThreshold: BN;
597
598
  depositTokenTwap: BN;
598
599
  borrowTokenTwap: BN;
@@ -641,8 +642,7 @@ export declare type AMM = {
641
642
  baseAssetAmountWithAmm: BN;
642
643
  baseAssetAmountLong: BN;
643
644
  baseAssetAmountShort: BN;
644
- quoteAssetAmountLong: BN;
645
- quoteAssetAmountShort: BN;
645
+ quoteAssetAmount: BN;
646
646
  terminalQuoteAssetReserve: BN;
647
647
  feePool: PoolBalance;
648
648
  totalExchangeFee: BN;
@@ -652,8 +652,8 @@ export declare type AMM = {
652
652
  lastOracleValid: boolean;
653
653
  lastBidPriceTwap: BN;
654
654
  lastAskPriceTwap: BN;
655
- longSpread: BN;
656
- shortSpread: BN;
655
+ longSpread: number;
656
+ shortSpread: number;
657
657
  maxSpread: number;
658
658
  baseAssetAmountPerLp: BN;
659
659
  quoteAssetAmountPerLp: BN;
@@ -668,6 +668,7 @@ export declare type PerpPosition = {
668
668
  marketIndex: number;
669
669
  quoteAssetAmount: BN;
670
670
  quoteEntryAmount: BN;
671
+ quoteBreakEvenAmount: BN;
671
672
  openOrders: number;
672
673
  openBids: BN;
673
674
  openAsks: BN;
@@ -679,6 +680,7 @@ export declare type PerpPosition = {
679
680
  };
680
681
  export declare type UserStatsAccount = {
681
682
  numberOfSubAccounts: number;
683
+ maxSubAccountId: number;
682
684
  makerVolume30D: BN;
683
685
  takerVolume30D: BN;
684
686
  fillerVolume30D: BN;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.2.0-master.36",
3
+ "version": "0.2.0-master.37",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -26,7 +26,7 @@ export async function getUserAccountPublicKeyAndNonce(
26
26
  [
27
27
  Buffer.from(anchor.utils.bytes.utf8.encode('user')),
28
28
  authority.toBuffer(),
29
- Uint8Array.from([subAccountId]),
29
+ new anchor.BN(subAccountId).toArrayLike(Buffer, 'le', 2),
30
30
  ],
31
31
  programId
32
32
  );
@@ -51,7 +51,7 @@ export function getUserAccountPublicKeySync(
51
51
  [
52
52
  Buffer.from(anchor.utils.bytes.utf8.encode('user')),
53
53
  authority.toBuffer(),
54
- Uint8Array.from([subAccountId]),
54
+ new anchor.BN(subAccountId).toArrayLike(Buffer, 'le', 2),
55
55
  ],
56
56
  programId
57
57
  )[0];
package/src/admin.ts CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  import { squareRootBN } from './math/utils';
28
28
  import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
29
29
  import { ClearingHouse } from './clearingHouse';
30
- import { PEG_PRECISION, ZERO } from './constants/numericConstants';
30
+ import { PEG_PRECISION } from './constants/numericConstants';
31
31
  import { calculateTargetPriceTrade } from './math/trade';
32
32
  import { calculateAmmReservesAfterSwap, getSwapDirection } from './math/amm';
33
33
 
@@ -76,12 +76,12 @@ export class Admin extends ClearingHouse {
76
76
  maxRate: number,
77
77
  oracle: PublicKey,
78
78
  oracleSource: OracleSource,
79
- initialAssetWeight: BN,
80
- maintenanceAssetWeight: BN,
81
- initialLiabilityWeight: BN,
82
- maintenanceLiabilityWeight: BN,
83
- imfFactor = new BN(0),
84
- liquidationFee = ZERO,
79
+ initialAssetWeight: number,
80
+ maintenanceAssetWeight: number,
81
+ initialLiabilityWeight: number,
82
+ maintenanceLiabilityWeight: number,
83
+ imfFactor = 0,
84
+ liquidationFee = 0,
85
85
  activeStatus = true
86
86
  ): Promise<TransactionSignature> {
87
87
  const spotMarketIndex = this.getStateAccount().numberOfSpotMarkets;
@@ -184,7 +184,7 @@ export class Admin extends ClearingHouse {
184
184
  oracleSource: OracleSource = OracleSource.PYTH,
185
185
  marginRatioInitial = 2000,
186
186
  marginRatioMaintenance = 500,
187
- liquidationFee = ZERO,
187
+ liquidationFee = 0,
188
188
  activeStatus = true,
189
189
  name = DEFAULT_MARKET_NAME
190
190
  ): Promise<TransactionSignature> {
@@ -827,11 +827,11 @@ export class Admin extends ClearingHouse {
827
827
 
828
828
  public async updateSpotMarketMarginWeights(
829
829
  spotMarketIndex: number,
830
- initialAssetWeight: BN,
831
- maintenanceAssetWeight: BN,
832
- initialLiabilityWeight: BN,
833
- maintenanceLiabilityWeight: BN,
834
- imfFactor = new BN(0)
830
+ initialAssetWeight: number,
831
+ maintenanceAssetWeight: number,
832
+ initialLiabilityWeight: number,
833
+ maintenanceLiabilityWeight: number,
834
+ imfFactor = 0
835
835
  ): Promise<TransactionSignature> {
836
836
  return await this.program.rpc.updateSpotMarketMarginWeights(
837
837
  initialAssetWeight,