flash-sdk 10.5.1 → 10.5.2-alpha.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.
@@ -20,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
20
20
  });
21
21
  };
22
22
  var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
25
  function verb(n) { return function (v) { return step([n, v]); }; }
26
26
  function step(op) {
27
27
  if (f) throw new TypeError("Generator is already executing.");
@@ -91,31 +91,35 @@ var PerpetualsClient = (function () {
91
91
  _this.prioritizationFee = fee;
92
92
  };
93
93
  this.loadAddressLookupTable = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
94
- var addresses, _i, _a, address, addressLookupTable, accCreationLamports;
95
- return __generator(this, function (_b) {
96
- switch (_b.label) {
94
+ var addresses, _i, _a, address, addressLookupTable, _b, accCreationLamports;
95
+ return __generator(this, function (_c) {
96
+ switch (_c.label) {
97
97
  case 0:
98
98
  addresses = [];
99
99
  _i = 0, _a = poolConfig.addressLookupTableAddresses;
100
- _b.label = 1;
100
+ _c.label = 1;
101
101
  case 1:
102
102
  if (!(_i < _a.length)) return [3, 4];
103
103
  address = _a[_i];
104
104
  return [4, this.provider.connection.getAddressLookupTable(address)];
105
105
  case 2:
106
- addressLookupTable = (_b.sent()).value;
106
+ addressLookupTable = (_c.sent()).value;
107
107
  if (addressLookupTable) {
108
108
  addresses.push(addressLookupTable);
109
109
  }
110
- _b.label = 3;
110
+ _c.label = 3;
111
111
  case 3:
112
112
  _i++;
113
113
  return [3, 1];
114
114
  case 4:
115
115
  this.addressLookupTables = addresses;
116
- return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
116
+ _b = this;
117
+ return [4, this.provider.connection.getAddressLookupTable(poolConfig.pusherAddressLookupTableAddress)];
117
118
  case 5:
118
- accCreationLamports = (_b.sent());
119
+ _b.pusherAddressLookupTables = (_c.sent()).value;
120
+ return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
121
+ case 6:
122
+ accCreationLamports = (_c.sent());
119
123
  if (accCreationLamports) {
120
124
  this.minimumBalanceForRentExemptAccountLamports = accCreationLamports;
121
125
  }
@@ -638,24 +642,41 @@ var PerpetualsClient = (function () {
638
642
  var averageEntryPrice = totalValue.div(totalSize);
639
643
  return averageEntryPrice;
640
644
  };
641
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
642
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
643
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
644
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
645
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
645
+ this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
646
+ var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
647
+ var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
648
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
649
+ var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
650
+ var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
651
+ var currentMarginUsd = constants_1.BN_ZERO;
652
+ if (isInitial) {
653
+ currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
654
+ }
655
+ else {
656
+ currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
657
+ }
658
+ if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
659
+ return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
646
660
  }
647
661
  else {
648
662
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
649
663
  }
650
664
  };
651
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
665
+ this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
666
+ positionAccount = positionAccount.clone();
667
+ positionAccount.sizeUsd = finalSizeUsd;
668
+ positionAccount.collateralUsd = finalCollateralUsd;
669
+ return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
670
+ };
671
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd, enableDebuglogs) {
672
+ if (enableDebuglogs === void 0) { enableDebuglogs = false; }
652
673
  var finalCollateralAmount = constants_1.BN_ZERO;
653
674
  if (!inputDeltaAmount.isZero()) {
654
675
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
655
676
  finalCollateralAmount = inputDeltaAmount;
656
677
  }
657
678
  else {
658
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
679
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
659
680
  finalCollateralAmount = swapAmountOut;
660
681
  }
661
682
  }
@@ -681,11 +702,13 @@ var PerpetualsClient = (function () {
681
702
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
682
703
  }
683
704
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
684
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
685
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
686
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
705
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals).add(positionAccount.collateralUsd);
706
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
687
707
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
688
708
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
709
+ if (enableDebuglogs) {
710
+ console.log("SDK logs : finalCollateralUsd:", finalCollateralUsd.toString(), "finalCollateralAmount:", finalCollateralAmount.toString(), "sizeAmount:", sizeAmount.toString(), "sizeAmountUsd:", sizeAmountUsd.toString(), "sizeDeltaAmount:", sizeDeltaAmount.toString(), "sizeUsd:", sizeUsd.toString(), "currentCollateralUsdIncludingPnl:", currentCollateralUsdIncludingPnl.toString(), "finalCollateralUsd :", finalCollateralUsd.toString(), "pnlUsd :", pnlUsd.toString());
711
+ }
689
712
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
690
713
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
691
714
  }
@@ -693,81 +716,20 @@ var PerpetualsClient = (function () {
693
716
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
694
717
  }
695
718
  };
696
- this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
697
- if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
698
- if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
699
- throw new Error("Delta Amounts cannot be negative.");
700
- }
701
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
702
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
703
- if (positionAccount === null) {
704
- var data = __assign({}, types_1.DEFAULT_POSITION);
705
- positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
706
- var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
707
- positionAccount.sizeUsd = sizeUsd_1;
708
- positionAccount.sizeDecimals = targetCustodyAccount.decimals;
709
- positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
710
- positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
711
- }
712
- else {
713
- positionAccount = positionAccount.clone();
714
- var positionEntryPrice = OraclePrice_1.OraclePrice.from({
715
- price: positionAccount.entryPrice.price,
716
- exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
717
- confidence: constants_1.BN_ZERO,
718
- timestamp: constants_1.BN_ZERO
719
- });
720
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
721
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
722
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
723
- }
724
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
725
- positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
726
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
727
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
728
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
729
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
730
- var feeUsd = constants_1.BN_ZERO;
731
- var feeAmount = constants_1.BN_ZERO;
732
- var feeUsdAfterDiscount = constants_1.BN_ZERO;
733
- var feeAmountAfterDiscount = constants_1.BN_ZERO;
734
- if (positionAccount !== null && sizeDeltaAmount.isZero()) {
735
- }
736
- else {
737
- feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
738
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
739
- if (discountBps.gt(constants_1.BN_ZERO)) {
740
- feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
741
- feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
742
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
- }
744
- else {
745
- feeUsdAfterDiscount = feeUsd;
746
- feeAmountAfterDiscount = feeAmount;
747
- }
748
- }
749
- return {
750
- entryOraclePrice: entryOraclePrice,
751
- feeUsd: feeUsd,
752
- feeAmount: feeAmount,
753
- feeUsdAfterDiscount: feeUsdAfterDiscount,
754
- feeAmountAfterDiscount: feeAmountAfterDiscount,
755
- liquidationPrice: liquidationPrice
756
- };
757
- };
758
719
  this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
759
720
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
760
721
  if (enableLogs === void 0) { enableLogs = false; }
761
722
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
762
723
  throw new Error("Delta Amounts cannot be negative.");
763
724
  }
764
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
765
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
725
+ var sizeDeltaUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
726
+ var entryDeltaOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeDeltaUsd);
727
+ var lockAndUnsettledFeeUsd = constants_1.BN_ZERO;
766
728
  if (positionAccount === null) {
767
729
  var data = __assign({}, types_1.DEFAULT_POSITION);
768
730
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
769
- var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
770
- positionAccount.sizeUsd = sizeUsd_2;
731
+ var sizeUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
732
+ positionAccount.sizeUsd = sizeUsd;
771
733
  positionAccount.sizeDecimals = targetCustodyAccount.decimals;
772
734
  positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
773
735
  positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
@@ -780,16 +742,17 @@ var PerpetualsClient = (function () {
780
742
  confidence: constants_1.BN_ZERO,
781
743
  timestamp: constants_1.BN_ZERO
782
744
  });
783
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
784
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
785
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
745
+ lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
746
+ entryDeltaOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryDeltaOraclePrice.price, sizeDeltaAmount);
747
+ var sizeDeltaUsd_1 = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
748
+ positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd_1);
786
749
  }
787
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
750
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
751
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
752
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
788
753
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
789
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
790
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
791
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
792
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
754
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryDeltaOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
755
+ var sizeAmountUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
793
756
  var feeUsd = constants_1.BN_ZERO;
794
757
  var feeAmount = constants_1.BN_ZERO;
795
758
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -798,11 +761,11 @@ var PerpetualsClient = (function () {
798
761
  }
799
762
  else {
800
763
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
801
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
764
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
802
765
  if (discountBps.gt(constants_1.BN_ZERO)) {
803
766
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
804
767
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
805
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
768
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
806
769
  }
807
770
  else {
808
771
  feeUsdAfterDiscount = feeUsd;
@@ -822,7 +785,7 @@ var PerpetualsClient = (function () {
822
785
  console.log("volitlity fee zero:", "divergenceBps", divergenceBps.toString(), "maxDivergenceBps", targetCustodyAccount.oracle.maxDivergenceBps.toString());
823
786
  }
824
787
  return {
825
- entryOraclePrice: entryOraclePrice,
788
+ entryOraclePrice: entryDeltaOraclePrice,
826
789
  feeUsd: feeUsd,
827
790
  feeAmount: feeAmount,
828
791
  vbFeeUsd: vbFeeUsd,
@@ -861,25 +824,26 @@ var PerpetualsClient = (function () {
861
824
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
862
825
  throw new Error("Delta Amounts cannot be negative ");
863
826
  }
864
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
865
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
866
827
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
867
828
  throw new Error("cannot remove/close more than collateral/Size");
868
829
  }
869
830
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
870
831
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
871
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
832
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
833
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
834
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
835
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
872
836
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
873
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
837
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
874
838
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
875
839
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
876
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
840
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
877
841
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
878
842
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
879
843
  if (discountBps.gt(constants_1.BN_ZERO)) {
880
844
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
881
845
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
882
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
846
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
883
847
  }
884
848
  else {
885
849
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -889,7 +853,7 @@ var PerpetualsClient = (function () {
889
853
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
890
854
  });
891
855
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
892
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
856
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
893
857
  return {
894
858
  exitOraclePrice: exitOraclePrice,
895
859
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -902,13 +866,11 @@ var PerpetualsClient = (function () {
902
866
  };
903
867
  };
904
868
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
905
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
906
- ||
907
- sizeUsd.isZero()) {
869
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
908
870
  return constants_1.BN_ZERO;
909
871
  }
910
872
  var slope = ((targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin)).mul(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))))
911
- .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
873
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
912
874
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
913
875
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
914
876
  return finalSpread;
@@ -923,21 +885,11 @@ var PerpetualsClient = (function () {
923
885
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
924
886
  return exitOraclePrice;
925
887
  };
926
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
927
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
928
- if ((0, types_1.isVariant)(side, 'long')) {
929
- return minPrice;
930
- }
931
- else {
932
- return maxPrice;
933
- }
934
- };
935
888
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
936
889
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
937
890
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
938
891
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
939
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
940
- .multipliedBy(collateralTokenMinPriceUi);
892
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
941
893
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
942
894
  if (!discountBps.isZero()) {
943
895
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -945,20 +897,20 @@ var PerpetualsClient = (function () {
945
897
  }
946
898
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
947
899
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
948
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
949
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
900
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
901
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
950
902
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
951
903
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
952
904
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
953
905
  };
954
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
906
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
955
907
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
956
908
  var finalCollateralAmount = constants_1.BN_ZERO;
957
909
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
958
910
  finalCollateralAmount = amountIn;
959
911
  }
960
912
  else {
961
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
913
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
962
914
  finalCollateralAmount = swapAmountOut;
963
915
  }
964
916
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -972,8 +924,8 @@ var PerpetualsClient = (function () {
972
924
  }
973
925
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
974
926
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
975
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
976
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
927
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
928
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
977
929
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
978
930
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
979
931
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -996,7 +948,7 @@ var PerpetualsClient = (function () {
996
948
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
997
949
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
998
950
  };
999
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
951
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1000
952
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1001
953
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1002
954
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -1013,11 +965,11 @@ var PerpetualsClient = (function () {
1013
965
  collateralInInputToken = collateralAmountWithFee;
1014
966
  }
1015
967
  else {
1016
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
968
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1017
969
  }
1018
970
  return collateralInInputToken;
1019
971
  };
1020
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
972
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1021
973
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1022
974
  if (debugLogs === void 0) { debugLogs = false; }
1023
975
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -1039,10 +991,9 @@ var PerpetualsClient = (function () {
1039
991
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1040
992
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1041
993
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1042
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1043
994
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1044
- positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1045
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
995
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
996
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1046
997
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
1047
998
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1048
999
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1052,30 +1003,37 @@ var PerpetualsClient = (function () {
1052
1003
  }
1053
1004
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1054
1005
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1055
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1006
+ var currentCollateralUsd = positionDelta.collateralUsd;
1056
1007
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1057
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1058
- var closeAmount, feesAmount;
1008
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1059
1009
  if (debugLogs) {
1060
1010
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1061
1011
  }
1012
+ var closeAmountUsd, feesAmountUsd;
1062
1013
  if (assetsUsd.gte(liabilityUsd)) {
1063
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1064
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1014
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1015
+ feesAmountUsd = totalFeesUsd;
1016
+ }
1017
+ else {
1018
+ closeAmountUsd = constants_1.BN_ZERO;
1019
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1020
+ }
1021
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1022
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1023
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1024
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
1065
1025
  }
1066
1026
  else {
1067
- closeAmount = constants_1.BN_ZERO;
1068
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1027
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1069
1028
  }
1070
1029
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1071
1030
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1072
1031
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1073
- newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1074
1032
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1075
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1033
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1076
1034
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1077
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1078
1035
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1036
+ newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
1079
1037
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1080
1038
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1081
1039
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1089,29 +1047,30 @@ var PerpetualsClient = (function () {
1089
1047
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1090
1048
  if (keepLevSame) {
1091
1049
  var collateralAmountReceived = closeAmount;
1092
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1093
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1050
+ var collateralAmountReceivedUsd = closeAmountUsd;
1051
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1094
1052
  if (debugLogs) {
1095
1053
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1096
1054
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1097
1055
  }
1098
- if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1056
+ if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1099
1057
  collateralAmountReceived = constants_1.BN_ZERO;
1100
- collateralAmountRecievedUsd = constants_1.BN_ZERO;
1058
+ collateralAmountReceivedUsd = constants_1.BN_ZERO;
1101
1059
  }
1102
- else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1060
+ else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1103
1061
  if (debugLogs) {
1104
1062
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1105
1063
  }
1106
1064
  collateralAmountReceived = maxWithdrawableAmount;
1107
- collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1065
+ collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1108
1066
  }
1109
1067
  var entryPrice = OraclePrice_1.OraclePrice.from({ price: newPosition.entryPrice.price, exponent: new anchor_1.BN(newPosition.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1110
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1111
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1068
+ newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1069
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1070
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1112
1071
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1113
1072
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1114
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1073
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1115
1074
  return {
1116
1075
  newSizeUsd: newPosition.sizeUsd,
1117
1076
  feeUsd: feeUsd,
@@ -1119,8 +1078,9 @@ var PerpetualsClient = (function () {
1119
1078
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1120
1079
  newLev: newLev,
1121
1080
  liquidationPrice: finalLiquidationPrice,
1122
- collateralAmountRecieved: collateralAmountReceived,
1123
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1081
+ collateralAmountReceived: collateralAmountReceived,
1082
+ collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1083
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1124
1084
  newPnl: finalPnlUsd
1125
1085
  };
1126
1086
  }
@@ -1128,8 +1088,7 @@ var PerpetualsClient = (function () {
1128
1088
  throw "only same leverage is supported for now";
1129
1089
  }
1130
1090
  };
1131
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1132
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1091
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1133
1092
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1134
1093
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1135
1094
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1138,61 +1097,87 @@ var PerpetualsClient = (function () {
1138
1097
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1139
1098
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1140
1099
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1141
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1100
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1142
1101
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1143
1102
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1144
1103
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1145
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1146
1104
  var availableInitMarginUsd = constants_1.BN_ZERO;
1147
- if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1148
- availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1105
+ if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1106
+ availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1149
1107
  }
1150
1108
  else {
1151
1109
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1152
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1110
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1153
1111
  }
1154
1112
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1155
1113
  if (maxRemovableCollateralUsd.isNeg()) {
1156
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1114
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1157
1115
  }
1158
1116
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1159
- var diff = constants_1.BN_ZERO;
1117
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1118
+ var diffUsd = constants_1.BN_ZERO;
1160
1119
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1161
1120
  var isDegenMode = positionAccount.isDegenMode();
1162
1121
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1163
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1164
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1122
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1123
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1165
1124
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1166
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1125
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1167
1126
  }
1168
1127
  else {
1169
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1128
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1129
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1170
1130
  }
1171
1131
  }
1172
1132
  else {
1173
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1133
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1134
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1174
1135
  }
1175
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1136
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1176
1137
  };
1177
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1138
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1178
1139
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1179
1140
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1180
- var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1181
1141
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1182
1142
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1183
1143
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1184
1144
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1185
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1186
- var closeAmount, feesAmount;
1145
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1146
+ var closeAmountUsd, feesAmountUsd;
1187
1147
  if (assetsUsd.gt(liabilityUsd)) {
1188
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1189
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1148
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1149
+ feesAmountUsd = totalFeesUsd;
1190
1150
  }
1191
1151
  else {
1192
- closeAmount = constants_1.BN_ZERO;
1193
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1152
+ closeAmountUsd = constants_1.BN_ZERO;
1153
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1194
1154
  }
1195
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1155
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1156
+ };
1157
+ this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1158
+ if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1159
+ if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1160
+ throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1161
+ }
1162
+ var rawMinInitLev = positionAccount.isDegenMode()
1163
+ ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1164
+ : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1165
+ var MIN_INIT_LEVERAGE = rawMinInitLev
1166
+ .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1167
+ .div(new anchor_1.BN(100));
1168
+ var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1169
+ .muln(constants_1.BPS_POWER)
1170
+ .div(MIN_INIT_LEVERAGE);
1171
+ var currentCollateralUsd = positionAccount.collateralUsd;
1172
+ var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1173
+ ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1174
+ : constants_1.BN_ZERO;
1175
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1176
+ var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1177
+ return {
1178
+ maxAddableAmount: maxAddableAmount,
1179
+ maxAddableAmountUsd: maxAddableCollateralUsd,
1180
+ };
1196
1181
  };
1197
1182
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1198
1183
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1205,34 +1190,37 @@ var PerpetualsClient = (function () {
1205
1190
  var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub((positionAccount.isDegenMode() ? new anchor_1.BN(targetCustodyAccount.pricing.minDegenCollateralUsd) : new anchor_1.BN(targetCustodyAccount.pricing.minCollateralUsd)).mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1206
1191
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1207
1192
  console.log("THIS cannot happen but still");
1208
- return constants_1.BN_ZERO;
1193
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1209
1194
  }
1210
1195
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1211
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1196
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1212
1197
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1213
1198
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1214
1199
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1215
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1200
+ var currentCollateralUsd = positionAccount.collateralUsd;
1216
1201
  var availableInitMarginUsd = constants_1.BN_ZERO;
1217
1202
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1218
1203
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1219
1204
  }
1220
1205
  else {
1221
1206
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1222
- return constants_1.BN_ZERO;
1207
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1223
1208
  }
1224
1209
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1225
1210
  if (maxRemovableCollateralUsd.isNeg()) {
1226
- return constants_1.BN_ZERO;
1211
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1227
1212
  }
1228
1213
  var maxWithdrawableAmount;
1214
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1229
1215
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1230
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1216
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1217
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1231
1218
  }
1232
1219
  else {
1233
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1220
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1221
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1234
1222
  }
1235
- return maxWithdrawableAmount;
1223
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1236
1224
  };
1237
1225
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1238
1226
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1270,12 +1258,12 @@ var PerpetualsClient = (function () {
1270
1258
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1271
1259
  var lockFeeUsd = constants_1.BN_ZERO;
1272
1260
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1273
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1261
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1274
1262
  }
1275
1263
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1276
1264
  return lockFeeUsd;
1277
1265
  };
1278
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1266
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1279
1267
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1280
1268
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1281
1269
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1283,193 +1271,144 @@ var PerpetualsClient = (function () {
1283
1271
  else {
1284
1272
  maxPayOffBpsNew = maxPayOffBps;
1285
1273
  }
1286
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1274
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1287
1275
  return lockedUsd;
1288
1276
  };
1289
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1277
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1290
1278
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1291
1279
  price: constants_1.BN_ZERO,
1292
1280
  exponent: constants_1.BN_ZERO,
1293
1281
  confidence: constants_1.BN_ZERO,
1294
1282
  timestamp: constants_1.BN_ZERO
1295
1283
  });
1296
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1297
- return zeroOraclePrice;
1298
- }
1299
1284
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1300
1285
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1301
1286
  }
1302
1287
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1303
1288
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1304
1289
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1305
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1306
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1307
1290
  var liquidationPrice;
1308
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1309
- var newCollateralAmount = void 0;
1310
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1311
- newCollateralAmount = collateralAmount;
1291
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1292
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1293
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1294
+ .div(positionAccount.sizeAmount),
1295
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1296
+ confidence: constants_1.BN_ZERO,
1297
+ timestamp: constants_1.BN_ZERO
1298
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1299
+ if ((0, types_1.isVariant)(side, 'long')) {
1300
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1301
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1302
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1303
+ confidence: constants_1.BN_ZERO,
1304
+ timestamp: constants_1.BN_ZERO
1305
+ });
1312
1306
  }
1313
1307
  else {
1314
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1315
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1316
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1308
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1309
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1310
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1311
+ confidence: constants_1.BN_ZERO,
1312
+ timestamp: constants_1.BN_ZERO
1313
+ });
1317
1314
  }
