flash-sdk 10.3.0 → 10.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.");
@@ -638,24 +638,42 @@ var PerpetualsClient = (function () {
638
638
  var averageEntryPrice = totalValue.div(totalSize);
639
639
  return averageEntryPrice;
640
640
  };
641
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
642
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
643
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
644
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
645
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
641
+ this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
642
+ var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
643
+ var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
644
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
645
+ var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
646
+ var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
647
+ var currentMarginUsd = constants_1.BN_ZERO;
648
+ if (isInitial) {
649
+ currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
650
+ }
651
+ else {
652
+ currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
653
+ }
654
+ if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
655
+ return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
646
656
  }
647
657
  else {
648
658
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
649
659
  }
650
660
  };
651
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
661
+ this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
662
+ positionAccount = positionAccount.clone();
663
+ positionAccount.sizeUsd = finalSizeUsd;
664
+ positionAccount.sizeAmount = targetPrice.getTokenAmount(finalSizeUsd, targetCustodyAccount.decimals);
665
+ positionAccount.collateralUsd = finalCollateralUsd;
666
+ return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
667
+ };
668
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd, enableDebuglogs) {
669
+ if (enableDebuglogs === void 0) { enableDebuglogs = false; }
652
670
  var finalCollateralAmount = constants_1.BN_ZERO;
653
671
  if (!inputDeltaAmount.isZero()) {
654
672
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
655
673
  finalCollateralAmount = inputDeltaAmount;
656
674
  }
657
675
  else {
658
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
676
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
659
677
  finalCollateralAmount = swapAmountOut;
660
678
  }
661
679
  }
@@ -681,11 +699,13 @@ var PerpetualsClient = (function () {
681
699
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
682
700
  }
683
701
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
684
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
685
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
686
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
702
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals).add(positionAccount.collateralUsd);
703
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
687
704
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
688
705
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
706
+ if (enableDebuglogs) {
707
+ console.log("SDK logs : finalCollateralUsd:", finalCollateralUsd.toString(), "finalCollateralAmount:", finalCollateralAmount.toString(), "sizeAmount:", sizeAmount.toString(), "sizeAmountUsd:", sizeAmountUsd.toString(), "sizeDeltaAmount:", sizeDeltaAmount.toString(), "sizeUsd:", sizeUsd.toString(), "currentCollateralUsdIncludingPnl:", currentCollateralUsdIncludingPnl.toString(), "finalCollateralUsd :", finalCollateralUsd.toString(), "pnlUsd :", pnlUsd.toString());
708
+ }
689
709
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
690
710
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
691
711
  }
@@ -693,68 +713,6 @@ var PerpetualsClient = (function () {
693
713
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
694
714
  }
695
715
  };
696
- this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
697
- if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
698
- if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
699
- throw new Error("Delta Amounts cannot be negative.");
700
- }
701
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
702
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
703
- if (positionAccount === null) {
704
- var data = __assign({}, types_1.DEFAULT_POSITION);
705
- positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
706
- var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
707
- positionAccount.sizeUsd = sizeUsd_1;
708
- positionAccount.sizeDecimals = targetCustodyAccount.decimals;
709
- positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
710
- positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
711
- }
712
- else {
713
- positionAccount = positionAccount.clone();
714
- var positionEntryPrice = OraclePrice_1.OraclePrice.from({
715
- price: positionAccount.entryPrice.price,
716
- exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
717
- confidence: constants_1.BN_ZERO,
718
- timestamp: constants_1.BN_ZERO
719
- });
720
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
721
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
722
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
723
- }
724
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
725
- positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
726
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
727
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
728
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
729
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
730
- var feeUsd = constants_1.BN_ZERO;
731
- var feeAmount = constants_1.BN_ZERO;
732
- var feeUsdAfterDiscount = constants_1.BN_ZERO;
733
- var feeAmountAfterDiscount = constants_1.BN_ZERO;
734
- if (positionAccount !== null && sizeDeltaAmount.isZero()) {
735
- }
736
- else {
737
- feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
738
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
739
- if (discountBps.gt(constants_1.BN_ZERO)) {
740
- feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
741
- feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
742
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
- }
744
- else {
745
- feeUsdAfterDiscount = feeUsd;
746
- feeAmountAfterDiscount = feeAmount;
747
- }
748
- }
749
- return {
750
- entryOraclePrice: entryOraclePrice,
751
- feeUsd: feeUsd,
752
- feeAmount: feeAmount,
753
- feeUsdAfterDiscount: feeUsdAfterDiscount,
754
- feeAmountAfterDiscount: feeAmountAfterDiscount,
755
- liquidationPrice: liquidationPrice
756
- };
757
- };
758
716
  this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
759
717
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
760
718
  if (enableLogs === void 0) { enableLogs = false; }
@@ -766,8 +724,8 @@ var PerpetualsClient = (function () {
766
724
  if (positionAccount === null) {
767
725
  var data = __assign({}, types_1.DEFAULT_POSITION);
768
726
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
769
- var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
770
- positionAccount.sizeUsd = sizeUsd_2;
727
+ var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
728
+ positionAccount.sizeUsd = sizeUsd_1;
771
729
  positionAccount.sizeDecimals = targetCustodyAccount.decimals;
772
730
  positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
773
731
  positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
@@ -784,12 +742,13 @@ var PerpetualsClient = (function () {
784
742
  var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
785
743
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
786
744
  }
787
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
745
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
746
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
747
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
788
748
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
789
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
790
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
749
+ var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
750
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
791
751
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
792
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
793
752
  var feeUsd = constants_1.BN_ZERO;
794
753
  var feeAmount = constants_1.BN_ZERO;
795
754
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -798,11 +757,11 @@ var PerpetualsClient = (function () {
798
757
  }
799
758
  else {
800
759
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
801
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
760
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
802
761
  if (discountBps.gt(constants_1.BN_ZERO)) {
803
762
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
804
763
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
805
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
764
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
806
765
  }
807
766
  else {
808
767
  feeUsdAfterDiscount = feeUsd;
@@ -861,25 +820,26 @@ var PerpetualsClient = (function () {
861
820
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
862
821
  throw new Error("Delta Amounts cannot be negative ");
863
822
  }
864
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
865
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
866
823
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
867
824
  throw new Error("cannot remove/close more than collateral/Size");
868
825
  }
869
826
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
870
827
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
871
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
828
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
829
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
830
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
831
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
872
832
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
873
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
833
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
874
834
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
875
835
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
876
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
836
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
877
837
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
878
838
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
879
839
  if (discountBps.gt(constants_1.BN_ZERO)) {
880
840
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
881
841
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
882
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
842
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
883
843
  }
884
844
  else {
885
845
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -889,7 +849,7 @@ var PerpetualsClient = (function () {
889
849
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
890
850
  });
891
851
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
892
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
852
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
893
853
  return {
894
854
  exitOraclePrice: exitOraclePrice,
895
855
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -902,13 +862,11 @@ var PerpetualsClient = (function () {
902
862
  };
903
863
  };
904
864
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
905
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
906
- ||
907
- sizeUsd.isZero()) {
865
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
908
866
  return constants_1.BN_ZERO;
909
867
  }
910
868
  var slope = ((targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin)).mul(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))))
911
- .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
869
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
912
870
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
913
871
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
914
872
  return finalSpread;
@@ -923,21 +881,11 @@ var PerpetualsClient = (function () {
923
881
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
924
882
  return exitOraclePrice;
925
883
  };
926
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
927
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
928
- if ((0, types_1.isVariant)(side, 'long')) {
929
- return minPrice;
930
- }
931
- else {
932
- return maxPrice;
933
- }
934
- };
935
884
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
936
885
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
937
886
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
938
887
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
939
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
940
- .multipliedBy(collateralTokenMinPriceUi);
888
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
941
889
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
942
890
  if (!discountBps.isZero()) {
943
891
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -945,20 +893,20 @@ var PerpetualsClient = (function () {
945
893
  }
946
894
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
947
895
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
948
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
949
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
896
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
897
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
950
898
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
951
899
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
952
900
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
953
901
  };
954
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
902
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
955
903
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
956
904
  var finalCollateralAmount = constants_1.BN_ZERO;
957
905
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
958
906
  finalCollateralAmount = amountIn;
959
907
  }
960
908
  else {
961
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
909
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
962
910
  finalCollateralAmount = swapAmountOut;
963
911
  }
964
912
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -972,8 +920,8 @@ var PerpetualsClient = (function () {
972
920
  }
973
921
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
974
922
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
975
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
976
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
923
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
924
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
977
925
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
978
926
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
979
927
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -996,7 +944,7 @@ var PerpetualsClient = (function () {
996
944
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
997
945
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
998
946
  };
999
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
947
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1000
948
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1001
949
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1002
950
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -1013,11 +961,11 @@ var PerpetualsClient = (function () {
1013
961
  collateralInInputToken = collateralAmountWithFee;
1014
962
  }
1015
963
  else {
1016
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
964
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1017
965
  }
1018
966
  return collateralInInputToken;
1019
967
  };
1020
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
968
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1021
969
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1022
970
  if (debugLogs === void 0) { debugLogs = false; }
1023
971
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -1039,10 +987,9 @@ var PerpetualsClient = (function () {
1039
987
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1040
988
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1041
989
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1042
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1043
990
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1044
- positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1045
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
991
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
992
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1046
993
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
1047
994
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1048
995
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1052,30 +999,37 @@ var PerpetualsClient = (function () {
1052
999
  }
1053
1000
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1054
1001
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1055
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1002
+ var currentCollateralUsd = positionDelta.collateralUsd;
1056
1003
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1057
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1058
- var closeAmount, feesAmount;
1004
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1059
1005
  if (debugLogs) {
1060
1006
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1061
1007
  }
1008
+ var closeAmountUsd, feesAmountUsd;
1062
1009
  if (assetsUsd.gte(liabilityUsd)) {
1063
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1064
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1010
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1011
+ feesAmountUsd = totalFeesUsd;
1065
1012
  }
1066
1013
  else {
1067
- closeAmount = constants_1.BN_ZERO;
1068
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1014
+ closeAmountUsd = constants_1.BN_ZERO;
1015
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1016
+ }
1017
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1018
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1019
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1020
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
1021
+ }
1022
+ else {
1023
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1069
1024
  }
1070
1025
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1071
1026
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1072
1027
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1073
- newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1074
1028
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1075
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1029
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1076
1030
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1077
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1078
1031
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1032
+ newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
1079
1033
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1080
1034
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1081
1035
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1089,29 +1043,30 @@ var PerpetualsClient = (function () {
1089
1043
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1090
1044
  if (keepLevSame) {
1091
1045
  var collateralAmountReceived = closeAmount;
1092
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1093
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1046
+ var collateralAmountReceivedUsd = closeAmountUsd;
1047
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1094
1048
  if (debugLogs) {
1095
1049
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1096
1050
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1097
1051
  }
1098
- if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1052
+ if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1099
1053
  collateralAmountReceived = constants_1.BN_ZERO;
1100
- collateralAmountRecievedUsd = constants_1.BN_ZERO;
1054
+ collateralAmountReceivedUsd = constants_1.BN_ZERO;
1101
1055
  }
1102
- else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1056
+ else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1103
1057
  if (debugLogs) {
1104
1058
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1105
1059
  }
1106
1060
  collateralAmountReceived = maxWithdrawableAmount;
1107
- collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1061
+ collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1108
1062
  }
1109
1063
  var entryPrice = OraclePrice_1.OraclePrice.from({ price: newPosition.entryPrice.price, exponent: new anchor_1.BN(newPosition.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1110
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1111
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1064
+ newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1065
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1066
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1112
1067
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1113
1068
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1114
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1069
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1115
1070
  return {
1116
1071
  newSizeUsd: newPosition.sizeUsd,
1117
1072
  feeUsd: feeUsd,
@@ -1119,8 +1074,9 @@ var PerpetualsClient = (function () {
1119
1074
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1120
1075
  newLev: newLev,
1121
1076
  liquidationPrice: finalLiquidationPrice,
1122
- collateralAmountRecieved: collateralAmountReceived,
1123
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1077
+ collateralAmountReceived: collateralAmountReceived,
1078
+ collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1079
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1124
1080
  newPnl: finalPnlUsd
1125
1081
  };
1126
1082
  }
@@ -1128,8 +1084,7 @@ var PerpetualsClient = (function () {
1128
1084
  throw "only same leverage is supported for now";
1129
1085
  }
1130
1086
  };
1131
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1132
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1087
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1133
1088
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1134
1089
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1135
1090
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1138,61 +1093,87 @@ var PerpetualsClient = (function () {
1138
1093
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1139
1094
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1140
1095
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1141
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1096
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1142
1097
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1143
1098
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1144
1099
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1145
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1146
1100
  var availableInitMarginUsd = constants_1.BN_ZERO;
1147
- if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1148
- availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1101
+ if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1102
+ availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1149
1103
  }
1150
1104
  else {
1151
1105
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1152
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1106
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1153
1107
  }
1154
1108
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1155
1109
  if (maxRemovableCollateralUsd.isNeg()) {
1156
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1110
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1157
1111
  }
1158
1112
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1159
- var diff = constants_1.BN_ZERO;
1113
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1114
+ var diffUsd = constants_1.BN_ZERO;
1160
1115
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1161
1116
  var isDegenMode = positionAccount.isDegenMode();
1162
1117
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1163
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1164
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1118
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1119
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1165
1120
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1166
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1121
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1167
1122
  }
1168
1123
  else {
1169
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1124
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1125
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1170
1126
  }
1171
1127
  }
1172
1128
  else {
1173
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1129
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1130
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1174
1131
  }
1175
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1132
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1176
1133
  };
1177
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1134
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1178
1135
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1179
1136
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1180
- var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1181
1137
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1182
1138
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1183
1139
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1184
1140
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1185
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1186
- var closeAmount, feesAmount;
1141
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1142
+ var closeAmountUsd, feesAmountUsd;
1187
1143
  if (assetsUsd.gt(liabilityUsd)) {
1188
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1189
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1144
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1145
+ feesAmountUsd = totalFeesUsd;
1190
1146
  }
1191
1147
  else {
1192
- closeAmount = constants_1.BN_ZERO;
1193
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1148
+ closeAmountUsd = constants_1.BN_ZERO;
1149
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1194
1150
  }
1195
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1151
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1152
+ };
1153
+ this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1154
+ if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1155
+ if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1156
+ throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1157
+ }
1158
+ var rawMinInitLev = positionAccount.isDegenMode()
1159
+ ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1160
+ : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1161
+ var MIN_INIT_LEVERAGE = rawMinInitLev
1162
+ .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1163
+ .div(new anchor_1.BN(100));
1164
+ var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1165
+ .muln(constants_1.BPS_POWER)
1166
+ .div(MIN_INIT_LEVERAGE);
1167
+ var currentCollateralUsd = positionAccount.collateralUsd;
1168
+ var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1169
+ ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1170
+ : constants_1.BN_ZERO;
1171
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1172
+ var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1173
+ return {
1174
+ maxAddableAmount: maxAddableAmount,
1175
+ maxAddableAmountUsd: maxAddableCollateralUsd,
1176
+ };
1196
1177
  };
1197
1178
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1198
1179
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1205,34 +1186,37 @@ var PerpetualsClient = (function () {
1205
1186
  var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub((positionAccount.isDegenMode() ? new anchor_1.BN(targetCustodyAccount.pricing.minDegenCollateralUsd) : new anchor_1.BN(targetCustodyAccount.pricing.minCollateralUsd)).mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1206
1187
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1207
1188
  console.log("THIS cannot happen but still");
1208
- return constants_1.BN_ZERO;
1189
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1209
1190
  }
1210
1191
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1211
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1192
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1212
1193
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1213
1194
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1214
1195
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1215
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1196
+ var currentCollateralUsd = positionAccount.collateralUsd;
1216
1197
  var availableInitMarginUsd = constants_1.BN_ZERO;
1217
1198
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1218
1199
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1219
1200
  }
1220
1201
  else {
1221
1202
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1222
- return constants_1.BN_ZERO;
1203
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1223
1204
  }
1224
1205
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1225
1206
  if (maxRemovableCollateralUsd.isNeg()) {
1226
- return constants_1.BN_ZERO;
1207
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1227
1208
  }
1228
1209
  var maxWithdrawableAmount;
1210
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1229
1211
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1230
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1212
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1213
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1231
1214
  }
1232
1215
  else {
1233
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1216
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1217
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1234
1218
  }
1235
- return maxWithdrawableAmount;
1219
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1236
1220
  };
1237
1221
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1238
1222
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1270,12 +1254,12 @@ var PerpetualsClient = (function () {
1270
1254
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1271
1255
  var lockFeeUsd = constants_1.BN_ZERO;
1272
1256
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1273
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1257
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1274
1258
  }
1275
1259
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1276
1260
  return lockFeeUsd;
1277
1261
  };
1278
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1262
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1279
1263
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1280
1264
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1281
1265
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1283,193 +1267,146 @@ var PerpetualsClient = (function () {
1283
1267
  else {
1284
1268
  maxPayOffBpsNew = maxPayOffBps;
1285
1269
  }
1286
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1270
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1287
1271
  return lockedUsd;
1288
1272
  };
1289
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1273
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1290
1274
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1291
1275
  price: constants_1.BN_ZERO,
1292
1276
  exponent: constants_1.BN_ZERO,
1293
1277
  confidence: constants_1.BN_ZERO,
1294
1278
  timestamp: constants_1.BN_ZERO
1295
1279
  });
1296
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1297
- return zeroOraclePrice;
1298
- }
1299
1280
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1300
1281
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1301
1282
  }
1302
1283
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1303
1284
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1304
1285
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1305
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1306
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1307
1286
  var liquidationPrice;
1308
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1309
- var newCollateralAmount = void 0;
1310
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1311
- newCollateralAmount = collateralAmount;
1287
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1288
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1289
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1290
+ .div(positionAccount.sizeAmount),
1291
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1292
+ confidence: constants_1.BN_ZERO,
1293
+ timestamp: constants_1.BN_ZERO
1294
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1295
+ if ((0, types_1.isVariant)(side, 'long')) {
1296
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1297
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1298
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1299
+ confidence: constants_1.BN_ZERO,
1300
+ timestamp: constants_1.BN_ZERO
1301
+ });
1312
1302
  }
1313
1303
  else {
1314
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1315
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1316
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1304
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1305
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1306
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1307
+ confidence: constants_1.BN_ZERO,
1308
+ timestamp: constants_1.BN_ZERO
1309
+ });
1317
1310
  }
1318
- var lp = OraclePrice_1.OraclePrice.from({
1319
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1320
- .div(sizeAmount.add(newCollateralAmount)),
1311
+ }
1312
+ else {
1313
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1314
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1315
+ .div(positionAccount.sizeAmount),
1321
1316
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1322
1317
  confidence: constants_1.BN_ZERO,
1323
1318
  timestamp: constants_1.BN_ZERO
1324
- });
1325
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1326
- }
1327
- else {
1328
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1329
- if (assetsUsd.gte(liablitiesUsd)) {
1330
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1331
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1332
- .div(positionAccount.sizeAmount),
1333
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1319
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1320
+ if ((0, types_1.isVariant)(side, 'long')) {
1321
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1322
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1323
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1334
1324
  confidence: constants_1.BN_ZERO,
1335
1325
  timestamp: constants_1.BN_ZERO
1336
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1337
- if ((0, types_1.isVariant)(side, 'long')) {
1338
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1339
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1340
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1341
- confidence: constants_1.BN_ZERO,
1342
- timestamp: constants_1.BN_ZERO
1343
- });
1344
- }
1345
- else {
1346
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1347
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1348
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1349
- confidence: constants_1.BN_ZERO,
1350
- timestamp: constants_1.BN_ZERO
1351
- });
1352
- }
1326
+ });
1353
1327
  }
