flash-sdk 9.0.1 → 9.0.2-alpha.1

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.
@@ -638,24 +638,41 @@ var PerpetualsClient = (function () {
638
638
  var averageEntryPrice = totalValue.div(totalSize);
639
639
  return averageEntryPrice;
640
640
  };
641
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
642
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
643
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
644
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
645
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
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);
646
656
  }
647
657
  else {
648
658
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
649
659
  }
650
660
  };
651
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
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, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd) {
652
669
  var finalCollateralAmount = constants_1.BN_ZERO;
653
670
  if (!inputDeltaAmount.isZero()) {
654
671
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
655
672
  finalCollateralAmount = inputDeltaAmount;
656
673
  }
657
674
  else {
658
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
675
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
659
676
  finalCollateralAmount = swapAmountOut;
660
677
  }
661
678
  }
@@ -681,9 +698,8 @@ var PerpetualsClient = (function () {
681
698
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
682
699
  }
683
700
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
684
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
685
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
686
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
701
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals);
702
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
687
703
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
688
704
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
689
705
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
@@ -693,68 +709,6 @@ var PerpetualsClient = (function () {
693
709
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
694
710
  }
695
711
  };
696
- this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
697
- if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
698
- if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
699
- throw new Error("Delta Amounts cannot be negative.");
700
- }
701
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
702
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
703
- if (positionAccount === null) {
704
- var data = __assign({}, types_1.DEFAULT_POSITION);
705
- positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
706
- var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
707
- positionAccount.sizeUsd = sizeUsd_1;
708
- positionAccount.sizeDecimals = targetCustodyAccount.decimals;
709
- positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
710
- positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
711
- }
712
- else {
713
- positionAccount = positionAccount.clone();
714
- var positionEntryPrice = OraclePrice_1.OraclePrice.from({
715
- price: positionAccount.entryPrice.price,
716
- exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
717
- confidence: constants_1.BN_ZERO,
718
- timestamp: constants_1.BN_ZERO
719
- });
720
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
721
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
722
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
723
- }
724
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
725
- positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
726
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
727
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
728
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
729
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
730
- var feeUsd = constants_1.BN_ZERO;
731
- var feeAmount = constants_1.BN_ZERO;
732
- var feeUsdAfterDiscount = constants_1.BN_ZERO;
733
- var feeAmountAfterDiscount = constants_1.BN_ZERO;
734
- if (positionAccount !== null && sizeDeltaAmount.isZero()) {
735
- }
736
- else {
737
- feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
738
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
739
- if (discountBps.gt(constants_1.BN_ZERO)) {
740
- feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
741
- feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
742
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
- }
744
- else {
745
- feeUsdAfterDiscount = feeUsd;
746
- feeAmountAfterDiscount = feeAmount;
747
- }
748
- }
749
- return {
750
- entryOraclePrice: entryOraclePrice,
751
- feeUsd: feeUsd,
752
- feeAmount: feeAmount,
753
- feeUsdAfterDiscount: feeUsdAfterDiscount,
754
- feeAmountAfterDiscount: feeAmountAfterDiscount,
755
- liquidationPrice: liquidationPrice
756
- };
757
- };
758
712
  this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
759
713
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
760
714
  if (enableLogs === void 0) { enableLogs = false; }
@@ -766,8 +720,8 @@ var PerpetualsClient = (function () {
766
720
  if (positionAccount === null) {
767
721
  var data = __assign({}, types_1.DEFAULT_POSITION);
768
722
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
769
- var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
770
- positionAccount.sizeUsd = sizeUsd_2;
723
+ var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
724
+ positionAccount.sizeUsd = sizeUsd_1;
771
725
  positionAccount.sizeDecimals = targetCustodyAccount.decimals;
772
726
  positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
773
727
  positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
@@ -784,12 +738,13 @@ var PerpetualsClient = (function () {
784
738
  var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
785
739
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
786
740
  }
787
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
741
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
742
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
743
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
788
744
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
789
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
790
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
745
+ var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
746
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
791
747
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
792
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
793
748
  var feeUsd = constants_1.BN_ZERO;
794
749
  var feeAmount = constants_1.BN_ZERO;
795
750
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -798,11 +753,11 @@ var PerpetualsClient = (function () {
798
753
  }
799
754
  else {
800
755
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
801
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
756
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
802
757
  if (discountBps.gt(constants_1.BN_ZERO)) {
803
758
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
804
759
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
805
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
760
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
806
761
  }
807
762
  else {
808
763
  feeUsdAfterDiscount = feeUsd;
@@ -861,25 +816,26 @@ var PerpetualsClient = (function () {
861
816
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
862
817
  throw new Error("Delta Amounts cannot be negative ");
863
818
  }
864
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
865
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
866
819
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
867
820
  throw new Error("cannot remove/close more than collateral/Size");
868
821
  }
869
822
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
870
823
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
871
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
824
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
825
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
826
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
827
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
872
828
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
873
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
829
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
874
830
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
875
831
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
876
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
832
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
877
833
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
878
834
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
879
835
  if (discountBps.gt(constants_1.BN_ZERO)) {
880
836
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
881
837
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
882
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
838
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
883
839
  }
884
840
  else {
885
841
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -889,7 +845,7 @@ var PerpetualsClient = (function () {
889
845
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
890
846
  });
891
847
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
892
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
848
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
893
849
  return {
894
850
  exitOraclePrice: exitOraclePrice,
895
851
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -902,13 +858,11 @@ var PerpetualsClient = (function () {
902
858
  };
903
859
  };
904
860
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
905
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
906
- ||
907
- sizeUsd.isZero()) {
861
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
908
862
  return constants_1.BN_ZERO;
909
863
  }
910
864
  var slope = ((targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin)).mul(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))))
911
- .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
865
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
912
866
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
913
867
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
914
868
  return finalSpread;
@@ -923,21 +877,11 @@ var PerpetualsClient = (function () {
923
877
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
924
878
  return exitOraclePrice;
925
879
  };
926
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
927
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
928
- if ((0, types_1.isVariant)(side, 'long')) {
929
- return minPrice;
930
- }
931
- else {
932
- return maxPrice;
933
- }
934
- };
935
880
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
936
881
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
937
882
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
938
883
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
939
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
940
- .multipliedBy(collateralTokenMinPriceUi);
884
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
941
885
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
942
886
  if (!discountBps.isZero()) {
943
887
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -945,20 +889,20 @@ var PerpetualsClient = (function () {
945
889
  }
946
890
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
947
891
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
948
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
949
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
892
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
893
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
950
894
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
951
895
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
952
896
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
953
897
  };
954
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
898
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
955
899
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
956
900
  var finalCollateralAmount = constants_1.BN_ZERO;
957
901
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
958
902
  finalCollateralAmount = amountIn;
959
903
  }
960
904
  else {
961
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
905
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
962
906
  finalCollateralAmount = swapAmountOut;
963
907
  }
964
908
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -972,8 +916,8 @@ var PerpetualsClient = (function () {
972
916
  }
973
917
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
974
918
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
975
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
976
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
919
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
920
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
977
921
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
978
922
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
979
923
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -996,7 +940,7 @@ var PerpetualsClient = (function () {
996
940
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
997
941
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
998
942
  };
999
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
943
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1000
944
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1001
945
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1002
946
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -1013,11 +957,11 @@ var PerpetualsClient = (function () {
1013
957
  collateralInInputToken = collateralAmountWithFee;
1014
958
  }
1015
959
  else {
1016
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
960
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1017
961
  }
1018
962
  return collateralInInputToken;
1019
963
  };
1020
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
964
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1021
965
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1022
966
  if (debugLogs === void 0) { debugLogs = false; }
1023
967
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -1039,10 +983,10 @@ var PerpetualsClient = (function () {
1039
983
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1040
984
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1041
985
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1042
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1043
986
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1044
987
  positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1045
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
988
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
989
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1046
990
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
1047
991
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1048
992
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1052,29 +996,36 @@ var PerpetualsClient = (function () {
1052
996
  }
1053
997
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1054
998
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1055
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
999
+ var currentCollateralUsd = positionDelta.collateralUsd;
1056
1000
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1057
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1058
- var closeAmount, feesAmount;
1001
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1059
1002
  if (debugLogs) {
1060
1003
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1061
1004
  }
1005
+ var closeAmountUsd, feesAmountUsd;
1062
1006
  if (assetsUsd.gte(liabilityUsd)) {
1063
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1064
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1007
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1008
+ feesAmountUsd = totalFeesUsd;
1009
+ }
1010
+ else {
1011
+ closeAmountUsd = constants_1.BN_ZERO;
1012
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1013
+ }
1014
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1015
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1016
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1017
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
1065
1018
  }
1066
1019
  else {
1067
- closeAmount = constants_1.BN_ZERO;
1068
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1020
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1069
1021
  }
1070
1022
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1071
1023
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1072
1024
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1073
1025
  newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1074
1026
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1075
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1027
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1076
1028
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1077
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1078
1029
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1079
1030
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1080
1031
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1089,8 +1040,8 @@ var PerpetualsClient = (function () {
1089
1040
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1090
1041
  if (keepLevSame) {
1091
1042
  var collateralAmountReceived = closeAmount;
1092
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1093
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1043
+ var collateralAmountRecievedUsd = closeAmountUsd;
1044
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmountUsd), maxWithdrawableAmount = _a.maxWithdrawableAmount, diffUsd = _a.diffUsd;
1094
1045
  if (debugLogs) {
1095
1046
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1096
1047
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
@@ -1107,11 +1058,11 @@ var PerpetualsClient = (function () {
1107
1058
  collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1108
1059
  }
1109
1060
  var entryPrice = OraclePrice_1.OraclePrice.from({ price: newPosition.entryPrice.price, exponent: new anchor_1.BN(newPosition.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1110
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1111
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1061
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1062
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1112
1063
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1113
1064
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1114
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1065
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1115
1066
  return {
1116
1067
  newSizeUsd: newPosition.sizeUsd,
1117
1068
  feeUsd: feeUsd,
@@ -1120,7 +1071,8 @@ var PerpetualsClient = (function () {
1120
1071
  newLev: newLev,
1121
1072
  liquidationPrice: finalLiquidationPrice,
1122
1073
  collateralAmountRecieved: collateralAmountReceived,
1123
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1074
+ collateralAmountRecievedUsd: collateralAmountRecievedUsd,
1075
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1124
1076
  newPnl: finalPnlUsd
1125
1077
  };
1126
1078
  }
@@ -1128,8 +1080,8 @@ var PerpetualsClient = (function () {
1128
1080
  throw "only same leverage is supported for now";
1129
1081
  }
1130
1082
  };
1131
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1132
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1083
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmountUsd, errorBandwidthPercentageUi) {
1084
+ if (closeAmountUsd === void 0) { closeAmountUsd = constants_1.BN_ZERO; }
1133
1085
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1134
1086
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1135
1087
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1138,61 +1090,63 @@ var PerpetualsClient = (function () {
1138
1090
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1139
1091
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1140
1092
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1141
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1093
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1142
1094
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1143
1095
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1144
1096
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1145
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1097
+ var currentCollateralUsd = positionAccount.collateralUsd.sub(closeAmountUsd);
1146
1098
  var availableInitMarginUsd = constants_1.BN_ZERO;
1147
1099
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1148
1100
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1149
1101
  }
1150
1102
  else {
1151
1103
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1152
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1104
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1153
1105
  }
1154
1106
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1155
1107
  if (maxRemovableCollateralUsd.isNeg()) {
1156
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1108
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1157
1109
  }
1158
1110
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1159
- var diff = constants_1.BN_ZERO;
1111
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1112
+ var diffUsd = constants_1.BN_ZERO;
1160
1113
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1161
1114
  var isDegenMode = positionAccount.isDegenMode();
1162
1115
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1163
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1164
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1116
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1117
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1165
1118
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1166
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1119
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1167
1120
  }
1168
1121
  else {
1169
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1122
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1123
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1170
1124
  }
1171
1125
  }
1172
1126
  else {
1173
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1127
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1128
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1174
1129
  }
1175
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1130
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1176
1131
  };
1177
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1132
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1178
1133
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1179
1134
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1180
- var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1181
1135
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1182
1136
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1183
1137
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1184
1138
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1185
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1186
- var closeAmount, feesAmount;
1139
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1140
+ var closeAmountUsd, feesAmountUsd;
1187
1141
  if (assetsUsd.gt(liabilityUsd)) {
1188
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1189
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1142
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1143
+ feesAmountUsd = totalFeesUsd;
1190
1144
  }
1191
1145
  else {
1192
- closeAmount = constants_1.BN_ZERO;
1193
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1146
+ closeAmountUsd = constants_1.BN_ZERO;
1147
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1194
1148
  }
1195
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1149
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1196
1150
  };
1197
1151
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1198
1152
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1205,34 +1159,37 @@ var PerpetualsClient = (function () {
1205
1159
  var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub((positionAccount.isDegenMode() ? new anchor_1.BN(targetCustodyAccount.pricing.minDegenCollateralUsd) : new anchor_1.BN(targetCustodyAccount.pricing.minCollateralUsd)).mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1206
1160
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1207
1161
  console.log("THIS cannot happen but still");
1208
- return constants_1.BN_ZERO;
1162
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1209
1163
  }
1210
1164
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1211
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1165
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1212
1166
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1213
1167
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1214
1168
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1215
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1169
+ var currentCollateralUsd = positionAccount.collateralUsd;
1216
1170
  var availableInitMarginUsd = constants_1.BN_ZERO;
1217
1171
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1218
1172
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1219
1173
  }
1220
1174
  else {
1221
1175
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1222
- return constants_1.BN_ZERO;
1176
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1223
1177
  }
1224
1178
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1225
1179
  if (maxRemovableCollateralUsd.isNeg()) {
1226
- return constants_1.BN_ZERO;
1180
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1227
1181
  }
1228
1182
  var maxWithdrawableAmount;
1183
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1229
1184
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1230
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1185
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1186
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1231
1187
  }
1232
1188
  else {
1233
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1189
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1190
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1234
1191
  }
1235
- return maxWithdrawableAmount;
1192
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1236
1193
  };
1237
1194
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1238
1195
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1275,7 +1232,7 @@ var PerpetualsClient = (function () {
1275
1232
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1276
1233
  return lockFeeUsd;
1277
1234
  };
1278
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1235
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1279
1236
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1280
1237
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1281
1238
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1283,188 +1240,141 @@ var PerpetualsClient = (function () {
1283
1240
  else {
1284
1241
  maxPayOffBpsNew = maxPayOffBps;
1285
1242
  }
1286
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1243
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1287
1244
  return lockedUsd;
1288
1245
  };
1289
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1246
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1290
1247
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1291
1248
  price: constants_1.BN_ZERO,
1292
1249
  exponent: constants_1.BN_ZERO,
1293
1250
  confidence: constants_1.BN_ZERO,
1294
1251
  timestamp: constants_1.BN_ZERO
1295
1252
  });
1296
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1297
- return zeroOraclePrice;
1298
- }
1299
1253
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1300
1254
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1301
1255
  }
1302
1256
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1303
1257
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1304
1258
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1305
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1306
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1307
1259
  var liquidationPrice;
1308
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1309
- var newCollateralAmount = void 0;
1310
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1311
- newCollateralAmount = collateralAmount;
1260
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1261
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1262
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1263
+ .div(positionAccount.sizeAmount),
1264
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1265
+ confidence: constants_1.BN_ZERO,
1266
+ timestamp: constants_1.BN_ZERO
1267
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1268
+ if ((0, types_1.isVariant)(side, 'long')) {
1269
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1270
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1271
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1272
+ confidence: constants_1.BN_ZERO,
1273
+ timestamp: constants_1.BN_ZERO
1274
+ });
1312
1275
  }
1313
1276
  else {
1314
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1315
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1316
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1277
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1278
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1279
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1280
+ confidence: constants_1.BN_ZERO,
1281
+ timestamp: constants_1.BN_ZERO
1282
+ });
1317
1283
  }
1318
- var lp = OraclePrice_1.OraclePrice.from({
1319
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1320
- .div(sizeAmount.add(newCollateralAmount)),
1284
+ }
1285
+ else {
1286
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1287
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1288
+ .div(positionAccount.sizeAmount),
1321
1289
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1322
1290
  confidence: constants_1.BN_ZERO,
1323
1291
  timestamp: constants_1.BN_ZERO
1324
- });
1325
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1326
- }
1327
- else {
1328
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1329
- if (assetsUsd.gte(liablitiesUsd)) {
1330
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1331
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1332
- .div(positionAccount.sizeAmount),
1333
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1292
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1293
+ if ((0, types_1.isVariant)(side, 'long')) {
1294
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1295
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1296
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1334
1297
  confidence: constants_1.BN_ZERO,
1335
1298
  timestamp: constants_1.BN_ZERO
1336
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1337
- if ((0, types_1.isVariant)(side, 'long')) {
1338
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1339
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1340
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1341
- confidence: constants_1.BN_ZERO,
1342
- timestamp: constants_1.BN_ZERO
1343
- });
1344
- }
1345
- else {
1346
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1347
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1348
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1349
- confidence: constants_1.BN_ZERO,
1350
- timestamp: constants_1.BN_ZERO
1351
- });
1352
- }
1299
+ });
1353
1300
  }
1354
1301
  else {
1355
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1356
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1357
- .div(positionAccount.sizeAmount),
1358
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1302
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1303
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1304
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1359
1305
  confidence: constants_1.BN_ZERO,
1360
1306
  timestamp: constants_1.BN_ZERO
1361
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1362
- if ((0, types_1.isVariant)(side, 'long')) {
1363
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1364
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1365
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1366
- confidence: constants_1.BN_ZERO,
1367
- timestamp: constants_1.BN_ZERO
1368
- });
1369
- }
1370
- else {
1371
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1373
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1374
- confidence: constants_1.BN_ZERO,
1375
- timestamp: constants_1.BN_ZERO
1376
- });
1377
- }
1307
+ });
1378
1308
  }
