flash-sdk 9.0.5-alpha.8 → 9.1.0-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.
@@ -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,42 +642,24 @@ var PerpetualsClient = (function () {
638
642
  var averageEntryPrice = totalValue.div(totalSize);
639
643
  return averageEntryPrice;
640
644
  };
641
- this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
642
- var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
643
- var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
644
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
645
- var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
646
- var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
647
- var currentMarginUsd = constants_1.BN_ZERO;
648
- if (isInitial) {
649
- currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
650
- }
651
- else {
652
- currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
653
- }
654
- if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
655
- return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
645
+ this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
646
+ var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
647
+ var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
648
+ if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
649
+ return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
656
650
  }
657
651
  else {
658
652
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
659
653
  }
660
654
  };
661
- this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
662
- positionAccount = positionAccount.clone();
663
- positionAccount.sizeUsd = finalSizeUsd;
664
- positionAccount.sizeAmount = targetPrice.getTokenAmount(finalSizeUsd, targetCustodyAccount.decimals);
665
- positionAccount.collateralUsd = finalCollateralUsd;
666
- return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
667
- };
668
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd, enableDebuglogs) {
669
- if (enableDebuglogs === void 0) { enableDebuglogs = false; }
655
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
670
656
  var finalCollateralAmount = constants_1.BN_ZERO;
671
657
  if (!inputDeltaAmount.isZero()) {
672
658
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
673
659
  finalCollateralAmount = inputDeltaAmount;
674
660
  }
675
661
  else {
676
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
662
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
677
663
  finalCollateralAmount = swapAmountOut;
678
664
  }
679
665
  }
@@ -699,13 +685,11 @@ var PerpetualsClient = (function () {
699
685
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
700
686
  }
701
687
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
702
- var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals).add(positionAccount.collateralUsd);
703
- var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
688
+ var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
689
+ var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
690
+ var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
704
691
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
705
692
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
706
- if (enableDebuglogs) {
707
- 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());
708
- }
709
693
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
710
694
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
711
695
  }
@@ -713,9 +697,8 @@ var PerpetualsClient = (function () {
713
697
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
714
698
  }
715
699
  };
716
- this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
700
+ this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
717
701
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
718
- if (enableLogs === void 0) { enableLogs = false; }
719
702
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
720
703
  throw new Error("Delta Amounts cannot be negative.");
721
704
  }
@@ -742,13 +725,75 @@ var PerpetualsClient = (function () {
742
725
  var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
743
726
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
744
727
  }
745
- var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
746
- var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
747
- positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
728
+ positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
748
729
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
749
- var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
750
- var liquidationPrice = _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
730
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
731
+ var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
732
+ var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
733
+ var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
734
+ var feeUsd = constants_1.BN_ZERO;
735
+ var feeAmount = constants_1.BN_ZERO;
736
+ var feeUsdAfterDiscount = constants_1.BN_ZERO;
737
+ var feeAmountAfterDiscount = constants_1.BN_ZERO;
738
+ if (positionAccount !== null && sizeDeltaAmount.isZero()) {
739
+ }
740
+ else {
741
+ feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
742
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
+ if (discountBps.gt(constants_1.BN_ZERO)) {
744
+ feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
745
+ feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
746
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
747
+ }
748
+ else {
749
+ feeUsdAfterDiscount = feeUsd;
750
+ feeAmountAfterDiscount = feeAmount;
751
+ }
752
+ }
753
+ return {
754
+ entryOraclePrice: entryOraclePrice,
755
+ feeUsd: feeUsd,
756
+ feeAmount: feeAmount,
757
+ feeUsdAfterDiscount: feeUsdAfterDiscount,
758
+ feeAmountAfterDiscount: feeAmountAfterDiscount,
759
+ liquidationPrice: liquidationPrice
760
+ };
761
+ };
762
+ this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
763
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
764
+ if (enableLogs === void 0) { enableLogs = false; }
765
+ if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
766
+ throw new Error("Delta Amounts cannot be negative.");
767
+ }
768
+ var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
769
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
770
+ if (positionAccount === null) {
771
+ var data = __assign({}, types_1.DEFAULT_POSITION);
772
+ positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
773
+ var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
774
+ positionAccount.sizeUsd = sizeUsd_2;
775
+ positionAccount.sizeDecimals = targetCustodyAccount.decimals;
776
+ positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
777
+ positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
778
+ }
779
+ else {
780
+ positionAccount = positionAccount.clone();
781
+ var positionEntryPrice = OraclePrice_1.OraclePrice.from({
782
+ price: positionAccount.entryPrice.price,
783
+ exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
784
+ confidence: constants_1.BN_ZERO,
785
+ timestamp: constants_1.BN_ZERO
786
+ });
787
+ entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
788
+ var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
789
+ positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
790
+ }
791
+ positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
792
+ positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
793
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
794
+ var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
751
795
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
796
+ var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
752
797
  var feeUsd = constants_1.BN_ZERO;
753
798
  var feeAmount = constants_1.BN_ZERO;
754
799
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -757,11 +802,11 @@ var PerpetualsClient = (function () {
757
802
  }
758
803
  else {
759
804
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
760
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
805
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
761
806
  if (discountBps.gt(constants_1.BN_ZERO)) {
762
807
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
763
808
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
764
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
809
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
765
810
  }
766
811
  else {
767
812
  feeUsdAfterDiscount = feeUsd;
@@ -820,26 +865,25 @@ var PerpetualsClient = (function () {
820
865
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
821
866
  throw new Error("Delta Amounts cannot be negative ");
822
867
  }
868
+ resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
869
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
823
870
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
824
871
  throw new Error("cannot remove/close more than collateral/Size");
825
872
  }
826
873
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
827
874
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
828
- var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
829
- var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
830
- resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
831
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
875
+ var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
832
876
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
833
- var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
877
+ var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
834
878
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
835
879
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
836
- var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
880
+ var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
837
881
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
838
882
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
839
883
  if (discountBps.gt(constants_1.BN_ZERO)) {
840
884
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
841
885
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
842
- exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
886
+ exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
843
887
  }
844
888
  else {
845
889
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -849,7 +893,7 @@ var PerpetualsClient = (function () {
849
893
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
850
894
  });
851
895
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
852
- var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
896
+ var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
853
897
  return {
854
898
  exitOraclePrice: exitOraclePrice,
855
899
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -862,11 +906,13 @@ var PerpetualsClient = (function () {
862
906
  };
863
907
  };
864
908
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
865
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
909
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
910
+ ||
911
+ sizeUsd.isZero()) {
866
912
  return constants_1.BN_ZERO;
867
913
  }
868
914
  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)))))
869
- .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
915
+ .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
870
916
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
871
917
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
872
918
  return finalSpread;
@@ -881,11 +927,21 @@ var PerpetualsClient = (function () {
881
927
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
882
928
  return exitOraclePrice;
883
929
  };
930
+ this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
931
+ var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
932
+ if ((0, types_1.isVariant)(side, 'long')) {
933
+ return minPrice;
934
+ }
935
+ else {
936
+ return maxPrice;
937
+ }
938
+ };
884
939
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
885
940
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
886
941
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
887
942
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
888
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
943
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
944
+ .multipliedBy(collateralTokenMinPriceUi);
889
945
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
890
946
  if (!discountBps.isZero()) {
891
947
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -893,20 +949,20 @@ var PerpetualsClient = (function () {
893
949
  }
894
950
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
895
951
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
896
- var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
897
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
952
+ var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
953
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
898
954
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
899
955
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
900
956
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
901
957
  };
902
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
958
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
903
959
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
904
960
  var finalCollateralAmount = constants_1.BN_ZERO;
905
961
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
906
962
  finalCollateralAmount = amountIn;
907
963
  }
908
964
  else {
909
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
965
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
910
966
  finalCollateralAmount = swapAmountOut;
911
967
  }