1354
1328
  else {
1355
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1356
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1357
- .div(positionAccount.sizeAmount),
1358
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1329
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1330
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1331
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1359
1332
  confidence: constants_1.BN_ZERO,
1360
1333
  timestamp: constants_1.BN_ZERO
1361
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1362
- if ((0, types_1.isVariant)(side, 'long')) {
1363
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1364
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1365
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1366
- confidence: constants_1.BN_ZERO,
1367
- timestamp: constants_1.BN_ZERO
1368
- });
1369
- }
1370
- else {
1371
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1373
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1374
- confidence: constants_1.BN_ZERO,
1375
- timestamp: constants_1.BN_ZERO
1376
- });
1377
- }
1334
+ });
1378
1335
  }
1379
1336
  }
1380
1337
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1381
1338
  };
1382
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1339
+ this.getLiquidationPriceSync = function (collateralUsd, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetPrice, targetCustodyAccount, positionAccount) {
1340
+ var newPositionAccount = positionAccount.clone();
1341
+ newPositionAccount.sizeAmount = sizeAmount;
1342
+ newPositionAccount.sizeUsd = targetPrice.getAssetAmountUsd(sizeAmount, targetCustodyAccount.decimals);
1343
+ newPositionAccount.collateralUsd = collateralUsd;
1344
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1345
+ };
1346
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1383
1347
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1384
1348
  price: constants_1.BN_ZERO,
1385
1349
  exponent: constants_1.BN_ZERO,
1386
1350
  confidence: constants_1.BN_ZERO,
1387
1351
  timestamp: constants_1.BN_ZERO
1388
1352
  });
1389
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1390
- return zeroOraclePrice;
1391
- }
1392
1353
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1393
1354
  var unsettledLossUsd = exitFeeUsd;
1394
1355
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1395
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1396
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1397
1356
  var liquidationPrice;
1398
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1399
- var newCollateralAmount = void 0;
1400
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1401
- newCollateralAmount = collateralAmount;
1357
+ if (collateralUsd.gte(liablitiesUsd)) {
1358
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1359
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1360
+ .div(sizeAmount),
1361
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1362
+ confidence: constants_1.BN_ZERO,
1363
+ timestamp: constants_1.BN_ZERO
1364
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1365
+ if ((0, types_1.isVariant)(side, 'long')) {
1366
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1367
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1368
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1369
+ confidence: constants_1.BN_ZERO,
1370
+ timestamp: constants_1.BN_ZERO
1371
+ });
1402
1372
  }
1403
1373
  else {
1404
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1405
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1406
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1374
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1375
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1376
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1377
+ confidence: constants_1.BN_ZERO,
1378
+ timestamp: constants_1.BN_ZERO
1379
+ });
1407
1380
  }
1408
- var lp = OraclePrice_1.OraclePrice.from({
1409
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1410
- .div(sizeAmount.add(newCollateralAmount)),
1381
+ }
1382
+ else {
1383
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1384
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1385
+ .div(sizeAmount),
1411
1386
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1412
1387
  confidence: constants_1.BN_ZERO,
1413
1388
  timestamp: constants_1.BN_ZERO
1414
- });
1415
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1416
- }
1417
- else {
1418
- var assetsUsd = collateralUsd;
1419
- if (assetsUsd.gte(liablitiesUsd)) {
1420
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1421
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1422
- .div(sizeAmount),
1423
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1389
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1390
+ if ((0, types_1.isVariant)(side, 'long')) {
1391
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1392
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1393
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1424
1394
  confidence: constants_1.BN_ZERO,
1425
1395
  timestamp: constants_1.BN_ZERO
1426
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1427
- if ((0, types_1.isVariant)(side, 'long')) {
1428
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1429
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1430
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1431
- confidence: constants_1.BN_ZERO,
1432
- timestamp: constants_1.BN_ZERO
1433
- });
1434
- }
1435
- else {
1436
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1437
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1438
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1439
- confidence: constants_1.BN_ZERO,
1440
- timestamp: constants_1.BN_ZERO
1441
- });
1442
- }
1396
+ });
1443
1397
  }
1444
1398
  else {
1445
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1446
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1447
- .div(sizeAmount),
1448
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1399
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1400
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1401
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1449
1402
  confidence: constants_1.BN_ZERO,
1450
1403
  timestamp: constants_1.BN_ZERO
1451
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1452
- if ((0, types_1.isVariant)(side, 'long')) {
1453
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1454
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1455
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1456
- confidence: constants_1.BN_ZERO,
1457
- timestamp: constants_1.BN_ZERO
1458
- });
1459
- }
1460
- else {
1461
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1462
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1463
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1464
- confidence: constants_1.BN_ZERO,
1465
- timestamp: constants_1.BN_ZERO
1466
- });
1467
- }
1404
+ });
1468
1405
  }
1469
1406
  }
1470
1407
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1471
1408
  };
1472
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1409
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1473
1410
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1474
1411
  price: constants_1.BN_ZERO,
1475
1412
  exponent: constants_1.BN_ZERO,
@@ -1480,7 +1417,7 @@ var PerpetualsClient = (function () {
1480
1417
  return zeroOraclePrice;
1481
1418
  }
1482
1419
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1483
- price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1420
+ price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1484
1421
  .div(positionAccount.sizeAmount),
1485
1422
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1486
1423
  confidence: constants_1.BN_ZERO,
@@ -1508,7 +1445,7 @@ var PerpetualsClient = (function () {
1508
1445
  }
1509
1446
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1510
1447
  };
1511
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1448
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1512
1449
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1513
1450
  throw new Error("Delta Amounts cannot be negative.");
1514
1451
  }
@@ -1538,10 +1475,9 @@ var PerpetualsClient = (function () {
1538
1475
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1539
1476
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1540
1477
  positionAccount.market = marketAccountPk;
1541
- positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1542
- positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1543
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1544
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1478
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1479
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1480
+ positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1545
1481
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1546
1482
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1547
1483
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1613,6 +1549,9 @@ var PerpetualsClient = (function () {
1613
1549
  });
1614
1550
  };
1615
1551
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1552
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1553
+ };
1554
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1616
1555
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1617
1556
  return {
1618
1557
  profitUsd: constants_1.BN_ZERO,
@@ -1671,7 +1610,7 @@ var PerpetualsClient = (function () {
1671
1610
  }
1672
1611
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1673
1612
  return {
1674
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1613
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1675
1614
  lossUsd: constants_1.BN_ZERO,
1676
1615
  };
1677
1616
  }
@@ -1762,6 +1701,9 @@ var PerpetualsClient = (function () {
1762
1701
  }
1763
1702
  };
1764
1703
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1704
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1705
+ };
1706
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1765
1707
  var poolAmountUsd = constants_1.BN_ZERO;
