flash-sdk 9.0.5-alpha.7 → 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,12 @@ 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);
751
732
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
733
+ var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
752
734
  var feeUsd = constants_1.BN_ZERO;
753
735
  var feeAmount = constants_1.BN_ZERO;
754
736
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -757,11 +739,74 @@ var PerpetualsClient = (function () {
757
739
  }
758
740
  else {
759
741
  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);
742
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
761
743
  if (discountBps.gt(constants_1.BN_ZERO)) {
762
744
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
763
745
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
764
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
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);
795
+ var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
796
+ var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
797
+ var feeUsd = constants_1.BN_ZERO;
798
+ var feeAmount = constants_1.BN_ZERO;
799
+ var feeUsdAfterDiscount = constants_1.BN_ZERO;
800
+ var feeAmountAfterDiscount = constants_1.BN_ZERO;
801
+ if (positionAccount !== null && sizeDeltaAmount.isZero()) {
802
+ }
803
+ else {
804
+ feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
805
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
806
+ if (discountBps.gt(constants_1.BN_ZERO)) {
807
+ feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
808
+ feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
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();
@@ -5418,18 +5498,179 @@ var PerpetualsClient = (function () {
5418
5498
  });
5419
5499
  });
5420
5500
  };
5421
- 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) {
5422
5592
  var args_1 = [];
5423
5593
  for (var _i = 3; _i < arguments.length; _i++) {
5424
5594
  args_1[_i - 3] = arguments[_i];
5425
5595
  }
5426
- return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5427
- 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;
5428
5666
  if (createUserATA === void 0) { createUserATA = true; }
5429
5667
  return __generator(this, function (_b) {
5430
5668
  switch (_b.label) {
5431
5669
  case 0:
5432
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); });
5433
5674
  preInstructions = [];
5434
5675
  instructions = [];
5435
5676
  postInstructions = [];
@@ -5437,43 +5678,59 @@ var PerpetualsClient = (function () {
5437
5678
  _b.label = 1;
5438
5679
  case 1:
5439
5680
  _b.trys.push([1, 5, , 6]);
5440
- rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5441
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5442
- 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);
5443
5684
  _a = createUserATA;
5444
5685
  if (!_a) return [3, 3];
5445
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5686
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5446
5687
  case 2:
5447
5688
  _a = !(_b.sent());
5448
5689
  _b.label = 3;
5449
5690
  case 3:
5450
5691
  if (_a) {
5451
- instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5692
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5452
5693
  }
5453
- return [4, this.program.methods
5454
- .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()
5455
5706
  .accounts({
5456
- owner: owner,
5457
- receivingTokenAccount: userTokenAccount,
5458
- perpetuals: this.perpetuals.publicKey,
5707
+ perpProgram: this.programId,
5708
+ owner: publicKey,
5709
+ receivingTokenAccount: receivingTokenAccount,
5459
5710
  transferAuthority: poolConfig.transferAuthority,
5460
- rebateVault: poolConfig.rebateVault,
5461
- rebateTokenAccount: poolConfig.rebateTokenAccount,
5462
- 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,
5463
5717
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5464
5718
  eventAuthority: this.eventAuthority.publicKey,
5465
- program: this.programId,
5466
- receivingTokenMint: rebateMint,
5719
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5720
+ fbnftRewardsProgram: this.programFbnftReward.programId,
5721
+ rewardVault: rewardVault,
5722
+ rewardTokenAccount: rewardTokenAccount
5467
5723
  })
5724
+ .remainingAccounts(tradingAccount)
5468
5725
  .instruction()];
5469
5726
  case 4:
5470
- collectRebateInstruction = _b.sent();
5471
- instructions.push(collectRebateInstruction);
5727
+ withdrawStakeInstruction = _b.sent();
5728
+ instructions.push(withdrawStakeInstruction);
5472
5729
  return [3, 6];
5473
5730
  case 5:
5474
- err_28 = _b.sent();
5475
- console.log("perpClient collectRebateInstruction error:: ", err_28);
5476
- throw err_28;
5731
+ err_31 = _b.sent();
5732
+ console.log("perpClient withdrawStake error:: ", err_31);
5733
+ throw err_31;
5477
5734
  case 6: return [2, {
5478
5735
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5479
5736
  additionalSigners: additionalSigners
@@ -5482,60 +5739,13 @@ var PerpetualsClient = (function () {
5482
5739
  });
5483
5740
  });
5484
5741
  };
5485
- this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5486
- var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5487
- return __generator(this, function (_a) {
5488
- switch (_a.label) {
5489
- case 0:
5490
- preInstructions = [];
5491
- instructions = [];
5492
- postInstructions = [];
5493
- additionalSigners = [];
5494
- _a.label = 1;
5495
- case 1:
5496
- _a.trys.push([1, 3, , 4]);
5497
- rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5498
- rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5499
- return [4, this.program.methods
5500
- .settleRebates()
5501
- .accounts({
5502
- transferAuthority: poolConfig.transferAuthority,
5503
- perpetuals: this.perpetuals.publicKey,
5504
- pool: poolConfig.poolAddress,
5505
- rewardCustody: rewardCustody.custodyAccount,
5506
- rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5507
- rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5508
- rebateVault: poolConfig.rebateVault,
5509
- rebateTokenAccount: poolConfig.rebateTokenAccount,
5510
- tokenMint: rebateMint,
5511
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5512
- eventAuthority: this.eventAuthority.publicKey,
5513
- program: this.programId,
5514
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5515
- })
5516
- .instruction()];
5517
- case 2:
5518
- settleRebatesInstruction = _a.sent();
5519
- instructions.push(settleRebatesInstruction);
5520
- return [3, 4];
5521
- case 3:
5522
- err_29 = _a.sent();
5523
- console.log("perpClient settleRebatesInstruction error:: ", err_29);
5524
- throw err_29;
5525
- case 4: return [2, {
5526
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5527
- additionalSigners: additionalSigners
5528
- }];
5529
- }
5530
- });
5531
- }); };
5532
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) {
5533
5743
  var args_1 = [];
5534
5744
  for (var _i = 11; _i < arguments.length; _i++) {
5535
5745
  args_1[_i - 11] = arguments[_i];
5536
5746
  }
5537
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) {
5538
- 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;
5539
5749
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5540
5750
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5541
5751
  return __generator(this, function (_c) {
@@ -5641,9 +5851,9 @@ var PerpetualsClient = (function () {
5641
5851
  instructions.push(placeLimitOrder);
5642
5852
  return [3, 10];
5643
5853
  case 9:
5644
- err_30 = _c.sent();
5645
- console.log("perpClient placeLimitOrder error:: ", err_30);
5646
- throw err_30;
5854
+ err_32 = _c.sent();
5855
+ console.log("perpClient placeLimitOrder error:: ", err_32);
5856
+ throw err_32;
5647
5857
  case 10: return [2, {
5648
5858
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5649
5859
  additionalSigners: additionalSigners
@@ -5658,7 +5868,7 @@ var PerpetualsClient = (function () {
5658
5868
  args_1[_i - 11] = arguments[_i];
5659
5869
  }
5660
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) {
5661
- 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;
5662
5872
  if (createUserATA === void 0) { createUserATA = true; }
5663
5873
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5664
5874
  return __generator(this, function (_b) {
@@ -5749,9 +5959,9 @@ var PerpetualsClient = (function () {
5749
5959
  instructions.push(editLimitOrder);
5750
5960
  return [3, 8];
5751
5961
  case 7:
5752
- err_31 = _b.sent();
5753
- console.log("perpClient editLimitOrder error:: ", err_31);
5754
- throw err_31;
5962
+ err_33 = _b.sent();
5963
+ console.log("perpClient editLimitOrder error:: ", err_33);
5964
+ throw err_33;
5755
5965
  case 8: return [2, {
5756
5966
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5757
5967
  additionalSigners: additionalSigners
@@ -5765,10 +5975,11 @@ var PerpetualsClient = (function () {
5765
5975
  for (var _i = 7; _i < arguments.length; _i++) {
5766
5976
  args_1[_i - 7] = arguments[_i];
5767
5977
  }
5768
- 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) {
5769
- 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;
5770
5980
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
5771
5981
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
5982
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
5772
5983
  return __generator(this, function (_a) {
5773
5984
  switch (_a.label) {
5774
5985
  case 0:
@@ -5811,16 +6022,16 @@ var PerpetualsClient = (function () {
5811
6022
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5812
6023
  collateralMint: collateralCustodyConfig.mintKey,
5813
6024
  })
5814
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6025
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5815
6026
  .instruction()];
5816
6027
  case 2:
5817
6028
  executeLimitOrder = _a.sent();
5818
6029
  instructions.push(executeLimitOrder);
5819
6030
  return [3, 4];
5820
6031
  case 3:
5821
- err_32 = _a.sent();
5822
- console.log("perpClient executeLimitOrder error:: ", err_32);
5823
- throw err_32;
6032
+ err_34 = _a.sent();
6033
+ console.log("perpClient executeLimitOrder error:: ", err_34);
6034
+ throw err_34;
5824
6035
  case 4: return [2, {
5825
6036
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5826
6037
  additionalSigners: additionalSigners
@@ -5834,10 +6045,11 @@ var PerpetualsClient = (function () {
5834
6045
  for (var _i = 8; _i < arguments.length; _i++) {
5835
6046
  args_1[_i - 8] = arguments[_i];
5836
6047
  }
5837
- 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) {
5838
- 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;
5839
6050
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
5840
6051
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6052
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
5841
6053
  return __generator(this, function (_a) {
5842
6054
  switch (_a.label) {
5843
6055
  case 0:
@@ -5883,16 +6095,16 @@ var PerpetualsClient = (function () {
5883
6095
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5884
6096
  collateralMint: collateralCustodyConfig.mintKey,
5885
6097
  })
5886
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6098
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5887
6099
  .instruction()];
5888
6100
  case 2:
5889
6101
  executeLimitWithSwap = _a.sent();
5890
6102
  instructions.push(executeLimitWithSwap);
5891
6103
  return [3, 4];
5892
6104
  case 3:
5893
- err_33 = _a.sent();
5894
- console.log("perpClient executeLimitWithSwap error:: ", err_33);
5895
- throw err_33;
6105
+ err_35 = _a.sent();
6106
+ console.log("perpClient executeLimitWithSwap error:: ", err_35);
6107
+ throw err_35;
5896
6108
  case 4: return [2, {
5897
6109
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5898
6110
  additionalSigners: additionalSigners
@@ -5902,7 +6114,7 @@ var PerpetualsClient = (function () {
5902
6114
  });
5903
6115
  };
5904
6116
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5905
- 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;
5906
6118
  return __generator(this, function (_a) {
5907
6119
  switch (_a.label) {
5908
6120
  case 0:
@@ -5950,9 +6162,9 @@ var PerpetualsClient = (function () {
5950
6162
  instructions.push(placeTriggerOrder);
5951
6163
  return [3, 4];
5952
6164
  case 3:
5953
- err_34 = _a.sent();
5954
- console.log("perpClient placeTriggerOrder error:: ", err_34);
5955
- throw err_34;
6165
+ err_36 = _a.sent();
6166
+ console.log("perpClient placeTriggerOrder error:: ", err_36);
6167
+ throw err_36;
5956
6168
  case 4: return [2, {
5957
6169
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5958
6170
  additionalSigners: additionalSigners
@@ -5961,7 +6173,7 @@ var PerpetualsClient = (function () {
5961
6173
  });
5962
6174
  }); };
5963
6175
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5964
- 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;
5965
6177
  return __generator(this, function (_a) {
5966
6178
  switch (_a.label) {
5967
6179
  case 0:
@@ -6008,9 +6220,9 @@ var PerpetualsClient = (function () {
6008
6220
  instructions.push(editTriggerOrder);
6009
6221
  return [3, 4];
6010
6222
  case 3:
6011
- err_35 = _a.sent();
6012
- console.log("perpClient editTriggerOrder error:: ", err_35);
6013
- throw err_35;
6223
+ err_37 = _a.sent();
6224
+ console.log("perpClient editTriggerOrder error:: ", err_37);
6225
+ throw err_37;
6014
6226
  case 4: return [2, {
6015
6227
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6016
6228
  additionalSigners: additionalSigners
@@ -6019,7 +6231,7 @@ var PerpetualsClient = (function () {
6019
6231
  });
6020
6232
  }); };
6021
6233
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6022
- 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;
6023
6235
  return __generator(this, function (_a) {
6024
6236
  switch (_a.label) {
6025
6237
  case 0:
@@ -6052,9 +6264,9 @@ var PerpetualsClient = (function () {
6052
6264
  instructions.push(cancelTriggerOrder);
6053
6265
  return [3, 4];
6054
6266
  case 3:
6055
- err_36 = _a.sent();
6056
- console.log("perpClient cancelTriggerOrder error:: ", err_36);
6057
- throw err_36;
6267
+ err_38 = _a.sent();
6268
+ console.log("perpClient cancelTriggerOrder error:: ", err_38);
6269
+ throw err_38;
6058
6270
  case 4: return [2, {
6059
6271
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6060
6272
  additionalSigners: additionalSigners
@@ -6063,7 +6275,7 @@ var PerpetualsClient = (function () {
6063
6275
  });
6064
6276
  }); };
6065
6277
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6066
- 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;
6067
6279
  return __generator(this, function (_a) {
6068
6280
  switch (_a.label) {
6069
6281
  case 0:
@@ -6094,9 +6306,9 @@ var PerpetualsClient = (function () {
6094
6306
  instructions.push(cancelAllTriggerOrders);
6095
6307
  return [3, 4];
6096
6308
  case 3:
6097
- err_37 = _a.sent();
6098
- console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6099
- throw err_37;
6309
+ err_39 = _a.sent();
6310
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_39);
6311
+ throw err_39;
6100
6312
  case 4: return [2, {
6101
6313
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6102
6314
  additionalSigners: additionalSigners
@@ -6109,12 +6321,13 @@ var PerpetualsClient = (function () {
6109
6321
  for (var _i = 9; _i < arguments.length; _i++) {
6110
6322
  args_1[_i - 9] = arguments[_i];
6111
6323
  }
6112
- 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) {
6113
- 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;
6114
6326
  if (createUserATA === void 0) { createUserATA = true; }
6115
6327
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6116
6328
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6117
6329
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6330
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6118
6331
  return __generator(this, function (_e) {
6119
6332
  switch (_e.label) {
6120
6333
  case 0:
@@ -6209,16 +6422,16 @@ var PerpetualsClient = (function () {
6209
6422
  collateralMint: collateralCustodyConfig.mintKey,
6210
6423
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6211
6424
  })
6212
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6425
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6213
6426
  .instruction()];
6214
6427
  case 8:
6215
6428
  executeTriggerWithSwap = _e.sent();
6216
6429
  instructions.push(executeTriggerWithSwap);
6217
6430
  return [3, 10];
6218
6431
  case 9:
6219
- err_38 = _e.sent();
6220
- console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6221
- throw err_38;
6432
+ err_40 = _e.sent();
6433
+ console.log("perpClient executeTriggerWithSwap error:: ", err_40);
6434
+ throw err_40;
6222
6435
  case 10: return [2, {
6223
6436
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6224
6437
  additionalSigners: additionalSigners
@@ -6232,12 +6445,13 @@ var PerpetualsClient = (function () {
6232
6445
  for (var _i = 8; _i < arguments.length; _i++) {
6233
6446
  args_1[_i - 8] = arguments[_i];
6234
6447
  }
6235
- 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) {
6236
- 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;
6237
6450
  if (createUserATA === void 0) { createUserATA = true; }
6238
6451
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6239
6452
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6240
6453
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6454
+ if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6241
6455
  return __generator(this, function (_b) {
6242
6456
  switch (_b.label) {
6243
6457
  case 0:
@@ -6297,16 +6511,16 @@ var PerpetualsClient = (function () {
6297
6511
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6298
6512
  receivingMint: collateralCustodyConfig.mintKey
6299
6513
  })
6300
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6514
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6301
6515
  .instruction()];
6302
6516
  case 6:
6303
6517
  executeTriggerOrder = _b.sent();
6304
6518
  instructions.push(executeTriggerOrder);
6305
6519
  return [3, 8];
6306
6520
  case 7:
6307
- err_39 = _b.sent();
6308
- console.log("perpClient executeTriggerOrder error:: ", err_39);
6309
- throw err_39;
6521
+ err_41 = _b.sent();
6522
+ console.log("perpClient executeTriggerOrder error:: ", err_41);
6523
+ throw err_41;
6310
6524
  case 8: return [2, {
6311
6525
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6312
6526
  additionalSigners: additionalSigners
@@ -6321,7 +6535,7 @@ var PerpetualsClient = (function () {
6321
6535
  args_1[_i - 5] = arguments[_i];
6322
6536
  }
6323
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) {
6324
- 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;
6325
6539
  if (useFeesPool === void 0) { useFeesPool = false; }
6326
6540
  if (createUserATA === void 0) { createUserATA = true; }
6327
6541
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6468,7 +6682,7 @@ var PerpetualsClient = (function () {
6468
6682
  _g.label = 16;
6469
6683
  case 16:
6470
6684
  if (_d) {
6471
- 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));
6472
6686
  }
6473
6687
  _g.label = 17;
6474
6688
  case 17:
@@ -6526,9 +6740,9 @@ var PerpetualsClient = (function () {
6526
6740
  }
6527
6741
  return [3, 20];
6528
6742
  case 19:
6529
- err_40 = _g.sent();
6530
- console.error("perpClient Swap error:: ", err_40);
6531
- throw err_40;
6743
+ err_42 = _g.sent();
6744
+ console.error("perpClient Swap error:: ", err_42);
6745
+ throw err_42;
6532
6746
  case 20: return [2, {
6533
6747
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6534
6748
  additionalSigners: additionalSigners
@@ -6538,7 +6752,7 @@ var PerpetualsClient = (function () {
6538
6752
  });
6539
6753
  };
6540
6754
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6541
- 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;
6542
6756
  return __generator(this, function (_b) {
6543
6757
  switch (_b.label) {
6544
6758
  case 0:
@@ -6583,7 +6797,11 @@ var PerpetualsClient = (function () {
6583
6797
  rewardCustody: rewardCustody.custodyAccount,
6584
6798
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
6585
6799
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
6800
+ custody: custody.custodyAccount,
6801
+ custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
6802
+ custodyTokenAccount: custody.tokenAccount,
6586
6803
  eventAuthority: this.eventAuthority.publicKey,
6804
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
6587
6805
  program: this.programId,
6588
6806
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
6589
6807
  })
@@ -6594,9 +6812,9 @@ var PerpetualsClient = (function () {
6594
6812
  instructions.push(inx);
6595
6813
  return [3, 4];
6596
6814
  case 3:
6597
- err_41 = _b.sent();
6598
- console.error("perpClient Swap error:: ", err_41);
6599
- throw err_41;
6815
+ err_43 = _b.sent();
6816
+ console.error("perpClient Swap error:: ", err_43);
6817
+ throw err_43;
6600
6818
  case 4: return [2, {
6601
6819
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6602
6820
  additionalSigners: additionalSigners
@@ -6605,7 +6823,7 @@ var PerpetualsClient = (function () {
6605
6823
  });
6606
6824
  }); };
6607
6825
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6608
- 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;
6609
6827
  return __generator(this, function (_d) {
6610
6828
  switch (_d.label) {
6611
6829
  case 0:
@@ -6653,9 +6871,9 @@ var PerpetualsClient = (function () {
6653
6871
  instructions.push(setLpTokenPriceInstruction);
6654
6872
  return [3, 4];
6655
6873
  case 3:
6656
- err_42 = _d.sent();
6657
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6658
- throw err_42;
6874
+ err_44 = _d.sent();
6875
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_44);
6876
+ throw err_44;
6659
6877
  case 4: return [2, {
6660
6878
  instructions: __spreadArray([], instructions, true),
6661
6879
  additionalSigners: additionalSigners
@@ -6703,7 +6921,7 @@ var PerpetualsClient = (function () {
6703
6921
  });
6704
6922
  }); };
6705
6923
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
6706
- var adminMetas, _i, admins_2, admin, err_43;
6924
+ var adminMetas, _i, admins_2, admin, err_45;
6707
6925
  return __generator(this, function (_a) {
6708
6926
  switch (_a.label) {
6709
6927
  case 0:
@@ -6733,16 +6951,16 @@ var PerpetualsClient = (function () {
6733
6951
  _a.sent();
6734
6952
  return [3, 4];
6735
6953
  case 3:
6736
- err_43 = _a.sent();
6954
+ err_45 = _a.sent();
6737
6955
  if (this.printErrors) {
6738
- console.error("setAdminSigners err:", err_43);
6956
+ console.error("setAdminSigners err:", err_45);
6739
6957
  }
6740
- throw err_43;
6958
+ throw err_45;
6741
6959
  case 4: return [2];
6742
6960
  }
6743
6961
  });
6744
6962
  }); };
6745
- 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 () {
6746
6964
  return __generator(this, function (_a) {
6747
6965
  switch (_a.label) {
6748
6966
  case 0: return [4, this.program.methods
@@ -6754,11 +6972,7 @@ var PerpetualsClient = (function () {
6754
6972
  metadataTitle: metadataTitle,
6755
6973
  metadataUri: metadataUri,
6756
6974
  stakingFeeShareBps: stakingFeeShareBps,
6757
- vpVolumeFactor: vpVolumeFactor,
6758
- stakingFeeBoostBps: stakingFeeBoostBps,
6759
- minLpPriceUsd: minLpPriceUsd,
6760
- maxLpPriceUsd: maxLpPriceUsd,
6761
- thresholdUsd: thresholdUsd
6975
+ vpVolumeFactor: vpVolumeFactor
6762
6976
  })
6763
6977
  .accounts({
6764
6978
  admin: this.provider.wallet.publicKey,
@@ -6806,7 +7020,7 @@ var PerpetualsClient = (function () {
6806
7020
  }
6807
7021
  });
6808
7022
  }); };
6809
- 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 () {
6810
7024
  var trx_id, error_3;
6811
7025
  return __generator(this, function (_a) {
6812
7026
  switch (_a.label) {
@@ -6824,9 +7038,6 @@ var PerpetualsClient = (function () {
6824
7038
  fees: fees,
6825
7039
  borrowRate: borrowRate,
6826
7040
  ratios: ratios,
6827
- rewardThreshold: rewardThreshold,
6828
- minReserveUsd: minReserveUsd,
6829
- limitPriceBufferBps: limitPriceBufferBps
6830
7041
  })
6831
7042
  .accounts({
6832
7043
  admin: this.admin,
@@ -6933,7 +7144,7 @@ var PerpetualsClient = (function () {
6933
7144
  });
6934
7145
  }); };
6935
7146
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6936
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7147
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_46;
6937
7148
  return __generator(this, function (_a) {
6938
7149
  switch (_a.label) {
6939
7150
  case 0:
@@ -6966,9 +7177,9 @@ var PerpetualsClient = (function () {
6966
7177
  instructions.push(withdrawFeesIx);
6967
7178
  return [3, 5];
6968
7179
  case 4:
6969
- err_44 = _a.sent();
6970
- console.log("perpClient setPool error:: ", err_44);
6971
- throw err_44;
7180
+ err_46 = _a.sent();
7181
+ console.log("perpClient setPool error:: ", err_46);
7182
+ throw err_46;
6972
7183
  case 5: return [2, {
6973
7184
  instructions: __spreadArray([], instructions, true),
6974
7185
  additionalSigners: additionalSigners
@@ -6977,7 +7188,7 @@ var PerpetualsClient = (function () {
6977
7188
  });
6978
7189
  }); };
6979
7190
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6980
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7191
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_47;
6981
7192
  return __generator(this, function (_a) {
6982
7193
  switch (_a.label) {
6983
7194
  case 0:
@@ -7011,9 +7222,9 @@ var PerpetualsClient = (function () {
7011
7222
  instructions.push(moveProtocolFeesIx);
7012
7223
  return [3, 4];
7013
7224
  case 3:
7014
- err_45 = _a.sent();
7015
- console.log("perpClient setPool error:: ", err_45);
7016
- throw err_45;
7225
+ err_47 = _a.sent();
7226
+ console.log("perpClient setPool error:: ", err_47);
7227
+ throw err_47;
7017
7228
  case 4: return [2, {
7018
7229
  instructions: __spreadArray([], instructions, true),
7019
7230
  additionalSigners: additionalSigners
@@ -7022,7 +7233,7 @@ var PerpetualsClient = (function () {
7022
7233
  });
7023
7234
  }); };
7024
7235
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7025
- var publicKey, setProtocolFeeShareBpsIx, err_46;
7236
+ var publicKey, setProtocolFeeShareBpsIx, err_48;
7026
7237
  return __generator(this, function (_a) {
7027
7238
  switch (_a.label) {
7028
7239
  case 0:
@@ -7042,15 +7253,15 @@ var PerpetualsClient = (function () {
7042
7253
  setProtocolFeeShareBpsIx = _a.sent();
7043
7254
  return [2, setProtocolFeeShareBpsIx];
7044
7255
  case 2:
7045
- err_46 = _a.sent();
7046
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7047
- throw err_46;
7256
+ err_48 = _a.sent();
7257
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_48);
7258
+ throw err_48;
7048
7259
  case 3: return [2];
7049
7260
  }
7050
7261
  });
7051
7262
  }); };
7052
7263
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7053
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7264
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_49;
7054
7265
  return __generator(this, function (_a) {
7055
7266
  switch (_a.label) {
7056
7267
  case 0:
@@ -7077,9 +7288,9 @@ var PerpetualsClient = (function () {
7077
7288
  instructions.push(setPermissionsInstruction);
7078
7289
  return [3, 4];
7079
7290
  case 3:
7080
- err_47 = _a.sent();
7081
- console.log("perpClient setPool error:: ", err_47);
7082
- throw err_47;
7291
+ err_49 = _a.sent();
7292
+ console.log("perpClient setPool error:: ", err_49);
7293
+ throw err_49;
7083
7294
  case 4: return [2, {
7084
7295
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7085
7296
  additionalSigners: additionalSigners
@@ -7088,7 +7299,7 @@ var PerpetualsClient = (function () {
7088
7299
  });
7089
7300
  }); };
7090
7301
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7091
- 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;
7092
7303
  var _f;
7093
7304
  return __generator(this, function (_g) {
7094
7305
  switch (_g.label) {
@@ -7149,9 +7360,9 @@ var PerpetualsClient = (function () {
7149
7360
  instructions.push(reimburse);
7150
7361
  return [3, 5];
7151
7362
  case 4:
7152
- err_48 = _g.sent();
7153
- console.log("perpClient setPool error:: ", err_48);
7154
- throw err_48;
7363
+ err_50 = _g.sent();
7364
+ console.log("perpClient setPool error:: ", err_50);
7365
+ throw err_50;
7155
7366
  case 5: return [2, {
7156
7367
  instructions: __spreadArray([], instructions, true),
7157
7368
  additionalSigners: additionalSigners
@@ -7160,7 +7371,7 @@ var PerpetualsClient = (function () {
7160
7371
  });
7161
7372
  }); };
7162
7373
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7163
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7374
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_51;
7164
7375
  return __generator(this, function (_a) {
7165
7376
  switch (_a.label) {
7166
7377
  case 0:
@@ -7194,9 +7405,9 @@ var PerpetualsClient = (function () {
7194
7405
  instructions.push(setInternalOraclePrice);
7195
7406
  return [3, 4];
7196
7407
  case 3:
7197
- err_49 = _a.sent();
7198
- console.log("perpClient setInternalOracleAccount error:: ", err_49);
7199
- throw err_49;
7408
+ err_51 = _a.sent();
7409
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7410
+ throw err_51;
7200
7411
  case 4: return [2, {
7201
7412
  instructions: __spreadArray([], instructions, true),
7202
7413
  additionalSigners: additionalSigners
@@ -7205,7 +7416,7 @@ var PerpetualsClient = (function () {
7205
7416
  });
7206
7417
  }); };
7207
7418
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7208
- 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;
7209
7420
  return __generator(this, function (_a) {
7210
7421
  switch (_a.label) {
7211
7422
  case 0:
@@ -7251,9 +7462,9 @@ var PerpetualsClient = (function () {
7251
7462
  instructions.push(setInternalOraclePrice);
7252
7463
  return [3, 4];
7253
7464
  case 3:
7254
- err_50 = _a.sent();
7255
- console.log("perpClient setInternalOracleAccount error:: ", err_50);
7256
- throw err_50;
7465
+ err_52 = _a.sent();
7466
+ console.log("perpClient setInternalOracleAccount error:: ", err_52);
7467
+ throw err_52;
7257
7468
  case 4: return [2, {
7258
7469
  instructions: __spreadArray([], instructions, true),
7259
7470
  additionalSigners: additionalSigners
@@ -7262,7 +7473,7 @@ var PerpetualsClient = (function () {
7262
7473
  });
7263
7474
  }); };
7264
7475
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7265
- 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;
7266
7477
  return __generator(this, function (_a) {
7267
7478
  switch (_a.label) {
7268
7479
  case 0:
@@ -7302,9 +7513,9 @@ var PerpetualsClient = (function () {
7302
7513
  instructions.push(setInternalOraclePrice);
7303
7514
  return [3, 4];
7304
7515
  case 3:
7305
- err_51 = _a.sent();
7306
- console.log("perpClient setInternalOracleAccount error:: ", err_51);
7307
- throw err_51;
7516
+ err_53 = _a.sent();
7517
+ console.log("perpClient setInternalOracleAccount error:: ", err_53);
7518
+ throw err_53;
7308
7519
  case 4: return [2, {
7309
7520
  instructions: __spreadArray([], instructions, true),
7310
7521
  additionalSigners: additionalSigners
@@ -7313,7 +7524,7 @@ var PerpetualsClient = (function () {
7313
7524
  });
7314
7525
  }); };
7315
7526
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7316
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7527
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_54;
7317
7528
  return __generator(this, function (_a) {
7318
7529
  switch (_a.label) {
7319
7530
  case 0:
@@ -7351,8 +7562,8 @@ var PerpetualsClient = (function () {
7351
7562
  instructions.push(renameFlp);
7352
7563
  return [3, 4];
7353
7564
  case 3:
7354
- err_52 = _a.sent();
7355
- console.log("perpClient renameFlp error:: ", err_52);
7565
+ err_54 = _a.sent();
7566
+ console.log("perpClient renameFlp error:: ", err_54);
7356
7567
  return [3, 4];
7357
7568
  case 4: return [2, {
7358
7569
  instructions: __spreadArray([], instructions, true),
@@ -7362,7 +7573,7 @@ var PerpetualsClient = (function () {
7362
7573
  });
7363
7574
  }); };
7364
7575
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7365
- 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;
7366
7577
  return __generator(this, function (_a) {
7367
7578
  switch (_a.label) {
7368
7579
  case 0:
@@ -7400,9 +7611,9 @@ var PerpetualsClient = (function () {
7400
7611
  instructions.push(initStakeInstruction);
7401
7612
  return [3, 4];
7402
7613
  case 3:
7403
- err_53 = _a.sent();
7404
- console.log("perpClient InitStaking error:: ", err_53);
7405
- throw err_53;
7614
+ err_55 = _a.sent();
7615
+ console.log("perpClient InitStaking error:: ", err_55);
7616
+ throw err_55;
7406
7617
  case 4: return [2, {
7407
7618
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7408
7619
  additionalSigners: additionalSigners
@@ -7411,7 +7622,7 @@ var PerpetualsClient = (function () {
7411
7622
  });
7412
7623
  }); };
7413
7624
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7414
- 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;
7415
7626
  return __generator(this, function (_a) {
7416
7627
  switch (_a.label) {
7417
7628
  case 0:
@@ -7455,9 +7666,9 @@ var PerpetualsClient = (function () {
7455
7666
  instructions.push(initCompoundingInstruction);
7456
7667
  return [3, 4];
7457
7668
  case 3:
7458
- err_54 = _a.sent();
7459
- console.log("perpClient initCompounding error:: ", err_54);
7460
- throw err_54;
7669
+ err_56 = _a.sent();
7670
+ console.log("perpClient initCompounding error:: ", err_56);
7671
+ throw err_56;
7461
7672
  case 4: return [2, {
7462
7673
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7463
7674
  additionalSigners: additionalSigners
@@ -7466,7 +7677,7 @@ var PerpetualsClient = (function () {
7466
7677
  });
7467
7678
  }); };
7468
7679
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7469
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7680
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_57;
7470
7681
  return __generator(this, function (_a) {
7471
7682
  switch (_a.label) {
7472
7683
  case 0:
@@ -7507,9 +7718,9 @@ var PerpetualsClient = (function () {
7507
7718
  instructions.push(initTokenVaultInstruction);
7508
7719
  return [3, 4];
7509
7720
  case 3:
7510
- err_55 = _a.sent();
7511
- console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7512
- throw err_55;
7721
+ err_57 = _a.sent();
7722
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_57);
7723
+ throw err_57;
7513
7724
  case 4: return [2, {
7514
7725
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7515
7726
  additionalSigners: additionalSigners
@@ -7518,7 +7729,7 @@ var PerpetualsClient = (function () {
7518
7729
  });
7519
7730
  }); };
7520
7731
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7521
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7732
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_58;
7522
7733
  return __generator(this, function (_a) {
7523
7734
  switch (_a.label) {
7524
7735
  case 0:
@@ -7549,9 +7760,9 @@ var PerpetualsClient = (function () {
7549
7760
  instructions.push(setTokenVaultConfigInstruction);
7550
7761
  return [3, 4];
7551
7762
  case 3:
7552
- err_56 = _a.sent();
7553
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7554
- throw err_56;
7763
+ err_58 = _a.sent();
7764
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_58);
7765
+ throw err_58;
7555
7766
  case 4: return [2, {
7556
7767
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7557
7768
  additionalSigners: additionalSigners
@@ -7560,7 +7771,7 @@ var PerpetualsClient = (function () {
7560
7771
  });
7561
7772
  }); };
7562
7773
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7563
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
7774
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_59;
7564
7775
  return __generator(this, function (_a) {
7565
7776
  switch (_a.label) {
7566
7777
  case 0:
@@ -7599,9 +7810,9 @@ var PerpetualsClient = (function () {
7599
7810
  instructions.push(withdrawInstantFeeInstruction);
7600
7811
  return [3, 6];
7601
7812
  case 5:
7602
- err_57 = _a.sent();
7603
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7604
- throw err_57;
7813
+ err_59 = _a.sent();
7814
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_59);
7815
+ throw err_59;
7605
7816
  case 6: return [2, {
7606
7817
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7607
7818
  additionalSigners: additionalSigners
@@ -7610,7 +7821,7 @@ var PerpetualsClient = (function () {
7610
7821
  });
7611
7822
  }); };
7612
7823
  this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7613
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7824
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_60;
7614
7825
  return __generator(this, function (_a) {
7615
7826
  switch (_a.label) {
7616
7827
  case 0:
@@ -7649,9 +7860,9 @@ var PerpetualsClient = (function () {
7649
7860
  instructions.push(withdrawUnclaimedTokensInstruction);
7650
7861
  return [3, 6];
7651
7862
  case 5:
7652
- err_58 = _a.sent();
7653
- console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7654
- throw err_58;
7863
+ err_60 = _a.sent();
7864
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_60);
7865
+ throw err_60;
7655
7866
  case 6: return [2, {
7656
7867
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7657
7868
  additionalSigners: additionalSigners
@@ -7660,7 +7871,7 @@ var PerpetualsClient = (function () {
7660
7871
  });
7661
7872
  }); };
7662
7873
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7663
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
7874
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_61;
7664
7875
  return __generator(this, function (_a) {
7665
7876
  switch (_a.label) {
7666
7877
  case 0:
@@ -7697,55 +7908,9 @@ var PerpetualsClient = (function () {
7697
7908
  instructions.push(initRevenueTokenAccountInstruction);
7698
7909
  return [3, 4];
7699
7910
  case 3:
7700
- err_59 = _a.sent();
7701
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7702
- throw err_59;
7703
- case 4: return [2, {
7704
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7705
- additionalSigners: additionalSigners
7706
- }];
7707
- }
7708
- });
7709
- }); };
7710
- this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7711
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7712
- return __generator(this, function (_a) {
7713
- switch (_a.label) {
7714
- case 0:
7715
- publicKey = this.provider.wallet.publicKey;
7716
- preInstructions = [];
7717
- instructions = [];
7718
- postInstructions = [];
7719
- additionalSigners = [];
7720
- _a.label = 1;
7721
- case 1:
7722
- _a.trys.push([1, 3, , 4]);
7723
- rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7724
- return [4, this.program.methods
7725
- .initRebateVault({
7726
- allowRebatePayout: allowRebatePayout
7727
- })
7728
- .accounts({
7729
- admin: publicKey,
7730
- multisig: this.multisig.publicKey,
7731
- transferAuthority: poolConfig.transferAuthority,
7732
- perpetuals: this.perpetuals.publicKey,
7733
- rebateMint: rebateCustodyMint,
7734
- rebateTokenAccount: poolConfig.rebateTokenAccount,
7735
- rebateVault: poolConfig.rebateVault,
7736
- systemProgram: web3_js_1.SystemProgram.programId,
7737
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7738
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
7739
- })
7740
- .instruction()];
7741
- case 2:
7742
- initRebateVaultInstruction = _a.sent();
7743
- instructions.push(initRebateVaultInstruction);
7744
- return [3, 4];
7745
- case 3:
7746
- err_60 = _a.sent();
7747
- console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7748
- throw err_60;
7911
+ err_61 = _a.sent();
7912
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_61);
7913
+ throw err_61;
7749
7914
  case 4: return [2, {
7750
7915
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7751
7916
  additionalSigners: additionalSigners
@@ -7754,7 +7919,7 @@ var PerpetualsClient = (function () {
7754
7919
  });
7755
7920
  }); };
7756
7921
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7757
- 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;
7758
7923
  return __generator(this, function (_a) {
7759
7924
  switch (_a.label) {
7760
7925
  case 0:
@@ -7793,9 +7958,9 @@ var PerpetualsClient = (function () {
7793
7958
  instructions.push(distributeTokenRewardInstruction);
7794
7959
  return [3, 4];
7795
7960
  case 3:
7796
- err_61 = _a.sent();
7797
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7798
- throw err_61;
7961
+ err_62 = _a.sent();
7962
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_62);
7963
+ throw err_62;
7799
7964
  case 4: return [2, {
7800
7965
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7801
7966
  additionalSigners: additionalSigners
@@ -7804,7 +7969,7 @@ var PerpetualsClient = (function () {
7804
7969
  });
7805
7970
  }); };
7806
7971
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
7807
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
7972
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_63;
7808
7973
  return __generator(this, function (_a) {
7809
7974
  switch (_a.label) {
7810
7975
  case 0:
@@ -7832,9 +7997,9 @@ var PerpetualsClient = (function () {
7832
7997
  instructions.push(setTokenStakeLevelInstruction);
7833
7998
  return [3, 4];
7834
7999
  case 3:
7835
- err_62 = _a.sent();
7836
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7837
- throw err_62;
8000
+ err_63 = _a.sent();
8001
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_63);
8002
+ throw err_63;
7838
8003
  case 4: return [2, {
7839
8004
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7840
8005
  additionalSigners: additionalSigners
@@ -7843,7 +8008,7 @@ var PerpetualsClient = (function () {
7843
8008
  });
7844
8009
  }); };
7845
8010
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7846
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8011
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_64;
7847
8012
  return __generator(this, function (_a) {
7848
8013
  switch (_a.label) {
7849
8014
  case 0:
@@ -7875,9 +8040,9 @@ var PerpetualsClient = (function () {
7875
8040
  instructions.push(setTokenRewardInstruction);
7876
8041
  return [3, 4];
7877
8042
  case 3:
7878
- err_63 = _a.sent();
7879
- console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7880
- throw err_63;
8043
+ err_64 = _a.sent();
8044
+ console.log("perpClient setTokenRewardInstruction error:: ", err_64);
8045
+ throw err_64;
7881
8046
  case 4: return [2, {
7882
8047
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7883
8048
  additionalSigners: additionalSigners
@@ -7886,7 +8051,7 @@ var PerpetualsClient = (function () {
7886
8051
  });
7887
8052
  }); };
7888
8053
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
7889
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8054
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_65;
7890
8055
  return __generator(this, function (_a) {
7891
8056
  switch (_a.label) {
7892
8057
  case 0:
@@ -7915,9 +8080,9 @@ var PerpetualsClient = (function () {
7915
8080
  instructions.push(resizeInternalOracleInstruction);
7916
8081
  return [3, 4];
7917
8082
  case 3:
7918
- err_64 = _a.sent();
7919
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7920
- throw err_64;
8083
+ err_65 = _a.sent();
8084
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_65);
8085
+ throw err_65;
7921
8086
  case 4: return [2, {
7922
8087
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7923
8088
  additionalSigners: additionalSigners