912
968
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -920,8 +976,8 @@ var PerpetualsClient = (function () {
920
976
  }
921
977
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
922
978
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
923
- var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
924
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
979
+ var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
980
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
925
981
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
926
982
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
927
983
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -944,7 +1000,7 @@ var PerpetualsClient = (function () {
944
1000
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
945
1001
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
946
1002
  };
947
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1003
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
948
1004
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
949
1005
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
950
1006
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -961,11 +1017,11 @@ var PerpetualsClient = (function () {
961
1017
  collateralInInputToken = collateralAmountWithFee;
962
1018
  }
963
1019
  else {
964
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1020
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
965
1021
  }
966
1022
  return collateralInInputToken;
967
1023
  };
968
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1024
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
969
1025
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
970
1026
  if (debugLogs === void 0) { debugLogs = false; }
971
1027
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -987,9 +1043,10 @@ var PerpetualsClient = (function () {
987
1043
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
988
1044
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
989
1045
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
990
- positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
991
- positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
992
1046
  positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1047
+ positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1048
+ positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1049
+ positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
993
1050
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
994
1051
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
995
1052
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -999,37 +1056,30 @@ var PerpetualsClient = (function () {
999
1056
  }
1000
1057
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1001
1058
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1002
- var currentCollateralUsd = positionDelta.collateralUsd;
1059
+ var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1003
1060
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1004
- var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1061
+ var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1062
+ var closeAmount, feesAmount;
1005
1063
  if (debugLogs) {
1006
1064
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1007
1065
  }
1008
- var closeAmountUsd, feesAmountUsd;
1009
1066
  if (assetsUsd.gte(liabilityUsd)) {
1010
- closeAmountUsd = assetsUsd.sub(liabilityUsd);
1011
- feesAmountUsd = totalFeesUsd;
1012
- }
1013
- else {
1014
- closeAmountUsd = constants_1.BN_ZERO;
1015
- feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1016
- }
1017
- var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1018
- var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1019
- if (newLockAmount.gt(positionDelta.lockedAmount)) {
1020
- positionDelta.lockedAmount = constants_1.BN_ZERO;
1067
+ closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1068
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1021
1069
  }
1022
1070
  else {
1023
- positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1071
+ closeAmount = constants_1.BN_ZERO;
1072
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1024
1073
  }
1025
1074
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1026
1075
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1027
1076
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1077
+ newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1028
1078
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1029
- newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1079
+ newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1030
1080
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1081
+ newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1031
1082
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1032
- newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
1033
1083
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1034
1084
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1035
1085
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1043,30 +1093,29 @@ var PerpetualsClient = (function () {
1043
1093
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1044
1094
  if (keepLevSame) {
1045
1095
  var collateralAmountReceived = closeAmount;
1046
- var collateralAmountReceivedUsd = closeAmountUsd;
1047
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1096
+ var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1097
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1048
1098
  if (debugLogs) {
1049
1099
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1050
1100
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1051
1101
  }
1052
- if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1102
+ if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1053
1103
  collateralAmountReceived = constants_1.BN_ZERO;
1054
- collateralAmountReceivedUsd = constants_1.BN_ZERO;
1104
+ collateralAmountRecievedUsd = constants_1.BN_ZERO;
1055
1105
  }
1056
- else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1106
+ else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1057
1107
  if (debugLogs) {
1058
1108
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1059
1109
  }
1060
1110
  collateralAmountReceived = maxWithdrawableAmount;
1061
- collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1111
+ collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1062
1112
  }
1063
1113
  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 });
1064
- newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1065
- var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1066
- var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1114
+ var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1115
+ var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1067
1116
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1068
1117
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1069
- var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1118
+ var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1070
1119
  return {
1071
1120
  newSizeUsd: newPosition.sizeUsd,
1072
1121
  feeUsd: feeUsd,
@@ -1074,9 +1123,8 @@ var PerpetualsClient = (function () {
1074
1123
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1075
1124
  newLev: newLev,
1076
1125
  liquidationPrice: finalLiquidationPrice,
1077
- collateralAmountReceived: collateralAmountReceived,
1078
- collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1079
- newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1126
+ collateralAmountRecieved: collateralAmountReceived,
1127
+ newCollateralAmount: newPosition.collateralAmount.add(diff),
1080
1128
  newPnl: finalPnlUsd
1081
1129
  };
1082
1130
  }
@@ -1084,7 +1132,8 @@ var PerpetualsClient = (function () {
1084
1132
  throw "only same leverage is supported for now";
1085
1133
  }
1086
1134
  };
1087
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1135
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1136
+ if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1088
1137
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1089
1138
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1090
1139
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1093,87 +1142,61 @@ var PerpetualsClient = (function () {
1093
1142
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1094
1143
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1095
1144
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1096
- var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1145
+ var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1097
1146
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1098
1147
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1099
1148
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1149
+ var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1100
1150
  var availableInitMarginUsd = constants_1.BN_ZERO;
1101
- if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1102
- availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1151
+ if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1152
+ availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1103
1153
  }
1104
1154
  else {
1105
1155
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1106
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1156
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1107
1157
  }
1108
1158
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1109
1159
  if (maxRemovableCollateralUsd.isNeg()) {
1110
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1160
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1111
1161
  }
1112
1162
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1113
- var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1114
- var diffUsd = constants_1.BN_ZERO;
1163
+ var diff = constants_1.BN_ZERO;
1115
1164
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1116
1165
  var isDegenMode = positionAccount.isDegenMode();
1117
1166
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1118
- diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1119
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1167
+ diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1168
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1120
1169
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1121
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1170
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1122
1171
  }
1123
1172
  else {
1124
- maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1125
- maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1173
+ maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1126
1174
  }
1127
1175
  }
1128
1176
  else {
1129
- maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1130
- maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1177
+ maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1131
1178
  }
1132
- return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1179
+ return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1133
1180
  };
1134
- this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1181
+ this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1135
1182
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1136
1183
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1184
+ var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1137
1185
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1138
1186
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1139
1187
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1140
1188
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1141
- var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1142
- var closeAmountUsd, feesAmountUsd;
1189
+ var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1190
+ var closeAmount, feesAmount;
1143
1191
  if (assetsUsd.gt(liabilityUsd)) {
1144
- closeAmountUsd = assetsUsd.sub(liabilityUsd);
1145
- feesAmountUsd = totalFeesUsd;
1192
+ closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1193
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1146
1194
  }
1147
1195
  else {
1148
- closeAmountUsd = constants_1.BN_ZERO;
1149
- feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1196
+ closeAmount = constants_1.BN_ZERO;
1197
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1150
1198
  }
1151
- return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1152
- };
1153
- this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1154
- if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1155
- if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1156
- throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1157
- }
1158
- var rawMinInitLev = positionAccount.isDegenMode()
1159
- ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1160
- : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1161
- var MIN_INIT_LEVERAGE = rawMinInitLev
1162
- .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1163
- .div(new anchor_1.BN(100));
1164
- var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1165
- .muln(constants_1.BPS_POWER)
1166
- .div(MIN_INIT_LEVERAGE);
1167
- var currentCollateralUsd = positionAccount.collateralUsd;
1168
- var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1169
- ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1170
- : constants_1.BN_ZERO;
1171
- var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1172
- var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1173
- return {
1174
- maxAddableAmount: maxAddableAmount,
1175
- maxAddableAmountUsd: maxAddableCollateralUsd,
1176
- };
1199
+ return { closeAmount: closeAmount, feesAmount: feesAmount };
1177
1200
  };
1178
1201
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1179
1202
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1186,37 +1209,34 @@ var PerpetualsClient = (function () {
1186
1209
  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)));
1187
1210
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1188
1211
  console.log("THIS cannot happen but still");
1189
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1212
+ return constants_1.BN_ZERO;
1190
1213
  }
1191
1214
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1192
- var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1215
+ var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1193
1216
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1194
1217
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1195
1218
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1196
- var currentCollateralUsd = positionAccount.collateralUsd;
1219
+ var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1197
1220
  var availableInitMarginUsd = constants_1.BN_ZERO;
1198
1221
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1199
1222
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1200
1223
  }
1201
1224
  else {
1202
1225
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1203
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1226
+ return constants_1.BN_ZERO;
1204
1227
  }
1205
1228
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1206
1229
  if (maxRemovableCollateralUsd.isNeg()) {
1207
- return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1230
+ return constants_1.BN_ZERO;
1208
1231
  }
1209
1232
  var maxWithdrawableAmount;
1210
- var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1211
1233
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1212
- maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1213
- maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1234
+ maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1214
1235
  }
1215
1236
  else {
1216
- maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1217
- maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1237
+ maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1218
1238
  }
1219
- return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1239
+ return maxWithdrawableAmount;
1220
1240
  };
1221
1241
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1222
1242
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1254,12 +1274,12 @@ var PerpetualsClient = (function () {
1254
1274
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1255
1275
  var lockFeeUsd = constants_1.BN_ZERO;
1256
1276
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1257
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1277
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1258
1278
  }
1259
1279
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1260
1280
  return lockFeeUsd;
1261
1281
  };
1262
- this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1282
+ this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1263
1283
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1264
1284
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1265
1285
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1267,146 +1287,193 @@ var PerpetualsClient = (function () {
1267
1287
  else {
1268
1288
  maxPayOffBpsNew = maxPayOffBps;
1269
1289
  }
1270
- var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1290
+ var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1271
1291
  return lockedUsd;
1272
1292
  };
1273
- this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1293
+ this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1274
1294
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1275
1295
  price: constants_1.BN_ZERO,
1276
1296
  exponent: constants_1.BN_ZERO,
1277
1297
  confidence: constants_1.BN_ZERO,
1278
1298
  timestamp: constants_1.BN_ZERO
1279
1299
  });
1300
+ if (collateralAmount.isZero() || sizeAmount.isZero()) {
1301
+ return zeroOraclePrice;
1302
+ }
1280
1303
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1281
1304
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1282
1305
  }
1283
1306
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1284
1307
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1285
1308
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1309
+ var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1310
+ var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1286
1311
  var liquidationPrice;
1287
- if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1288
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1289
- price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1290
- .div(positionAccount.sizeAmount),
1291
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1292
- confidence: constants_1.BN_ZERO,
1293
- timestamp: constants_1.BN_ZERO
1294
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1295
- if ((0, types_1.isVariant)(side, 'long')) {
1296
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1297
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1298
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1299
- confidence: constants_1.BN_ZERO,
1300
- timestamp: constants_1.BN_ZERO
1301
- });
1312
+ if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1313
+ var newCollateralAmount = void 0;
1314
+ if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1315
+ newCollateralAmount = collateralAmount;
1302
1316
  }
1303
1317
  else {
1304
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1305
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1306
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1307
- confidence: constants_1.BN_ZERO,
1308
- timestamp: constants_1.BN_ZERO
1309
- });
1318
+ var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1319
+ var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1320
+ newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1310
1321
  }
1311
- }
1312
- else {
1313
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1314
- price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1315
- .div(positionAccount.sizeAmount),
1322
+ var lp = OraclePrice_1.OraclePrice.from({
1323
+ price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1324
+ .div(sizeAmount.add(newCollateralAmount)),
1316
1325
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1317
1326
  confidence: constants_1.BN_ZERO,
1318
1327
  timestamp: constants_1.BN_ZERO
1319
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1320
- if ((0, types_1.isVariant)(side, 'long')) {
1321
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1322
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1323
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1328
+ });
1329
+ liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1330
+ }
1331
+ else {
1332
+ var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1333
+ if (assetsUsd.gte(liablitiesUsd)) {
1334
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1335
+ price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1336
+ .div(positionAccount.sizeAmount),
1337
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1324
1338
  confidence: constants_1.BN_ZERO,
1325
1339
  timestamp: constants_1.BN_ZERO
1326
- });
1340
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1341
+ if ((0, types_1.isVariant)(side, 'long')) {
1342
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1343
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1344
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1345
+ confidence: constants_1.BN_ZERO,
1346
+ timestamp: constants_1.BN_ZERO
1347
+ });
1348
+ }
1349
+ else {
1350
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1351
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1352
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1353
+ confidence: constants_1.BN_ZERO,
1354
+ timestamp: constants_1.BN_ZERO
1355
+ });
1356
+ }
1327
1357
  }
1328
1358
  else {
1329
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1330
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1331
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1359
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1360
+ price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1361
+ .div(positionAccount.sizeAmount),
1362
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1332
1363
  confidence: constants_1.BN_ZERO,
1333
1364
  timestamp: constants_1.BN_ZERO
1334
- });
1365
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1366
+ if ((0, types_1.isVariant)(side, 'long')) {
1367
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1368
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1369
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1370
+ confidence: constants_1.BN_ZERO,
1371
+ timestamp: constants_1.BN_ZERO
1372
+ });
1373
+ }
1374
+ else {
1375
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1376
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1377
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1378
+ confidence: constants_1.BN_ZERO,
1379
+ timestamp: constants_1.BN_ZERO
1380
+ });
1381
+ }
1335
1382
  }
1336
1383
  }
1337
1384
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1338
1385
  };
1339
- this.getLiquidationPriceSync = function (collateralUsd, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetPrice, targetCustodyAccount, positionAccount) {
1340
- var newPositionAccount = positionAccount.clone();
1341
- newPositionAccount.sizeAmount = sizeAmount;
1342
- newPositionAccount.sizeUsd = targetPrice.getAssetAmountUsd(sizeAmount, targetCustodyAccount.decimals);
1343
- newPositionAccount.collateralUsd = collateralUsd;
1344
- return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1345
- };
1346
- this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1386
+ this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1347
1387
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1348
1388
  price: constants_1.BN_ZERO,
1349
1389
  exponent: constants_1.BN_ZERO,
1350
1390
  confidence: constants_1.BN_ZERO,
1351
1391
  timestamp: constants_1.BN_ZERO
1352
1392
  });
1393
+ if (collateralAmount.isZero() || sizeAmount.isZero()) {
1394
+ return zeroOraclePrice;
1395
+ }
1353
1396
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1354
1397
  var unsettledLossUsd = exitFeeUsd;
1355
1398
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1399
+ var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1400
+ var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1356
1401
  var liquidationPrice;