1318
- var lp = OraclePrice_1.OraclePrice.from({
1319
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1320
- .div(sizeAmount.add(newCollateralAmount)),
1315
+ }
1316
+ else {
1317
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1318
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1319
+ .div(positionAccount.sizeAmount),
1321
1320
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1322
1321
  confidence: constants_1.BN_ZERO,
1323
1322
  timestamp: constants_1.BN_ZERO
1324
- });
1325
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1326
- }
1327
- else {
1328
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1329
- if (assetsUsd.gte(liablitiesUsd)) {
1330
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1331
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1332
- .div(positionAccount.sizeAmount),
1333
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1323
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1324
+ if ((0, types_1.isVariant)(side, 'long')) {
1325
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1326
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1327
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1334
1328
  confidence: constants_1.BN_ZERO,
1335
1329
  timestamp: constants_1.BN_ZERO
1336
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1337
- if ((0, types_1.isVariant)(side, 'long')) {
1338
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1339
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1340
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1341
- confidence: constants_1.BN_ZERO,
1342
- timestamp: constants_1.BN_ZERO
1343
- });
1344
- }
1345
- else {
1346
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1347
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1348
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1349
- confidence: constants_1.BN_ZERO,
1350
- timestamp: constants_1.BN_ZERO
1351
- });
1352
- }
1330
+ });
1353
1331
  }
1354
1332
  else {
1355
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1356
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1357
- .div(positionAccount.sizeAmount),
1358
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1333
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1334
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1335
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1359
1336
  confidence: constants_1.BN_ZERO,
1360
1337
  timestamp: constants_1.BN_ZERO
1361
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1362
- if ((0, types_1.isVariant)(side, 'long')) {
1363
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1364
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1365
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1366
- confidence: constants_1.BN_ZERO,
1367
- timestamp: constants_1.BN_ZERO
1368
- });
1369
- }
1370
- else {
1371
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1373
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1374
- confidence: constants_1.BN_ZERO,
1375
- timestamp: constants_1.BN_ZERO
1376
- });
1377
- }
1338
+ });
1378
1339
  }
1379
1340
  }
1380
1341
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1381
1342
  };
1382
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1343
+ this.getLiquidationPriceSync = function (collateralUsd, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1344
+ var newPositionAccount = positionAccount.clone();
1345
+ newPositionAccount.collateralUsd = collateralUsd;
1346
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1347
+ };
1348
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1383
1349
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1384
1350
  price: constants_1.BN_ZERO,
1385
1351
  exponent: constants_1.BN_ZERO,
1386
1352
  confidence: constants_1.BN_ZERO,
1387
1353
  timestamp: constants_1.BN_ZERO
1388
1354
  });
1389
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1390
- return zeroOraclePrice;
1391
- }
1392
1355
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1393
1356
  var unsettledLossUsd = exitFeeUsd;
1394
1357
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1395
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1396
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1397
1358
  var liquidationPrice;
1398
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1399
- var newCollateralAmount = void 0;
1400
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1401
- newCollateralAmount = collateralAmount;
1359
+ if (collateralUsd.gte(liablitiesUsd)) {
1360
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1361
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1362
+ .div(sizeAmount),
1363
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1364
+ confidence: constants_1.BN_ZERO,
1365
+ timestamp: constants_1.BN_ZERO
1366
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1367
+ if ((0, types_1.isVariant)(side, 'long')) {
1368
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1369
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1370
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1371
+ confidence: constants_1.BN_ZERO,
1372
+ timestamp: constants_1.BN_ZERO
1373
+ });
1402
1374
  }
1403
1375
  else {
1404
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1405
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1406
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1376
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1377
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1378
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1379
+ confidence: constants_1.BN_ZERO,
1380
+ timestamp: constants_1.BN_ZERO
1381
+ });
1407
1382
  }
1408
- var lp = OraclePrice_1.OraclePrice.from({
1409
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1410
- .div(sizeAmount.add(newCollateralAmount)),
1383
+ }
1384
+ else {
1385
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1386
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1387
+ .div(sizeAmount),
1411
1388
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1412
1389
  confidence: constants_1.BN_ZERO,
1413
1390
  timestamp: constants_1.BN_ZERO
1414
- });
1415
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1416
- }
1417
- else {
1418
- var assetsUsd = collateralUsd;
1419
- if (assetsUsd.gte(liablitiesUsd)) {
1420
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1421
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1422
- .div(sizeAmount),
1423
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1391
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1392
+ if ((0, types_1.isVariant)(side, 'long')) {
1393
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1394
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1395
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1424
1396
  confidence: constants_1.BN_ZERO,
1425
1397
  timestamp: constants_1.BN_ZERO
1426
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1427
- if ((0, types_1.isVariant)(side, 'long')) {
1428
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1429
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1430
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1431
- confidence: constants_1.BN_ZERO,
1432
- timestamp: constants_1.BN_ZERO
1433
- });
1434
- }
1435
- else {
1436
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1437
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1438
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1439
- confidence: constants_1.BN_ZERO,
1440
- timestamp: constants_1.BN_ZERO
1441
- });
1442
- }
1398
+ });
1443
1399
  }
1444
1400
  else {
1445
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1446
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1447
- .div(sizeAmount),
1448
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1401
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1402
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1403
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1449
1404
  confidence: constants_1.BN_ZERO,
1450
1405
  timestamp: constants_1.BN_ZERO
1451
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1452
- if ((0, types_1.isVariant)(side, 'long')) {
1453
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1454
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1455
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1456
- confidence: constants_1.BN_ZERO,
1457
- timestamp: constants_1.BN_ZERO
1458
- });
1459
- }
1460
- else {
1461
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1462
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1463
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1464
- confidence: constants_1.BN_ZERO,
1465
- timestamp: constants_1.BN_ZERO
1466
- });
1467
- }
1406
+ });
1468
1407
  }
1469
1408
  }
1470
1409
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1471
1410
  };
1472
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1411
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1473
1412
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1474
1413
  price: constants_1.BN_ZERO,
1475
1414
  exponent: constants_1.BN_ZERO,
@@ -1480,7 +1419,7 @@ var PerpetualsClient = (function () {
1480
1419
  return zeroOraclePrice;
1481
1420
  }
1482
1421
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1483
- price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1422
+ price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1484
1423
  .div(positionAccount.sizeAmount),
1485
1424
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1486
1425
  confidence: constants_1.BN_ZERO,
@@ -1508,7 +1447,7 @@ var PerpetualsClient = (function () {
1508
1447
  }
1509
1448
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1510
1449
  };
1511
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1450
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1512
1451
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1513
1452
  throw new Error("Delta Amounts cannot be negative.");
1514
1453
  }
@@ -1538,10 +1477,9 @@ var PerpetualsClient = (function () {
1538
1477
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1539
1478
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1540
1479
  positionAccount.market = marketAccountPk;
1541
- positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1542
- positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1543
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1544
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1480
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1481
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1482
+ positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1545
1483
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1546
1484
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1547
1485
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1613,6 +1551,9 @@ var PerpetualsClient = (function () {
1613
1551
  });
1614
1552
  };
1615
1553
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1554
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1555
+ };
1556
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1616
1557
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1617
1558
  return {
1618
1559
  profitUsd: constants_1.BN_ZERO,
@@ -1620,9 +1561,8 @@ var PerpetualsClient = (function () {
1620
1561
  };
1621
1562
  }
1622
1563
  var side = poolConfig.getMarketConfigByPk(positionAccount.market).side;
1623
- var sizeUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1564
+ var sizeUsd = positionAccount.sizeUsd;
1624
1565
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, sizeUsd);
1625
- var collateralMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1626
1566
  var priceDiffProfit, priceDiffLoss;
1627
1567
  var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1628
1568
  price: positionAccount.entryPrice.price,
@@ -1671,7 +1611,7 @@ var PerpetualsClient = (function () {
1671
1611
  }
1672
1612
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1673
1613
  return {
1674
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1614
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1675
1615
  lossUsd: constants_1.BN_ZERO,
1676
1616
  };
1677
1617
  }
@@ -1762,6 +1702,9 @@ var PerpetualsClient = (function () {
1762
1702
  }
1763
1703
  };
1764
1704
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1705
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1706
+ };
1707
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1765
1708
  var poolAmountUsd = constants_1.BN_ZERO;