1379
1309
  }
1380
1310
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1381
1311
  };
1382
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1312
+ this.getLiquidationPriceSync = function (collateralUsd, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetPrice, targetCustodyAccount, positionAccount) {
1313
+ var newPositionAccount = positionAccount.clone();
1314
+ newPositionAccount.sizeAmount = sizeAmount;
1315
+ newPositionAccount.sizeUsd = targetPrice.getAssetAmountUsd(sizeAmount, targetCustodyAccount.decimals);
1316
+ newPositionAccount.collateralUsd = collateralUsd;
1317
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1318
+ };
1319
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1383
1320
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1384
1321
  price: constants_1.BN_ZERO,
1385
1322
  exponent: constants_1.BN_ZERO,
1386
1323
  confidence: constants_1.BN_ZERO,
1387
1324
  timestamp: constants_1.BN_ZERO
1388
1325
  });
1389
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1390
- return zeroOraclePrice;
1391
- }
1392
1326
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1393
1327
  var unsettledLossUsd = exitFeeUsd;
1394
1328
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1395
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1396
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1397
1329
  var liquidationPrice;
1398
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1399
- var newCollateralAmount = void 0;
1400
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1401
- newCollateralAmount = collateralAmount;
1330
+ if (collateralUsd.gte(liablitiesUsd)) {
1331
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1332
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1333
+ .div(sizeAmount),
1334
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1335
+ confidence: constants_1.BN_ZERO,
1336
+ timestamp: constants_1.BN_ZERO
1337
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1338
+ if ((0, types_1.isVariant)(side, 'long')) {
1339
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1340
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1341
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1342
+ confidence: constants_1.BN_ZERO,
1343
+ timestamp: constants_1.BN_ZERO
1344
+ });
1402
1345
  }
1403
1346
  else {
1404
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1405
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1406
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1347
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1348
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1349
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1350
+ confidence: constants_1.BN_ZERO,
1351
+ timestamp: constants_1.BN_ZERO
1352
+ });
1407
1353
  }
1408
- var lp = OraclePrice_1.OraclePrice.from({
1409
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1410
- .div(sizeAmount.add(newCollateralAmount)),
1354
+ }
1355
+ else {
1356
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1357
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1358
+ .div(sizeAmount),
1411
1359
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1412
1360
  confidence: constants_1.BN_ZERO,
1413
1361
  timestamp: constants_1.BN_ZERO
1414
- });
1415
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1416
- }
1417
- else {
1418
- var assetsUsd = collateralUsd;
1419
- if (assetsUsd.gte(liablitiesUsd)) {
1420
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1421
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1422
- .div(sizeAmount),
1423
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1362
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1363
+ if ((0, types_1.isVariant)(side, 'long')) {
1364
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1365
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1366
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1424
1367
  confidence: constants_1.BN_ZERO,
1425
1368
  timestamp: constants_1.BN_ZERO
1426
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1427
- if ((0, types_1.isVariant)(side, 'long')) {
1428
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1429
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1430
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1431
- confidence: constants_1.BN_ZERO,
1432
- timestamp: constants_1.BN_ZERO
1433
- });
1434
- }
1435
- else {
1436
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1437
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1438
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1439
- confidence: constants_1.BN_ZERO,
1440
- timestamp: constants_1.BN_ZERO
1441
- });
1442
- }
1369
+ });
1443
1370
  }
1444
1371
  else {
1445
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1446
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1447
- .div(sizeAmount),
1448
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1372
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1373
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1374
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1449
1375
  confidence: constants_1.BN_ZERO,
1450
1376
  timestamp: constants_1.BN_ZERO
1451
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1452
- if ((0, types_1.isVariant)(side, 'long')) {
1453
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1454
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1455
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1456
- confidence: constants_1.BN_ZERO,
1457
- timestamp: constants_1.BN_ZERO
1458
- });
1459
- }
1460
- else {
1461
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1462
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1463
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1464
- confidence: constants_1.BN_ZERO,
1465
- timestamp: constants_1.BN_ZERO
1466
- });
1467
- }
1377
+ });
1468
1378
  }
1469
1379
  }
1470
1380
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
@@ -1540,8 +1450,8 @@ var PerpetualsClient = (function () {
1540
1450
  positionAccount.market = marketAccountPk;
1541
1451
  positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1542
1452
  positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1543
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1544
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1453
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1454
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1545
1455
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1546
1456
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1547
1457
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1613,6 +1523,9 @@ var PerpetualsClient = (function () {
1613
1523
  });
1614
1524
  };
1615
1525
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1526
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1527
+ };
1528
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1616
1529
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1617
1530
  return {
1618
1531
  profitUsd: constants_1.BN_ZERO,
@@ -1671,7 +1584,7 @@ var PerpetualsClient = (function () {
1671
1584
  }
1672
1585
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1673
1586
  return {
1674
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1587
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1675
1588
  lossUsd: constants_1.BN_ZERO,
1676
1589
  };
1677
1590
  }
@@ -1762,6 +1675,9 @@ var PerpetualsClient = (function () {
1762
1675
  }
1763
1676
  };
1764
1677
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1678
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1679
+ };
1680
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1765
1681
  var poolAmountUsd = constants_1.BN_ZERO;