1357
- if (collateralUsd.gte(liablitiesUsd)) {
1358
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1359
- price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1360
- .div(sizeAmount),
1361
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1362
- confidence: constants_1.BN_ZERO,
1363
- timestamp: constants_1.BN_ZERO
1364
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1365
- if ((0, types_1.isVariant)(side, 'long')) {
1366
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1367
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1368
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1369
- confidence: constants_1.BN_ZERO,
1370
- timestamp: constants_1.BN_ZERO
1371
- });
1402
+ if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1403
+ var newCollateralAmount = void 0;
1404
+ if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1405
+ newCollateralAmount = collateralAmount;
1372
1406
  }
1373
1407
  else {
1374
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1375
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1376
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1377
- confidence: constants_1.BN_ZERO,
1378
- timestamp: constants_1.BN_ZERO
1379
- });
1408
+ var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1409
+ var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1410
+ newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1380
1411
  }
1381
- }
1382
- else {
1383
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1384
- price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1385
- .div(sizeAmount),
1412
+ var lp = OraclePrice_1.OraclePrice.from({
1413
+ price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1414
+ .div(sizeAmount.add(newCollateralAmount)),
1386
1415
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1387
1416
  confidence: constants_1.BN_ZERO,
1388
1417
  timestamp: constants_1.BN_ZERO
1389
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1390
- if ((0, types_1.isVariant)(side, 'long')) {
1391
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1392
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1393
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1418
+ });
1419
+ liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1420
+ }
1421
+ else {
1422
+ var assetsUsd = collateralUsd;
1423
+ if (assetsUsd.gte(liablitiesUsd)) {
1424
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1425
+ price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1426
+ .div(sizeAmount),
1427
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1394
1428
  confidence: constants_1.BN_ZERO,
1395
1429
  timestamp: constants_1.BN_ZERO
1396
- });
1430
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1431
+ if ((0, types_1.isVariant)(side, 'long')) {
1432
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1433
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1434
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1435
+ confidence: constants_1.BN_ZERO,
1436
+ timestamp: constants_1.BN_ZERO
1437
+ });
1438
+ }
1439
+ else {
1440
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1441
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1442
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1443
+ confidence: constants_1.BN_ZERO,
1444
+ timestamp: constants_1.BN_ZERO
1445
+ });
1446
+ }
1397
1447
  }
1398
1448
  else {
1399
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1400
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1401
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1449
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1450
+ price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1451
+ .div(sizeAmount),
1452
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1402
1453
  confidence: constants_1.BN_ZERO,
1403
1454
  timestamp: constants_1.BN_ZERO
1404
- });
1455
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1456
+ if ((0, types_1.isVariant)(side, 'long')) {
1457
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1458
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1459
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1460
+ confidence: constants_1.BN_ZERO,
1461
+ timestamp: constants_1.BN_ZERO
1462
+ });
1463
+ }
1464
+ else {
1465
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1466
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1467
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1468
+ confidence: constants_1.BN_ZERO,
1469
+ timestamp: constants_1.BN_ZERO
1470
+ });
1471
+ }
1405
1472
  }
1406
1473
  }
1407
1474
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1408
1475
  };
1409
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1476
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1410
1477
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1411
1478
  price: constants_1.BN_ZERO,
1412
1479
  exponent: constants_1.BN_ZERO,
@@ -1417,7 +1484,7 @@ var PerpetualsClient = (function () {
1417
1484
  return zeroOraclePrice;
1418
1485
  }
1419
1486
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1420
- price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1487
+ price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1421
1488
  .div(positionAccount.sizeAmount),
1422
1489
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1423
1490
  confidence: constants_1.BN_ZERO,
@@ -1445,7 +1512,7 @@ var PerpetualsClient = (function () {
1445
1512
  }
1446
1513
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1447
1514
  };
1448
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1515
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1449
1516
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1450
1517
  throw new Error("Delta Amounts cannot be negative.");
1451
1518
  }
@@ -1475,9 +1542,10 @@ var PerpetualsClient = (function () {
1475
1542
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1476
1543
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1477
1544
  positionAccount.market = marketAccountPk;
1478
- var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1479
- positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1480
- positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1545
+ positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1546
+ positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1547
+ positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1548
+ positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1481
1549
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1482
1550
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1483
1551
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1549,9 +1617,6 @@ var PerpetualsClient = (function () {
1549
1617
  });
1550
1618
  };
1551
1619
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1552
- return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1553
- };
1554
- this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1555
1620
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1556
1621
  return {
1557
1622
  profitUsd: constants_1.BN_ZERO,
@@ -1610,7 +1675,7 @@ var PerpetualsClient = (function () {
1610
1675
  }
1611
1676
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1612
1677
  return {
1613
- profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1678
+ profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1614
1679
  lossUsd: constants_1.BN_ZERO,
1615
1680
  };
1616
1681
  }
@@ -1701,9 +1766,6 @@ var PerpetualsClient = (function () {
1701
1766
  }
1702
1767
  };
1703
1768
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1704
- return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1705
- };
1706
- this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1707
1769
  var poolAmountUsd = constants_1.BN_ZERO;
