flash-sdk 10.10.5 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
20
20
  });
21
21
  };
22
22
  var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
25
  function verb(n) { return function (v) { return step([n, v]); }; }
26
26
  function step(op) {
27
27
  if (f) throw new TypeError("Generator is already executing.");
@@ -642,24 +642,41 @@ var PerpetualsClient = (function () {
642
642
  var averageEntryPrice = totalValue.div(totalSize);
643
643
  return averageEntryPrice;
644
644
  };
645
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
646
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
647
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
648
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
649
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
645
+ this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
646
+ var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
647
+ var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
648
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
649
+ var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
650
+ var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
651
+ var currentMarginUsd = constants_1.BN_ZERO;
652
+ if (isInitial) {
653
+ currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
654
+ }
655
+ else {
656
+ currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
657
+ }
658
+ if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
659
+ return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
650
660
  }
651
661
  else {
652
662
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
653
663
  }
654
664
  };
655
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
665
+ this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
666
+ positionAccount = positionAccount.clone();
667
+ positionAccount.sizeUsd = finalSizeUsd;
668
+ positionAccount.collateralUsd = finalCollateralUsd;
669
+ return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
670
+ };
671
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd, enableDebuglogs) {
672
+ if (enableDebuglogs === void 0) { enableDebuglogs = false; }
656
673
  var finalCollateralAmount = constants_1.BN_ZERO;
657
674
  if (!inputDeltaAmount.isZero()) {
658
675
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
659
676
  finalCollateralAmount = inputDeltaAmount;
660
677
  }
661
678
  else {
662
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
679
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
663
680
  finalCollateralAmount = swapAmountOut;
664
681
  }
665
682
  }
@@ -685,11 +702,13 @@ var PerpetualsClient = (function () {
685
702
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
686
703
  }
687
704
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
688
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
689
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
690
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
705
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals).add(positionAccount.collateralUsd);
706
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
691
707
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
692
708
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
709
+ if (enableDebuglogs) {
710
+ console.log("SDK logs : finalCollateralUsd:", finalCollateralUsd.toString(), "finalCollateralAmount:", finalCollateralAmount.toString(), "sizeAmount:", sizeAmount.toString(), "sizeAmountUsd:", sizeAmountUsd.toString(), "sizeDeltaAmount:", sizeDeltaAmount.toString(), "sizeUsd:", sizeUsd.toString(), "currentCollateralUsdIncludingPnl:", currentCollateralUsdIncludingPnl.toString(), "finalCollateralUsd :", finalCollateralUsd.toString(), "pnlUsd :", pnlUsd.toString());
711
+ }
693
712
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
694
713
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
695
714
  }
@@ -697,81 +716,22 @@ var PerpetualsClient = (function () {
697
716
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
698
717
  }
699
718
  };
700
- this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
701
- if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
702
- if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
703
- throw new Error("Delta Amounts cannot be negative.");
704
- }
705
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
706
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
707
- if (positionAccount === null) {
708
- var data = __assign({}, types_1.DEFAULT_POSITION);
709
- positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
710
- var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
711
- positionAccount.sizeUsd = sizeUsd_1;
712
- positionAccount.sizeDecimals = targetCustodyAccount.decimals;
713
- positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
714
- positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
715
- }
716
- else {
717
- positionAccount = positionAccount.clone();
718
- var positionEntryPrice = OraclePrice_1.OraclePrice.from({
719
- price: positionAccount.entryPrice.price,
720
- exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
721
- confidence: constants_1.BN_ZERO,
722
- timestamp: constants_1.BN_ZERO
723
- });
724
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
725
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
726
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
727
- }
728
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
729
- positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
730
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
731
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
732
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
733
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
734
- var feeUsd = constants_1.BN_ZERO;
735
- var feeAmount = constants_1.BN_ZERO;
736
- var feeUsdAfterDiscount = constants_1.BN_ZERO;
737
- var feeAmountAfterDiscount = constants_1.BN_ZERO;
738
- if (positionAccount !== null && sizeDeltaAmount.isZero()) {
739
- }
740
- else {
741
- feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
742
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
- if (discountBps.gt(constants_1.BN_ZERO)) {
744
- feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
745
- feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
746
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
747
- }
748
- else {
749
- feeUsdAfterDiscount = feeUsd;
750
- feeAmountAfterDiscount = feeAmount;
751
- }
752
- }
753
- return {
754
- entryOraclePrice: entryOraclePrice,
755
- feeUsd: feeUsd,
756
- feeAmount: feeAmount,
757
- feeUsdAfterDiscount: feeUsdAfterDiscount,
758
- feeAmountAfterDiscount: feeAmountAfterDiscount,
759
- liquidationPrice: liquidationPrice
760
- };
761
- };
762
719
  this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
763
720
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
764
721
  if (enableLogs === void 0) { enableLogs = false; }
765
722
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
766
723
  throw new Error("Delta Amounts cannot be negative.");
767
724
  }
768
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
769
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
725
+ var sizeDeltaUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
726
+ var entryDeltaOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeDeltaUsd);
727
+ var entryAvgOraclePrice = entryDeltaOraclePrice;
728
+ var lockAndUnsettledFeeUsd = constants_1.BN_ZERO;
770
729
  if (positionAccount === null) {
771
730
  var data = __assign({}, types_1.DEFAULT_POSITION);
772
731
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
773
- var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
774
- positionAccount.sizeUsd = sizeUsd_2;
732
+ entryAvgOraclePrice = entryDeltaOraclePrice;
733
+ var sizeUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
734
+ positionAccount.sizeUsd = sizeUsd;
775
735
  positionAccount.sizeDecimals = targetCustodyAccount.decimals;
776
736
  positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
777
737
  positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
@@ -784,16 +744,17 @@ var PerpetualsClient = (function () {
784
744
  confidence: constants_1.BN_ZERO,
785
745
  timestamp: constants_1.BN_ZERO
786
746
  });
787
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
788
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
789
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
747
+ lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
748
+ entryAvgOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryDeltaOraclePrice.price, sizeDeltaAmount);
749
+ var sizeDeltaUsd_1 = entryAvgOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
750
+ positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd_1);
790
751
  }
791
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
752
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
753
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
754
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
792
755
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
793
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
794
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
795
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
796
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
756
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryAvgOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
757
+ var sizeAmountUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
797
758
  var feeUsd = constants_1.BN_ZERO;
798
759
  var feeAmount = constants_1.BN_ZERO;