1766
1709
  for (var index = 0; index < custodies.length; index++) {
1767
1710
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1774,6 +1717,7 @@ var PerpetualsClient = (function () {
1774
1717
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1775
1718
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1776
1719
  }
1720
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1777
1721
  if (aumCalcMode === "includePnl") {
1778
1722
  var poolEquityUsd = poolAmountUsd;
1779
1723
  for (var index = 0; index < markets.length; index++) {
@@ -1783,11 +1727,12 @@ var PerpetualsClient = (function () {
1783
1727
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1784
1728
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1785
1729
  var position = markets[index].getCollectivePosition();
1730
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1786
1731
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1787
1732
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1788
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1789
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1790
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1733
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1734
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1735
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1791
1736
  }
1792
1737
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1793
1738
  }
@@ -1795,14 +1740,6 @@ var PerpetualsClient = (function () {
1795
1740
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1796
1741
  }
1797
1742
  };
1798
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1799
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1800
- return { discountBn: constants_1.BN_ZERO };
1801
- }
1802
- else {
1803
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1804
- }
1805
- };
1806
1743
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1807
1744
  if (tokenStakeAccount.level === 0) {
1808
1745
  return { discountBn: constants_1.BN_ZERO };
@@ -1887,7 +1824,7 @@ var PerpetualsClient = (function () {
1887
1824
  });
1888
1825
  };
1889
1826
  this.getStakedLpTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
1890
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, result, index, res;
1827
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, setCULimitIx, result, index, res;
1891
1828
  var _d;
1892
1829
  return __generator(this, function (_e) {
1893
1830
  switch (_e.label) {
@@ -1935,6 +1872,8 @@ var PerpetualsClient = (function () {
1935
1872
  return [4, backUpOracleInstructionPromise];
1936
1873
  case 2:
1937
1874
  backUpOracleInstruction = _e.sent();
1875
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1876
+ transaction.instructions.unshift(setCULimitIx);
1938
1877
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
1939
1878
  return [4, this.viewHelper.simulateTransaction(transaction)];
1940
1879
  case 3:
@@ -2001,7 +1940,7 @@ var PerpetualsClient = (function () {
2001
1940
  args_1[_i - 4] = arguments[_i];
2002
1941
  }
2003
1942
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2004
- var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
1943
+ var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2005
1944
  var _e;
2006
1945
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2007
1946
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2052,6 +1991,8 @@ var PerpetualsClient = (function () {
2052
1991
  .transaction()];
2053
1992
  case 1:
2054
1993
  transaction = _f.sent();
1994
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1995
+ transaction.instructions.unshift(setCULimitIx);
2055
1996
  if (!enableBackupOracle) return [3, 3];
2056
1997
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2057
1998
  case 2:
@@ -2061,6 +2002,14 @@ var PerpetualsClient = (function () {
2061
2002
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2062
2003
  case 4:
2063
2004
  result = _f.sent();
2005
+ if (result.value.err) {
2006
+ console.error('error Simulation failed:::', result);
2007
+ return [2, {
2008
+ amount: undefined,
2009
+ fee: undefined,
2010
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2011
+ }];
2012
+ }
2064
2013
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2065
2014
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2066
2015
  return [2, {
@@ -2077,7 +2026,7 @@ var PerpetualsClient = (function () {
2077
2026
  args_1[_i - 4] = arguments[_i];
2078
2027
  }
2079
2028
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2080
- var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
2029
+ var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2081
2030
  var _e;
2082
2031
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2083
2032
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2128,6 +2077,8 @@ var PerpetualsClient = (function () {
2128
2077
  .transaction()];
2129
2078
  case 1:
2130
2079
  transaction = _f.sent();
2080
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2081
+ transaction.instructions.unshift(setCULimitIx);
2131
2082
  if (!enableBackupOracle) return [3, 3];
2132
2083
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2133
2084
  case 2:
@@ -2139,9 +2090,11 @@ var PerpetualsClient = (function () {
2139
2090
  result = _f.sent();
2140
2091
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2141
2092
  if (result.value.err) {
2093
+ console.error('error Simulation failed:', result);
2142
2094
  return [2, {
2143
- amount: new anchor_1.BN(0),
2144
- fee: new anchor_1.BN(0),
2095
+ amount: undefined,
2096
+ fee: undefined,
2097
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2145
2098
  }];
2146
2099
  }
2147
2100
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2154,7 +2107,7 @@ var PerpetualsClient = (function () {
2154
2107
  });
2155
2108
  };
2156
2109
  this.getCompoundingLPTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
2157
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, result, index, res;
2110
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, setCULimitIx, result, index, res;
2158
2111
  var _d;
2159
2112
  return __generator(this, function (_e) {
2160
2113
  switch (_e.label) {
@@ -2202,6 +2155,8 @@ var PerpetualsClient = (function () {
2202
2155
  .transaction()];
2203
2156
  case 2:
2204
2157
  transaction = _e.sent();
2158
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2159
+ transaction.instructions.unshift(setCULimitIx);
2205
2160
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
2206
2161
  return [4, this.viewHelper.simulateTransaction(transaction)];
2207
2162
  case 3:
@@ -2551,11 +2506,10 @@ var PerpetualsClient = (function () {
2551
2506
  for (var _i = 8; _i < arguments.length; _i++) {
2552
2507
  args_1[_i - 8] = arguments[_i];
2553
2508
  }
2554
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2509
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2555
2510
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2556
2511
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2557
2512
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2558
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2559
2513
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2560
2514
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2561
2515
  return __generator(this, function (_c) {
@@ -2648,7 +2602,7 @@ var PerpetualsClient = (function () {
2648
2602
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2649
2603
  fundingMint: collateralCustodyConfig.mintKey
2650
2604
  })
2651
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2605
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2652
2606
  .instruction()];
2653
2607
  case 7:
2654
2608
  instruction = _c.sent();
@@ -2666,11 +2620,10 @@ var PerpetualsClient = (function () {
2666
2620
  for (var _i = 6; _i < arguments.length; _i++) {
2667
2621
  args_1[_i - 6] = arguments[_i];
2668
2622
  }
2669
- return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2623
+ return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2670
2624
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2671
2625
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2672
2626
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2673
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2674
2627
  if (createUserATA === void 0) { createUserATA = true; }
2675
2628
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2676
2629
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2749,7 +2702,7 @@ var PerpetualsClient = (function () {
2749
2702
  collateralMint: collateralCustodyConfig.mintKey,
2750
2703
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2751
2704
  })
2752
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2705
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2753
2706
  .instruction()];
2754
2707
  case 6:
2755
2708
  instruction = _b.sent();
@@ -2771,16 +2724,15 @@ var PerpetualsClient = (function () {
2771
2724
  });
2772
2725
  });
2773
2726
  };
2774
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2727
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2775
2728
  var args_1 = [];
2776
- for (var _i = 10; _i < arguments.length; _i++) {
2777
- args_1[_i - 10] = arguments[_i];
2729
+ for (var _i = 9; _i < arguments.length; _i++) {
2730
+ args_1[_i - 9] = arguments[_i];
2778
2731
  }
2779
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, minCollateralAmountOut, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2780
- var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, rebateMintAccount, inx, err_3;
2732
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2733
+ var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, inx, err_3;
2781
2734
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2782
2735
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2783
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2784
2736
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2785
2737
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2786
2738
  return __generator(this, function (_c) {
@@ -2874,18 +2826,10 @@ var PerpetualsClient = (function () {
2874
2826
  }
2875
2827
  _c.label = 10;
2876
2828
  case 10:
2877
- rebateMintAccount = {
2878
- pubkey: collateralCustodyConfig.mintKey,
2879
- isSigner: false,
2880
- isWritable: false
2881
- };
2882
- _c.label = 11;
2883
- case 11:
2884
- _c.trys.push([11, 13, , 14]);
2829
+ _c.trys.push([10, 12, , 13]);
2885
2830
  return [4, this.program.methods
2886
2831
  .swapAndOpen({
2887
2832
  amountIn: amountIn,
2888
- minCollateralAmountOut: minCollateralAmountOut,
2889
2833
  priceWithSlippage: priceWithSlippage,
2890
2834
  sizeAmount: sizeAmount,
2891
2835
  privilege: privilege
@@ -2916,17 +2860,17 @@ var PerpetualsClient = (function () {
2916
2860
  collateralMint: collateralCustodyConfig.mintKey,
2917
2861
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2918
2862
  })
2919
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2863
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2920
2864
  .instruction()];
2921
- case 12:
2865
+ case 11:
2922
2866
  inx = _c.sent();
2923
2867
  instructions.push(inx);
2924
- return [3, 14];
2925
- case 13:
2868
+ return [3, 13];
2869
+ case 12:
2926
2870
  err_3 = _c.sent();
2927
2871
  console.error("perpClient SwapAndOpen error:: ", err_3);
2928
2872
  throw err_3;
2929
- case 14: return [2, {
2873
+ case 13: return [2, {
2930
2874
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2931
2875
  additionalSigners: additionalSigners
2932
2876
  }];
@@ -2934,16 +2878,15 @@ var PerpetualsClient = (function () {
2934
2878
  });
2935
2879
  });
2936
2880
  };
2937
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2881
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2938
2882
  var args_1 = [];
2939
- for (var _i = 8; _i < arguments.length; _i++) {
2940
- args_1[_i - 8] = arguments[_i];
2883
+ for (var _i = 7; _i < arguments.length; _i++) {
2884
+ args_1[_i - 7] = arguments[_i];
2941
2885
  }
2942
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, minSwapAmountOut, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, ephemeralSignerPubkey) {
2943
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2886
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, ephemeralSignerPubkey) {
2887
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2944
2888
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2945
2889
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2946
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2947
2890
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2948
2891
  return __generator(this, function (_a) {
2949
2892
  switch (_a.label) {
@@ -3009,18 +2952,12 @@ var PerpetualsClient = (function () {
3009
2952
  if (!(_a.sent())) {
3010
2953
  preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, collateralToken.mintKey, collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
3011
2954
  }
3012
- rebateMintAccount = {
3013
- pubkey: collateralCustodyConfig.mintKey,
3014
- isSigner: false,
3015
- isWritable: false
3016
- };
3017
2955
  _a.label = 5;
3018
2956
  case 5:
3019
2957
  _a.trys.push([5, 7, , 8]);
3020
2958
  return [4, this.program.methods
3021
2959
  .closeAndSwap({
3022
2960
  priceWithSlippage: priceWithSlippage,
3023
- minSwapAmountOut: minSwapAmountOut,
3024
2961
  privilege: privilege
3025
2962
  })
3026
2963
  .accounts({
@@ -3049,7 +2986,7 @@ var PerpetualsClient = (function () {
3049
2986
  collateralMint: collateralCustodyConfig.mintKey,
3050
2987
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
3051
2988
  })
3052
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2989
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3053
2990
  .instruction()];
3054
2991
  case 6:
3055
2992
  inx = _a.sent();
@@ -3170,12 +3107,12 @@ var PerpetualsClient = (function () {
3170
3107
  });
3171
3108
  });
3172
3109
  };
3173
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3110
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3174
3111
  var args_1 = [];
3175
- for (var _i = 8; _i < arguments.length; _i++) {
3176
- args_1[_i - 8] = arguments[_i];
3112
+ for (var _i = 7; _i < arguments.length; _i++) {
3113
+ args_1[_i - 7] = arguments[_i];
3177
3114
  }
3178
- return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, minCollateralAmountOut, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3115
+ return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3179
3116
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3180
3117
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3181
3118
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3254,7 +3191,6 @@ var PerpetualsClient = (function () {
3254
3191
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3255
3192
  return [4, this.program.methods.swapAndAddCollateral({
3256
3193
  amountIn: amountIn,
3257
- minCollateralAmountOut: minCollateralAmountOut,
3258
3194
  }).accounts({
3259
3195
  owner: publicKey,
3260
3196
  feePayer: publicKey,
@@ -3290,12 +3226,12 @@ var PerpetualsClient = (function () {
3290
3226
  });
3291
3227
  });
3292
3228
  };
3293
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3229
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3294
3230
  var args_1 = [];
3295
3231
  for (var _i = 6; _i < arguments.length; _i++) {
3296
3232
  args_1[_i - 6] = arguments[_i];
3297
3233
  }
3298
- return __awaiter(_this, __spreadArray([collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralWithFee, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3234
+ return __awaiter(_this, __spreadArray([collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralDeltaUsd, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3299
3235
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3300
3236
  if (createUserATA === void 0) { createUserATA = true; }
3301
3237
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3359,7 +3295,7 @@ var PerpetualsClient = (function () {
3359
3295
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3360
3296
  return [4, this.program.methods
3361
3297
  .removeCollateral({
3362
- collateralDelta: collateralWithFee,
3298
+ collateralDeltaUsd: collateralDeltaUsd,
3363
3299
  })
3364
3300
  .accounts({
3365
3301
  owner: publicKey,
@@ -3401,12 +3337,12 @@ var PerpetualsClient = (function () {
3401
3337
  });
3402
3338
  });
3403
3339
  };
3404
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3340
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3405
3341
  var args_1 = [];
3406
- for (var _i = 7; _i < arguments.length; _i++) {
3407
- args_1[_i - 7] = arguments[_i];
3342
+ for (var _i = 6; _i < arguments.length; _i++) {
3343
+ args_1[_i - 6] = arguments[_i];
3408
3344
  }
3409
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, minSwapAmountOut, collateralDelta, side, poolConfig, ephemeralSignerPubkey) {
3345
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, collateralDeltaUsd, side, poolConfig, ephemeralSignerPubkey) {
3410
3346
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3411
3347
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3412
3348
  return __generator(this, function (_a) {
@@ -3463,8 +3399,7 @@ var PerpetualsClient = (function () {
3463
3399
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3464
3400
  return [4, this.program.methods
3465
3401
  .removeCollateralAndSwap({
3466
- collateralDelta: collateralDelta,
3467
- minSwapAmountOut: minSwapAmountOut,
3402
+ collateralDeltaUsd: collateralDeltaUsd,
3468
3403
  })
3469
3404
  .accounts({
3470
3405
  owner: publicKey,
@@ -3509,11 +3444,10 @@ var PerpetualsClient = (function () {
3509
3444
  for (var _i = 8; _i < arguments.length; _i++) {
3510
3445
  args_1[_i - 8] = arguments[_i];
3511
3446
  }
3512
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3447
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3513
3448
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3514
3449
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3515
3450
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3516
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3517
3451
  return __generator(this, function (_a) {
3518
3452
  switch (_a.label) {
3519
3453
  case 0:
@@ -3556,7 +3490,7 @@ var PerpetualsClient = (function () {
3556
3490
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3557
3491
  collateralMint: collateralCustodyConfig.mintKey
3558
3492
  })
3559
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3493
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3560
3494
  .instruction()];
3561
3495
  case 1:
3562
3496
  instruction = _a.sent();
@@ -3574,11 +3508,10 @@ var PerpetualsClient = (function () {
3574
3508
  for (var _i = 8; _i < arguments.length; _i++) {
3575
3509
  args_1[_i - 8] = arguments[_i];
3576
3510
  }
3577
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3511
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3578
3512
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3579
3513
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3580
3514
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3581
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3582
3515
  return __generator(this, function (_a) {
3583
3516
  switch (_a.label) {
3584
3517
  case 0:
@@ -3621,7 +3554,7 @@ var PerpetualsClient = (function () {
3621
3554
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3622
3555
  collateralMint: collateralCustodyConfig.mintKey
3623
3556
  })
3624
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3557
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3625
3558
  .instruction()];
3626
3559
  case 1:
3627
3560
  instruction = _a.sent();
@@ -4088,119 +4021,8 @@ var PerpetualsClient = (function () {
4088
4021
  }
4089
4022
  });
4090
4023
  }); };
4091
- this.updateNftAccount = function (nftMint, updateReferer, updateBooster, flpStakeAccounts) { return __awaiter(_this, void 0, void 0, function () {
4092
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, flpStakeAccountMetas, _i, flpStakeAccounts_1, flpStakeAccountPk, updateNftTradingAccountInstruction, err_8;
4093
- return __generator(this, function (_a) {
4094
- switch (_a.label) {
4095
- case 0:
4096
- publicKey = this.provider.wallet.publicKey;
4097
- preInstructions = [];
4098
- instructions = [];
4099
- postInstructions = [];
4100
- additionalSigners = [];
4101
- _a.label = 1;
4102
- case 1:
4103
- _a.trys.push([1, 4, , 5]);
4104
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4105
- Buffer.from("trading"),
4106
- nftMint.toBuffer(),
4107
- ], this.programId)[0];
4108
- nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
4109
- Buffer.from("referral"),
4110
- publicKey.toBuffer(),
4111
- ], this.programId)[0];
4112
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey, true)];
4113
- case 2:
4114
- nftTokenAccount = _a.sent();
4115
- flpStakeAccountMetas = [];
4116
- for (_i = 0, flpStakeAccounts_1 = flpStakeAccounts; _i < flpStakeAccounts_1.length; _i++) {
4117
- flpStakeAccountPk = flpStakeAccounts_1[_i];
4118
- flpStakeAccountMetas.push({
4119
- pubkey: flpStakeAccountPk,
4120
- isSigner: false,
4121
- isWritable: true,
4122
- });
4123
- }
4124
- return [4, this.program.methods
4125
- .updateTradingAccount({
4126
- updateReferer: updateReferer,
4127
- updateBooster: updateBooster
4128
- })
4129
- .accounts({
4130
- owner: publicKey,
4131
- feePayer: publicKey,
4132
- nftTokenAccount: nftTokenAccount,
4133
- referralAccount: nftReferralAccount,
4134
- tradingAccount: nftTradingAccount
4135
- })
4136
- .instruction()];
4137
- case 3:
4138
- updateNftTradingAccountInstruction = _a.sent();
4139
- instructions.push(updateNftTradingAccountInstruction);
4140
- return [3, 5];
4141
- case 4:
4142
- err_8 = _a.sent();
4143
- console.log("perpClient updateNftAccount error:: ", err_8);
4144
- throw err_8;
4145
- case 5: return [2, {
4146
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4147
- additionalSigners: additionalSigners
4148
- }];
4149
- }
4150
- });
4151
- }); };
4152
- this.levelUp = function (poolConfig, nftMint, authorizationRulesAccount) { return __awaiter(_this, void 0, void 0, function () {
4153
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_9;
4154
- return __generator(this, function (_a) {
4155
- switch (_a.label) {
4156
- case 0:
4157
- publicKey = this.provider.wallet.publicKey;
4158
- preInstructions = [];
4159
- instructions = [];
4160
- postInstructions = [];
4161
- additionalSigners = [];
4162
- _a.label = 1;
4163
- case 1:
4164
- _a.trys.push([1, 3, , 4]);
4165
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4166
- Buffer.from("trading"),
4167
- nftMint.toBuffer(),
4168
- ], this.programId)[0];
4169
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
4170
- return [4, this.program.methods
4171
- .levelUp({})
4172
- .accounts({
4173
- owner: publicKey,
4174
- perpetuals: this.perpetuals.publicKey,
4175
- pool: poolConfig.poolAddress,
4176
- metadataAccount: metadataAccount,
4177
- nftMint: nftMint,
4178
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
4179
- tradingAccount: nftTradingAccount,
4180
- transferAuthority: this.authority.publicKey,
4181
- authorizationRulesAccount: authorizationRulesAccount,
4182
- authorizationRulesProgram: new web3_js_1.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg'),
4183
- systemProgram: web3_js_1.SystemProgram.programId,
4184
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
4185
- })
4186
- .instruction()];
4187
- case 2:
4188
- levelUpInstruction = _a.sent();
4189
- instructions.push(levelUpInstruction);
4190
- return [3, 4];
4191
- case 3:
4192
- err_9 = _a.sent();
4193
- console.log("perpClient levelUp error:: ", err_9);
4194
- throw err_9;
4195
- case 4: return [2, {
4196
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4197
- additionalSigners: additionalSigners
4198
- }];
4199
- }
4200
- });
4201
- }); };
4202
4024
  this.depositStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4203
- var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
4025
+ var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_8;
4204
4026
  return __generator(this, function (_a) {
4205
4027
  switch (_a.label) {
4206
4028
  case 0:
@@ -4242,10 +4064,10 @@ var PerpetualsClient = (function () {
4242
4064
  instructions.push(depositStakeInstruction);
4243
4065
  return [3, 5];
4244
4066
  case 4:
4245
- err_10 = _a.sent();
4246
- console.log("perpClient depositStaking error:: ", err_10);
4247
- throw err_10;
4248
- case 5: return [2, {
4067
+ err_8 = _a.sent();
4068
+ console.log("perpClient depositStaking error:: ", err_8);
4069
+ throw err_8;
4070
+ case 5: return [2, {
4249
4071
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4250
4072
  additionalSigners: additionalSigners
4251
4073
  }];
@@ -4253,7 +4075,7 @@ var PerpetualsClient = (function () {
4253
4075
  });
4254
4076
  }); };
4255
4077
  this.refreshStakeWithAllFlpStakeAccounts = function (rewardSymbol, poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4256
- var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_11;
4078
+ var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_9;
4257
4079
  return __generator(this, function (_c) {
4258
4080
  switch (_c.label) {
4259
4081
  case 0:
@@ -4300,9 +4122,9 @@ var PerpetualsClient = (function () {
4300
4122
  refreshStakeInstruction = _c.sent();
4301
4123
  return [2, refreshStakeInstruction];
4302
4124
  case 2:
4303
- err_11 = _c.sent();
4304
- console.log("perpClient refreshStaking error:: ", err_11);
4305
- throw err_11;
4125
+ err_9 = _c.sent();
4126
+ console.log("perpClient refreshStaking error:: ", err_9);
4127
+ throw err_9;
4306
4128
  case 3: return [2];
4307
4129
  }
4308
4130
  });
@@ -4313,7 +4135,7 @@ var PerpetualsClient = (function () {
4313
4135
  args_1[_i - 3] = arguments[_i];
4314
4136
  }
4315
4137
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, flpStakeAccountPk_1], args_1, true), void 0, function (rewardSymbol, poolConfig, flpStakeAccountPk, userPublicKey) {
4316
- var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_12;
4138
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_10;
4317
4139
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4318
4140
  return __generator(this, function (_c) {
4319
4141
  switch (_c.label) {
@@ -4361,9 +4183,9 @@ var PerpetualsClient = (function () {
4361
4183
  refreshStakeInstruction = _c.sent();
4362
4184
  return [2, refreshStakeInstruction];
4363
4185
  case 2:
4364
- err_12 = _c.sent();
4365
- console.log("perpClient refreshStaking error:: ", err_12);
4366
- throw err_12;
4186
+ err_10 = _c.sent();
4187
+ console.log("perpClient refreshStaking error:: ", err_10);
4188
+ throw err_10;
4367
4189
  case 3: return [2];
4368
4190
  }
4369
4191
  });
@@ -4375,7 +4197,7 @@ var PerpetualsClient = (function () {
4375
4197
  args_1[_i - 3] = arguments[_i];
4376
4198
  }
4377
4199
  return __awaiter(_this, __spreadArray([rewardSymbol_1, unstakeAmount_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, unstakeAmount, poolConfig, userPublicKey) {
4378
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_13;
4200
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_11;
4379
4201
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4380
4202
  return __generator(this, function (_b) {
4381
4203
  switch (_b.label) {
@@ -4427,9 +4249,9 @@ var PerpetualsClient = (function () {
4427
4249
  instructions.push(unstakeInstantInstruction);
4428
4250
  return [3, 6];
4429
4251
  case 5:
4430
- err_13 = _b.sent();
4431
- console.log("perpClient unstakeInstant error:: ", err_13);
4432
- throw err_13;
4252
+ err_11 = _b.sent();
4253
+ console.log("perpClient unstakeInstant error:: ", err_11);
4254
+ throw err_11;
4433
4255
  case 6: return [2, {
4434
4256
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4435
4257
  additionalSigners: additionalSigners
@@ -4439,7 +4261,7 @@ var PerpetualsClient = (function () {
4439
4261
  });
4440
4262
  };
4441
4263
  this.setFeeShareBps = function (poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4442
- var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_14;
4264
+ var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_12;
4443
4265
  return __generator(this, function (_c) {
4444
4266
  switch (_c.label) {
4445
4267
  case 0:
@@ -4483,15 +4305,15 @@ var PerpetualsClient = (function () {
4483
4305
  refreshStakeInstruction = _c.sent();
4484
4306
  return [2, refreshStakeInstruction];
4485
4307
  case 2:
4486
- err_14 = _c.sent();
4487
- console.log("perpClient refreshStaking error:: ", err_14);
4488
- throw err_14;
4308
+ err_12 = _c.sent();
4309
+ console.log("perpClient refreshStaking error:: ", err_12);
4310
+ throw err_12;
4489
4311
  case 3: return [2];
4490
4312
  }
4491
4313
  });
4492
4314
  }); };
4493
4315
  this.unstakeRequest = function (unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4494
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_15;
4316
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_13;
4495
4317
  return __generator(this, function (_a) {
4496
4318
  switch (_a.label) {
4497
4319
  case 0:
@@ -4525,9 +4347,9 @@ var PerpetualsClient = (function () {
4525
4347
  instructions.push(unstakeRequestInstruction);
4526
4348
  return [3, 4];
4527
4349
  case 3:
4528
- err_15 = _a.sent();
4529
- console.log("perpClient unstakeRequest error:: ", err_15);
4530
- throw err_15;
4350
+ err_13 = _a.sent();
4351
+ console.log("perpClient unstakeRequest error:: ", err_13);
4352
+ throw err_13;
4531
4353
  case 4: return [2, {
4532
4354
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4533
4355
  additionalSigners: additionalSigners
@@ -4541,7 +4363,7 @@ var PerpetualsClient = (function () {
4541
4363
  args_1[_i - 1] = arguments[_i];
4542
4364
  }
4543
4365
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, pendingActivation, deactivated, createUserLPTA, userPublicKey) {
4544
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_16;
4366
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_14;
4545
4367
  if (pendingActivation === void 0) { pendingActivation = true; }
4546
4368
  if (deactivated === void 0) { deactivated = true; }
4547
4369
  if (createUserLPTA === void 0) { createUserLPTA = true; }
@@ -4597,9 +4419,9 @@ var PerpetualsClient = (function () {
4597
4419
  instructions.push(withdrawStakeInstruction);
4598
4420
  return [3, 6];
4599
4421
  case 5:
4600
- err_16 = _b.sent();
4601
- console.log("perpClient withdrawStake error:: ", err_16);
4602
- throw err_16;
4422
+ err_14 = _b.sent();
4423
+ console.log("perpClient withdrawStake error:: ", err_14);
4424
+ throw err_14;
4603
4425
  case 6: return [2, {
4604
4426
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4605
4427
  additionalSigners: additionalSigners
@@ -4614,7 +4436,7 @@ var PerpetualsClient = (function () {
4614
4436
  args_1[_i - 3] = arguments[_i];
4615
4437
  }
4616
4438
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, tokenStakeAccount_1], args_1, true), void 0, function (rewardSymbol, poolConfig, tokenStakeAccount, createUserATA) {
4617
- var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_17;
4439
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_15;
4618
4440
  if (createUserATA === void 0) { createUserATA = true; }
4619
4441
  return __generator(this, function (_b) {
4620
4442
  switch (_b.label) {
@@ -4675,9 +4497,9 @@ var PerpetualsClient = (function () {
4675
4497
  instructions.push(withdrawStakeInstruction);
4676
4498
  return [3, 6];
4677
4499
  case 5:
4678
- err_17 = _b.sent();
4679
- console.log("perpClient withdrawStake error:: ", err_17);
4680
- throw err_17;
4500
+ err_15 = _b.sent();
4501
+ console.log("perpClient withdrawStake error:: ", err_15);
4502
+ throw err_15;
4681
4503
  case 6: return [2, {
4682
4504
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4683
4505
  additionalSigners: additionalSigners
@@ -4691,11 +4513,13 @@ var PerpetualsClient = (function () {
4691
4513
  for (var _i = 5; _i < arguments.length; _i++) {
4692
4514
  args_1[_i - 5] = arguments[_i];
4693
4515
  }
4694
- return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey) {
4695
- var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_18;
4516
+ return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4517
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, heapSizeIx, addCompoundingLiquidity, err_16;
4696
4518
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4697
4519
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4698
4520
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4521
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4522
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4699
4523
  return __generator(this, function (_f) {
4700
4524
  switch (_f.label) {
4701
4525
  case 0:
@@ -4786,6 +4610,15 @@ var PerpetualsClient = (function () {
4786
4610
  _f.label = 7;
4787
4611
  case 7:
4788
4612
  _f.trys.push([7, 9, , 10]);
4613
+ if (enableHeapSizeIx) {
4614
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4615
+ bytes: 64 * 1024,
4616
+ });
4617
+ if (enableDebugLogs) {
4618
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4619
+ }
4620
+ preInstructions.push(heapSizeIx);
4621
+ }
4789
4622
  return [4, this.program.methods
4790
4623
  .addCompoundingLiquidity({
4791
4624
  amountIn: amountIn,
@@ -4820,8 +4653,8 @@ var PerpetualsClient = (function () {
4820
4653
  instructions.push(addCompoundingLiquidity);
4821
4654
  return [3, 10];
4822
4655
  case 9:
4823
- err_18 = _f.sent();
4824
- console.log("perpClient addCompoundingLiquidity error:: ", err_18);
4656
+ err_16 = _f.sent();
4657
+ console.log("perpClient addCompoundingLiquidity error:: ", err_16);
4825
4658
  return [3, 10];
4826
4659
  case 10: return [2, {
4827
4660
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4836,11 +4669,13 @@ var PerpetualsClient = (function () {
4836
4669
  for (var _i = 5; _i < arguments.length; _i++) {
4837
4670
  args_1[_i - 5] = arguments[_i];
4838
4671
  }
4839
- return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey) {
4840
- var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_19;
4672
+ return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4673
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, heapSizeIx, removeCompoundingLiquidity, err_17;
4841
4674
  if (createUserATA === void 0) { createUserATA = true; }
4842
4675
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4843
4676
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4677
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4678
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4844
4679
  return __generator(this, function (_f) {
4845
4680
  switch (_f.label) {
4846
4681
  case 0:
@@ -4915,6 +4750,15 @@ var PerpetualsClient = (function () {
4915
4750
  _f.label = 5;
4916
4751
  case 5:
4917
4752
  _f.trys.push([5, 7, , 8]);
4753
+ if (enableHeapSizeIx) {
4754
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4755
+ bytes: 64 * 1024,
4756
+ });
4757
+ if (enableDebugLogs) {
4758
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4759
+ }
4760
+ preInstructions.push(heapSizeIx);
4761
+ }
4918
4762
  return [4, this.program.methods
4919
4763
  .removeCompoundingLiquidity({
4920
4764
  compoundingAmountIn: compoundingAmountIn,
@@ -4949,8 +4793,8 @@ var PerpetualsClient = (function () {
4949
4793
  instructions.push(removeCompoundingLiquidity);
4950
4794
  return [3, 8];
4951
4795
  case 7:
4952
- err_19 = _f.sent();
4953
- console.log("perpClient removeCompoundingLiquidity error:: ", err_19);
4796
+ err_17 = _f.sent();
4797
+ console.log("perpClient removeCompoundingLiquidity error:: ", err_17);
4954
4798
  return [3, 8];
4955
4799
  case 8: return [2, {
4956
4800
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4966,7 +4810,7 @@ var PerpetualsClient = (function () {
4966
4810
  args_1[_i - 3] = arguments[_i];
4967
4811
  }
4968
4812
  return __awaiter(_this, __spreadArray([amount_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amount, rewardTokenMint, poolConfig, createUserATA) {
4969
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_20;
4813
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_18;
4970
4814
  if (createUserATA === void 0) { createUserATA = true; }
4971
4815
  return __generator(this, function (_g) {
4972
4816
  switch (_g.label) {
@@ -5064,8 +4908,8 @@ var PerpetualsClient = (function () {
5064
4908
  instructions.push(migrateStake);
5065
4909
  return [3, 8];
5066
4910
  case 7:
5067
- err_20 = _g.sent();
5068
- console.log("perpClient migrateStake error:: ", err_20);
4911
+ err_18 = _g.sent();
4912
+ console.log("perpClient migrateStake error:: ", err_18);
5069
4913
  return [3, 8];
5070
4914
  case 8: return [2, {
5071
4915
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5076,7 +4920,7 @@ var PerpetualsClient = (function () {
5076
4920
  });
5077
4921
  };
5078
4922
  this.migrateFlp = function (amount, rewardTokenMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5079
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_21;
4923
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_19;
5080
4924
  return __generator(this, function (_d) {
5081
4925
  switch (_d.label) {
5082
4926
  case 0:
@@ -5148,8 +4992,8 @@ var PerpetualsClient = (function () {
5148
4992
  instructions.push(migrateFlp);
5149
4993
  return [3, 4];
5150
4994
  case 3:
5151
- err_21 = _d.sent();
5152
- console.log("perpClient migrateFlp error:: ", err_21);
4995
+ err_19 = _d.sent();
4996
+ console.log("perpClient migrateFlp error:: ", err_19);
5153
4997
  return [3, 4];
5154
4998
  case 4: return [2, {
5155
4999
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5164,7 +5008,7 @@ var PerpetualsClient = (function () {
5164
5008
  args_1[_i - 1] = arguments[_i];
5165
5009
  }
5166
5010
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, rewardTokenSymbol) {
5167
- var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_22;
5011
+ var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_20;
5168
5012
  if (rewardTokenSymbol === void 0) { rewardTokenSymbol = 'USDC'; }
5169
5013
  return __generator(this, function (_e) {
5170
5014
  switch (_e.label) {
@@ -5222,8 +5066,8 @@ var PerpetualsClient = (function () {
5222
5066
  instructions.push(compoundingFee);
5223
5067
  return [3, 4];
5224
5068
  case 3:
5225
- err_22 = _e.sent();
5226
- console.log("perpClient compoundingFee error:: ", err_22);
5069
+ err_20 = _e.sent();
5070
+ console.log("perpClient compoundingFee error:: ", err_20);
5227
5071
  return [3, 4];
5228
5072
  case 4: return [2, {
5229
5073
  instructions: __spreadArray([], instructions, true),
@@ -5233,146 +5077,8 @@ var PerpetualsClient = (function () {
5233
5077
  });
5234
5078
  });
5235
5079
  };
5236
- this.burnAndClaim = function (owner, nftMint, poolConfig, createAta) { return __awaiter(_this, void 0, void 0, function () {
5237
- var preInstructions, instructions, postInstructions, additionalSigners, userTokenAccount, _a, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndClaimInstruction, err_23;
5238
- return __generator(this, function (_b) {
5239
- switch (_b.label) {
5240
- case 0:
5241
- preInstructions = [];
5242
- instructions = [];
5243
- postInstructions = [];
5244
- additionalSigners = [];
5245
- _b.label = 1;
5246
- case 1:
5247
- _b.trys.push([1, 7, , 8]);
5248
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, owner, true)];
5249
- case 2:
5250
- userTokenAccount = _b.sent();
5251
- _a = createAta;
5252
- if (!_a) return [3, 4];
5253
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5254
- case 3:
5255
- _a = !(_b.sent());
5256
- _b.label = 4;
5257
- case 4:
5258
- if (_a) {
5259
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, userTokenAccount, owner, poolConfig.tokenMint));
5260
- }
5261
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, owner, true)];
5262
- case 5:
5263
- nftTokenAccount = _b.sent();
5264
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5265
- Buffer.from("trading"),
5266
- nftMint.toBuffer(),
5267
- ], this.programId)[0];
5268
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5269
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5270
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5271
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5272
- return [4, this.program.methods
5273
- .burnAndClaim({})
5274
- .accounts({
5275
- owner: owner,
5276
- receivingTokenAccount: userTokenAccount,
5277
- perpetuals: this.perpetuals.publicKey,
5278
- tokenVault: poolConfig.tokenVault,
5279
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5280
- metadataAccount: metadataAccount,
5281
- collectionMetadata: collectionMetadata,
5282
- edition: edition,
5283
- tokenRecord: tokenRecord,
5284
- tradingAccount: nftTradingAccount,
5285
- transferAuthority: poolConfig.transferAuthority,
5286
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5287
- nftMint: nftMint,
5288
- nftTokenAccount: nftTokenAccount,
5289
- systemProgram: web3_js_1.SystemProgram.programId,
5290
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5291
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5292
- eventAuthority: this.eventAuthority.publicKey,
5293
- program: this.programId,
5294
- receivingTokenMint: poolConfig.tokenMint,
5295
- })
5296
- .instruction()];
5297
- case 6:
5298
- burnAndClaimInstruction = _b.sent();
5299
- instructions.push(burnAndClaimInstruction);
5300
- return [3, 8];
5301
- case 7:
5302
- err_23 = _b.sent();
5303
- console.log("perpClient burnAndClaimInstruction error:: ", err_23);
5304
- throw err_23;
5305
- case 8: return [2, {
5306
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5307
- additionalSigners: additionalSigners
5308
- }];
5309
- }
5310
- });
5311
- }); };
5312
- this.burnAndStake = function (owner, feePayer, nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5313
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndStakeInstruction, err_24;
5314
- return __generator(this, function (_a) {
5315
- switch (_a.label) {
5316
- case 0:
5317
- preInstructions = [];
5318
- instructions = [];
5319
- postInstructions = [];
5320
- additionalSigners = [];
5321
- _a.label = 1;
5322
- case 1:
5323
- _a.trys.push([1, 3, , 4]);
5324
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5325
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, owner, true);
5326
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5327
- Buffer.from("trading"),
5328
- nftMint.toBuffer(),
5329
- ], this.programId)[0];
5330
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5331
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5332
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5333
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5334
- return [4, this.program.methods
5335
- .burnAndStake({})
5336
- .accounts({
5337
- owner: owner,
5338
- feePayer: feePayer,
5339
- perpetuals: this.perpetuals.publicKey,
5340
- tokenVault: poolConfig.tokenVault,
5341
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5342
- tokenStakeAccount: tokenStakeAccount,
5343
- metadataAccount: metadataAccount,
5344
- collectionMetadata: collectionMetadata,
5345
- edition: edition,
5346
- tokenRecord: tokenRecord,
5347
- tradingAccount: nftTradingAccount,
5348
- transferAuthority: poolConfig.transferAuthority,
5349
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5350
- nftMint: nftMint,
5351
- nftTokenAccount: nftTokenAccount,
5352
- systemProgram: web3_js_1.SystemProgram.programId,
5353
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5354
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5355
- eventAuthority: this.eventAuthority.publicKey,
5356
- program: this.programId
5357
- })
5358
- .instruction()];
5359
- case 2:
5360
- burnAndStakeInstruction = _a.sent();
5361
- instructions.push(burnAndStakeInstruction);
5362
- return [3, 4];
5363
- case 3:
5364
- err_24 = _a.sent();
5365
- console.log("perpClient burnAndStakeInstruction error:: ", err_24);
5366
- throw err_24;
5367
- case 4: return [2, {
5368
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5369
- additionalSigners: additionalSigners
5370
- }];
5371
- }
5372
- });
5373
- }); };
5374
5080
  this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5375
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_25;
5081
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_21;
5376
5082
  return __generator(this, function (_a) {
5377
5083
  switch (_a.label) {
5378
5084
  case 0:
@@ -5414,9 +5120,9 @@ var PerpetualsClient = (function () {
5414
5120
  instructions.push(depositTokenStakeInstruction);
5415
5121
  return [3, 5];
5416
5122
  case 4:
5417
- err_25 = _a.sent();
5418
- console.log("perpClient depositStakingInstruction error:: ", err_25);
5419
- throw err_25;
5123
+ err_21 = _a.sent();
5124
+ console.log("perpClient depositStakingInstruction error:: ", err_21);
5125
+ throw err_21;
5420
5126
  case 5: return [2, {
5421
5127
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5422
5128
  additionalSigners: additionalSigners
@@ -5425,7 +5131,7 @@ var PerpetualsClient = (function () {
5425
5131
  });
5426
5132
  }); };
5427
5133
  this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5428
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_26;
5134
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_22;
5429
5135
  return __generator(this, function (_a) {
5430
5136
  switch (_a.label) {
5431
5137
  case 0:
@@ -5454,9 +5160,9 @@ var PerpetualsClient = (function () {
5454
5160
  instructions.push(unstakeTokenRequestInstruction);
5455
5161
  return [3, 4];
5456
5162
  case 3:
5457
- err_26 = _a.sent();
5458
- console.log("perpClient unstakeTokenRequestInstruction error:: ", err_26);
5459
- throw err_26;
5163
+ err_22 = _a.sent();
5164
+ console.log("perpClient unstakeTokenRequestInstruction error:: ", err_22);
5165
+ throw err_22;
5460
5166
  case 4: return [2, {
5461
5167
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5462
5168
  additionalSigners: additionalSigners
@@ -5465,7 +5171,7 @@ var PerpetualsClient = (function () {
5465
5171
  });
5466
5172
  }); };
5467
5173
  this.unstakeTokenInstant = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5468
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_27;
5174
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_23;
5469
5175
  return __generator(this, function (_a) {
5470
5176
  switch (_a.label) {
5471
5177
  case 0:
@@ -5506,9 +5212,9 @@ var PerpetualsClient = (function () {
5506
5212
  instructions.push(unstakeTokenInstantInstruction);
5507
5213
  return [3, 5];
5508
5214
  case 4:
5509
- err_27 = _a.sent();
5510
- console.log("perpClient unstakeTokenInstantInstruction error:: ", err_27);
5511
- throw err_27;
5215
+ err_23 = _a.sent();
5216
+ console.log("perpClient unstakeTokenInstantInstruction error:: ", err_23);
5217
+ throw err_23;
5512
5218
  case 5: return [2, {
5513
5219
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5514
5220
  additionalSigners: additionalSigners
@@ -5517,7 +5223,7 @@ var PerpetualsClient = (function () {
5517
5223
  });
5518
5224
  }); };
5519
5225
  this.withdrawToken = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5520
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_28;
5226
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_24;
5521
5227
  return __generator(this, function (_a) {
5522
5228
  switch (_a.label) {
5523
5229
  case 0:
@@ -5558,9 +5264,9 @@ var PerpetualsClient = (function () {
5558
5264
  instructions.push(withdrawTokenInstruction);
5559
5265
  return [3, 5];
5560
5266
  case 4:
5561
- err_28 = _a.sent();
5562
- console.log("perpClient withdrawTokenInstruction error:: ", err_28);
5563
- throw err_28;
5267
+ err_24 = _a.sent();
5268
+ console.log("perpClient withdrawTokenInstruction error:: ", err_24);
5269
+ throw err_24;
5564
5270
  case 5: return [2, {
5565
5271
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5566
5272
  additionalSigners: additionalSigners
@@ -5569,7 +5275,7 @@ var PerpetualsClient = (function () {
5569
5275
  });
5570
5276
  }); };
5571
5277
  this.cancelUnstakeRequest = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5572
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_29;
5278
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_25;
5573
5279
  return __generator(this, function (_a) {
5574
5280
  switch (_a.label) {
5575
5281
  case 0:
@@ -5598,9 +5304,9 @@ var PerpetualsClient = (function () {
5598
5304
  instructions.push(cancelUnstakeRequestInstruction);
5599
5305
  return [3, 4];
5600
5306
  case 3:
5601
- err_29 = _a.sent();
5602
- console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_29);
5603
- throw err_29;
5307
+ err_25 = _a.sent();
5308
+ console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_25);
5309
+ throw err_25;
5604
5310
  case 4: return [2, {
5605
5311
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5606
5312
  additionalSigners: additionalSigners
@@ -5614,7 +5320,7 @@ var PerpetualsClient = (function () {
5614
5320
  args_1[_i - 2] = arguments[_i];
5615
5321
  }
5616
5322
  return __awaiter(_this, __spreadArray([owner_1, poolConfig_1], args_1, true), void 0, function (owner, poolConfig, createUserATA) {
5617
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_30;
5323
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_26;
5618
5324
  if (createUserATA === void 0) { createUserATA = true; }
5619
5325
  return __generator(this, function (_b) {
5620
5326
  switch (_b.label) {
@@ -5660,9 +5366,9 @@ var PerpetualsClient = (function () {
5660
5366
  instructions.push(collectTokenRewardInstruction);
5661
5367
  return [3, 6];
5662
5368
  case 5:
5663
- err_30 = _b.sent();
5664
- console.log("perpClient collectTokenRewardInstruction error:: ", err_30);
5665
- throw err_30;
5369
+ err_26 = _b.sent();
5370
+ console.log("perpClient collectTokenRewardInstruction error:: ", err_26);
5371
+ throw err_26;
5666
5372
  case 6: return [2, {
5667
5373
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5668
5374
  additionalSigners: additionalSigners
@@ -5677,7 +5383,7 @@ var PerpetualsClient = (function () {
5677
5383
  args_1[_i - 3] = arguments[_i];
5678
5384
  }
5679
5385
  return __awaiter(_this, __spreadArray([owner_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rewardSymbol, poolConfig, createUserATA) {
5680
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_31;
5386
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_27;
5681
5387
  if (createUserATA === void 0) { createUserATA = true; }
5682
5388
  return __generator(this, function (_b) {
5683
5389
  switch (_b.label) {
@@ -5724,9 +5430,9 @@ var PerpetualsClient = (function () {
5724
5430
  instructions.push(collectRevenueInstruction);
5725
5431
  return [3, 6];
5726
5432
  case 5:
5727
- err_31 = _b.sent();
5728
- console.log("perpClient collectRevenueInstruction error:: ", err_31);
5729
- throw err_31;
5433
+ err_27 = _b.sent();
5434
+ console.log("perpClient collectRevenueInstruction error:: ", err_27);
5435
+ throw err_27;
5730
5436
  case 6: return [2, {
5731
5437
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5732
5438
  additionalSigners: additionalSigners
@@ -5735,179 +5441,18 @@ var PerpetualsClient = (function () {
5735
5441
  });
5736
5442
  });
5737
5443
  };
5738
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5739
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_32;
5740
- return __generator(this, function (_a) {
5741
- switch (_a.label) {
5742
- case 0:
5743
- publicKey = this.provider.wallet.publicKey;
5744
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5745
- instructions = [];
5746
- additionalSigners = [];
5747
- _a.label = 1;
5748
- case 1:
5749
- _a.trys.push([1, 3, , 4]);
5750
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5751
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5752
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5753
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5754
- return [4, this.programFbnftReward.methods
5755
- .initRewardVault({
5756
- nftCount: nftCount
5757
- })
5758
- .accounts({
5759
- admin: publicKey,
5760
- transferAuthority: nftTransferAuthority,
5761
- rewardVault: rewardVault,
5762
- rewardMint: rewardCustodyMint,
5763
- rewardTokenAccount: rewardTokenAccount,
5764
- collectionMint: collectionMint,
5765
- programData: fbNftProgramData,
5766
- systemProgram: web3_js_1.SystemProgram.programId,
5767
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5768
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5769
- })
5770
- .instruction()];
5771
- case 2:
5772
- initRewardVault = _a.sent();
5773
- instructions.push(initRewardVault);
5774
- return [3, 4];
5775
- case 3:
5776
- err_32 = _a.sent();
5777
- console.log("perpClient InitRewardVault error:: ", err_32);
5778
- throw err_32;
5779
- case 4: return [2, {
5780
- instructions: __spreadArray([], instructions, true),
5781
- additionalSigners: additionalSigners
5782
- }];
5783
- }
5784
- });
5785
- }); };
5786
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5787
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_33;
5788
- return __generator(this, function (_a) {
5789
- switch (_a.label) {
5790
- case 0:
5791
- publicKey = this.provider.wallet.publicKey;
5792
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5793
- instructions = [];
5794
- additionalSigners = [];
5795
- _a.label = 1;
5796
- case 1:
5797
- _a.trys.push([1, 3, , 4]);
5798
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5799
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5800
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5801
- return [4, this.programFbnftReward.methods
5802
- .distributeRewards({
5803
- rewardAmount: rewardAmount
5804
- })
5805
- .accounts({
5806
- admin: publicKey,
5807
- fundingAccount: fundingAccount,
5808
- rewardVault: rewardVault,
5809
- rewardTokenAccount: rewardTokenAccount,
5810
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5811
- })
5812
- .instruction()];
5813
- case 2:
5814
- distributeReward = _a.sent();
5815
- instructions.push(distributeReward);
5816
- return [3, 4];
5817
- case 3:
5818
- err_33 = _a.sent();
5819
- console.log("perpClient distributeReward error:: ", err_33);
5820
- throw err_33;
5821
- case 4: return [2, {
5822
- instructions: __spreadArray([], instructions, true),
5823
- additionalSigners: additionalSigners
5824
- }];
5825
- }
5826
- });
5827
- }); };
5828
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5444
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5829
5445
  var args_1 = [];
5830
5446
  for (var _i = 3; _i < arguments.length; _i++) {
5831
5447
  args_1[_i - 3] = arguments[_i];
5832
5448
  }
5833
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5834
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_34;
5835
- if (createUserATA === void 0) { createUserATA = true; }
5836
- return __generator(this, function (_b) {
5837
- switch (_b.label) {
5838
- case 0:
5839
- publicKey = this.provider.wallet.publicKey;
5840
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5841
- rewardCustodyMint = rewardToken.mintKey;
5842
- instructions = [];
5843
- additionalSigners = [];
5844
- _b.label = 1;
5845
- case 1:
5846
- _b.trys.push([1, 5, , 6]);
5847
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5848
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5849
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5850
- _a = createUserATA;
5851
- if (!_a) return [3, 3];
5852
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5853
- case 2:
5854
- _a = !(_b.sent());
5855
- _b.label = 3;
5856
- case 3:
5857
- if (_a) {
5858
- instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
5859
- }
5860
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5861
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5862
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5863
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5864
- return [4, this.programFbnftReward.methods
5865
- .collectReward()
5866
- .accounts({
5867
- owner: publicKey,
5868
- feePayer: publicKey,
5869
- nftMint: nftMint,
5870
- nftTokenAccount: nftTokenAccount,
5871
- metadataAccount: metadataAccount,
5872
- receivingAccount: receivingTokenAccount,
5873
- rewardRecord: rewardRecord,
5874
- rewardVault: rewardVault,
5875
- rewardTokenAccount: rewardTokenAccount,
5876
- transferAuthority: nftTransferAuthority,
5877
- systemProgram: web3_js_1.SystemProgram.programId,
5878
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5879
- })
5880
- .instruction()];
5881
- case 4:
5882
- collectNftReward = _b.sent();
5883
- instructions.push(collectNftReward);
5884
- return [3, 6];
5885
- case 5:
5886
- err_34 = _b.sent();
5887
- throw err_34;
5888
- case 6: return [2, {
5889
- instructions: __spreadArray([], instructions, true),
5890
- additionalSigners: additionalSigners
5891
- }];
5892
- }
5893
- });
5894
- });
5895
- };
5896
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5897
- var args_1 = [];
5898
- for (var _i = 2; _i < arguments.length; _i++) {
5899
- args_1[_i - 2] = arguments[_i];
5900
- }
5901
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5902
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_35;
5449
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5450
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5903
5451
  if (createUserATA === void 0) { createUserATA = true; }
5904
5452
  return __generator(this, function (_b) {
5905
5453
  switch (_b.label) {
5906
5454
  case 0:
5907
5455
  publicKey = this.provider.wallet.publicKey;
5908
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5909
- rewardCustodyMint = rewardToken.mintKey;
5910
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5911
5456
  preInstructions = [];
5912
5457
  instructions = [];
5913
5458
  postInstructions = [];
@@ -5915,59 +5460,43 @@ var PerpetualsClient = (function () {
5915
5460
  _b.label = 1;
5916
5461
  case 1:
5917
5462
  _b.trys.push([1, 5, , 6]);
5918
- pool = poolConfig.poolAddress;
5919
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5920
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5463
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5464
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5465
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5921
5466
  _a = createUserATA;
5922
5467
  if (!_a) return [3, 3];
5923
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5468
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5924
5469
  case 2:
5925
5470
  _a = !(_b.sent());
5926
5471
  _b.label = 3;
5927
5472
  case 3:
5928
5473
  if (_a) {
5929
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5930
- }
5931
- tradingAccount = [];
5932
- if (nftTradingAccount) {
5933
- tradingAccount.push({
5934
- pubkey: nftTradingAccount,
5935
- isSigner: false,
5936
- isWritable: true,
5937
- });
5474
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5938
5475
  }
5939
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5940
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5941
- return [4, this.programPerpComposability.methods
5942
- .collectAndDistributeFee()
5476
+ return [4, this.program.methods
5477
+ .collectRebate()
5943
5478
  .accounts({
5944
- perpProgram: this.programId,
5945
- owner: publicKey,
5946
- receivingTokenAccount: receivingTokenAccount,
5947
- transferAuthority: poolConfig.transferAuthority,
5479
+ owner: owner,
5480
+ receivingTokenAccount: userTokenAccount,
5948
5481
  perpetuals: this.perpetuals.publicKey,
5949
- pool: pool,
5950
- feeCustody: rewardCustodyConfig.custodyAccount,
5951
- flpStakeAccount: flpStakeAccount,
5952
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5953
- systemProgram: web3_js_1.SystemProgram.programId,
5482
+ transferAuthority: poolConfig.transferAuthority,
5483
+ rebateVault: poolConfig.rebateVault,
5484
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5485
+ tokenStakeAccount: tokenStakeAccount,
5954
5486
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5955
5487
  eventAuthority: this.eventAuthority.publicKey,
5956
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5957
- fbnftRewardsProgram: this.programFbnftReward.programId,
5958
- rewardVault: rewardVault,
5959
- rewardTokenAccount: rewardTokenAccount
5488
+ program: this.programId,
5489
+ receivingTokenMint: rebateMint,
5960
5490
  })
5961
- .remainingAccounts(tradingAccount)
5962
5491
  .instruction()];
5963
5492
  case 4:
5964
- withdrawStakeInstruction = _b.sent();
5965
- instructions.push(withdrawStakeInstruction);
5493
+ collectRebateInstruction = _b.sent();
5494
+ instructions.push(collectRebateInstruction);
5966
5495
  return [3, 6];
5967
5496
  case 5:
5968
- err_35 = _b.sent();
5969
- console.log("perpClient withdrawStake error:: ", err_35);
5970
- throw err_35;
5497
+ err_28 = _b.sent();
5498
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5499
+ throw err_28;
5971
5500
  case 6: return [2, {
5972
5501
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5973
5502
  additionalSigners: additionalSigners
@@ -5976,13 +5505,60 @@ var PerpetualsClient = (function () {
5976
5505
  });
5977
5506
  });
5978
5507
  };
5508
+ this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5509
+ var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5510
+ return __generator(this, function (_a) {
5511
+ switch (_a.label) {
5512
+ case 0:
5513
+ preInstructions = [];
5514
+ instructions = [];
5515
+ postInstructions = [];
5516
+ additionalSigners = [];
5517
+ _a.label = 1;
5518
+ case 1:
5519
+ _a.trys.push([1, 3, , 4]);
5520
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5521
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5522
+ return [4, this.program.methods
5523
+ .settleRebates()
5524
+ .accounts({
5525
+ transferAuthority: poolConfig.transferAuthority,
5526
+ perpetuals: this.perpetuals.publicKey,
5527
+ pool: poolConfig.poolAddress,
5528
+ rewardCustody: rewardCustody.custodyAccount,
5529
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5530
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5531
+ rebateVault: poolConfig.rebateVault,
5532
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5533
+ tokenMint: rebateMint,
5534
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5535
+ eventAuthority: this.eventAuthority.publicKey,
5536
+ program: this.programId,
5537
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5538
+ })
5539
+ .instruction()];
5540
+ case 2:
5541
+ settleRebatesInstruction = _a.sent();
5542
+ instructions.push(settleRebatesInstruction);
5543
+ return [3, 4];
5544
+ case 3:
5545
+ err_29 = _a.sent();
5546
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5547
+ throw err_29;
5548
+ case 4: return [2, {
5549
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5550
+ additionalSigners: additionalSigners
5551
+ }];
5552
+ }
5553
+ });
5554
+ }); };
5979
5555
  this.placeLimitOrder = function (targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1) {
5980
5556
  var args_1 = [];
5981
5557
  for (var _i = 11; _i < arguments.length; _i++) {
5982
5558
  args_1[_i - 11] = arguments[_i];
5983
5559
  }
5984
5560
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, limitPrice, reserveAmount, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
5985
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_36;
5561
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5986
5562
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5987
5563
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5988
5564
  return __generator(this, function (_c) {
@@ -6088,9 +5664,9 @@ var PerpetualsClient = (function () {
6088
5664
  instructions.push(placeLimitOrder);
6089
5665
  return [3, 10];
6090
5666
  case 9:
6091
- err_36 = _c.sent();
6092
- console.log("perpClient placeLimitOrder error:: ", err_36);
6093
- throw err_36;
5667
+ err_30 = _c.sent();
5668
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5669
+ throw err_30;
6094
5670
  case 10: return [2, {
6095
5671
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6096
5672
  additionalSigners: additionalSigners
@@ -6105,7 +5681,7 @@ var PerpetualsClient = (function () {
6105
5681
  args_1[_i - 11] = arguments[_i];
6106
5682
  }
6107
5683
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, orderId_1, limitPrice_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, orderId, limitPrice, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, createUserATA, ephemeralSignerPubkey) {
6108
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_37;
5684
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
6109
5685
  if (createUserATA === void 0) { createUserATA = true; }
6110
5686
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6111
5687
  return __generator(this, function (_b) {
@@ -6196,9 +5772,9 @@ var PerpetualsClient = (function () {
6196
5772
  instructions.push(editLimitOrder);
6197
5773
  return [3, 8];
6198
5774
  case 7:
6199
- err_37 = _b.sent();
6200
- console.log("perpClient editLimitOrder error:: ", err_37);
6201
- throw err_37;
5775
+ err_31 = _b.sent();
5776
+ console.log("perpClient editLimitOrder error:: ", err_31);
5777
+ throw err_31;
6202
5778
  case 8: return [2, {
6203
5779
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6204
5780
  additionalSigners: additionalSigners
@@ -6212,11 +5788,10 @@ var PerpetualsClient = (function () {
6212
5788
  for (var _i = 7; _i < arguments.length; _i++) {
6213
5789
  args_1[_i - 7] = arguments[_i];
6214
5790
  }
6215
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6216
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_38;
5791
+ return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount) {
5792
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
6217
5793
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6218
5794
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6219
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6220
5795
  return __generator(this, function (_a) {
6221
5796
  switch (_a.label) {
6222
5797
  case 0:
@@ -6259,16 +5834,16 @@ var PerpetualsClient = (function () {
6259
5834
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6260
5835
  collateralMint: collateralCustodyConfig.mintKey,
6261
5836
  })
6262
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5837
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6263
5838
  .instruction()];
6264
5839
  case 2:
6265
5840
  executeLimitOrder = _a.sent();
6266
5841
  instructions.push(executeLimitOrder);
6267
5842
  return [3, 4];
6268
5843
  case 3:
6269
- err_38 = _a.sent();
6270
- console.log("perpClient executeLimitOrder error:: ", err_38);
6271
- throw err_38;
5844
+ err_32 = _a.sent();
5845
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5846
+ throw err_32;
6272
5847
  case 4: return [2, {
6273
5848
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6274
5849
  additionalSigners: additionalSigners
@@ -6282,11 +5857,10 @@ var PerpetualsClient = (function () {
6282
5857
  for (var _i = 8; _i < arguments.length; _i++) {
6283
5858
  args_1[_i - 8] = arguments[_i];
6284
5859
  }
6285
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, reserveSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, reserveSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6286
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_39;
5860
+ return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, reserveSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, reserveSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount) {
5861
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6287
5862
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6288
5863
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6289
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6290
5864
  return __generator(this, function (_a) {
6291
5865
  switch (_a.label) {
6292
5866
  case 0:
@@ -6332,16 +5906,16 @@ var PerpetualsClient = (function () {
6332
5906
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6333
5907
  collateralMint: collateralCustodyConfig.mintKey,
6334
5908
  })
6335
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5909
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6336
5910
  .instruction()];
6337
5911
  case 2:
6338
5912
  executeLimitWithSwap = _a.sent();
6339
5913
  instructions.push(executeLimitWithSwap);
6340
5914
  return [3, 4];
6341
5915
  case 3:
6342
- err_39 = _a.sent();
6343
- console.log("perpClient executeLimitWithSwap error:: ", err_39);
6344
- throw err_39;
5916
+ err_33 = _a.sent();
5917
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5918
+ throw err_33;
6345
5919
  case 4: return [2, {
6346
5920
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6347
5921
  additionalSigners: additionalSigners
@@ -6351,7 +5925,7 @@ var PerpetualsClient = (function () {
6351
5925
  });
6352
5926
  };
6353
5927
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6354
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_40;
5928
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6355
5929
  return __generator(this, function (_a) {
6356
5930
  switch (_a.label) {
6357
5931
  case 0:
@@ -6399,9 +5973,9 @@ var PerpetualsClient = (function () {
6399
5973
  instructions.push(placeTriggerOrder);
6400
5974
  return [3, 4];
6401
5975
  case 3:
6402
- err_40 = _a.sent();
6403
- console.log("perpClient placeTriggerOrder error:: ", err_40);
6404
- throw err_40;
5976
+ err_34 = _a.sent();
5977
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5978
+ throw err_34;
6405
5979
  case 4: return [2, {
6406
5980
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6407
5981
  additionalSigners: additionalSigners
@@ -6410,7 +5984,7 @@ var PerpetualsClient = (function () {
6410
5984
  });
6411
5985
  }); };
6412
5986
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6413
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_41;
5987
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6414
5988
  return __generator(this, function (_a) {
6415
5989
  switch (_a.label) {
6416
5990
  case 0:
@@ -6457,9 +6031,9 @@ var PerpetualsClient = (function () {
6457
6031
  instructions.push(editTriggerOrder);
6458
6032
  return [3, 4];
6459
6033
  case 3:
6460
- err_41 = _a.sent();
6461
- console.log("perpClient editTriggerOrder error:: ", err_41);
6462
- throw err_41;
6034
+ err_35 = _a.sent();
6035
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6036
+ throw err_35;
6463
6037
  case 4: return [2, {
6464
6038
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6465
6039
  additionalSigners: additionalSigners
@@ -6468,7 +6042,7 @@ var PerpetualsClient = (function () {
6468
6042
  });
6469
6043
  }); };
6470
6044
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6471
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_42;
6045
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6472
6046
  return __generator(this, function (_a) {
6473
6047
  switch (_a.label) {
6474
6048
  case 0:
@@ -6501,9 +6075,9 @@ var PerpetualsClient = (function () {
6501
6075
  instructions.push(cancelTriggerOrder);
6502
6076
  return [3, 4];
6503
6077
  case 3:
6504
- err_42 = _a.sent();
6505
- console.log("perpClient cancelTriggerOrder error:: ", err_42);
6506
- throw err_42;
6078
+ err_36 = _a.sent();
6079
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6080
+ throw err_36;
6507
6081
  case 4: return [2, {
6508
6082
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6509
6083
  additionalSigners: additionalSigners
@@ -6512,7 +6086,7 @@ var PerpetualsClient = (function () {
6512
6086
  });
6513
6087
  }); };
6514
6088
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6515
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_43;
6089
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6516
6090
  return __generator(this, function (_a) {
6517
6091
  switch (_a.label) {
6518
6092
  case 0:
@@ -6543,9 +6117,9 @@ var PerpetualsClient = (function () {
6543
6117
  instructions.push(cancelAllTriggerOrders);
6544
6118
  return [3, 4];
6545
6119
  case 3:
6546
- err_43 = _a.sent();
6547
- console.log("perpClient cancelAllTriggerOrders error:: ", err_43);
6548
- throw err_43;
6120
+ err_37 = _a.sent();
6121
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6122
+ throw err_37;
6549
6123
  case 4: return [2, {
6550
6124
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6551
6125
  additionalSigners: additionalSigners
@@ -6558,13 +6132,12 @@ var PerpetualsClient = (function () {
6558
6132
  for (var _i = 9; _i < arguments.length; _i++) {
6559
6133
  args_1[_i - 9] = arguments[_i];
6560
6134
  }
6561
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, receivingSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, receivingSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6562
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_44;
6135
+ return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, receivingSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, receivingSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount) {
6136
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_38;
6563
6137
  if (createUserATA === void 0) { createUserATA = true; }
6564
6138
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6565
6139
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6566
6140
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6567
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6568
6141
  return __generator(this, function (_e) {
6569
6142
  switch (_e.label) {
6570
6143
  case 0:
@@ -6659,16 +6232,16 @@ var PerpetualsClient = (function () {
6659
6232
  collateralMint: collateralCustodyConfig.mintKey,
6660
6233
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6661
6234
  })
6662
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6235
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6663
6236
  .instruction()];
6664
6237
  case 8:
6665
6238
  executeTriggerWithSwap = _e.sent();
6666
6239
  instructions.push(executeTriggerWithSwap);
6667
6240
  return [3, 10];
6668
6241
  case 9:
6669
- err_44 = _e.sent();
6670
- console.log("perpClient executeTriggerWithSwap error:: ", err_44);
6671
- throw err_44;
6242
+ err_38 = _e.sent();
6243
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6244
+ throw err_38;
6672
6245
  case 10: return [2, {
6673
6246
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6674
6247
  additionalSigners: additionalSigners
@@ -6682,13 +6255,12 @@ var PerpetualsClient = (function () {
6682
6255
  for (var _i = 8; _i < arguments.length; _i++) {
6683
6256
  args_1[_i - 8] = arguments[_i];
6684
6257
  }
6685
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6686
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_45;
6258
+ return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount) {
6259
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6687
6260
  if (createUserATA === void 0) { createUserATA = true; }
6688
6261
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6689
6262
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6690
6263
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6691
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6692
6264
  return __generator(this, function (_b) {
6693
6265
  switch (_b.label) {
6694
6266
  case 0:
@@ -6748,16 +6320,16 @@ var PerpetualsClient = (function () {
6748
6320
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6749
6321
  receivingMint: collateralCustodyConfig.mintKey
6750
6322
  })
6751
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6323
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6752
6324
  .instruction()];
6753
6325
  case 6:
6754
6326
  executeTriggerOrder = _b.sent();
6755
6327
  instructions.push(executeTriggerOrder);
6756
6328
  return [3, 8];
6757
6329
  case 7:
6758
- err_45 = _b.sent();
6759
- console.log("perpClient executeTriggerOrder error:: ", err_45);
6760
- throw err_45;
6330
+ err_39 = _b.sent();
6331
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6332
+ throw err_39;
6761
6333
  case 8: return [2, {
6762
6334
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6763
6335
  additionalSigners: additionalSigners
@@ -6772,7 +6344,7 @@ var PerpetualsClient = (function () {
6772
6344
  args_1[_i - 5] = arguments[_i];
6773
6345
  }
6774
6346
  return __awaiter(_this, __spreadArray([userInputTokenSymbol_1, userOutputTokenSymbol_1, amountIn_1, minAmountOut_1, poolConfig_1], args_1, true), void 0, function (userInputTokenSymbol, userOutputTokenSymbol, amountIn, minAmountOut, poolConfig, useFeesPool, createUserATA, unWrapSol, skipBalanceChecks, ephemeralSignerPubkey) {
6775
- var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_46;
6347
+ var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_40;
6776
6348
  if (useFeesPool === void 0) { useFeesPool = false; }
6777
6349
  if (createUserATA === void 0) { createUserATA = true; }
6778
6350
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6919,7 +6491,7 @@ var PerpetualsClient = (function () {
6919
6491
  _g.label = 16;
6920
6492
  case 16:
6921
6493
  if (_d) {
6922
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userOutputTokenAccount, publicKey, poolConfig.getTokenFromSymbol(userOutputTokenSymbol).mintKey));
6494
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userOutputTokenAccount, publicKey, poolConfig.getTokenFromSymbol(userOutputTokenSymbol).mintKey, poolConfig.getTokenFromSymbol(userOutputTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
6923
6495
  }
6924
6496
  _g.label = 17;
6925
6497
  case 17:
@@ -6977,9 +6549,9 @@ var PerpetualsClient = (function () {
6977
6549
  }
6978
6550
  return [3, 20];
6979
6551
  case 19:
6980
- err_46 = _g.sent();
6981
- console.error("perpClient Swap error:: ", err_46);
6982
- throw err_46;
6552
+ err_40 = _g.sent();
6553
+ console.error("perpClient Swap error:: ", err_40);
6554
+ throw err_40;
6983
6555
  case 20: return [2, {
6984
6556
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6985
6557
  additionalSigners: additionalSigners
@@ -6989,7 +6561,7 @@ var PerpetualsClient = (function () {
6989
6561
  });
6990
6562
  };
6991
6563
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6992
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_47;
6564
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6993
6565
  return __generator(this, function (_b) {
6994
6566
  switch (_b.label) {
6995
6567
  case 0:
@@ -7034,11 +6606,7 @@ var PerpetualsClient = (function () {
7034
6606
  rewardCustody: rewardCustody.custodyAccount,
7035
6607
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
7036
6608
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
7037
- custody: custody.custodyAccount,
7038
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
7039
- custodyTokenAccount: custody.tokenAccount,
7040
6609
  eventAuthority: this.eventAuthority.publicKey,
7041
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7042
6610
  program: this.programId,
7043
6611
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
7044
6612
  })
@@ -7049,9 +6617,9 @@ var PerpetualsClient = (function () {
7049
6617
  instructions.push(inx);
7050
6618
  return [3, 4];
7051
6619
  case 3:
7052
- err_47 = _b.sent();
7053
- console.error("perpClient Swap error:: ", err_47);
7054
- throw err_47;
6620
+ err_41 = _b.sent();
6621
+ console.error("perpClient Swap error:: ", err_41);
6622
+ throw err_41;
7055
6623
  case 4: return [2, {
7056
6624
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7057
6625
  additionalSigners: additionalSigners
@@ -7060,7 +6628,7 @@ var PerpetualsClient = (function () {
7060
6628
  });
7061
6629
  }); };
7062
6630
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7063
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_48;
6631
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
7064
6632
  return __generator(this, function (_d) {
7065
6633
  switch (_d.label) {
7066
6634
  case 0:
@@ -7108,9 +6676,9 @@ var PerpetualsClient = (function () {
7108
6676
  instructions.push(setLpTokenPriceInstruction);
7109
6677
  return [3, 4];
7110
6678
  case 3:
7111
- err_48 = _d.sent();
7112
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_48);
7113
- throw err_48;
6679
+ err_42 = _d.sent();
6680
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6681
+ throw err_42;
7114
6682
  case 4: return [2, {
7115
6683
  instructions: __spreadArray([], instructions, true),
7116
6684
  additionalSigners: additionalSigners
@@ -7158,7 +6726,7 @@ var PerpetualsClient = (function () {
7158
6726
  });
7159
6727
  }); };
7160
6728
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
7161
- var adminMetas, _i, admins_2, admin, err_49;
6729
+ var adminMetas, _i, admins_2, admin, err_43;
7162
6730
  return __generator(this, function (_a) {
7163
6731
  switch (_a.label) {
7164
6732
  case 0:
@@ -7188,16 +6756,16 @@ var PerpetualsClient = (function () {
7188
6756
  _a.sent();
7189
6757
  return [3, 4];
7190
6758
  case 3:
7191
- err_49 = _a.sent();
6759
+ err_43 = _a.sent();
7192
6760
  if (this.printErrors) {
7193
- console.error("setAdminSigners err:", err_49);
6761
+ console.error("setAdminSigners err:", err_43);
7194
6762
  }
7195
- throw err_49;
6763
+ throw err_43;
7196
6764
  case 4: return [2];
7197
6765
  }
7198
6766
  });
7199
6767
  }); };
7200
- this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor) { return __awaiter(_this, void 0, void 0, function () {
6768
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor, stakingFeeBoostBps, minLpPriceUsd, maxLpPriceUsd, thresholdUsd) { return __awaiter(_this, void 0, void 0, function () {
7201
6769
  return __generator(this, function (_a) {
7202
6770
  switch (_a.label) {
7203
6771
  case 0: return [4, this.program.methods
@@ -7209,7 +6777,11 @@ var PerpetualsClient = (function () {
7209
6777
  metadataTitle: metadataTitle,
7210
6778
  metadataUri: metadataUri,
7211
6779
  stakingFeeShareBps: stakingFeeShareBps,
7212
- vpVolumeFactor: vpVolumeFactor
6780
+ vpVolumeFactor: vpVolumeFactor,
6781
+ stakingFeeBoostBps: stakingFeeBoostBps,
6782
+ minLpPriceUsd: minLpPriceUsd,
6783
+ maxLpPriceUsd: maxLpPriceUsd,
6784
+ thresholdUsd: thresholdUsd
7213
6785
  })
7214
6786
  .accounts({
7215
6787
  admin: this.provider.wallet.publicKey,
@@ -7257,7 +6829,7 @@ var PerpetualsClient = (function () {
7257
6829
  }
7258
6830
  });
7259
6831
  }); };
7260
- this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
6832
+ this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment, rewardThreshold, minReserveUsd, limitPriceBufferBps) { return __awaiter(_this, void 0, void 0, function () {
7261
6833
  var trx_id, error_3;
7262
6834
  return __generator(this, function (_a) {
7263
6835
  switch (_a.label) {
@@ -7275,6 +6847,9 @@ var PerpetualsClient = (function () {
7275
6847
  fees: fees,
7276
6848
  borrowRate: borrowRate,
7277
6849
  ratios: ratios,
6850
+ rewardThreshold: rewardThreshold,
6851
+ minReserveUsd: minReserveUsd,
6852
+ limitPriceBufferBps: limitPriceBufferBps
7278
6853
  })
7279
6854
  .accounts({
7280
6855
  admin: this.admin,
@@ -7381,7 +6956,7 @@ var PerpetualsClient = (function () {
7381
6956
  });
7382
6957
  }); };
7383
6958
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7384
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_50;
6959
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7385
6960
  return __generator(this, function (_a) {
7386
6961
  switch (_a.label) {
7387
6962
  case 0:
@@ -7414,9 +6989,9 @@ var PerpetualsClient = (function () {
7414
6989
  instructions.push(withdrawFeesIx);
7415
6990
  return [3, 5];
7416
6991
  case 4:
7417
- err_50 = _a.sent();
7418
- console.log("perpClient setPool error:: ", err_50);
7419
- throw err_50;
6992
+ err_44 = _a.sent();
6993
+ console.log("perpClient setPool error:: ", err_44);
6994
+ throw err_44;
7420
6995
  case 5: return [2, {
7421
6996
  instructions: __spreadArray([], instructions, true),
7422
6997
  additionalSigners: additionalSigners
@@ -7425,7 +7000,7 @@ var PerpetualsClient = (function () {
7425
7000
  });
7426
7001
  }); };
7427
7002
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7428
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_51;
7003
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7429
7004
  return __generator(this, function (_a) {
7430
7005
  switch (_a.label) {
7431
7006
  case 0:
@@ -7459,9 +7034,9 @@ var PerpetualsClient = (function () {
7459
7034
  instructions.push(moveProtocolFeesIx);
7460
7035
  return [3, 4];
7461
7036
  case 3:
7462
- err_51 = _a.sent();
7463
- console.log("perpClient setPool error:: ", err_51);
7464
- throw err_51;
7037
+ err_45 = _a.sent();
7038
+ console.log("perpClient setPool error:: ", err_45);
7039
+ throw err_45;
7465
7040
  case 4: return [2, {
7466
7041
  instructions: __spreadArray([], instructions, true),
7467
7042
  additionalSigners: additionalSigners
@@ -7470,7 +7045,7 @@ var PerpetualsClient = (function () {
7470
7045
  });
7471
7046
  }); };
7472
7047
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7473
- var publicKey, setProtocolFeeShareBpsIx, err_52;
7048
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7474
7049
  return __generator(this, function (_a) {
7475
7050
  switch (_a.label) {
7476
7051
  case 0:
@@ -7490,15 +7065,15 @@ var PerpetualsClient = (function () {
7490
7065
  setProtocolFeeShareBpsIx = _a.sent();
7491
7066
  return [2, setProtocolFeeShareBpsIx];
7492
7067
  case 2:
7493
- err_52 = _a.sent();
7494
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_52);
7495
- throw err_52;
7068
+ err_46 = _a.sent();
7069
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7070
+ throw err_46;
7496
7071
  case 3: return [2];
7497
7072
  }
7498
7073
  });
7499
7074
  }); };
7500
7075
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7501
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_53;
7076
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7502
7077
  return __generator(this, function (_a) {
7503
7078
  switch (_a.label) {
7504
7079
  case 0:
@@ -7525,9 +7100,9 @@ var PerpetualsClient = (function () {
7525
7100
  instructions.push(setPermissionsInstruction);
7526
7101
  return [3, 4];
7527
7102
  case 3:
7528
- err_53 = _a.sent();
7529
- console.log("perpClient setPool error:: ", err_53);
7530
- throw err_53;
7103
+ err_47 = _a.sent();
7104
+ console.log("perpClient setPool error:: ", err_47);
7105
+ throw err_47;
7531
7106
  case 4: return [2, {
7532
7107
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7533
7108
  additionalSigners: additionalSigners
@@ -7536,7 +7111,7 @@ var PerpetualsClient = (function () {
7536
7111
  });
7537
7112
  }); };
7538
7113
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7539
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_54;
7114
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7540
7115
  var _f;
7541
7116
  return __generator(this, function (_g) {
7542
7117
  switch (_g.label) {
@@ -7597,9 +7172,9 @@ var PerpetualsClient = (function () {
7597
7172
  instructions.push(reimburse);
7598
7173
  return [3, 5];
7599
7174
  case 4:
7600
- err_54 = _g.sent();
7601
- console.log("perpClient setPool error:: ", err_54);
7602
- throw err_54;
7175
+ err_48 = _g.sent();
7176
+ console.log("perpClient setPool error:: ", err_48);
7177
+ throw err_48;
7603
7178
  case 5: return [2, {
7604
7179
  instructions: __spreadArray([], instructions, true),
7605
7180
  additionalSigners: additionalSigners
@@ -7608,7 +7183,7 @@ var PerpetualsClient = (function () {
7608
7183
  });
7609
7184
  }); };
7610
7185
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7611
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_55;
7186
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7612
7187
  return __generator(this, function (_a) {
7613
7188
  switch (_a.label) {
7614
7189
  case 0:
@@ -7642,9 +7217,9 @@ var PerpetualsClient = (function () {
7642
7217
  instructions.push(setInternalOraclePrice);
7643
7218
  return [3, 4];
7644
7219
  case 3:
7645
- err_55 = _a.sent();
7646
- console.log("perpClient setInternalOracleAccount error:: ", err_55);
7647
- throw err_55;
7220
+ err_49 = _a.sent();
7221
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7222
+ throw err_49;
7648
7223
  case 4: return [2, {
7649
7224
  instructions: __spreadArray([], instructions, true),
7650
7225
  additionalSigners: additionalSigners
@@ -7653,7 +7228,7 @@ var PerpetualsClient = (function () {
7653
7228
  });
7654
7229
  }); };
7655
7230
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7656
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_56;
7231
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7657
7232
  return __generator(this, function (_a) {
7658
7233
  switch (_a.label) {
7659
7234
  case 0:
@@ -7699,9 +7274,9 @@ var PerpetualsClient = (function () {
7699
7274
  instructions.push(setInternalOraclePrice);
7700
7275
  return [3, 4];
7701
7276
  case 3:
7702
- err_56 = _a.sent();
7703
- console.log("perpClient setInternalOracleAccount error:: ", err_56);
7704
- throw err_56;
7277
+ err_50 = _a.sent();
7278
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7279
+ throw err_50;
7705
7280
  case 4: return [2, {
7706
7281
  instructions: __spreadArray([], instructions, true),
7707
7282
  additionalSigners: additionalSigners
@@ -7710,7 +7285,7 @@ var PerpetualsClient = (function () {
7710
7285
  });
7711
7286
  }); };
7712
7287
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7713
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_57;
7288
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7714
7289
  return __generator(this, function (_a) {
7715
7290
  switch (_a.label) {
7716
7291
  case 0:
@@ -7750,9 +7325,9 @@ var PerpetualsClient = (function () {
7750
7325
  instructions.push(setInternalOraclePrice);
7751
7326
  return [3, 4];
7752
7327
  case 3:
7753
- err_57 = _a.sent();
7754
- console.log("perpClient setInternalOracleAccount error:: ", err_57);
7755
- throw err_57;
7328
+ err_51 = _a.sent();
7329
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7330
+ throw err_51;
7756
7331
  case 4: return [2, {
7757
7332
  instructions: __spreadArray([], instructions, true),
7758
7333
  additionalSigners: additionalSigners
@@ -7761,7 +7336,7 @@ var PerpetualsClient = (function () {
7761
7336
  });
7762
7337
  }); };
7763
7338
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7764
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_58;
7339
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7765
7340
  return __generator(this, function (_a) {
7766
7341
  switch (_a.label) {
7767
7342
  case 0:
@@ -7799,8 +7374,8 @@ var PerpetualsClient = (function () {
7799
7374
  instructions.push(renameFlp);
7800
7375
  return [3, 4];
7801
7376
  case 3:
7802
- err_58 = _a.sent();
7803
- console.log("perpClient renameFlp error:: ", err_58);
7377
+ err_52 = _a.sent();
7378
+ console.log("perpClient renameFlp error:: ", err_52);
7804
7379
  return [3, 4];
7805
7380
  case 4: return [2, {
7806
7381
  instructions: __spreadArray([], instructions, true),
@@ -7810,7 +7385,7 @@ var PerpetualsClient = (function () {
7810
7385
  });
7811
7386
  }); };
7812
7387
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7813
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_59;
7388
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7814
7389
  return __generator(this, function (_a) {
7815
7390
  switch (_a.label) {
7816
7391
  case 0:
@@ -7848,9 +7423,9 @@ var PerpetualsClient = (function () {
7848
7423
  instructions.push(initStakeInstruction);
7849
7424
  return [3, 4];
7850
7425
  case 3:
7851
- err_59 = _a.sent();
7852
- console.log("perpClient InitStaking error:: ", err_59);
7853
- throw err_59;
7426
+ err_53 = _a.sent();
7427
+ console.log("perpClient InitStaking error:: ", err_53);
7428
+ throw err_53;
7854
7429
  case 4: return [2, {
7855
7430
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7856
7431
  additionalSigners: additionalSigners
@@ -7859,7 +7434,7 @@ var PerpetualsClient = (function () {
7859
7434
  });
7860
7435
  }); };
7861
7436
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7862
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_60;
7437
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7863
7438
  return __generator(this, function (_a) {
7864
7439
  switch (_a.label) {
7865
7440
  case 0:
@@ -7888,7 +7463,6 @@ var PerpetualsClient = (function () {
7888
7463
  transferAuthority: poolConfig.transferAuthority,
7889
7464
  perpetuals: this.perpetuals.publicKey,
7890
7465
  pool: poolConfig.poolAddress,
7891
- custody: rewardCustodyConfig.custodyAccount,
7892
7466
  lpTokenMint: poolConfig.stakedLpTokenMint,
7893
7467
  compoundingVault: compoundingVault,
7894
7468
  compoundingTokenMint: compoundingTokenMint,
@@ -7904,9 +7478,9 @@ var PerpetualsClient = (function () {
7904
7478
  instructions.push(initCompoundingInstruction);
7905
7479
  return [3, 4];
7906
7480
  case 3:
7907
- err_60 = _a.sent();
7908
- console.log("perpClient initCompounding error:: ", err_60);
7909
- throw err_60;
7481
+ err_54 = _a.sent();
7482
+ console.log("perpClient initCompounding error:: ", err_54);
7483
+ throw err_54;
7910
7484
  case 4: return [2, {
7911
7485
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7912
7486
  additionalSigners: additionalSigners
@@ -7915,7 +7489,7 @@ var PerpetualsClient = (function () {
7915
7489
  });
7916
7490
  }); };
7917
7491
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7918
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_61;
7492
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7919
7493
  return __generator(this, function (_a) {
7920
7494
  switch (_a.label) {
7921
7495
  case 0:
@@ -7956,9 +7530,9 @@ var PerpetualsClient = (function () {
7956
7530
  instructions.push(initTokenVaultInstruction);
7957
7531
  return [3, 4];
7958
7532
  case 3:
7959
- err_61 = _a.sent();
7960
- console.log("perpClient InitTokenVaultInstruction error:: ", err_61);
7961
- throw err_61;
7533
+ err_55 = _a.sent();
7534
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7535
+ throw err_55;
7962
7536
  case 4: return [2, {
7963
7537
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7964
7538
  additionalSigners: additionalSigners
@@ -7967,7 +7541,7 @@ var PerpetualsClient = (function () {
7967
7541
  });
7968
7542
  }); };
7969
7543
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7970
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_62;
7544
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7971
7545
  return __generator(this, function (_a) {
7972
7546
  switch (_a.label) {
7973
7547
  case 0:
@@ -7998,9 +7572,9 @@ var PerpetualsClient = (function () {
7998
7572
  instructions.push(setTokenVaultConfigInstruction);
7999
7573
  return [3, 4];
8000
7574
  case 3:
8001
- err_62 = _a.sent();
8002
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_62);
8003
- throw err_62;
7575
+ err_56 = _a.sent();
7576
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7577
+ throw err_56;
8004
7578
  case 4: return [2, {
8005
7579
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8006
7580
  additionalSigners: additionalSigners
@@ -8009,7 +7583,7 @@ var PerpetualsClient = (function () {
8009
7583
  });
8010
7584
  }); };
8011
7585
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8012
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_63;
7586
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
8013
7587
  return __generator(this, function (_a) {
8014
7588
  switch (_a.label) {
8015
7589
  case 0:
@@ -8048,9 +7622,59 @@ var PerpetualsClient = (function () {
8048
7622
  instructions.push(withdrawInstantFeeInstruction);
8049
7623
  return [3, 6];
8050
7624
  case 5:
8051
- err_63 = _a.sent();
8052
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_63);
8053
- throw err_63;
7625
+ err_57 = _a.sent();
7626
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7627
+ throw err_57;
7628
+ case 6: return [2, {
7629
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7630
+ additionalSigners: additionalSigners
7631
+ }];
7632
+ }
7633
+ });
7634
+ }); };
7635
+ this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7636
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7637
+ return __generator(this, function (_a) {
7638
+ switch (_a.label) {
7639
+ case 0:
7640
+ publicKey = this.provider.wallet.publicKey;
7641
+ preInstructions = [];
7642
+ instructions = [];
7643
+ postInstructions = [];
7644
+ additionalSigners = [];
7645
+ _a.label = 1;
7646
+ case 1:
7647
+ _a.trys.push([1, 5, , 6]);
7648
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, publicKey, true)];
7649
+ case 2:
7650
+ receivingTokenAccount = _a.sent();
7651
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
7652
+ case 3:
7653
+ if (!(_a.sent())) {
7654
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, poolConfig.tokenMint));
7655
+ }
7656
+ return [4, this.program.methods
7657
+ .withdrawUnclaimedTokens({})
7658
+ .accounts({
7659
+ admin: publicKey,
7660
+ multisig: this.multisig.publicKey,
7661
+ perpetuals: this.perpetuals.publicKey,
7662
+ transferAuthority: poolConfig.transferAuthority,
7663
+ tokenVault: poolConfig.tokenVault,
7664
+ tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
7665
+ receivingTokenAccount: receivingTokenAccount,
7666
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7667
+ receivingTokenMint: poolConfig.tokenMint,
7668
+ })
7669
+ .instruction()];
7670
+ case 4:
7671
+ withdrawUnclaimedTokensInstruction = _a.sent();
7672
+ instructions.push(withdrawUnclaimedTokensInstruction);
7673
+ return [3, 6];
7674
+ case 5:
7675
+ err_58 = _a.sent();
7676
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7677
+ throw err_58;
8054
7678
  case 6: return [2, {
8055
7679
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8056
7680
  additionalSigners: additionalSigners
@@ -8059,7 +7683,7 @@ var PerpetualsClient = (function () {
8059
7683
  });
8060
7684
  }); };
8061
7685
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8062
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_64;
7686
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
8063
7687
  return __generator(this, function (_a) {
8064
7688
  switch (_a.label) {
8065
7689
  case 0:
@@ -8096,9 +7720,55 @@ var PerpetualsClient = (function () {
8096
7720
  instructions.push(initRevenueTokenAccountInstruction);
8097
7721
  return [3, 4];
8098
7722
  case 3:
8099
- err_64 = _a.sent();
8100
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_64);
8101
- throw err_64;
7723
+ err_59 = _a.sent();
7724
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7725
+ throw err_59;
7726
+ case 4: return [2, {
7727
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7728
+ additionalSigners: additionalSigners
7729
+ }];
7730
+ }
7731
+ });
7732
+ }); };
7733
+ this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7734
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7735
+ return __generator(this, function (_a) {
7736
+ switch (_a.label) {
7737
+ case 0:
7738
+ publicKey = this.provider.wallet.publicKey;
7739
+ preInstructions = [];
7740
+ instructions = [];
7741
+ postInstructions = [];
7742
+ additionalSigners = [];
7743
+ _a.label = 1;
7744
+ case 1:
7745
+ _a.trys.push([1, 3, , 4]);
7746
+ rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7747
+ return [4, this.program.methods
7748
+ .initRebateVault({
7749
+ allowRebatePayout: allowRebatePayout
7750
+ })
7751
+ .accounts({
7752
+ admin: publicKey,
7753
+ multisig: this.multisig.publicKey,
7754
+ transferAuthority: poolConfig.transferAuthority,
7755
+ perpetuals: this.perpetuals.publicKey,
7756
+ rebateMint: rebateCustodyMint,
7757
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
7758
+ rebateVault: poolConfig.rebateVault,
7759
+ systemProgram: web3_js_1.SystemProgram.programId,
7760
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7761
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
7762
+ })
7763
+ .instruction()];
7764
+ case 2:
7765
+ initRebateVaultInstruction = _a.sent();
7766
+ instructions.push(initRebateVaultInstruction);
7767
+ return [3, 4];
7768
+ case 3:
7769
+ err_60 = _a.sent();
7770
+ console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7771
+ throw err_60;
8102
7772
  case 4: return [2, {
8103
7773
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8104
7774
  additionalSigners: additionalSigners
@@ -8107,7 +7777,7 @@ var PerpetualsClient = (function () {
8107
7777
  });
8108
7778
  }); };
8109
7779
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8110
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_65;
7780
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
8111
7781
  return __generator(this, function (_a) {
8112
7782
  switch (_a.label) {
8113
7783
  case 0:
@@ -8146,9 +7816,9 @@ var PerpetualsClient = (function () {
8146
7816
  instructions.push(distributeTokenRewardInstruction);
8147
7817
  return [3, 4];
8148
7818
  case 3:
8149
- err_65 = _a.sent();
8150
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_65);
8151
- throw err_65;
7819
+ err_61 = _a.sent();
7820
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7821
+ throw err_61;
8152
7822
  case 4: return [2, {
8153
7823
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8154
7824
  additionalSigners: additionalSigners
@@ -8157,7 +7827,7 @@ var PerpetualsClient = (function () {
8157
7827
  });
8158
7828
  }); };
8159
7829
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
8160
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_66;
7830
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
8161
7831
  return __generator(this, function (_a) {
8162
7832
  switch (_a.label) {
8163
7833
  case 0:
@@ -8185,9 +7855,9 @@ var PerpetualsClient = (function () {
8185
7855
  instructions.push(setTokenStakeLevelInstruction);
8186
7856
  return [3, 4];
8187
7857
  case 3:
8188
- err_66 = _a.sent();
8189
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_66);
8190
- throw err_66;
7858
+ err_62 = _a.sent();
7859
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7860
+ throw err_62;
8191
7861
  case 4: return [2, {
8192
7862
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8193
7863
  additionalSigners: additionalSigners
@@ -8196,7 +7866,7 @@ var PerpetualsClient = (function () {
8196
7866
  });
8197
7867
  }); };
8198
7868
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8199
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_67;
7869
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8200
7870
  return __generator(this, function (_a) {
8201
7871
  switch (_a.label) {
8202
7872
  case 0:
@@ -8228,9 +7898,9 @@ var PerpetualsClient = (function () {
8228
7898
  instructions.push(setTokenRewardInstruction);
8229
7899
  return [3, 4];
8230
7900
  case 3:
8231
- err_67 = _a.sent();
8232
- console.log("perpClient setTokenRewardInstruction error:: ", err_67);
8233
- throw err_67;
7901
+ err_63 = _a.sent();
7902
+ console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7903
+ throw err_63;
8234
7904
  case 4: return [2, {
8235
7905
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8236
7906
  additionalSigners: additionalSigners
@@ -8239,7 +7909,7 @@ var PerpetualsClient = (function () {
8239
7909
  });
8240
7910
  }); };
8241
7911
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
8242
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_68;
7912
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8243
7913
  return __generator(this, function (_a) {
8244
7914
  switch (_a.label) {
8245
7915
  case 0:
@@ -8268,9 +7938,9 @@ var PerpetualsClient = (function () {
8268
7938
  instructions.push(resizeInternalOracleInstruction);
8269
7939
  return [3, 4];
8270
7940
  case 3:
8271
- err_68 = _a.sent();
8272
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_68);
8273
- throw err_68;
7941
+ err_64 = _a.sent();
7942
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7943
+ throw err_64;
8274
7944
  case 4: return [2, {
8275
7945
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8276
7946
  additionalSigners: additionalSigners