1766
1682
  for (var index = 0; index < custodies.length; index++) {
1767
1683
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1774,6 +1690,7 @@ var PerpetualsClient = (function () {
1774
1690
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1775
1691
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1776
1692
  }
1693
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1777
1694
  if (aumCalcMode === "includePnl") {
1778
1695
  var poolEquityUsd = poolAmountUsd;
1779
1696
  for (var index = 0; index < markets.length; index++) {
@@ -1783,11 +1700,12 @@ var PerpetualsClient = (function () {
1783
1700
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1784
1701
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1785
1702
  var position = markets[index].getCollectivePosition();
1703
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1786
1704
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1787
1705
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1788
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1789
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1790
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1706
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1707
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1708
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1791
1709
  }
1792
1710
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1793
1711
  }
@@ -1795,14 +1713,6 @@ var PerpetualsClient = (function () {
1795
1713
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1796
1714
  }
1797
1715
  };
1798
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1799
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1800
- return { discountBn: constants_1.BN_ZERO };
1801
- }
1802
- else {
1803
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1804
- }
1805
- };
1806
1716
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1807
1717
  if (tokenStakeAccount.level === 0) {
1808
1718
  return { discountBn: constants_1.BN_ZERO };
@@ -1887,7 +1797,7 @@ var PerpetualsClient = (function () {
1887
1797
  });
1888
1798
  };
1889
1799
  this.getStakedLpTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
1890
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, result, index, res;
1800
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, setCULimitIx, result, index, res;
1891
1801
  var _d;
1892
1802
  return __generator(this, function (_e) {
1893
1803
  switch (_e.label) {
@@ -1935,6 +1845,8 @@ var PerpetualsClient = (function () {
1935
1845
  return [4, backUpOracleInstructionPromise];
1936
1846
  case 2:
1937
1847
  backUpOracleInstruction = _e.sent();
1848
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1849
+ transaction.instructions.unshift(setCULimitIx);
1938
1850
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
1939
1851
  return [4, this.viewHelper.simulateTransaction(transaction)];
1940
1852
  case 3:
@@ -2001,7 +1913,7 @@ var PerpetualsClient = (function () {
2001
1913
  args_1[_i - 4] = arguments[_i];
2002
1914
  }
2003
1915
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2004
- var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
1916
+ var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2005
1917
  var _e;
2006
1918
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2007
1919
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2052,6 +1964,8 @@ var PerpetualsClient = (function () {
2052
1964
  .transaction()];
2053
1965
  case 1:
2054
1966
  transaction = _f.sent();
1967
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1968
+ transaction.instructions.unshift(setCULimitIx);
2055
1969
  if (!enableBackupOracle) return [3, 3];
2056
1970
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2057
1971
  case 2:
@@ -2061,6 +1975,14 @@ var PerpetualsClient = (function () {
2061
1975
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2062
1976
  case 4:
2063
1977
  result = _f.sent();
1978
+ if (result.value.err) {
1979
+ console.error('error Simulation failed:::', result);
1980
+ return [2, {
1981
+ amount: undefined,
1982
+ fee: undefined,
1983
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
1984
+ }];
1985
+ }
2064
1986
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2065
1987
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2066
1988
  return [2, {
@@ -2077,7 +1999,7 @@ var PerpetualsClient = (function () {
2077
1999
  args_1[_i - 4] = arguments[_i];
2078
2000
  }
2079
2001
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2080
- var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
2002
+ var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2081
2003
  var _e;
2082
2004
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2083
2005
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2128,6 +2050,8 @@ var PerpetualsClient = (function () {
2128
2050
  .transaction()];
2129
2051
  case 1:
2130
2052
  transaction = _f.sent();
2053
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2054
+ transaction.instructions.unshift(setCULimitIx);
2131
2055
  if (!enableBackupOracle) return [3, 3];
2132
2056
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2133
2057
  case 2:
@@ -2139,9 +2063,11 @@ var PerpetualsClient = (function () {
2139
2063
  result = _f.sent();
2140
2064
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2141
2065
  if (result.value.err) {
2066
+ console.error('error Simulation failed:', result);
2142
2067
  return [2, {
2143
- amount: new anchor_1.BN(0),
2144
- fee: new anchor_1.BN(0),
2068
+ amount: undefined,
2069
+ fee: undefined,
2070
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2145
2071
  }];
2146
2072
  }
2147
2073
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2154,7 +2080,7 @@ var PerpetualsClient = (function () {
2154
2080
  });
2155
2081
  };
2156
2082
  this.getCompoundingLPTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
2157
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, result, index, res;
2083
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, setCULimitIx, result, index, res;
2158
2084
  var _d;
2159
2085
  return __generator(this, function (_e) {
2160
2086
  switch (_e.label) {
@@ -2202,6 +2128,8 @@ var PerpetualsClient = (function () {
2202
2128
  .transaction()];
2203
2129
  case 2:
2204
2130
  transaction = _e.sent();
2131
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2132
+ transaction.instructions.unshift(setCULimitIx);
2205
2133
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
2206
2134
  return [4, this.viewHelper.simulateTransaction(transaction)];
2207
2135
  case 3:
@@ -2218,7 +2146,7 @@ var PerpetualsClient = (function () {
2218
2146
  args_1[_i - 4] = arguments[_i];
2219
2147
  }
2220
2148
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2221
- var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2149
+ var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2222
2150
  var _e;
2223
2151
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2224
2152
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2273,6 +2201,8 @@ var PerpetualsClient = (function () {
2273
2201
  .transaction()];
2274
2202
  case 1:
2275
2203
  transaction = _f.sent();
2204
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2205
+ transaction.instructions.unshift(setCULimitIx);
2276
2206
  if (!enableBackupOracle) return [3, 3];
2277
2207
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2278
2208
  case 2:
@@ -2298,7 +2228,7 @@ var PerpetualsClient = (function () {
2298
2228
  args_1[_i - 4] = arguments[_i];
2299
2229
  }
2300
2230
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2301
- var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2231
+ var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2302
2232
  var _e;
2303
2233
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2304
2234
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2353,6 +2283,8 @@ var PerpetualsClient = (function () {
2353
2283
  .transaction()];
2354
2284
  case 1:
2355
2285
  transaction = _f.sent();
2286
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2287
+ transaction.instructions.unshift(setCULimitIx);
2356
2288
  if (!enableBackupOracle) return [3, 3];
2357
2289
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2358
2290
  case 2:
@@ -2547,11 +2479,10 @@ var PerpetualsClient = (function () {
2547
2479
  for (var _i = 8; _i < arguments.length; _i++) {
2548
2480
  args_1[_i - 8] = arguments[_i];
2549
2481
  }
2550
- 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) {
2482
+ 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) {
2551
2483
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2552
2484
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2553
2485
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2554
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2555
2486
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2556
2487
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2557
2488
  return __generator(this, function (_c) {
@@ -2644,7 +2575,7 @@ var PerpetualsClient = (function () {
2644
2575
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2645
2576
  fundingMint: collateralCustodyConfig.mintKey
2646
2577
  })
2647
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2578
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2648
2579
  .instruction()];
2649
2580
  case 7:
2650
2581
  instruction = _c.sent();
@@ -2662,11 +2593,10 @@ var PerpetualsClient = (function () {
2662
2593
  for (var _i = 6; _i < arguments.length; _i++) {
2663
2594
  args_1[_i - 6] = arguments[_i];
2664
2595
  }
2665
- 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) {
2596
+ 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) {
2666
2597
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2667
2598
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2668
2599
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2669
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2670
2600
  if (createUserATA === void 0) { createUserATA = true; }
2671
2601
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2672
2602
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2745,7 +2675,7 @@ var PerpetualsClient = (function () {
2745
2675
  collateralMint: collateralCustodyConfig.mintKey,
2746
2676
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2747
2677
  })
2748
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2678
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2749
2679
  .instruction()];
2750
2680
  case 6:
2751
2681
  instruction = _b.sent();
@@ -2767,16 +2697,15 @@ var PerpetualsClient = (function () {
2767
2697
  });
2768
2698
  });
2769
2699
  };
2770
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2700
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2771
2701
  var args_1 = [];
2772
- for (var _i = 10; _i < arguments.length; _i++) {
2773
- args_1[_i - 10] = arguments[_i];
2702
+ for (var _i = 9; _i < arguments.length; _i++) {
2703
+ args_1[_i - 9] = arguments[_i];
2774
2704
  }
2775
- 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) {
2776
- 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;
2705
+ 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) {
2706
+ 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;
2777
2707
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2778
2708
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2779
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2780
2709
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2781
2710
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2782
2711
  return __generator(this, function (_c) {
@@ -2870,18 +2799,10 @@ var PerpetualsClient = (function () {
2870
2799
  }
2871
2800
  _c.label = 10;
2872
2801
  case 10:
2873
- rebateMintAccount = {
2874
- pubkey: collateralCustodyConfig.mintKey,
2875
- isSigner: false,
2876
- isWritable: false
2877
- };
2878
- _c.label = 11;
2879
- case 11:
2880
- _c.trys.push([11, 13, , 14]);
2802
+ _c.trys.push([10, 12, , 13]);
2881
2803
  return [4, this.program.methods
2882
2804
  .swapAndOpen({
2883
2805
  amountIn: amountIn,
2884
- minCollateralAmountOut: minCollateralAmountOut,
2885
2806
  priceWithSlippage: priceWithSlippage,
2886
2807
  sizeAmount: sizeAmount,
2887
2808
  privilege: privilege
@@ -2912,17 +2833,17 @@ var PerpetualsClient = (function () {
2912
2833
  collateralMint: collateralCustodyConfig.mintKey,
2913
2834
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2914
2835
  })
2915
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2836
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2916
2837
  .instruction()];
2917
- case 12:
2838
+ case 11:
2918
2839
  inx = _c.sent();
2919
2840
  instructions.push(inx);
2920
- return [3, 14];
2921
- case 13:
2841
+ return [3, 13];
2842
+ case 12:
2922
2843
  err_3 = _c.sent();
2923
2844
  console.error("perpClient SwapAndOpen error:: ", err_3);
2924
2845
  throw err_3;
2925
- case 14: return [2, {
2846
+ case 13: return [2, {
2926
2847
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2927
2848
  additionalSigners: additionalSigners
2928
2849
  }];
@@ -2930,16 +2851,15 @@ var PerpetualsClient = (function () {
2930
2851
  });
2931
2852
  });
2932
2853
  };
2933
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2854
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2934
2855
  var args_1 = [];
2935
- for (var _i = 8; _i < arguments.length; _i++) {
2936
- args_1[_i - 8] = arguments[_i];
2856
+ for (var _i = 7; _i < arguments.length; _i++) {
2857
+ args_1[_i - 7] = arguments[_i];
2937
2858
  }
2938
- 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) {
2939
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2859
+ 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) {
2860
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2940
2861
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2941
2862
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2942
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2943
2863
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2944
2864
  return __generator(this, function (_a) {
2945
2865
  switch (_a.label) {
@@ -3005,18 +2925,12 @@ var PerpetualsClient = (function () {
3005
2925
  if (!(_a.sent())) {
3006
2926
  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));
3007
2927
  }
3008
- rebateMintAccount = {
3009
- pubkey: collateralCustodyConfig.mintKey,
3010
- isSigner: false,
3011
- isWritable: false
3012
- };
3013
2928
  _a.label = 5;
3014
2929
  case 5:
3015
2930
  _a.trys.push([5, 7, , 8]);
3016
2931
  return [4, this.program.methods
3017
2932
  .closeAndSwap({
3018
2933
  priceWithSlippage: priceWithSlippage,
3019
- minSwapAmountOut: minSwapAmountOut,
3020
2934
  privilege: privilege
3021
2935
  })
3022
2936
  .accounts({
@@ -3045,7 +2959,7 @@ var PerpetualsClient = (function () {
3045
2959
  collateralMint: collateralCustodyConfig.mintKey,
3046
2960
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
3047
2961
  })
3048
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2962
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3049
2963
  .instruction()];
3050
2964
  case 6:
3051
2965
  inx = _a.sent();
@@ -3166,12 +3080,12 @@ var PerpetualsClient = (function () {
3166
3080
  });
3167
3081
  });
3168
3082
  };
3169
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3083
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3170
3084
  var args_1 = [];
3171
- for (var _i = 8; _i < arguments.length; _i++) {
3172
- args_1[_i - 8] = arguments[_i];
3085
+ for (var _i = 7; _i < arguments.length; _i++) {
3086
+ args_1[_i - 7] = arguments[_i];
3173
3087
  }
3174
- 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) {
3088
+ 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) {
3175
3089
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3176
3090
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3177
3091
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3250,7 +3164,6 @@ var PerpetualsClient = (function () {
3250
3164
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3251
3165
  return [4, this.program.methods.swapAndAddCollateral({
3252
3166
  amountIn: amountIn,
3253
- minCollateralAmountOut: minCollateralAmountOut,
3254
3167
  }).accounts({
3255
3168
  owner: publicKey,
3256
3169
  feePayer: publicKey,
@@ -3286,12 +3199,12 @@ var PerpetualsClient = (function () {
3286
3199
  });
3287
3200
  });
3288
3201
  };
3289
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3202
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3290
3203
  var args_1 = [];
3291
3204
  for (var _i = 6; _i < arguments.length; _i++) {
3292
3205
  args_1[_i - 6] = arguments[_i];
3293
3206
  }
3294
- 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) {
3207
+ 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) {
3295
3208
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3296
3209
  if (createUserATA === void 0) { createUserATA = true; }
3297
3210
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3355,7 +3268,7 @@ var PerpetualsClient = (function () {
3355
3268
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3356
3269
  return [4, this.program.methods
3357
3270
  .removeCollateral({
3358
- collateralDelta: collateralWithFee,
3271
+ collateralDeltaUsd: collateralDeltaUsd,
3359
3272
  })
3360
3273
  .accounts({
3361
3274
  owner: publicKey,
@@ -3397,12 +3310,12 @@ var PerpetualsClient = (function () {
3397
3310
  });
3398
3311
  });
3399
3312
  };
3400
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3313
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3401
3314
  var args_1 = [];
3402
- for (var _i = 7; _i < arguments.length; _i++) {
3403
- args_1[_i - 7] = arguments[_i];
3315
+ for (var _i = 6; _i < arguments.length; _i++) {
3316
+ args_1[_i - 6] = arguments[_i];
3404
3317
  }
3405
- 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) {
3318
+ 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) {
3406
3319
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3407
3320
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3408
3321
  return __generator(this, function (_a) {
@@ -3459,8 +3372,7 @@ var PerpetualsClient = (function () {
3459
3372
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3460
3373
  return [4, this.program.methods
3461
3374
  .removeCollateralAndSwap({
3462
- collateralDelta: collateralDelta,
3463
- minSwapAmountOut: minSwapAmountOut,
3375
+ collateralDeltaUsd: collateralDeltaUsd,
3464
3376
  })
3465
3377
  .accounts({
3466
3378
  owner: publicKey,
@@ -3505,11 +3417,10 @@ var PerpetualsClient = (function () {
3505
3417
  for (var _i = 8; _i < arguments.length; _i++) {
3506
3418
  args_1[_i - 8] = arguments[_i];
3507
3419
  }
3508
- 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) {
3420
+ 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) {
3509
3421
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3510
3422
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3511
3423
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3512
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3513
3424
  return __generator(this, function (_a) {
3514
3425
  switch (_a.label) {
3515
3426
  case 0:
@@ -3552,7 +3463,7 @@ var PerpetualsClient = (function () {
3552
3463
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3553
3464
  collateralMint: collateralCustodyConfig.mintKey
3554
3465
  })
3555
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3466
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3556
3467
  .instruction()];
3557
3468
  case 1:
3558
3469
  instruction = _a.sent();
@@ -3570,11 +3481,10 @@ var PerpetualsClient = (function () {
3570
3481
  for (var _i = 8; _i < arguments.length; _i++) {
3571
3482
  args_1[_i - 8] = arguments[_i];
3572
3483
  }
3573
- 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) {
3484
+ 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) {
3574
3485
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3575
3486
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3576
3487
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3577
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3578
3488
  return __generator(this, function (_a) {
3579
3489
  switch (_a.label) {
3580
3490
  case 0:
@@ -3617,7 +3527,7 @@ var PerpetualsClient = (function () {
3617
3527
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3618
3528
  collateralMint: collateralCustodyConfig.mintKey
3619
3529
  })
3620
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3530
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3621
3531
  .instruction()];
3622
3532
  case 1:
3623
3533
  instruction = _a.sent();
@@ -4084,119 +3994,8 @@ var PerpetualsClient = (function () {
4084
3994
  }
4085
3995
  });
4086
3996
  }); };
4087
- this.updateNftAccount = function (nftMint, updateReferer, updateBooster, flpStakeAccounts) { return __awaiter(_this, void 0, void 0, function () {
4088
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, flpStakeAccountMetas, _i, flpStakeAccounts_1, flpStakeAccountPk, updateNftTradingAccountInstruction, err_8;
4089
- return __generator(this, function (_a) {
4090
- switch (_a.label) {
4091
- case 0:
4092
- publicKey = this.provider.wallet.publicKey;
4093
- preInstructions = [];
4094
- instructions = [];
4095
- postInstructions = [];
4096
- additionalSigners = [];
4097
- _a.label = 1;
4098
- case 1:
4099
- _a.trys.push([1, 4, , 5]);
4100
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4101
- Buffer.from("trading"),
4102
- nftMint.toBuffer(),
4103
- ], this.programId)[0];
4104
- nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
4105
- Buffer.from("referral"),
4106
- publicKey.toBuffer(),
4107
- ], this.programId)[0];
4108
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey, true)];
4109
- case 2:
4110
- nftTokenAccount = _a.sent();
4111
- flpStakeAccountMetas = [];
4112
- for (_i = 0, flpStakeAccounts_1 = flpStakeAccounts; _i < flpStakeAccounts_1.length; _i++) {
4113
- flpStakeAccountPk = flpStakeAccounts_1[_i];
4114
- flpStakeAccountMetas.push({
4115
- pubkey: flpStakeAccountPk,
4116
- isSigner: false,
4117
- isWritable: true,
4118
- });
4119
- }
4120
- return [4, this.program.methods
4121
- .updateTradingAccount({
4122
- updateReferer: updateReferer,
4123
- updateBooster: updateBooster
4124
- })
4125
- .accounts({
4126
- owner: publicKey,
4127
- feePayer: publicKey,
4128
- nftTokenAccount: nftTokenAccount,
4129
- referralAccount: nftReferralAccount,
4130
- tradingAccount: nftTradingAccount
4131
- })
4132
- .instruction()];
4133
- case 3:
4134
- updateNftTradingAccountInstruction = _a.sent();
4135
- instructions.push(updateNftTradingAccountInstruction);
4136
- return [3, 5];
4137
- case 4:
4138
- err_8 = _a.sent();
4139
- console.log("perpClient updateNftAccount error:: ", err_8);
4140
- throw err_8;
4141
- case 5: return [2, {
4142
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4143
- additionalSigners: additionalSigners
4144
- }];
4145
- }
4146
- });
4147
- }); };
4148
- this.levelUp = function (poolConfig, nftMint, authorizationRulesAccount) { return __awaiter(_this, void 0, void 0, function () {
4149
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_9;
4150
- return __generator(this, function (_a) {
4151
- switch (_a.label) {
4152
- case 0:
4153
- publicKey = this.provider.wallet.publicKey;
4154
- preInstructions = [];
4155
- instructions = [];
4156
- postInstructions = [];
4157
- additionalSigners = [];
4158
- _a.label = 1;
4159
- case 1:
4160
- _a.trys.push([1, 3, , 4]);
4161
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4162
- Buffer.from("trading"),
4163
- nftMint.toBuffer(),
4164
- ], this.programId)[0];
4165
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
4166
- return [4, this.program.methods
4167
- .levelUp({})
4168
- .accounts({
4169
- owner: publicKey,
4170
- perpetuals: this.perpetuals.publicKey,
4171
- pool: poolConfig.poolAddress,
4172
- metadataAccount: metadataAccount,
4173
- nftMint: nftMint,
4174
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
4175
- tradingAccount: nftTradingAccount,
4176
- transferAuthority: this.authority.publicKey,
4177
- authorizationRulesAccount: authorizationRulesAccount,
4178
- authorizationRulesProgram: new web3_js_1.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg'),
4179
- systemProgram: web3_js_1.SystemProgram.programId,
4180
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
4181
- })
4182
- .instruction()];
4183
- case 2:
4184
- levelUpInstruction = _a.sent();
4185
- instructions.push(levelUpInstruction);
4186
- return [3, 4];
4187
- case 3:
4188
- err_9 = _a.sent();
4189
- console.log("perpClient levelUp error:: ", err_9);
4190
- throw err_9;
4191
- case 4: return [2, {
4192
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4193
- additionalSigners: additionalSigners
4194
- }];
4195
- }
4196
- });
4197
- }); };
4198
3997
  this.depositStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4199
- var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
3998
+ var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_8;
4200
3999
  return __generator(this, function (_a) {
4201
4000
  switch (_a.label) {
4202
4001
  case 0:
@@ -4238,9 +4037,9 @@ var PerpetualsClient = (function () {
4238
4037
  instructions.push(depositStakeInstruction);
4239
4038
  return [3, 5];
4240
4039
  case 4:
4241
- err_10 = _a.sent();
4242
- console.log("perpClient depositStaking error:: ", err_10);
4243
- throw err_10;
4040
+ err_8 = _a.sent();
4041
+ console.log("perpClient depositStaking error:: ", err_8);
4042
+ throw err_8;
4244
4043
  case 5: return [2, {
4245
4044
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4246
4045
  additionalSigners: additionalSigners
@@ -4249,7 +4048,7 @@ var PerpetualsClient = (function () {
4249
4048
  });
4250
4049
  }); };
4251
4050
  this.refreshStakeWithAllFlpStakeAccounts = function (rewardSymbol, poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4252
- var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_11;
4051
+ var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_9;
4253
4052
  return __generator(this, function (_c) {
4254
4053
  switch (_c.label) {
4255
4054
  case 0:
@@ -4296,9 +4095,9 @@ var PerpetualsClient = (function () {
4296
4095
  refreshStakeInstruction = _c.sent();
4297
4096
  return [2, refreshStakeInstruction];
4298
4097
  case 2:
4299
- err_11 = _c.sent();
4300
- console.log("perpClient refreshStaking error:: ", err_11);
4301
- throw err_11;
4098
+ err_9 = _c.sent();
4099
+ console.log("perpClient refreshStaking error:: ", err_9);
4100
+ throw err_9;
4302
4101
  case 3: return [2];
4303
4102
  }
4304
4103
  });
@@ -4309,7 +4108,7 @@ var PerpetualsClient = (function () {
4309
4108
  args_1[_i - 3] = arguments[_i];
4310
4109
  }
4311
4110
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, flpStakeAccountPk_1], args_1, true), void 0, function (rewardSymbol, poolConfig, flpStakeAccountPk, userPublicKey) {
4312
- var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_12;
4111
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_10;
4313
4112
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4314
4113
  return __generator(this, function (_c) {
4315
4114
  switch (_c.label) {
@@ -4357,9 +4156,9 @@ var PerpetualsClient = (function () {
4357
4156
  refreshStakeInstruction = _c.sent();
4358
4157
  return [2, refreshStakeInstruction];
4359
4158
  case 2:
4360
- err_12 = _c.sent();
4361
- console.log("perpClient refreshStaking error:: ", err_12);
4362
- throw err_12;
4159
+ err_10 = _c.sent();
4160
+ console.log("perpClient refreshStaking error:: ", err_10);
4161
+ throw err_10;
4363
4162
  case 3: return [2];
4364
4163
  }
4365
4164
  });
@@ -4371,7 +4170,7 @@ var PerpetualsClient = (function () {
4371
4170
  args_1[_i - 3] = arguments[_i];
4372
4171
  }
4373
4172
  return __awaiter(_this, __spreadArray([rewardSymbol_1, unstakeAmount_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, unstakeAmount, poolConfig, userPublicKey) {
4374
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_13;
4173
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_11;
4375
4174
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4376
4175
  return __generator(this, function (_b) {
4377
4176
  switch (_b.label) {
@@ -4423,9 +4222,9 @@ var PerpetualsClient = (function () {
4423
4222
  instructions.push(unstakeInstantInstruction);
4424
4223
  return [3, 6];
4425
4224
  case 5:
4426
- err_13 = _b.sent();
4427
- console.log("perpClient unstakeInstant error:: ", err_13);
4428
- throw err_13;
4225
+ err_11 = _b.sent();
4226
+ console.log("perpClient unstakeInstant error:: ", err_11);
4227
+ throw err_11;
4429
4228
  case 6: return [2, {
4430
4229
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4431
4230
  additionalSigners: additionalSigners
@@ -4435,7 +4234,7 @@ var PerpetualsClient = (function () {
4435
4234
  });
4436
4235
  };
4437
4236
  this.setFeeShareBps = function (poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4438
- var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_14;
4237
+ var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_12;
4439
4238
  return __generator(this, function (_c) {
4440
4239
  switch (_c.label) {
4441
4240
  case 0:
@@ -4479,15 +4278,15 @@ var PerpetualsClient = (function () {
4479
4278
  refreshStakeInstruction = _c.sent();
4480
4279
  return [2, refreshStakeInstruction];
4481
4280
  case 2:
4482
- err_14 = _c.sent();
4483
- console.log("perpClient refreshStaking error:: ", err_14);
4484
- throw err_14;
4281
+ err_12 = _c.sent();
4282
+ console.log("perpClient refreshStaking error:: ", err_12);
4283
+ throw err_12;
4485
4284
  case 3: return [2];
4486
4285
  }
4487
4286
  });
4488
4287
  }); };
4489
4288
  this.unstakeRequest = function (unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4490
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_15;
4289
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_13;
4491
4290
  return __generator(this, function (_a) {
4492
4291
  switch (_a.label) {
4493
4292
  case 0:
@@ -4521,9 +4320,9 @@ var PerpetualsClient = (function () {
4521
4320
  instructions.push(unstakeRequestInstruction);
4522
4321
  return [3, 4];
4523
4322
  case 3:
4524
- err_15 = _a.sent();
4525
- console.log("perpClient unstakeRequest error:: ", err_15);
4526
- throw err_15;
4323
+ err_13 = _a.sent();
4324
+ console.log("perpClient unstakeRequest error:: ", err_13);
4325
+ throw err_13;
4527
4326
  case 4: return [2, {
4528
4327
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4529
4328
  additionalSigners: additionalSigners
@@ -4537,7 +4336,7 @@ var PerpetualsClient = (function () {
4537
4336
  args_1[_i - 1] = arguments[_i];
4538
4337
  }
4539
4338
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, pendingActivation, deactivated, createUserLPTA, userPublicKey) {
4540
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_16;
4339
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_14;
4541
4340
  if (pendingActivation === void 0) { pendingActivation = true; }
4542
4341
  if (deactivated === void 0) { deactivated = true; }
4543
4342
  if (createUserLPTA === void 0) { createUserLPTA = true; }
@@ -4593,9 +4392,9 @@ var PerpetualsClient = (function () {
4593
4392
  instructions.push(withdrawStakeInstruction);
4594
4393
  return [3, 6];
4595
4394
  case 5:
4596
- err_16 = _b.sent();
4597
- console.log("perpClient withdrawStake error:: ", err_16);
4598
- throw err_16;
4395
+ err_14 = _b.sent();
4396
+ console.log("perpClient withdrawStake error:: ", err_14);
4397
+ throw err_14;
4599
4398
  case 6: return [2, {
4600
4399
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4601
4400
  additionalSigners: additionalSigners
@@ -4610,7 +4409,7 @@ var PerpetualsClient = (function () {
4610
4409
  args_1[_i - 3] = arguments[_i];
4611
4410
  }
4612
4411
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, tokenStakeAccount_1], args_1, true), void 0, function (rewardSymbol, poolConfig, tokenStakeAccount, createUserATA) {
4613
- var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_17;
4412
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_15;
4614
4413
  if (createUserATA === void 0) { createUserATA = true; }
4615
4414
  return __generator(this, function (_b) {
4616
4415
  switch (_b.label) {
@@ -4671,9 +4470,9 @@ var PerpetualsClient = (function () {
4671
4470
  instructions.push(withdrawStakeInstruction);
4672
4471
  return [3, 6];
4673
4472
  case 5:
4674
- err_17 = _b.sent();
4675
- console.log("perpClient withdrawStake error:: ", err_17);
4676
- throw err_17;
4473
+ err_15 = _b.sent();
4474
+ console.log("perpClient withdrawStake error:: ", err_15);
4475
+ throw err_15;
4677
4476
  case 6: return [2, {
4678
4477
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4679
4478
  additionalSigners: additionalSigners
@@ -4688,7 +4487,7 @@ var PerpetualsClient = (function () {
4688
4487
  args_1[_i - 5] = arguments[_i];
4689
4488
  }
4690
4489
  return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey) {
4691
- var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_18;
4490
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_16;
4692
4491
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4693
4492
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4694
4493
  if (userPublicKey === void 0) { userPublicKey = undefined; }
@@ -4816,8 +4615,8 @@ var PerpetualsClient = (function () {
4816
4615
  instructions.push(addCompoundingLiquidity);
4817
4616
  return [3, 10];
4818
4617
  case 9:
4819
- err_18 = _f.sent();
4820
- console.log("perpClient addCompoundingLiquidity error:: ", err_18);
4618
+ err_16 = _f.sent();
4619
+ console.log("perpClient addCompoundingLiquidity error:: ", err_16);
4821
4620
  return [3, 10];
4822
4621
  case 10: return [2, {
4823
4622
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4833,7 +4632,7 @@ var PerpetualsClient = (function () {
4833
4632
  args_1[_i - 5] = arguments[_i];
4834
4633
  }
4835
4634
  return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey) {
4836
- var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_19;
4635
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_17;
4837
4636
  if (createUserATA === void 0) { createUserATA = true; }
4838
4637
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4839
4638
  if (userPublicKey === void 0) { userPublicKey = undefined; }
@@ -4945,8 +4744,8 @@ var PerpetualsClient = (function () {
4945
4744
  instructions.push(removeCompoundingLiquidity);
4946
4745
  return [3, 8];
4947
4746
  case 7:
4948
- err_19 = _f.sent();
4949
- console.log("perpClient removeCompoundingLiquidity error:: ", err_19);
4747
+ err_17 = _f.sent();
4748
+ console.log("perpClient removeCompoundingLiquidity error:: ", err_17);
4950
4749
  return [3, 8];
4951
4750
  case 8: return [2, {
4952
4751
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4962,7 +4761,7 @@ var PerpetualsClient = (function () {
4962
4761
  args_1[_i - 3] = arguments[_i];
4963
4762
  }
4964
4763
  return __awaiter(_this, __spreadArray([amount_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amount, rewardTokenMint, poolConfig, createUserATA) {
4965
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_20;
4764
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_18;
4966
4765
  if (createUserATA === void 0) { createUserATA = true; }
4967
4766
  return __generator(this, function (_g) {
4968
4767
  switch (_g.label) {
@@ -5060,8 +4859,8 @@ var PerpetualsClient = (function () {
5060
4859
  instructions.push(migrateStake);
5061
4860
  return [3, 8];
5062
4861
  case 7:
5063
- err_20 = _g.sent();
5064
- console.log("perpClient migrateStake error:: ", err_20);
4862
+ err_18 = _g.sent();
4863
+ console.log("perpClient migrateStake error:: ", err_18);
5065
4864
  return [3, 8];
5066
4865
  case 8: return [2, {
5067
4866
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5072,7 +4871,7 @@ var PerpetualsClient = (function () {
5072
4871
  });
5073
4872
  };
5074
4873
  this.migrateFlp = function (amount, rewardTokenMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5075
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_21;
4874
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_19;
5076
4875
  return __generator(this, function (_d) {
5077
4876
  switch (_d.label) {
5078
4877
  case 0:
@@ -5144,8 +4943,8 @@ var PerpetualsClient = (function () {
5144
4943
  instructions.push(migrateFlp);
5145
4944
  return [3, 4];
5146
4945
  case 3:
5147
- err_21 = _d.sent();
5148
- console.log("perpClient migrateFlp error:: ", err_21);
4946
+ err_19 = _d.sent();
4947
+ console.log("perpClient migrateFlp error:: ", err_19);
5149
4948
  return [3, 4];
5150
4949
  case 4: return [2, {
5151
4950
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5160,7 +4959,7 @@ var PerpetualsClient = (function () {
5160
4959
  args_1[_i - 1] = arguments[_i];
5161
4960
  }
5162
4961
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, rewardTokenSymbol) {
5163
- var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_22;
4962
+ var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_20;
5164
4963
  if (rewardTokenSymbol === void 0) { rewardTokenSymbol = 'USDC'; }
5165
4964
  return __generator(this, function (_e) {
5166
4965
  switch (_e.label) {
@@ -5218,8 +5017,8 @@ var PerpetualsClient = (function () {
5218
5017
  instructions.push(compoundingFee);
5219
5018
  return [3, 4];
5220
5019
  case 3:
5221
- err_22 = _e.sent();
5222
- console.log("perpClient compoundingFee error:: ", err_22);
5020
+ err_20 = _e.sent();
5021
+ console.log("perpClient compoundingFee error:: ", err_20);
5223
5022
  return [3, 4];
5224
5023
  case 4: return [2, {
5225
5024
  instructions: __spreadArray([], instructions, true),
@@ -5229,158 +5028,20 @@ var PerpetualsClient = (function () {
5229
5028
  });
5230
5029
  });
5231
5030
  };
5232
- this.burnAndClaim = function (owner, nftMint, poolConfig, createAta) { return __awaiter(_this, void 0, void 0, function () {
5233
- var preInstructions, instructions, postInstructions, additionalSigners, userTokenAccount, _a, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndClaimInstruction, err_23;
5234
- return __generator(this, function (_b) {
5235
- switch (_b.label) {
5031
+ this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5032
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_21;
5033
+ return __generator(this, function (_a) {
5034
+ switch (_a.label) {
5236
5035
  case 0:
5237
5036
  preInstructions = [];
5238
5037
  instructions = [];
5239
5038
  postInstructions = [];
5240
5039
  additionalSigners = [];
5241
- _b.label = 1;
5040
+ _a.label = 1;
5242
5041
  case 1:
5243
- _b.trys.push([1, 7, , 8]);
5244
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, owner, true)];
5245
- case 2:
5246
- userTokenAccount = _b.sent();
5247
- _a = createAta;
5248
- if (!_a) return [3, 4];
5249
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5250
- case 3:
5251
- _a = !(_b.sent());
5252
- _b.label = 4;
5253
- case 4:
5254
- if (_a) {
5255
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, userTokenAccount, owner, poolConfig.tokenMint));
5256
- }
5257
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, owner, true)];
5258
- case 5:
5259
- nftTokenAccount = _b.sent();
5260
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5261
- Buffer.from("trading"),
5262
- nftMint.toBuffer(),
5263
- ], this.programId)[0];
5264
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5265
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5266
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5267
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5268
- return [4, this.program.methods
5269
- .burnAndClaim({})
5270
- .accounts({
5271
- owner: owner,
5272
- receivingTokenAccount: userTokenAccount,
5273
- perpetuals: this.perpetuals.publicKey,
5274
- tokenVault: poolConfig.tokenVault,
5275
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5276
- metadataAccount: metadataAccount,
5277
- collectionMetadata: collectionMetadata,
5278
- edition: edition,
5279
- tokenRecord: tokenRecord,
5280
- tradingAccount: nftTradingAccount,
5281
- transferAuthority: poolConfig.transferAuthority,
5282
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5283
- nftMint: nftMint,
5284
- nftTokenAccount: nftTokenAccount,
5285
- systemProgram: web3_js_1.SystemProgram.programId,
5286
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5287
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5288
- eventAuthority: this.eventAuthority.publicKey,
5289
- program: this.programId,
5290
- receivingTokenMint: poolConfig.tokenMint,
5291
- })
5292
- .instruction()];
5293
- case 6:
5294
- burnAndClaimInstruction = _b.sent();
5295
- instructions.push(burnAndClaimInstruction);
5296
- return [3, 8];
5297
- case 7:
5298
- err_23 = _b.sent();
5299
- console.log("perpClient burnAndClaimInstruction error:: ", err_23);
5300
- throw err_23;
5301
- case 8: return [2, {
5302
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5303
- additionalSigners: additionalSigners
5304
- }];
5305
- }
5306
- });
5307
- }); };
5308
- this.burnAndStake = function (owner, feePayer, nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5309
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndStakeInstruction, err_24;
5310
- return __generator(this, function (_a) {
5311
- switch (_a.label) {
5312
- case 0:
5313
- preInstructions = [];
5314
- instructions = [];
5315
- postInstructions = [];
5316
- additionalSigners = [];
5317
- _a.label = 1;
5318
- case 1:
5319
- _a.trys.push([1, 3, , 4]);
5320
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5321
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, owner, true);
5322
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5323
- Buffer.from("trading"),
5324
- nftMint.toBuffer(),
5325
- ], this.programId)[0];
5326
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5327
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5328
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5329
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5330
- return [4, this.program.methods
5331
- .burnAndStake({})
5332
- .accounts({
5333
- owner: owner,
5334
- feePayer: feePayer,
5335
- perpetuals: this.perpetuals.publicKey,
5336
- tokenVault: poolConfig.tokenVault,
5337
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5338
- tokenStakeAccount: tokenStakeAccount,
5339
- metadataAccount: metadataAccount,
5340
- collectionMetadata: collectionMetadata,
5341
- edition: edition,
5342
- tokenRecord: tokenRecord,
5343
- tradingAccount: nftTradingAccount,
5344
- transferAuthority: poolConfig.transferAuthority,
5345
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5346
- nftMint: nftMint,
5347
- nftTokenAccount: nftTokenAccount,
5348
- systemProgram: web3_js_1.SystemProgram.programId,
5349
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5350
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5351
- eventAuthority: this.eventAuthority.publicKey,
5352
- program: this.programId
5353
- })
5354
- .instruction()];
5355
- case 2:
5356
- burnAndStakeInstruction = _a.sent();
5357
- instructions.push(burnAndStakeInstruction);
5358
- return [3, 4];
5359
- case 3:
5360
- err_24 = _a.sent();
5361
- console.log("perpClient burnAndStakeInstruction error:: ", err_24);
5362
- throw err_24;
5363
- case 4: return [2, {
5364
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5365
- additionalSigners: additionalSigners
5366
- }];
5367
- }
5368
- });
5369
- }); };
5370
- this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5371
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_25;
5372
- return __generator(this, function (_a) {
5373
- switch (_a.label) {
5374
- case 0:
5375
- preInstructions = [];
5376
- instructions = [];
5377
- postInstructions = [];
5378
- additionalSigners = [];
5379
- _a.label = 1;
5380
- case 1:
5381
- _a.trys.push([1, 4, , 5]);
5382
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5383
- userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.tokenMint, owner, true);
5042
+ _a.trys.push([1, 4, , 5]);
5043
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5044
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.tokenMint, owner, true);
5384
5045
  return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5385
5046
  case 2:
5386
5047
  if (!(_a.sent())) {
@@ -5410,9 +5071,9 @@ var PerpetualsClient = (function () {
5410
5071
  instructions.push(depositTokenStakeInstruction);
5411
5072
  return [3, 5];
5412
5073
  case 4:
5413
- err_25 = _a.sent();
5414
- console.log("perpClient depositStakingInstruction error:: ", err_25);
5415
- throw err_25;
5074
+ err_21 = _a.sent();
5075
+ console.log("perpClient depositStakingInstruction error:: ", err_21);
5076
+ throw err_21;
5416
5077
  case 5: return [2, {
5417
5078
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5418
5079
  additionalSigners: additionalSigners
@@ -5421,7 +5082,7 @@ var PerpetualsClient = (function () {
5421
5082
  });
5422
5083
  }); };
5423
5084
  this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5424
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_26;
5085
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_22;
5425
5086
  return __generator(this, function (_a) {
5426
5087
  switch (_a.label) {
5427
5088
  case 0:
@@ -5450,9 +5111,9 @@ var PerpetualsClient = (function () {
5450
5111
  instructions.push(unstakeTokenRequestInstruction);
5451
5112
  return [3, 4];
5452
5113
  case 3:
5453
- err_26 = _a.sent();
5454
- console.log("perpClient unstakeTokenRequestInstruction error:: ", err_26);
5455
- throw err_26;
5114
+ err_22 = _a.sent();
5115
+ console.log("perpClient unstakeTokenRequestInstruction error:: ", err_22);
5116
+ throw err_22;
5456
5117
  case 4: return [2, {
5457
5118
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5458
5119
  additionalSigners: additionalSigners
@@ -5461,7 +5122,7 @@ var PerpetualsClient = (function () {
5461
5122
  });
5462
5123
  }); };
5463
5124
  this.unstakeTokenInstant = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5464
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_27;
5125
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_23;
5465
5126
  return __generator(this, function (_a) {
5466
5127
  switch (_a.label) {
5467
5128
  case 0:
@@ -5502,9 +5163,9 @@ var PerpetualsClient = (function () {
5502
5163
  instructions.push(unstakeTokenInstantInstruction);
5503
5164
  return [3, 5];
5504
5165
  case 4:
5505
- err_27 = _a.sent();
5506
- console.log("perpClient unstakeTokenInstantInstruction error:: ", err_27);
5507
- throw err_27;
5166
+ err_23 = _a.sent();
5167
+ console.log("perpClient unstakeTokenInstantInstruction error:: ", err_23);
5168
+ throw err_23;
5508
5169
  case 5: return [2, {
5509
5170
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5510
5171
  additionalSigners: additionalSigners
@@ -5513,7 +5174,7 @@ var PerpetualsClient = (function () {
5513
5174
  });
5514
5175
  }); };
5515
5176
  this.withdrawToken = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5516
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_28;
5177
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_24;
5517
5178
  return __generator(this, function (_a) {
5518
5179
  switch (_a.label) {
5519
5180
  case 0:
@@ -5554,9 +5215,9 @@ var PerpetualsClient = (function () {
5554
5215
  instructions.push(withdrawTokenInstruction);
5555
5216
  return [3, 5];
5556
5217
  case 4:
5557
- err_28 = _a.sent();
5558
- console.log("perpClient withdrawTokenInstruction error:: ", err_28);
5559
- throw err_28;
5218
+ err_24 = _a.sent();
5219
+ console.log("perpClient withdrawTokenInstruction error:: ", err_24);
5220
+ throw err_24;
5560
5221
  case 5: return [2, {
5561
5222
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5562
5223
  additionalSigners: additionalSigners
@@ -5565,7 +5226,7 @@ var PerpetualsClient = (function () {
5565
5226
  });
5566
5227
  }); };
5567
5228
  this.cancelUnstakeRequest = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5568
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_29;
5229
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_25;
5569
5230
  return __generator(this, function (_a) {
5570
5231
  switch (_a.label) {
5571
5232
  case 0:
@@ -5594,9 +5255,9 @@ var PerpetualsClient = (function () {
5594
5255
  instructions.push(cancelUnstakeRequestInstruction);
5595
5256
  return [3, 4];
5596
5257
  case 3:
5597
- err_29 = _a.sent();
5598
- console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_29);
5599
- throw err_29;
5258
+ err_25 = _a.sent();
5259
+ console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_25);
5260
+ throw err_25;
5600
5261
  case 4: return [2, {
5601
5262
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5602
5263
  additionalSigners: additionalSigners
@@ -5610,7 +5271,7 @@ var PerpetualsClient = (function () {
5610
5271
  args_1[_i - 2] = arguments[_i];
5611
5272
  }
5612
5273
  return __awaiter(_this, __spreadArray([owner_1, poolConfig_1], args_1, true), void 0, function (owner, poolConfig, createUserATA) {
5613
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_30;
5274
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_26;
5614
5275
  if (createUserATA === void 0) { createUserATA = true; }
5615
5276
  return __generator(this, function (_b) {
5616
5277
  switch (_b.label) {
@@ -5656,9 +5317,9 @@ var PerpetualsClient = (function () {
5656
5317
  instructions.push(collectTokenRewardInstruction);
5657
5318
  return [3, 6];
5658
5319
  case 5:
5659
- err_30 = _b.sent();
5660
- console.log("perpClient collectTokenRewardInstruction error:: ", err_30);
5661
- throw err_30;
5320
+ err_26 = _b.sent();
5321
+ console.log("perpClient collectTokenRewardInstruction error:: ", err_26);
5322
+ throw err_26;
5662
5323
  case 6: return [2, {
5663
5324
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5664
5325
  additionalSigners: additionalSigners
@@ -5673,7 +5334,7 @@ var PerpetualsClient = (function () {
5673
5334
  args_1[_i - 3] = arguments[_i];
5674
5335
  }
5675
5336
  return __awaiter(_this, __spreadArray([owner_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rewardSymbol, poolConfig, createUserATA) {
5676
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_31;
5337
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_27;
5677
5338
  if (createUserATA === void 0) { createUserATA = true; }
5678
5339
  return __generator(this, function (_b) {
5679
5340
  switch (_b.label) {
@@ -5720,9 +5381,9 @@ var PerpetualsClient = (function () {
5720
5381
  instructions.push(collectRevenueInstruction);
5721
5382
  return [3, 6];
5722
5383
  case 5:
5723
- err_31 = _b.sent();
5724
- console.log("perpClient collectRevenueInstruction error:: ", err_31);
5725
- throw err_31;
5384
+ err_27 = _b.sent();
5385
+ console.log("perpClient collectRevenueInstruction error:: ", err_27);
5386
+ throw err_27;
5726
5387
  case 6: return [2, {
5727
5388
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5728
5389
  additionalSigners: additionalSigners
@@ -5731,179 +5392,82 @@ var PerpetualsClient = (function () {
5731
5392
  });
5732
5393
  });
5733
5394
  };
5734
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5735
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_32;
5736
- return __generator(this, function (_a) {
5737
- switch (_a.label) {
5738
- case 0:
5739
- publicKey = this.provider.wallet.publicKey;
5740
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5741
- instructions = [];
5742
- additionalSigners = [];
5743
- _a.label = 1;
5744
- case 1:
5745
- _a.trys.push([1, 3, , 4]);
5746
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5747
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5748
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5749
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5750
- return [4, this.programFbnftReward.methods
5751
- .initRewardVault({
5752
- nftCount: nftCount
5753
- })
5754
- .accounts({
5755
- admin: publicKey,
5756
- transferAuthority: nftTransferAuthority,
5757
- rewardVault: rewardVault,
5758
- rewardMint: rewardCustodyMint,
5759
- rewardTokenAccount: rewardTokenAccount,
5760
- collectionMint: collectionMint,
5761
- programData: fbNftProgramData,
5762
- systemProgram: web3_js_1.SystemProgram.programId,
5763
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5764
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5765
- })
5766
- .instruction()];
5767
- case 2:
5768
- initRewardVault = _a.sent();
5769
- instructions.push(initRewardVault);
5770
- return [3, 4];
5771
- case 3:
5772
- err_32 = _a.sent();
5773
- console.log("perpClient InitRewardVault error:: ", err_32);
5774
- throw err_32;
5775
- case 4: return [2, {
5776
- instructions: __spreadArray([], instructions, true),
5777
- additionalSigners: additionalSigners
5778
- }];
5779
- }
5780
- });
5781
- }); };
5782
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5783
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_33;
5784
- return __generator(this, function (_a) {
5785
- switch (_a.label) {
5786
- case 0:
5787
- publicKey = this.provider.wallet.publicKey;
5788
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5789
- instructions = [];
5790
- additionalSigners = [];
5791
- _a.label = 1;
5792
- case 1:
5793
- _a.trys.push([1, 3, , 4]);
5794
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5795
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5796
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5797
- return [4, this.programFbnftReward.methods
5798
- .distributeRewards({
5799
- rewardAmount: rewardAmount
5800
- })
5801
- .accounts({
5802
- admin: publicKey,
5803
- fundingAccount: fundingAccount,
5804
- rewardVault: rewardVault,
5805
- rewardTokenAccount: rewardTokenAccount,
5806
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5807
- })
5808
- .instruction()];
5809
- case 2:
5810
- distributeReward = _a.sent();
5811
- instructions.push(distributeReward);
5812
- return [3, 4];
5813
- case 3:
5814
- err_33 = _a.sent();
5815
- console.log("perpClient distributeReward error:: ", err_33);
5816
- throw err_33;
5817
- case 4: return [2, {
5818
- instructions: __spreadArray([], instructions, true),
5819
- additionalSigners: additionalSigners
5820
- }];
5821
- }
5822
- });
5823
- }); };
5824
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5395
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5825
5396
  var args_1 = [];
5826
5397
  for (var _i = 3; _i < arguments.length; _i++) {
5827
5398
  args_1[_i - 3] = arguments[_i];
5828
5399
  }
5829
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5830
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_34;
5400
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5401
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5831
5402
  if (createUserATA === void 0) { createUserATA = true; }
5832
5403
  return __generator(this, function (_b) {
5833
5404
  switch (_b.label) {
5834
5405
  case 0:
5835
5406
  publicKey = this.provider.wallet.publicKey;
5836
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5837
- rewardCustodyMint = rewardToken.mintKey;
5407
+ preInstructions = [];
5838
5408
  instructions = [];
5409
+ postInstructions = [];
5839
5410
  additionalSigners = [];
5840
5411
  _b.label = 1;
5841
5412
  case 1:
5842
5413
  _b.trys.push([1, 5, , 6]);
5843
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5844
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5845
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5414
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5415
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5416
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5846
5417
  _a = createUserATA;
5847
5418
  if (!_a) return [3, 3];
5848
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5419
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5849
5420
  case 2:
5850
5421
  _a = !(_b.sent());
5851
5422
  _b.label = 3;
5852
5423
  case 3:
5853
5424
  if (_a) {
5854
- 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));
5855
- }
5856
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5857
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5858
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5859
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5860
- return [4, this.programFbnftReward.methods
5861
- .collectReward()
5425
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5426
+ }
5427
+ return [4, this.program.methods
5428
+ .collectRebate()
5862
5429
  .accounts({
5863
- owner: publicKey,
5864
- feePayer: publicKey,
5865
- nftMint: nftMint,
5866
- nftTokenAccount: nftTokenAccount,
5867
- metadataAccount: metadataAccount,
5868
- receivingAccount: receivingTokenAccount,
5869
- rewardRecord: rewardRecord,
5870
- rewardVault: rewardVault,
5871
- rewardTokenAccount: rewardTokenAccount,
5872
- transferAuthority: nftTransferAuthority,
5873
- systemProgram: web3_js_1.SystemProgram.programId,
5874
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5430
+ owner: owner,
5431
+ receivingTokenAccount: userTokenAccount,
5432
+ perpetuals: this.perpetuals.publicKey,
5433
+ transferAuthority: poolConfig.transferAuthority,
5434
+ rebateVault: poolConfig.rebateVault,
5435
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5436
+ tokenStakeAccount: tokenStakeAccount,
5437
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5438
+ eventAuthority: this.eventAuthority.publicKey,
5439
+ program: this.programId,
5440
+ receivingTokenMint: rebateMint,
5875
5441
  })
5876
5442
  .instruction()];
5877
5443
  case 4:
5878
- collectNftReward = _b.sent();
5879
- instructions.push(collectNftReward);
5444
+ collectRebateInstruction = _b.sent();
5445
+ instructions.push(collectRebateInstruction);
5880
5446
  return [3, 6];
5881
5447
  case 5:
5882
- err_34 = _b.sent();
5883
- throw err_34;
5448
+ err_28 = _b.sent();
5449
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5450
+ throw err_28;
5884
5451
  case 6: return [2, {
5885
- instructions: __spreadArray([], instructions, true),
5452
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5886
5453
  additionalSigners: additionalSigners
5887
5454
  }];
5888
5455
  }
5889
5456
  });
5890
5457
  });
5891
5458
  };
5892
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5459
+ this.settleRebates = function (owner_1, rebateSymbol_1, rewardSymbol_1, poolConfig_1) {
5893
5460
  var args_1 = [];
5894
- for (var _i = 2; _i < arguments.length; _i++) {
5895
- args_1[_i - 2] = arguments[_i];
5461
+ for (var _i = 4; _i < arguments.length; _i++) {
5462
+ args_1[_i - 4] = arguments[_i];
5896
5463
  }
5897
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5898
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_35;
5464
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, rewardSymbol, poolConfig, createUserATA) {
5465
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, userTokenAccount, _a, settleRebatesInstruction, err_29;
5899
5466
  if (createUserATA === void 0) { createUserATA = true; }
5900
5467
  return __generator(this, function (_b) {
5901
5468
  switch (_b.label) {
5902
5469
  case 0:
5903
5470
  publicKey = this.provider.wallet.publicKey;
5904
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5905
- rewardCustodyMint = rewardToken.mintKey;
5906
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5907
5471
  preInstructions = [];
5908
5472
  instructions = [];
5909
5473
  postInstructions = [];
@@ -5911,59 +5475,45 @@ var PerpetualsClient = (function () {
5911
5475
  _b.label = 1;
5912
5476
  case 1:
5913
5477
  _b.trys.push([1, 5, , 6]);
5914
- pool = poolConfig.poolAddress;
5915
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5916
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5478
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5479
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5480
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5917
5481
  _a = createUserATA;
5918
5482
  if (!_a) return [3, 3];
5919
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5483
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5920
5484
  case 2:
5921
5485
  _a = !(_b.sent());
5922
5486
  _b.label = 3;
5923
5487
  case 3:
5924
5488
  if (_a) {
5925
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5926
- }
5927
- tradingAccount = [];
5928
- if (nftTradingAccount) {
5929
- tradingAccount.push({
5930
- pubkey: nftTradingAccount,
5931
- isSigner: false,
5932
- isWritable: true,
5933
- });
5489
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5934
5490
  }
5935
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5936
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5937
- return [4, this.programPerpComposability.methods
5938
- .collectAndDistributeFee()
5491
+ return [4, this.program.methods
5492
+ .settleRebates()
5939
5493
  .accounts({
5940
- perpProgram: this.programId,
5941
- owner: publicKey,
5942
- receivingTokenAccount: receivingTokenAccount,
5943
5494
  transferAuthority: poolConfig.transferAuthority,
5944
5495
  perpetuals: this.perpetuals.publicKey,
5945
- pool: pool,
5946
- feeCustody: rewardCustodyConfig.custodyAccount,
5947
- flpStakeAccount: flpStakeAccount,
5948
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5949
- systemProgram: web3_js_1.SystemProgram.programId,
5496
+ pool: poolConfig.poolAddress,
5497
+ rewardCustody: rewardCustody.custodyAccount,
5498
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5499
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5500
+ rebateVault: poolConfig.rebateVault,
5501
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5502
+ tokenMint: rebateMint,
5950
5503
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5951
5504
  eventAuthority: this.eventAuthority.publicKey,
5952
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5953
- fbnftRewardsProgram: this.programFbnftReward.programId,
5954
- rewardVault: rewardVault,
5955
- rewardTokenAccount: rewardTokenAccount
5505
+ program: this.programId,
5506
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5956
5507
  })
5957
- .remainingAccounts(tradingAccount)
5958
5508
  .instruction()];
5959
5509
  case 4:
5960
- withdrawStakeInstruction = _b.sent();
5961
- instructions.push(withdrawStakeInstruction);
5510
+ settleRebatesInstruction = _b.sent();
5511
+ instructions.push(settleRebatesInstruction);
5962
5512
  return [3, 6];
5963
5513
  case 5:
5964
- err_35 = _b.sent();
5965
- console.log("perpClient withdrawStake error:: ", err_35);
5966
- throw err_35;
5514
+ err_29 = _b.sent();
5515
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5516
+ throw err_29;
5967
5517
  case 6: return [2, {
5968
5518
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5969
5519
  additionalSigners: additionalSigners
@@ -5978,7 +5528,7 @@ var PerpetualsClient = (function () {
5978
5528
  args_1[_i - 11] = arguments[_i];
5979
5529
  }
5980
5530
  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) {
5981
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_36;
5531
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5982
5532
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5983
5533
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5984
5534
  return __generator(this, function (_c) {
@@ -6084,9 +5634,9 @@ var PerpetualsClient = (function () {
6084
5634
  instructions.push(placeLimitOrder);
6085
5635
  return [3, 10];
6086
5636
  case 9:
6087
- err_36 = _c.sent();
6088
- console.log("perpClient placeLimitOrder error:: ", err_36);
6089
- throw err_36;
5637
+ err_30 = _c.sent();
5638
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5639
+ throw err_30;
6090
5640
  case 10: return [2, {
6091
5641
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6092
5642
  additionalSigners: additionalSigners
@@ -6101,7 +5651,7 @@ var PerpetualsClient = (function () {
6101
5651
  args_1[_i - 11] = arguments[_i];
6102
5652
  }
6103
5653
  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) {
6104
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_37;
5654
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
6105
5655
  if (createUserATA === void 0) { createUserATA = true; }
6106
5656
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6107
5657
  return __generator(this, function (_b) {
@@ -6192,9 +5742,9 @@ var PerpetualsClient = (function () {
6192
5742
  instructions.push(editLimitOrder);
6193
5743
  return [3, 8];
6194
5744
  case 7:
6195
- err_37 = _b.sent();
6196
- console.log("perpClient editLimitOrder error:: ", err_37);
6197
- throw err_37;
5745
+ err_31 = _b.sent();
5746
+ console.log("perpClient editLimitOrder error:: ", err_31);
5747
+ throw err_31;
6198
5748
  case 8: return [2, {
6199
5749
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6200
5750
  additionalSigners: additionalSigners
@@ -6208,11 +5758,10 @@ var PerpetualsClient = (function () {
6208
5758
  for (var _i = 7; _i < arguments.length; _i++) {
6209
5759
  args_1[_i - 7] = arguments[_i];
6210
5760
  }
6211
- 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) {
6212
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_38;
5761
+ 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) {
5762
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
6213
5763
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6214
5764
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6215
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6216
5765
  return __generator(this, function (_a) {
6217
5766
  switch (_a.label) {
6218
5767
  case 0:
@@ -6255,16 +5804,16 @@ var PerpetualsClient = (function () {
6255
5804
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6256
5805
  collateralMint: collateralCustodyConfig.mintKey,
6257
5806
  })
6258
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5807
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6259
5808
  .instruction()];
6260
5809
  case 2:
6261
5810
  executeLimitOrder = _a.sent();
6262
5811
  instructions.push(executeLimitOrder);
6263
5812
  return [3, 4];
6264
5813
  case 3:
6265
- err_38 = _a.sent();
6266
- console.log("perpClient executeLimitOrder error:: ", err_38);
6267
- throw err_38;
5814
+ err_32 = _a.sent();
5815
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5816
+ throw err_32;
6268
5817
  case 4: return [2, {
6269
5818
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6270
5819
  additionalSigners: additionalSigners
@@ -6278,11 +5827,10 @@ var PerpetualsClient = (function () {
6278
5827
  for (var _i = 8; _i < arguments.length; _i++) {
6279
5828
  args_1[_i - 8] = arguments[_i];
6280
5829
  }
6281
- 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) {
6282
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_39;
5830
+ 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) {
5831
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6283
5832
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6284
5833
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6285
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6286
5834
  return __generator(this, function (_a) {
6287
5835
  switch (_a.label) {
6288
5836
  case 0:
@@ -6328,16 +5876,16 @@ var PerpetualsClient = (function () {
6328
5876
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6329
5877
  collateralMint: collateralCustodyConfig.mintKey,
6330
5878
  })
6331
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5879
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6332
5880
  .instruction()];
6333
5881
  case 2:
6334
5882
  executeLimitWithSwap = _a.sent();
6335
5883
  instructions.push(executeLimitWithSwap);
6336
5884
  return [3, 4];
6337
5885
  case 3:
6338
- err_39 = _a.sent();
6339
- console.log("perpClient executeLimitWithSwap error:: ", err_39);
6340
- throw err_39;
5886
+ err_33 = _a.sent();
5887
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5888
+ throw err_33;
6341
5889
  case 4: return [2, {
6342
5890
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6343
5891
  additionalSigners: additionalSigners
@@ -6347,7 +5895,7 @@ var PerpetualsClient = (function () {
6347
5895
  });
6348
5896
  };
6349
5897
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6350
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_40;
5898
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6351
5899
  return __generator(this, function (_a) {
6352
5900
  switch (_a.label) {
6353
5901
  case 0:
@@ -6395,9 +5943,9 @@ var PerpetualsClient = (function () {
6395
5943
  instructions.push(placeTriggerOrder);
6396
5944
  return [3, 4];
6397
5945
  case 3:
6398
- err_40 = _a.sent();
6399
- console.log("perpClient placeTriggerOrder error:: ", err_40);
6400
- throw err_40;
5946
+ err_34 = _a.sent();
5947
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5948
+ throw err_34;
6401
5949
  case 4: return [2, {
6402
5950
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6403
5951
  additionalSigners: additionalSigners
@@ -6406,7 +5954,7 @@ var PerpetualsClient = (function () {
6406
5954
  });
6407
5955
  }); };
6408
5956
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6409
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_41;
5957
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6410
5958
  return __generator(this, function (_a) {
6411
5959
  switch (_a.label) {
6412
5960
  case 0:
@@ -6453,9 +6001,9 @@ var PerpetualsClient = (function () {
6453
6001
  instructions.push(editTriggerOrder);
6454
6002
  return [3, 4];
6455
6003
  case 3:
6456
- err_41 = _a.sent();
6457
- console.log("perpClient editTriggerOrder error:: ", err_41);
6458
- throw err_41;
6004
+ err_35 = _a.sent();
6005
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6006
+ throw err_35;
6459
6007
  case 4: return [2, {
6460
6008
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6461
6009
  additionalSigners: additionalSigners
@@ -6464,7 +6012,7 @@ var PerpetualsClient = (function () {
6464
6012
  });
6465
6013
  }); };
6466
6014
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6467
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_42;
6015
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6468
6016
  return __generator(this, function (_a) {
6469
6017
  switch (_a.label) {
6470
6018
  case 0:
@@ -6497,9 +6045,9 @@ var PerpetualsClient = (function () {
6497
6045
  instructions.push(cancelTriggerOrder);
6498
6046
  return [3, 4];
6499
6047
  case 3:
6500
- err_42 = _a.sent();
6501
- console.log("perpClient cancelTriggerOrder error:: ", err_42);
6502
- throw err_42;
6048
+ err_36 = _a.sent();
6049
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6050
+ throw err_36;
6503
6051
  case 4: return [2, {
6504
6052
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6505
6053
  additionalSigners: additionalSigners
@@ -6508,7 +6056,7 @@ var PerpetualsClient = (function () {
6508
6056
  });
6509
6057
  }); };
6510
6058
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6511
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_43;
6059
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6512
6060
  return __generator(this, function (_a) {
6513
6061
  switch (_a.label) {
6514
6062
  case 0:
@@ -6539,9 +6087,9 @@ var PerpetualsClient = (function () {
6539
6087
  instructions.push(cancelAllTriggerOrders);
6540
6088
  return [3, 4];
6541
6089
  case 3:
6542
- err_43 = _a.sent();
6543
- console.log("perpClient cancelAllTriggerOrders error:: ", err_43);
6544
- throw err_43;
6090
+ err_37 = _a.sent();
6091
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6092
+ throw err_37;
6545
6093
  case 4: return [2, {
6546
6094
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6547
6095
  additionalSigners: additionalSigners
@@ -6554,13 +6102,12 @@ var PerpetualsClient = (function () {
6554
6102
  for (var _i = 9; _i < arguments.length; _i++) {
6555
6103
  args_1[_i - 9] = arguments[_i];
6556
6104
  }
6557
- 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) {
6558
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_44;
6105
+ 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) {
6106
+ 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;
6559
6107
  if (createUserATA === void 0) { createUserATA = true; }
6560
6108
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6561
6109
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6562
6110
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6563
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6564
6111
  return __generator(this, function (_e) {
6565
6112
  switch (_e.label) {
6566
6113
  case 0:
@@ -6655,16 +6202,16 @@ var PerpetualsClient = (function () {
6655
6202
  collateralMint: collateralCustodyConfig.mintKey,
6656
6203
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6657
6204
  })
6658
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6205
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6659
6206
  .instruction()];
6660
6207
  case 8:
6661
6208
  executeTriggerWithSwap = _e.sent();
6662
6209
  instructions.push(executeTriggerWithSwap);
6663
6210
  return [3, 10];
6664
6211
  case 9:
6665
- err_44 = _e.sent();
6666
- console.log("perpClient executeTriggerWithSwap error:: ", err_44);
6667
- throw err_44;
6212
+ err_38 = _e.sent();
6213
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6214
+ throw err_38;
6668
6215
  case 10: return [2, {
6669
6216
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6670
6217
  additionalSigners: additionalSigners
@@ -6678,13 +6225,12 @@ var PerpetualsClient = (function () {
6678
6225
  for (var _i = 8; _i < arguments.length; _i++) {
6679
6226
  args_1[_i - 8] = arguments[_i];
6680
6227
  }
6681
- 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) {
6682
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_45;
6228
+ 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) {
6229
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6683
6230
  if (createUserATA === void 0) { createUserATA = true; }
6684
6231
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6685
6232
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6686
6233
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6687
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6688
6234
  return __generator(this, function (_b) {
6689
6235
  switch (_b.label) {
6690
6236
  case 0:
@@ -6744,16 +6290,16 @@ var PerpetualsClient = (function () {
6744
6290
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6745
6291
  receivingMint: collateralCustodyConfig.mintKey
6746
6292
  })
6747
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6293
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6748
6294
  .instruction()];
6749
6295
  case 6:
6750
6296
  executeTriggerOrder = _b.sent();
6751
6297
  instructions.push(executeTriggerOrder);
6752
6298
  return [3, 8];
6753
6299
  case 7:
6754
- err_45 = _b.sent();
6755
- console.log("perpClient executeTriggerOrder error:: ", err_45);
6756
- throw err_45;
6300
+ err_39 = _b.sent();
6301
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6302
+ throw err_39;
6757
6303
  case 8: return [2, {
6758
6304
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6759
6305
  additionalSigners: additionalSigners
@@ -6768,7 +6314,7 @@ var PerpetualsClient = (function () {
6768
6314
  args_1[_i - 5] = arguments[_i];
6769
6315
  }
6770
6316
  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) {
6771
- var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_46;
6317
+ 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;
6772
6318
  if (useFeesPool === void 0) { useFeesPool = false; }
6773
6319
  if (createUserATA === void 0) { createUserATA = true; }
6774
6320
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6973,9 +6519,9 @@ var PerpetualsClient = (function () {
6973
6519
  }
6974
6520
  return [3, 20];
6975
6521
  case 19:
6976
- err_46 = _g.sent();
6977
- console.error("perpClient Swap error:: ", err_46);
6978
- throw err_46;
6522
+ err_40 = _g.sent();
6523
+ console.error("perpClient Swap error:: ", err_40);
6524
+ throw err_40;
6979
6525
  case 20: return [2, {
6980
6526
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6981
6527
  additionalSigners: additionalSigners
@@ -6985,7 +6531,7 @@ var PerpetualsClient = (function () {
6985
6531
  });
6986
6532
  };
6987
6533
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6988
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_47;
6534
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6989
6535
  return __generator(this, function (_b) {
6990
6536
  switch (_b.label) {
6991
6537
  case 0:
@@ -7030,11 +6576,7 @@ var PerpetualsClient = (function () {
7030
6576
  rewardCustody: rewardCustody.custodyAccount,
7031
6577
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
7032
6578
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
7033
- custody: custody.custodyAccount,
7034
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
7035
- custodyTokenAccount: custody.tokenAccount,
7036
6579
  eventAuthority: this.eventAuthority.publicKey,
7037
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7038
6580
  program: this.programId,
7039
6581
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
7040
6582
  })
@@ -7045,9 +6587,9 @@ var PerpetualsClient = (function () {
7045
6587
  instructions.push(inx);
7046
6588
  return [3, 4];
7047
6589
  case 3:
7048
- err_47 = _b.sent();
7049
- console.error("perpClient Swap error:: ", err_47);
7050
- throw err_47;
6590
+ err_41 = _b.sent();
6591
+ console.error("perpClient Swap error:: ", err_41);
6592
+ throw err_41;
7051
6593
  case 4: return [2, {
7052
6594
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7053
6595
  additionalSigners: additionalSigners
@@ -7056,7 +6598,7 @@ var PerpetualsClient = (function () {
7056
6598
  });
7057
6599
  }); };
7058
6600
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7059
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_48;
6601
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
7060
6602
  return __generator(this, function (_d) {
7061
6603
  switch (_d.label) {
7062
6604
  case 0:
@@ -7104,9 +6646,9 @@ var PerpetualsClient = (function () {
7104
6646
  instructions.push(setLpTokenPriceInstruction);
7105
6647
  return [3, 4];
7106
6648
  case 3:
7107
- err_48 = _d.sent();
7108
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_48);
7109
- throw err_48;
6649
+ err_42 = _d.sent();
6650
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6651
+ throw err_42;
7110
6652
  case 4: return [2, {
7111
6653
  instructions: __spreadArray([], instructions, true),
7112
6654
  additionalSigners: additionalSigners
@@ -7154,7 +6696,7 @@ var PerpetualsClient = (function () {
7154
6696
  });
7155
6697
  }); };
7156
6698
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
7157
- var adminMetas, _i, admins_2, admin, err_49;
6699
+ var adminMetas, _i, admins_2, admin, err_43;
7158
6700
  return __generator(this, function (_a) {
7159
6701
  switch (_a.label) {
7160
6702
  case 0:
@@ -7184,11 +6726,11 @@ var PerpetualsClient = (function () {
7184
6726
  _a.sent();
7185
6727
  return [3, 4];
7186
6728
  case 3:
7187
- err_49 = _a.sent();
6729
+ err_43 = _a.sent();
7188
6730
  if (this.printErrors) {
7189
- console.error("setAdminSigners err:", err_49);
6731
+ console.error("setAdminSigners err:", err_43);
7190
6732
  }
7191
- throw err_49;
6733
+ throw err_43;
7192
6734
  case 4: return [2];
7193
6735
  }
7194
6736
  });
@@ -7377,7 +6919,7 @@ var PerpetualsClient = (function () {
7377
6919
  });
7378
6920
  }); };
7379
6921
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7380
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_50;
6922
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7381
6923
  return __generator(this, function (_a) {
7382
6924
  switch (_a.label) {
7383
6925
  case 0:
@@ -7410,9 +6952,9 @@ var PerpetualsClient = (function () {
7410
6952
  instructions.push(withdrawFeesIx);
7411
6953
  return [3, 5];
7412
6954
  case 4:
7413
- err_50 = _a.sent();
7414
- console.log("perpClient setPool error:: ", err_50);
7415
- throw err_50;
6955
+ err_44 = _a.sent();
6956
+ console.log("perpClient setPool error:: ", err_44);
6957
+ throw err_44;
7416
6958
  case 5: return [2, {
7417
6959
  instructions: __spreadArray([], instructions, true),
7418
6960
  additionalSigners: additionalSigners
@@ -7421,7 +6963,7 @@ var PerpetualsClient = (function () {
7421
6963
  });
7422
6964
  }); };
7423
6965
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7424
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_51;
6966
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7425
6967
  return __generator(this, function (_a) {
7426
6968
  switch (_a.label) {
7427
6969
  case 0:
@@ -7455,9 +6997,9 @@ var PerpetualsClient = (function () {
7455
6997
  instructions.push(moveProtocolFeesIx);
7456
6998
  return [3, 4];
7457
6999
  case 3:
7458
- err_51 = _a.sent();
7459
- console.log("perpClient setPool error:: ", err_51);
7460
- throw err_51;
7000
+ err_45 = _a.sent();
7001
+ console.log("perpClient setPool error:: ", err_45);
7002
+ throw err_45;
7461
7003
  case 4: return [2, {
7462
7004
  instructions: __spreadArray([], instructions, true),
7463
7005
  additionalSigners: additionalSigners
@@ -7466,7 +7008,7 @@ var PerpetualsClient = (function () {
7466
7008
  });
7467
7009
  }); };
7468
7010
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7469
- var publicKey, setProtocolFeeShareBpsIx, err_52;
7011
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7470
7012
  return __generator(this, function (_a) {
7471
7013
  switch (_a.label) {
7472
7014
  case 0:
@@ -7486,15 +7028,15 @@ var PerpetualsClient = (function () {
7486
7028
  setProtocolFeeShareBpsIx = _a.sent();
7487
7029
  return [2, setProtocolFeeShareBpsIx];
7488
7030
  case 2:
7489
- err_52 = _a.sent();
7490
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_52);
7491
- throw err_52;
7031
+ err_46 = _a.sent();
7032
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7033
+ throw err_46;
7492
7034
  case 3: return [2];
7493
7035
  }
7494
7036
  });
7495
7037
  }); };
7496
7038
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7497
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_53;
7039
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7498
7040
  return __generator(this, function (_a) {
7499
7041
  switch (_a.label) {
7500
7042
  case 0:
@@ -7521,9 +7063,9 @@ var PerpetualsClient = (function () {
7521
7063
  instructions.push(setPermissionsInstruction);
7522
7064
  return [3, 4];
7523
7065
  case 3:
7524
- err_53 = _a.sent();
7525
- console.log("perpClient setPool error:: ", err_53);
7526
- throw err_53;
7066
+ err_47 = _a.sent();
7067
+ console.log("perpClient setPool error:: ", err_47);
7068
+ throw err_47;
7527
7069
  case 4: return [2, {
7528
7070
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7529
7071
  additionalSigners: additionalSigners
@@ -7532,7 +7074,7 @@ var PerpetualsClient = (function () {
7532
7074
  });
7533
7075
  }); };
7534
7076
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7535
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_54;
7077
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7536
7078
  var _f;
7537
7079
  return __generator(this, function (_g) {
7538
7080
  switch (_g.label) {
@@ -7593,9 +7135,9 @@ var PerpetualsClient = (function () {
7593
7135
  instructions.push(reimburse);
7594
7136
  return [3, 5];
7595
7137
  case 4:
7596
- err_54 = _g.sent();
7597
- console.log("perpClient setPool error:: ", err_54);
7598
- throw err_54;
7138
+ err_48 = _g.sent();
7139
+ console.log("perpClient setPool error:: ", err_48);
7140
+ throw err_48;
7599
7141
  case 5: return [2, {
7600
7142
  instructions: __spreadArray([], instructions, true),
7601
7143
  additionalSigners: additionalSigners
@@ -7603,8 +7145,8 @@ var PerpetualsClient = (function () {
7603
7145
  }
7604
7146
  });
7605
7147
  }); };
7606
- this.setInternalOraclePrice = function (tokenMint, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7607
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_55;
7148
+ this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7149
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7608
7150
  return __generator(this, function (_a) {
7609
7151
  switch (_a.label) {
7610
7152
  case 0:
@@ -7616,6 +7158,7 @@ var PerpetualsClient = (function () {
7616
7158
  _a.trys.push([1, 3, , 4]);
7617
7159
  return [4, this.program.methods
7618
7160
  .setInternalOraclePrice({
7161
+ useCurrentTime: useCurrentTime,
7619
7162
  price: price,
7620
7163
  expo: expo,
7621
7164
  conf: conf,
@@ -7637,9 +7180,9 @@ var PerpetualsClient = (function () {
7637
7180
  instructions.push(setInternalOraclePrice);
7638
7181
  return [3, 4];
7639
7182
  case 3:
7640
- err_55 = _a.sent();
7641
- console.log("perpClient setInternalOracleAccount error:: ", err_55);
7642
- throw err_55;
7183
+ err_49 = _a.sent();
7184
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7185
+ throw err_49;
7643
7186
  case 4: return [2, {
7644
7187
  instructions: __spreadArray([], instructions, true),
7645
7188
  additionalSigners: additionalSigners
@@ -7647,8 +7190,8 @@ var PerpetualsClient = (function () {
7647
7190
  }
7648
7191
  });
7649
7192
  }); };
7650
- this.setInternalOraclePriceBatch = function (tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7651
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_56;
7193
+ this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7194
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7652
7195
  return __generator(this, function (_a) {
7653
7196
  switch (_a.label) {
7654
7197
  case 0:
@@ -7659,11 +7202,6 @@ var PerpetualsClient = (function () {
7659
7202
  accountMetas = [];
7660
7203
  _loop_1 = function (tokenMint) {
7661
7204
  var custody = ALL_CUSTODY_CONFIGS.find(function (i) { return i.mintKey.equals(tokenMint); });
7662
- accountMetas.push({
7663
- pubkey: custody.custodyAccount,
7664
- isSigner: false,
7665
- isWritable: false,
7666
- });
7667
7205
  accountMetas.push({
7668
7206
  pubkey: custody.intOracleAccount,
7669
7207
  isSigner: false,
@@ -7686,6 +7224,7 @@ var PerpetualsClient = (function () {
7686
7224
  _a.trys.push([1, 3, , 4]);
7687
7225
  return [4, this.program.methods
7688
7226
  .setInternalCurrentPrice({
7227
+ useCurrentTime: useCurrentTime,
7689
7228
  prices: tokenInternalPrices
7690
7229
  })
7691
7230
  .accounts({
@@ -7698,9 +7237,9 @@ var PerpetualsClient = (function () {
7698
7237
  instructions.push(setInternalOraclePrice);
7699
7238
  return [3, 4];
7700
7239
  case 3:
7701
- err_56 = _a.sent();
7702
- console.log("perpClient setInternalOracleAccount error:: ", err_56);
7703
- throw err_56;
7240
+ err_50 = _a.sent();
7241
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7242
+ throw err_50;
7704
7243
  case 4: return [2, {
7705
7244
  instructions: __spreadArray([], instructions, true),
7706
7245
  additionalSigners: additionalSigners
@@ -7709,7 +7248,7 @@ var PerpetualsClient = (function () {
7709
7248
  });
7710
7249
  }); };
7711
7250
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7712
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_57;
7251
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7713
7252
  return __generator(this, function (_a) {
7714
7253
  switch (_a.label) {
7715
7254
  case 0:
@@ -7720,21 +7259,11 @@ var PerpetualsClient = (function () {
7720
7259
  accountMetas = [];
7721
7260
  _loop_2 = function (tokenMint) {
7722
7261
  var custody = ALL_CUSTODY_CONFIGS.find(function (i) { return i.mintKey.equals(tokenMint); });
7723
- accountMetas.push({
7724
- pubkey: custody.custodyAccount,
7725
- isSigner: false,
7726
- isWritable: false,
7727
- });
7728
7262
  accountMetas.push({
7729
7263
  pubkey: custody.intOracleAccount,
7730
7264
  isSigner: false,
7731
7265
  isWritable: true,
7732
7266
  });
7733
- accountMetas.push({
7734
- pubkey: custody.extOracleAccount,
7735
- isSigner: false,
7736
- isWritable: false,
7737
- });
7738
7267
  };
7739
7268
  for (_i = 0, tokenMintList_2 = tokenMintList; _i < tokenMintList_2.length; _i++) {
7740
7269
  tokenMint = tokenMintList_2[_i];
@@ -7759,9 +7288,9 @@ var PerpetualsClient = (function () {
7759
7288
  instructions.push(setInternalOraclePrice);
7760
7289
  return [3, 4];
7761
7290
  case 3:
7762
- err_57 = _a.sent();
7763
- console.log("perpClient setInternalOracleAccount error:: ", err_57);
7764
- throw err_57;
7291
+ err_51 = _a.sent();
7292
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7293
+ throw err_51;
7765
7294
  case 4: return [2, {
7766
7295
  instructions: __spreadArray([], instructions, true),
7767
7296
  additionalSigners: additionalSigners
@@ -7770,7 +7299,7 @@ var PerpetualsClient = (function () {
7770
7299
  });
7771
7300
  }); };
7772
7301
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7773
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_58;
7302
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7774
7303
  return __generator(this, function (_a) {
7775
7304
  switch (_a.label) {
7776
7305
  case 0:
@@ -7808,8 +7337,8 @@ var PerpetualsClient = (function () {
7808
7337
  instructions.push(renameFlp);
7809
7338
  return [3, 4];
7810
7339
  case 3:
7811
- err_58 = _a.sent();
7812
- console.log("perpClient renameFlp error:: ", err_58);
7340
+ err_52 = _a.sent();
7341
+ console.log("perpClient renameFlp error:: ", err_52);
7813
7342
  return [3, 4];
7814
7343
  case 4: return [2, {
7815
7344
  instructions: __spreadArray([], instructions, true),
@@ -7819,7 +7348,7 @@ var PerpetualsClient = (function () {
7819
7348
  });
7820
7349
  }); };
7821
7350
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7822
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_59;
7351
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7823
7352
  return __generator(this, function (_a) {
7824
7353
  switch (_a.label) {
7825
7354
  case 0:
@@ -7857,9 +7386,9 @@ var PerpetualsClient = (function () {
7857
7386
  instructions.push(initStakeInstruction);
7858
7387
  return [3, 4];
7859
7388
  case 3:
7860
- err_59 = _a.sent();
7861
- console.log("perpClient InitStaking error:: ", err_59);
7862
- throw err_59;
7389
+ err_53 = _a.sent();
7390
+ console.log("perpClient InitStaking error:: ", err_53);
7391
+ throw err_53;
7863
7392
  case 4: return [2, {
7864
7393
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7865
7394
  additionalSigners: additionalSigners
@@ -7868,7 +7397,7 @@ var PerpetualsClient = (function () {
7868
7397
  });
7869
7398
  }); };
7870
7399
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7871
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_60;
7400
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7872
7401
  return __generator(this, function (_a) {
7873
7402
  switch (_a.label) {
7874
7403
  case 0:
@@ -7897,7 +7426,6 @@ var PerpetualsClient = (function () {
7897
7426
  transferAuthority: poolConfig.transferAuthority,
7898
7427
  perpetuals: this.perpetuals.publicKey,
7899
7428
  pool: poolConfig.poolAddress,
7900
- custody: rewardCustodyConfig.custodyAccount,
7901
7429
  lpTokenMint: poolConfig.stakedLpTokenMint,
7902
7430
  compoundingVault: compoundingVault,
7903
7431
  compoundingTokenMint: compoundingTokenMint,
@@ -7913,9 +7441,9 @@ var PerpetualsClient = (function () {
7913
7441
  instructions.push(initCompoundingInstruction);
7914
7442
  return [3, 4];
7915
7443
  case 3:
7916
- err_60 = _a.sent();
7917
- console.log("perpClient initCompounding error:: ", err_60);
7918
- throw err_60;
7444
+ err_54 = _a.sent();
7445
+ console.log("perpClient initCompounding error:: ", err_54);
7446
+ throw err_54;
7919
7447
  case 4: return [2, {
7920
7448
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7921
7449
  additionalSigners: additionalSigners
@@ -7924,7 +7452,7 @@ var PerpetualsClient = (function () {
7924
7452
  });
7925
7453
  }); };
7926
7454
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7927
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_61;
7455
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7928
7456
  return __generator(this, function (_a) {
7929
7457
  switch (_a.label) {
7930
7458
  case 0:
@@ -7965,9 +7493,9 @@ var PerpetualsClient = (function () {
7965
7493
  instructions.push(initTokenVaultInstruction);
7966
7494
  return [3, 4];
7967
7495
  case 3:
7968
- err_61 = _a.sent();
7969
- console.log("perpClient InitTokenVaultInstruction error:: ", err_61);
7970
- throw err_61;
7496
+ err_55 = _a.sent();
7497
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7498
+ throw err_55;
7971
7499
  case 4: return [2, {
7972
7500
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7973
7501
  additionalSigners: additionalSigners
@@ -7976,7 +7504,7 @@ var PerpetualsClient = (function () {
7976
7504
  });
7977
7505
  }); };
7978
7506
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7979
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_62;
7507
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7980
7508
  return __generator(this, function (_a) {
7981
7509
  switch (_a.label) {
7982
7510
  case 0:
@@ -8007,9 +7535,9 @@ var PerpetualsClient = (function () {
8007
7535
  instructions.push(setTokenVaultConfigInstruction);
8008
7536
  return [3, 4];
8009
7537
  case 3:
8010
- err_62 = _a.sent();
8011
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_62);
8012
- throw err_62;
7538
+ err_56 = _a.sent();
7539
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7540
+ throw err_56;
8013
7541
  case 4: return [2, {
8014
7542
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8015
7543
  additionalSigners: additionalSigners
@@ -8018,7 +7546,7 @@ var PerpetualsClient = (function () {
8018
7546
  });
8019
7547
  }); };
8020
7548
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8021
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_63;
7549
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
8022
7550
  return __generator(this, function (_a) {
8023
7551
  switch (_a.label) {
8024
7552
  case 0:
@@ -8057,9 +7585,59 @@ var PerpetualsClient = (function () {
8057
7585
  instructions.push(withdrawInstantFeeInstruction);
8058
7586
  return [3, 6];
8059
7587
  case 5:
8060
- err_63 = _a.sent();
8061
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_63);
8062
- throw err_63;
7588
+ err_57 = _a.sent();
7589
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7590
+ throw err_57;
7591
+ case 6: return [2, {
7592
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7593
+ additionalSigners: additionalSigners
7594
+ }];
7595
+ }
7596
+ });
7597
+ }); };
7598
+ this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7599
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7600
+ return __generator(this, function (_a) {
7601
+ switch (_a.label) {
7602
+ case 0:
7603
+ publicKey = this.provider.wallet.publicKey;
7604
+ preInstructions = [];
7605
+ instructions = [];
7606
+ postInstructions = [];
7607
+ additionalSigners = [];
7608
+ _a.label = 1;
7609
+ case 1:
7610
+ _a.trys.push([1, 5, , 6]);
7611
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, publicKey, true)];
7612
+ case 2:
7613
+ receivingTokenAccount = _a.sent();
7614
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
7615
+ case 3:
7616
+ if (!(_a.sent())) {
7617
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, poolConfig.tokenMint));
7618
+ }
7619
+ return [4, this.program.methods
7620
+ .withdrawUnclaimedTokens({})
7621
+ .accounts({
7622
+ admin: publicKey,
7623
+ multisig: this.multisig.publicKey,
7624
+ perpetuals: this.perpetuals.publicKey,
7625
+ transferAuthority: poolConfig.transferAuthority,
7626
+ tokenVault: poolConfig.tokenVault,
7627
+ tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
7628
+ receivingTokenAccount: receivingTokenAccount,
7629
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7630
+ receivingTokenMint: poolConfig.tokenMint,
7631
+ })
7632
+ .instruction()];
7633
+ case 4:
7634
+ withdrawUnclaimedTokensInstruction = _a.sent();
7635
+ instructions.push(withdrawUnclaimedTokensInstruction);
7636
+ return [3, 6];
7637
+ case 5:
7638
+ err_58 = _a.sent();
7639
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7640
+ throw err_58;
8063
7641
  case 6: return [2, {
8064
7642
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8065
7643
  additionalSigners: additionalSigners
@@ -8068,7 +7646,7 @@ var PerpetualsClient = (function () {
8068
7646
  });
8069
7647
  }); };
8070
7648
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8071
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_64;
7649
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
8072
7650
  return __generator(this, function (_a) {
8073
7651
  switch (_a.label) {
8074
7652
  case 0:
@@ -8105,9 +7683,9 @@ var PerpetualsClient = (function () {
8105
7683
  instructions.push(initRevenueTokenAccountInstruction);
8106
7684
  return [3, 4];
8107
7685
  case 3:
8108
- err_64 = _a.sent();
8109
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_64);
8110
- throw err_64;
7686
+ err_59 = _a.sent();
7687
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7688
+ throw err_59;
8111
7689
  case 4: return [2, {
8112
7690
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8113
7691
  additionalSigners: additionalSigners
@@ -8116,7 +7694,7 @@ var PerpetualsClient = (function () {
8116
7694
  });
8117
7695
  }); };
8118
7696
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8119
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_65;
7697
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_60;
8120
7698
  return __generator(this, function (_a) {
8121
7699
  switch (_a.label) {
8122
7700
  case 0:
@@ -8155,9 +7733,9 @@ var PerpetualsClient = (function () {
8155
7733
  instructions.push(distributeTokenRewardInstruction);
8156
7734
  return [3, 4];
8157
7735
  case 3:
8158
- err_65 = _a.sent();
8159
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_65);
8160
- throw err_65;
7736
+ err_60 = _a.sent();
7737
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_60);
7738
+ throw err_60;
8161
7739
  case 4: return [2, {
8162
7740
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8163
7741
  additionalSigners: additionalSigners
@@ -8166,7 +7744,7 @@ var PerpetualsClient = (function () {
8166
7744
  });
8167
7745
  }); };
8168
7746
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
8169
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_66;
7747
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_61;
8170
7748
  return __generator(this, function (_a) {
8171
7749
  switch (_a.label) {
8172
7750
  case 0:
@@ -8194,9 +7772,9 @@ var PerpetualsClient = (function () {
8194
7772
  instructions.push(setTokenStakeLevelInstruction);
8195
7773
  return [3, 4];
8196
7774
  case 3:
8197
- err_66 = _a.sent();
8198
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_66);
8199
- throw err_66;
7775
+ err_61 = _a.sent();
7776
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_61);
7777
+ throw err_61;
8200
7778
  case 4: return [2, {
8201
7779
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8202
7780
  additionalSigners: additionalSigners
@@ -8205,7 +7783,7 @@ var PerpetualsClient = (function () {
8205
7783
  });
8206
7784
  }); };
8207
7785
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8208
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_67;
7786
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_62;
8209
7787
  return __generator(this, function (_a) {
8210
7788
  switch (_a.label) {
8211
7789
  case 0:
@@ -8237,9 +7815,49 @@ var PerpetualsClient = (function () {
8237
7815
  instructions.push(setTokenRewardInstruction);
8238
7816
  return [3, 4];
8239
7817
  case 3:
8240
- err_67 = _a.sent();
8241
- console.log("perpClient setTokenRewardInstruction error:: ", err_67);
8242
- throw err_67;
7818
+ err_62 = _a.sent();
7819
+ console.log("perpClient setTokenRewardInstruction error:: ", err_62);
7820
+ throw err_62;
7821
+ case 4: return [2, {
7822
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7823
+ additionalSigners: additionalSigners
7824
+ }];
7825
+ }
7826
+ });
7827
+ }); };
7828
+ this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
7829
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_63;
7830
+ return __generator(this, function (_a) {
7831
+ switch (_a.label) {
7832
+ case 0:
7833
+ publicKey = this.provider.wallet.publicKey;
7834
+ preInstructions = [];
7835
+ instructions = [];
7836
+ postInstructions = [];
7837
+ additionalSigners = [];
7838
+ _a.label = 1;
7839
+ case 1:
7840
+ _a.trys.push([1, 3, , 4]);
7841
+ return [4, this.program.methods
7842
+ .resizeInternalOracle({
7843
+ extOracle: extOracle
7844
+ })
7845
+ .accounts({
7846
+ admin: publicKey,
7847
+ multisig: this.multisig.publicKey,
7848
+ custodyTokenMint: tokenMint,
7849
+ intOracleAccount: intOracleAccount,
7850
+ systemProgram: web3_js_1.SystemProgram.programId,
7851
+ })
7852
+ .instruction()];
7853
+ case 2:
7854
+ resizeInternalOracleInstruction = _a.sent();
7855
+ instructions.push(resizeInternalOracleInstruction);
7856
+ return [3, 4];
7857
+ case 3:
7858
+ err_63 = _a.sent();
7859
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_63);
7860
+ throw err_63;
8243
7861
  case 4: return [2, {
8244
7862
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8245
7863
  additionalSigners: additionalSigners