799
760
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -802,11 +763,11 @@ var PerpetualsClient = (function () {
802
763
  }
803
764
  else {
804
765
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
805
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
766
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
806
767
  if (discountBps.gt(constants_1.BN_ZERO)) {
807
768
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
808
769
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
809
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
770
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
810
771
  }
811
772
  else {
812
773
  feeUsdAfterDiscount = feeUsd;
@@ -826,7 +787,8 @@ var PerpetualsClient = (function () {
826
787
  console.log("volitlity fee zero:", "divergenceBps", divergenceBps.toString(), "maxDivergenceBps", targetCustodyAccount.oracle.maxDivergenceBps.toString());
827
788
  }
828
789
  return {
829
- entryOraclePrice: entryOraclePrice,
790
+ entryDeltaOraclePrice: entryDeltaOraclePrice,
791
+ entryAvgOraclePrice: entryAvgOraclePrice,
830
792
  feeUsd: feeUsd,
831
793
  feeAmount: feeAmount,
832
794
  vbFeeUsd: vbFeeUsd,
@@ -865,25 +827,26 @@ var PerpetualsClient = (function () {
865
827
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
866
828
  throw new Error("Delta Amounts cannot be negative ");
867
829
  }
868
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
869
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
870
830
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
871
831
  throw new Error("cannot remove/close more than collateral/Size");
872
832
  }
873
833
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
874
834
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
875
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
835
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
836
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
837
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
838
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
876
839
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
877
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
840
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
878
841
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
879
842
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
880
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
843
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
881
844
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
882
845
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
883
846
  if (discountBps.gt(constants_1.BN_ZERO)) {
884
847
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
885
848
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
886
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
849
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
887
850
  }
888
851
  else {
889
852
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -893,7 +856,7 @@ var PerpetualsClient = (function () {
893
856
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
894
857
  });
895
858
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
896
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
859
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
897
860
  return {
898
861
  exitOraclePrice: exitOraclePrice,
899
862
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -906,13 +869,11 @@ var PerpetualsClient = (function () {
906
869
  };
907
870
  };
908
871
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
909
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
910
- ||
911
- sizeUsd.isZero()) {
872
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
912
873
  return constants_1.BN_ZERO;
913
874
  }
914
875
  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)))))
915
- .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
876
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
916
877
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
917
878
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
918
879
  return finalSpread;
@@ -927,21 +888,11 @@ var PerpetualsClient = (function () {
927
888
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
928
889
  return exitOraclePrice;
929
890
  };
930
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
931
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
932
- if ((0, types_1.isVariant)(side, 'long')) {
933
- return minPrice;
934
- }
935
- else {
936
- return maxPrice;
937
- }
938
- };
939
891
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
940
892
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
941
893
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
942
894
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
943
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
944
- .multipliedBy(collateralTokenMinPriceUi);
895
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
945
896
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
946
897
  if (!discountBps.isZero()) {
947
898
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -949,20 +900,20 @@ var PerpetualsClient = (function () {
949
900
  }
950
901
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
951
902
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
952
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
953
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
903
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
904
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
954
905
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
955
906
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
956
907
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
957
908
  };
958
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
909
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
959
910
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
960
911
  var finalCollateralAmount = constants_1.BN_ZERO;
961
912
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
962
913
  finalCollateralAmount = amountIn;
963
914
  }
964
915
  else {
965
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
916
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
966
917
  finalCollateralAmount = swapAmountOut;
967
918
  }
968
919
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -976,8 +927,8 @@ var PerpetualsClient = (function () {
976
927
  }
977
928
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
978
929
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
979
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
980
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
930
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
931
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
981
932
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
982
933
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
983
934
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -1000,7 +951,7 @@ var PerpetualsClient = (function () {
1000
951
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1001
952
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
1002
953
  };
1003
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
954
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1004
955
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1005
956
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1006
957
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -1017,11 +968,11 @@ var PerpetualsClient = (function () {
1017
968
  collateralInInputToken = collateralAmountWithFee;
1018
969
  }
1019
970
  else {
1020
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
971
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1021
972
  }
1022
973
  return collateralInInputToken;
1023
974
  };
1024
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
975
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1025
976
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1026
977
  if (debugLogs === void 0) { debugLogs = false; }
1027
978
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -1043,10 +994,9 @@ var PerpetualsClient = (function () {
1043
994
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1044
995
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1045
996
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1046
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1047
997
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1048
- positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1049
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
998
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
999
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1050
1000
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
1051
1001
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1052
1002
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1056,30 +1006,37 @@ var PerpetualsClient = (function () {
1056
1006
  }
1057
1007
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1058
1008
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1059
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1009
+ var currentCollateralUsd = positionDelta.collateralUsd;
1060
1010
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1061
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1062
- var closeAmount, feesAmount;
1011
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1063
1012
  if (debugLogs) {
1064
1013
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1065
1014
  }
1015
+ var closeAmountUsd, feesAmountUsd;
1066
1016
  if (assetsUsd.gte(liabilityUsd)) {
1067
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1068
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1017
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1018
+ feesAmountUsd = totalFeesUsd;
1069
1019
  }
1070
1020
  else {
1071
- closeAmount = constants_1.BN_ZERO;
1072
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1021
+ closeAmountUsd = constants_1.BN_ZERO;
1022
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1023
+ }
1024
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1025
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1026
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1027
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
1028
+ }
1029
+ else {
1030
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1073
1031
  }
1074
1032
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1075
1033
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1076
1034
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1077
- newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1078
1035
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1079
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1036
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1080
1037
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1081
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1082
1038
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1039
+ newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
1083
1040
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1084
1041
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1085
1042
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1093,29 +1050,30 @@ var PerpetualsClient = (function () {
1093
1050
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1094
1051
  if (keepLevSame) {
1095
1052
  var collateralAmountReceived = closeAmount;
1096
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1097
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1053
+ var collateralAmountReceivedUsd = closeAmountUsd;
1054
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1098
1055
  if (debugLogs) {
1099
1056
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1100
1057
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1101
1058
  }
1102
- if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1059
+ if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1103
1060
  collateralAmountReceived = constants_1.BN_ZERO;
1104
- collateralAmountRecievedUsd = constants_1.BN_ZERO;
1061
+ collateralAmountReceivedUsd = constants_1.BN_ZERO;
1105
1062
  }
1106
- else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1063
+ else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1107
1064
  if (debugLogs) {
1108
1065
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1109
1066
  }
1110
1067
  collateralAmountReceived = maxWithdrawableAmount;
1111
- collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1068
+ collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1112
1069
  }
1113
1070
  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 });
1114
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1115
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1071
+ newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1072
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1073
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1116
1074
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1117
1075
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1118
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1076
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1119
1077
  return {
1120
1078
  newSizeUsd: newPosition.sizeUsd,
1121
1079
  feeUsd: feeUsd,
@@ -1123,8 +1081,9 @@ var PerpetualsClient = (function () {
1123
1081
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1124
1082
  newLev: newLev,
1125
1083
  liquidationPrice: finalLiquidationPrice,
1126
- collateralAmountRecieved: collateralAmountReceived,
1127
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1084
+ collateralAmountReceived: collateralAmountReceived,
1085
+ collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1086
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1128
1087
  newPnl: finalPnlUsd
1129
1088
  };
1130
1089
  }
@@ -1132,8 +1091,7 @@ var PerpetualsClient = (function () {
1132
1091
  throw "only same leverage is supported for now";
1133
1092
  }
1134
1093
  };
1135
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1136
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1094
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1137
1095
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1138
1096
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1139
1097
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1142,61 +1100,87 @@ var PerpetualsClient = (function () {
1142
1100
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1143
1101
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1144
1102
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1145
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1103
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1146
1104
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1147
1105
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1148
1106
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1149
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1150
1107
  var availableInitMarginUsd = constants_1.BN_ZERO;
1151
- if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1152
- availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1108
+ if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1109
+ availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1153
1110
  }
1154
1111
  else {
1155
1112
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1156
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1113
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1157
1114
  }
1158
1115
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1159
1116
  if (maxRemovableCollateralUsd.isNeg()) {
1160
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1117
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1161
1118
  }
1162
1119
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1163
- var diff = constants_1.BN_ZERO;
1120
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1121
+ var diffUsd = constants_1.BN_ZERO;
1164
1122
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1165
1123
  var isDegenMode = positionAccount.isDegenMode();
1166
1124
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1167
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1168
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1125
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1126
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1169
1127
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1170
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1128
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1171
1129
  }
1172
1130
  else {
1173
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1131
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1132
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1174
1133
  }
1175
1134
  }
1176
1135
  else {
1177
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1136
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1137
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1178
1138
  }
1179
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1139
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1180
1140
  };
1181
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1141
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1182
1142
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1183
1143
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1184
- var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1185
1144
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1186
1145
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1187
1146
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1188
1147
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1189
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1190
- var closeAmount, feesAmount;
1148
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1149
+ var closeAmountUsd, feesAmountUsd;
1191
1150
  if (assetsUsd.gt(liabilityUsd)) {
1192
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1193
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1151
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1152
+ feesAmountUsd = totalFeesUsd;
1194
1153
  }
1195
1154
  else {
1196
- closeAmount = constants_1.BN_ZERO;
1197
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1155
+ closeAmountUsd = constants_1.BN_ZERO;
1156
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1198
1157
  }
1199
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1158
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1159
+ };
1160
+ this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1161
+ if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1162
+ if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1163
+ throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1164
+ }
1165
+ var rawMinInitLev = positionAccount.isDegenMode()
1166
+ ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1167
+ : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1168
+ var MIN_INIT_LEVERAGE = rawMinInitLev
1169
+ .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1170
+ .div(new anchor_1.BN(100));
1171
+ var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1172
+ .muln(constants_1.BPS_POWER)
1173
+ .div(MIN_INIT_LEVERAGE);
1174
+ var currentCollateralUsd = positionAccount.collateralUsd;
1175
+ var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1176
+ ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1177
+ : constants_1.BN_ZERO;
1178
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1179
+ var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1180
+ return {
1181
+ maxAddableAmount: maxAddableAmount,
1182
+ maxAddableAmountUsd: maxAddableCollateralUsd,
1183
+ };
1200
1184
  };
1201
1185
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1202
1186
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1209,34 +1193,37 @@ var PerpetualsClient = (function () {
1209
1193
  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)));
1210
1194
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1211
1195
  console.log("THIS cannot happen but still");
1212
- return constants_1.BN_ZERO;
1196
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1213
1197
  }
1214
1198
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1215
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1199
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1216
1200
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1217
1201
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1218
1202
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1219
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1203
+ var currentCollateralUsd = positionAccount.collateralUsd;
1220
1204
  var availableInitMarginUsd = constants_1.BN_ZERO;
1221
1205
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1222
1206
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1223
1207
  }
1224
1208
  else {
1225
1209
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1226
- return constants_1.BN_ZERO;
1210
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1227
1211
  }
1228
1212
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1229
1213
  if (maxRemovableCollateralUsd.isNeg()) {
1230
- return constants_1.BN_ZERO;
1214
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1231
1215
  }
1232
1216
  var maxWithdrawableAmount;
1217
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1233
1218
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1234
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1219
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1220
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1235
1221
  }
1236
1222
  else {
1237
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1223
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1224
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1238
1225
  }
1239
- return maxWithdrawableAmount;
1226
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1240
1227
  };
1241
1228
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1242
1229
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1274,12 +1261,12 @@ var PerpetualsClient = (function () {
1274
1261
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1275
1262
  var lockFeeUsd = constants_1.BN_ZERO;
1276
1263
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1277
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1264
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1278
1265
  }
1279
1266
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1280
1267
  return lockFeeUsd;
1281
1268
  };
1282
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1269
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1283
1270
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1284
1271
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1285
1272
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1287,193 +1274,144 @@ var PerpetualsClient = (function () {
1287
1274
  else {
1288
1275
  maxPayOffBpsNew = maxPayOffBps;
1289
1276
  }
1290
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1277
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1291
1278
  return lockedUsd;
1292
1279
  };
1293
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1280
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1294
1281
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1295
1282
  price: constants_1.BN_ZERO,
1296
1283
  exponent: constants_1.BN_ZERO,
1297
1284
  confidence: constants_1.BN_ZERO,
1298
1285
  timestamp: constants_1.BN_ZERO
1299
1286
  });
1300
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1301
- return zeroOraclePrice;
1302
- }
1303
1287
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1304
1288
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1305
1289
  }
1306
1290
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1307
1291
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1308
1292
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1309
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1310
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1311
1293
  var liquidationPrice;
1312
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1313
- var newCollateralAmount = void 0;
1314
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1315
- newCollateralAmount = collateralAmount;
1294
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1295
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1296
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1297
+ .div(positionAccount.sizeAmount),
1298
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1299
+ confidence: constants_1.BN_ZERO,
1300
+ timestamp: constants_1.BN_ZERO
1301
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1302
+ if ((0, types_1.isVariant)(side, 'long')) {
1303
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1304
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1305
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1306
+ confidence: constants_1.BN_ZERO,
1307
+ timestamp: constants_1.BN_ZERO
1308
+ });
1316
1309
  }
1317
1310
  else {
1318
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1319
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1320
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1311
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1312
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1313
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1314
+ confidence: constants_1.BN_ZERO,
1315
+ timestamp: constants_1.BN_ZERO
1316
+ });
1321
1317
  }
1322
- var lp = OraclePrice_1.OraclePrice.from({
1323
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1324
- .div(sizeAmount.add(newCollateralAmount)),
1318
+ }
1319
+ else {
1320
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1321
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1322
+ .div(positionAccount.sizeAmount),
1325
1323
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1326
1324
  confidence: constants_1.BN_ZERO,
1327
1325
  timestamp: constants_1.BN_ZERO
1328
- });
1329
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1330
- }
1331
- else {
1332
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1333
- if (assetsUsd.gte(liablitiesUsd)) {
1334
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1335
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1336
- .div(positionAccount.sizeAmount),
1337
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1326
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1327
+ if ((0, types_1.isVariant)(side, 'long')) {
1328
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1329
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1330
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1338
1331
  confidence: constants_1.BN_ZERO,
1339
1332
  timestamp: constants_1.BN_ZERO
1340
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1341
- if ((0, types_1.isVariant)(side, 'long')) {
1342
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1343
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1344
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1345
- confidence: constants_1.BN_ZERO,
1346
- timestamp: constants_1.BN_ZERO
1347
- });
1348
- }
1349
- else {
1350
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1351
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1352
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1353
- confidence: constants_1.BN_ZERO,
1354
- timestamp: constants_1.BN_ZERO
1355
- });
1356
- }
1333
+ });
1357
1334
  }
1358
1335
  else {
1359
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1360
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1361
- .div(positionAccount.sizeAmount),
1362
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1336
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1337
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1338
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1363
1339
  confidence: constants_1.BN_ZERO,
1364
1340
  timestamp: constants_1.BN_ZERO
1365
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1366
- if ((0, types_1.isVariant)(side, 'long')) {
1367
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1368
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1369
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1370
- confidence: constants_1.BN_ZERO,
1371
- timestamp: constants_1.BN_ZERO
1372
- });
1373
- }
1374
- else {
1375
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1376
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1377
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1378
- confidence: constants_1.BN_ZERO,
1379
- timestamp: constants_1.BN_ZERO
1380
- });
1381
- }
1341
+ });
1382
1342
  }
1383
1343
  }
1384
1344
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1385
1345
  };
1386
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1346
+ this.getLiquidationPriceSync = function (collateralUsd, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1347
+ var newPositionAccount = positionAccount.clone();
1348
+ newPositionAccount.collateralUsd = collateralUsd;
1349
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1350
+ };
1351
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1387
1352
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1388
1353
  price: constants_1.BN_ZERO,
1389
1354
  exponent: constants_1.BN_ZERO,
1390
1355
  confidence: constants_1.BN_ZERO,