1708
1770
  for (var index = 0; index < custodies.length; index++) {
1709
1771
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1716,7 +1778,6 @@ var PerpetualsClient = (function () {
1716
1778
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1717
1779
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1718
1780
  }
1719
- poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1720
1781
  if (aumCalcMode === "includePnl") {
1721
1782
  var poolEquityUsd = poolAmountUsd;
1722
1783
  for (var index = 0; index < markets.length; index++) {
@@ -1726,12 +1787,11 @@ var PerpetualsClient = (function () {
1726
1787
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1727
1788
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1728
1789
  var position = markets[index].getCollectivePosition();
1729
- poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1730
1790
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1731
1791
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1732
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1733
- var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1734
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1792
+ var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1793
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1794
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1735
1795
  }
1736
1796
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1737
1797
  }
@@ -1739,6 +1799,14 @@ var PerpetualsClient = (function () {
1739
1799
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1740
1800
  }
1741
1801
  };
1802
+ this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1803
+ if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1804
+ return { discountBn: constants_1.BN_ZERO };
1805
+ }
1806
+ else {
1807
+ return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1808
+ }
1809
+ };
1742
1810
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1743
1811
  if (tokenStakeAccount.level === 0) {
1744
1812
  return { discountBn: constants_1.BN_ZERO };
@@ -2001,14 +2069,6 @@ var PerpetualsClient = (function () {
2001
2069
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2002
2070
  case 4:
2003
2071
  result = _f.sent();
2004
- if (result.value.err) {
2005
- console.error('error Simulation failed:::', result);
2006
- return [2, {
2007
- amount: undefined,
2008
- fee: undefined,
2009
- error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2010
- }];
2011
- }
2012
2072
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2013
2073
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2014
2074
  return [2, {
@@ -2089,11 +2149,9 @@ var PerpetualsClient = (function () {
2089
2149
  result = _f.sent();
2090
2150
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2091
2151
  if (result.value.err) {
2092
- console.error('error Simulation failed:', result);
2093
2152
  return [2, {
2094
- amount: undefined,
2095
- fee: undefined,
2096
- error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2153
+ amount: new anchor_1.BN(0),
2154
+ fee: new anchor_1.BN(0),
2097
2155
  }];
2098
2156
  }
2099
2157
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2505,10 +2563,11 @@ var PerpetualsClient = (function () {
2505
2563
  for (var _i = 8; _i < arguments.length; _i++) {
2506
2564
  args_1[_i - 8] = arguments[_i];
2507
2565
  }
2508
- 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) {
2566
+ 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
2567
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2510
2568
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2511
2569
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2570
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2512
2571
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2513
2572
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2514
2573
  return __generator(this, function (_c) {
@@ -2601,7 +2660,7 @@ var PerpetualsClient = (function () {
2601
2660
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2602
2661
  fundingMint: collateralCustodyConfig.mintKey
2603
2662
  })
2604
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2663
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2605
2664
  .instruction()];
2606
2665
  case 7:
2607
2666
  instruction = _c.sent();
@@ -2619,10 +2678,11 @@ var PerpetualsClient = (function () {
2619
2678
  for (var _i = 6; _i < arguments.length; _i++) {
2620
2679
  args_1[_i - 6] = arguments[_i];
2621
2680
  }
2622
- 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) {
2681
+ 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
2682
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2624
2683
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2625
2684
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2685
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2626
2686
  if (createUserATA === void 0) { createUserATA = true; }
2627
2687
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2628
2688
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2701,7 +2761,7 @@ var PerpetualsClient = (function () {
2701
2761
  collateralMint: collateralCustodyConfig.mintKey,
2702
2762
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2703
2763
  })
2704
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2764
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2705
2765
  .instruction()];
2706
2766
  case 6:
2707
2767
  instruction = _b.sent();
@@ -2723,15 +2783,16 @@ var PerpetualsClient = (function () {
2723
2783
  });
2724
2784
  });
2725
2785
  };
2726
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2786
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2727
2787
  var args_1 = [];
2728
- for (var _i = 9; _i < arguments.length; _i++) {
2729
- args_1[_i - 9] = arguments[_i];
2788
+ for (var _i = 10; _i < arguments.length; _i++) {
2789
+ args_1[_i - 10] = arguments[_i];
2730
2790
  }
2731
- 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) {
2732
- 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;
2791
+ 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) {
2792
+ 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;
2733
2793
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2734
2794
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2795
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2735
2796
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2736
2797
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2737
2798
  return __generator(this, function (_c) {
@@ -2825,10 +2886,18 @@ var PerpetualsClient = (function () {
2825
2886
  }
2826
2887
  _c.label = 10;
2827
2888
  case 10:
2828
- _c.trys.push([10, 12, , 13]);
2889
+ rebateMintAccount = {
2890
+ pubkey: collateralCustodyConfig.mintKey,
2891
+ isSigner: false,
2892
+ isWritable: false
2893
+ };
2894
+ _c.label = 11;
2895
+ case 11:
2896
+ _c.trys.push([11, 13, , 14]);
2829
2897
  return [4, this.program.methods
2830
2898
  .swapAndOpen({
2831
2899
  amountIn: amountIn,
2900
+ minCollateralAmountOut: minCollateralAmountOut,
2832
2901
  priceWithSlippage: priceWithSlippage,
2833
2902
  sizeAmount: sizeAmount,
2834
2903
  privilege: privilege
@@ -2859,17 +2928,17 @@ var PerpetualsClient = (function () {
2859
2928
  collateralMint: collateralCustodyConfig.mintKey,
2860
2929
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2861
2930
  })
2862
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2931
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2863
2932
  .instruction()];
2864
- case 11:
2933
+ case 12:
2865
2934
  inx = _c.sent();
2866
2935
  instructions.push(inx);
2867
- return [3, 13];
2868
- case 12:
2936
+ return [3, 14];
2937
+ case 13:
2869
2938
  err_3 = _c.sent();
2870
2939
  console.error("perpClient SwapAndOpen error:: ", err_3);
2871
2940
  throw err_3;
2872
- case 13: return [2, {
2941
+ case 14: return [2, {
2873
2942
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2874
2943
  additionalSigners: additionalSigners
2875
2944
  }];
@@ -2877,15 +2946,16 @@ var PerpetualsClient = (function () {
2877
2946
  });
2878
2947
  });
2879
2948
  };
2880
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2949
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2881
2950
  var args_1 = [];
2882
- for (var _i = 7; _i < arguments.length; _i++) {
2883
- args_1[_i - 7] = arguments[_i];
2951
+ for (var _i = 8; _i < arguments.length; _i++) {
2952
+ args_1[_i - 8] = arguments[_i];
2884
2953
  }
2885
- 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) {
2886
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2954
+ 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) {
2955
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2887
2956
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2888
2957
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2958
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2889
2959
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2890
2960
  return __generator(this, function (_a) {
2891
2961
  switch (_a.label) {
@@ -2951,12 +3021,18 @@ var PerpetualsClient = (function () {
2951
3021
  if (!(_a.sent())) {
2952
3022
  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));
2953
3023
  }
3024
+ rebateMintAccount = {
3025
+ pubkey: collateralCustodyConfig.mintKey,
3026
+ isSigner: false,
3027
+ isWritable: false
3028
+ };
2954
3029
  _a.label = 5;
2955
3030
  case 5:
2956
3031
  _a.trys.push([5, 7, , 8]);
2957
3032
  return [4, this.program.methods
2958
3033
  .closeAndSwap({
2959
3034
  priceWithSlippage: priceWithSlippage,
3035
+ minSwapAmountOut: minSwapAmountOut,
2960
3036
  privilege: privilege
2961
3037
  })
2962
3038
  .accounts({
@@ -2985,7 +3061,7 @@ var PerpetualsClient = (function () {
2985
3061
  collateralMint: collateralCustodyConfig.mintKey,
2986
3062
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2987
3063
  })
2988
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3064
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2989
3065
  .instruction()];
2990
3066
  case 6:
2991
3067
  inx = _a.sent();
@@ -3106,12 +3182,12 @@ var PerpetualsClient = (function () {
3106
3182
  });
3107
3183
  });
3108
3184
  };
3109
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3185
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3110
3186
  var args_1 = [];
3111
- for (var _i = 7; _i < arguments.length; _i++) {
3112
- args_1[_i - 7] = arguments[_i];
3187
+ for (var _i = 8; _i < arguments.length; _i++) {
3188
+ args_1[_i - 8] = arguments[_i];
3113
3189
  }
3114
- 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) {
3190
+ 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
3191
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3116
3192
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3117
3193
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3190,6 +3266,7 @@ var PerpetualsClient = (function () {
3190
3266
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3191
3267
  return [4, this.program.methods.swapAndAddCollateral({
3192
3268
  amountIn: amountIn,
3269
+ minCollateralAmountOut: minCollateralAmountOut,
3193
3270
  }).accounts({
3194
3271
  owner: publicKey,
3195
3272
  feePayer: publicKey,
@@ -3225,12 +3302,12 @@ var PerpetualsClient = (function () {
3225
3302
  });
3226
3303
  });
3227
3304
  };
3228
- this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3305
+ this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3229
3306
  var args_1 = [];
3230
3307
  for (var _i = 6; _i < arguments.length; _i++) {
3231
3308
  args_1[_i - 6] = arguments[_i];
3232
3309
  }
3233
- 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) {
3310
+ 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
3311
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3235
3312
  if (createUserATA === void 0) { createUserATA = true; }
3236
3313
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3294,7 +3371,7 @@ var PerpetualsClient = (function () {
3294
3371
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3295
3372
  return [4, this.program.methods
3296
3373
  .removeCollateral({
3297
- collateralDeltaUsd: collateralDeltaUsd,
3374
+ collateralDelta: collateralWithFee,
3298
3375
  })
3299
3376
  .accounts({
3300
3377
  owner: publicKey,
@@ -3336,12 +3413,12 @@ var PerpetualsClient = (function () {
3336
3413
  });
3337
3414
  });
3338
3415
  };
3339
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3416
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3340
3417
  var args_1 = [];
3341
- for (var _i = 6; _i < arguments.length; _i++) {
3342
- args_1[_i - 6] = arguments[_i];
3418
+ for (var _i = 7; _i < arguments.length; _i++) {
3419
+ args_1[_i - 7] = arguments[_i];
3343
3420
  }
3344
- 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) {
3421
+ 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
3422
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3346
3423
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3347
3424
  return __generator(this, function (_a) {
@@ -3398,7 +3475,8 @@ var PerpetualsClient = (function () {
3398
3475
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3399
3476
  return [4, this.program.methods
3400
3477
  .removeCollateralAndSwap({
3401
- collateralDeltaUsd: collateralDeltaUsd,
3478
+ collateralDelta: collateralDelta,
3479
+ minSwapAmountOut: minSwapAmountOut,
3402
3480
  })
3403
3481
  .accounts({
3404
3482
  owner: publicKey,
@@ -3443,10 +3521,11 @@ var PerpetualsClient = (function () {
3443
3521
  for (var _i = 8; _i < arguments.length; _i++) {
3444
3522
  args_1[_i - 8] = arguments[_i];
3445
3523
  }
3446
- 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) {
3524
+ 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
3525
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3448
3526
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3449
3527
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3528
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3450
3529
  return __generator(this, function (_a) {
3451
3530
  switch (_a.label) {
3452
3531
  case 0:
@@ -3489,7 +3568,7 @@ var PerpetualsClient = (function () {
3489
3568
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3490
3569
  collateralMint: collateralCustodyConfig.mintKey
3491
3570
  })
3492
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3571
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3493
3572
  .instruction()];
3494
3573
  case 1:
3495
3574
  instruction = _a.sent();
@@ -3507,10 +3586,11 @@ var PerpetualsClient = (function () {
3507
3586
  for (var _i = 8; _i < arguments.length; _i++) {
3508
3587
  args_1[_i - 8] = arguments[_i];
3509
3588
  }
3510
- 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) {
3589
+ 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
3590
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3512
3591
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3513
3592
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3593
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3514
3594
  return __generator(this, function (_a) {
3515
3595
  switch (_a.label) {
3516
3596
  case 0:
@@ -3553,7 +3633,7 @@ var PerpetualsClient = (function () {
3553
3633
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3554
3634
  collateralMint: collateralCustodyConfig.mintKey
3555
3635
  })
3556
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3636
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3557
3637
  .instruction()];
3558
3638
  case 1:
3559
3639
  instruction = _a.sent();
@@ -4512,13 +4592,11 @@ var PerpetualsClient = (function () {
4512
4592
  for (var _i = 5; _i < arguments.length; _i++) {
4513
4593
  args_1[_i - 5] = arguments[_i];
4514
4594
  }
4515
- 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) {
4516
- 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;
4595
+ 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) {
4596
+ 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_16;
4517
4597
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4518
4598
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4519
4599
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4520
- if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4521
- if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4522
4600
  return __generator(this, function (_f) {
4523
4601
  switch (_f.label) {
4524
4602
  case 0:
@@ -4609,15 +4687,6 @@ var PerpetualsClient = (function () {
4609
4687
  _f.label = 7;
4610
4688
  case 7:
4611
4689
  _f.trys.push([7, 9, , 10]);
4612
- if (enableHeapSizeIx) {
4613
- heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4614
- bytes: 64 * 1024,
4615
- });
4616
- if (enableDebugLogs) {
4617
- console.log("adding 32 liq Data heapSizeIx for addCompoundingLiquidity");
4618
- }
4619
- preInstructions.push(heapSizeIx);
4620
- }
4621
4690
  return [4, this.program.methods
4622
4691
  .addCompoundingLiquidity({
4623
4692
  amountIn: amountIn,
@@ -5429,18 +5498,179 @@ var PerpetualsClient = (function () {
5429
5498
  });
5430
5499
  });
5431
5500
  };
5432
- this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5501
+ this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5502
+ var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_28;
5503
+ return __generator(this, function (_a) {
5504
+ switch (_a.label) {
5505
+ case 0:
5506
+ publicKey = this.provider.wallet.publicKey;
5507
+ rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5508
+ instructions = [];
5509
+ additionalSigners = [];
5510
+ _a.label = 1;
5511
+ case 1:
5512
+ _a.trys.push([1, 3, , 4]);
5513
+ fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5514
+ rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5515
+ rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5516
+ nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5517
+ return [4, this.programFbnftReward.methods
5518
+ .initRewardVault({
5519
+ nftCount: nftCount
5520
+ })
5521
+ .accounts({
5522
+ admin: publicKey,
5523
+ transferAuthority: nftTransferAuthority,
5524
+ rewardVault: rewardVault,
5525
+ rewardMint: rewardCustodyMint,
5526
+ rewardTokenAccount: rewardTokenAccount,
5527
+ collectionMint: collectionMint,
5528
+ programData: fbNftProgramData,
5529
+ systemProgram: web3_js_1.SystemProgram.programId,
5530
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5531
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
5532
+ })
5533
+ .instruction()];
5534
+ case 2:
5535
+ initRewardVault = _a.sent();
5536
+ instructions.push(initRewardVault);
5537
+ return [3, 4];
5538
+ case 3:
5539
+ err_28 = _a.sent();
5540
+ console.log("perpClient InitRewardVault error:: ", err_28);
5541
+ throw err_28;
5542
+ case 4: return [2, {
5543
+ instructions: __spreadArray([], instructions, true),
5544
+ additionalSigners: additionalSigners
5545
+ }];
5546
+ }
5547
+ });
5548
+ }); };
5549
+ this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5550
+ var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_29;
5551
+ return __generator(this, function (_a) {
5552
+ switch (_a.label) {
5553
+ case 0:
5554
+ publicKey = this.provider.wallet.publicKey;
5555
+ rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5556
+ instructions = [];
5557
+ additionalSigners = [];
5558
+ _a.label = 1;
5559
+ case 1:
5560
+ _a.trys.push([1, 3, , 4]);
5561
+ fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5562
+ rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5563
+ rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5564
+ return [4, this.programFbnftReward.methods
5565
+ .distributeRewards({
5566
+ rewardAmount: rewardAmount
5567
+ })
5568
+ .accounts({
5569
+ admin: publicKey,
5570
+ fundingAccount: fundingAccount,
5571
+ rewardVault: rewardVault,
5572
+ rewardTokenAccount: rewardTokenAccount,
5573
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5574
+ })
5575
+ .instruction()];
5576
+ case 2:
5577
+ distributeReward = _a.sent();
5578
+ instructions.push(distributeReward);
5579
+ return [3, 4];
5580
+ case 3:
5581
+ err_29 = _a.sent();
5582
+ console.log("perpClient distributeReward error:: ", err_29);
5583
+ throw err_29;
5584
+ case 4: return [2, {
5585
+ instructions: __spreadArray([], instructions, true),
5586
+ additionalSigners: additionalSigners
5587
+ }];
5588
+ }
5589
+ });
5590
+ }); };
5591
+ this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5433
5592
  var args_1 = [];
5434
5593
  for (var _i = 3; _i < arguments.length; _i++) {
5435
5594
  args_1[_i - 3] = arguments[_i];
5436
5595
  }
5437
- return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5438
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5596
+ return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5597
+ var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_30;
5598
+ if (createUserATA === void 0) { createUserATA = true; }
5599
+ return __generator(this, function (_b) {
5600
+ switch (_b.label) {
5601
+ case 0:
5602
+ publicKey = this.provider.wallet.publicKey;
5603
+ rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5604
+ rewardCustodyMint = rewardToken.mintKey;
5605
+ instructions = [];
5606
+ additionalSigners = [];
5607
+ _b.label = 1;
5608
+ case 1:
5609
+ _b.trys.push([1, 5, , 6]);
5610
+ nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5611
+ metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5612
+ receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5613
+ _a = createUserATA;
5614
+ if (!_a) return [3, 3];
5615
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5616
+ case 2:
5617
+ _a = !(_b.sent());
5618
+ _b.label = 3;
5619
+ case 3:
5620
+ if (_a) {
5621
+ 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));
5622
+ }
5623
+ rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5624
+ rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5625
+ rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5626
+ nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5627
+ return [4, this.programFbnftReward.methods
5628
+ .collectReward()
5629
+ .accounts({
5630
+ owner: publicKey,
5631
+ feePayer: publicKey,
5632
+ nftMint: nftMint,
5633
+ nftTokenAccount: nftTokenAccount,
5634
+ metadataAccount: metadataAccount,
5635
+ receivingAccount: receivingTokenAccount,
5636
+ rewardRecord: rewardRecord,
5637
+ rewardVault: rewardVault,
5638
+ rewardTokenAccount: rewardTokenAccount,
5639
+ transferAuthority: nftTransferAuthority,
5640
+ systemProgram: web3_js_1.SystemProgram.programId,
5641
+ tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5642
+ })
5643
+ .instruction()];
5644
+ case 4:
5645
+ collectNftReward = _b.sent();
5646
+ instructions.push(collectNftReward);
5647
+ return [3, 6];
5648
+ case 5:
5649
+ err_30 = _b.sent();
5650
+ throw err_30;
5651
+ case 6: return [2, {
5652
+ instructions: __spreadArray([], instructions, true),
5653
+ additionalSigners: additionalSigners
5654
+ }];
5655
+ }
5656
+ });
5657
+ });
5658
+ };
5659
+ this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5660
+ var args_1 = [];
5661
+ for (var _i = 2; _i < arguments.length; _i++) {
5662
+ args_1[_i - 2] = arguments[_i];
5663
+ }
5664
+ return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5665
+ var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_31;
5439
5666
  if (createUserATA === void 0) { createUserATA = true; }
5440
5667
  return __generator(this, function (_b) {
5441
5668
  switch (_b.label) {
5442
5669
  case 0:
5443
5670
  publicKey = this.provider.wallet.publicKey;
5671
+ rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5672
+ rewardCustodyMint = rewardToken.mintKey;
5673
+ rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5444
5674
  preInstructions = [];
5445
5675
  instructions = [];
5446
5676
  postInstructions = [];
@@ -5448,43 +5678,59 @@ var PerpetualsClient = (function () {
5448
5678
  _b.label = 1;
5449
5679
  case 1:
5450
5680
  _b.trys.push([1, 5, , 6]);
5451
- rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5452
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5453
- userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5681
+ pool = poolConfig.poolAddress;
5682
+ flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5683
+ receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5454
5684
  _a = createUserATA;
5455
5685
  if (!_a) return [3, 3];
5456
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5686
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5457
5687
  case 2:
5458
5688
  _a = !(_b.sent());
5459
5689
  _b.label = 3;
5460
5690
  case 3:
5461
5691
  if (_a) {
5462
- instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5692
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5463
5693
  }
5464
- return [4, this.program.methods
5465
- .collectRebate()
5694
+ tradingAccount = [];
5695
+ if (nftTradingAccount) {
5696
+ tradingAccount.push({
5697
+ pubkey: nftTradingAccount,
5698
+ isSigner: false,
5699
+ isWritable: true,
5700
+ });
5701
+ }
5702
+ rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5703
+ rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5704
+ return [4, this.programPerpComposability.methods
5705
+ .collectAndDistributeFee()
5466
5706
  .accounts({
5467
- owner: owner,
5468
- receivingTokenAccount: userTokenAccount,
5469
- perpetuals: this.perpetuals.publicKey,
5707
+ perpProgram: this.programId,
5708
+ owner: publicKey,
5709
+ receivingTokenAccount: receivingTokenAccount,
5470
5710
  transferAuthority: poolConfig.transferAuthority,
5471
- rebateVault: poolConfig.rebateVault,
5472
- rebateTokenAccount: poolConfig.rebateTokenAccount,
5473
- tokenStakeAccount: tokenStakeAccount,
5711
+ perpetuals: this.perpetuals.publicKey,
5712
+ pool: pool,
5713
+ feeCustody: rewardCustodyConfig.custodyAccount,
5714
+ flpStakeAccount: flpStakeAccount,
5715
+ feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5716
+ systemProgram: web3_js_1.SystemProgram.programId,
5474
5717
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5475
5718
  eventAuthority: this.eventAuthority.publicKey,
5476
- program: this.programId,
5477
- receivingTokenMint: rebateMint,
5719
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5720
+ fbnftRewardsProgram: this.programFbnftReward.programId,
5721
+ rewardVault: rewardVault,
5722
+ rewardTokenAccount: rewardTokenAccount
5478
5723
  })
5724
+ .remainingAccounts(tradingAccount)
5479
5725
  .instruction()];
5480
5726
  case 4:
5481
- collectRebateInstruction = _b.sent();
5482
- instructions.push(collectRebateInstruction);
5727
+ withdrawStakeInstruction = _b.sent();
5728
+ instructions.push(withdrawStakeInstruction);
5483
5729
  return [3, 6];
5484
5730
  case 5:
5485
- err_28 = _b.sent();
5486
- console.log("perpClient collectRebateInstruction error:: ", err_28);
5487
- throw err_28;
5731
+ err_31 = _b.sent();
5732
+ console.log("perpClient withdrawStake error:: ", err_31);
5733
+ throw err_31;
5488
5734
  case 6: return [2, {
5489
5735
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5490
5736
  additionalSigners: additionalSigners
@@ -5493,60 +5739,13 @@ var PerpetualsClient = (function () {
5493
5739
  });
5494
5740
  });
5495
5741
  };
5496
- this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5497
- var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5498
- return __generator(this, function (_a) {
5499
- switch (_a.label) {
5500
- case 0:
5501
- preInstructions = [];
5502
- instructions = [];
5503
- postInstructions = [];
5504
- additionalSigners = [];
5505
- _a.label = 1;
5506
- case 1:
5507
- _a.trys.push([1, 3, , 4]);
5508
- rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5509
- rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5510
- return [4, this.program.methods
5511
- .settleRebates()
5512
- .accounts({
5513
- transferAuthority: poolConfig.transferAuthority,
5514
- perpetuals: this.perpetuals.publicKey,
5515
- pool: poolConfig.poolAddress,
5516
- rewardCustody: rewardCustody.custodyAccount,
5517
- rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5518
- rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5519
- rebateVault: poolConfig.rebateVault,
5520
- rebateTokenAccount: poolConfig.rebateTokenAccount,
5521
- tokenMint: rebateMint,
5522
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5523
- eventAuthority: this.eventAuthority.publicKey,
5524
- program: this.programId,
5525
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5526
- })
5527
- .instruction()];
5528
- case 2:
5529
- settleRebatesInstruction = _a.sent();
5530
- instructions.push(settleRebatesInstruction);
5531
- return [3, 4];
5532
- case 3:
5533
- err_29 = _a.sent();
5534
- console.log("perpClient settleRebatesInstruction error:: ", err_29);
5535
- throw err_29;
5536
- case 4: return [2, {
5537
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5538
- additionalSigners: additionalSigners
5539
- }];
5540
- }
5541
- });
5542
- }); };
5543
5742
  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) {
5544
5743
  var args_1 = [];
5545
5744
  for (var _i = 11; _i < arguments.length; _i++) {
5546
5745
  args_1[_i - 11] = arguments[_i];
5547
5746
  }
5548
5747
  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) {
5549
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5748
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_32;
5550
5749
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5551
5750
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5552
5751
  return __generator(this, function (_c) {
@@ -5652,9 +5851,9 @@ var PerpetualsClient = (function () {
5652
5851
  instructions.push(placeLimitOrder);
5653
5852
  return [3, 10];
5654
5853
  case 9:
5655
- err_30 = _c.sent();
5656
- console.log("perpClient placeLimitOrder error:: ", err_30);
5657
- throw err_30;
5854
+ err_32 = _c.sent();
5855
+ console.log("perpClient placeLimitOrder error:: ", err_32);
5856
+ throw err_32;
5658
5857
  case 10: return [2, {
5659
5858
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5660
5859
  additionalSigners: additionalSigners
@@ -5669,7 +5868,7 @@ var PerpetualsClient = (function () {
5669
5868
  args_1[_i - 11] = arguments[_i];
5670
5869
  }
5671
5870
  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) {
5672
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
5871
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_33;
5673
5872
  if (createUserATA === void 0) { createUserATA = true; }
5674
5873
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5675
5874
  return __generator(this, function (_b) {
@@ -5760,9 +5959,9 @@ var PerpetualsClient = (function () {
5760
5959
  instructions.push(editLimitOrder);
5761
5960
  return [3, 8];
5762
5961
  case 7:
5763
- err_31 = _b.sent();
5764
- console.log("perpClient editLimitOrder error:: ", err_31);
5765
- throw err_31;
5962
+ err_33 = _b.sent();
5963
+ console.log("perpClient editLimitOrder error:: ", err_33);
5964
+ throw err_33;
5766
5965
  case 8: return [2, {
5767
5966
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5768
5967
  additionalSigners: additionalSigners
@@ -5776,10 +5975,11 @@ var PerpetualsClient = (function () {
5776
5975
  for (var _i = 7; _i < arguments.length; _i++) {
5777
5976
  args_1[_i - 7] = arguments[_i];
5778
5977
  }
5779
- 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) {
5780
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
5978
+ 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) {
5979
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_34;
5781
5980
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
5782
5981
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
5982
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
5783
5983
  return __generator(this, function (_a) {
5784
5984
  switch (_a.label) {
5785
5985
  case 0:
@@ -5822,16 +6022,16 @@ var PerpetualsClient = (function () {
5822
6022
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5823
6023
  collateralMint: collateralCustodyConfig.mintKey,
5824
6024
  })
5825
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6025
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5826
6026
  .instruction()];
5827
6027
  case 2:
5828
6028
  executeLimitOrder = _a.sent();
5829
6029
  instructions.push(executeLimitOrder);
5830
6030
  return [3, 4];
5831
6031
  case 3:
5832
- err_32 = _a.sent();
5833
- console.log("perpClient executeLimitOrder error:: ", err_32);
5834
- throw err_32;
6032
+ err_34 = _a.sent();
6033
+ console.log("perpClient executeLimitOrder error:: ", err_34);
6034
+ throw err_34;
5835
6035
  case 4: return [2, {
5836
6036
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5837
6037
  additionalSigners: additionalSigners
@@ -5845,10 +6045,11 @@ var PerpetualsClient = (function () {
5845
6045
  for (var _i = 8; _i < arguments.length; _i++) {
5846
6046
  args_1[_i - 8] = arguments[_i];
5847
6047
  }
5848
- 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) {
5849
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6048
+ 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) {
6049
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_35;
5850
6050
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
5851
6051
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6052
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
5852
6053
  return __generator(this, function (_a) {
5853
6054
  switch (_a.label) {
5854
6055
  case 0:
@@ -5894,16 +6095,16 @@ var PerpetualsClient = (function () {
5894
6095
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5895
6096
  collateralMint: collateralCustodyConfig.mintKey,
5896
6097
  })
5897
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6098
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5898
6099
  .instruction()];
5899
6100
  case 2:
5900
6101
  executeLimitWithSwap = _a.sent();
5901
6102
  instructions.push(executeLimitWithSwap);
5902
6103
  return [3, 4];
5903
6104
  case 3:
5904
- err_33 = _a.sent();
5905
- console.log("perpClient executeLimitWithSwap error:: ", err_33);
5906
- throw err_33;
6105
+ err_35 = _a.sent();
6106
+ console.log("perpClient executeLimitWithSwap error:: ", err_35);
6107
+ throw err_35;
5907
6108
  case 4: return [2, {
5908
6109
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5909
6110
  additionalSigners: additionalSigners
@@ -5913,7 +6114,7 @@ var PerpetualsClient = (function () {
5913
6114
  });
5914
6115
  };
5915
6116
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5916
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6117
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_36;
5917
6118
  return __generator(this, function (_a) {
5918
6119
  switch (_a.label) {
5919
6120
  case 0:
@@ -5961,9 +6162,9 @@ var PerpetualsClient = (function () {
5961
6162
  instructions.push(placeTriggerOrder);
5962
6163
  return [3, 4];
5963
6164
  case 3:
5964
- err_34 = _a.sent();
5965
- console.log("perpClient placeTriggerOrder error:: ", err_34);
5966
- throw err_34;
6165
+ err_36 = _a.sent();
6166
+ console.log("perpClient placeTriggerOrder error:: ", err_36);
6167
+ throw err_36;
5967
6168
  case 4: return [2, {
5968
6169
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5969
6170
  additionalSigners: additionalSigners
@@ -5972,7 +6173,7 @@ var PerpetualsClient = (function () {
5972
6173
  });
5973
6174
  }); };
5974
6175
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5975
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6176
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_37;
5976
6177
  return __generator(this, function (_a) {
5977
6178
  switch (_a.label) {
5978
6179
  case 0:
@@ -6019,9 +6220,9 @@ var PerpetualsClient = (function () {
6019
6220
  instructions.push(editTriggerOrder);
6020
6221
  return [3, 4];
6021
6222
  case 3:
6022
- err_35 = _a.sent();
6023
- console.log("perpClient editTriggerOrder error:: ", err_35);
6024
- throw err_35;
6223
+ err_37 = _a.sent();
6224
+ console.log("perpClient editTriggerOrder error:: ", err_37);
6225
+ throw err_37;
6025
6226
  case 4: return [2, {
6026
6227
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6027
6228
  additionalSigners: additionalSigners
@@ -6030,7 +6231,7 @@ var PerpetualsClient = (function () {
6030
6231
  });
6031
6232
  }); };
6032
6233
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6033
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6234
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_38;
6034
6235
  return __generator(this, function (_a) {
6035
6236
  switch (_a.label) {
6036
6237
  case 0:
@@ -6063,9 +6264,9 @@ var PerpetualsClient = (function () {
6063
6264
  instructions.push(cancelTriggerOrder);
6064
6265
  return [3, 4];
6065
6266
  case 3:
6066
- err_36 = _a.sent();
6067
- console.log("perpClient cancelTriggerOrder error:: ", err_36);
6068
- throw err_36;
6267
+ err_38 = _a.sent();
6268
+ console.log("perpClient cancelTriggerOrder error:: ", err_38);
6269
+ throw err_38;
6069
6270
  case 4: return [2, {
6070
6271
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6071
6272
  additionalSigners: additionalSigners
@@ -6074,7 +6275,7 @@ var PerpetualsClient = (function () {
6074
6275
  });
6075
6276
  }); };
6076
6277
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6077
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6278
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_39;
6078
6279
  return __generator(this, function (_a) {
6079
6280
  switch (_a.label) {
6080
6281
  case 0:
@@ -6105,9 +6306,9 @@ var PerpetualsClient = (function () {
6105
6306
  instructions.push(cancelAllTriggerOrders);
6106
6307
  return [3, 4];
6107
6308
  case 3:
6108
- err_37 = _a.sent();
6109
- console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6110
- throw err_37;
6309
+ err_39 = _a.sent();
6310
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_39);
6311
+ throw err_39;
6111
6312
  case 4: return [2, {
6112
6313
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6113
6314
  additionalSigners: additionalSigners
@@ -6120,12 +6321,13 @@ var PerpetualsClient = (function () {
6120
6321
  for (var _i = 9; _i < arguments.length; _i++) {
6121
6322
  args_1[_i - 9] = arguments[_i];
6122
6323
  }
6123
- 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) {
6124
- 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;
6324
+ 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) {
6325
+ 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_40;
6125
6326
  if (createUserATA === void 0) { createUserATA = true; }
6126
6327
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6127
6328
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6128
6329
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6330
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6129
6331
  return __generator(this, function (_e) {
6130
6332
  switch (_e.label) {
6131
6333
  case 0:
@@ -6220,16 +6422,16 @@ var PerpetualsClient = (function () {
6220
6422
  collateralMint: collateralCustodyConfig.mintKey,
6221
6423
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6222
6424
  })
6223
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6425
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6224
6426
  .instruction()];
6225
6427
  case 8:
6226
6428
  executeTriggerWithSwap = _e.sent();
6227
6429
  instructions.push(executeTriggerWithSwap);
6228
6430
  return [3, 10];
6229
6431
  case 9:
6230
- err_38 = _e.sent();
6231
- console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6232
- throw err_38;
6432
+ err_40 = _e.sent();
6433
+ console.log("perpClient executeTriggerWithSwap error:: ", err_40);
6434
+ throw err_40;
6233
6435
  case 10: return [2, {
6234
6436
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6235
6437
  additionalSigners: additionalSigners
@@ -6243,12 +6445,13 @@ var PerpetualsClient = (function () {
6243
6445
  for (var _i = 8; _i < arguments.length; _i++) {
6244
6446
  args_1[_i - 8] = arguments[_i];
6245
6447
  }
6246
- 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) {
6247
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6448
+ 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) {
6449
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_41;
6248
6450
  if (createUserATA === void 0) { createUserATA = true; }
6249
6451
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6250
6452
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6251
6453
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6454
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6252
6455
  return __generator(this, function (_b) {
6253
6456
  switch (_b.label) {
6254
6457
  case 0:
@@ -6308,16 +6511,16 @@ var PerpetualsClient = (function () {
6308
6511
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6309
6512
  receivingMint: collateralCustodyConfig.mintKey
6310
6513
  })
6311
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6514
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6312
6515
  .instruction()];
6313
6516
  case 6:
6314
6517
  executeTriggerOrder = _b.sent();
6315
6518
  instructions.push(executeTriggerOrder);
6316
6519
  return [3, 8];
6317
6520
  case 7:
6318
- err_39 = _b.sent();
6319
- console.log("perpClient executeTriggerOrder error:: ", err_39);
6320
- throw err_39;
6521
+ err_41 = _b.sent();
6522
+ console.log("perpClient executeTriggerOrder error:: ", err_41);
6523
+ throw err_41;
6321
6524
  case 8: return [2, {
6322
6525
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6323
6526
  additionalSigners: additionalSigners
@@ -6332,7 +6535,7 @@ var PerpetualsClient = (function () {
6332
6535
  args_1[_i - 5] = arguments[_i];
6333
6536
  }
6334
6537
  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) {
6335
- 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;
6538
+ 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_42;
6336
6539
  if (useFeesPool === void 0) { useFeesPool = false; }
6337
6540
  if (createUserATA === void 0) { createUserATA = true; }
6338
6541
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6479,7 +6682,7 @@ var PerpetualsClient = (function () {
6479
6682
  _g.label = 16;
6480
6683
  case 16:
6481
6684
  if (_d) {
6482
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userOutputTokenAccount, publicKey, poolConfig.getTokenFromSymbol(userOutputTokenSymbol).mintKey));
6685
+ 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));
6483
6686
  }
6484
6687
  _g.label = 17;
6485
6688
  case 17:
@@ -6537,9 +6740,9 @@ var PerpetualsClient = (function () {
6537
6740
  }
6538
6741
  return [3, 20];
6539
6742
  case 19:
6540
- err_40 = _g.sent();
6541
- console.error("perpClient Swap error:: ", err_40);
6542
- throw err_40;
6743
+ err_42 = _g.sent();
6744
+ console.error("perpClient Swap error:: ", err_42);
6745
+ throw err_42;
6543
6746
  case 20: return [2, {
6544
6747
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6545
6748
  additionalSigners: additionalSigners
@@ -6549,7 +6752,7 @@ var PerpetualsClient = (function () {
6549
6752
  });
6550
6753
  };
6551
6754
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6552
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6755
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_43;
6553
6756
  return __generator(this, function (_b) {
6554
6757
  switch (_b.label) {
6555
6758
  case 0:
@@ -6594,7 +6797,11 @@ var PerpetualsClient = (function () {
6594
6797
  rewardCustody: rewardCustody.custodyAccount,
6595
6798
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
6596
6799
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
6800
+ custody: custody.custodyAccount,
6801
+ custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
6802
+ custodyTokenAccount: custody.tokenAccount,
6597
6803
  eventAuthority: this.eventAuthority.publicKey,
6804
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
6598
6805
  program: this.programId,
6599
6806
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
6600
6807
  })
@@ -6605,9 +6812,9 @@ var PerpetualsClient = (function () {
6605
6812
  instructions.push(inx);
6606
6813
  return [3, 4];
6607
6814
  case 3:
6608
- err_41 = _b.sent();
6609
- console.error("perpClient Swap error:: ", err_41);
6610
- throw err_41;
6815
+ err_43 = _b.sent();
6816
+ console.error("perpClient Swap error:: ", err_43);
6817
+ throw err_43;
6611
6818
  case 4: return [2, {
6612
6819
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6613
6820
  additionalSigners: additionalSigners
@@ -6616,7 +6823,7 @@ var PerpetualsClient = (function () {
6616
6823
  });
6617
6824
  }); };
6618
6825
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6619
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
6826
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_44;
6620
6827
  return __generator(this, function (_d) {
6621
6828
  switch (_d.label) {
6622
6829
  case 0:
@@ -6664,9 +6871,9 @@ var PerpetualsClient = (function () {
6664
6871
  instructions.push(setLpTokenPriceInstruction);
6665
6872
  return [3, 4];
6666
6873
  case 3:
6667
- err_42 = _d.sent();
6668
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6669
- throw err_42;
6874
+ err_44 = _d.sent();
6875
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_44);
6876
+ throw err_44;
6670
6877
  case 4: return [2, {
6671
6878
  instructions: __spreadArray([], instructions, true),
6672
6879
  additionalSigners: additionalSigners
@@ -6714,7 +6921,7 @@ var PerpetualsClient = (function () {
6714
6921
  });
6715
6922
  }); };
6716
6923
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
6717
- var adminMetas, _i, admins_2, admin, err_43;
6924
+ var adminMetas, _i, admins_2, admin, err_45;
6718
6925
  return __generator(this, function (_a) {
6719
6926
  switch (_a.label) {
6720
6927
  case 0:
@@ -6744,16 +6951,16 @@ var PerpetualsClient = (function () {
6744
6951
  _a.sent();
6745
6952
  return [3, 4];
6746
6953
  case 3:
6747
- err_43 = _a.sent();
6954
+ err_45 = _a.sent();
6748
6955
  if (this.printErrors) {
6749
- console.error("setAdminSigners err:", err_43);
6956
+ console.error("setAdminSigners err:", err_45);
6750
6957
  }
6751
- throw err_43;
6958
+ throw err_45;
6752
6959
  case 4: return [2];
6753
6960
  }
6754
6961
  });
6755
6962
  }); };
6756
- this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor, stakingFeeBoostBps, minLpPriceUsd, maxLpPriceUsd, thresholdUsd) { return __awaiter(_this, void 0, void 0, function () {
6963
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor) { return __awaiter(_this, void 0, void 0, function () {
6757
6964
  return __generator(this, function (_a) {
6758
6965
  switch (_a.label) {
6759
6966
  case 0: return [4, this.program.methods
@@ -6765,11 +6972,7 @@ var PerpetualsClient = (function () {
6765
6972
  metadataTitle: metadataTitle,
6766
6973
  metadataUri: metadataUri,
6767
6974
  stakingFeeShareBps: stakingFeeShareBps,
6768
- vpVolumeFactor: vpVolumeFactor,
6769
- stakingFeeBoostBps: stakingFeeBoostBps,
6770
- minLpPriceUsd: minLpPriceUsd,
6771
- maxLpPriceUsd: maxLpPriceUsd,
6772
- thresholdUsd: thresholdUsd
6975
+ vpVolumeFactor: vpVolumeFactor
6773
6976
  })
6774
6977
  .accounts({
6775
6978
  admin: this.provider.wallet.publicKey,
@@ -6817,7 +7020,7 @@ var PerpetualsClient = (function () {
6817
7020
  }
6818
7021
  });
6819
7022
  }); };
6820
- 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 () {
7023
+ this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
6821
7024
  var trx_id, error_3;
6822
7025
  return __generator(this, function (_a) {
6823
7026
  switch (_a.label) {
@@ -6835,9 +7038,6 @@ var PerpetualsClient = (function () {
6835
7038
  fees: fees,
6836
7039
  borrowRate: borrowRate,
6837
7040
  ratios: ratios,
6838
- rewardThreshold: rewardThreshold,
6839
- minReserveUsd: minReserveUsd,
6840
- limitPriceBufferBps: limitPriceBufferBps
6841
7041
  })
6842
7042
  .accounts({
6843
7043
  admin: this.admin,
@@ -6944,7 +7144,7 @@ var PerpetualsClient = (function () {
6944
7144
  });
6945
7145
  }); };
6946
7146
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6947
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7147
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_46;
6948
7148
  return __generator(this, function (_a) {
6949
7149
  switch (_a.label) {
6950
7150
  case 0:
@@ -6977,9 +7177,9 @@ var PerpetualsClient = (function () {
6977
7177
  instructions.push(withdrawFeesIx);
6978
7178
  return [3, 5];
6979
7179
  case 4:
6980
- err_44 = _a.sent();
6981
- console.log("perpClient setPool error:: ", err_44);
6982
- throw err_44;
7180
+ err_46 = _a.sent();
7181
+ console.log("perpClient setPool error:: ", err_46);
7182
+ throw err_46;
6983
7183
  case 5: return [2, {
6984
7184
  instructions: __spreadArray([], instructions, true),
6985
7185
  additionalSigners: additionalSigners
@@ -6988,7 +7188,7 @@ var PerpetualsClient = (function () {
6988
7188
  });
6989
7189
  }); };
6990
7190
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6991
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7191
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_47;
6992
7192
  return __generator(this, function (_a) {
6993
7193
  switch (_a.label) {
6994
7194
  case 0:
@@ -7022,9 +7222,9 @@ var PerpetualsClient = (function () {
7022
7222
  instructions.push(moveProtocolFeesIx);
7023
7223
  return [3, 4];
7024
7224
  case 3:
7025
- err_45 = _a.sent();
7026
- console.log("perpClient setPool error:: ", err_45);
7027
- throw err_45;
7225
+ err_47 = _a.sent();
7226
+ console.log("perpClient setPool error:: ", err_47);
7227
+ throw err_47;
7028
7228
  case 4: return [2, {
7029
7229
  instructions: __spreadArray([], instructions, true),
7030
7230
  additionalSigners: additionalSigners
@@ -7033,7 +7233,7 @@ var PerpetualsClient = (function () {
7033
7233
  });
7034
7234
  }); };
7035
7235
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7036
- var publicKey, setProtocolFeeShareBpsIx, err_46;
7236
+ var publicKey, setProtocolFeeShareBpsIx, err_48;
7037
7237
  return __generator(this, function (_a) {
7038
7238
  switch (_a.label) {
7039
7239
  case 0:
@@ -7053,15 +7253,15 @@ var PerpetualsClient = (function () {
7053
7253
  setProtocolFeeShareBpsIx = _a.sent();
7054
7254
  return [2, setProtocolFeeShareBpsIx];
7055
7255
  case 2:
7056
- err_46 = _a.sent();
7057
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7058
- throw err_46;
7256
+ err_48 = _a.sent();
7257
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_48);
7258
+ throw err_48;
7059
7259
  case 3: return [2];
7060
7260
  }
7061
7261
  });
7062
7262
  }); };
7063
7263
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7064
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7264
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_49;
7065
7265
  return __generator(this, function (_a) {
7066
7266
  switch (_a.label) {
7067
7267
  case 0:
@@ -7088,9 +7288,9 @@ var PerpetualsClient = (function () {
7088
7288
  instructions.push(setPermissionsInstruction);
7089
7289
  return [3, 4];
7090
7290
  case 3:
7091
- err_47 = _a.sent();
7092
- console.log("perpClient setPool error:: ", err_47);
7093
- throw err_47;
7291
+ err_49 = _a.sent();
7292
+ console.log("perpClient setPool error:: ", err_49);
7293
+ throw err_49;
7094
7294
  case 4: return [2, {
7095
7295
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7096
7296
  additionalSigners: additionalSigners
@@ -7099,7 +7299,7 @@ var PerpetualsClient = (function () {
7099
7299
  });
7100
7300
  }); };
7101
7301
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7102
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7302
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_50;
7103
7303
  var _f;
7104
7304
  return __generator(this, function (_g) {
7105
7305
  switch (_g.label) {
@@ -7160,9 +7360,9 @@ var PerpetualsClient = (function () {
7160
7360
  instructions.push(reimburse);
7161
7361
  return [3, 5];
7162
7362
  case 4:
7163
- err_48 = _g.sent();
7164
- console.log("perpClient setPool error:: ", err_48);
7165
- throw err_48;
7363
+ err_50 = _g.sent();
7364
+ console.log("perpClient setPool error:: ", err_50);
7365
+ throw err_50;
7166
7366
  case 5: return [2, {
7167
7367
  instructions: __spreadArray([], instructions, true),
7168
7368
  additionalSigners: additionalSigners
@@ -7171,7 +7371,7 @@ var PerpetualsClient = (function () {
7171
7371
  });
7172
7372
  }); };
7173
7373
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7174
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7374
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_51;
7175
7375
  return __generator(this, function (_a) {
7176
7376
  switch (_a.label) {
7177
7377
  case 0:
@@ -7205,9 +7405,9 @@ var PerpetualsClient = (function () {
7205
7405
  instructions.push(setInternalOraclePrice);
7206
7406
  return [3, 4];
7207
7407
  case 3:
7208
- err_49 = _a.sent();
7209
- console.log("perpClient setInternalOracleAccount error:: ", err_49);
7210
- throw err_49;
7408
+ err_51 = _a.sent();
7409
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7410
+ throw err_51;
7211
7411
  case 4: return [2, {
7212
7412
  instructions: __spreadArray([], instructions, true),
7213
7413
  additionalSigners: additionalSigners
@@ -7216,7 +7416,7 @@ var PerpetualsClient = (function () {
7216
7416
  });
7217
7417
  }); };
7218
7418
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7219
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7419
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_52;
7220
7420
  return __generator(this, function (_a) {
7221
7421
  switch (_a.label) {
7222
7422
  case 0:
@@ -7262,9 +7462,9 @@ var PerpetualsClient = (function () {
7262
7462
  instructions.push(setInternalOraclePrice);
7263
7463
  return [3, 4];
7264
7464
  case 3:
7265
- err_50 = _a.sent();
7266
- console.log("perpClient setInternalOracleAccount error:: ", err_50);
7267
- throw err_50;
7465
+ err_52 = _a.sent();
7466
+ console.log("perpClient setInternalOracleAccount error:: ", err_52);
7467
+ throw err_52;
7268
7468
  case 4: return [2, {
7269
7469
  instructions: __spreadArray([], instructions, true),
7270
7470
  additionalSigners: additionalSigners
@@ -7273,7 +7473,7 @@ var PerpetualsClient = (function () {
7273
7473
  });
7274
7474
  }); };
7275
7475
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7276
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7476
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_53;
7277
7477
  return __generator(this, function (_a) {
7278
7478
  switch (_a.label) {
7279
7479
  case 0:
@@ -7313,9 +7513,9 @@ var PerpetualsClient = (function () {
7313
7513
  instructions.push(setInternalOraclePrice);
7314
7514
  return [3, 4];
7315
7515
  case 3:
7316
- err_51 = _a.sent();
7317
- console.log("perpClient setInternalOracleAccount error:: ", err_51);
7318
- throw err_51;
7516
+ err_53 = _a.sent();
7517
+ console.log("perpClient setInternalOracleAccount error:: ", err_53);
7518
+ throw err_53;
7319
7519
  case 4: return [2, {
7320
7520
  instructions: __spreadArray([], instructions, true),
7321
7521
  additionalSigners: additionalSigners
@@ -7324,7 +7524,7 @@ var PerpetualsClient = (function () {
7324
7524
  });
7325
7525
  }); };
7326
7526
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7327
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7527
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_54;
7328
7528
  return __generator(this, function (_a) {
7329
7529
  switch (_a.label) {
7330
7530
  case 0:
@@ -7362,8 +7562,8 @@ var PerpetualsClient = (function () {
7362
7562
  instructions.push(renameFlp);
7363
7563
  return [3, 4];
7364
7564
  case 3:
7365
- err_52 = _a.sent();
7366
- console.log("perpClient renameFlp error:: ", err_52);
7565
+ err_54 = _a.sent();
7566
+ console.log("perpClient renameFlp error:: ", err_54);
7367
7567
  return [3, 4];
7368
7568
  case 4: return [2, {
7369
7569
  instructions: __spreadArray([], instructions, true),
@@ -7373,7 +7573,7 @@ var PerpetualsClient = (function () {
7373
7573
  });
7374
7574
  }); };
7375
7575
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7376
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7576
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_55;
7377
7577
  return __generator(this, function (_a) {
7378
7578
  switch (_a.label) {
7379
7579
  case 0:
@@ -7411,9 +7611,9 @@ var PerpetualsClient = (function () {
7411
7611
  instructions.push(initStakeInstruction);
7412
7612
  return [3, 4];
7413
7613
  case 3:
7414
- err_53 = _a.sent();
7415
- console.log("perpClient InitStaking error:: ", err_53);
7416
- throw err_53;
7614
+ err_55 = _a.sent();
7615
+ console.log("perpClient InitStaking error:: ", err_55);
7616
+ throw err_55;
7417
7617
  case 4: return [2, {
7418
7618
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7419
7619
  additionalSigners: additionalSigners
@@ -7422,7 +7622,7 @@ var PerpetualsClient = (function () {
7422
7622
  });
7423
7623
  }); };
7424
7624
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7425
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7625
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_56;
7426
7626
  return __generator(this, function (_a) {
7427
7627
  switch (_a.label) {
7428
7628
  case 0:
@@ -7466,9 +7666,9 @@ var PerpetualsClient = (function () {
7466
7666
  instructions.push(initCompoundingInstruction);
7467
7667
  return [3, 4];
7468
7668
  case 3:
7469
- err_54 = _a.sent();
7470
- console.log("perpClient initCompounding error:: ", err_54);
7471
- throw err_54;
7669
+ err_56 = _a.sent();
7670
+ console.log("perpClient initCompounding error:: ", err_56);
7671
+ throw err_56;
7472
7672
  case 4: return [2, {
7473
7673
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7474
7674
  additionalSigners: additionalSigners
@@ -7477,7 +7677,7 @@ var PerpetualsClient = (function () {
7477
7677
  });
7478
7678
  }); };
7479
7679
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7480
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7680
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_57;
7481
7681
  return __generator(this, function (_a) {
7482
7682
  switch (_a.label) {
7483
7683
  case 0:
@@ -7518,9 +7718,9 @@ var PerpetualsClient = (function () {
7518
7718
  instructions.push(initTokenVaultInstruction);
7519
7719
  return [3, 4];
7520
7720
  case 3:
7521
- err_55 = _a.sent();
7522
- console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7523
- throw err_55;
7721
+ err_57 = _a.sent();
7722
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_57);
7723
+ throw err_57;
7524
7724
  case 4: return [2, {
7525
7725
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7526
7726
  additionalSigners: additionalSigners
@@ -7529,7 +7729,7 @@ var PerpetualsClient = (function () {
7529
7729
  });
7530
7730
  }); };
7531
7731
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7532
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7732
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_58;
7533
7733
  return __generator(this, function (_a) {
7534
7734
  switch (_a.label) {
7535
7735
  case 0:
@@ -7560,9 +7760,9 @@ var PerpetualsClient = (function () {
7560
7760
  instructions.push(setTokenVaultConfigInstruction);
7561
7761
  return [3, 4];
7562
7762
  case 3:
7563
- err_56 = _a.sent();
7564
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7565
- throw err_56;
7763
+ err_58 = _a.sent();
7764
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_58);
7765
+ throw err_58;
7566
7766
  case 4: return [2, {
7567
7767
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7568
7768
  additionalSigners: additionalSigners
@@ -7571,7 +7771,7 @@ var PerpetualsClient = (function () {
7571
7771
  });
7572
7772
  }); };
7573
7773
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7574
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
7774
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_59;
7575
7775
  return __generator(this, function (_a) {
7576
7776
  switch (_a.label) {
7577
7777
  case 0:
@@ -7610,9 +7810,9 @@ var PerpetualsClient = (function () {
7610
7810
  instructions.push(withdrawInstantFeeInstruction);
7611
7811
  return [3, 6];
7612
7812
  case 5:
7613
- err_57 = _a.sent();
7614
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7615
- throw err_57;
7813
+ err_59 = _a.sent();
7814
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_59);
7815
+ throw err_59;
7616
7816
  case 6: return [2, {
7617
7817
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7618
7818
  additionalSigners: additionalSigners
@@ -7621,7 +7821,7 @@ var PerpetualsClient = (function () {
7621
7821
  });
7622
7822
  }); };
7623
7823
  this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7624
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7824
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_60;
7625
7825
  return __generator(this, function (_a) {
7626
7826
  switch (_a.label) {
7627
7827
  case 0:
@@ -7660,9 +7860,9 @@ var PerpetualsClient = (function () {
7660
7860
  instructions.push(withdrawUnclaimedTokensInstruction);
7661
7861
  return [3, 6];
7662
7862
  case 5:
7663
- err_58 = _a.sent();
7664
- console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7665
- throw err_58;
7863
+ err_60 = _a.sent();
7864
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_60);
7865
+ throw err_60;
7666
7866
  case 6: return [2, {
7667
7867
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7668
7868
  additionalSigners: additionalSigners
@@ -7671,7 +7871,7 @@ var PerpetualsClient = (function () {
7671
7871
  });
7672
7872
  }); };
7673
7873
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7674
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
7874
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_61;
7675
7875
  return __generator(this, function (_a) {
7676
7876
  switch (_a.label) {
7677
7877
  case 0:
@@ -7708,55 +7908,9 @@ var PerpetualsClient = (function () {
7708
7908
  instructions.push(initRevenueTokenAccountInstruction);
7709
7909
  return [3, 4];
7710
7910
  case 3:
7711
- err_59 = _a.sent();
7712
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7713
- throw err_59;
7714
- case 4: return [2, {
7715
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7716
- additionalSigners: additionalSigners
7717
- }];
7718
- }
7719
- });
7720
- }); };
7721
- this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7722
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7723
- return __generator(this, function (_a) {
7724
- switch (_a.label) {
7725
- case 0:
7726
- publicKey = this.provider.wallet.publicKey;
7727
- preInstructions = [];
7728
- instructions = [];
7729
- postInstructions = [];
7730
- additionalSigners = [];
7731
- _a.label = 1;
7732
- case 1:
7733
- _a.trys.push([1, 3, , 4]);
7734
- rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7735
- return [4, this.program.methods
7736
- .initRebateVault({
7737
- allowRebatePayout: allowRebatePayout
7738
- })
7739
- .accounts({
7740
- admin: publicKey,
7741
- multisig: this.multisig.publicKey,
7742
- transferAuthority: poolConfig.transferAuthority,
7743
- perpetuals: this.perpetuals.publicKey,
7744
- rebateMint: rebateCustodyMint,
7745
- rebateTokenAccount: poolConfig.rebateTokenAccount,
7746
- rebateVault: poolConfig.rebateVault,
7747
- systemProgram: web3_js_1.SystemProgram.programId,
7748
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7749
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
7750
- })
7751
- .instruction()];
7752
- case 2:
7753
- initRebateVaultInstruction = _a.sent();
7754
- instructions.push(initRebateVaultInstruction);
7755
- return [3, 4];
7756
- case 3:
7757
- err_60 = _a.sent();
7758
- console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7759
- throw err_60;
7911
+ err_61 = _a.sent();
7912
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_61);
7913
+ throw err_61;
7760
7914
  case 4: return [2, {
7761
7915
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7762
7916
  additionalSigners: additionalSigners
@@ -7765,7 +7919,7 @@ var PerpetualsClient = (function () {
7765
7919
  });
7766
7920
  }); };
7767
7921
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7768
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
7922
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_62;
7769
7923
  return __generator(this, function (_a) {
7770
7924
  switch (_a.label) {
7771
7925
  case 0:
@@ -7804,9 +7958,9 @@ var PerpetualsClient = (function () {
7804
7958
  instructions.push(distributeTokenRewardInstruction);
7805
7959
  return [3, 4];
7806
7960
  case 3:
7807
- err_61 = _a.sent();
7808
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7809
- throw err_61;
7961
+ err_62 = _a.sent();
7962
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_62);
7963
+ throw err_62;
7810
7964
  case 4: return [2, {
7811
7965
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7812
7966
  additionalSigners: additionalSigners
@@ -7815,7 +7969,7 @@ var PerpetualsClient = (function () {
7815
7969
  });
7816
7970
  }); };
7817
7971
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
7818
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
7972
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_63;
7819
7973
  return __generator(this, function (_a) {
7820
7974
  switch (_a.label) {
7821
7975
  case 0:
@@ -7843,9 +7997,9 @@ var PerpetualsClient = (function () {
7843
7997
  instructions.push(setTokenStakeLevelInstruction);
7844
7998
  return [3, 4];
7845
7999
  case 3:
7846
- err_62 = _a.sent();
7847
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7848
- throw err_62;
8000
+ err_63 = _a.sent();
8001
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_63);
8002
+ throw err_63;
7849
8003
  case 4: return [2, {
7850
8004
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7851
8005
  additionalSigners: additionalSigners
@@ -7854,7 +8008,7 @@ var PerpetualsClient = (function () {
7854
8008
  });
7855
8009
  }); };
7856
8010
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7857
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8011
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_64;
7858
8012
  return __generator(this, function (_a) {
7859
8013
  switch (_a.label) {
7860
8014
  case 0:
@@ -7886,9 +8040,9 @@ var PerpetualsClient = (function () {
7886
8040
  instructions.push(setTokenRewardInstruction);
7887
8041
  return [3, 4];
7888
8042
  case 3:
7889
- err_63 = _a.sent();
7890
- console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7891
- throw err_63;
8043
+ err_64 = _a.sent();
8044
+ console.log("perpClient setTokenRewardInstruction error:: ", err_64);
8045
+ throw err_64;
7892
8046
  case 4: return [2, {
7893
8047
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7894
8048
  additionalSigners: additionalSigners
@@ -7897,7 +8051,7 @@ var PerpetualsClient = (function () {
7897
8051
  });
7898
8052
  }); };
7899
8053
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
7900
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8054
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_65;
7901
8055
  return __generator(this, function (_a) {
7902
8056
  switch (_a.label) {
7903
8057
  case 0:
@@ -7926,9 +8080,9 @@ var PerpetualsClient = (function () {
7926
8080
  instructions.push(resizeInternalOracleInstruction);
7927
8081
  return [3, 4];
7928
8082
  case 3:
7929
- err_64 = _a.sent();
7930
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7931
- throw err_64;
8083
+ err_65 = _a.sent();
8084
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_65);
8085
+ throw err_65;
7932
8086
  case 4: return [2, {
7933
8087
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7934
8088
  additionalSigners: additionalSigners