flash-sdk 9.0.5-alpha.9 → 9.1.0-alpha.1

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