1391
1356
  timestamp: constants_1.BN_ZERO
1392
1357
  });
1393
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1394
- return zeroOraclePrice;
1395
- }
1396
1358
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1397
1359
  var unsettledLossUsd = exitFeeUsd;
1398
1360
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1399
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1400
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1401
1361
  var liquidationPrice;
1402
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1403
- var newCollateralAmount = void 0;
1404
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1405
- newCollateralAmount = collateralAmount;
1362
+ if (collateralUsd.gte(liablitiesUsd)) {
1363
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1364
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1365
+ .div(sizeAmount),
1366
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1367
+ confidence: constants_1.BN_ZERO,
1368
+ timestamp: constants_1.BN_ZERO
1369
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1370
+ if ((0, types_1.isVariant)(side, 'long')) {
1371
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1373
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1374
+ confidence: constants_1.BN_ZERO,
1375
+ timestamp: constants_1.BN_ZERO
1376
+ });
1406
1377
  }
1407
1378
  else {
1408
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1409
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1410
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1379
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1380
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1381
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1382
+ confidence: constants_1.BN_ZERO,
1383
+ timestamp: constants_1.BN_ZERO
1384
+ });
1411
1385
  }
1412
- var lp = OraclePrice_1.OraclePrice.from({
1413
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1414
- .div(sizeAmount.add(newCollateralAmount)),
1386
+ }
1387
+ else {
1388
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1389
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1390
+ .div(sizeAmount),
1415
1391
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1416
1392
  confidence: constants_1.BN_ZERO,
1417
1393
  timestamp: constants_1.BN_ZERO
1418
- });
1419
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1420
- }
1421
- else {
1422
- var assetsUsd = collateralUsd;
1423
- if (assetsUsd.gte(liablitiesUsd)) {
1424
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1425
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1426
- .div(sizeAmount),
1427
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1394
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1395
+ if ((0, types_1.isVariant)(side, 'long')) {
1396
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1397
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1398
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1428
1399
  confidence: constants_1.BN_ZERO,
1429
1400
  timestamp: constants_1.BN_ZERO
1430
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1431
- if ((0, types_1.isVariant)(side, 'long')) {
1432
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1433
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1434
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1435
- confidence: constants_1.BN_ZERO,
1436
- timestamp: constants_1.BN_ZERO
1437
- });
1438
- }
1439
- else {
1440
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1441
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1442
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1443
- confidence: constants_1.BN_ZERO,
1444
- timestamp: constants_1.BN_ZERO
1445
- });
1446
- }
1401
+ });
1447
1402
  }
1448
1403
  else {
1449
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1450
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1451
- .div(sizeAmount),
1452
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1404
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1405
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1406
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1453
1407
  confidence: constants_1.BN_ZERO,
1454
1408
  timestamp: constants_1.BN_ZERO
1455
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1456
- if ((0, types_1.isVariant)(side, 'long')) {
1457
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1458
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1459
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1460
- confidence: constants_1.BN_ZERO,
1461
- timestamp: constants_1.BN_ZERO
1462
- });
1463
- }
1464
- else {
1465
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1466
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1467
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1468
- confidence: constants_1.BN_ZERO,
1469
- timestamp: constants_1.BN_ZERO
1470
- });
1471
- }
1409
+ });
1472
1410
  }
1473
1411
  }
1474
1412
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1475
1413
  };
1476
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1414
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1477
1415
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1478
1416
  price: constants_1.BN_ZERO,
1479
1417
  exponent: constants_1.BN_ZERO,
@@ -1484,7 +1422,7 @@ var PerpetualsClient = (function () {
1484
1422
  return zeroOraclePrice;
1485
1423
  }
1486
1424
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1487
- price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1425
+ price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1488
1426
  .div(positionAccount.sizeAmount),
1489
1427
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1490
1428
  confidence: constants_1.BN_ZERO,
@@ -1512,7 +1450,7 @@ var PerpetualsClient = (function () {
1512
1450
  }
1513
1451
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1514
1452
  };
1515
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1453
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1516
1454
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1517
1455
  throw new Error("Delta Amounts cannot be negative.");
1518
1456
  }
@@ -1542,10 +1480,9 @@ var PerpetualsClient = (function () {
1542
1480
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1543
1481
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1544
1482
  positionAccount.market = marketAccountPk;
1545
- positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1546
- positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1547
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1548
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1483
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1484
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1485
+ positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1549
1486
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1550
1487
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1551
1488
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1617,6 +1554,9 @@ var PerpetualsClient = (function () {
1617
1554
  });
1618
1555
  };
1619
1556
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1557
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1558
+ };
1559
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1620
1560
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1621
1561
  return {
1622
1562
  profitUsd: constants_1.BN_ZERO,
@@ -1624,9 +1564,8 @@ var PerpetualsClient = (function () {
1624
1564
  };
1625
1565
  }
1626
1566
  var side = poolConfig.getMarketConfigByPk(positionAccount.market).side;
1627
- var sizeUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1567
+ var sizeUsd = positionAccount.sizeUsd;
1628
1568
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, sizeUsd);
1629
- var collateralMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1630
1569
  var priceDiffProfit, priceDiffLoss;
1631
1570
  var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1632
1571
  price: positionAccount.entryPrice.price,
@@ -1675,7 +1614,7 @@ var PerpetualsClient = (function () {
1675
1614
  }
1676
1615
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1677
1616
  return {
1678
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1617
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1679
1618
  lossUsd: constants_1.BN_ZERO,
1680
1619
  };
1681
1620
  }
@@ -1766,6 +1705,9 @@ var PerpetualsClient = (function () {
1766
1705
  }
1767
1706
  };
1768
1707
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1708
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1709
+ };
1710
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1769
1711
  var poolAmountUsd = constants_1.BN_ZERO;