1766
1708
  for (var index = 0; index < custodies.length; index++) {
1767
1709
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1774,6 +1716,7 @@ var PerpetualsClient = (function () {
1774
1716
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1775
1717
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1776
1718
  }
1719
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1777
1720
  if (aumCalcMode === "includePnl") {
1778
1721
  var poolEquityUsd = poolAmountUsd;
1779
1722
  for (var index = 0; index < markets.length; index++) {
@@ -1783,11 +1726,12 @@ var PerpetualsClient = (function () {
1783
1726
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1784
1727
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1785
1728
  var position = markets[index].getCollectivePosition();
1729
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1786
1730
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1787
1731
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1788
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1789
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1790
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1732
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1733
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1734
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1791
1735
  }
1792
1736
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1793
1737
  }
@@ -1795,14 +1739,6 @@ var PerpetualsClient = (function () {
1795
1739
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1796
1740
  }
1797
1741
  };
1798
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1799
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1800
- return { discountBn: constants_1.BN_ZERO };
1801
- }
1802
- else {
1803
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1804
- }
1805
- };
1806
1742
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1807
1743
  if (tokenStakeAccount.level === 0) {
1808
1744
  return { discountBn: constants_1.BN_ZERO };
@@ -1887,7 +1823,7 @@ var PerpetualsClient = (function () {
1887
1823
  });
1888
1824
  };
1889
1825
  this.getStakedLpTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
1890
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, result, index, res;
1826
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, setCULimitIx, result, index, res;
1891
1827
  var _d;
1892
1828
  return __generator(this, function (_e) {
1893
1829
  switch (_e.label) {
@@ -1935,6 +1871,8 @@ var PerpetualsClient = (function () {
1935
1871
  return [4, backUpOracleInstructionPromise];
1936
1872
  case 2:
1937
1873
  backUpOracleInstruction = _e.sent();
1874
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1875
+ transaction.instructions.unshift(setCULimitIx);
1938
1876
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
1939
1877
  return [4, this.viewHelper.simulateTransaction(transaction)];
1940
1878
  case 3:
@@ -2001,7 +1939,7 @@ var PerpetualsClient = (function () {
2001
1939
  args_1[_i - 4] = arguments[_i];
2002
1940
  }
2003
1941
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2004
- var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
1942
+ var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2005
1943
  var _e;
2006
1944
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2007
1945
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2052,6 +1990,8 @@ var PerpetualsClient = (function () {
2052
1990
  .transaction()];
2053
1991
  case 1:
2054
1992
  transaction = _f.sent();
1993
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1994
+ transaction.instructions.unshift(setCULimitIx);
2055
1995
  if (!enableBackupOracle) return [3, 3];
2056
1996
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2057
1997
  case 2:
@@ -2061,6 +2001,14 @@ var PerpetualsClient = (function () {
2061
2001
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2062
2002
  case 4:
2063
2003
  result = _f.sent();
2004
+ if (result.value.err) {
2005
+ console.error('error Simulation failed:::', result);
2006
+ return [2, {
2007
+ amount: undefined,
2008
+ fee: undefined,
2009
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2010
+ }];
2011
+ }
2064
2012
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2065
2013
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2066
2014
  return [2, {
@@ -2077,7 +2025,7 @@ var PerpetualsClient = (function () {
2077
2025
  args_1[_i - 4] = arguments[_i];
2078
2026
  }
2079
2027
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2080
- var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
2028
+ var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2081
2029
  var _e;
2082
2030
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2083
2031
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2128,6 +2076,8 @@ var PerpetualsClient = (function () {
2128
2076
  .transaction()];
2129
2077
  case 1:
2130
2078
  transaction = _f.sent();
2079
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2080
+ transaction.instructions.unshift(setCULimitIx);
2131
2081
  if (!enableBackupOracle) return [3, 3];
2132
2082
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2133
2083
  case 2:
@@ -2139,9 +2089,11 @@ var PerpetualsClient = (function () {
2139
2089
  result = _f.sent();
2140
2090
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2141
2091
  if (result.value.err) {
2092
+ console.error('error Simulation failed:', result);
2142
2093
  return [2, {
2143
- amount: new anchor_1.BN(0),
2144
- fee: new anchor_1.BN(0),
2094
+ amount: undefined,
2095
+ fee: undefined,
2096
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2145
2097
  }];
2146
2098
  }
2147
2099
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2154,7 +2106,7 @@ var PerpetualsClient = (function () {
2154
2106
  });
2155
2107
  };
2156
2108
  this.getCompoundingLPTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
2157
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, result, index, res;
2109
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, setCULimitIx, result, index, res;
2158
2110
  var _d;
2159
2111
  return __generator(this, function (_e) {
2160
2112
  switch (_e.label) {
@@ -2202,6 +2154,8 @@ var PerpetualsClient = (function () {
2202
2154
  .transaction()];
2203
2155
  case 2:
2204
2156
  transaction = _e.sent();
2157
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2158
+ transaction.instructions.unshift(setCULimitIx);
2205
2159
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
2206
2160
  return [4, this.viewHelper.simulateTransaction(transaction)];
2207
2161
  case 3:
@@ -2218,7 +2172,7 @@ var PerpetualsClient = (function () {
2218
2172
  args_1[_i - 4] = arguments[_i];
2219
2173
  }
2220
2174
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2221
- var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2175
+ var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2222
2176
  var _e;
2223
2177
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2224
2178
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2273,6 +2227,8 @@ var PerpetualsClient = (function () {
2273
2227
  .transaction()];
2274
2228
  case 1:
2275
2229
  transaction = _f.sent();
2230
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2231
+ transaction.instructions.unshift(setCULimitIx);
2276
2232
  if (!enableBackupOracle) return [3, 3];
2277
2233
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2278
2234
  case 2:
@@ -2298,7 +2254,7 @@ var PerpetualsClient = (function () {
2298
2254
  args_1[_i - 4] = arguments[_i];
2299
2255
  }
2300
2256
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2301
- var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2257
+ var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2302
2258
  var _e;
2303
2259
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2304
2260
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2353,6 +2309,8 @@ var PerpetualsClient = (function () {
2353
2309
  .transaction()];
2354
2310
  case 1:
2355
2311
  transaction = _f.sent();
2312
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2313
+ transaction.instructions.unshift(setCULimitIx);
2356
2314
  if (!enableBackupOracle) return [3, 3];
2357
2315
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2358
2316
  case 2:
@@ -2547,11 +2505,10 @@ var PerpetualsClient = (function () {
2547
2505
  for (var _i = 8; _i < arguments.length; _i++) {
2548
2506
  args_1[_i - 8] = arguments[_i];
2549
2507
  }
2550
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2508
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2551
2509
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2552
2510
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2553
2511
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2554
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2555
2512
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2556
2513
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2557
2514
  return __generator(this, function (_c) {
@@ -2644,7 +2601,7 @@ var PerpetualsClient = (function () {
2644
2601
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2645
2602
  fundingMint: collateralCustodyConfig.mintKey
2646
2603
  })
2647
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2604
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2648
2605
  .instruction()];
2649
2606
  case 7:
2650
2607
  instruction = _c.sent();
@@ -2662,11 +2619,10 @@ var PerpetualsClient = (function () {
2662
2619
  for (var _i = 6; _i < arguments.length; _i++) {
2663
2620
  args_1[_i - 6] = arguments[_i];
2664
2621
  }
2665
- return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2622
+ return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2666
2623
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2667
2624
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2668
2625
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2669
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2670
2626
  if (createUserATA === void 0) { createUserATA = true; }
2671
2627
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2672
2628
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2745,7 +2701,7 @@ var PerpetualsClient = (function () {
2745
2701
  collateralMint: collateralCustodyConfig.mintKey,
2746
2702
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2747
2703
  })
2748
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2704
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2749
2705
  .instruction()];
2750
2706
  case 6:
2751
2707
  instruction = _b.sent();
@@ -2767,16 +2723,15 @@ var PerpetualsClient = (function () {
2767
2723
  });
2768
2724
  });
2769
2725
  };
2770
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2726
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2771
2727
  var args_1 = [];
2772
- for (var _i = 10; _i < arguments.length; _i++) {
2773
- args_1[_i - 10] = arguments[_i];
2728
+ for (var _i = 9; _i < arguments.length; _i++) {
2729
+ args_1[_i - 9] = arguments[_i];
2774
2730
  }
2775
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, minCollateralAmountOut, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2776
- var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, rebateMintAccount, inx, err_3;
2731
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2732
+ var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, inx, err_3;
2777
2733
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2778
2734
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2779
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2780
2735
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2781
2736
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2782
2737
  return __generator(this, function (_c) {
@@ -2870,18 +2825,10 @@ var PerpetualsClient = (function () {
2870
2825
  }
2871
2826
  _c.label = 10;
2872
2827
  case 10:
2873
- rebateMintAccount = {
2874
- pubkey: collateralCustodyConfig.mintKey,
2875
- isSigner: false,
2876
- isWritable: false
2877
- };
2878
- _c.label = 11;
2879
- case 11:
2880
- _c.trys.push([11, 13, , 14]);
2828
+ _c.trys.push([10, 12, , 13]);
2881
2829
  return [4, this.program.methods
2882
2830
  .swapAndOpen({
2883
2831
  amountIn: amountIn,
2884
- minCollateralAmountOut: minCollateralAmountOut,
2885
2832
  priceWithSlippage: priceWithSlippage,
2886
2833
  sizeAmount: sizeAmount,
2887
2834
  privilege: privilege
@@ -2912,17 +2859,17 @@ var PerpetualsClient = (function () {
2912
2859
  collateralMint: collateralCustodyConfig.mintKey,
2913
2860
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2914
2861
  })
2915
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2862
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2916
2863
  .instruction()];
2917
- case 12:
2864
+ case 11:
2918
2865
  inx = _c.sent();
2919
2866
  instructions.push(inx);
2920
- return [3, 14];
2921
- case 13:
2867
+ return [3, 13];
2868
+ case 12:
2922
2869
  err_3 = _c.sent();
2923
2870
  console.error("perpClient SwapAndOpen error:: ", err_3);
2924
2871
  throw err_3;
2925
- case 14: return [2, {
2872
+ case 13: return [2, {
2926
2873
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2927
2874
  additionalSigners: additionalSigners
2928
2875
  }];
@@ -2930,16 +2877,15 @@ var PerpetualsClient = (function () {
2930
2877
  });
2931
2878
  });
2932
2879
  };
2933
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2880
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2934
2881
  var args_1 = [];
2935
- for (var _i = 8; _i < arguments.length; _i++) {
2936
- args_1[_i - 8] = arguments[_i];
2882
+ for (var _i = 7; _i < arguments.length; _i++) {
2883
+ args_1[_i - 7] = arguments[_i];
2937
2884
  }
2938
- return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, minSwapAmountOut, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, ephemeralSignerPubkey) {
2939
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2885
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, ephemeralSignerPubkey) {
2886
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2940
2887
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2941
2888
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2942
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2943
2889
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2944
2890
  return __generator(this, function (_a) {
2945
2891
  switch (_a.label) {
@@ -3005,18 +2951,12 @@ var PerpetualsClient = (function () {
3005
2951
  if (!(_a.sent())) {
3006
2952
  preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, collateralToken.mintKey, collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
3007
2953
  }
3008
- rebateMintAccount = {
3009
- pubkey: collateralCustodyConfig.mintKey,
3010
- isSigner: false,
3011
- isWritable: false
3012
- };
3013
2954
  _a.label = 5;
3014
2955
  case 5:
3015
2956
  _a.trys.push([5, 7, , 8]);
3016
2957
  return [4, this.program.methods
3017
2958
  .closeAndSwap({
3018
2959
  priceWithSlippage: priceWithSlippage,
3019
- minSwapAmountOut: minSwapAmountOut,
3020
2960
  privilege: privilege
3021
2961
  })
3022
2962
  .accounts({
@@ -3045,7 +2985,7 @@ var PerpetualsClient = (function () {
3045
2985
  collateralMint: collateralCustodyConfig.mintKey,
3046
2986
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
3047
2987
  })
3048
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2988
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3049
2989
  .instruction()];
3050
2990
  case 6:
3051
2991
  inx = _a.sent();
@@ -3166,12 +3106,12 @@ var PerpetualsClient = (function () {
3166
3106
  });
3167
3107
  });
3168
3108
  };
3169
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3109
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3170
3110
  var args_1 = [];
3171
- for (var _i = 8; _i < arguments.length; _i++) {
3172
- args_1[_i - 8] = arguments[_i];
3111
+ for (var _i = 7; _i < arguments.length; _i++) {
3112
+ args_1[_i - 7] = arguments[_i];
3173
3113
  }
3174
- return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, minCollateralAmountOut, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3114
+ return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3175
3115
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3176
3116
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3177
3117
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3250,7 +3190,6 @@ var PerpetualsClient = (function () {
3250
3190
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3251
3191
  return [4, this.program.methods.swapAndAddCollateral({
3252
3192
  amountIn: amountIn,
3253
- minCollateralAmountOut: minCollateralAmountOut,
3254
3193
  }).accounts({
3255
3194
  owner: publicKey,
3256
3195
  feePayer: publicKey,
@@ -3286,12 +3225,12 @@ var PerpetualsClient = (function () {
3286
3225
  });
3287
3226
  });
3288
3227
  };
3289
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3228
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3290
3229
  var args_1 = [];
3291
3230
  for (var _i = 6; _i < arguments.length; _i++) {
3292
3231
  args_1[_i - 6] = arguments[_i];
3293
3232
  }
3294
- return __awaiter(_this, __spreadArray([collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralWithFee, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3233
+ return __awaiter(_this, __spreadArray([collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralDeltaUsd, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3295
3234
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3296
3235
  if (createUserATA === void 0) { createUserATA = true; }
3297
3236
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3355,7 +3294,7 @@ var PerpetualsClient = (function () {
3355
3294
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3356
3295
  return [4, this.program.methods
3357
3296
  .removeCollateral({
3358
- collateralDelta: collateralWithFee,
3297
+ collateralDeltaUsd: collateralDeltaUsd,
3359
3298
  })
3360
3299
  .accounts({
3361
3300
  owner: publicKey,
@@ -3397,12 +3336,12 @@ var PerpetualsClient = (function () {
3397
3336
  });
3398
3337
  });
3399
3338
  };
3400
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3339
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3401
3340
  var args_1 = [];
3402
- for (var _i = 7; _i < arguments.length; _i++) {
3403
- args_1[_i - 7] = arguments[_i];
3341
+ for (var _i = 6; _i < arguments.length; _i++) {
3342
+ args_1[_i - 6] = arguments[_i];
3404
3343
  }
3405
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, minSwapAmountOut, collateralDelta, side, poolConfig, ephemeralSignerPubkey) {
3344
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, collateralDeltaUsd, side, poolConfig, ephemeralSignerPubkey) {
3406
3345
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3407
3346
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3408
3347
  return __generator(this, function (_a) {
@@ -3459,8 +3398,7 @@ var PerpetualsClient = (function () {
3459
3398
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3460
3399
  return [4, this.program.methods
3461
3400
  .removeCollateralAndSwap({
3462
- collateralDelta: collateralDelta,
3463
- minSwapAmountOut: minSwapAmountOut,
3401
+ collateralDeltaUsd: collateralDeltaUsd,
3464
3402
  })
3465
3403
  .accounts({
3466
3404
  owner: publicKey,
@@ -3505,11 +3443,10 @@ var PerpetualsClient = (function () {
3505
3443
  for (var _i = 8; _i < arguments.length; _i++) {
3506
3444
  args_1[_i - 8] = arguments[_i];
3507
3445
  }
3508
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3446
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3509
3447
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3510
3448
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3511
3449
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3512
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3513
3450
  return __generator(this, function (_a) {
3514
3451
  switch (_a.label) {
3515
3452
  case 0:
@@ -3552,7 +3489,7 @@ var PerpetualsClient = (function () {
3552
3489
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3553
3490
  collateralMint: collateralCustodyConfig.mintKey
3554
3491
  })
3555
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3492
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3556
3493
  .instruction()];
3557
3494
  case 1:
3558
3495
  instruction = _a.sent();
@@ -3570,11 +3507,10 @@ var PerpetualsClient = (function () {
3570
3507
  for (var _i = 8; _i < arguments.length; _i++) {
3571
3508
  args_1[_i - 8] = arguments[_i];
3572
3509
  }
3573
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3510
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3574
3511
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3575
3512
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3576
3513
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3577
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3578
3514
  return __generator(this, function (_a) {
3579
3515
  switch (_a.label) {
3580
3516
  case 0:
@@ -3617,7 +3553,7 @@ var PerpetualsClient = (function () {
3617
3553
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3618
3554
  collateralMint: collateralCustodyConfig.mintKey
3619
3555
  })
3620
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3556
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3621
3557
  .instruction()];
3622
3558
  case 1:
3623
3559
  instruction = _a.sent();
@@ -4084,119 +4020,8 @@ var PerpetualsClient = (function () {
4084
4020
  }
4085
4021
  });
4086
4022
  }); };
4087
- this.updateNftAccount = function (nftMint, updateReferer, updateBooster, flpStakeAccounts) { return __awaiter(_this, void 0, void 0, function () {
4088
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, flpStakeAccountMetas, _i, flpStakeAccounts_1, flpStakeAccountPk, updateNftTradingAccountInstruction, err_8;
4089
- return __generator(this, function (_a) {
4090
- switch (_a.label) {
4091
- case 0:
4092
- publicKey = this.provider.wallet.publicKey;
4093
- preInstructions = [];
4094
- instructions = [];
4095
- postInstructions = [];
4096
- additionalSigners = [];
4097
- _a.label = 1;
4098
- case 1:
4099
- _a.trys.push([1, 4, , 5]);
4100
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4101
- Buffer.from("trading"),
4102
- nftMint.toBuffer(),
4103
- ], this.programId)[0];
4104
- nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
4105
- Buffer.from("referral"),
4106
- publicKey.toBuffer(),
4107
- ], this.programId)[0];
4108
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey, true)];
4109
- case 2:
4110
- nftTokenAccount = _a.sent();
4111
- flpStakeAccountMetas = [];
4112
- for (_i = 0, flpStakeAccounts_1 = flpStakeAccounts; _i < flpStakeAccounts_1.length; _i++) {
4113
- flpStakeAccountPk = flpStakeAccounts_1[_i];
4114
- flpStakeAccountMetas.push({
4115
- pubkey: flpStakeAccountPk,
4116
- isSigner: false,
4117
- isWritable: true,
4118
- });
4119
- }
4120
- return [4, this.program.methods
4121
- .updateTradingAccount({
4122
- updateReferer: updateReferer,
4123
- updateBooster: updateBooster
4124
- })
4125
- .accounts({
4126
- owner: publicKey,
4127
- feePayer: publicKey,
4128
- nftTokenAccount: nftTokenAccount,
4129
- referralAccount: nftReferralAccount,
4130
- tradingAccount: nftTradingAccount
4131
- })
4132
- .instruction()];
4133
- case 3:
4134
- updateNftTradingAccountInstruction = _a.sent();
4135
- instructions.push(updateNftTradingAccountInstruction);
4136
- return [3, 5];
4137
- case 4:
4138
- err_8 = _a.sent();
4139
- console.log("perpClient updateNftAccount error:: ", err_8);
4140
- throw err_8;
4141
- case 5: return [2, {
4142
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4143
- additionalSigners: additionalSigners
4144
- }];
4145
- }
4146
- });
4147
- }); };
4148
- this.levelUp = function (poolConfig, nftMint, authorizationRulesAccount) { return __awaiter(_this, void 0, void 0, function () {
4149
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_9;
4150
- return __generator(this, function (_a) {
4151
- switch (_a.label) {
4152
- case 0:
4153
- publicKey = this.provider.wallet.publicKey;
4154
- preInstructions = [];
4155
- instructions = [];
4156
- postInstructions = [];
4157
- additionalSigners = [];
4158
- _a.label = 1;
4159
- case 1:
4160
- _a.trys.push([1, 3, , 4]);
4161
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4162
- Buffer.from("trading"),
4163
- nftMint.toBuffer(),
4164
- ], this.programId)[0];
4165
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
4166
- return [4, this.program.methods
4167
- .levelUp({})
4168
- .accounts({
4169
- owner: publicKey,
4170
- perpetuals: this.perpetuals.publicKey,
4171
- pool: poolConfig.poolAddress,
4172
- metadataAccount: metadataAccount,
4173
- nftMint: nftMint,
4174
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
4175
- tradingAccount: nftTradingAccount,
4176
- transferAuthority: this.authority.publicKey,
4177
- authorizationRulesAccount: authorizationRulesAccount,
4178
- authorizationRulesProgram: new web3_js_1.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg'),
4179
- systemProgram: web3_js_1.SystemProgram.programId,
4180
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
4181
- })
4182
- .instruction()];
4183
- case 2:
4184
- levelUpInstruction = _a.sent();
4185
- instructions.push(levelUpInstruction);
4186
- return [3, 4];
4187
- case 3:
4188
- err_9 = _a.sent();
4189
- console.log("perpClient levelUp error:: ", err_9);
4190
- throw err_9;
4191
- case 4: return [2, {
4192
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4193
- additionalSigners: additionalSigners
4194
- }];
4195
- }
4196
- });
4197
- }); };
4198
4023
  this.depositStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4199
- var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
4024
+ var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_8;
4200
4025
  return __generator(this, function (_a) {
4201
4026
  switch (_a.label) {
4202
4027
  case 0:
@@ -4238,9 +4063,9 @@ var PerpetualsClient = (function () {
4238
4063
  instructions.push(depositStakeInstruction);
4239
4064
  return [3, 5];
4240
4065
  case 4:
4241
- err_10 = _a.sent();
4242
- console.log("perpClient depositStaking error:: ", err_10);
4243
- throw err_10;
4066
+ err_8 = _a.sent();
4067
+ console.log("perpClient depositStaking error:: ", err_8);
4068
+ throw err_8;
4244
4069
  case 5: return [2, {
4245
4070
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4246
4071
  additionalSigners: additionalSigners
@@ -4249,7 +4074,7 @@ var PerpetualsClient = (function () {
4249
4074
  });
4250
4075
  }); };
4251
4076
  this.refreshStakeWithAllFlpStakeAccounts = function (rewardSymbol, poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4252
- var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_11;
4077
+ var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_9;
4253
4078
  return __generator(this, function (_c) {
4254
4079
  switch (_c.label) {
4255
4080
  case 0:
@@ -4296,9 +4121,9 @@ var PerpetualsClient = (function () {
4296
4121
  refreshStakeInstruction = _c.sent();
4297
4122
  return [2, refreshStakeInstruction];
4298
4123
  case 2:
4299
- err_11 = _c.sent();
4300
- console.log("perpClient refreshStaking error:: ", err_11);
4301
- throw err_11;
4124
+ err_9 = _c.sent();
4125
+ console.log("perpClient refreshStaking error:: ", err_9);
4126
+ throw err_9;
4302
4127
  case 3: return [2];
4303
4128
  }
4304
4129
  });
@@ -4309,7 +4134,7 @@ var PerpetualsClient = (function () {
4309
4134
  args_1[_i - 3] = arguments[_i];
4310
4135
  }
4311
4136
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, flpStakeAccountPk_1], args_1, true), void 0, function (rewardSymbol, poolConfig, flpStakeAccountPk, userPublicKey) {
4312
- var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_12;
4137
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_10;
4313
4138
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4314
4139
  return __generator(this, function (_c) {
4315
4140
  switch (_c.label) {
@@ -4357,9 +4182,9 @@ var PerpetualsClient = (function () {
4357
4182
  refreshStakeInstruction = _c.sent();
4358
4183
  return [2, refreshStakeInstruction];
4359
4184
  case 2:
4360
- err_12 = _c.sent();
4361
- console.log("perpClient refreshStaking error:: ", err_12);
4362
- throw err_12;
4185
+ err_10 = _c.sent();
4186
+ console.log("perpClient refreshStaking error:: ", err_10);
4187
+ throw err_10;
4363
4188
  case 3: return [2];
4364
4189
  }
4365
4190
  });
@@ -4371,7 +4196,7 @@ var PerpetualsClient = (function () {
4371
4196
  args_1[_i - 3] = arguments[_i];
4372
4197
  }
4373
4198
  return __awaiter(_this, __spreadArray([rewardSymbol_1, unstakeAmount_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, unstakeAmount, poolConfig, userPublicKey) {
4374
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_13;
4199
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_11;
4375
4200
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4376
4201
  return __generator(this, function (_b) {
4377
4202
  switch (_b.label) {
@@ -4423,9 +4248,9 @@ var PerpetualsClient = (function () {
4423
4248
  instructions.push(unstakeInstantInstruction);
4424
4249
  return [3, 6];
4425
4250
  case 5:
4426
- err_13 = _b.sent();
4427
- console.log("perpClient unstakeInstant error:: ", err_13);
4428
- throw err_13;
4251
+ err_11 = _b.sent();
4252
+ console.log("perpClient unstakeInstant error:: ", err_11);
4253
+ throw err_11;
4429
4254
  case 6: return [2, {
4430
4255
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4431
4256
  additionalSigners: additionalSigners
@@ -4435,7 +4260,7 @@ var PerpetualsClient = (function () {
4435
4260
  });
4436
4261
  };
4437
4262
  this.setFeeShareBps = function (poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4438
- var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_14;
4263
+ var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_12;
4439
4264
  return __generator(this, function (_c) {
4440
4265
  switch (_c.label) {
4441
4266
  case 0:
@@ -4479,15 +4304,15 @@ var PerpetualsClient = (function () {
4479
4304
  refreshStakeInstruction = _c.sent();
4480
4305
  return [2, refreshStakeInstruction];
4481
4306
  case 2:
4482
- err_14 = _c.sent();
4483
- console.log("perpClient refreshStaking error:: ", err_14);
4484
- throw err_14;
4307
+ err_12 = _c.sent();
4308
+ console.log("perpClient refreshStaking error:: ", err_12);
4309
+ throw err_12;
4485
4310
  case 3: return [2];
4486
4311
  }
4487
4312
  });
4488
4313
  }); };
4489
4314
  this.unstakeRequest = function (unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4490
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_15;
4315
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_13;
4491
4316
  return __generator(this, function (_a) {
4492
4317
  switch (_a.label) {
4493
4318
  case 0:
@@ -4521,9 +4346,9 @@ var PerpetualsClient = (function () {
4521
4346
  instructions.push(unstakeRequestInstruction);
4522
4347
  return [3, 4];
4523
4348
  case 3:
4524
- err_15 = _a.sent();
4525
- console.log("perpClient unstakeRequest error:: ", err_15);
4526
- throw err_15;
4349
+ err_13 = _a.sent();
4350
+ console.log("perpClient unstakeRequest error:: ", err_13);
4351
+ throw err_13;
4527
4352
  case 4: return [2, {
4528
4353
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4529
4354
  additionalSigners: additionalSigners
@@ -4537,7 +4362,7 @@ var PerpetualsClient = (function () {
4537
4362
  args_1[_i - 1] = arguments[_i];
4538
4363
  }
4539
4364
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, pendingActivation, deactivated, createUserLPTA, userPublicKey) {
4540
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_16;
4365
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_14;
4541
4366
  if (pendingActivation === void 0) { pendingActivation = true; }
4542
4367
  if (deactivated === void 0) { deactivated = true; }
4543
4368
  if (createUserLPTA === void 0) { createUserLPTA = true; }
@@ -4593,9 +4418,9 @@ var PerpetualsClient = (function () {
4593
4418
  instructions.push(withdrawStakeInstruction);
4594
4419
  return [3, 6];
4595
4420
  case 5:
4596
- err_16 = _b.sent();
4597
- console.log("perpClient withdrawStake error:: ", err_16);
4598
- throw err_16;
4421
+ err_14 = _b.sent();
4422
+ console.log("perpClient withdrawStake error:: ", err_14);
4423
+ throw err_14;
4599
4424
  case 6: return [2, {
4600
4425
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4601
4426
  additionalSigners: additionalSigners
@@ -4610,7 +4435,7 @@ var PerpetualsClient = (function () {
4610
4435
  args_1[_i - 3] = arguments[_i];
4611
4436
  }
4612
4437
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, tokenStakeAccount_1], args_1, true), void 0, function (rewardSymbol, poolConfig, tokenStakeAccount, createUserATA) {
4613
- var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_17;
4438
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_15;
4614
4439
  if (createUserATA === void 0) { createUserATA = true; }
4615
4440
  return __generator(this, function (_b) {
4616
4441
  switch (_b.label) {
@@ -4671,9 +4496,9 @@ var PerpetualsClient = (function () {
4671
4496
  instructions.push(withdrawStakeInstruction);
4672
4497
  return [3, 6];
4673
4498
  case 5:
4674
- err_17 = _b.sent();
4675
- console.log("perpClient withdrawStake error:: ", err_17);
4676
- throw err_17;
4499
+ err_15 = _b.sent();
4500
+ console.log("perpClient withdrawStake error:: ", err_15);
4501
+ throw err_15;
4677
4502
  case 6: return [2, {
4678
4503
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4679
4504
  additionalSigners: additionalSigners
@@ -4687,11 +4512,13 @@ var PerpetualsClient = (function () {
4687
4512
  for (var _i = 5; _i < arguments.length; _i++) {
4688
4513
  args_1[_i - 5] = arguments[_i];
4689
4514
  }
4690
- return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey) {
4691
- var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_18;
4515
+ return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4516
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, heapSizeIx, addCompoundingLiquidity, err_16;
4692
4517
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4693
4518
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4694
4519
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4520
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4521
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4695
4522
  return __generator(this, function (_f) {
4696
4523
  switch (_f.label) {
4697
4524
  case 0:
@@ -4782,6 +4609,15 @@ var PerpetualsClient = (function () {
4782
4609
  _f.label = 7;
4783
4610
  case 7:
4784
4611
  _f.trys.push([7, 9, , 10]);
4612
+ if (enableHeapSizeIx) {
4613
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4614
+ bytes: 64 * 1024,
4615
+ });
4616
+ if (enableDebugLogs) {
4617
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4618
+ }
4619
+ preInstructions.push(heapSizeIx);
4620
+ }
4785
4621
  return [4, this.program.methods
4786
4622
  .addCompoundingLiquidity({
4787
4623
  amountIn: amountIn,
@@ -4816,8 +4652,8 @@ var PerpetualsClient = (function () {
4816
4652
  instructions.push(addCompoundingLiquidity);
4817
4653
  return [3, 10];
4818
4654
  case 9:
4819
- err_18 = _f.sent();
4820
- console.log("perpClient addCompoundingLiquidity error:: ", err_18);
4655
+ err_16 = _f.sent();
4656
+ console.log("perpClient addCompoundingLiquidity error:: ", err_16);
4821
4657
  return [3, 10];
4822
4658
  case 10: return [2, {
4823
4659
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4832,11 +4668,13 @@ var PerpetualsClient = (function () {
4832
4668
  for (var _i = 5; _i < arguments.length; _i++) {
4833
4669
  args_1[_i - 5] = arguments[_i];
4834
4670
  }
4835
- return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey) {
4836
- var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_19;
4671
+ 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) {
4672
+ 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;
4837
4673
  if (createUserATA === void 0) { createUserATA = true; }
4838
4674
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4839
4675
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4676
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4677
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4840
4678
  return __generator(this, function (_f) {
4841
4679
  switch (_f.label) {
4842
4680
  case 0:
@@ -4911,7 +4749,16 @@ var PerpetualsClient = (function () {
4911
4749
  _f.label = 5;
4912
4750
  case 5:
4913
4751
  _f.trys.push([5, 7, , 8]);
4914
- return [4, this.program.methods
4752
+ if (enableHeapSizeIx) {
4753
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4754
+ bytes: 64 * 1024,
4755
+ });
4756
+ if (enableDebugLogs) {
4757
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4758
+ }
4759
+ preInstructions.push(heapSizeIx);
4760
+ }
4761
+ return [4, this.program.methods
4915
4762
  .removeCompoundingLiquidity({
4916
4763
  compoundingAmountIn: compoundingAmountIn,
4917
4764
  minAmountOut: minAmountOut
@@ -4945,8 +4792,8 @@ var PerpetualsClient = (function () {
4945
4792
  instructions.push(removeCompoundingLiquidity);
4946
4793
  return [3, 8];
4947
4794
  case 7:
4948
- err_19 = _f.sent();
4949
- console.log("perpClient removeCompoundingLiquidity error:: ", err_19);
4795
+ err_17 = _f.sent();
4796
+ console.log("perpClient removeCompoundingLiquidity error:: ", err_17);
4950
4797
  return [3, 8];
4951
4798
  case 8: return [2, {
4952
4799
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4962,7 +4809,7 @@ var PerpetualsClient = (function () {
4962
4809
  args_1[_i - 3] = arguments[_i];
4963
4810
  }
4964
4811
  return __awaiter(_this, __spreadArray([amount_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amount, rewardTokenMint, poolConfig, createUserATA) {
4965
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_20;
4812
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_18;
4966
4813
  if (createUserATA === void 0) { createUserATA = true; }
4967
4814
  return __generator(this, function (_g) {
4968
4815
  switch (_g.label) {
@@ -5060,8 +4907,8 @@ var PerpetualsClient = (function () {
5060
4907
  instructions.push(migrateStake);
5061
4908
  return [3, 8];
5062
4909
  case 7:
5063
- err_20 = _g.sent();
5064
- console.log("perpClient migrateStake error:: ", err_20);
4910
+ err_18 = _g.sent();
4911
+ console.log("perpClient migrateStake error:: ", err_18);
5065
4912
  return [3, 8];
5066
4913
  case 8: return [2, {
5067
4914
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5072,7 +4919,7 @@ var PerpetualsClient = (function () {
5072
4919
  });
5073
4920
  };
5074
4921
  this.migrateFlp = function (amount, rewardTokenMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5075
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_21;
4922
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_19;
5076
4923
  return __generator(this, function (_d) {
5077
4924
  switch (_d.label) {
5078
4925
  case 0:
@@ -5144,8 +4991,8 @@ var PerpetualsClient = (function () {
5144
4991
  instructions.push(migrateFlp);
5145
4992
  return [3, 4];
5146
4993
  case 3:
5147
- err_21 = _d.sent();
5148
- console.log("perpClient migrateFlp error:: ", err_21);
4994
+ err_19 = _d.sent();
4995
+ console.log("perpClient migrateFlp error:: ", err_19);
5149
4996
  return [3, 4];
5150
4997
  case 4: return [2, {
5151
4998
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5160,7 +5007,7 @@ var PerpetualsClient = (function () {
5160
5007
  args_1[_i - 1] = arguments[_i];
5161
5008
  }
5162
5009
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, rewardTokenSymbol) {
5163
- var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_22;
5010
+ var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_20;
5164
5011
  if (rewardTokenSymbol === void 0) { rewardTokenSymbol = 'USDC'; }
5165
5012
  return __generator(this, function (_e) {
5166
5013
  switch (_e.label) {
@@ -5218,8 +5065,8 @@ var PerpetualsClient = (function () {
5218
5065
  instructions.push(compoundingFee);
5219
5066
  return [3, 4];
5220
5067
  case 3:
5221
- err_22 = _e.sent();
5222
- console.log("perpClient compoundingFee error:: ", err_22);
5068
+ err_20 = _e.sent();
5069
+ console.log("perpClient compoundingFee error:: ", err_20);
5223
5070
  return [3, 4];
5224
5071
  case 4: return [2, {
5225
5072
  instructions: __spreadArray([], instructions, true),
@@ -5229,146 +5076,8 @@ var PerpetualsClient = (function () {
5229
5076
  });
5230
5077
  });
5231
5078
  };
5232
- this.burnAndClaim = function (owner, nftMint, poolConfig, createAta) { return __awaiter(_this, void 0, void 0, function () {
5233
- var preInstructions, instructions, postInstructions, additionalSigners, userTokenAccount, _a, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndClaimInstruction, err_23;
5234
- return __generator(this, function (_b) {
5235
- switch (_b.label) {
5236
- case 0:
5237
- preInstructions = [];
5238
- instructions = [];
5239
- postInstructions = [];
5240
- additionalSigners = [];
5241
- _b.label = 1;
5242
- case 1:
5243
- _b.trys.push([1, 7, , 8]);
5244
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, owner, true)];
5245
- case 2:
5246
- userTokenAccount = _b.sent();
5247
- _a = createAta;
5248
- if (!_a) return [3, 4];
5249
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5250
- case 3:
5251
- _a = !(_b.sent());
5252
- _b.label = 4;
5253
- case 4:
5254
- if (_a) {
5255
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, userTokenAccount, owner, poolConfig.tokenMint));
5256
- }
5257
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, owner, true)];
5258
- case 5:
5259
- nftTokenAccount = _b.sent();
5260
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5261
- Buffer.from("trading"),
5262
- nftMint.toBuffer(),
5263
- ], this.programId)[0];
5264
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5265
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5266
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5267
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5268
- return [4, this.program.methods
5269
- .burnAndClaim({})
5270
- .accounts({
5271
- owner: owner,
5272
- receivingTokenAccount: userTokenAccount,
5273
- perpetuals: this.perpetuals.publicKey,
5274
- tokenVault: poolConfig.tokenVault,
5275
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5276
- metadataAccount: metadataAccount,
5277
- collectionMetadata: collectionMetadata,
5278
- edition: edition,
5279
- tokenRecord: tokenRecord,
5280
- tradingAccount: nftTradingAccount,
5281
- transferAuthority: poolConfig.transferAuthority,
5282
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5283
- nftMint: nftMint,
5284
- nftTokenAccount: nftTokenAccount,
5285
- systemProgram: web3_js_1.SystemProgram.programId,
5286
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5287
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5288
- eventAuthority: this.eventAuthority.publicKey,
5289
- program: this.programId,
5290
- receivingTokenMint: poolConfig.tokenMint,
5291
- })
5292
- .instruction()];
5293
- case 6:
5294
- burnAndClaimInstruction = _b.sent();
5295
- instructions.push(burnAndClaimInstruction);
5296
- return [3, 8];
5297
- case 7:
5298
- err_23 = _b.sent();
5299
- console.log("perpClient burnAndClaimInstruction error:: ", err_23);
5300
- throw err_23;
5301
- case 8: return [2, {
5302
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5303
- additionalSigners: additionalSigners
5304
- }];
5305
- }
5306
- });
5307
- }); };
5308
- this.burnAndStake = function (owner, feePayer, nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5309
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndStakeInstruction, err_24;
5310
- return __generator(this, function (_a) {
5311
- switch (_a.label) {
5312
- case 0:
5313
- preInstructions = [];
5314
- instructions = [];
5315
- postInstructions = [];
5316
- additionalSigners = [];
5317
- _a.label = 1;
5318
- case 1:
5319
- _a.trys.push([1, 3, , 4]);
5320
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5321
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, owner, true);
5322
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5323
- Buffer.from("trading"),
5324
- nftMint.toBuffer(),
5325
- ], this.programId)[0];
5326
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5327
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5328
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5329
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5330
- return [4, this.program.methods
5331
- .burnAndStake({})
5332
- .accounts({
5333
- owner: owner,
5334
- feePayer: feePayer,
5335
- perpetuals: this.perpetuals.publicKey,
5336
- tokenVault: poolConfig.tokenVault,
5337
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5338
- tokenStakeAccount: tokenStakeAccount,
5339
- metadataAccount: metadataAccount,
5340
- collectionMetadata: collectionMetadata,
5341
- edition: edition,
5342
- tokenRecord: tokenRecord,
5343
- tradingAccount: nftTradingAccount,
5344
- transferAuthority: poolConfig.transferAuthority,
5345
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5346
- nftMint: nftMint,
5347
- nftTokenAccount: nftTokenAccount,
5348
- systemProgram: web3_js_1.SystemProgram.programId,
5349
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5350
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5351
- eventAuthority: this.eventAuthority.publicKey,
5352
- program: this.programId
5353
- })
5354
- .instruction()];
5355
- case 2:
5356
- burnAndStakeInstruction = _a.sent();
5357
- instructions.push(burnAndStakeInstruction);
5358
- return [3, 4];
5359
- case 3:
5360
- err_24 = _a.sent();
5361
- console.log("perpClient burnAndStakeInstruction error:: ", err_24);
5362
- throw err_24;
5363
- case 4: return [2, {
5364
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5365
- additionalSigners: additionalSigners
5366
- }];
5367
- }
5368
- });
5369
- }); };
5370
5079
  this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5371
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_25;
5080
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_21;
5372
5081
  return __generator(this, function (_a) {
5373
5082
  switch (_a.label) {
5374
5083
  case 0:
@@ -5410,9 +5119,9 @@ var PerpetualsClient = (function () {
5410
5119
  instructions.push(depositTokenStakeInstruction);
5411
5120
  return [3, 5];
5412
5121
  case 4:
5413
- err_25 = _a.sent();
5414
- console.log("perpClient depositStakingInstruction error:: ", err_25);
5415
- throw err_25;
5122
+ err_21 = _a.sent();
5123
+ console.log("perpClient depositStakingInstruction error:: ", err_21);
5124
+ throw err_21;
5416
5125
  case 5: return [2, {
5417
5126
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5418
5127
  additionalSigners: additionalSigners
@@ -5421,7 +5130,7 @@ var PerpetualsClient = (function () {
5421
5130
  });
5422
5131
  }); };
5423
5132
  this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5424
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_26;
5133
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_22;
5425
5134
  return __generator(this, function (_a) {
5426
5135
  switch (_a.label) {
5427
5136
  case 0:
@@ -5450,9 +5159,9 @@ var PerpetualsClient = (function () {
5450
5159
  instructions.push(unstakeTokenRequestInstruction);
5451
5160
  return [3, 4];
5452
5161
  case 3:
5453
- err_26 = _a.sent();
5454
- console.log("perpClient unstakeTokenRequestInstruction error:: ", err_26);
5455
- throw err_26;
5162
+ err_22 = _a.sent();
5163
+ console.log("perpClient unstakeTokenRequestInstruction error:: ", err_22);
5164
+ throw err_22;
5456
5165
  case 4: return [2, {
5457
5166
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5458
5167
  additionalSigners: additionalSigners
@@ -5461,7 +5170,7 @@ var PerpetualsClient = (function () {
5461
5170
  });
5462
5171
  }); };
5463
5172
  this.unstakeTokenInstant = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5464
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_27;
5173
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_23;
5465
5174
  return __generator(this, function (_a) {
5466
5175
  switch (_a.label) {
5467
5176
  case 0:
@@ -5502,9 +5211,9 @@ var PerpetualsClient = (function () {
5502
5211
  instructions.push(unstakeTokenInstantInstruction);
5503
5212
  return [3, 5];
5504
5213
  case 4:
5505
- err_27 = _a.sent();
5506
- console.log("perpClient unstakeTokenInstantInstruction error:: ", err_27);
5507
- throw err_27;
5214
+ err_23 = _a.sent();
5215
+ console.log("perpClient unstakeTokenInstantInstruction error:: ", err_23);
5216
+ throw err_23;
5508
5217
  case 5: return [2, {
5509
5218
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5510
5219
  additionalSigners: additionalSigners
@@ -5513,7 +5222,7 @@ var PerpetualsClient = (function () {
5513
5222
  });
5514
5223
  }); };
5515
5224
  this.withdrawToken = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5516
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_28;
5225
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_24;
5517
5226
  return __generator(this, function (_a) {
5518
5227
  switch (_a.label) {
5519
5228
  case 0:
@@ -5554,9 +5263,9 @@ var PerpetualsClient = (function () {
5554
5263
  instructions.push(withdrawTokenInstruction);
5555
5264
  return [3, 5];
5556
5265
  case 4:
5557
- err_28 = _a.sent();
5558
- console.log("perpClient withdrawTokenInstruction error:: ", err_28);
5559
- throw err_28;
5266
+ err_24 = _a.sent();
5267
+ console.log("perpClient withdrawTokenInstruction error:: ", err_24);
5268
+ throw err_24;
5560
5269
  case 5: return [2, {
5561
5270
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5562
5271
  additionalSigners: additionalSigners
@@ -5565,7 +5274,7 @@ var PerpetualsClient = (function () {
5565
5274
  });
5566
5275
  }); };
5567
5276
  this.cancelUnstakeRequest = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5568
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_29;
5277
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_25;
5569
5278
  return __generator(this, function (_a) {
5570
5279
  switch (_a.label) {
5571
5280
  case 0:
@@ -5594,9 +5303,9 @@ var PerpetualsClient = (function () {
5594
5303
  instructions.push(cancelUnstakeRequestInstruction);
5595
5304
  return [3, 4];
5596
5305
  case 3:
5597
- err_29 = _a.sent();
5598
- console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_29);
5599
- throw err_29;
5306
+ err_25 = _a.sent();
5307
+ console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_25);
5308
+ throw err_25;
5600
5309
  case 4: return [2, {
5601
5310
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5602
5311
  additionalSigners: additionalSigners
@@ -5610,7 +5319,7 @@ var PerpetualsClient = (function () {
5610
5319
  args_1[_i - 2] = arguments[_i];
5611
5320
  }
5612
5321
  return __awaiter(_this, __spreadArray([owner_1, poolConfig_1], args_1, true), void 0, function (owner, poolConfig, createUserATA) {
5613
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_30;
5322
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_26;
5614
5323
  if (createUserATA === void 0) { createUserATA = true; }
5615
5324
  return __generator(this, function (_b) {
5616
5325
  switch (_b.label) {
@@ -5656,9 +5365,9 @@ var PerpetualsClient = (function () {
5656
5365
  instructions.push(collectTokenRewardInstruction);
5657
5366
  return [3, 6];
5658
5367
  case 5:
5659
- err_30 = _b.sent();
5660
- console.log("perpClient collectTokenRewardInstruction error:: ", err_30);
5661
- throw err_30;
5368
+ err_26 = _b.sent();
5369
+ console.log("perpClient collectTokenRewardInstruction error:: ", err_26);
5370
+ throw err_26;
5662
5371
  case 6: return [2, {
5663
5372
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5664
5373
  additionalSigners: additionalSigners
@@ -5673,7 +5382,7 @@ var PerpetualsClient = (function () {
5673
5382
  args_1[_i - 3] = arguments[_i];
5674
5383
  }
5675
5384
  return __awaiter(_this, __spreadArray([owner_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rewardSymbol, poolConfig, createUserATA) {
5676
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_31;
5385
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_27;
5677
5386
  if (createUserATA === void 0) { createUserATA = true; }
5678
5387
  return __generator(this, function (_b) {
5679
5388
  switch (_b.label) {
@@ -5720,9 +5429,9 @@ var PerpetualsClient = (function () {
5720
5429
  instructions.push(collectRevenueInstruction);
5721
5430
  return [3, 6];
5722
5431
  case 5:
5723
- err_31 = _b.sent();
5724
- console.log("perpClient collectRevenueInstruction error:: ", err_31);
5725
- throw err_31;
5432
+ err_27 = _b.sent();
5433
+ console.log("perpClient collectRevenueInstruction error:: ", err_27);
5434
+ throw err_27;
5726
5435
  case 6: return [2, {
5727
5436
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5728
5437
  additionalSigners: additionalSigners
@@ -5731,179 +5440,18 @@ var PerpetualsClient = (function () {
5731
5440
  });
5732
5441
  });
5733
5442
  };
5734
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5735
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_32;
5736
- return __generator(this, function (_a) {
5737
- switch (_a.label) {
5738
- case 0:
5739
- publicKey = this.provider.wallet.publicKey;
5740
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5741
- instructions = [];
5742
- additionalSigners = [];
5743
- _a.label = 1;
5744
- case 1:
5745
- _a.trys.push([1, 3, , 4]);
5746
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5747
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5748
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5749
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5750
- return [4, this.programFbnftReward.methods
5751
- .initRewardVault({
5752
- nftCount: nftCount
5753
- })
5754
- .accounts({
5755
- admin: publicKey,
5756
- transferAuthority: nftTransferAuthority,
5757
- rewardVault: rewardVault,
5758
- rewardMint: rewardCustodyMint,
5759
- rewardTokenAccount: rewardTokenAccount,
5760
- collectionMint: collectionMint,
5761
- programData: fbNftProgramData,
5762
- systemProgram: web3_js_1.SystemProgram.programId,
5763
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5764
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5765
- })
5766
- .instruction()];
5767
- case 2:
5768
- initRewardVault = _a.sent();
5769
- instructions.push(initRewardVault);
5770
- return [3, 4];
5771
- case 3:
5772
- err_32 = _a.sent();
5773
- console.log("perpClient InitRewardVault error:: ", err_32);
5774
- throw err_32;
5775
- case 4: return [2, {
5776
- instructions: __spreadArray([], instructions, true),
5777
- additionalSigners: additionalSigners
5778
- }];
5779
- }
5780
- });
5781
- }); };
5782
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5783
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_33;
5784
- return __generator(this, function (_a) {
5785
- switch (_a.label) {
5786
- case 0:
5787
- publicKey = this.provider.wallet.publicKey;
5788
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5789
- instructions = [];
5790
- additionalSigners = [];
5791
- _a.label = 1;
5792
- case 1:
5793
- _a.trys.push([1, 3, , 4]);
5794
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5795
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5796
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5797
- return [4, this.programFbnftReward.methods
5798
- .distributeRewards({
5799
- rewardAmount: rewardAmount
5800
- })
5801
- .accounts({
5802
- admin: publicKey,
5803
- fundingAccount: fundingAccount,
5804
- rewardVault: rewardVault,
5805
- rewardTokenAccount: rewardTokenAccount,
5806
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5807
- })
5808
- .instruction()];
5809
- case 2:
5810
- distributeReward = _a.sent();
5811
- instructions.push(distributeReward);
5812
- return [3, 4];
5813
- case 3:
5814
- err_33 = _a.sent();
5815
- console.log("perpClient distributeReward error:: ", err_33);
5816
- throw err_33;
5817
- case 4: return [2, {
5818
- instructions: __spreadArray([], instructions, true),
5819
- additionalSigners: additionalSigners
5820
- }];
5821
- }
5822
- });
5823
- }); };
5824
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5443
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5825
5444
  var args_1 = [];
5826
5445
  for (var _i = 3; _i < arguments.length; _i++) {
5827
5446
  args_1[_i - 3] = arguments[_i];
5828
5447
  }
5829
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5830
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_34;
5831
- if (createUserATA === void 0) { createUserATA = true; }
5832
- return __generator(this, function (_b) {
5833
- switch (_b.label) {
5834
- case 0:
5835
- publicKey = this.provider.wallet.publicKey;
5836
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5837
- rewardCustodyMint = rewardToken.mintKey;
5838
- instructions = [];
5839
- additionalSigners = [];
5840
- _b.label = 1;
5841
- case 1:
5842
- _b.trys.push([1, 5, , 6]);
5843
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5844
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5845
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5846
- _a = createUserATA;
5847
- if (!_a) return [3, 3];
5848
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5849
- case 2:
5850
- _a = !(_b.sent());
5851
- _b.label = 3;
5852
- case 3:
5853
- if (_a) {
5854
- instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
5855
- }
5856
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5857
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5858
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5859
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5860
- return [4, this.programFbnftReward.methods
5861
- .collectReward()
5862
- .accounts({
5863
- owner: publicKey,
5864
- feePayer: publicKey,
5865
- nftMint: nftMint,
5866
- nftTokenAccount: nftTokenAccount,
5867
- metadataAccount: metadataAccount,
5868
- receivingAccount: receivingTokenAccount,
5869
- rewardRecord: rewardRecord,
5870
- rewardVault: rewardVault,
5871
- rewardTokenAccount: rewardTokenAccount,
5872
- transferAuthority: nftTransferAuthority,
5873
- systemProgram: web3_js_1.SystemProgram.programId,
5874
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5875
- })
5876
- .instruction()];
5877
- case 4:
5878
- collectNftReward = _b.sent();
5879
- instructions.push(collectNftReward);
5880
- return [3, 6];
5881
- case 5:
5882
- err_34 = _b.sent();
5883
- throw err_34;
5884
- case 6: return [2, {
5885
- instructions: __spreadArray([], instructions, true),
5886
- additionalSigners: additionalSigners
5887
- }];
5888
- }
5889
- });
5890
- });
5891
- };
5892
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5893
- var args_1 = [];
5894
- for (var _i = 2; _i < arguments.length; _i++) {
5895
- args_1[_i - 2] = arguments[_i];
5896
- }
5897
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5898
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_35;
5448
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5449
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5899
5450
  if (createUserATA === void 0) { createUserATA = true; }
5900
5451
  return __generator(this, function (_b) {
5901
5452
  switch (_b.label) {
5902
5453
  case 0:
5903
5454
  publicKey = this.provider.wallet.publicKey;
5904
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5905
- rewardCustodyMint = rewardToken.mintKey;
5906
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5907
5455
  preInstructions = [];
5908
5456
  instructions = [];
5909
5457
  postInstructions = [];
@@ -5911,59 +5459,43 @@ var PerpetualsClient = (function () {
5911
5459
  _b.label = 1;
5912
5460
  case 1:
5913
5461
  _b.trys.push([1, 5, , 6]);
5914
- pool = poolConfig.poolAddress;
5915
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5916
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5462
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5463
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5464
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5917
5465
  _a = createUserATA;
5918
5466
  if (!_a) return [3, 3];
5919
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5467
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5920
5468
  case 2:
5921
5469
  _a = !(_b.sent());
5922
5470
  _b.label = 3;
5923
5471
  case 3:
5924
5472
  if (_a) {
5925
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5926
- }
5927
- tradingAccount = [];
5928
- if (nftTradingAccount) {
5929
- tradingAccount.push({
5930
- pubkey: nftTradingAccount,
5931
- isSigner: false,
5932
- isWritable: true,
5933
- });
5473
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5934
5474
  }
5935
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5936
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5937
- return [4, this.programPerpComposability.methods
5938
- .collectAndDistributeFee()
5475
+ return [4, this.program.methods
5476
+ .collectRebate()
5939
5477
  .accounts({
5940
- perpProgram: this.programId,
5941
- owner: publicKey,
5942
- receivingTokenAccount: receivingTokenAccount,
5943
- transferAuthority: poolConfig.transferAuthority,
5478
+ owner: owner,
5479
+ receivingTokenAccount: userTokenAccount,
5944
5480
  perpetuals: this.perpetuals.publicKey,
5945
- pool: pool,
5946
- feeCustody: rewardCustodyConfig.custodyAccount,
5947
- flpStakeAccount: flpStakeAccount,
5948
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5949
- systemProgram: web3_js_1.SystemProgram.programId,
5481
+ transferAuthority: poolConfig.transferAuthority,
5482
+ rebateVault: poolConfig.rebateVault,
5483
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5484
+ tokenStakeAccount: tokenStakeAccount,
5950
5485
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5951
5486
  eventAuthority: this.eventAuthority.publicKey,
5952
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5953
- fbnftRewardsProgram: this.programFbnftReward.programId,
5954
- rewardVault: rewardVault,
5955
- rewardTokenAccount: rewardTokenAccount
5487
+ program: this.programId,
5488
+ receivingTokenMint: rebateMint,
5956
5489
  })
5957
- .remainingAccounts(tradingAccount)
5958
5490
  .instruction()];
5959
5491
  case 4:
5960
- withdrawStakeInstruction = _b.sent();
5961
- instructions.push(withdrawStakeInstruction);
5492
+ collectRebateInstruction = _b.sent();
5493
+ instructions.push(collectRebateInstruction);
5962
5494
  return [3, 6];
5963
5495
  case 5:
5964
- err_35 = _b.sent();
5965
- console.log("perpClient withdrawStake error:: ", err_35);
5966
- throw err_35;
5496
+ err_28 = _b.sent();
5497
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5498
+ throw err_28;
5967
5499
  case 6: return [2, {
5968
5500
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5969
5501
  additionalSigners: additionalSigners
@@ -5972,13 +5504,60 @@ var PerpetualsClient = (function () {
5972
5504
  });
5973
5505
  });
5974
5506
  };
5507
+ this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5508
+ var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5509
+ return __generator(this, function (_a) {
5510
+ switch (_a.label) {
5511
+ case 0:
5512
+ preInstructions = [];
5513
+ instructions = [];
5514
+ postInstructions = [];
5515
+ additionalSigners = [];
5516
+ _a.label = 1;
5517
+ case 1:
5518
+ _a.trys.push([1, 3, , 4]);
5519
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5520
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5521
+ return [4, this.program.methods
5522
+ .settleRebates()
5523
+ .accounts({
5524
+ transferAuthority: poolConfig.transferAuthority,
5525
+ perpetuals: this.perpetuals.publicKey,
5526
+ pool: poolConfig.poolAddress,
5527
+ rewardCustody: rewardCustody.custodyAccount,
5528
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5529
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5530
+ rebateVault: poolConfig.rebateVault,
5531
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5532
+ tokenMint: rebateMint,
5533
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5534
+ eventAuthority: this.eventAuthority.publicKey,
5535
+ program: this.programId,
5536
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5537
+ })
5538
+ .instruction()];
5539
+ case 2:
5540
+ settleRebatesInstruction = _a.sent();
5541
+ instructions.push(settleRebatesInstruction);
5542
+ return [3, 4];
5543
+ case 3:
5544
+ err_29 = _a.sent();
5545
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5546
+ throw err_29;
5547
+ case 4: return [2, {
5548
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5549
+ additionalSigners: additionalSigners
5550
+ }];
5551
+ }
5552
+ });
5553
+ }); };
5975
5554
  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) {
5976
5555
  var args_1 = [];
5977
5556
  for (var _i = 11; _i < arguments.length; _i++) {
5978
5557
  args_1[_i - 11] = arguments[_i];
5979
5558
  }
5980
5559
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, limitPrice, reserveAmount, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
5981
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_36;
5560
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5982
5561
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5983
5562
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5984
5563
  return __generator(this, function (_c) {
@@ -6084,9 +5663,9 @@ var PerpetualsClient = (function () {
6084
5663
  instructions.push(placeLimitOrder);
6085
5664
  return [3, 10];
6086
5665
  case 9:
6087
- err_36 = _c.sent();
6088
- console.log("perpClient placeLimitOrder error:: ", err_36);
6089
- throw err_36;
5666
+ err_30 = _c.sent();
5667
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5668
+ throw err_30;
6090
5669
  case 10: return [2, {
6091
5670
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6092
5671
  additionalSigners: additionalSigners
@@ -6101,7 +5680,7 @@ var PerpetualsClient = (function () {
6101
5680
  args_1[_i - 11] = arguments[_i];
6102
5681
  }
6103
5682
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, orderId_1, limitPrice_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, orderId, limitPrice, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, createUserATA, ephemeralSignerPubkey) {
6104
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_37;
5683
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
6105
5684
  if (createUserATA === void 0) { createUserATA = true; }
6106
5685
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6107
5686
  return __generator(this, function (_b) {
@@ -6192,9 +5771,9 @@ var PerpetualsClient = (function () {
6192
5771
  instructions.push(editLimitOrder);
6193
5772
  return [3, 8];
6194
5773
  case 7:
6195
- err_37 = _b.sent();
6196
- console.log("perpClient editLimitOrder error:: ", err_37);
6197
- throw err_37;
5774
+ err_31 = _b.sent();
5775
+ console.log("perpClient editLimitOrder error:: ", err_31);
5776
+ throw err_31;
6198
5777
  case 8: return [2, {
6199
5778
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6200
5779
  additionalSigners: additionalSigners
@@ -6208,11 +5787,10 @@ var PerpetualsClient = (function () {
6208
5787
  for (var _i = 7; _i < arguments.length; _i++) {
6209
5788
  args_1[_i - 7] = arguments[_i];
6210
5789
  }
6211
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6212
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_38;
5790
+ 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) {
5791
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
6213
5792
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6214
5793
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6215
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6216
5794
  return __generator(this, function (_a) {
6217
5795
  switch (_a.label) {
6218
5796
  case 0:
@@ -6255,16 +5833,16 @@ var PerpetualsClient = (function () {
6255
5833
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6256
5834
  collateralMint: collateralCustodyConfig.mintKey,
6257
5835
  })
6258
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5836
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6259
5837
  .instruction()];
6260
5838
  case 2:
6261
5839
  executeLimitOrder = _a.sent();
6262
5840
  instructions.push(executeLimitOrder);
6263
5841
  return [3, 4];
6264
5842
  case 3:
6265
- err_38 = _a.sent();
6266
- console.log("perpClient executeLimitOrder error:: ", err_38);
6267
- throw err_38;
5843
+ err_32 = _a.sent();
5844
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5845
+ throw err_32;
6268
5846
  case 4: return [2, {
6269
5847
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6270
5848
  additionalSigners: additionalSigners
@@ -6278,11 +5856,10 @@ var PerpetualsClient = (function () {
6278
5856
  for (var _i = 8; _i < arguments.length; _i++) {
6279
5857
  args_1[_i - 8] = arguments[_i];
6280
5858
  }
6281
- return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, reserveSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, reserveSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6282
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_39;
5859
+ 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) {
5860
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6283
5861
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6284
5862
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6285
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6286
5863
  return __generator(this, function (_a) {
6287
5864
  switch (_a.label) {
6288
5865
  case 0:
@@ -6328,16 +5905,16 @@ var PerpetualsClient = (function () {
6328
5905
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6329
5906
  collateralMint: collateralCustodyConfig.mintKey,
6330
5907
  })
6331
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5908
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6332
5909
  .instruction()];
6333
5910
  case 2:
6334
5911
  executeLimitWithSwap = _a.sent();
6335
5912
  instructions.push(executeLimitWithSwap);
6336
5913
  return [3, 4];
6337
5914
  case 3:
6338
- err_39 = _a.sent();
6339
- console.log("perpClient executeLimitWithSwap error:: ", err_39);
6340
- throw err_39;
5915
+ err_33 = _a.sent();
5916
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5917
+ throw err_33;
6341
5918
  case 4: return [2, {
6342
5919
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6343
5920
  additionalSigners: additionalSigners
@@ -6347,7 +5924,7 @@ var PerpetualsClient = (function () {
6347
5924
  });
6348
5925
  };
6349
5926
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6350
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_40;
5927
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6351
5928
  return __generator(this, function (_a) {
6352
5929
  switch (_a.label) {
6353
5930
  case 0:
@@ -6395,9 +5972,9 @@ var PerpetualsClient = (function () {
6395
5972
  instructions.push(placeTriggerOrder);
6396
5973
  return [3, 4];
6397
5974
  case 3:
6398
- err_40 = _a.sent();
6399
- console.log("perpClient placeTriggerOrder error:: ", err_40);
6400
- throw err_40;
5975
+ err_34 = _a.sent();
5976
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5977
+ throw err_34;
6401
5978
  case 4: return [2, {
6402
5979
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6403
5980
  additionalSigners: additionalSigners
@@ -6406,7 +5983,7 @@ var PerpetualsClient = (function () {
6406
5983
  });
6407
5984
  }); };
6408
5985
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6409
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_41;
5986
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6410
5987
  return __generator(this, function (_a) {
6411
5988
  switch (_a.label) {
6412
5989
  case 0:
@@ -6453,9 +6030,9 @@ var PerpetualsClient = (function () {
6453
6030
  instructions.push(editTriggerOrder);
6454
6031
  return [3, 4];
6455
6032
  case 3:
6456
- err_41 = _a.sent();
6457
- console.log("perpClient editTriggerOrder error:: ", err_41);
6458
- throw err_41;
6033
+ err_35 = _a.sent();
6034
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6035
+ throw err_35;
6459
6036
  case 4: return [2, {
6460
6037
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6461
6038
  additionalSigners: additionalSigners
@@ -6464,7 +6041,7 @@ var PerpetualsClient = (function () {
6464
6041
  });
6465
6042
  }); };
6466
6043
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6467
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_42;
6044
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6468
6045
  return __generator(this, function (_a) {
6469
6046
  switch (_a.label) {
6470
6047
  case 0:
@@ -6497,9 +6074,9 @@ var PerpetualsClient = (function () {
6497
6074
  instructions.push(cancelTriggerOrder);
6498
6075
  return [3, 4];
6499
6076
  case 3:
6500
- err_42 = _a.sent();
6501
- console.log("perpClient cancelTriggerOrder error:: ", err_42);
6502
- throw err_42;
6077
+ err_36 = _a.sent();
6078
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6079
+ throw err_36;
6503
6080
  case 4: return [2, {
6504
6081
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6505
6082
  additionalSigners: additionalSigners
@@ -6508,7 +6085,7 @@ var PerpetualsClient = (function () {
6508
6085
  });
6509
6086
  }); };
6510
6087
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6511
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_43;
6088
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6512
6089
  return __generator(this, function (_a) {
6513
6090
  switch (_a.label) {
6514
6091
  case 0:
@@ -6539,9 +6116,9 @@ var PerpetualsClient = (function () {
6539
6116
  instructions.push(cancelAllTriggerOrders);
6540
6117
  return [3, 4];
6541
6118
  case 3:
6542
- err_43 = _a.sent();
6543
- console.log("perpClient cancelAllTriggerOrders error:: ", err_43);
6544
- throw err_43;
6119
+ err_37 = _a.sent();
6120
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6121
+ throw err_37;
6545
6122
  case 4: return [2, {
6546
6123
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6547
6124
  additionalSigners: additionalSigners
@@ -6554,13 +6131,12 @@ var PerpetualsClient = (function () {
6554
6131
  for (var _i = 9; _i < arguments.length; _i++) {
6555
6132
  args_1[_i - 9] = arguments[_i];
6556
6133
  }
6557
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, receivingSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, receivingSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6558
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_44;
6134
+ 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) {
6135
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_38;
6559
6136
  if (createUserATA === void 0) { createUserATA = true; }
6560
6137
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6561
6138
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6562
6139
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6563
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6564
6140
  return __generator(this, function (_e) {
6565
6141
  switch (_e.label) {
6566
6142
  case 0:
@@ -6655,16 +6231,16 @@ var PerpetualsClient = (function () {
6655
6231
  collateralMint: collateralCustodyConfig.mintKey,
6656
6232
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6657
6233
  })
6658
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6234
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6659
6235
  .instruction()];
6660
6236
  case 8:
6661
6237
  executeTriggerWithSwap = _e.sent();
6662
6238
  instructions.push(executeTriggerWithSwap);
6663
6239
  return [3, 10];
6664
6240
  case 9:
6665
- err_44 = _e.sent();
6666
- console.log("perpClient executeTriggerWithSwap error:: ", err_44);
6667
- throw err_44;
6241
+ err_38 = _e.sent();
6242
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6243
+ throw err_38;
6668
6244
  case 10: return [2, {
6669
6245
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6670
6246
  additionalSigners: additionalSigners
@@ -6678,13 +6254,12 @@ var PerpetualsClient = (function () {
6678
6254
  for (var _i = 8; _i < arguments.length; _i++) {
6679
6255
  args_1[_i - 8] = arguments[_i];
6680
6256
  }
6681
- return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
6682
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_45;
6257
+ 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) {
6258
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6683
6259
  if (createUserATA === void 0) { createUserATA = true; }
6684
6260
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6685
6261
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6686
6262
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6687
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6688
6263
  return __generator(this, function (_b) {
6689
6264
  switch (_b.label) {
6690
6265
  case 0:
@@ -6744,16 +6319,16 @@ var PerpetualsClient = (function () {
6744
6319
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6745
6320
  receivingMint: collateralCustodyConfig.mintKey
6746
6321
  })
6747
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6322
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6748
6323
  .instruction()];
6749
6324
  case 6:
6750
6325
  executeTriggerOrder = _b.sent();
6751
6326
  instructions.push(executeTriggerOrder);
6752
6327
  return [3, 8];
6753
6328
  case 7:
6754
- err_45 = _b.sent();
6755
- console.log("perpClient executeTriggerOrder error:: ", err_45);
6756
- throw err_45;
6329
+ err_39 = _b.sent();
6330
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6331
+ throw err_39;
6757
6332
  case 8: return [2, {
6758
6333
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6759
6334
  additionalSigners: additionalSigners
@@ -6768,7 +6343,7 @@ var PerpetualsClient = (function () {
6768
6343
  args_1[_i - 5] = arguments[_i];
6769
6344
  }
6770
6345
  return __awaiter(_this, __spreadArray([userInputTokenSymbol_1, userOutputTokenSymbol_1, amountIn_1, minAmountOut_1, poolConfig_1], args_1, true), void 0, function (userInputTokenSymbol, userOutputTokenSymbol, amountIn, minAmountOut, poolConfig, useFeesPool, createUserATA, unWrapSol, skipBalanceChecks, ephemeralSignerPubkey) {
6771
- var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_46;
6346
+ var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_40;
6772
6347
  if (useFeesPool === void 0) { useFeesPool = false; }
6773
6348
  if (createUserATA === void 0) { createUserATA = true; }
6774
6349
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6973,9 +6548,9 @@ var PerpetualsClient = (function () {
6973
6548
  }
6974
6549
  return [3, 20];
6975
6550
  case 19:
6976
- err_46 = _g.sent();
6977
- console.error("perpClient Swap error:: ", err_46);
6978
- throw err_46;
6551
+ err_40 = _g.sent();
6552
+ console.error("perpClient Swap error:: ", err_40);
6553
+ throw err_40;
6979
6554
  case 20: return [2, {
6980
6555
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6981
6556
  additionalSigners: additionalSigners
@@ -6985,7 +6560,7 @@ var PerpetualsClient = (function () {
6985
6560
  });
6986
6561
  };
6987
6562
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6988
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_47;
6563
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6989
6564
  return __generator(this, function (_b) {
6990
6565
  switch (_b.label) {
6991
6566
  case 0:
@@ -7030,11 +6605,7 @@ var PerpetualsClient = (function () {
7030
6605
  rewardCustody: rewardCustody.custodyAccount,
7031
6606
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
7032
6607
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
7033
- custody: custody.custodyAccount,
7034
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
7035
- custodyTokenAccount: custody.tokenAccount,
7036
6608
  eventAuthority: this.eventAuthority.publicKey,
7037
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7038
6609
  program: this.programId,
7039
6610
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
7040
6611
  })
@@ -7045,9 +6616,9 @@ var PerpetualsClient = (function () {
7045
6616
  instructions.push(inx);
7046
6617
  return [3, 4];
7047
6618
  case 3:
7048
- err_47 = _b.sent();
7049
- console.error("perpClient Swap error:: ", err_47);
7050
- throw err_47;
6619
+ err_41 = _b.sent();
6620
+ console.error("perpClient Swap error:: ", err_41);
6621
+ throw err_41;
7051
6622
  case 4: return [2, {
7052
6623
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7053
6624
  additionalSigners: additionalSigners
@@ -7056,7 +6627,7 @@ var PerpetualsClient = (function () {
7056
6627
  });
7057
6628
  }); };
7058
6629
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7059
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_48;
6630
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
7060
6631
  return __generator(this, function (_d) {
7061
6632
  switch (_d.label) {
7062
6633
  case 0:
@@ -7104,9 +6675,9 @@ var PerpetualsClient = (function () {
7104
6675
  instructions.push(setLpTokenPriceInstruction);
7105
6676
  return [3, 4];
7106
6677
  case 3:
7107
- err_48 = _d.sent();
7108
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_48);
7109
- throw err_48;
6678
+ err_42 = _d.sent();
6679
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6680
+ throw err_42;
7110
6681
  case 4: return [2, {
7111
6682
  instructions: __spreadArray([], instructions, true),
7112
6683
  additionalSigners: additionalSigners
@@ -7154,7 +6725,7 @@ var PerpetualsClient = (function () {
7154
6725
  });
7155
6726
  }); };
7156
6727
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
7157
- var adminMetas, _i, admins_2, admin, err_49;
6728
+ var adminMetas, _i, admins_2, admin, err_43;
7158
6729
  return __generator(this, function (_a) {
7159
6730
  switch (_a.label) {
7160
6731
  case 0:
@@ -7184,16 +6755,16 @@ var PerpetualsClient = (function () {
7184
6755
  _a.sent();
7185
6756
  return [3, 4];
7186
6757
  case 3:
7187
- err_49 = _a.sent();
6758
+ err_43 = _a.sent();
7188
6759
  if (this.printErrors) {
7189
- console.error("setAdminSigners err:", err_49);
6760
+ console.error("setAdminSigners err:", err_43);
7190
6761
  }
7191
- throw err_49;
6762
+ throw err_43;
7192
6763
  case 4: return [2];
7193
6764
  }
7194
6765
  });
7195
6766
  }); };
7196
- this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor) { return __awaiter(_this, void 0, void 0, function () {
6767
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor, stakingFeeBoostBps, minLpPriceUsd, maxLpPriceUsd, thresholdUsd) { return __awaiter(_this, void 0, void 0, function () {
7197
6768
  return __generator(this, function (_a) {
7198
6769
  switch (_a.label) {
7199
6770
  case 0: return [4, this.program.methods
@@ -7205,7 +6776,11 @@ var PerpetualsClient = (function () {
7205
6776
  metadataTitle: metadataTitle,
7206
6777
  metadataUri: metadataUri,
7207
6778
  stakingFeeShareBps: stakingFeeShareBps,
7208
- vpVolumeFactor: vpVolumeFactor
6779
+ vpVolumeFactor: vpVolumeFactor,
6780
+ stakingFeeBoostBps: stakingFeeBoostBps,
6781
+ minLpPriceUsd: minLpPriceUsd,
6782
+ maxLpPriceUsd: maxLpPriceUsd,
6783
+ thresholdUsd: thresholdUsd
7209
6784
  })
7210
6785
  .accounts({
7211
6786
  admin: this.provider.wallet.publicKey,
@@ -7253,7 +6828,7 @@ var PerpetualsClient = (function () {
7253
6828
  }
7254
6829
  });
7255
6830
  }); };
7256
- this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
6831
+ 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 () {
7257
6832
  var trx_id, error_3;
7258
6833
  return __generator(this, function (_a) {
7259
6834
  switch (_a.label) {
@@ -7271,6 +6846,9 @@ var PerpetualsClient = (function () {
7271
6846
  fees: fees,
7272
6847
  borrowRate: borrowRate,
7273
6848
  ratios: ratios,
6849
+ rewardThreshold: rewardThreshold,
6850
+ minReserveUsd: minReserveUsd,
6851
+ limitPriceBufferBps: limitPriceBufferBps
7274
6852
  })
7275
6853
  .accounts({
7276
6854
  admin: this.admin,
@@ -7377,7 +6955,7 @@ var PerpetualsClient = (function () {
7377
6955
  });
7378
6956
  }); };
7379
6957
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7380
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_50;
6958
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7381
6959
  return __generator(this, function (_a) {
7382
6960
  switch (_a.label) {
7383
6961
  case 0:
@@ -7410,9 +6988,9 @@ var PerpetualsClient = (function () {
7410
6988
  instructions.push(withdrawFeesIx);
7411
6989
  return [3, 5];
7412
6990
  case 4:
7413
- err_50 = _a.sent();
7414
- console.log("perpClient setPool error:: ", err_50);
7415
- throw err_50;
6991
+ err_44 = _a.sent();
6992
+ console.log("perpClient setPool error:: ", err_44);
6993
+ throw err_44;
7416
6994
  case 5: return [2, {
7417
6995
  instructions: __spreadArray([], instructions, true),
7418
6996
  additionalSigners: additionalSigners
@@ -7421,7 +6999,7 @@ var PerpetualsClient = (function () {
7421
6999
  });
7422
7000
  }); };
7423
7001
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7424
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_51;
7002
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7425
7003
  return __generator(this, function (_a) {
7426
7004
  switch (_a.label) {
7427
7005
  case 0:
@@ -7455,9 +7033,9 @@ var PerpetualsClient = (function () {
7455
7033
  instructions.push(moveProtocolFeesIx);
7456
7034
  return [3, 4];
7457
7035
  case 3:
7458
- err_51 = _a.sent();
7459
- console.log("perpClient setPool error:: ", err_51);
7460
- throw err_51;
7036
+ err_45 = _a.sent();
7037
+ console.log("perpClient setPool error:: ", err_45);
7038
+ throw err_45;
7461
7039
  case 4: return [2, {
7462
7040
  instructions: __spreadArray([], instructions, true),
7463
7041
  additionalSigners: additionalSigners
@@ -7466,7 +7044,7 @@ var PerpetualsClient = (function () {
7466
7044
  });
7467
7045
  }); };
7468
7046
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7469
- var publicKey, setProtocolFeeShareBpsIx, err_52;
7047
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7470
7048
  return __generator(this, function (_a) {
7471
7049
  switch (_a.label) {
7472
7050
  case 0:
@@ -7486,15 +7064,15 @@ var PerpetualsClient = (function () {
7486
7064
  setProtocolFeeShareBpsIx = _a.sent();
7487
7065
  return [2, setProtocolFeeShareBpsIx];
7488
7066
  case 2:
7489
- err_52 = _a.sent();
7490
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_52);
7491
- throw err_52;
7067
+ err_46 = _a.sent();
7068
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7069
+ throw err_46;
7492
7070
  case 3: return [2];
7493
7071
  }
7494
7072
  });
7495
7073
  }); };
7496
7074
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7497
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_53;
7075
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7498
7076
  return __generator(this, function (_a) {
7499
7077
  switch (_a.label) {
7500
7078
  case 0:
@@ -7521,9 +7099,9 @@ var PerpetualsClient = (function () {
7521
7099
  instructions.push(setPermissionsInstruction);
7522
7100
  return [3, 4];
7523
7101
  case 3:
7524
- err_53 = _a.sent();
7525
- console.log("perpClient setPool error:: ", err_53);
7526
- throw err_53;
7102
+ err_47 = _a.sent();
7103
+ console.log("perpClient setPool error:: ", err_47);
7104
+ throw err_47;
7527
7105
  case 4: return [2, {
7528
7106
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7529
7107
  additionalSigners: additionalSigners
@@ -7532,7 +7110,7 @@ var PerpetualsClient = (function () {
7532
7110
  });
7533
7111
  }); };
7534
7112
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7535
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_54;
7113
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7536
7114
  var _f;
7537
7115
  return __generator(this, function (_g) {
7538
7116
  switch (_g.label) {
@@ -7593,9 +7171,9 @@ var PerpetualsClient = (function () {
7593
7171
  instructions.push(reimburse);
7594
7172
  return [3, 5];
7595
7173
  case 4:
7596
- err_54 = _g.sent();
7597
- console.log("perpClient setPool error:: ", err_54);
7598
- throw err_54;
7174
+ err_48 = _g.sent();
7175
+ console.log("perpClient setPool error:: ", err_48);
7176
+ throw err_48;
7599
7177
  case 5: return [2, {
7600
7178
  instructions: __spreadArray([], instructions, true),
7601
7179
  additionalSigners: additionalSigners
@@ -7604,7 +7182,7 @@ var PerpetualsClient = (function () {
7604
7182
  });
7605
7183
  }); };
7606
7184
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7607
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_55;
7185
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7608
7186
  return __generator(this, function (_a) {
7609
7187
  switch (_a.label) {
7610
7188
  case 0:
@@ -7638,9 +7216,9 @@ var PerpetualsClient = (function () {
7638
7216
  instructions.push(setInternalOraclePrice);
7639
7217
  return [3, 4];
7640
7218
  case 3:
7641
- err_55 = _a.sent();
7642
- console.log("perpClient setInternalOracleAccount error:: ", err_55);
7643
- throw err_55;
7219
+ err_49 = _a.sent();
7220
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7221
+ throw err_49;
7644
7222
  case 4: return [2, {
7645
7223
  instructions: __spreadArray([], instructions, true),
7646
7224
  additionalSigners: additionalSigners
@@ -7649,7 +7227,7 @@ var PerpetualsClient = (function () {
7649
7227
  });
7650
7228
  }); };
7651
7229
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7652
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_56;
7230
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7653
7231
  return __generator(this, function (_a) {
7654
7232
  switch (_a.label) {
7655
7233
  case 0:
@@ -7695,9 +7273,9 @@ var PerpetualsClient = (function () {
7695
7273
  instructions.push(setInternalOraclePrice);
7696
7274
  return [3, 4];
7697
7275
  case 3:
7698
- err_56 = _a.sent();
7699
- console.log("perpClient setInternalOracleAccount error:: ", err_56);
7700
- throw err_56;
7276
+ err_50 = _a.sent();
7277
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7278
+ throw err_50;
7701
7279
  case 4: return [2, {
7702
7280
  instructions: __spreadArray([], instructions, true),
7703
7281
  additionalSigners: additionalSigners
@@ -7706,7 +7284,7 @@ var PerpetualsClient = (function () {
7706
7284
  });
7707
7285
  }); };
7708
7286
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7709
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_57;
7287
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7710
7288
  return __generator(this, function (_a) {
7711
7289
  switch (_a.label) {
7712
7290
  case 0:
@@ -7746,9 +7324,9 @@ var PerpetualsClient = (function () {
7746
7324
  instructions.push(setInternalOraclePrice);
7747
7325
  return [3, 4];
7748
7326
  case 3:
7749
- err_57 = _a.sent();
7750
- console.log("perpClient setInternalOracleAccount error:: ", err_57);
7751
- throw err_57;
7327
+ err_51 = _a.sent();
7328
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7329
+ throw err_51;
7752
7330
  case 4: return [2, {
7753
7331
  instructions: __spreadArray([], instructions, true),
7754
7332
  additionalSigners: additionalSigners
@@ -7757,7 +7335,7 @@ var PerpetualsClient = (function () {
7757
7335
  });
7758
7336
  }); };
7759
7337
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7760
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_58;
7338
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7761
7339
  return __generator(this, function (_a) {
7762
7340
  switch (_a.label) {
7763
7341
  case 0:
@@ -7795,8 +7373,8 @@ var PerpetualsClient = (function () {
7795
7373
  instructions.push(renameFlp);
7796
7374
  return [3, 4];
7797
7375
  case 3:
7798
- err_58 = _a.sent();
7799
- console.log("perpClient renameFlp error:: ", err_58);
7376
+ err_52 = _a.sent();
7377
+ console.log("perpClient renameFlp error:: ", err_52);
7800
7378
  return [3, 4];
7801
7379
  case 4: return [2, {
7802
7380
  instructions: __spreadArray([], instructions, true),
@@ -7806,7 +7384,7 @@ var PerpetualsClient = (function () {
7806
7384
  });
7807
7385
  }); };
7808
7386
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7809
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_59;
7387
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7810
7388
  return __generator(this, function (_a) {
7811
7389
  switch (_a.label) {
7812
7390
  case 0:
@@ -7844,9 +7422,9 @@ var PerpetualsClient = (function () {
7844
7422
  instructions.push(initStakeInstruction);
7845
7423
  return [3, 4];
7846
7424
  case 3:
7847
- err_59 = _a.sent();
7848
- console.log("perpClient InitStaking error:: ", err_59);
7849
- throw err_59;
7425
+ err_53 = _a.sent();
7426
+ console.log("perpClient InitStaking error:: ", err_53);
7427
+ throw err_53;
7850
7428
  case 4: return [2, {
7851
7429
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7852
7430
  additionalSigners: additionalSigners
@@ -7855,7 +7433,7 @@ var PerpetualsClient = (function () {
7855
7433
  });
7856
7434
  }); };
7857
7435
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7858
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_60;
7436
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7859
7437
  return __generator(this, function (_a) {
7860
7438
  switch (_a.label) {
7861
7439
  case 0:
@@ -7884,7 +7462,6 @@ var PerpetualsClient = (function () {
7884
7462
  transferAuthority: poolConfig.transferAuthority,
7885
7463
  perpetuals: this.perpetuals.publicKey,
7886
7464
  pool: poolConfig.poolAddress,
7887
- custody: rewardCustodyConfig.custodyAccount,
7888
7465
  lpTokenMint: poolConfig.stakedLpTokenMint,
7889
7466
  compoundingVault: compoundingVault,
7890
7467
  compoundingTokenMint: compoundingTokenMint,
@@ -7900,9 +7477,9 @@ var PerpetualsClient = (function () {
7900
7477
  instructions.push(initCompoundingInstruction);
7901
7478
  return [3, 4];
7902
7479
  case 3:
7903
- err_60 = _a.sent();
7904
- console.log("perpClient initCompounding error:: ", err_60);
7905
- throw err_60;
7480
+ err_54 = _a.sent();
7481
+ console.log("perpClient initCompounding error:: ", err_54);
7482
+ throw err_54;
7906
7483
  case 4: return [2, {
7907
7484
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7908
7485
  additionalSigners: additionalSigners
@@ -7911,7 +7488,7 @@ var PerpetualsClient = (function () {
7911
7488
  });
7912
7489
  }); };
7913
7490
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7914
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_61;
7491
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7915
7492
  return __generator(this, function (_a) {
7916
7493
  switch (_a.label) {
7917
7494
  case 0:
@@ -7952,9 +7529,9 @@ var PerpetualsClient = (function () {
7952
7529
  instructions.push(initTokenVaultInstruction);
7953
7530
  return [3, 4];
7954
7531
  case 3:
7955
- err_61 = _a.sent();
7956
- console.log("perpClient InitTokenVaultInstruction error:: ", err_61);
7957
- throw err_61;
7532
+ err_55 = _a.sent();
7533
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7534
+ throw err_55;
7958
7535
  case 4: return [2, {
7959
7536
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7960
7537
  additionalSigners: additionalSigners
@@ -7963,7 +7540,7 @@ var PerpetualsClient = (function () {
7963
7540
  });
7964
7541
  }); };
7965
7542
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7966
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_62;
7543
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7967
7544
  return __generator(this, function (_a) {
7968
7545
  switch (_a.label) {
7969
7546
  case 0:
@@ -7994,9 +7571,9 @@ var PerpetualsClient = (function () {
7994
7571
  instructions.push(setTokenVaultConfigInstruction);
7995
7572
  return [3, 4];
7996
7573
  case 3:
7997
- err_62 = _a.sent();
7998
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_62);
7999
- throw err_62;
7574
+ err_56 = _a.sent();
7575
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7576
+ throw err_56;
8000
7577
  case 4: return [2, {
8001
7578
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8002
7579
  additionalSigners: additionalSigners
@@ -8005,7 +7582,7 @@ var PerpetualsClient = (function () {
8005
7582
  });
8006
7583
  }); };
8007
7584
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8008
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_63;
7585
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
8009
7586
  return __generator(this, function (_a) {
8010
7587
  switch (_a.label) {
8011
7588
  case 0:
@@ -8044,9 +7621,59 @@ var PerpetualsClient = (function () {
8044
7621
  instructions.push(withdrawInstantFeeInstruction);
8045
7622
  return [3, 6];
8046
7623
  case 5:
8047
- err_63 = _a.sent();
8048
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_63);
8049
- throw err_63;
7624
+ err_57 = _a.sent();
7625
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7626
+ throw err_57;
7627
+ case 6: return [2, {
7628
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7629
+ additionalSigners: additionalSigners
7630
+ }];
7631
+ }
7632
+ });
7633
+ }); };
7634
+ this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7635
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7636
+ return __generator(this, function (_a) {
7637
+ switch (_a.label) {
7638
+ case 0:
7639
+ publicKey = this.provider.wallet.publicKey;
7640
+ preInstructions = [];
7641
+ instructions = [];
7642
+ postInstructions = [];
7643
+ additionalSigners = [];
7644
+ _a.label = 1;
7645
+ case 1:
7646
+ _a.trys.push([1, 5, , 6]);
7647
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, publicKey, true)];
7648
+ case 2:
7649
+ receivingTokenAccount = _a.sent();
7650
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
7651
+ case 3:
7652
+ if (!(_a.sent())) {
7653
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, poolConfig.tokenMint));
7654
+ }
7655
+ return [4, this.program.methods
7656
+ .withdrawUnclaimedTokens({})
7657
+ .accounts({
7658
+ admin: publicKey,
7659
+ multisig: this.multisig.publicKey,
7660
+ perpetuals: this.perpetuals.publicKey,
7661
+ transferAuthority: poolConfig.transferAuthority,
7662
+ tokenVault: poolConfig.tokenVault,
7663
+ tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
7664
+ receivingTokenAccount: receivingTokenAccount,
7665
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7666
+ receivingTokenMint: poolConfig.tokenMint,
7667
+ })
7668
+ .instruction()];
7669
+ case 4:
7670
+ withdrawUnclaimedTokensInstruction = _a.sent();
7671
+ instructions.push(withdrawUnclaimedTokensInstruction);
7672
+ return [3, 6];
7673
+ case 5:
7674
+ err_58 = _a.sent();
7675
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7676
+ throw err_58;
8050
7677
  case 6: return [2, {
8051
7678
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8052
7679
  additionalSigners: additionalSigners
@@ -8055,7 +7682,7 @@ var PerpetualsClient = (function () {
8055
7682
  });
8056
7683
  }); };
8057
7684
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8058
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_64;
7685
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
8059
7686
  return __generator(this, function (_a) {
8060
7687
  switch (_a.label) {
8061
7688
  case 0:
@@ -8092,9 +7719,55 @@ var PerpetualsClient = (function () {
8092
7719
  instructions.push(initRevenueTokenAccountInstruction);
8093
7720
  return [3, 4];
8094
7721
  case 3:
8095
- err_64 = _a.sent();
8096
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_64);
8097
- throw err_64;
7722
+ err_59 = _a.sent();
7723
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7724
+ throw err_59;
7725
+ case 4: return [2, {
7726
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7727
+ additionalSigners: additionalSigners
7728
+ }];
7729
+ }
7730
+ });
7731
+ }); };
7732
+ this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7733
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7734
+ return __generator(this, function (_a) {
7735
+ switch (_a.label) {
7736
+ case 0:
7737
+ publicKey = this.provider.wallet.publicKey;
7738
+ preInstructions = [];
7739
+ instructions = [];
7740
+ postInstructions = [];
7741
+ additionalSigners = [];
7742
+ _a.label = 1;
7743
+ case 1:
7744
+ _a.trys.push([1, 3, , 4]);
7745
+ rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7746
+ return [4, this.program.methods
7747
+ .initRebateVault({
7748
+ allowRebatePayout: allowRebatePayout
7749
+ })
7750
+ .accounts({
7751
+ admin: publicKey,
7752
+ multisig: this.multisig.publicKey,
7753
+ transferAuthority: poolConfig.transferAuthority,
7754
+ perpetuals: this.perpetuals.publicKey,
7755
+ rebateMint: rebateCustodyMint,
7756
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
7757
+ rebateVault: poolConfig.rebateVault,
7758
+ systemProgram: web3_js_1.SystemProgram.programId,
7759
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7760
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
7761
+ })
7762
+ .instruction()];
7763
+ case 2:
7764
+ initRebateVaultInstruction = _a.sent();
7765
+ instructions.push(initRebateVaultInstruction);
7766
+ return [3, 4];
7767
+ case 3:
7768
+ err_60 = _a.sent();
7769
+ console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7770
+ throw err_60;
8098
7771
  case 4: return [2, {
8099
7772
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8100
7773
  additionalSigners: additionalSigners
@@ -8103,7 +7776,7 @@ var PerpetualsClient = (function () {
8103
7776
  });
8104
7777
  }); };
8105
7778
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8106
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_65;
7779
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
8107
7780
  return __generator(this, function (_a) {
8108
7781
  switch (_a.label) {
8109
7782
  case 0:
@@ -8142,9 +7815,9 @@ var PerpetualsClient = (function () {
8142
7815
  instructions.push(distributeTokenRewardInstruction);
8143
7816
  return [3, 4];
8144
7817
  case 3:
8145
- err_65 = _a.sent();
8146
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_65);
8147
- throw err_65;
7818
+ err_61 = _a.sent();
7819
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7820
+ throw err_61;
8148
7821
  case 4: return [2, {
8149
7822
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8150
7823
  additionalSigners: additionalSigners
@@ -8153,7 +7826,7 @@ var PerpetualsClient = (function () {
8153
7826
  });
8154
7827
  }); };
8155
7828
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
8156
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_66;
7829
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
8157
7830
  return __generator(this, function (_a) {
8158
7831
  switch (_a.label) {
8159
7832
  case 0:
@@ -8181,9 +7854,9 @@ var PerpetualsClient = (function () {
8181
7854
  instructions.push(setTokenStakeLevelInstruction);
8182
7855
  return [3, 4];
8183
7856
  case 3:
8184
- err_66 = _a.sent();
8185
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_66);
8186
- throw err_66;
7857
+ err_62 = _a.sent();
7858
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7859
+ throw err_62;
8187
7860
  case 4: return [2, {
8188
7861
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8189
7862
  additionalSigners: additionalSigners
@@ -8192,7 +7865,7 @@ var PerpetualsClient = (function () {
8192
7865
  });
8193
7866
  }); };
8194
7867
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8195
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_67;
7868
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8196
7869
  return __generator(this, function (_a) {
8197
7870
  switch (_a.label) {
8198
7871
  case 0:
@@ -8224,9 +7897,9 @@ var PerpetualsClient = (function () {
8224
7897
  instructions.push(setTokenRewardInstruction);
8225
7898
  return [3, 4];
8226
7899
  case 3:
8227
- err_67 = _a.sent();
8228
- console.log("perpClient setTokenRewardInstruction error:: ", err_67);
8229
- throw err_67;
7900
+ err_63 = _a.sent();
7901
+ console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7902
+ throw err_63;
8230
7903
  case 4: return [2, {
8231
7904
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8232
7905
  additionalSigners: additionalSigners
@@ -8235,7 +7908,7 @@ var PerpetualsClient = (function () {
8235
7908
  });
8236
7909
  }); };
8237
7910
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
8238
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_68;
7911
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8239
7912
  return __generator(this, function (_a) {
8240
7913
  switch (_a.label) {
8241
7914
  case 0:
@@ -8264,9 +7937,9 @@ var PerpetualsClient = (function () {
8264
7937
  instructions.push(resizeInternalOracleInstruction);
8265
7938
  return [3, 4];
8266
7939
  case 3:
8267
- err_68 = _a.sent();
8268
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_68);
8269
- throw err_68;
7940
+ err_64 = _a.sent();
7941
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7942
+ throw err_64;
8270
7943
  case 4: return [2, {
8271
7944
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8272
7945
  additionalSigners: additionalSigners