1770
1712
  for (var index = 0; index < custodies.length; index++) {
1771
1713
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1778,6 +1720,7 @@ var PerpetualsClient = (function () {
1778
1720
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1779
1721
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1780
1722
  }
1723
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1781
1724
  if (aumCalcMode === "includePnl") {
1782
1725
  var poolEquityUsd = poolAmountUsd;
1783
1726
  for (var index = 0; index < markets.length; index++) {
@@ -1787,11 +1730,12 @@ var PerpetualsClient = (function () {
1787
1730
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1788
1731
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1789
1732
  var position = markets[index].getCollectivePosition();
1733
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1790
1734
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1791
1735
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1792
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1793
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1794
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1736
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1737
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1738
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1795
1739
  }
1796
1740
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1797
1741
  }
@@ -1799,14 +1743,6 @@ var PerpetualsClient = (function () {
1799
1743
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1800
1744
  }
1801
1745
  };
1802
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1803
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1804
- return { discountBn: constants_1.BN_ZERO };
1805
- }
1806
- else {
1807
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1808
- }
1809
- };
1810
1746
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1811
1747
  if (tokenStakeAccount.level === 0) {
1812
1748
  return { discountBn: constants_1.BN_ZERO };
@@ -2069,6 +2005,14 @@ var PerpetualsClient = (function () {
2069
2005
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2070
2006
  case 4:
2071
2007
  result = _f.sent();
2008
+ if (result.value.err) {
2009
+ console.error('error Simulation failed:::', result);
2010
+ return [2, {
2011
+ amount: undefined,
2012
+ fee: undefined,
2013
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2014
+ }];
2015
+ }
2072
2016
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2073
2017
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2074
2018
  return [2, {
@@ -2149,9 +2093,11 @@ var PerpetualsClient = (function () {
2149
2093
  result = _f.sent();
2150
2094
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2151
2095
  if (result.value.err) {
2096
+ console.error('error Simulation failed:', result);
2152
2097
  return [2, {
2153
- amount: new anchor_1.BN(0),
2154
- fee: new anchor_1.BN(0),
2098
+ amount: undefined,
2099
+ fee: undefined,
2100
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2155
2101
  }];
2156
2102
  }
2157
2103
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2563,11 +2509,10 @@ var PerpetualsClient = (function () {
2563
2509
  for (var _i = 8; _i < arguments.length; _i++) {
2564
2510
  args_1[_i - 8] = arguments[_i];
2565
2511
  }
2566
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2512
+ 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) {
2567
2513
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2568
2514
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2569
2515
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2570
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2571
2516
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2572
2517
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2573
2518
  return __generator(this, function (_c) {
@@ -2660,7 +2605,7 @@ var PerpetualsClient = (function () {
2660
2605
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2661
2606
  fundingMint: collateralCustodyConfig.mintKey
2662
2607
  })
2663
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2608
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2664
2609
  .instruction()];
2665
2610
  case 7:
2666
2611
  instruction = _c.sent();
@@ -2678,11 +2623,10 @@ var PerpetualsClient = (function () {
2678
2623
  for (var _i = 6; _i < arguments.length; _i++) {
2679
2624
  args_1[_i - 6] = arguments[_i];
2680
2625
  }
2681
- return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2626
+ 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) {
2682
2627
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2683
2628
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2684
2629
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2685
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2686
2630
  if (createUserATA === void 0) { createUserATA = true; }
2687
2631
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2688
2632
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2761,7 +2705,7 @@ var PerpetualsClient = (function () {
2761
2705
  collateralMint: collateralCustodyConfig.mintKey,
2762
2706
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2763
2707
  })
2764
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2708
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2765
2709
  .instruction()];
2766
2710
  case 6:
2767
2711
  instruction = _b.sent();
@@ -2783,16 +2727,15 @@ var PerpetualsClient = (function () {
2783
2727
  });
2784
2728
  });
2785
2729
  };
2786
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2730
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2787
2731
  var args_1 = [];
2788
- for (var _i = 10; _i < arguments.length; _i++) {
2789
- args_1[_i - 10] = arguments[_i];
2732
+ for (var _i = 9; _i < arguments.length; _i++) {
2733
+ args_1[_i - 9] = arguments[_i];
2790
2734
  }
2791
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, minCollateralAmountOut, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2792
- var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, rebateMintAccount, inx, err_3;
2735
+ 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) {
2736
+ 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;
2793
2737
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2794
2738
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2795
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2796
2739
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2797
2740
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2798
2741
  return __generator(this, function (_c) {
@@ -2886,18 +2829,10 @@ var PerpetualsClient = (function () {
2886
2829
  }
2887
2830
  _c.label = 10;
2888
2831
  case 10:
2889
- rebateMintAccount = {
2890
- pubkey: collateralCustodyConfig.mintKey,
2891
- isSigner: false,
2892
- isWritable: false
2893
- };
2894
- _c.label = 11;
2895
- case 11:
2896
- _c.trys.push([11, 13, , 14]);
2832
+ _c.trys.push([10, 12, , 13]);
2897
2833
  return [4, this.program.methods
2898
2834
  .swapAndOpen({
2899
2835
  amountIn: amountIn,
2900
- minCollateralAmountOut: minCollateralAmountOut,
2901
2836
  priceWithSlippage: priceWithSlippage,
2902
2837
  sizeAmount: sizeAmount,
2903
2838
  privilege: privilege
@@ -2928,17 +2863,17 @@ var PerpetualsClient = (function () {
2928
2863
  collateralMint: collateralCustodyConfig.mintKey,
2929
2864
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2930
2865
  })
2931
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2866
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2932
2867
  .instruction()];
2933
- case 12:
2868
+ case 11:
2934
2869
  inx = _c.sent();
2935
2870
  instructions.push(inx);
2936
- return [3, 14];
2937
- case 13:
2871
+ return [3, 13];
2872
+ case 12:
2938
2873
  err_3 = _c.sent();
2939
2874
  console.error("perpClient SwapAndOpen error:: ", err_3);
2940
2875
  throw err_3;
2941
- case 14: return [2, {
2876
+ case 13: return [2, {
2942
2877
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2943
2878
  additionalSigners: additionalSigners
2944
2879
  }];
@@ -2946,16 +2881,15 @@ var PerpetualsClient = (function () {
2946
2881
  });
2947
2882
  });
2948
2883
  };
2949
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2884
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2950
2885
  var args_1 = [];
2951
- for (var _i = 8; _i < arguments.length; _i++) {
2952
- args_1[_i - 8] = arguments[_i];
2886
+ for (var _i = 7; _i < arguments.length; _i++) {
2887
+ args_1[_i - 7] = arguments[_i];
2953
2888
  }
2954
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, minSwapAmountOut, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, ephemeralSignerPubkey) {
2955
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2889
+ 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) {
2890
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2956
2891
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2957
2892
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2958
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2959
2893
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2960
2894
  return __generator(this, function (_a) {
2961
2895
  switch (_a.label) {
@@ -3021,18 +2955,12 @@ var PerpetualsClient = (function () {
3021
2955
  if (!(_a.sent())) {
3022
2956
  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));
3023
2957
  }
3024
- rebateMintAccount = {
3025
- pubkey: collateralCustodyConfig.mintKey,
3026
- isSigner: false,
3027
- isWritable: false
3028
- };
3029
2958
  _a.label = 5;
3030
2959
  case 5:
3031
2960
  _a.trys.push([5, 7, , 8]);
3032
2961
  return [4, this.program.methods
3033
2962
  .closeAndSwap({
3034
2963
  priceWithSlippage: priceWithSlippage,
3035
- minSwapAmountOut: minSwapAmountOut,
3036
2964
  privilege: privilege
3037
2965
  })
3038
2966
  .accounts({
@@ -3061,7 +2989,7 @@ var PerpetualsClient = (function () {
3061
2989
  collateralMint: collateralCustodyConfig.mintKey,
3062
2990
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
3063
2991
  })
3064
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2992
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3065
2993
  .instruction()];
3066
2994
  case 6:
3067
2995
  inx = _a.sent();
@@ -3182,12 +3110,12 @@ var PerpetualsClient = (function () {
3182
3110
  });
3183
3111
  });
3184
3112
  };
3185
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3113
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3186
3114
  var args_1 = [];
3187
- for (var _i = 8; _i < arguments.length; _i++) {
3188
- args_1[_i - 8] = arguments[_i];
3115
+ for (var _i = 7; _i < arguments.length; _i++) {
3116
+ args_1[_i - 7] = arguments[_i];
3189
3117
  }
3190
- return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, minCollateralAmountOut, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3118
+ 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) {
3191
3119
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3192
3120
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3193
3121
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3266,7 +3194,6 @@ var PerpetualsClient = (function () {
3266
3194
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3267
3195
  return [4, this.program.methods.swapAndAddCollateral({
3268
3196
  amountIn: amountIn,
3269
- minCollateralAmountOut: minCollateralAmountOut,
3270
3197
  }).accounts({
3271
3198
  owner: publicKey,
3272
3199
  feePayer: publicKey,
@@ -3302,12 +3229,12 @@ var PerpetualsClient = (function () {
3302
3229
  });
3303
3230
  });
3304
3231
  };
3305
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3232
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3306
3233
  var args_1 = [];
3307
3234
  for (var _i = 6; _i < arguments.length; _i++) {
3308
3235
  args_1[_i - 6] = arguments[_i];
3309
3236
  }
3310
- return __awaiter(_this, __spreadArray([collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralWithFee, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3237
+ 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) {
3311
3238
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3312
3239
  if (createUserATA === void 0) { createUserATA = true; }
3313
3240
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3371,7 +3298,7 @@ var PerpetualsClient = (function () {
3371
3298
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3372
3299
  return [4, this.program.methods
3373
3300
  .removeCollateral({
3374
- collateralDelta: collateralWithFee,
3301
+ collateralDeltaUsd: collateralDeltaUsd,
3375
3302
  })
3376
3303
  .accounts({
3377
3304
  owner: publicKey,
@@ -3413,12 +3340,12 @@ var PerpetualsClient = (function () {
3413
3340
  });
3414
3341
  });
3415
3342
  };
3416
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3343
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3417
3344
  var args_1 = [];
3418
- for (var _i = 7; _i < arguments.length; _i++) {
3419
- args_1[_i - 7] = arguments[_i];
3345
+ for (var _i = 6; _i < arguments.length; _i++) {
3346
+ args_1[_i - 6] = arguments[_i];
3420
3347
  }
3421
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, minSwapAmountOut, collateralDelta, side, poolConfig, ephemeralSignerPubkey) {
3348
+ 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) {
3422
3349
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3423
3350
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3424
3351
  return __generator(this, function (_a) {
@@ -3475,8 +3402,7 @@ var PerpetualsClient = (function () {
3475
3402
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3476
3403
  return [4, this.program.methods
3477
3404
  .removeCollateralAndSwap({
3478
- collateralDelta: collateralDelta,
3479
- minSwapAmountOut: minSwapAmountOut,
3405
+ collateralDeltaUsd: collateralDeltaUsd,
3480
3406
  })
3481
3407
  .accounts({
3482
3408
  owner: publicKey,
@@ -3521,11 +3447,10 @@ var PerpetualsClient = (function () {
3521
3447
  for (var _i = 8; _i < arguments.length; _i++) {
3522
3448
  args_1[_i - 8] = arguments[_i];
3523
3449
  }
3524
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3450
+ 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) {
3525
3451
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3526
3452
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3527
3453
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3528
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3529
3454
  return __generator(this, function (_a) {
3530
3455
  switch (_a.label) {
3531
3456
  case 0:
@@ -3568,7 +3493,7 @@ var PerpetualsClient = (function () {
3568
3493
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3569
3494
  collateralMint: collateralCustodyConfig.mintKey
3570
3495
  })
3571
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3496
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3572
3497
  .instruction()];
3573
3498
  case 1:
3574
3499
  instruction = _a.sent();
@@ -3586,11 +3511,10 @@ var PerpetualsClient = (function () {
3586
3511
  for (var _i = 8; _i < arguments.length; _i++) {
3587
3512
  args_1[_i - 8] = arguments[_i];
3588
3513
  }
3589
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3514
+ 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) {
3590
3515
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3591
3516
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3592
3517
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3593
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3594
3518
  return __generator(this, function (_a) {
3595
3519
  switch (_a.label) {
3596
3520
  case 0:
@@ -3633,7 +3557,7 @@ var PerpetualsClient = (function () {
3633
3557
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3634
3558
  collateralMint: collateralCustodyConfig.mintKey
3635
3559
  })
3636
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3560
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3637
3561
  .instruction()];
3638
3562
  case 1:
3639
3563
  instruction = _a.sent();
@@ -4592,11 +4516,13 @@ var PerpetualsClient = (function () {
4592
4516
  for (var _i = 5; _i < arguments.length; _i++) {
4593
4517
  args_1[_i - 5] = arguments[_i];
4594
4518
  }
4595
- return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey) {
4596
- var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_16;
4519
+ return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4520
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, heapSizeIx, addCompoundingLiquidity, err_16;
4597
4521
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4598
4522
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4599
4523
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4524
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4525
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4600
4526
  return __generator(this, function (_f) {
4601
4527
  switch (_f.label) {
4602
4528
  case 0:
@@ -4687,6 +4613,15 @@ var PerpetualsClient = (function () {
4687
4613
  _f.label = 7;
4688
4614
  case 7:
4689
4615
  _f.trys.push([7, 9, , 10]);
4616
+ if (enableHeapSizeIx) {
4617
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4618
+ bytes: 64 * 1024,
4619
+ });
4620
+ if (enableDebugLogs) {
4621
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4622
+ }
4623
+ preInstructions.push(heapSizeIx);
4624
+ }
4690
4625
  return [4, this.program.methods
4691
4626
  .addCompoundingLiquidity({
4692
4627
  amountIn: amountIn,
@@ -4737,11 +4672,13 @@ var PerpetualsClient = (function () {
4737
4672
  for (var _i = 5; _i < arguments.length; _i++) {
4738
4673
  args_1[_i - 5] = arguments[_i];
4739
4674
  }
4740
- 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) {
4741
- 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;
4675
+ return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4676
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, heapSizeIx, removeCompoundingLiquidity, err_17;
4742
4677
  if (createUserATA === void 0) { createUserATA = true; }
4743
4678
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4744
4679
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4680
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4681
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4745
4682
  return __generator(this, function (_f) {
4746
4683
  switch (_f.label) {
4747
4684
  case 0:
@@ -4816,6 +4753,15 @@ var PerpetualsClient = (function () {
4816
4753
  _f.label = 5;
4817
4754
  case 5:
4818
4755
  _f.trys.push([5, 7, , 8]);
4756
+ if (enableHeapSizeIx) {
4757
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4758
+ bytes: 64 * 1024,
4759
+ });
4760
+ if (enableDebugLogs) {
4761
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4762
+ }
4763
+ preInstructions.push(heapSizeIx);
4764
+ }
4819
4765
  return [4, this.program.methods
4820
4766
  .removeCompoundingLiquidity({
4821
4767
  compoundingAmountIn: compoundingAmountIn,
@@ -5498,179 +5444,18 @@ var PerpetualsClient = (function () {
5498
5444
  });
5499
5445
  });
5500
5446
  };
5501
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5502
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_28;
5503
- return __generator(this, function (_a) {
5504
- switch (_a.label) {
5505
- case 0:
5506
- publicKey = this.provider.wallet.publicKey;
5507
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5508
- instructions = [];
5509
- additionalSigners = [];
5510
- _a.label = 1;
5511
- case 1:
5512
- _a.trys.push([1, 3, , 4]);
5513
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5514
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5515
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5516
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5517
- return [4, this.programFbnftReward.methods
5518
- .initRewardVault({
5519
- nftCount: nftCount
5520
- })
5521
- .accounts({
5522
- admin: publicKey,
5523
- transferAuthority: nftTransferAuthority,
5524
- rewardVault: rewardVault,
5525
- rewardMint: rewardCustodyMint,
5526
- rewardTokenAccount: rewardTokenAccount,
5527
- collectionMint: collectionMint,
5528
- programData: fbNftProgramData,
5529
- systemProgram: web3_js_1.SystemProgram.programId,
5530
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5531
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5532
- })
5533
- .instruction()];
5534
- case 2:
5535
- initRewardVault = _a.sent();
5536
- instructions.push(initRewardVault);
5537
- return [3, 4];
5538
- case 3:
5539
- err_28 = _a.sent();
5540
- console.log("perpClient InitRewardVault error:: ", err_28);
5541
- throw err_28;
5542
- case 4: return [2, {
5543
- instructions: __spreadArray([], instructions, true),
5544
- additionalSigners: additionalSigners
5545
- }];
5546
- }
5547
- });
5548
- }); };
5549
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5550
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_29;
5551
- return __generator(this, function (_a) {
5552
- switch (_a.label) {
5553
- case 0:
5554
- publicKey = this.provider.wallet.publicKey;
5555
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5556
- instructions = [];
5557
- additionalSigners = [];
5558
- _a.label = 1;
5559
- case 1:
5560
- _a.trys.push([1, 3, , 4]);
5561
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5562
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5563
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5564
- return [4, this.programFbnftReward.methods
5565
- .distributeRewards({
5566
- rewardAmount: rewardAmount
5567
- })
5568
- .accounts({
5569
- admin: publicKey,
5570
- fundingAccount: fundingAccount,
5571
- rewardVault: rewardVault,
5572
- rewardTokenAccount: rewardTokenAccount,
5573
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5574
- })
5575
- .instruction()];
5576
- case 2:
5577
- distributeReward = _a.sent();
5578
- instructions.push(distributeReward);
5579
- return [3, 4];
5580
- case 3:
5581
- err_29 = _a.sent();
5582
- console.log("perpClient distributeReward error:: ", err_29);
5583
- throw err_29;
5584
- case 4: return [2, {
5585
- instructions: __spreadArray([], instructions, true),
5586
- additionalSigners: additionalSigners
5587
- }];
5588
- }
5589
- });
5590
- }); };
5591
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5447
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5592
5448
  var args_1 = [];
5593
5449
  for (var _i = 3; _i < arguments.length; _i++) {
5594
5450
  args_1[_i - 3] = arguments[_i];
5595
5451
  }
5596
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5597
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_30;
5452
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5453
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5598
5454
  if (createUserATA === void 0) { createUserATA = true; }
5599
5455
  return __generator(this, function (_b) {
5600
5456
  switch (_b.label) {
5601
5457
  case 0:
5602
5458
  publicKey = this.provider.wallet.publicKey;
5603
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5604
- rewardCustodyMint = rewardToken.mintKey;
5605
- instructions = [];
5606
- additionalSigners = [];
5607
- _b.label = 1;
5608
- case 1:
5609
- _b.trys.push([1, 5, , 6]);
5610
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5611
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5612
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5613
- _a = createUserATA;
5614
- if (!_a) return [3, 3];
5615
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5616
- case 2:
5617
- _a = !(_b.sent());
5618
- _b.label = 3;
5619
- case 3:
5620
- if (_a) {
5621
- instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
5622
- }
5623
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5624
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5625
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5626
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5627
- return [4, this.programFbnftReward.methods
5628
- .collectReward()
5629
- .accounts({
5630
- owner: publicKey,
5631
- feePayer: publicKey,
5632
- nftMint: nftMint,
5633
- nftTokenAccount: nftTokenAccount,
5634
- metadataAccount: metadataAccount,
5635
- receivingAccount: receivingTokenAccount,
5636
- rewardRecord: rewardRecord,
5637
- rewardVault: rewardVault,
5638
- rewardTokenAccount: rewardTokenAccount,
5639
- transferAuthority: nftTransferAuthority,
5640
- systemProgram: web3_js_1.SystemProgram.programId,
5641
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5642
- })
5643
- .instruction()];
5644
- case 4:
5645
- collectNftReward = _b.sent();
5646
- instructions.push(collectNftReward);
5647
- return [3, 6];
5648
- case 5:
5649
- err_30 = _b.sent();
5650
- throw err_30;
5651
- case 6: return [2, {
5652
- instructions: __spreadArray([], instructions, true),
5653
- additionalSigners: additionalSigners
5654
- }];
5655
- }
5656
- });
5657
- });
5658
- };
5659
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5660
- var args_1 = [];
5661
- for (var _i = 2; _i < arguments.length; _i++) {
5662
- args_1[_i - 2] = arguments[_i];
5663
- }
5664
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5665
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_31;
5666
- if (createUserATA === void 0) { createUserATA = true; }
5667
- return __generator(this, function (_b) {
5668
- switch (_b.label) {
5669
- case 0:
5670
- publicKey = this.provider.wallet.publicKey;
5671
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5672
- rewardCustodyMint = rewardToken.mintKey;
5673
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5674
5459
  preInstructions = [];
5675
5460
  instructions = [];
5676
5461
  postInstructions = [];
@@ -5678,59 +5463,43 @@ var PerpetualsClient = (function () {
5678
5463
  _b.label = 1;
5679
5464
  case 1:
5680
5465
  _b.trys.push([1, 5, , 6]);
5681
- pool = poolConfig.poolAddress;
5682
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5683
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5466
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5467
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5468
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5684
5469
  _a = createUserATA;
5685
5470
  if (!_a) return [3, 3];
5686
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5471
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5687
5472
  case 2:
5688
5473
  _a = !(_b.sent());
5689
5474
  _b.label = 3;
5690
5475
  case 3:
5691
5476
  if (_a) {
5692
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5477
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5693
5478
  }
5694
- tradingAccount = [];
5695
- if (nftTradingAccount) {
5696
- tradingAccount.push({
5697
- pubkey: nftTradingAccount,
5698
- isSigner: false,
5699
- isWritable: true,
5700
- });
5701
- }
5702
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5703
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5704
- return [4, this.programPerpComposability.methods
5705
- .collectAndDistributeFee()
5479
+ return [4, this.program.methods
5480
+ .collectRebate()
5706
5481
  .accounts({
5707
- perpProgram: this.programId,
5708
- owner: publicKey,
5709
- receivingTokenAccount: receivingTokenAccount,
5710
- transferAuthority: poolConfig.transferAuthority,
5482
+ owner: owner,
5483
+ receivingTokenAccount: userTokenAccount,
5711
5484
  perpetuals: this.perpetuals.publicKey,
5712
- pool: pool,
5713
- feeCustody: rewardCustodyConfig.custodyAccount,
5714
- flpStakeAccount: flpStakeAccount,
5715
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5716
- systemProgram: web3_js_1.SystemProgram.programId,
5485
+ transferAuthority: poolConfig.transferAuthority,
5486
+ rebateVault: poolConfig.rebateVault,
5487
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5488
+ tokenStakeAccount: tokenStakeAccount,
5717
5489
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5718
5490
  eventAuthority: this.eventAuthority.publicKey,
5719
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5720
- fbnftRewardsProgram: this.programFbnftReward.programId,
5721
- rewardVault: rewardVault,
5722
- rewardTokenAccount: rewardTokenAccount
5491
+ program: this.programId,
5492
+ receivingTokenMint: rebateMint,
5723
5493
  })
5724
- .remainingAccounts(tradingAccount)
5725
5494
  .instruction()];
5726
5495
  case 4:
5727
- withdrawStakeInstruction = _b.sent();
5728
- instructions.push(withdrawStakeInstruction);
5496
+ collectRebateInstruction = _b.sent();
5497
+ instructions.push(collectRebateInstruction);
5729
5498
  return [3, 6];
5730
5499
  case 5:
5731
- err_31 = _b.sent();
5732
- console.log("perpClient withdrawStake error:: ", err_31);
5733
- throw err_31;
5500
+ err_28 = _b.sent();
5501
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5502
+ throw err_28;
5734
5503
  case 6: return [2, {
5735
5504
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5736
5505
  additionalSigners: additionalSigners
@@ -5739,13 +5508,60 @@ var PerpetualsClient = (function () {
5739
5508
  });
5740
5509
  });
5741
5510
  };
5511
+ this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5512
+ var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5513
+ return __generator(this, function (_a) {
5514
+ switch (_a.label) {
5515
+ case 0:
5516
+ preInstructions = [];
5517
+ instructions = [];
5518
+ postInstructions = [];
5519
+ additionalSigners = [];
5520
+ _a.label = 1;
5521
+ case 1:
5522
+ _a.trys.push([1, 3, , 4]);
5523
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5524
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5525
+ return [4, this.program.methods
5526
+ .settleRebates()
5527
+ .accounts({
5528
+ transferAuthority: poolConfig.transferAuthority,
5529
+ perpetuals: this.perpetuals.publicKey,
5530
+ pool: poolConfig.poolAddress,
5531
+ rewardCustody: rewardCustody.custodyAccount,
5532
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5533
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5534
+ rebateVault: poolConfig.rebateVault,
5535
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5536
+ tokenMint: rebateMint,
5537
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5538
+ eventAuthority: this.eventAuthority.publicKey,
5539
+ program: this.programId,
5540
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5541
+ })
5542
+ .instruction()];
5543
+ case 2:
5544
+ settleRebatesInstruction = _a.sent();
5545
+ instructions.push(settleRebatesInstruction);
5546
+ return [3, 4];
5547
+ case 3:
5548
+ err_29 = _a.sent();
5549
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5550
+ throw err_29;
5551
+ case 4: return [2, {
5552
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5553
+ additionalSigners: additionalSigners
5554
+ }];
5555
+ }
5556
+ });
5557
+ }); };
5742
5558
  this.placeLimitOrder = function (targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1) {
5743
5559
  var args_1 = [];
5744
5560
  for (var _i = 11; _i < arguments.length; _i++) {
5745
5561
  args_1[_i - 11] = arguments[_i];
5746
5562
  }
5747
5563
  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) {
5748
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_32;
5564
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5749
5565
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5750
5566
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5751
5567
  return __generator(this, function (_c) {
@@ -5851,9 +5667,9 @@ var PerpetualsClient = (function () {
5851
5667
  instructions.push(placeLimitOrder);
5852
5668
  return [3, 10];
5853
5669
  case 9:
5854
- err_32 = _c.sent();
5855
- console.log("perpClient placeLimitOrder error:: ", err_32);
5856
- throw err_32;
5670
+ err_30 = _c.sent();
5671
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5672
+ throw err_30;
5857
5673
  case 10: return [2, {
5858
5674
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5859
5675
  additionalSigners: additionalSigners
@@ -5868,7 +5684,7 @@ var PerpetualsClient = (function () {
5868
5684
  args_1[_i - 11] = arguments[_i];
5869
5685
  }
5870
5686
  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) {
5871
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_33;
5687
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
5872
5688
  if (createUserATA === void 0) { createUserATA = true; }
5873
5689
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5874
5690
  return __generator(this, function (_b) {
@@ -5959,9 +5775,9 @@ var PerpetualsClient = (function () {
5959
5775
  instructions.push(editLimitOrder);
5960
5776
  return [3, 8];
5961
5777
  case 7:
5962
- err_33 = _b.sent();
5963
- console.log("perpClient editLimitOrder error:: ", err_33);
5964
- throw err_33;
5778
+ err_31 = _b.sent();
5779
+ console.log("perpClient editLimitOrder error:: ", err_31);
5780
+ throw err_31;
5965
5781
  case 8: return [2, {
5966
5782
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5967
5783
  additionalSigners: additionalSigners
@@ -5975,11 +5791,10 @@ var PerpetualsClient = (function () {
5975
5791
  for (var _i = 7; _i < arguments.length; _i++) {
5976
5792
  args_1[_i - 7] = arguments[_i];
5977
5793
  }
5978
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
5979
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_34;
5794
+ 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) {
5795
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
5980
5796
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
5981
5797
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
5982
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
5983
5798
  return __generator(this, function (_a) {
5984
5799
  switch (_a.label) {
5985
5800
  case 0:
@@ -6022,16 +5837,16 @@ var PerpetualsClient = (function () {
6022
5837
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6023
5838
  collateralMint: collateralCustodyConfig.mintKey,
6024
5839
  })
6025
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5840
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6026
5841
  .instruction()];
6027
5842
  case 2:
6028
5843
  executeLimitOrder = _a.sent();
6029
5844
  instructions.push(executeLimitOrder);
6030
5845
  return [3, 4];
6031
5846
  case 3:
6032
- err_34 = _a.sent();
6033
- console.log("perpClient executeLimitOrder error:: ", err_34);
6034
- throw err_34;
5847
+ err_32 = _a.sent();
5848
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5849
+ throw err_32;
6035
5850
  case 4: return [2, {
6036
5851
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6037
5852
  additionalSigners: additionalSigners
@@ -6045,11 +5860,10 @@ var PerpetualsClient = (function () {
6045
5860
  for (var _i = 8; _i < arguments.length; _i++) {
6046
5861
  args_1[_i - 8] = arguments[_i];
6047
5862
  }
6048
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, reserveSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, reserveSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6049
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_35;
5863
+ 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) {
5864
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6050
5865
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6051
5866
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6052
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6053
5867
  return __generator(this, function (_a) {
6054
5868
  switch (_a.label) {
6055
5869
  case 0:
@@ -6095,16 +5909,16 @@ var PerpetualsClient = (function () {
6095
5909
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6096
5910
  collateralMint: collateralCustodyConfig.mintKey,
6097
5911
  })
6098
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5912
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6099
5913
  .instruction()];
6100
5914
  case 2:
6101
5915
  executeLimitWithSwap = _a.sent();
6102
5916
  instructions.push(executeLimitWithSwap);
6103
5917
  return [3, 4];
6104
5918
  case 3:
6105
- err_35 = _a.sent();
6106
- console.log("perpClient executeLimitWithSwap error:: ", err_35);
6107
- throw err_35;
5919
+ err_33 = _a.sent();
5920
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5921
+ throw err_33;
6108
5922
  case 4: return [2, {
6109
5923
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6110
5924
  additionalSigners: additionalSigners
@@ -6114,7 +5928,7 @@ var PerpetualsClient = (function () {
6114
5928
  });
6115
5929
  };
6116
5930
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6117
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_36;
5931
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6118
5932
  return __generator(this, function (_a) {
6119
5933
  switch (_a.label) {
6120
5934
  case 0:
@@ -6162,9 +5976,9 @@ var PerpetualsClient = (function () {
6162
5976
  instructions.push(placeTriggerOrder);
6163
5977
  return [3, 4];
6164
5978
  case 3:
6165
- err_36 = _a.sent();
6166
- console.log("perpClient placeTriggerOrder error:: ", err_36);
6167
- throw err_36;
5979
+ err_34 = _a.sent();
5980
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5981
+ throw err_34;
6168
5982
  case 4: return [2, {
6169
5983
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6170
5984
  additionalSigners: additionalSigners
@@ -6173,7 +5987,7 @@ var PerpetualsClient = (function () {
6173
5987
  });
6174
5988
  }); };
6175
5989
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6176
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_37;
5990
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6177
5991
  return __generator(this, function (_a) {
6178
5992
  switch (_a.label) {
6179
5993
  case 0:
@@ -6220,9 +6034,9 @@ var PerpetualsClient = (function () {
6220
6034
  instructions.push(editTriggerOrder);
6221
6035
  return [3, 4];
6222
6036
  case 3:
6223
- err_37 = _a.sent();
6224
- console.log("perpClient editTriggerOrder error:: ", err_37);
6225
- throw err_37;
6037
+ err_35 = _a.sent();
6038
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6039
+ throw err_35;
6226
6040
  case 4: return [2, {
6227
6041
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6228
6042
  additionalSigners: additionalSigners
@@ -6231,7 +6045,7 @@ var PerpetualsClient = (function () {
6231
6045
  });
6232
6046
  }); };
6233
6047
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6234
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_38;
6048
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6235
6049
  return __generator(this, function (_a) {
6236
6050
  switch (_a.label) {
6237
6051
  case 0:
@@ -6264,9 +6078,9 @@ var PerpetualsClient = (function () {
6264
6078
  instructions.push(cancelTriggerOrder);
6265
6079
  return [3, 4];
6266
6080
  case 3:
6267
- err_38 = _a.sent();
6268
- console.log("perpClient cancelTriggerOrder error:: ", err_38);
6269
- throw err_38;
6081
+ err_36 = _a.sent();
6082
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6083
+ throw err_36;
6270
6084
  case 4: return [2, {
6271
6085
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6272
6086
  additionalSigners: additionalSigners
@@ -6275,7 +6089,7 @@ var PerpetualsClient = (function () {
6275
6089
  });
6276
6090
  }); };
6277
6091
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6278
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_39;
6092
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6279
6093
  return __generator(this, function (_a) {
6280
6094
  switch (_a.label) {
6281
6095
  case 0:
@@ -6306,9 +6120,9 @@ var PerpetualsClient = (function () {
6306
6120
  instructions.push(cancelAllTriggerOrders);
6307
6121
  return [3, 4];
6308
6122
  case 3:
6309
- err_39 = _a.sent();
6310
- console.log("perpClient cancelAllTriggerOrders error:: ", err_39);
6311
- throw err_39;
6123
+ err_37 = _a.sent();
6124
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6125
+ throw err_37;
6312
6126
  case 4: return [2, {
6313
6127
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6314
6128
  additionalSigners: additionalSigners
@@ -6321,13 +6135,12 @@ var PerpetualsClient = (function () {
6321
6135
  for (var _i = 9; _i < arguments.length; _i++) {
6322
6136
  args_1[_i - 9] = arguments[_i];
6323
6137
  }
6324
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, receivingSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, receivingSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6325
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_40;
6138
+ 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) {
6139
+ 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;
6326
6140
  if (createUserATA === void 0) { createUserATA = true; }
6327
6141
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6328
6142
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6329
6143
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6330
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6331
6144
  return __generator(this, function (_e) {
6332
6145
  switch (_e.label) {
6333
6146
  case 0:
@@ -6422,16 +6235,16 @@ var PerpetualsClient = (function () {
6422
6235
  collateralMint: collateralCustodyConfig.mintKey,
6423
6236
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6424
6237
  })
6425
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6238
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6426
6239
  .instruction()];
6427
6240
  case 8:
6428
6241
  executeTriggerWithSwap = _e.sent();
6429
6242
  instructions.push(executeTriggerWithSwap);
6430
6243
  return [3, 10];
6431
6244
  case 9:
6432
- err_40 = _e.sent();
6433
- console.log("perpClient executeTriggerWithSwap error:: ", err_40);
6434
- throw err_40;
6245
+ err_38 = _e.sent();
6246
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6247
+ throw err_38;
6435
6248
  case 10: return [2, {
6436
6249
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6437
6250
  additionalSigners: additionalSigners
@@ -6445,13 +6258,12 @@ var PerpetualsClient = (function () {
6445
6258
  for (var _i = 8; _i < arguments.length; _i++) {
6446
6259
  args_1[_i - 8] = arguments[_i];
6447
6260
  }
6448
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6449
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_41;
6261
+ 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) {
6262
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6450
6263
  if (createUserATA === void 0) { createUserATA = true; }
6451
6264
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6452
6265
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6453
6266
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6454
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6455
6267
  return __generator(this, function (_b) {
6456
6268
  switch (_b.label) {
6457
6269
  case 0:
@@ -6511,16 +6323,16 @@ var PerpetualsClient = (function () {
6511
6323
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6512
6324
  receivingMint: collateralCustodyConfig.mintKey
6513
6325
  })
6514
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6326
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6515
6327
  .instruction()];
6516
6328
  case 6:
6517
6329
  executeTriggerOrder = _b.sent();
6518
6330
  instructions.push(executeTriggerOrder);
6519
6331
  return [3, 8];
6520
6332
  case 7:
6521
- err_41 = _b.sent();
6522
- console.log("perpClient executeTriggerOrder error:: ", err_41);
6523
- throw err_41;
6333
+ err_39 = _b.sent();
6334
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6335
+ throw err_39;
6524
6336
  case 8: return [2, {
6525
6337
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6526
6338
  additionalSigners: additionalSigners
@@ -6535,7 +6347,7 @@ var PerpetualsClient = (function () {
6535
6347
  args_1[_i - 5] = arguments[_i];
6536
6348
  }
6537
6349
  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) {
6538
- var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_42;
6350
+ 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;
6539
6351
  if (useFeesPool === void 0) { useFeesPool = false; }
6540
6352
  if (createUserATA === void 0) { createUserATA = true; }
6541
6353
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6740,9 +6552,9 @@ var PerpetualsClient = (function () {
6740
6552
  }
6741
6553
  return [3, 20];
6742
6554
  case 19:
6743
- err_42 = _g.sent();
6744
- console.error("perpClient Swap error:: ", err_42);
6745
- throw err_42;
6555
+ err_40 = _g.sent();
6556
+ console.error("perpClient Swap error:: ", err_40);
6557
+ throw err_40;
6746
6558
  case 20: return [2, {
6747
6559
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6748
6560
  additionalSigners: additionalSigners
@@ -6752,7 +6564,7 @@ var PerpetualsClient = (function () {
6752
6564
  });
6753
6565
  };
6754
6566
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6755
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_43;
6567
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6756
6568
  return __generator(this, function (_b) {
6757
6569
  switch (_b.label) {
6758
6570
  case 0:
@@ -6797,11 +6609,7 @@ var PerpetualsClient = (function () {
6797
6609
  rewardCustody: rewardCustody.custodyAccount,
6798
6610
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
6799
6611
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
6800
- custody: custody.custodyAccount,
6801
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
6802
- custodyTokenAccount: custody.tokenAccount,
6803
6612
  eventAuthority: this.eventAuthority.publicKey,
6804
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
6805
6613
  program: this.programId,
6806
6614
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
6807
6615
  })
@@ -6812,9 +6620,9 @@ var PerpetualsClient = (function () {
6812
6620
  instructions.push(inx);
6813
6621
  return [3, 4];
6814
6622
  case 3:
6815
- err_43 = _b.sent();
6816
- console.error("perpClient Swap error:: ", err_43);
6817
- throw err_43;
6623
+ err_41 = _b.sent();
6624
+ console.error("perpClient Swap error:: ", err_41);
6625
+ throw err_41;
6818
6626
  case 4: return [2, {
6819
6627
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6820
6628
  additionalSigners: additionalSigners
@@ -6823,7 +6631,7 @@ var PerpetualsClient = (function () {
6823
6631
  });
6824
6632
  }); };
6825
6633
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6826
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_44;
6634
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
6827
6635
  return __generator(this, function (_d) {
6828
6636
  switch (_d.label) {
6829
6637
  case 0:
@@ -6871,9 +6679,9 @@ var PerpetualsClient = (function () {
6871
6679
  instructions.push(setLpTokenPriceInstruction);
6872
6680
  return [3, 4];
6873
6681
  case 3:
6874
- err_44 = _d.sent();
6875
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_44);
6876
- throw err_44;
6682
+ err_42 = _d.sent();
6683
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6684
+ throw err_42;
6877
6685
  case 4: return [2, {
6878
6686
  instructions: __spreadArray([], instructions, true),
6879
6687
  additionalSigners: additionalSigners
@@ -6921,7 +6729,7 @@ var PerpetualsClient = (function () {
6921
6729
  });
6922
6730
  }); };
6923
6731
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
6924
- var adminMetas, _i, admins_2, admin, err_45;
6732
+ var adminMetas, _i, admins_2, admin, err_43;
6925
6733
  return __generator(this, function (_a) {
6926
6734
  switch (_a.label) {
6927
6735
  case 0:
@@ -6951,16 +6759,16 @@ var PerpetualsClient = (function () {
6951
6759
  _a.sent();
6952
6760
  return [3, 4];
6953
6761
  case 3:
6954
- err_45 = _a.sent();
6762
+ err_43 = _a.sent();
6955
6763
  if (this.printErrors) {
6956
- console.error("setAdminSigners err:", err_45);
6764
+ console.error("setAdminSigners err:", err_43);
6957
6765
  }
6958
- throw err_45;
6766
+ throw err_43;
6959
6767
  case 4: return [2];
6960
6768
  }
6961
6769
  });
6962
6770
  }); };
6963
- this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor) { return __awaiter(_this, void 0, void 0, function () {
6771
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor, stakingFeeBoostBps, minLpPriceUsd, maxLpPriceUsd, thresholdUsd) { return __awaiter(_this, void 0, void 0, function () {
6964
6772
  return __generator(this, function (_a) {
6965
6773
  switch (_a.label) {
6966
6774
  case 0: return [4, this.program.methods
@@ -6972,7 +6780,11 @@ var PerpetualsClient = (function () {
6972
6780
  metadataTitle: metadataTitle,
6973
6781
  metadataUri: metadataUri,
6974
6782
  stakingFeeShareBps: stakingFeeShareBps,
6975
- vpVolumeFactor: vpVolumeFactor
6783
+ vpVolumeFactor: vpVolumeFactor,
6784
+ stakingFeeBoostBps: stakingFeeBoostBps,
6785
+ minLpPriceUsd: minLpPriceUsd,
6786
+ maxLpPriceUsd: maxLpPriceUsd,
6787
+ thresholdUsd: thresholdUsd
6976
6788
  })
6977
6789
  .accounts({
6978
6790
  admin: this.provider.wallet.publicKey,
@@ -7020,7 +6832,7 @@ var PerpetualsClient = (function () {
7020
6832
  }
7021
6833
  });
7022
6834
  }); };
7023
- this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
6835
+ this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment, rewardThreshold, minReserveUsd, limitPriceBufferBps) { return __awaiter(_this, void 0, void 0, function () {
7024
6836
  var trx_id, error_3;
7025
6837
  return __generator(this, function (_a) {
7026
6838
  switch (_a.label) {
@@ -7038,6 +6850,9 @@ var PerpetualsClient = (function () {
7038
6850
  fees: fees,
7039
6851
  borrowRate: borrowRate,
7040
6852
  ratios: ratios,
6853
+ rewardThreshold: rewardThreshold,
6854
+ minReserveUsd: minReserveUsd,
6855
+ limitPriceBufferBps: limitPriceBufferBps
7041
6856
  })
7042
6857
  .accounts({
7043
6858
  admin: this.admin,
@@ -7144,7 +6959,7 @@ var PerpetualsClient = (function () {
7144
6959
  });
7145
6960
  }); };
7146
6961
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7147
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_46;
6962
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7148
6963
  return __generator(this, function (_a) {
7149
6964
  switch (_a.label) {
7150
6965
  case 0:
@@ -7177,9 +6992,9 @@ var PerpetualsClient = (function () {
7177
6992
  instructions.push(withdrawFeesIx);
7178
6993
  return [3, 5];
7179
6994
  case 4:
7180
- err_46 = _a.sent();
7181
- console.log("perpClient setPool error:: ", err_46);
7182
- throw err_46;
6995
+ err_44 = _a.sent();
6996
+ console.log("perpClient setPool error:: ", err_44);
6997
+ throw err_44;
7183
6998
  case 5: return [2, {
7184
6999
  instructions: __spreadArray([], instructions, true),
7185
7000
  additionalSigners: additionalSigners
@@ -7188,7 +7003,7 @@ var PerpetualsClient = (function () {
7188
7003
  });
7189
7004
  }); };
7190
7005
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7191
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_47;
7006
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7192
7007
  return __generator(this, function (_a) {
7193
7008
  switch (_a.label) {
7194
7009
  case 0:
@@ -7222,9 +7037,9 @@ var PerpetualsClient = (function () {
7222
7037
  instructions.push(moveProtocolFeesIx);
7223
7038
  return [3, 4];
7224
7039
  case 3:
7225
- err_47 = _a.sent();
7226
- console.log("perpClient setPool error:: ", err_47);
7227
- throw err_47;
7040
+ err_45 = _a.sent();
7041
+ console.log("perpClient setPool error:: ", err_45);
7042
+ throw err_45;
7228
7043
  case 4: return [2, {
7229
7044
  instructions: __spreadArray([], instructions, true),
7230
7045
  additionalSigners: additionalSigners
@@ -7233,7 +7048,7 @@ var PerpetualsClient = (function () {
7233
7048
  });
7234
7049
  }); };
7235
7050
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7236
- var publicKey, setProtocolFeeShareBpsIx, err_48;
7051
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7237
7052
  return __generator(this, function (_a) {
7238
7053
  switch (_a.label) {
7239
7054
  case 0:
@@ -7253,15 +7068,15 @@ var PerpetualsClient = (function () {
7253
7068
  setProtocolFeeShareBpsIx = _a.sent();
7254
7069
  return [2, setProtocolFeeShareBpsIx];
7255
7070
  case 2:
7256
- err_48 = _a.sent();
7257
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_48);
7258
- throw err_48;
7071
+ err_46 = _a.sent();
7072
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7073
+ throw err_46;
7259
7074
  case 3: return [2];
7260
7075
  }
7261
7076
  });
7262
7077
  }); };
7263
7078
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7264
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_49;
7079
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7265
7080
  return __generator(this, function (_a) {
7266
7081
  switch (_a.label) {
7267
7082
  case 0:
@@ -7288,9 +7103,9 @@ var PerpetualsClient = (function () {
7288
7103
  instructions.push(setPermissionsInstruction);
7289
7104
  return [3, 4];
7290
7105
  case 3:
7291
- err_49 = _a.sent();
7292
- console.log("perpClient setPool error:: ", err_49);
7293
- throw err_49;
7106
+ err_47 = _a.sent();
7107
+ console.log("perpClient setPool error:: ", err_47);
7108
+ throw err_47;
7294
7109
  case 4: return [2, {
7295
7110
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7296
7111
  additionalSigners: additionalSigners
@@ -7299,7 +7114,7 @@ var PerpetualsClient = (function () {
7299
7114
  });
7300
7115
  }); };
7301
7116
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7302
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_50;
7117
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7303
7118
  var _f;
7304
7119
  return __generator(this, function (_g) {
7305
7120
  switch (_g.label) {
@@ -7360,9 +7175,9 @@ var PerpetualsClient = (function () {
7360
7175
  instructions.push(reimburse);
7361
7176
  return [3, 5];
7362
7177
  case 4:
7363
- err_50 = _g.sent();
7364
- console.log("perpClient setPool error:: ", err_50);
7365
- throw err_50;
7178
+ err_48 = _g.sent();
7179
+ console.log("perpClient setPool error:: ", err_48);
7180
+ throw err_48;
7366
7181
  case 5: return [2, {
7367
7182
  instructions: __spreadArray([], instructions, true),
7368
7183
  additionalSigners: additionalSigners
@@ -7371,7 +7186,7 @@ var PerpetualsClient = (function () {
7371
7186
  });
7372
7187
  }); };
7373
7188
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7374
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_51;
7189
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7375
7190
  return __generator(this, function (_a) {
7376
7191
  switch (_a.label) {
7377
7192
  case 0:
@@ -7405,9 +7220,9 @@ var PerpetualsClient = (function () {
7405
7220
  instructions.push(setInternalOraclePrice);
7406
7221
  return [3, 4];
7407
7222
  case 3:
7408
- err_51 = _a.sent();
7409
- console.log("perpClient setInternalOracleAccount error:: ", err_51);
7410
- throw err_51;
7223
+ err_49 = _a.sent();
7224
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7225
+ throw err_49;
7411
7226
  case 4: return [2, {
7412
7227
  instructions: __spreadArray([], instructions, true),
7413
7228
  additionalSigners: additionalSigners
@@ -7416,7 +7231,7 @@ var PerpetualsClient = (function () {
7416
7231
  });
7417
7232
  }); };
7418
7233
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7419
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_52;
7234
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7420
7235
  return __generator(this, function (_a) {
7421
7236
  switch (_a.label) {
7422
7237
  case 0:
@@ -7462,9 +7277,9 @@ var PerpetualsClient = (function () {
7462
7277
  instructions.push(setInternalOraclePrice);
7463
7278
  return [3, 4];
7464
7279
  case 3:
7465
- err_52 = _a.sent();
7466
- console.log("perpClient setInternalOracleAccount error:: ", err_52);
7467
- throw err_52;
7280
+ err_50 = _a.sent();
7281
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7282
+ throw err_50;
7468
7283
  case 4: return [2, {
7469
7284
  instructions: __spreadArray([], instructions, true),
7470
7285
  additionalSigners: additionalSigners
@@ -7473,7 +7288,7 @@ var PerpetualsClient = (function () {
7473
7288
  });
7474
7289
  }); };
7475
7290
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7476
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_53;
7291
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7477
7292
  return __generator(this, function (_a) {
7478
7293
  switch (_a.label) {
7479
7294
  case 0:
@@ -7513,9 +7328,9 @@ var PerpetualsClient = (function () {
7513
7328
  instructions.push(setInternalOraclePrice);
7514
7329
  return [3, 4];
7515
7330
  case 3:
7516
- err_53 = _a.sent();
7517
- console.log("perpClient setInternalOracleAccount error:: ", err_53);
7518
- throw err_53;
7331
+ err_51 = _a.sent();
7332
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7333
+ throw err_51;
7519
7334
  case 4: return [2, {
7520
7335
  instructions: __spreadArray([], instructions, true),
7521
7336
  additionalSigners: additionalSigners
@@ -7524,7 +7339,7 @@ var PerpetualsClient = (function () {
7524
7339
  });
7525
7340
  }); };
7526
7341
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7527
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_54;
7342
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7528
7343
  return __generator(this, function (_a) {
7529
7344
  switch (_a.label) {
7530
7345
  case 0:
@@ -7562,8 +7377,8 @@ var PerpetualsClient = (function () {
7562
7377
  instructions.push(renameFlp);
7563
7378
  return [3, 4];
7564
7379
  case 3:
7565
- err_54 = _a.sent();
7566
- console.log("perpClient renameFlp error:: ", err_54);
7380
+ err_52 = _a.sent();
7381
+ console.log("perpClient renameFlp error:: ", err_52);
7567
7382
  return [3, 4];
7568
7383
  case 4: return [2, {
7569
7384
  instructions: __spreadArray([], instructions, true),
@@ -7573,7 +7388,7 @@ var PerpetualsClient = (function () {
7573
7388
  });
7574
7389
  }); };
7575
7390
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7576
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_55;
7391
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7577
7392
  return __generator(this, function (_a) {
7578
7393
  switch (_a.label) {
7579
7394
  case 0:
@@ -7611,9 +7426,9 @@ var PerpetualsClient = (function () {
7611
7426
  instructions.push(initStakeInstruction);
7612
7427
  return [3, 4];
7613
7428
  case 3:
7614
- err_55 = _a.sent();
7615
- console.log("perpClient InitStaking error:: ", err_55);
7616
- throw err_55;
7429
+ err_53 = _a.sent();
7430
+ console.log("perpClient InitStaking error:: ", err_53);
7431
+ throw err_53;
7617
7432
  case 4: return [2, {
7618
7433
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7619
7434
  additionalSigners: additionalSigners
@@ -7622,7 +7437,7 @@ var PerpetualsClient = (function () {
7622
7437
  });
7623
7438
  }); };
7624
7439
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7625
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_56;
7440
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7626
7441
  return __generator(this, function (_a) {
7627
7442
  switch (_a.label) {
7628
7443
  case 0:
@@ -7666,9 +7481,9 @@ var PerpetualsClient = (function () {
7666
7481
  instructions.push(initCompoundingInstruction);
7667
7482
  return [3, 4];
7668
7483
  case 3:
7669
- err_56 = _a.sent();
7670
- console.log("perpClient initCompounding error:: ", err_56);
7671
- throw err_56;
7484
+ err_54 = _a.sent();
7485
+ console.log("perpClient initCompounding error:: ", err_54);
7486
+ throw err_54;
7672
7487
  case 4: return [2, {
7673
7488
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7674
7489
  additionalSigners: additionalSigners
@@ -7677,7 +7492,7 @@ var PerpetualsClient = (function () {
7677
7492
  });
7678
7493
  }); };
7679
7494
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7680
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_57;
7495
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7681
7496
  return __generator(this, function (_a) {
7682
7497
  switch (_a.label) {
7683
7498
  case 0:
@@ -7718,9 +7533,9 @@ var PerpetualsClient = (function () {
7718
7533
  instructions.push(initTokenVaultInstruction);
7719
7534
  return [3, 4];
7720
7535
  case 3:
7721
- err_57 = _a.sent();
7722
- console.log("perpClient InitTokenVaultInstruction error:: ", err_57);
7723
- throw err_57;
7536
+ err_55 = _a.sent();
7537
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7538
+ throw err_55;
7724
7539
  case 4: return [2, {
7725
7540
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7726
7541
  additionalSigners: additionalSigners
@@ -7729,7 +7544,7 @@ var PerpetualsClient = (function () {
7729
7544
  });
7730
7545
  }); };
7731
7546
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7732
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_58;
7547
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7733
7548
  return __generator(this, function (_a) {
7734
7549
  switch (_a.label) {
7735
7550
  case 0:
@@ -7760,9 +7575,9 @@ var PerpetualsClient = (function () {
7760
7575
  instructions.push(setTokenVaultConfigInstruction);
7761
7576
  return [3, 4];
7762
7577
  case 3:
7763
- err_58 = _a.sent();
7764
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_58);
7765
- throw err_58;
7578
+ err_56 = _a.sent();
7579
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7580
+ throw err_56;
7766
7581
  case 4: return [2, {
7767
7582
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7768
7583
  additionalSigners: additionalSigners
@@ -7771,7 +7586,7 @@ var PerpetualsClient = (function () {
7771
7586
  });
7772
7587
  }); };
7773
7588
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7774
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_59;
7589
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
7775
7590
  return __generator(this, function (_a) {
7776
7591
  switch (_a.label) {
7777
7592
  case 0:
@@ -7810,9 +7625,9 @@ var PerpetualsClient = (function () {
7810
7625
  instructions.push(withdrawInstantFeeInstruction);
7811
7626
  return [3, 6];
7812
7627
  case 5:
7813
- err_59 = _a.sent();
7814
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_59);
7815
- throw err_59;
7628
+ err_57 = _a.sent();
7629
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7630
+ throw err_57;
7816
7631
  case 6: return [2, {
7817
7632
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7818
7633
  additionalSigners: additionalSigners
@@ -7821,7 +7636,7 @@ var PerpetualsClient = (function () {
7821
7636
  });
7822
7637
  }); };
7823
7638
  this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7824
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_60;
7639
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7825
7640
  return __generator(this, function (_a) {
7826
7641
  switch (_a.label) {
7827
7642
  case 0:
@@ -7860,9 +7675,9 @@ var PerpetualsClient = (function () {
7860
7675
  instructions.push(withdrawUnclaimedTokensInstruction);
7861
7676
  return [3, 6];
7862
7677
  case 5:
7863
- err_60 = _a.sent();
7864
- console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_60);
7865
- throw err_60;
7678
+ err_58 = _a.sent();
7679
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7680
+ throw err_58;
7866
7681
  case 6: return [2, {
7867
7682
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7868
7683
  additionalSigners: additionalSigners
@@ -7871,7 +7686,7 @@ var PerpetualsClient = (function () {
7871
7686
  });
7872
7687
  }); };
7873
7688
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7874
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_61;
7689
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
7875
7690
  return __generator(this, function (_a) {
7876
7691
  switch (_a.label) {
7877
7692
  case 0:
@@ -7908,9 +7723,55 @@ var PerpetualsClient = (function () {
7908
7723
  instructions.push(initRevenueTokenAccountInstruction);
7909
7724
  return [3, 4];
7910
7725
  case 3:
7911
- err_61 = _a.sent();
7912
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_61);
7913
- throw err_61;
7726
+ err_59 = _a.sent();
7727
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7728
+ throw err_59;
7729
+ case 4: return [2, {
7730
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7731
+ additionalSigners: additionalSigners
7732
+ }];
7733
+ }
7734
+ });
7735
+ }); };
7736
+ this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7737
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7738
+ return __generator(this, function (_a) {
7739
+ switch (_a.label) {
7740
+ case 0:
7741
+ publicKey = this.provider.wallet.publicKey;
7742
+ preInstructions = [];
7743
+ instructions = [];
7744
+ postInstructions = [];
7745
+ additionalSigners = [];
7746
+ _a.label = 1;
7747
+ case 1:
7748
+ _a.trys.push([1, 3, , 4]);
7749
+ rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7750
+ return [4, this.program.methods
7751
+ .initRebateVault({
7752
+ allowRebatePayout: allowRebatePayout
7753
+ })
7754
+ .accounts({
7755
+ admin: publicKey,
7756
+ multisig: this.multisig.publicKey,
7757
+ transferAuthority: poolConfig.transferAuthority,
7758
+ perpetuals: this.perpetuals.publicKey,
7759
+ rebateMint: rebateCustodyMint,
7760
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
7761
+ rebateVault: poolConfig.rebateVault,
7762
+ systemProgram: web3_js_1.SystemProgram.programId,
7763
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7764
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
7765
+ })
7766
+ .instruction()];
7767
+ case 2:
7768
+ initRebateVaultInstruction = _a.sent();
7769
+ instructions.push(initRebateVaultInstruction);
7770
+ return [3, 4];
7771
+ case 3:
7772
+ err_60 = _a.sent();
7773
+ console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7774
+ throw err_60;
7914
7775
  case 4: return [2, {
7915
7776
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7916
7777
  additionalSigners: additionalSigners
@@ -7919,7 +7780,7 @@ var PerpetualsClient = (function () {
7919
7780
  });
7920
7781
  }); };
7921
7782
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7922
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_62;
7783
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
7923
7784
  return __generator(this, function (_a) {
7924
7785
  switch (_a.label) {
7925
7786
  case 0:
@@ -7958,9 +7819,9 @@ var PerpetualsClient = (function () {
7958
7819
  instructions.push(distributeTokenRewardInstruction);
7959
7820
  return [3, 4];
7960
7821
  case 3:
7961
- err_62 = _a.sent();
7962
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_62);
7963
- throw err_62;
7822
+ err_61 = _a.sent();
7823
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7824
+ throw err_61;
7964
7825
  case 4: return [2, {
7965
7826
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7966
7827
  additionalSigners: additionalSigners
@@ -7969,7 +7830,7 @@ var PerpetualsClient = (function () {
7969
7830
  });
7970
7831
  }); };
7971
7832
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
7972
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_63;
7833
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
7973
7834
  return __generator(this, function (_a) {
7974
7835
  switch (_a.label) {
7975
7836
  case 0:
@@ -7997,9 +7858,9 @@ var PerpetualsClient = (function () {
7997
7858
  instructions.push(setTokenStakeLevelInstruction);
7998
7859
  return [3, 4];
7999
7860
  case 3:
8000
- err_63 = _a.sent();
8001
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_63);
8002
- throw err_63;
7861
+ err_62 = _a.sent();
7862
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7863
+ throw err_62;
8003
7864
  case 4: return [2, {
8004
7865
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8005
7866
  additionalSigners: additionalSigners
@@ -8008,7 +7869,7 @@ var PerpetualsClient = (function () {
8008
7869
  });
8009
7870
  }); };
8010
7871
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8011
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_64;
7872
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8012
7873
  return __generator(this, function (_a) {
8013
7874
  switch (_a.label) {
8014
7875
  case 0:
@@ -8040,9 +7901,9 @@ var PerpetualsClient = (function () {
8040
7901
  instructions.push(setTokenRewardInstruction);
8041
7902
  return [3, 4];
8042
7903
  case 3:
8043
- err_64 = _a.sent();
8044
- console.log("perpClient setTokenRewardInstruction error:: ", err_64);
8045
- throw err_64;
7904
+ err_63 = _a.sent();
7905
+ console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7906
+ throw err_63;
8046
7907
  case 4: return [2, {
8047
7908
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8048
7909
  additionalSigners: additionalSigners
@@ -8051,7 +7912,7 @@ var PerpetualsClient = (function () {
8051
7912
  });
8052
7913
  }); };
8053
7914
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
8054
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_65;
7915
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8055
7916
  return __generator(this, function (_a) {
8056
7917
  switch (_a.label) {
8057
7918
  case 0:
@@ -8080,9 +7941,9 @@ var PerpetualsClient = (function () {
8080
7941
  instructions.push(resizeInternalOracleInstruction);
8081
7942
  return [3, 4];
8082
7943
  case 3:
8083
- err_65 = _a.sent();
8084
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_65);
8085
- throw err_65;
7944
+ err_64 = _a.sent();
7945
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7946
+ throw err_64;
8086
7947
  case 4: return [2, {
8087
7948
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8088
7949
  additionalSigners: additionalSigners