flash-sdk 10.5.1 → 10.5.3-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
20
20
  });
21
21
  };
22
22
  var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
25
  function verb(n) { return function (v) { return step([n, v]); }; }
26
26
  function step(op) {
27
27
  if (f) throw new TypeError("Generator is already executing.");
@@ -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,24 +642,41 @@ var PerpetualsClient = (function () {
638
642
  var averageEntryPrice = totalValue.div(totalSize);
639
643
  return averageEntryPrice;
640
644
  };
641
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
642
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
643
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
644
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
645
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
645
+ this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
646
+ var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
647
+ var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
648
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
649
+ var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
650
+ var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
651
+ var currentMarginUsd = constants_1.BN_ZERO;
652
+ if (isInitial) {
653
+ currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
654
+ }
655
+ else {
656
+ currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
657
+ }
658
+ if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
659
+ return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
646
660
  }
647
661
  else {
648
662
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
649
663
  }
650
664
  };
651
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
665
+ this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
666
+ positionAccount = positionAccount.clone();
667
+ positionAccount.sizeUsd = finalSizeUsd;
668
+ positionAccount.collateralUsd = finalCollateralUsd;
669
+ return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
670
+ };
671
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd, enableDebuglogs) {
672
+ if (enableDebuglogs === void 0) { enableDebuglogs = false; }
652
673
  var finalCollateralAmount = constants_1.BN_ZERO;
653
674
  if (!inputDeltaAmount.isZero()) {
654
675
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
655
676
  finalCollateralAmount = inputDeltaAmount;
656
677
  }
657
678
  else {
658
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
679
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
659
680
  finalCollateralAmount = swapAmountOut;
660
681
  }
661
682
  }
@@ -681,11 +702,13 @@ var PerpetualsClient = (function () {
681
702
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
682
703
  }
683
704
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
684
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
685
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
686
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
705
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals).add(positionAccount.collateralUsd);
706
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
687
707
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
688
708
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
709
+ if (enableDebuglogs) {
710
+ console.log("SDK logs : finalCollateralUsd:", finalCollateralUsd.toString(), "finalCollateralAmount:", finalCollateralAmount.toString(), "sizeAmount:", sizeAmount.toString(), "sizeAmountUsd:", sizeAmountUsd.toString(), "sizeDeltaAmount:", sizeDeltaAmount.toString(), "sizeUsd:", sizeUsd.toString(), "currentCollateralUsdIncludingPnl:", currentCollateralUsdIncludingPnl.toString(), "finalCollateralUsd :", finalCollateralUsd.toString(), "pnlUsd :", pnlUsd.toString());
711
+ }
689
712
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
690
713
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
691
714
  }
@@ -693,81 +716,22 @@ var PerpetualsClient = (function () {
693
716
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
694
717
  }
695
718
  };
696
- this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
697
- if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
698
- if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
699
- throw new Error("Delta Amounts cannot be negative.");
700
- }
701
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
702
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
703
- if (positionAccount === null) {
704
- var data = __assign({}, types_1.DEFAULT_POSITION);
705
- positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
706
- var sizeUsd_1 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
707
- positionAccount.sizeUsd = sizeUsd_1;
708
- positionAccount.sizeDecimals = targetCustodyAccount.decimals;
709
- positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
710
- positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
711
- }
712
- else {
713
- positionAccount = positionAccount.clone();
714
- var positionEntryPrice = OraclePrice_1.OraclePrice.from({
715
- price: positionAccount.entryPrice.price,
716
- exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
717
- confidence: constants_1.BN_ZERO,
718
- timestamp: constants_1.BN_ZERO
719
- });
720
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
721
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
722
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
723
- }
724
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
725
- positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
726
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
727
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
728
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
729
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
730
- var feeUsd = constants_1.BN_ZERO;
731
- var feeAmount = constants_1.BN_ZERO;
732
- var feeUsdAfterDiscount = constants_1.BN_ZERO;
733
- var feeAmountAfterDiscount = constants_1.BN_ZERO;
734
- if (positionAccount !== null && sizeDeltaAmount.isZero()) {
735
- }
736
- else {
737
- feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
738
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
739
- if (discountBps.gt(constants_1.BN_ZERO)) {
740
- feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
741
- feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
742
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
743
- }
744
- else {
745
- feeUsdAfterDiscount = feeUsd;
746
- feeAmountAfterDiscount = feeAmount;
747
- }
748
- }
749
- return {
750
- entryOraclePrice: entryOraclePrice,
751
- feeUsd: feeUsd,
752
- feeAmount: feeAmount,
753
- feeUsdAfterDiscount: feeUsdAfterDiscount,
754
- feeAmountAfterDiscount: feeAmountAfterDiscount,
755
- liquidationPrice: liquidationPrice
756
- };
757
- };
758
719
  this.getEntryPriceAndFeeSyncV2 = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps, enableLogs) {
759
720
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
760
721
  if (enableLogs === void 0) { enableLogs = false; }
761
722
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
762
723
  throw new Error("Delta Amounts cannot be negative.");
763
724
  }
764
- var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
765
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
725
+ var sizeDeltaUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
726
+ var entryDeltaOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeDeltaUsd);
727
+ var entryAvgOraclePrice;
728
+ var lockAndUnsettledFeeUsd = constants_1.BN_ZERO;
766
729
  if (positionAccount === null) {
767
730
  var data = __assign({}, types_1.DEFAULT_POSITION);
768
731
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
769
- var sizeUsd_2 = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
770
- positionAccount.sizeUsd = sizeUsd_2;
732
+ entryAvgOraclePrice = entryDeltaOraclePrice;
733
+ var sizeUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
734
+ positionAccount.sizeUsd = sizeUsd;
771
735
  positionAccount.sizeDecimals = targetCustodyAccount.decimals;
772
736
  positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
773
737
  positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
@@ -780,16 +744,17 @@ var PerpetualsClient = (function () {
780
744
  confidence: constants_1.BN_ZERO,
781
745
  timestamp: constants_1.BN_ZERO
782
746
  });
783
- entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
784
- var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
785
- positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
747
+ lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
748
+ entryAvgOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryDeltaOraclePrice.price, sizeDeltaAmount);
749
+ var sizeDeltaUsd_1 = entryAvgOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
750
+ positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd_1);
786
751
  }
787
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
752
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
753
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
754
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
788
755
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
789
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
790
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
791
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
792
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
756
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryAvgOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
757
+ var sizeAmountUsd = entryDeltaOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
793
758
  var feeUsd = constants_1.BN_ZERO;
794
759
  var feeAmount = constants_1.BN_ZERO;
795
760
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -798,11 +763,11 @@ var PerpetualsClient = (function () {
798
763
  }
799
764
  else {
800
765
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
801
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
766
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
802
767
  if (discountBps.gt(constants_1.BN_ZERO)) {
803
768
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
804
769
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
805
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
770
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
806
771
  }
807
772
  else {
808
773
  feeUsdAfterDiscount = feeUsd;
@@ -822,7 +787,8 @@ var PerpetualsClient = (function () {
822
787
  console.log("volitlity fee zero:", "divergenceBps", divergenceBps.toString(), "maxDivergenceBps", targetCustodyAccount.oracle.maxDivergenceBps.toString());
823
788
  }
824
789
  return {
825
- entryOraclePrice: entryOraclePrice,
790
+ entryDeltaOraclePrice: entryDeltaOraclePrice,
791
+ entryAvgOraclePrice: entryAvgOraclePrice,
826
792
  feeUsd: feeUsd,
827
793
  feeAmount: feeAmount,
828
794
  vbFeeUsd: vbFeeUsd,
@@ -861,25 +827,26 @@ var PerpetualsClient = (function () {
861
827
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
862
828
  throw new Error("Delta Amounts cannot be negative ");
863
829
  }
864
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
865
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
866
830
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
867
831
  throw new Error("cannot remove/close more than collateral/Size");
868
832
  }
869
833
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
870
834
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
871
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
835
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
836
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
837
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
838
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
872
839
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
873
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
840
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
874
841
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
875
842
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
876
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
843
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
877
844
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
878
845
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
879
846
  if (discountBps.gt(constants_1.BN_ZERO)) {
880
847
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
881
848
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
882
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
849
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
883
850
  }
884
851
  else {
885
852
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -889,7 +856,7 @@ var PerpetualsClient = (function () {
889
856
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
890
857
  });
891
858
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
892
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
859
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
893
860
  return {
894
861
  exitOraclePrice: exitOraclePrice,
895
862
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -902,13 +869,11 @@ var PerpetualsClient = (function () {
902
869
  };
903
870
  };
904
871
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
905
- if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero()
906
- ||
907
- sizeUsd.isZero()) {
872
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
908
873
  return constants_1.BN_ZERO;
909
874
  }
910
875
  var slope = ((targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin)).mul(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))))
911
- .div(targetCustodyAccount.pricing.maxPositionLockedUsd);
876
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
912
877
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
913
878
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
914
879
  return finalSpread;
@@ -923,21 +888,11 @@ var PerpetualsClient = (function () {
923
888
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
924
889
  return exitOraclePrice;
925
890
  };
926
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
927
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
928
- if ((0, types_1.isVariant)(side, 'long')) {
929
- return minPrice;
930
- }
931
- else {
932
- return maxPrice;
933
- }
934
- };
935
891
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
936
892
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
937
893
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
938
894
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
939
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
940
- .multipliedBy(collateralTokenMinPriceUi);
895
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
941
896
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
942
897
  if (!discountBps.isZero()) {
943
898
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -945,20 +900,20 @@ var PerpetualsClient = (function () {
945
900
  }
946
901
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
947
902
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
948
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
949
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
903
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
904
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
950
905
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
951
906
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
952
907
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
953
908
  };
954
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
909
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
955
910
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
956
911
  var finalCollateralAmount = constants_1.BN_ZERO;
957
912
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
958
913
  finalCollateralAmount = amountIn;
959
914
  }
960
915
  else {
961
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
916
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
962
917
  finalCollateralAmount = swapAmountOut;
963
918
  }
964
919
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
@@ -972,8 +927,8 @@ var PerpetualsClient = (function () {
972
927
  }
973
928
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
974
929
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
975
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
976
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
930
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
931
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
977
932
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
978
933
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
979
934
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
@@ -996,7 +951,7 @@ var PerpetualsClient = (function () {
996
951
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
997
952
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
998
953
  };
999
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
954
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
1000
955
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1001
956
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1002
957
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
@@ -1013,11 +968,11 @@ var PerpetualsClient = (function () {
1013
968
  collateralInInputToken = collateralAmountWithFee;
1014
969
  }
1015
970
  else {
1016
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
971
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
1017
972
  }
1018
973
  return collateralInInputToken;
1019
974
  };
1020
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
975
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
1021
976
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1022
977
  if (debugLogs === void 0) { debugLogs = false; }
1023
978
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -1039,10 +994,9 @@ var PerpetualsClient = (function () {
1039
994
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1040
995
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1041
996
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1042
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1043
997
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1044
- positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1045
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
998
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
999
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1046
1000
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
1047
1001
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1048
1002
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -1052,30 +1006,37 @@ var PerpetualsClient = (function () {
1052
1006
  }
1053
1007
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1054
1008
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
1055
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1009
+ var currentCollateralUsd = positionDelta.collateralUsd;
1056
1010
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1057
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1058
- var closeAmount, feesAmount;
1011
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
1059
1012
  if (debugLogs) {
1060
1013
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
1061
1014
  }
1015
+ var closeAmountUsd, feesAmountUsd;
1062
1016
  if (assetsUsd.gte(liabilityUsd)) {
1063
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1064
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1017
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1018
+ feesAmountUsd = totalFeesUsd;
1019
+ }
1020
+ else {
1021
+ closeAmountUsd = constants_1.BN_ZERO;
1022
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1023
+ }
1024
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1025
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1026
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1027
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
1065
1028
  }
1066
1029
  else {
1067
- closeAmount = constants_1.BN_ZERO;
1068
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1030
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
1069
1031
  }
1070
1032
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1071
1033
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1072
1034
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1073
- newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1074
1035
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1075
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1036
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
1076
1037
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1077
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1078
1038
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1039
+ newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
1079
1040
  var feeUsdWithDiscount = constants_1.BN_ZERO;
1080
1041
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1081
1042
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1089,29 +1050,30 @@ var PerpetualsClient = (function () {
1089
1050
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1090
1051
  if (keepLevSame) {
1091
1052
  var collateralAmountReceived = closeAmount;
1092
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1093
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1053
+ var collateralAmountReceivedUsd = closeAmountUsd;
1054
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1094
1055
  if (debugLogs) {
1095
1056
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1096
1057
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1097
1058
  }
1098
- if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1059
+ if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1099
1060
  collateralAmountReceived = constants_1.BN_ZERO;
1100
- collateralAmountRecievedUsd = constants_1.BN_ZERO;
1061
+ collateralAmountReceivedUsd = constants_1.BN_ZERO;
1101
1062
  }
1102
- else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1063
+ else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1103
1064
  if (debugLogs) {
1104
1065
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1105
1066
  }
1106
1067
  collateralAmountReceived = maxWithdrawableAmount;
1107
- collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1068
+ collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1108
1069
  }
1109
1070
  var entryPrice = OraclePrice_1.OraclePrice.from({ price: newPosition.entryPrice.price, exponent: new anchor_1.BN(newPosition.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1110
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1111
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1071
+ newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1072
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1073
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1112
1074
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1113
1075
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1114
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1076
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1115
1077
  return {
1116
1078
  newSizeUsd: newPosition.sizeUsd,
1117
1079
  feeUsd: feeUsd,
@@ -1119,8 +1081,9 @@ var PerpetualsClient = (function () {
1119
1081
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1120
1082
  newLev: newLev,
1121
1083
  liquidationPrice: finalLiquidationPrice,
1122
- collateralAmountRecieved: collateralAmountReceived,
1123
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1084
+ collateralAmountReceived: collateralAmountReceived,
1085
+ collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1086
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1124
1087
  newPnl: finalPnlUsd
1125
1088
  };
1126
1089
  }
@@ -1128,8 +1091,7 @@ var PerpetualsClient = (function () {
1128
1091
  throw "only same leverage is supported for now";
1129
1092
  }
1130
1093
  };
1131
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1132
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1094
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1133
1095
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1134
1096
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1135
1097
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1138,61 +1100,87 @@ var PerpetualsClient = (function () {
1138
1100
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1139
1101
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1140
1102
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1141
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1103
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1142
1104
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1143
1105
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1144
1106
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1145
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1146
1107
  var availableInitMarginUsd = constants_1.BN_ZERO;
1147
- if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1148
- availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1108
+ if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1109
+ availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1149
1110
  }
1150
1111
  else {
1151
1112
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1152
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1113
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1153
1114
  }
1154
1115
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1155
1116
  if (maxRemovableCollateralUsd.isNeg()) {
1156
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1117
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1157
1118
  }
1158
1119
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1159
- var diff = constants_1.BN_ZERO;
1120
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1121
+ var diffUsd = constants_1.BN_ZERO;
1160
1122
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1161
1123
  var isDegenMode = positionAccount.isDegenMode();
1162
1124
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1163
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1164
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1125
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1126
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1165
1127
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1166
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1128
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1167
1129
  }
1168
1130
  else {
1169
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1131
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1132
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1170
1133
  }
1171
1134
  }
1172
1135
  else {
1173
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1136
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1137
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1174
1138
  }
1175
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1139
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1176
1140
  };
1177
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1141
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1178
1142
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1179
1143
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1180
- var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1181
1144
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1182
1145
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1183
1146
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1184
1147
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1185
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1186
- var closeAmount, feesAmount;
1148
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1149
+ var closeAmountUsd, feesAmountUsd;
1187
1150
  if (assetsUsd.gt(liabilityUsd)) {
1188
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1189
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1151
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1152
+ feesAmountUsd = totalFeesUsd;
1190
1153
  }
1191
1154
  else {
1192
- closeAmount = constants_1.BN_ZERO;
1193
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1155
+ closeAmountUsd = constants_1.BN_ZERO;
1156
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1194
1157
  }
1195
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1158
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1159
+ };
1160
+ this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1161
+ if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1162
+ if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1163
+ throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1164
+ }
1165
+ var rawMinInitLev = positionAccount.isDegenMode()
1166
+ ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1167
+ : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1168
+ var MIN_INIT_LEVERAGE = rawMinInitLev
1169
+ .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1170
+ .div(new anchor_1.BN(100));
1171
+ var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1172
+ .muln(constants_1.BPS_POWER)
1173
+ .div(MIN_INIT_LEVERAGE);
1174
+ var currentCollateralUsd = positionAccount.collateralUsd;
1175
+ var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1176
+ ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1177
+ : constants_1.BN_ZERO;
1178
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1179
+ var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1180
+ return {
1181
+ maxAddableAmount: maxAddableAmount,
1182
+ maxAddableAmountUsd: maxAddableCollateralUsd,
1183
+ };
1196
1184
  };
1197
1185
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1198
1186
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1205,34 +1193,37 @@ var PerpetualsClient = (function () {
1205
1193
  var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub((positionAccount.isDegenMode() ? new anchor_1.BN(targetCustodyAccount.pricing.minDegenCollateralUsd) : new anchor_1.BN(targetCustodyAccount.pricing.minCollateralUsd)).mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1206
1194
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1207
1195
  console.log("THIS cannot happen but still");
1208
- return constants_1.BN_ZERO;
1196
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1209
1197
  }
1210
1198
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1211
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1199
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1212
1200
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1213
1201
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1214
1202
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1215
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1203
+ var currentCollateralUsd = positionAccount.collateralUsd;
1216
1204
  var availableInitMarginUsd = constants_1.BN_ZERO;
1217
1205
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1218
1206
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1219
1207
  }
1220
1208
  else {
1221
1209
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1222
- return constants_1.BN_ZERO;
1210
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1223
1211
  }
1224
1212
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1225
1213
  if (maxRemovableCollateralUsd.isNeg()) {
1226
- return constants_1.BN_ZERO;
1214
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1227
1215
  }
1228
1216
  var maxWithdrawableAmount;
1217
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1229
1218
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1230
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1219
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1220
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1231
1221
  }
1232
1222
  else {
1233
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1223
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1224
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1234
1225
  }
1235
- return maxWithdrawableAmount;
1226
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1236
1227
  };
1237
1228
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1238
1229
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1270,12 +1261,12 @@ var PerpetualsClient = (function () {
1270
1261
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1271
1262
  var lockFeeUsd = constants_1.BN_ZERO;
1272
1263
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1273
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1264
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1274
1265
  }
1275
1266
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1276
1267
  return lockFeeUsd;
1277
1268
  };
1278
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1269
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1279
1270
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1280
1271
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1281
1272
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1283,193 +1274,144 @@ var PerpetualsClient = (function () {
1283
1274
  else {
1284
1275
  maxPayOffBpsNew = maxPayOffBps;
1285
1276
  }
1286
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1277
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1287
1278
  return lockedUsd;
1288
1279
  };
1289
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1280
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1290
1281
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1291
1282
  price: constants_1.BN_ZERO,
1292
1283
  exponent: constants_1.BN_ZERO,
1293
1284
  confidence: constants_1.BN_ZERO,
1294
1285
  timestamp: constants_1.BN_ZERO
1295
1286
  });
1296
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1297
- return zeroOraclePrice;
1298
- }
1299
1287
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1300
1288
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1301
1289
  }
1302
1290
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1303
1291
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1304
1292
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1305
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1306
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1307
1293
  var liquidationPrice;
1308
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1309
- var newCollateralAmount = void 0;
1310
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1311
- newCollateralAmount = collateralAmount;
1294
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1295
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1296
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1297
+ .div(positionAccount.sizeAmount),
1298
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1299
+ confidence: constants_1.BN_ZERO,
1300
+ timestamp: constants_1.BN_ZERO
1301
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1302
+ if ((0, types_1.isVariant)(side, 'long')) {
1303
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1304
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1305
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1306
+ confidence: constants_1.BN_ZERO,
1307
+ timestamp: constants_1.BN_ZERO
1308
+ });
1312
1309
  }
1313
1310
  else {
1314
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1315
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1316
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1311
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1312
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1313
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1314
+ confidence: constants_1.BN_ZERO,
1315
+ timestamp: constants_1.BN_ZERO
1316
+ });
1317
1317
  }
1318
- var lp = OraclePrice_1.OraclePrice.from({
1319
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1320
- .div(sizeAmount.add(newCollateralAmount)),
1318
+ }
1319
+ else {
1320
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1321
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1322
+ .div(positionAccount.sizeAmount),
1321
1323
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1322
1324
  confidence: constants_1.BN_ZERO,
1323
1325
  timestamp: constants_1.BN_ZERO
1324
- });
1325
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1326
- }
1327
- else {
1328
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1329
- if (assetsUsd.gte(liablitiesUsd)) {
1330
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1331
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1332
- .div(positionAccount.sizeAmount),
1333
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1326
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1327
+ if ((0, types_1.isVariant)(side, 'long')) {
1328
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1329
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1330
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1334
1331
  confidence: constants_1.BN_ZERO,
1335
1332
  timestamp: constants_1.BN_ZERO
1336
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1337
- if ((0, types_1.isVariant)(side, 'long')) {
1338
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1339
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1340
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1341
- confidence: constants_1.BN_ZERO,
1342
- timestamp: constants_1.BN_ZERO
1343
- });
1344
- }
1345
- else {
1346
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1347
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1348
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1349
- confidence: constants_1.BN_ZERO,
1350
- timestamp: constants_1.BN_ZERO
1351
- });
1352
- }
1333
+ });
1353
1334
  }
1354
1335
  else {
1355
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1356
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1357
- .div(positionAccount.sizeAmount),
1358
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1336
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1337
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1338
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1359
1339
  confidence: constants_1.BN_ZERO,
1360
1340
  timestamp: constants_1.BN_ZERO
1361
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1362
- if ((0, types_1.isVariant)(side, 'long')) {
1363
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1364
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1365
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1366
- confidence: constants_1.BN_ZERO,
1367
- timestamp: constants_1.BN_ZERO
1368
- });
1369
- }
1370
- else {
1371
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1373
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1374
- confidence: constants_1.BN_ZERO,
1375
- timestamp: constants_1.BN_ZERO
1376
- });
1377
- }
1341
+ });
1378
1342
  }
1379
1343
  }
1380
1344
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1381
1345
  };
1382
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1346
+ this.getLiquidationPriceSync = function (collateralUsd, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1347
+ var newPositionAccount = positionAccount.clone();
1348
+ newPositionAccount.collateralUsd = collateralUsd;
1349
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1350
+ };
1351
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1383
1352
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1384
1353
  price: constants_1.BN_ZERO,
1385
1354
  exponent: constants_1.BN_ZERO,
1386
1355
  confidence: constants_1.BN_ZERO,
1387
1356
  timestamp: constants_1.BN_ZERO
1388
1357
  });
1389
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1390
- return zeroOraclePrice;
1391
- }
1392
1358
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1393
1359
  var unsettledLossUsd = exitFeeUsd;
1394
1360
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1395
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1396
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1397
1361
  var liquidationPrice;
1398
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1399
- var newCollateralAmount = void 0;
1400
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1401
- newCollateralAmount = collateralAmount;
1362
+ if (collateralUsd.gte(liablitiesUsd)) {
1363
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1364
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1365
+ .div(sizeAmount),
1366
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1367
+ confidence: constants_1.BN_ZERO,
1368
+ timestamp: constants_1.BN_ZERO
1369
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1370
+ if ((0, types_1.isVariant)(side, 'long')) {
1371
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1372
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1373
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1374
+ confidence: constants_1.BN_ZERO,
1375
+ timestamp: constants_1.BN_ZERO
1376
+ });
1402
1377
  }
1403
1378
  else {
1404
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1405
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1406
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1379
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1380
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1381
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1382
+ confidence: constants_1.BN_ZERO,
1383
+ timestamp: constants_1.BN_ZERO
1384
+ });
1407
1385
  }
1408
- var lp = OraclePrice_1.OraclePrice.from({
1409
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1410
- .div(sizeAmount.add(newCollateralAmount)),
1386
+ }
1387
+ else {
1388
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1389
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1390
+ .div(sizeAmount),
1411
1391
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1412
1392
  confidence: constants_1.BN_ZERO,
1413
1393
  timestamp: constants_1.BN_ZERO
1414
- });
1415
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1416
- }
1417
- else {
1418
- var assetsUsd = collateralUsd;
1419
- if (assetsUsd.gte(liablitiesUsd)) {
1420
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1421
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1422
- .div(sizeAmount),
1423
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1394
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1395
+ if ((0, types_1.isVariant)(side, 'long')) {
1396
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1397
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1398
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1424
1399
  confidence: constants_1.BN_ZERO,
1425
1400
  timestamp: constants_1.BN_ZERO
1426
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1427
- if ((0, types_1.isVariant)(side, 'long')) {
1428
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1429
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1430
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1431
- confidence: constants_1.BN_ZERO,
1432
- timestamp: constants_1.BN_ZERO
1433
- });
1434
- }
1435
- else {
1436
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1437
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1438
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1439
- confidence: constants_1.BN_ZERO,
1440
- timestamp: constants_1.BN_ZERO
1441
- });
1442
- }
1401
+ });
1443
1402
  }
1444
1403
  else {
1445
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1446
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1447
- .div(sizeAmount),
1448
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1404
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1405
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1406
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1449
1407
  confidence: constants_1.BN_ZERO,
1450
1408
  timestamp: constants_1.BN_ZERO
1451
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1452
- if ((0, types_1.isVariant)(side, 'long')) {
1453
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1454
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1455
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1456
- confidence: constants_1.BN_ZERO,
1457
- timestamp: constants_1.BN_ZERO
1458
- });
1459
- }
1460
- else {
1461
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1462
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1463
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1464
- confidence: constants_1.BN_ZERO,
1465
- timestamp: constants_1.BN_ZERO
1466
- });
1467
- }
1409
+ });
1468
1410
  }
1469
1411
  }
1470
1412
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1471
1413
  };
1472
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1414
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1473
1415
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1474
1416
  price: constants_1.BN_ZERO,
1475
1417
  exponent: constants_1.BN_ZERO,
@@ -1480,7 +1422,7 @@ var PerpetualsClient = (function () {
1480
1422
  return zeroOraclePrice;
1481
1423
  }
1482
1424
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1483
- price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1425
+ price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1484
1426
  .div(positionAccount.sizeAmount),
1485
1427
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1486
1428
  confidence: constants_1.BN_ZERO,
@@ -1508,7 +1450,7 @@ var PerpetualsClient = (function () {
1508
1450
  }
1509
1451
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1510
1452
  };
1511
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1453
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1512
1454
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1513
1455
  throw new Error("Delta Amounts cannot be negative.");
1514
1456
  }
@@ -1538,10 +1480,9 @@ var PerpetualsClient = (function () {
1538
1480
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1539
1481
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1540
1482
  positionAccount.market = marketAccountPk;
1541
- positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1542
- positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1543
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1544
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1483
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1484
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1485
+ positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1545
1486
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1546
1487
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1547
1488
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1613,6 +1554,9 @@ var PerpetualsClient = (function () {
1613
1554
  });
1614
1555
  };
1615
1556
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1557
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1558
+ };
1559
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1616
1560
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1617
1561
  return {
1618
1562
  profitUsd: constants_1.BN_ZERO,
@@ -1620,9 +1564,8 @@ var PerpetualsClient = (function () {
1620
1564
  };
1621
1565
  }
1622
1566
  var side = poolConfig.getMarketConfigByPk(positionAccount.market).side;
1623
- var sizeUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1567
+ var sizeUsd = positionAccount.sizeUsd;
1624
1568
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, sizeUsd);
1625
- var collateralMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1626
1569
  var priceDiffProfit, priceDiffLoss;
1627
1570
  var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1628
1571
  price: positionAccount.entryPrice.price,
@@ -1671,7 +1614,7 @@ var PerpetualsClient = (function () {
1671
1614
  }
1672
1615
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1673
1616
  return {
1674
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1617
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1675
1618
  lossUsd: constants_1.BN_ZERO,
1676
1619
  };
1677
1620
  }
@@ -1762,6 +1705,9 @@ var PerpetualsClient = (function () {
1762
1705
  }
1763
1706
  };
1764
1707
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1708
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1709
+ };
1710
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1765
1711
  var poolAmountUsd = constants_1.BN_ZERO;
1766
1712
  for (var index = 0; index < custodies.length; index++) {
1767
1713
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1774,6 +1720,7 @@ var PerpetualsClient = (function () {
1774
1720
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1775
1721
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1776
1722
  }
1723
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1777
1724
  if (aumCalcMode === "includePnl") {
1778
1725
  var poolEquityUsd = poolAmountUsd;
1779
1726
  for (var index = 0; index < markets.length; index++) {
@@ -1783,11 +1730,12 @@ var PerpetualsClient = (function () {
1783
1730
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1784
1731
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1785
1732
  var position = markets[index].getCollectivePosition();
1733
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1786
1734
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1787
1735
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1788
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1789
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1790
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1736
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1737
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1738
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1791
1739
  }
1792
1740
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1793
1741
  }
@@ -1795,14 +1743,6 @@ var PerpetualsClient = (function () {
1795
1743
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1796
1744
  }
1797
1745
  };
1798
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1799
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1800
- return { discountBn: constants_1.BN_ZERO };
1801
- }
1802
- else {
1803
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1804
- }
1805
- };
1806
1746
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1807
1747
  if (tokenStakeAccount.level === 0) {
1808
1748
  return { discountBn: constants_1.BN_ZERO };
@@ -1887,7 +1827,7 @@ var PerpetualsClient = (function () {
1887
1827
  });
1888
1828
  };
1889
1829
  this.getStakedLpTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
1890
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, result, index, res;
1830
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, setCULimitIx, result, index, res;
1891
1831
  var _d;
1892
1832
  return __generator(this, function (_e) {
1893
1833
  switch (_e.label) {
@@ -1935,6 +1875,8 @@ var PerpetualsClient = (function () {
1935
1875
  return [4, backUpOracleInstructionPromise];
1936
1876
  case 2:
1937
1877
  backUpOracleInstruction = _e.sent();
1878
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1879
+ transaction.instructions.unshift(setCULimitIx);
1938
1880
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
1939
1881
  return [4, this.viewHelper.simulateTransaction(transaction)];
1940
1882
  case 3:
@@ -2001,7 +1943,7 @@ var PerpetualsClient = (function () {
2001
1943
  args_1[_i - 4] = arguments[_i];
2002
1944
  }
2003
1945
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, depositCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, depositCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2004
- var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
1946
+ var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2005
1947
  var _e;
2006
1948
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2007
1949
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2052,6 +1994,8 @@ var PerpetualsClient = (function () {
2052
1994
  .transaction()];
2053
1995
  case 1:
2054
1996
  transaction = _f.sent();
1997
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1998
+ transaction.instructions.unshift(setCULimitIx);
2055
1999
  if (!enableBackupOracle) return [3, 3];
2056
2000
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2057
2001
  case 2:
@@ -2061,6 +2005,14 @@ var PerpetualsClient = (function () {
2061
2005
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
2062
2006
  case 4:
2063
2007
  result = _f.sent();
2008
+ if (result.value.err) {
2009
+ console.error('error Simulation failed:::', result);
2010
+ return [2, {
2011
+ amount: undefined,
2012
+ fee: undefined,
2013
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2014
+ }];
2015
+ }
2064
2016
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
2065
2017
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
2066
2018
  return [2, {
@@ -2077,7 +2029,7 @@ var PerpetualsClient = (function () {
2077
2029
  args_1[_i - 4] = arguments[_i];
2078
2030
  }
2079
2031
  return __awaiter(_this, __spreadArray([amount_1, poolKey_1, removeTokenCustodyKey_1, POOL_CONFIG_1], args_1, true), void 0, function (amount, poolKey, removeTokenCustodyKey, POOL_CONFIG, userPublicKey, enableBackupOracle) {
2080
- var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
2032
+ var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2081
2033
  var _e;
2082
2034
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2083
2035
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2128,6 +2080,8 @@ var PerpetualsClient = (function () {
2128
2080
  .transaction()];
2129
2081
  case 1:
2130
2082
  transaction = _f.sent();
2083
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2084
+ transaction.instructions.unshift(setCULimitIx);
2131
2085
  if (!enableBackupOracle) return [3, 3];
2132
2086
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2133
2087
  case 2:
@@ -2139,9 +2093,11 @@ var PerpetualsClient = (function () {
2139
2093
  result = _f.sent();
2140
2094
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2141
2095
  if (result.value.err) {
2096
+ console.error('error Simulation failed:', result);
2142
2097
  return [2, {
2143
- amount: new anchor_1.BN(0),
2144
- fee: new anchor_1.BN(0),
2098
+ amount: undefined,
2099
+ fee: undefined,
2100
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2145
2101
  }];
2146
2102
  }
2147
2103
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2154,7 +2110,7 @@ var PerpetualsClient = (function () {
2154
2110
  });
2155
2111
  };
2156
2112
  this.getCompoundingLPTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
2157
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, result, index, res;
2113
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, setCULimitIx, result, index, res;
2158
2114
  var _d;
2159
2115
  return __generator(this, function (_e) {
2160
2116
  switch (_e.label) {
@@ -2202,6 +2158,8 @@ var PerpetualsClient = (function () {
2202
2158
  .transaction()];
2203
2159
  case 2:
2204
2160
  transaction = _e.sent();
2161
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2162
+ transaction.instructions.unshift(setCULimitIx);
2205
2163
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
2206
2164
  return [4, this.viewHelper.simulateTransaction(transaction)];
2207
2165
  case 3:
@@ -2551,11 +2509,10 @@ var PerpetualsClient = (function () {
2551
2509
  for (var _i = 8; _i < arguments.length; _i++) {
2552
2510
  args_1[_i - 8] = arguments[_i];
2553
2511
  }
2554
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2512
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, priceWithSlippage_1, collateralWithfee_1, size_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2555
2513
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2556
2514
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2557
2515
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2558
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2559
2516
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2560
2517
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2561
2518
  return __generator(this, function (_c) {
@@ -2648,7 +2605,7 @@ var PerpetualsClient = (function () {
2648
2605
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2649
2606
  fundingMint: collateralCustodyConfig.mintKey
2650
2607
  })
2651
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2608
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2652
2609
  .instruction()];
2653
2610
  case 7:
2654
2611
  instruction = _c.sent();
@@ -2666,11 +2623,10 @@ var PerpetualsClient = (function () {
2666
2623
  for (var _i = 6; _i < arguments.length; _i++) {
2667
2624
  args_1[_i - 6] = arguments[_i];
2668
2625
  }
2669
- return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2626
+ return __awaiter(_this, __spreadArray([marketSymbol_1, collateralSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
2670
2627
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2671
2628
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2672
2629
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2673
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2674
2630
  if (createUserATA === void 0) { createUserATA = true; }
2675
2631
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2676
2632
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2749,7 +2705,7 @@ var PerpetualsClient = (function () {
2749
2705
  collateralMint: collateralCustodyConfig.mintKey,
2750
2706
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2751
2707
  })
2752
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2708
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2753
2709
  .instruction()];
2754
2710
  case 6:
2755
2711
  instruction = _b.sent();
@@ -2771,16 +2727,15 @@ var PerpetualsClient = (function () {
2771
2727
  });
2772
2728
  });
2773
2729
  };
2774
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2730
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2775
2731
  var args_1 = [];
2776
- for (var _i = 10; _i < arguments.length; _i++) {
2777
- args_1[_i - 10] = arguments[_i];
2732
+ for (var _i = 9; _i < arguments.length; _i++) {
2733
+ args_1[_i - 9] = arguments[_i];
2778
2734
  }
2779
- 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) {
2780
- var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, rebateMintAccount, inx, err_3;
2735
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, collateralTokenSymbol, userInputTokenSymbol, amountIn, priceWithSlippage, sizeAmount, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, skipBalanceChecks, ephemeralSignerPubkey) {
2736
+ var publicKey, userInputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, targetToken, userInputTokenAccount, userInputToken, lamports, unWrappedSolBalance, _a, userOutputTokenAccount, tokenAccountBalance, _b, userOutputTokenAccount, inx, err_3;
2781
2737
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2782
2738
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2783
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2784
2739
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2785
2740
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2786
2741
  return __generator(this, function (_c) {
@@ -2874,18 +2829,10 @@ var PerpetualsClient = (function () {
2874
2829
  }
2875
2830
  _c.label = 10;
2876
2831
  case 10:
2877
- rebateMintAccount = {
2878
- pubkey: collateralCustodyConfig.mintKey,
2879
- isSigner: false,
2880
- isWritable: false
2881
- };
2882
- _c.label = 11;
2883
- case 11:
2884
- _c.trys.push([11, 13, , 14]);
2832
+ _c.trys.push([10, 12, , 13]);
2885
2833
  return [4, this.program.methods
2886
2834
  .swapAndOpen({
2887
2835
  amountIn: amountIn,
2888
- minCollateralAmountOut: minCollateralAmountOut,
2889
2836
  priceWithSlippage: priceWithSlippage,
2890
2837
  sizeAmount: sizeAmount,
2891
2838
  privilege: privilege
@@ -2916,17 +2863,17 @@ var PerpetualsClient = (function () {
2916
2863
  collateralMint: collateralCustodyConfig.mintKey,
2917
2864
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2918
2865
  })
2919
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2866
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2920
2867
  .instruction()];
2921
- case 12:
2868
+ case 11:
2922
2869
  inx = _c.sent();
2923
2870
  instructions.push(inx);
2924
- return [3, 14];
2925
- case 13:
2871
+ return [3, 13];
2872
+ case 12:
2926
2873
  err_3 = _c.sent();
2927
2874
  console.error("perpClient SwapAndOpen error:: ", err_3);
2928
2875
  throw err_3;
2929
- case 14: return [2, {
2876
+ case 13: return [2, {
2930
2877
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2931
2878
  additionalSigners: additionalSigners
2932
2879
  }];
@@ -2934,16 +2881,15 @@ var PerpetualsClient = (function () {
2934
2881
  });
2935
2882
  });
2936
2883
  };
2937
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2884
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2938
2885
  var args_1 = [];
2939
- for (var _i = 8; _i < arguments.length; _i++) {
2940
- args_1[_i - 8] = arguments[_i];
2886
+ for (var _i = 7; _i < arguments.length; _i++) {
2887
+ args_1[_i - 7] = arguments[_i];
2941
2888
  }
2942
- 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) {
2943
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2889
+ return __awaiter(_this, __spreadArray([targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1], args_1, true), void 0, function (targetTokenSymbol, userOutputTokenSymbol, collateralTokenSymbol, priceWithSlippage, side, poolConfig, privilege, tokenStakeAccount, userReferralAccount, ephemeralSignerPubkey) {
2890
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2944
2891
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2945
2892
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2946
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2947
2893
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2948
2894
  return __generator(this, function (_a) {
2949
2895
  switch (_a.label) {
@@ -3009,18 +2955,12 @@ var PerpetualsClient = (function () {
3009
2955
  if (!(_a.sent())) {
3010
2956
  preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, collateralToken.mintKey, collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID));
3011
2957
  }
3012
- rebateMintAccount = {
3013
- pubkey: collateralCustodyConfig.mintKey,
3014
- isSigner: false,
3015
- isWritable: false
3016
- };
3017
2958
  _a.label = 5;
3018
2959
  case 5:
3019
2960
  _a.trys.push([5, 7, , 8]);
3020
2961
  return [4, this.program.methods
3021
2962
  .closeAndSwap({
3022
2963
  priceWithSlippage: priceWithSlippage,
3023
- minSwapAmountOut: minSwapAmountOut,
3024
2964
  privilege: privilege
3025
2965
  })
3026
2966
  .accounts({
@@ -3049,7 +2989,7 @@ var PerpetualsClient = (function () {
3049
2989
  collateralMint: collateralCustodyConfig.mintKey,
3050
2990
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
3051
2991
  })
3052
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2992
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3053
2993
  .instruction()];
3054
2994
  case 6:
3055
2995
  inx = _a.sent();
@@ -3170,12 +3110,12 @@ var PerpetualsClient = (function () {
3170
3110
  });
3171
3111
  });
3172
3112
  };
3173
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3113
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3174
3114
  var args_1 = [];
3175
- for (var _i = 8; _i < arguments.length; _i++) {
3176
- args_1[_i - 8] = arguments[_i];
3115
+ for (var _i = 7; _i < arguments.length; _i++) {
3116
+ args_1[_i - 7] = arguments[_i];
3177
3117
  }
3178
- return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, minCollateralAmountOut, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3118
+ return __awaiter(_this, __spreadArray([targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, inputSymbol, collateralSymbol, amountIn, side, positionPubKey, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
3179
3119
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3180
3120
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3181
3121
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3254,7 +3194,6 @@ var PerpetualsClient = (function () {
3254
3194
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3255
3195
  return [4, this.program.methods.swapAndAddCollateral({
3256
3196
  amountIn: amountIn,
3257
- minCollateralAmountOut: minCollateralAmountOut,
3258
3197
  }).accounts({
3259
3198
  owner: publicKey,
3260
3199
  feePayer: publicKey,
@@ -3290,12 +3229,12 @@ var PerpetualsClient = (function () {
3290
3229
  });
3291
3230
  });
3292
3231
  };
3293
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3232
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3294
3233
  var args_1 = [];
3295
3234
  for (var _i = 6; _i < arguments.length; _i++) {
3296
3235
  args_1[_i - 6] = arguments[_i];
3297
3236
  }
3298
- return __awaiter(_this, __spreadArray([collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralWithFee, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3237
+ return __awaiter(_this, __spreadArray([collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1], args_1, true), void 0, function (collateralDeltaUsd, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA, ephemeralSignerPubkey) {
3299
3238
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3300
3239
  if (createUserATA === void 0) { createUserATA = true; }
3301
3240
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3359,7 +3298,7 @@ var PerpetualsClient = (function () {
3359
3298
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3360
3299
  return [4, this.program.methods
3361
3300
  .removeCollateral({
3362
- collateralDelta: collateralWithFee,
3301
+ collateralDeltaUsd: collateralDeltaUsd,
3363
3302
  })
3364
3303
  .accounts({
3365
3304
  owner: publicKey,
@@ -3401,12 +3340,12 @@ var PerpetualsClient = (function () {
3401
3340
  });
3402
3341
  });
3403
3342
  };
3404
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3343
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3405
3344
  var args_1 = [];
3406
- for (var _i = 7; _i < arguments.length; _i++) {
3407
- args_1[_i - 7] = arguments[_i];
3345
+ for (var _i = 6; _i < arguments.length; _i++) {
3346
+ args_1[_i - 6] = arguments[_i];
3408
3347
  }
3409
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, minSwapAmountOut, collateralDelta, side, poolConfig, ephemeralSignerPubkey) {
3348
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, outputSymbol, collateralDeltaUsd, side, poolConfig, ephemeralSignerPubkey) {
3410
3349
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3411
3350
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3412
3351
  return __generator(this, function (_a) {
@@ -3463,8 +3402,7 @@ var PerpetualsClient = (function () {
3463
3402
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3464
3403
  return [4, this.program.methods
3465
3404
  .removeCollateralAndSwap({
3466
- collateralDelta: collateralDelta,
3467
- minSwapAmountOut: minSwapAmountOut,
3405
+ collateralDeltaUsd: collateralDeltaUsd,
3468
3406
  })
3469
3407
  .accounts({
3470
3408
  owner: publicKey,
@@ -3509,11 +3447,10 @@ var PerpetualsClient = (function () {
3509
3447
  for (var _i = 8; _i < arguments.length; _i++) {
3510
3448
  args_1[_i - 8] = arguments[_i];
3511
3449
  }
3512
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3450
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, positionPubKey_1, side_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3513
3451
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3514
3452
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3515
3453
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3516
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3517
3454
  return __generator(this, function (_a) {
3518
3455
  switch (_a.label) {
3519
3456
  case 0:
@@ -3556,7 +3493,7 @@ var PerpetualsClient = (function () {
3556
3493
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3557
3494
  collateralMint: collateralCustodyConfig.mintKey
3558
3495
  })
3559
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3496
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3560
3497
  .instruction()];
3561
3498
  case 1:
3562
3499
  instruction = _a.sent();
@@ -3574,11 +3511,10 @@ var PerpetualsClient = (function () {
3574
3511
  for (var _i = 8; _i < arguments.length; _i++) {
3575
3512
  args_1[_i - 8] = arguments[_i];
3576
3513
  }
3577
- return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount, rebateTokenAccount) {
3514
+ return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1, priceWithSlippage_1, sizeDelta_1, privilege_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, privilege, tokenStakeAccount, userReferralAccount) {
3578
3515
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3579
3516
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3580
3517
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3581
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3582
3518
  return __generator(this, function (_a) {
3583
3519
  switch (_a.label) {
3584
3520
  case 0:
@@ -3621,7 +3557,7 @@ var PerpetualsClient = (function () {
3621
3557
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3622
3558
  collateralMint: collateralCustodyConfig.mintKey
3623
3559
  })
3624
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3560
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3625
3561
  .instruction()];
3626
3562
  case 1:
3627
3563
  instruction = _a.sent();
@@ -4088,119 +4024,8 @@ var PerpetualsClient = (function () {
4088
4024
  }
4089
4025
  });
4090
4026
  }); };
4091
- this.updateNftAccount = function (nftMint, updateReferer, updateBooster, flpStakeAccounts) { return __awaiter(_this, void 0, void 0, function () {
4092
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, flpStakeAccountMetas, _i, flpStakeAccounts_1, flpStakeAccountPk, updateNftTradingAccountInstruction, err_8;
4093
- return __generator(this, function (_a) {
4094
- switch (_a.label) {
4095
- case 0:
4096
- publicKey = this.provider.wallet.publicKey;
4097
- preInstructions = [];
4098
- instructions = [];
4099
- postInstructions = [];
4100
- additionalSigners = [];
4101
- _a.label = 1;
4102
- case 1:
4103
- _a.trys.push([1, 4, , 5]);
4104
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4105
- Buffer.from("trading"),
4106
- nftMint.toBuffer(),
4107
- ], this.programId)[0];
4108
- nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
4109
- Buffer.from("referral"),
4110
- publicKey.toBuffer(),
4111
- ], this.programId)[0];
4112
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey, true)];
4113
- case 2:
4114
- nftTokenAccount = _a.sent();
4115
- flpStakeAccountMetas = [];
4116
- for (_i = 0, flpStakeAccounts_1 = flpStakeAccounts; _i < flpStakeAccounts_1.length; _i++) {
4117
- flpStakeAccountPk = flpStakeAccounts_1[_i];
4118
- flpStakeAccountMetas.push({
4119
- pubkey: flpStakeAccountPk,
4120
- isSigner: false,
4121
- isWritable: true,
4122
- });
4123
- }
4124
- return [4, this.program.methods
4125
- .updateTradingAccount({
4126
- updateReferer: updateReferer,
4127
- updateBooster: updateBooster
4128
- })
4129
- .accounts({
4130
- owner: publicKey,
4131
- feePayer: publicKey,
4132
- nftTokenAccount: nftTokenAccount,
4133
- referralAccount: nftReferralAccount,
4134
- tradingAccount: nftTradingAccount
4135
- })
4136
- .instruction()];
4137
- case 3:
4138
- updateNftTradingAccountInstruction = _a.sent();
4139
- instructions.push(updateNftTradingAccountInstruction);
4140
- return [3, 5];
4141
- case 4:
4142
- err_8 = _a.sent();
4143
- console.log("perpClient updateNftAccount error:: ", err_8);
4144
- throw err_8;
4145
- case 5: return [2, {
4146
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4147
- additionalSigners: additionalSigners
4148
- }];
4149
- }
4150
- });
4151
- }); };
4152
- this.levelUp = function (poolConfig, nftMint, authorizationRulesAccount) { return __awaiter(_this, void 0, void 0, function () {
4153
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_9;
4154
- return __generator(this, function (_a) {
4155
- switch (_a.label) {
4156
- case 0:
4157
- publicKey = this.provider.wallet.publicKey;
4158
- preInstructions = [];
4159
- instructions = [];
4160
- postInstructions = [];
4161
- additionalSigners = [];
4162
- _a.label = 1;
4163
- case 1:
4164
- _a.trys.push([1, 3, , 4]);
4165
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4166
- Buffer.from("trading"),
4167
- nftMint.toBuffer(),
4168
- ], this.programId)[0];
4169
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
4170
- return [4, this.program.methods
4171
- .levelUp({})
4172
- .accounts({
4173
- owner: publicKey,
4174
- perpetuals: this.perpetuals.publicKey,
4175
- pool: poolConfig.poolAddress,
4176
- metadataAccount: metadataAccount,
4177
- nftMint: nftMint,
4178
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
4179
- tradingAccount: nftTradingAccount,
4180
- transferAuthority: this.authority.publicKey,
4181
- authorizationRulesAccount: authorizationRulesAccount,
4182
- authorizationRulesProgram: new web3_js_1.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg'),
4183
- systemProgram: web3_js_1.SystemProgram.programId,
4184
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
4185
- })
4186
- .instruction()];
4187
- case 2:
4188
- levelUpInstruction = _a.sent();
4189
- instructions.push(levelUpInstruction);
4190
- return [3, 4];
4191
- case 3:
4192
- err_9 = _a.sent();
4193
- console.log("perpClient levelUp error:: ", err_9);
4194
- throw err_9;
4195
- case 4: return [2, {
4196
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4197
- additionalSigners: additionalSigners
4198
- }];
4199
- }
4200
- });
4201
- }); };
4202
4027
  this.depositStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4203
- var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
4028
+ var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_8;
4204
4029
  return __generator(this, function (_a) {
4205
4030
  switch (_a.label) {
4206
4031
  case 0:
@@ -4242,10 +4067,10 @@ var PerpetualsClient = (function () {
4242
4067
  instructions.push(depositStakeInstruction);
4243
4068
  return [3, 5];
4244
4069
  case 4:
4245
- err_10 = _a.sent();
4246
- console.log("perpClient depositStaking error:: ", err_10);
4247
- throw err_10;
4248
- case 5: return [2, {
4070
+ err_8 = _a.sent();
4071
+ console.log("perpClient depositStaking error:: ", err_8);
4072
+ throw err_8;
4073
+ case 5: return [2, {
4249
4074
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4250
4075
  additionalSigners: additionalSigners
4251
4076
  }];
@@ -4253,7 +4078,7 @@ var PerpetualsClient = (function () {
4253
4078
  });
4254
4079
  }); };
4255
4080
  this.refreshStakeWithAllFlpStakeAccounts = function (rewardSymbol, poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4256
- var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_11;
4081
+ var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_9;
4257
4082
  return __generator(this, function (_c) {
4258
4083
  switch (_c.label) {
4259
4084
  case 0:
@@ -4300,9 +4125,9 @@ var PerpetualsClient = (function () {
4300
4125
  refreshStakeInstruction = _c.sent();
4301
4126
  return [2, refreshStakeInstruction];
4302
4127
  case 2:
4303
- err_11 = _c.sent();
4304
- console.log("perpClient refreshStaking error:: ", err_11);
4305
- throw err_11;
4128
+ err_9 = _c.sent();
4129
+ console.log("perpClient refreshStaking error:: ", err_9);
4130
+ throw err_9;
4306
4131
  case 3: return [2];
4307
4132
  }
4308
4133
  });
@@ -4313,7 +4138,7 @@ var PerpetualsClient = (function () {
4313
4138
  args_1[_i - 3] = arguments[_i];
4314
4139
  }
4315
4140
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, flpStakeAccountPk_1], args_1, true), void 0, function (rewardSymbol, poolConfig, flpStakeAccountPk, userPublicKey) {
4316
- var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_12;
4141
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_10;
4317
4142
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4318
4143
  return __generator(this, function (_c) {
4319
4144
  switch (_c.label) {
@@ -4361,9 +4186,9 @@ var PerpetualsClient = (function () {
4361
4186
  refreshStakeInstruction = _c.sent();
4362
4187
  return [2, refreshStakeInstruction];
4363
4188
  case 2:
4364
- err_12 = _c.sent();
4365
- console.log("perpClient refreshStaking error:: ", err_12);
4366
- throw err_12;
4189
+ err_10 = _c.sent();
4190
+ console.log("perpClient refreshStaking error:: ", err_10);
4191
+ throw err_10;
4367
4192
  case 3: return [2];
4368
4193
  }
4369
4194
  });
@@ -4375,7 +4200,7 @@ var PerpetualsClient = (function () {
4375
4200
  args_1[_i - 3] = arguments[_i];
4376
4201
  }
4377
4202
  return __awaiter(_this, __spreadArray([rewardSymbol_1, unstakeAmount_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, unstakeAmount, poolConfig, userPublicKey) {
4378
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_13;
4203
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_11;
4379
4204
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4380
4205
  return __generator(this, function (_b) {
4381
4206
  switch (_b.label) {
@@ -4427,9 +4252,9 @@ var PerpetualsClient = (function () {
4427
4252
  instructions.push(unstakeInstantInstruction);
4428
4253
  return [3, 6];
4429
4254
  case 5:
4430
- err_13 = _b.sent();
4431
- console.log("perpClient unstakeInstant error:: ", err_13);
4432
- throw err_13;
4255
+ err_11 = _b.sent();
4256
+ console.log("perpClient unstakeInstant error:: ", err_11);
4257
+ throw err_11;
4433
4258
  case 6: return [2, {
4434
4259
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4435
4260
  additionalSigners: additionalSigners
@@ -4439,7 +4264,7 @@ var PerpetualsClient = (function () {
4439
4264
  });
4440
4265
  };
4441
4266
  this.setFeeShareBps = function (poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4442
- var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_14;
4267
+ var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_12;
4443
4268
  return __generator(this, function (_c) {
4444
4269
  switch (_c.label) {
4445
4270
  case 0:
@@ -4483,15 +4308,15 @@ var PerpetualsClient = (function () {
4483
4308
  refreshStakeInstruction = _c.sent();
4484
4309
  return [2, refreshStakeInstruction];
4485
4310
  case 2:
4486
- err_14 = _c.sent();
4487
- console.log("perpClient refreshStaking error:: ", err_14);
4488
- throw err_14;
4311
+ err_12 = _c.sent();
4312
+ console.log("perpClient refreshStaking error:: ", err_12);
4313
+ throw err_12;
4489
4314
  case 3: return [2];
4490
4315
  }
4491
4316
  });
4492
4317
  }); };
4493
4318
  this.unstakeRequest = function (unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4494
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_15;
4319
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_13;
4495
4320
  return __generator(this, function (_a) {
4496
4321
  switch (_a.label) {
4497
4322
  case 0:
@@ -4525,9 +4350,9 @@ var PerpetualsClient = (function () {
4525
4350
  instructions.push(unstakeRequestInstruction);
4526
4351
  return [3, 4];
4527
4352
  case 3:
4528
- err_15 = _a.sent();
4529
- console.log("perpClient unstakeRequest error:: ", err_15);
4530
- throw err_15;
4353
+ err_13 = _a.sent();
4354
+ console.log("perpClient unstakeRequest error:: ", err_13);
4355
+ throw err_13;
4531
4356
  case 4: return [2, {
4532
4357
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4533
4358
  additionalSigners: additionalSigners
@@ -4541,7 +4366,7 @@ var PerpetualsClient = (function () {
4541
4366
  args_1[_i - 1] = arguments[_i];
4542
4367
  }
4543
4368
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, pendingActivation, deactivated, createUserLPTA, userPublicKey) {
4544
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_16;
4369
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_14;
4545
4370
  if (pendingActivation === void 0) { pendingActivation = true; }
4546
4371
  if (deactivated === void 0) { deactivated = true; }
4547
4372
  if (createUserLPTA === void 0) { createUserLPTA = true; }
@@ -4597,9 +4422,9 @@ var PerpetualsClient = (function () {
4597
4422
  instructions.push(withdrawStakeInstruction);
4598
4423
  return [3, 6];
4599
4424
  case 5:
4600
- err_16 = _b.sent();
4601
- console.log("perpClient withdrawStake error:: ", err_16);
4602
- throw err_16;
4425
+ err_14 = _b.sent();
4426
+ console.log("perpClient withdrawStake error:: ", err_14);
4427
+ throw err_14;
4603
4428
  case 6: return [2, {
4604
4429
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4605
4430
  additionalSigners: additionalSigners
@@ -4614,7 +4439,7 @@ var PerpetualsClient = (function () {
4614
4439
  args_1[_i - 3] = arguments[_i];
4615
4440
  }
4616
4441
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, tokenStakeAccount_1], args_1, true), void 0, function (rewardSymbol, poolConfig, tokenStakeAccount, createUserATA) {
4617
- var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_17;
4442
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_15;
4618
4443
  if (createUserATA === void 0) { createUserATA = true; }
4619
4444
  return __generator(this, function (_b) {
4620
4445
  switch (_b.label) {
@@ -4675,9 +4500,9 @@ var PerpetualsClient = (function () {
4675
4500
  instructions.push(withdrawStakeInstruction);
4676
4501
  return [3, 6];
4677
4502
  case 5:
4678
- err_17 = _b.sent();
4679
- console.log("perpClient withdrawStake error:: ", err_17);
4680
- throw err_17;
4503
+ err_15 = _b.sent();
4504
+ console.log("perpClient withdrawStake error:: ", err_15);
4505
+ throw err_15;
4681
4506
  case 6: return [2, {
4682
4507
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4683
4508
  additionalSigners: additionalSigners
@@ -4691,11 +4516,13 @@ var PerpetualsClient = (function () {
4691
4516
  for (var _i = 5; _i < arguments.length; _i++) {
4692
4517
  args_1[_i - 5] = arguments[_i];
4693
4518
  }
4694
- 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) {
4695
- var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_18;
4519
+ return __awaiter(_this, __spreadArray([amountIn_1, minCompoundingAmountOut_1, inTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amountIn, minCompoundingAmountOut, inTokenSymbol, rewardTokenMint, poolConfig, skipBalanceChecks, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4520
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, heapSizeIx, addCompoundingLiquidity, err_16;
4696
4521
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4697
4522
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4698
4523
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4524
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4525
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4699
4526
  return __generator(this, function (_f) {
4700
4527
  switch (_f.label) {
4701
4528
  case 0:
@@ -4786,6 +4613,15 @@ var PerpetualsClient = (function () {
4786
4613
  _f.label = 7;
4787
4614
  case 7:
4788
4615
  _f.trys.push([7, 9, , 10]);
4616
+ if (enableHeapSizeIx) {
4617
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4618
+ bytes: 64 * 1024,
4619
+ });
4620
+ if (enableDebugLogs) {
4621
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4622
+ }
4623
+ preInstructions.push(heapSizeIx);
4624
+ }
4789
4625
  return [4, this.program.methods
4790
4626
  .addCompoundingLiquidity({
4791
4627
  amountIn: amountIn,
@@ -4820,8 +4656,8 @@ var PerpetualsClient = (function () {
4820
4656
  instructions.push(addCompoundingLiquidity);
4821
4657
  return [3, 10];
4822
4658
  case 9:
4823
- err_18 = _f.sent();
4824
- console.log("perpClient addCompoundingLiquidity error:: ", err_18);
4659
+ err_16 = _f.sent();
4660
+ console.log("perpClient addCompoundingLiquidity error:: ", err_16);
4825
4661
  return [3, 10];
4826
4662
  case 10: return [2, {
4827
4663
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4836,11 +4672,13 @@ var PerpetualsClient = (function () {
4836
4672
  for (var _i = 5; _i < arguments.length; _i++) {
4837
4673
  args_1[_i - 5] = arguments[_i];
4838
4674
  }
4839
- 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) {
4840
- var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_19;
4675
+ return __awaiter(_this, __spreadArray([compoundingAmountIn_1, minAmountOut_1, outTokenSymbol_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (compoundingAmountIn, minAmountOut, outTokenSymbol, rewardTokenMint, poolConfig, createUserATA, ephemeralSignerPubkey, userPublicKey, enableHeapSizeIx, enableDebugLogs) {
4676
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, heapSizeIx, removeCompoundingLiquidity, err_17;
4841
4677
  if (createUserATA === void 0) { createUserATA = true; }
4842
4678
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4843
4679
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4680
+ if (enableHeapSizeIx === void 0) { enableHeapSizeIx = true; }
4681
+ if (enableDebugLogs === void 0) { enableDebugLogs = false; }
4844
4682
  return __generator(this, function (_f) {
4845
4683
  switch (_f.label) {
4846
4684
  case 0:
@@ -4915,6 +4753,15 @@ var PerpetualsClient = (function () {
4915
4753
  _f.label = 5;
4916
4754
  case 5:
4917
4755
  _f.trys.push([5, 7, , 8]);
4756
+ if (enableHeapSizeIx) {
4757
+ heapSizeIx = web3_js_1.ComputeBudgetProgram.requestHeapFrame({
4758
+ bytes: 64 * 1024,
4759
+ });
4760
+ if (enableDebugLogs) {
4761
+ console.log("SDK: adding 64 liq Data heapSizeIx for addCompoundingLiquidity");
4762
+ }
4763
+ preInstructions.push(heapSizeIx);
4764
+ }
4918
4765
  return [4, this.program.methods
4919
4766
  .removeCompoundingLiquidity({
4920
4767
  compoundingAmountIn: compoundingAmountIn,
@@ -4949,8 +4796,8 @@ var PerpetualsClient = (function () {
4949
4796
  instructions.push(removeCompoundingLiquidity);
4950
4797
  return [3, 8];
4951
4798
  case 7:
4952
- err_19 = _f.sent();
4953
- console.log("perpClient removeCompoundingLiquidity error:: ", err_19);
4799
+ err_17 = _f.sent();
4800
+ console.log("perpClient removeCompoundingLiquidity error:: ", err_17);
4954
4801
  return [3, 8];
4955
4802
  case 8: return [2, {
4956
4803
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4966,7 +4813,7 @@ var PerpetualsClient = (function () {
4966
4813
  args_1[_i - 3] = arguments[_i];
4967
4814
  }
4968
4815
  return __awaiter(_this, __spreadArray([amount_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amount, rewardTokenMint, poolConfig, createUserATA) {
4969
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_20;
4816
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, _a, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _b, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _c, _d, custody, _e, _f, market, migrateStake, err_18;
4970
4817
  if (createUserATA === void 0) { createUserATA = true; }
4971
4818
  return __generator(this, function (_g) {
4972
4819
  switch (_g.label) {
@@ -5064,8 +4911,8 @@ var PerpetualsClient = (function () {
5064
4911
  instructions.push(migrateStake);
5065
4912
  return [3, 8];
5066
4913
  case 7:
5067
- err_20 = _g.sent();
5068
- console.log("perpClient migrateStake error:: ", err_20);
4914
+ err_18 = _g.sent();
4915
+ console.log("perpClient migrateStake error:: ", err_18);
5069
4916
  return [3, 8];
5070
4917
  case 8: return [2, {
5071
4918
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5076,7 +4923,7 @@ var PerpetualsClient = (function () {
5076
4923
  });
5077
4924
  };
5078
4925
  this.migrateFlp = function (amount, rewardTokenMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5079
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_21;
4926
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_19;
5080
4927
  return __generator(this, function (_d) {
5081
4928
  switch (_d.label) {
5082
4929
  case 0:
@@ -5148,8 +4995,8 @@ var PerpetualsClient = (function () {
5148
4995
  instructions.push(migrateFlp);
5149
4996
  return [3, 4];
5150
4997
  case 3:
5151
- err_21 = _d.sent();
5152
- console.log("perpClient migrateFlp error:: ", err_21);
4998
+ err_19 = _d.sent();
4999
+ console.log("perpClient migrateFlp error:: ", err_19);
5153
5000
  return [3, 4];
5154
5001
  case 4: return [2, {
5155
5002
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5164,7 +5011,7 @@ var PerpetualsClient = (function () {
5164
5011
  args_1[_i - 1] = arguments[_i];
5165
5012
  }
5166
5013
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, rewardTokenSymbol) {
5167
- var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_22;
5014
+ var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_20;
5168
5015
  if (rewardTokenSymbol === void 0) { rewardTokenSymbol = 'USDC'; }
5169
5016
  return __generator(this, function (_e) {
5170
5017
  switch (_e.label) {
@@ -5222,8 +5069,8 @@ var PerpetualsClient = (function () {
5222
5069
  instructions.push(compoundingFee);
5223
5070
  return [3, 4];
5224
5071
  case 3:
5225
- err_22 = _e.sent();
5226
- console.log("perpClient compoundingFee error:: ", err_22);
5072
+ err_20 = _e.sent();
5073
+ console.log("perpClient compoundingFee error:: ", err_20);
5227
5074
  return [3, 4];
5228
5075
  case 4: return [2, {
5229
5076
  instructions: __spreadArray([], instructions, true),
@@ -5233,146 +5080,8 @@ var PerpetualsClient = (function () {
5233
5080
  });
5234
5081
  });
5235
5082
  };
5236
- this.burnAndClaim = function (owner, nftMint, poolConfig, createAta) { return __awaiter(_this, void 0, void 0, function () {
5237
- var preInstructions, instructions, postInstructions, additionalSigners, userTokenAccount, _a, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndClaimInstruction, err_23;
5238
- return __generator(this, function (_b) {
5239
- switch (_b.label) {
5240
- case 0:
5241
- preInstructions = [];
5242
- instructions = [];
5243
- postInstructions = [];
5244
- additionalSigners = [];
5245
- _b.label = 1;
5246
- case 1:
5247
- _b.trys.push([1, 7, , 8]);
5248
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, owner, true)];
5249
- case 2:
5250
- userTokenAccount = _b.sent();
5251
- _a = createAta;
5252
- if (!_a) return [3, 4];
5253
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5254
- case 3:
5255
- _a = !(_b.sent());
5256
- _b.label = 4;
5257
- case 4:
5258
- if (_a) {
5259
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, userTokenAccount, owner, poolConfig.tokenMint));
5260
- }
5261
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, owner, true)];
5262
- case 5:
5263
- nftTokenAccount = _b.sent();
5264
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5265
- Buffer.from("trading"),
5266
- nftMint.toBuffer(),
5267
- ], this.programId)[0];
5268
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5269
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5270
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5271
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5272
- return [4, this.program.methods
5273
- .burnAndClaim({})
5274
- .accounts({
5275
- owner: owner,
5276
- receivingTokenAccount: userTokenAccount,
5277
- perpetuals: this.perpetuals.publicKey,
5278
- tokenVault: poolConfig.tokenVault,
5279
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5280
- metadataAccount: metadataAccount,
5281
- collectionMetadata: collectionMetadata,
5282
- edition: edition,
5283
- tokenRecord: tokenRecord,
5284
- tradingAccount: nftTradingAccount,
5285
- transferAuthority: poolConfig.transferAuthority,
5286
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5287
- nftMint: nftMint,
5288
- nftTokenAccount: nftTokenAccount,
5289
- systemProgram: web3_js_1.SystemProgram.programId,
5290
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5291
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5292
- eventAuthority: this.eventAuthority.publicKey,
5293
- program: this.programId,
5294
- receivingTokenMint: poolConfig.tokenMint,
5295
- })
5296
- .instruction()];
5297
- case 6:
5298
- burnAndClaimInstruction = _b.sent();
5299
- instructions.push(burnAndClaimInstruction);
5300
- return [3, 8];
5301
- case 7:
5302
- err_23 = _b.sent();
5303
- console.log("perpClient burnAndClaimInstruction error:: ", err_23);
5304
- throw err_23;
5305
- case 8: return [2, {
5306
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5307
- additionalSigners: additionalSigners
5308
- }];
5309
- }
5310
- });
5311
- }); };
5312
- this.burnAndStake = function (owner, feePayer, nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5313
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndStakeInstruction, err_24;
5314
- return __generator(this, function (_a) {
5315
- switch (_a.label) {
5316
- case 0:
5317
- preInstructions = [];
5318
- instructions = [];
5319
- postInstructions = [];
5320
- additionalSigners = [];
5321
- _a.label = 1;
5322
- case 1:
5323
- _a.trys.push([1, 3, , 4]);
5324
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5325
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, owner, true);
5326
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5327
- Buffer.from("trading"),
5328
- nftMint.toBuffer(),
5329
- ], this.programId)[0];
5330
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5331
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5332
- edition = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("edition")], constants_1.METAPLEX_PROGRAM_ID)[0];
5333
- tokenRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer(), Buffer.from("token_record"), nftTokenAccount.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5334
- return [4, this.program.methods
5335
- .burnAndStake({})
5336
- .accounts({
5337
- owner: owner,
5338
- feePayer: feePayer,
5339
- perpetuals: this.perpetuals.publicKey,
5340
- tokenVault: poolConfig.tokenVault,
5341
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5342
- tokenStakeAccount: tokenStakeAccount,
5343
- metadataAccount: metadataAccount,
5344
- collectionMetadata: collectionMetadata,
5345
- edition: edition,
5346
- tokenRecord: tokenRecord,
5347
- tradingAccount: nftTradingAccount,
5348
- transferAuthority: poolConfig.transferAuthority,
5349
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5350
- nftMint: nftMint,
5351
- nftTokenAccount: nftTokenAccount,
5352
- systemProgram: web3_js_1.SystemProgram.programId,
5353
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5354
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5355
- eventAuthority: this.eventAuthority.publicKey,
5356
- program: this.programId
5357
- })
5358
- .instruction()];
5359
- case 2:
5360
- burnAndStakeInstruction = _a.sent();
5361
- instructions.push(burnAndStakeInstruction);
5362
- return [3, 4];
5363
- case 3:
5364
- err_24 = _a.sent();
5365
- console.log("perpClient burnAndStakeInstruction error:: ", err_24);
5366
- throw err_24;
5367
- case 4: return [2, {
5368
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5369
- additionalSigners: additionalSigners
5370
- }];
5371
- }
5372
- });
5373
- }); };
5374
5083
  this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5375
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_25;
5084
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_21;
5376
5085
  return __generator(this, function (_a) {
5377
5086
  switch (_a.label) {
5378
5087
  case 0:
@@ -5414,9 +5123,9 @@ var PerpetualsClient = (function () {
5414
5123
  instructions.push(depositTokenStakeInstruction);
5415
5124
  return [3, 5];
5416
5125
  case 4:
5417
- err_25 = _a.sent();
5418
- console.log("perpClient depositStakingInstruction error:: ", err_25);
5419
- throw err_25;
5126
+ err_21 = _a.sent();
5127
+ console.log("perpClient depositStakingInstruction error:: ", err_21);
5128
+ throw err_21;
5420
5129
  case 5: return [2, {
5421
5130
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5422
5131
  additionalSigners: additionalSigners
@@ -5425,7 +5134,7 @@ var PerpetualsClient = (function () {
5425
5134
  });
5426
5135
  }); };
5427
5136
  this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5428
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_26;
5137
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_22;
5429
5138
  return __generator(this, function (_a) {
5430
5139
  switch (_a.label) {
5431
5140
  case 0:
@@ -5454,9 +5163,9 @@ var PerpetualsClient = (function () {
5454
5163
  instructions.push(unstakeTokenRequestInstruction);
5455
5164
  return [3, 4];
5456
5165
  case 3:
5457
- err_26 = _a.sent();
5458
- console.log("perpClient unstakeTokenRequestInstruction error:: ", err_26);
5459
- throw err_26;
5166
+ err_22 = _a.sent();
5167
+ console.log("perpClient unstakeTokenRequestInstruction error:: ", err_22);
5168
+ throw err_22;
5460
5169
  case 4: return [2, {
5461
5170
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5462
5171
  additionalSigners: additionalSigners
@@ -5465,7 +5174,7 @@ var PerpetualsClient = (function () {
5465
5174
  });
5466
5175
  }); };
5467
5176
  this.unstakeTokenInstant = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5468
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_27;
5177
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_23;
5469
5178
  return __generator(this, function (_a) {
5470
5179
  switch (_a.label) {
5471
5180
  case 0:
@@ -5506,9 +5215,9 @@ var PerpetualsClient = (function () {
5506
5215
  instructions.push(unstakeTokenInstantInstruction);
5507
5216
  return [3, 5];
5508
5217
  case 4:
5509
- err_27 = _a.sent();
5510
- console.log("perpClient unstakeTokenInstantInstruction error:: ", err_27);
5511
- throw err_27;
5218
+ err_23 = _a.sent();
5219
+ console.log("perpClient unstakeTokenInstantInstruction error:: ", err_23);
5220
+ throw err_23;
5512
5221
  case 5: return [2, {
5513
5222
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5514
5223
  additionalSigners: additionalSigners
@@ -5517,7 +5226,7 @@ var PerpetualsClient = (function () {
5517
5226
  });
5518
5227
  }); };
5519
5228
  this.withdrawToken = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5520
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_28;
5229
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_24;
5521
5230
  return __generator(this, function (_a) {
5522
5231
  switch (_a.label) {
5523
5232
  case 0:
@@ -5558,9 +5267,9 @@ var PerpetualsClient = (function () {
5558
5267
  instructions.push(withdrawTokenInstruction);
5559
5268
  return [3, 5];
5560
5269
  case 4:
5561
- err_28 = _a.sent();
5562
- console.log("perpClient withdrawTokenInstruction error:: ", err_28);
5563
- throw err_28;
5270
+ err_24 = _a.sent();
5271
+ console.log("perpClient withdrawTokenInstruction error:: ", err_24);
5272
+ throw err_24;
5564
5273
  case 5: return [2, {
5565
5274
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5566
5275
  additionalSigners: additionalSigners
@@ -5569,7 +5278,7 @@ var PerpetualsClient = (function () {
5569
5278
  });
5570
5279
  }); };
5571
5280
  this.cancelUnstakeRequest = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5572
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_29;
5281
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_25;
5573
5282
  return __generator(this, function (_a) {
5574
5283
  switch (_a.label) {
5575
5284
  case 0:
@@ -5598,9 +5307,9 @@ var PerpetualsClient = (function () {
5598
5307
  instructions.push(cancelUnstakeRequestInstruction);
5599
5308
  return [3, 4];
5600
5309
  case 3:
5601
- err_29 = _a.sent();
5602
- console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_29);
5603
- throw err_29;
5310
+ err_25 = _a.sent();
5311
+ console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_25);
5312
+ throw err_25;
5604
5313
  case 4: return [2, {
5605
5314
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5606
5315
  additionalSigners: additionalSigners
@@ -5614,7 +5323,7 @@ var PerpetualsClient = (function () {
5614
5323
  args_1[_i - 2] = arguments[_i];
5615
5324
  }
5616
5325
  return __awaiter(_this, __spreadArray([owner_1, poolConfig_1], args_1, true), void 0, function (owner, poolConfig, createUserATA) {
5617
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_30;
5326
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_26;
5618
5327
  if (createUserATA === void 0) { createUserATA = true; }
5619
5328
  return __generator(this, function (_b) {
5620
5329
  switch (_b.label) {
@@ -5660,9 +5369,9 @@ var PerpetualsClient = (function () {
5660
5369
  instructions.push(collectTokenRewardInstruction);
5661
5370
  return [3, 6];
5662
5371
  case 5:
5663
- err_30 = _b.sent();
5664
- console.log("perpClient collectTokenRewardInstruction error:: ", err_30);
5665
- throw err_30;
5372
+ err_26 = _b.sent();
5373
+ console.log("perpClient collectTokenRewardInstruction error:: ", err_26);
5374
+ throw err_26;
5666
5375
  case 6: return [2, {
5667
5376
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5668
5377
  additionalSigners: additionalSigners
@@ -5677,7 +5386,7 @@ var PerpetualsClient = (function () {
5677
5386
  args_1[_i - 3] = arguments[_i];
5678
5387
  }
5679
5388
  return __awaiter(_this, __spreadArray([owner_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rewardSymbol, poolConfig, createUserATA) {
5680
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_31;
5389
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_27;
5681
5390
  if (createUserATA === void 0) { createUserATA = true; }
5682
5391
  return __generator(this, function (_b) {
5683
5392
  switch (_b.label) {
@@ -5724,9 +5433,9 @@ var PerpetualsClient = (function () {
5724
5433
  instructions.push(collectRevenueInstruction);
5725
5434
  return [3, 6];
5726
5435
  case 5:
5727
- err_31 = _b.sent();
5728
- console.log("perpClient collectRevenueInstruction error:: ", err_31);
5729
- throw err_31;
5436
+ err_27 = _b.sent();
5437
+ console.log("perpClient collectRevenueInstruction error:: ", err_27);
5438
+ throw err_27;
5730
5439
  case 6: return [2, {
5731
5440
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5732
5441
  additionalSigners: additionalSigners
@@ -5735,179 +5444,18 @@ var PerpetualsClient = (function () {
5735
5444
  });
5736
5445
  });
5737
5446
  };
5738
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5739
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_32;
5740
- return __generator(this, function (_a) {
5741
- switch (_a.label) {
5742
- case 0:
5743
- publicKey = this.provider.wallet.publicKey;
5744
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5745
- instructions = [];
5746
- additionalSigners = [];
5747
- _a.label = 1;
5748
- case 1:
5749
- _a.trys.push([1, 3, , 4]);
5750
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5751
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5752
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5753
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5754
- return [4, this.programFbnftReward.methods
5755
- .initRewardVault({
5756
- nftCount: nftCount
5757
- })
5758
- .accounts({
5759
- admin: publicKey,
5760
- transferAuthority: nftTransferAuthority,
5761
- rewardVault: rewardVault,
5762
- rewardMint: rewardCustodyMint,
5763
- rewardTokenAccount: rewardTokenAccount,
5764
- collectionMint: collectionMint,
5765
- programData: fbNftProgramData,
5766
- systemProgram: web3_js_1.SystemProgram.programId,
5767
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5768
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5769
- })
5770
- .instruction()];
5771
- case 2:
5772
- initRewardVault = _a.sent();
5773
- instructions.push(initRewardVault);
5774
- return [3, 4];
5775
- case 3:
5776
- err_32 = _a.sent();
5777
- console.log("perpClient InitRewardVault error:: ", err_32);
5778
- throw err_32;
5779
- case 4: return [2, {
5780
- instructions: __spreadArray([], instructions, true),
5781
- additionalSigners: additionalSigners
5782
- }];
5783
- }
5784
- });
5785
- }); };
5786
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5787
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_33;
5788
- return __generator(this, function (_a) {
5789
- switch (_a.label) {
5790
- case 0:
5791
- publicKey = this.provider.wallet.publicKey;
5792
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5793
- instructions = [];
5794
- additionalSigners = [];
5795
- _a.label = 1;
5796
- case 1:
5797
- _a.trys.push([1, 3, , 4]);
5798
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5799
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5800
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5801
- return [4, this.programFbnftReward.methods
5802
- .distributeRewards({
5803
- rewardAmount: rewardAmount
5804
- })
5805
- .accounts({
5806
- admin: publicKey,
5807
- fundingAccount: fundingAccount,
5808
- rewardVault: rewardVault,
5809
- rewardTokenAccount: rewardTokenAccount,
5810
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5811
- })
5812
- .instruction()];
5813
- case 2:
5814
- distributeReward = _a.sent();
5815
- instructions.push(distributeReward);
5816
- return [3, 4];
5817
- case 3:
5818
- err_33 = _a.sent();
5819
- console.log("perpClient distributeReward error:: ", err_33);
5820
- throw err_33;
5821
- case 4: return [2, {
5822
- instructions: __spreadArray([], instructions, true),
5823
- additionalSigners: additionalSigners
5824
- }];
5825
- }
5826
- });
5827
- }); };
5828
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5447
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5829
5448
  var args_1 = [];
5830
5449
  for (var _i = 3; _i < arguments.length; _i++) {
5831
5450
  args_1[_i - 3] = arguments[_i];
5832
5451
  }
5833
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5834
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_34;
5835
- if (createUserATA === void 0) { createUserATA = true; }
5836
- return __generator(this, function (_b) {
5837
- switch (_b.label) {
5838
- case 0:
5839
- publicKey = this.provider.wallet.publicKey;
5840
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5841
- rewardCustodyMint = rewardToken.mintKey;
5842
- instructions = [];
5843
- additionalSigners = [];
5844
- _b.label = 1;
5845
- case 1:
5846
- _b.trys.push([1, 5, , 6]);
5847
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5848
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5849
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5850
- _a = createUserATA;
5851
- if (!_a) return [3, 3];
5852
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5853
- case 2:
5854
- _a = !(_b.sent());
5855
- _b.label = 3;
5856
- case 3:
5857
- if (_a) {
5858
- 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));
5859
- }
5860
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5861
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5862
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5863
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5864
- return [4, this.programFbnftReward.methods
5865
- .collectReward()
5866
- .accounts({
5867
- owner: publicKey,
5868
- feePayer: publicKey,
5869
- nftMint: nftMint,
5870
- nftTokenAccount: nftTokenAccount,
5871
- metadataAccount: metadataAccount,
5872
- receivingAccount: receivingTokenAccount,
5873
- rewardRecord: rewardRecord,
5874
- rewardVault: rewardVault,
5875
- rewardTokenAccount: rewardTokenAccount,
5876
- transferAuthority: nftTransferAuthority,
5877
- systemProgram: web3_js_1.SystemProgram.programId,
5878
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5879
- })
5880
- .instruction()];
5881
- case 4:
5882
- collectNftReward = _b.sent();
5883
- instructions.push(collectNftReward);
5884
- return [3, 6];
5885
- case 5:
5886
- err_34 = _b.sent();
5887
- throw err_34;
5888
- case 6: return [2, {
5889
- instructions: __spreadArray([], instructions, true),
5890
- additionalSigners: additionalSigners
5891
- }];
5892
- }
5893
- });
5894
- });
5895
- };
5896
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5897
- var args_1 = [];
5898
- for (var _i = 2; _i < arguments.length; _i++) {
5899
- args_1[_i - 2] = arguments[_i];
5900
- }
5901
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5902
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_35;
5452
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5453
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5903
5454
  if (createUserATA === void 0) { createUserATA = true; }
5904
5455
  return __generator(this, function (_b) {
5905
5456
  switch (_b.label) {
5906
5457
  case 0:
5907
5458
  publicKey = this.provider.wallet.publicKey;
5908
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5909
- rewardCustodyMint = rewardToken.mintKey;
5910
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5911
5459
  preInstructions = [];
5912
5460
  instructions = [];
5913
5461
  postInstructions = [];
@@ -5915,59 +5463,43 @@ var PerpetualsClient = (function () {
5915
5463
  _b.label = 1;
5916
5464
  case 1:
5917
5465
  _b.trys.push([1, 5, , 6]);
5918
- pool = poolConfig.poolAddress;
5919
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5920
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5466
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5467
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5468
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5921
5469
  _a = createUserATA;
5922
5470
  if (!_a) return [3, 3];
5923
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5471
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5924
5472
  case 2:
5925
5473
  _a = !(_b.sent());
5926
5474
  _b.label = 3;
5927
5475
  case 3:
5928
5476
  if (_a) {
5929
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5930
- }
5931
- tradingAccount = [];
5932
- if (nftTradingAccount) {
5933
- tradingAccount.push({
5934
- pubkey: nftTradingAccount,
5935
- isSigner: false,
5936
- isWritable: true,
5937
- });
5477
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5938
5478
  }
5939
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5940
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5941
- return [4, this.programPerpComposability.methods
5942
- .collectAndDistributeFee()
5479
+ return [4, this.program.methods
5480
+ .collectRebate()
5943
5481
  .accounts({
5944
- perpProgram: this.programId,
5945
- owner: publicKey,
5946
- receivingTokenAccount: receivingTokenAccount,
5947
- transferAuthority: poolConfig.transferAuthority,
5482
+ owner: owner,
5483
+ receivingTokenAccount: userTokenAccount,
5948
5484
  perpetuals: this.perpetuals.publicKey,
5949
- pool: pool,
5950
- feeCustody: rewardCustodyConfig.custodyAccount,
5951
- flpStakeAccount: flpStakeAccount,
5952
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5953
- systemProgram: web3_js_1.SystemProgram.programId,
5485
+ transferAuthority: poolConfig.transferAuthority,
5486
+ rebateVault: poolConfig.rebateVault,
5487
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5488
+ tokenStakeAccount: tokenStakeAccount,
5954
5489
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5955
5490
  eventAuthority: this.eventAuthority.publicKey,
5956
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5957
- fbnftRewardsProgram: this.programFbnftReward.programId,
5958
- rewardVault: rewardVault,
5959
- rewardTokenAccount: rewardTokenAccount
5491
+ program: this.programId,
5492
+ receivingTokenMint: rebateMint,
5960
5493
  })
5961
- .remainingAccounts(tradingAccount)
5962
5494
  .instruction()];
5963
5495
  case 4:
5964
- withdrawStakeInstruction = _b.sent();
5965
- instructions.push(withdrawStakeInstruction);
5496
+ collectRebateInstruction = _b.sent();
5497
+ instructions.push(collectRebateInstruction);
5966
5498
  return [3, 6];
5967
5499
  case 5:
5968
- err_35 = _b.sent();
5969
- console.log("perpClient withdrawStake error:: ", err_35);
5970
- throw err_35;
5500
+ err_28 = _b.sent();
5501
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5502
+ throw err_28;
5971
5503
  case 6: return [2, {
5972
5504
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5973
5505
  additionalSigners: additionalSigners
@@ -5976,13 +5508,60 @@ var PerpetualsClient = (function () {
5976
5508
  });
5977
5509
  });
5978
5510
  };
5511
+ this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5512
+ var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5513
+ return __generator(this, function (_a) {
5514
+ switch (_a.label) {
5515
+ case 0:
5516
+ preInstructions = [];
5517
+ instructions = [];
5518
+ postInstructions = [];
5519
+ additionalSigners = [];
5520
+ _a.label = 1;
5521
+ case 1:
5522
+ _a.trys.push([1, 3, , 4]);
5523
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5524
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5525
+ return [4, this.program.methods
5526
+ .settleRebates()
5527
+ .accounts({
5528
+ transferAuthority: poolConfig.transferAuthority,
5529
+ perpetuals: this.perpetuals.publicKey,
5530
+ pool: poolConfig.poolAddress,
5531
+ rewardCustody: rewardCustody.custodyAccount,
5532
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5533
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5534
+ rebateVault: poolConfig.rebateVault,
5535
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5536
+ tokenMint: rebateMint,
5537
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5538
+ eventAuthority: this.eventAuthority.publicKey,
5539
+ program: this.programId,
5540
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5541
+ })
5542
+ .instruction()];
5543
+ case 2:
5544
+ settleRebatesInstruction = _a.sent();
5545
+ instructions.push(settleRebatesInstruction);
5546
+ return [3, 4];
5547
+ case 3:
5548
+ err_29 = _a.sent();
5549
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5550
+ throw err_29;
5551
+ case 4: return [2, {
5552
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5553
+ additionalSigners: additionalSigners
5554
+ }];
5555
+ }
5556
+ });
5557
+ }); };
5979
5558
  this.placeLimitOrder = function (targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1) {
5980
5559
  var args_1 = [];
5981
5560
  for (var _i = 11; _i < arguments.length; _i++) {
5982
5561
  args_1[_i - 11] = arguments[_i];
5983
5562
  }
5984
5563
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, limitPrice_1, reserveAmount_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, limitPrice, reserveAmount, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, skipBalanceChecks, ephemeralSignerPubkey) {
5985
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_36;
5564
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5986
5565
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5987
5566
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5988
5567
  return __generator(this, function (_c) {
@@ -6088,9 +5667,9 @@ var PerpetualsClient = (function () {
6088
5667
  instructions.push(placeLimitOrder);
6089
5668
  return [3, 10];
6090
5669
  case 9:
6091
- err_36 = _c.sent();
6092
- console.log("perpClient placeLimitOrder error:: ", err_36);
6093
- throw err_36;
5670
+ err_30 = _c.sent();
5671
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5672
+ throw err_30;
6094
5673
  case 10: return [2, {
6095
5674
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6096
5675
  additionalSigners: additionalSigners
@@ -6105,7 +5684,7 @@ var PerpetualsClient = (function () {
6105
5684
  args_1[_i - 11] = arguments[_i];
6106
5685
  }
6107
5686
  return __awaiter(_this, __spreadArray([targetSymbol_1, collateralSymbol_1, reserveSymbol_1, receiveSymbol_1, side_1, orderId_1, limitPrice_1, sizeAmount_1, stopLossPrice_1, takeProfitPrice_1, poolConfig_1], args_1, true), void 0, function (targetSymbol, collateralSymbol, reserveSymbol, receiveSymbol, side, orderId, limitPrice, sizeAmount, stopLossPrice, takeProfitPrice, poolConfig, createUserATA, ephemeralSignerPubkey) {
6108
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_37;
5687
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
6109
5688
  if (createUserATA === void 0) { createUserATA = true; }
6110
5689
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6111
5690
  return __generator(this, function (_b) {
@@ -6196,9 +5775,9 @@ var PerpetualsClient = (function () {
6196
5775
  instructions.push(editLimitOrder);
6197
5776
  return [3, 8];
6198
5777
  case 7:
6199
- err_37 = _b.sent();
6200
- console.log("perpClient editLimitOrder error:: ", err_37);
6201
- throw err_37;
5778
+ err_31 = _b.sent();
5779
+ console.log("perpClient editLimitOrder error:: ", err_31);
5780
+ throw err_31;
6202
5781
  case 8: return [2, {
6203
5782
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6204
5783
  additionalSigners: additionalSigners
@@ -6212,11 +5791,10 @@ var PerpetualsClient = (function () {
6212
5791
  for (var _i = 7; _i < arguments.length; _i++) {
6213
5792
  args_1[_i - 7] = arguments[_i];
6214
5793
  }
6215
- 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) {
6216
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_38;
5794
+ return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount) {
5795
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
6217
5796
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6218
5797
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6219
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6220
5798
  return __generator(this, function (_a) {
6221
5799
  switch (_a.label) {
6222
5800
  case 0:
@@ -6259,16 +5837,16 @@ var PerpetualsClient = (function () {
6259
5837
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6260
5838
  collateralMint: collateralCustodyConfig.mintKey,
6261
5839
  })
6262
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5840
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6263
5841
  .instruction()];
6264
5842
  case 2:
6265
5843
  executeLimitOrder = _a.sent();
6266
5844
  instructions.push(executeLimitOrder);
6267
5845
  return [3, 4];
6268
5846
  case 3:
6269
- err_38 = _a.sent();
6270
- console.log("perpClient executeLimitOrder error:: ", err_38);
6271
- throw err_38;
5847
+ err_32 = _a.sent();
5848
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5849
+ throw err_32;
6272
5850
  case 4: return [2, {
6273
5851
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6274
5852
  additionalSigners: additionalSigners
@@ -6282,11 +5860,10 @@ var PerpetualsClient = (function () {
6282
5860
  for (var _i = 8; _i < arguments.length; _i++) {
6283
5861
  args_1[_i - 8] = arguments[_i];
6284
5862
  }
6285
- 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) {
6286
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_39;
5863
+ return __awaiter(_this, __spreadArray([userPubkey_1, targetSymbol_1, collateralSymbol_1, reserveSymbol_1, side_1, orderId_1, poolConfig_1, privilege_1], args_1, true), void 0, function (userPubkey, targetSymbol, collateralSymbol, reserveSymbol, side, orderId, poolConfig, privilege, tokenStakeAccount, userReferralAccount) {
5864
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6287
5865
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6288
5866
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6289
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6290
5867
  return __generator(this, function (_a) {
6291
5868
  switch (_a.label) {
6292
5869
  case 0:
@@ -6332,16 +5909,16 @@ var PerpetualsClient = (function () {
6332
5909
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6333
5910
  collateralMint: collateralCustodyConfig.mintKey,
6334
5911
  })
6335
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5912
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6336
5913
  .instruction()];
6337
5914
  case 2:
6338
5915
  executeLimitWithSwap = _a.sent();
6339
5916
  instructions.push(executeLimitWithSwap);
6340
5917
  return [3, 4];
6341
5918
  case 3:
6342
- err_39 = _a.sent();
6343
- console.log("perpClient executeLimitWithSwap error:: ", err_39);
6344
- throw err_39;
5919
+ err_33 = _a.sent();
5920
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5921
+ throw err_33;
6345
5922
  case 4: return [2, {
6346
5923
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6347
5924
  additionalSigners: additionalSigners
@@ -6351,7 +5928,7 @@ var PerpetualsClient = (function () {
6351
5928
  });
6352
5929
  };
6353
5930
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6354
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_40;
5931
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6355
5932
  return __generator(this, function (_a) {
6356
5933
  switch (_a.label) {
6357
5934
  case 0:
@@ -6399,9 +5976,9 @@ var PerpetualsClient = (function () {
6399
5976
  instructions.push(placeTriggerOrder);
6400
5977
  return [3, 4];
6401
5978
  case 3:
6402
- err_40 = _a.sent();
6403
- console.log("perpClient placeTriggerOrder error:: ", err_40);
6404
- throw err_40;
5979
+ err_34 = _a.sent();
5980
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5981
+ throw err_34;
6405
5982
  case 4: return [2, {
6406
5983
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6407
5984
  additionalSigners: additionalSigners
@@ -6410,7 +5987,7 @@ var PerpetualsClient = (function () {
6410
5987
  });
6411
5988
  }); };
6412
5989
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6413
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_41;
5990
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6414
5991
  return __generator(this, function (_a) {
6415
5992
  switch (_a.label) {
6416
5993
  case 0:
@@ -6457,9 +6034,9 @@ var PerpetualsClient = (function () {
6457
6034
  instructions.push(editTriggerOrder);
6458
6035
  return [3, 4];
6459
6036
  case 3:
6460
- err_41 = _a.sent();
6461
- console.log("perpClient editTriggerOrder error:: ", err_41);
6462
- throw err_41;
6037
+ err_35 = _a.sent();
6038
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6039
+ throw err_35;
6463
6040
  case 4: return [2, {
6464
6041
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6465
6042
  additionalSigners: additionalSigners
@@ -6468,7 +6045,7 @@ var PerpetualsClient = (function () {
6468
6045
  });
6469
6046
  }); };
6470
6047
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6471
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_42;
6048
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6472
6049
  return __generator(this, function (_a) {
6473
6050
  switch (_a.label) {
6474
6051
  case 0:
@@ -6501,9 +6078,9 @@ var PerpetualsClient = (function () {
6501
6078
  instructions.push(cancelTriggerOrder);
6502
6079
  return [3, 4];
6503
6080
  case 3:
6504
- err_42 = _a.sent();
6505
- console.log("perpClient cancelTriggerOrder error:: ", err_42);
6506
- throw err_42;
6081
+ err_36 = _a.sent();
6082
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6083
+ throw err_36;
6507
6084
  case 4: return [2, {
6508
6085
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6509
6086
  additionalSigners: additionalSigners
@@ -6512,7 +6089,7 @@ var PerpetualsClient = (function () {
6512
6089
  });
6513
6090
  }); };
6514
6091
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6515
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_43;
6092
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6516
6093
  return __generator(this, function (_a) {
6517
6094
  switch (_a.label) {
6518
6095
  case 0:
@@ -6543,9 +6120,9 @@ var PerpetualsClient = (function () {
6543
6120
  instructions.push(cancelAllTriggerOrders);
6544
6121
  return [3, 4];
6545
6122
  case 3:
6546
- err_43 = _a.sent();
6547
- console.log("perpClient cancelAllTriggerOrders error:: ", err_43);
6548
- throw err_43;
6123
+ err_37 = _a.sent();
6124
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6125
+ throw err_37;
6549
6126
  case 4: return [2, {
6550
6127
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6551
6128
  additionalSigners: additionalSigners
@@ -6558,13 +6135,12 @@ var PerpetualsClient = (function () {
6558
6135
  for (var _i = 9; _i < arguments.length; _i++) {
6559
6136
  args_1[_i - 9] = arguments[_i];
6560
6137
  }
6561
- 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) {
6562
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_44;
6138
+ return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, receivingSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, receivingSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount) {
6139
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, userReceivingTokenAccount, userReceivingTokenAccountCollateral, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, collateralToken, receivingToken, _a, _b, positionAccount, orderAccount, custodyAccountMetas, custodyOracleAccountMetas, _c, _d, custody, executeTriggerWithSwap, err_38;
6563
6140
  if (createUserATA === void 0) { createUserATA = true; }
6564
6141
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6565
6142
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6566
6143
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6567
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6568
6144
  return __generator(this, function (_e) {
6569
6145
  switch (_e.label) {
6570
6146
  case 0:
@@ -6659,16 +6235,16 @@ var PerpetualsClient = (function () {
6659
6235
  collateralMint: collateralCustodyConfig.mintKey,
6660
6236
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6661
6237
  })
6662
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6238
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6663
6239
  .instruction()];
6664
6240
  case 8:
6665
6241
  executeTriggerWithSwap = _e.sent();
6666
6242
  instructions.push(executeTriggerWithSwap);
6667
6243
  return [3, 10];
6668
6244
  case 9:
6669
- err_44 = _e.sent();
6670
- console.log("perpClient executeTriggerWithSwap error:: ", err_44);
6671
- throw err_44;
6245
+ err_38 = _e.sent();
6246
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6247
+ throw err_38;
6672
6248
  case 10: return [2, {
6673
6249
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6674
6250
  additionalSigners: additionalSigners
@@ -6682,13 +6258,12 @@ var PerpetualsClient = (function () {
6682
6258
  for (var _i = 8; _i < arguments.length; _i++) {
6683
6259
  args_1[_i - 8] = arguments[_i];
6684
6260
  }
6685
- 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) {
6686
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_45;
6261
+ return __awaiter(_this, __spreadArray([owner_1, targetSymbol_1, collateralSymbol_1, side_1, orderId_1, isStopLoss_1, privilege_1, poolConfig_1], args_1, true), void 0, function (owner, targetSymbol, collateralSymbol, side, orderId, isStopLoss, privilege, poolConfig, createUserATA, ephemeralSignerPubkey, tokenStakeAccount, userReferralAccount) {
6262
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6687
6263
  if (createUserATA === void 0) { createUserATA = true; }
6688
6264
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6689
6265
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6690
6266
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6691
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6692
6267
  return __generator(this, function (_b) {
6693
6268
  switch (_b.label) {
6694
6269
  case 0:
@@ -6748,16 +6323,16 @@ var PerpetualsClient = (function () {
6748
6323
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6749
6324
  receivingMint: collateralCustodyConfig.mintKey
6750
6325
  })
6751
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6326
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6752
6327
  .instruction()];
6753
6328
  case 6:
6754
6329
  executeTriggerOrder = _b.sent();
6755
6330
  instructions.push(executeTriggerOrder);
6756
6331
  return [3, 8];
6757
6332
  case 7:
6758
- err_45 = _b.sent();
6759
- console.log("perpClient executeTriggerOrder error:: ", err_45);
6760
- throw err_45;
6333
+ err_39 = _b.sent();
6334
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6335
+ throw err_39;
6761
6336
  case 8: return [2, {
6762
6337
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6763
6338
  additionalSigners: additionalSigners
@@ -6772,7 +6347,7 @@ var PerpetualsClient = (function () {
6772
6347
  args_1[_i - 5] = arguments[_i];
6773
6348
  }
6774
6349
  return __awaiter(_this, __spreadArray([userInputTokenSymbol_1, userOutputTokenSymbol_1, amountIn_1, minAmountOut_1, poolConfig_1], args_1, true), void 0, function (userInputTokenSymbol, userOutputTokenSymbol, amountIn, minAmountOut, poolConfig, useFeesPool, createUserATA, unWrapSol, skipBalanceChecks, ephemeralSignerPubkey) {
6775
- var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_46;
6350
+ var userInputCustodyConfig, userOutputCustodyConfig, publicKey, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userOutputTokenAccount, userInputTokenAccount, wsolAssociatedTokenAccount, wsolATAExist, unWrappedSolBalance, _a, wsolAssociatedTokenAccount, closeWsolATAIns, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, lamports, _d, custodyAccountMetas, custodyOracleAccountMetas, _e, _f, custody, params, inx, closeWsolATAIns, err_40;
6776
6351
  if (useFeesPool === void 0) { useFeesPool = false; }
6777
6352
  if (createUserATA === void 0) { createUserATA = true; }
6778
6353
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6919,7 +6494,7 @@ var PerpetualsClient = (function () {
6919
6494
  _g.label = 16;
6920
6495
  case 16:
6921
6496
  if (_d) {
6922
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userOutputTokenAccount, publicKey, poolConfig.getTokenFromSymbol(userOutputTokenSymbol).mintKey));
6497
+ 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));
6923
6498
  }
6924
6499
  _g.label = 17;
6925
6500
  case 17:
@@ -6977,9 +6552,9 @@ var PerpetualsClient = (function () {
6977
6552
  }
6978
6553
  return [3, 20];
6979
6554
  case 19:
6980
- err_46 = _g.sent();
6981
- console.error("perpClient Swap error:: ", err_46);
6982
- throw err_46;
6555
+ err_40 = _g.sent();
6556
+ console.error("perpClient Swap error:: ", err_40);
6557
+ throw err_40;
6983
6558
  case 20: return [2, {
6984
6559
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6985
6560
  additionalSigners: additionalSigners
@@ -6989,7 +6564,7 @@ var PerpetualsClient = (function () {
6989
6564
  });
6990
6565
  };
6991
6566
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6992
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_47;
6567
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6993
6568
  return __generator(this, function (_b) {
6994
6569
  switch (_b.label) {
6995
6570
  case 0:
@@ -7034,11 +6609,7 @@ var PerpetualsClient = (function () {
7034
6609
  rewardCustody: rewardCustody.custodyAccount,
7035
6610
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
7036
6611
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
7037
- custody: custody.custodyAccount,
7038
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
7039
- custodyTokenAccount: custody.tokenAccount,
7040
6612
  eventAuthority: this.eventAuthority.publicKey,
7041
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7042
6613
  program: this.programId,
7043
6614
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
7044
6615
  })
@@ -7049,9 +6620,9 @@ var PerpetualsClient = (function () {
7049
6620
  instructions.push(inx);
7050
6621
  return [3, 4];
7051
6622
  case 3:
7052
- err_47 = _b.sent();
7053
- console.error("perpClient Swap error:: ", err_47);
7054
- throw err_47;
6623
+ err_41 = _b.sent();
6624
+ console.error("perpClient Swap error:: ", err_41);
6625
+ throw err_41;
7055
6626
  case 4: return [2, {
7056
6627
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7057
6628
  additionalSigners: additionalSigners
@@ -7060,7 +6631,7 @@ var PerpetualsClient = (function () {
7060
6631
  });
7061
6632
  }); };
7062
6633
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7063
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_48;
6634
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
7064
6635
  return __generator(this, function (_d) {
7065
6636
  switch (_d.label) {
7066
6637
  case 0:
@@ -7108,9 +6679,9 @@ var PerpetualsClient = (function () {
7108
6679
  instructions.push(setLpTokenPriceInstruction);
7109
6680
  return [3, 4];
7110
6681
  case 3:
7111
- err_48 = _d.sent();
7112
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_48);
7113
- throw err_48;
6682
+ err_42 = _d.sent();
6683
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6684
+ throw err_42;
7114
6685
  case 4: return [2, {
7115
6686
  instructions: __spreadArray([], instructions, true),
7116
6687
  additionalSigners: additionalSigners
@@ -7158,7 +6729,7 @@ var PerpetualsClient = (function () {
7158
6729
  });
7159
6730
  }); };
7160
6731
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
7161
- var adminMetas, _i, admins_2, admin, err_49;
6732
+ var adminMetas, _i, admins_2, admin, err_43;
7162
6733
  return __generator(this, function (_a) {
7163
6734
  switch (_a.label) {
7164
6735
  case 0:
@@ -7188,16 +6759,16 @@ var PerpetualsClient = (function () {
7188
6759
  _a.sent();
7189
6760
  return [3, 4];
7190
6761
  case 3:
7191
- err_49 = _a.sent();
6762
+ err_43 = _a.sent();
7192
6763
  if (this.printErrors) {
7193
- console.error("setAdminSigners err:", err_49);
6764
+ console.error("setAdminSigners err:", err_43);
7194
6765
  }
7195
- throw err_49;
6766
+ throw err_43;
7196
6767
  case 4: return [2];
7197
6768
  }
7198
6769
  });
7199
6770
  }); };
7200
- this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor) { return __awaiter(_this, void 0, void 0, function () {
6771
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri, stakingFeeShareBps, vpVolumeFactor, stakingFeeBoostBps, minLpPriceUsd, maxLpPriceUsd, thresholdUsd) { return __awaiter(_this, void 0, void 0, function () {
7201
6772
  return __generator(this, function (_a) {
7202
6773
  switch (_a.label) {
7203
6774
  case 0: return [4, this.program.methods
@@ -7209,7 +6780,11 @@ var PerpetualsClient = (function () {
7209
6780
  metadataTitle: metadataTitle,
7210
6781
  metadataUri: metadataUri,
7211
6782
  stakingFeeShareBps: stakingFeeShareBps,
7212
- vpVolumeFactor: vpVolumeFactor
6783
+ vpVolumeFactor: vpVolumeFactor,
6784
+ stakingFeeBoostBps: stakingFeeBoostBps,
6785
+ minLpPriceUsd: minLpPriceUsd,
6786
+ maxLpPriceUsd: maxLpPriceUsd,
6787
+ thresholdUsd: thresholdUsd
7213
6788
  })
7214
6789
  .accounts({
7215
6790
  admin: this.provider.wallet.publicKey,
@@ -7257,7 +6832,7 @@ var PerpetualsClient = (function () {
7257
6832
  }
7258
6833
  });
7259
6834
  }); };
7260
- this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
6835
+ this.addCustody = function (poolName, tokenMint, isToken222, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment, rewardThreshold, minReserveUsd, limitPriceBufferBps) { return __awaiter(_this, void 0, void 0, function () {
7261
6836
  var trx_id, error_3;
7262
6837
  return __generator(this, function (_a) {
7263
6838
  switch (_a.label) {
@@ -7275,6 +6850,9 @@ var PerpetualsClient = (function () {
7275
6850
  fees: fees,
7276
6851
  borrowRate: borrowRate,
7277
6852
  ratios: ratios,
6853
+ rewardThreshold: rewardThreshold,
6854
+ minReserveUsd: minReserveUsd,
6855
+ limitPriceBufferBps: limitPriceBufferBps
7278
6856
  })
7279
6857
  .accounts({
7280
6858
  admin: this.admin,
@@ -7381,7 +6959,7 @@ var PerpetualsClient = (function () {
7381
6959
  });
7382
6960
  }); };
7383
6961
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7384
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_50;
6962
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7385
6963
  return __generator(this, function (_a) {
7386
6964
  switch (_a.label) {
7387
6965
  case 0:
@@ -7414,9 +6992,9 @@ var PerpetualsClient = (function () {
7414
6992
  instructions.push(withdrawFeesIx);
7415
6993
  return [3, 5];
7416
6994
  case 4:
7417
- err_50 = _a.sent();
7418
- console.log("perpClient setPool error:: ", err_50);
7419
- throw err_50;
6995
+ err_44 = _a.sent();
6996
+ console.log("perpClient setPool error:: ", err_44);
6997
+ throw err_44;
7420
6998
  case 5: return [2, {
7421
6999
  instructions: __spreadArray([], instructions, true),
7422
7000
  additionalSigners: additionalSigners
@@ -7425,7 +7003,7 @@ var PerpetualsClient = (function () {
7425
7003
  });
7426
7004
  }); };
7427
7005
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7428
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_51;
7006
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7429
7007
  return __generator(this, function (_a) {
7430
7008
  switch (_a.label) {
7431
7009
  case 0:
@@ -7459,9 +7037,9 @@ var PerpetualsClient = (function () {
7459
7037
  instructions.push(moveProtocolFeesIx);
7460
7038
  return [3, 4];
7461
7039
  case 3:
7462
- err_51 = _a.sent();
7463
- console.log("perpClient setPool error:: ", err_51);
7464
- throw err_51;
7040
+ err_45 = _a.sent();
7041
+ console.log("perpClient setPool error:: ", err_45);
7042
+ throw err_45;
7465
7043
  case 4: return [2, {
7466
7044
  instructions: __spreadArray([], instructions, true),
7467
7045
  additionalSigners: additionalSigners
@@ -7470,7 +7048,7 @@ var PerpetualsClient = (function () {
7470
7048
  });
7471
7049
  }); };
7472
7050
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7473
- var publicKey, setProtocolFeeShareBpsIx, err_52;
7051
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7474
7052
  return __generator(this, function (_a) {
7475
7053
  switch (_a.label) {
7476
7054
  case 0:
@@ -7490,15 +7068,15 @@ var PerpetualsClient = (function () {
7490
7068
  setProtocolFeeShareBpsIx = _a.sent();
7491
7069
  return [2, setProtocolFeeShareBpsIx];
7492
7070
  case 2:
7493
- err_52 = _a.sent();
7494
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_52);
7495
- throw err_52;
7071
+ err_46 = _a.sent();
7072
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7073
+ throw err_46;
7496
7074
  case 3: return [2];
7497
7075
  }
7498
7076
  });
7499
7077
  }); };
7500
7078
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7501
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_53;
7079
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7502
7080
  return __generator(this, function (_a) {
7503
7081
  switch (_a.label) {
7504
7082
  case 0:
@@ -7525,9 +7103,9 @@ var PerpetualsClient = (function () {
7525
7103
  instructions.push(setPermissionsInstruction);
7526
7104
  return [3, 4];
7527
7105
  case 3:
7528
- err_53 = _a.sent();
7529
- console.log("perpClient setPool error:: ", err_53);
7530
- throw err_53;
7106
+ err_47 = _a.sent();
7107
+ console.log("perpClient setPool error:: ", err_47);
7108
+ throw err_47;
7531
7109
  case 4: return [2, {
7532
7110
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7533
7111
  additionalSigners: additionalSigners
@@ -7536,7 +7114,7 @@ var PerpetualsClient = (function () {
7536
7114
  });
7537
7115
  }); };
7538
7116
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7539
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_54;
7117
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7540
7118
  var _f;
7541
7119
  return __generator(this, function (_g) {
7542
7120
  switch (_g.label) {
@@ -7597,9 +7175,9 @@ var PerpetualsClient = (function () {
7597
7175
  instructions.push(reimburse);
7598
7176
  return [3, 5];
7599
7177
  case 4:
7600
- err_54 = _g.sent();
7601
- console.log("perpClient setPool error:: ", err_54);
7602
- throw err_54;
7178
+ err_48 = _g.sent();
7179
+ console.log("perpClient setPool error:: ", err_48);
7180
+ throw err_48;
7603
7181
  case 5: return [2, {
7604
7182
  instructions: __spreadArray([], instructions, true),
7605
7183
  additionalSigners: additionalSigners
@@ -7608,7 +7186,7 @@ var PerpetualsClient = (function () {
7608
7186
  });
7609
7187
  }); };
7610
7188
  this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7611
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_55;
7189
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7612
7190
  return __generator(this, function (_a) {
7613
7191
  switch (_a.label) {
7614
7192
  case 0:
@@ -7642,9 +7220,9 @@ var PerpetualsClient = (function () {
7642
7220
  instructions.push(setInternalOraclePrice);
7643
7221
  return [3, 4];
7644
7222
  case 3:
7645
- err_55 = _a.sent();
7646
- console.log("perpClient setInternalOracleAccount error:: ", err_55);
7647
- throw err_55;
7223
+ err_49 = _a.sent();
7224
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7225
+ throw err_49;
7648
7226
  case 4: return [2, {
7649
7227
  instructions: __spreadArray([], instructions, true),
7650
7228
  additionalSigners: additionalSigners
@@ -7653,7 +7231,7 @@ var PerpetualsClient = (function () {
7653
7231
  });
7654
7232
  }); };
7655
7233
  this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7656
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_56;
7234
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7657
7235
  return __generator(this, function (_a) {
7658
7236
  switch (_a.label) {
7659
7237
  case 0:
@@ -7699,9 +7277,9 @@ var PerpetualsClient = (function () {
7699
7277
  instructions.push(setInternalOraclePrice);
7700
7278
  return [3, 4];
7701
7279
  case 3:
7702
- err_56 = _a.sent();
7703
- console.log("perpClient setInternalOracleAccount error:: ", err_56);
7704
- throw err_56;
7280
+ err_50 = _a.sent();
7281
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7282
+ throw err_50;
7705
7283
  case 4: return [2, {
7706
7284
  instructions: __spreadArray([], instructions, true),
7707
7285
  additionalSigners: additionalSigners
@@ -7710,7 +7288,7 @@ var PerpetualsClient = (function () {
7710
7288
  });
7711
7289
  }); };
7712
7290
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7713
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_57;
7291
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7714
7292
  return __generator(this, function (_a) {
7715
7293
  switch (_a.label) {
7716
7294
  case 0:
@@ -7750,9 +7328,9 @@ var PerpetualsClient = (function () {
7750
7328
  instructions.push(setInternalOraclePrice);
7751
7329
  return [3, 4];
7752
7330
  case 3:
7753
- err_57 = _a.sent();
7754
- console.log("perpClient setInternalOracleAccount error:: ", err_57);
7755
- throw err_57;
7331
+ err_51 = _a.sent();
7332
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7333
+ throw err_51;
7756
7334
  case 4: return [2, {
7757
7335
  instructions: __spreadArray([], instructions, true),
7758
7336
  additionalSigners: additionalSigners
@@ -7761,7 +7339,7 @@ var PerpetualsClient = (function () {
7761
7339
  });
7762
7340
  }); };
7763
7341
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7764
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_58;
7342
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7765
7343
  return __generator(this, function (_a) {
7766
7344
  switch (_a.label) {
7767
7345
  case 0:
@@ -7799,8 +7377,8 @@ var PerpetualsClient = (function () {
7799
7377
  instructions.push(renameFlp);
7800
7378
  return [3, 4];
7801
7379
  case 3:
7802
- err_58 = _a.sent();
7803
- console.log("perpClient renameFlp error:: ", err_58);
7380
+ err_52 = _a.sent();
7381
+ console.log("perpClient renameFlp error:: ", err_52);
7804
7382
  return [3, 4];
7805
7383
  case 4: return [2, {
7806
7384
  instructions: __spreadArray([], instructions, true),
@@ -7810,7 +7388,7 @@ var PerpetualsClient = (function () {
7810
7388
  });
7811
7389
  }); };
7812
7390
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7813
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_59;
7391
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7814
7392
  return __generator(this, function (_a) {
7815
7393
  switch (_a.label) {
7816
7394
  case 0:
@@ -7848,9 +7426,9 @@ var PerpetualsClient = (function () {
7848
7426
  instructions.push(initStakeInstruction);
7849
7427
  return [3, 4];
7850
7428
  case 3:
7851
- err_59 = _a.sent();
7852
- console.log("perpClient InitStaking error:: ", err_59);
7853
- throw err_59;
7429
+ err_53 = _a.sent();
7430
+ console.log("perpClient InitStaking error:: ", err_53);
7431
+ throw err_53;
7854
7432
  case 4: return [2, {
7855
7433
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7856
7434
  additionalSigners: additionalSigners
@@ -7859,7 +7437,7 @@ var PerpetualsClient = (function () {
7859
7437
  });
7860
7438
  }); };
7861
7439
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7862
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_60;
7440
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7863
7441
  return __generator(this, function (_a) {
7864
7442
  switch (_a.label) {
7865
7443
  case 0:
@@ -7888,7 +7466,6 @@ var PerpetualsClient = (function () {
7888
7466
  transferAuthority: poolConfig.transferAuthority,
7889
7467
  perpetuals: this.perpetuals.publicKey,
7890
7468
  pool: poolConfig.poolAddress,
7891
- custody: rewardCustodyConfig.custodyAccount,
7892
7469
  lpTokenMint: poolConfig.stakedLpTokenMint,
7893
7470
  compoundingVault: compoundingVault,
7894
7471
  compoundingTokenMint: compoundingTokenMint,
@@ -7904,9 +7481,9 @@ var PerpetualsClient = (function () {
7904
7481
  instructions.push(initCompoundingInstruction);
7905
7482
  return [3, 4];
7906
7483
  case 3:
7907
- err_60 = _a.sent();
7908
- console.log("perpClient initCompounding error:: ", err_60);
7909
- throw err_60;
7484
+ err_54 = _a.sent();
7485
+ console.log("perpClient initCompounding error:: ", err_54);
7486
+ throw err_54;
7910
7487
  case 4: return [2, {
7911
7488
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7912
7489
  additionalSigners: additionalSigners
@@ -7915,7 +7492,7 @@ var PerpetualsClient = (function () {
7915
7492
  });
7916
7493
  }); };
7917
7494
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7918
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_61;
7495
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7919
7496
  return __generator(this, function (_a) {
7920
7497
  switch (_a.label) {
7921
7498
  case 0:
@@ -7956,9 +7533,9 @@ var PerpetualsClient = (function () {
7956
7533
  instructions.push(initTokenVaultInstruction);
7957
7534
  return [3, 4];
7958
7535
  case 3:
7959
- err_61 = _a.sent();
7960
- console.log("perpClient InitTokenVaultInstruction error:: ", err_61);
7961
- throw err_61;
7536
+ err_55 = _a.sent();
7537
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7538
+ throw err_55;
7962
7539
  case 4: return [2, {
7963
7540
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7964
7541
  additionalSigners: additionalSigners
@@ -7967,7 +7544,7 @@ var PerpetualsClient = (function () {
7967
7544
  });
7968
7545
  }); };
7969
7546
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7970
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_62;
7547
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7971
7548
  return __generator(this, function (_a) {
7972
7549
  switch (_a.label) {
7973
7550
  case 0:
@@ -7998,9 +7575,9 @@ var PerpetualsClient = (function () {
7998
7575
  instructions.push(setTokenVaultConfigInstruction);
7999
7576
  return [3, 4];
8000
7577
  case 3:
8001
- err_62 = _a.sent();
8002
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_62);
8003
- throw err_62;
7578
+ err_56 = _a.sent();
7579
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7580
+ throw err_56;
8004
7581
  case 4: return [2, {
8005
7582
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8006
7583
  additionalSigners: additionalSigners
@@ -8009,7 +7586,7 @@ var PerpetualsClient = (function () {
8009
7586
  });
8010
7587
  }); };
8011
7588
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8012
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_63;
7589
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
8013
7590
  return __generator(this, function (_a) {
8014
7591
  switch (_a.label) {
8015
7592
  case 0:
@@ -8048,9 +7625,59 @@ var PerpetualsClient = (function () {
8048
7625
  instructions.push(withdrawInstantFeeInstruction);
8049
7626
  return [3, 6];
8050
7627
  case 5:
8051
- err_63 = _a.sent();
8052
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_63);
8053
- throw err_63;
7628
+ err_57 = _a.sent();
7629
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7630
+ throw err_57;
7631
+ case 6: return [2, {
7632
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7633
+ additionalSigners: additionalSigners
7634
+ }];
7635
+ }
7636
+ });
7637
+ }); };
7638
+ this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7639
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7640
+ return __generator(this, function (_a) {
7641
+ switch (_a.label) {
7642
+ case 0:
7643
+ publicKey = this.provider.wallet.publicKey;
7644
+ preInstructions = [];
7645
+ instructions = [];
7646
+ postInstructions = [];
7647
+ additionalSigners = [];
7648
+ _a.label = 1;
7649
+ case 1:
7650
+ _a.trys.push([1, 5, , 6]);
7651
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, publicKey, true)];
7652
+ case 2:
7653
+ receivingTokenAccount = _a.sent();
7654
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
7655
+ case 3:
7656
+ if (!(_a.sent())) {
7657
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, poolConfig.tokenMint));
7658
+ }
7659
+ return [4, this.program.methods
7660
+ .withdrawUnclaimedTokens({})
7661
+ .accounts({
7662
+ admin: publicKey,
7663
+ multisig: this.multisig.publicKey,
7664
+ perpetuals: this.perpetuals.publicKey,
7665
+ transferAuthority: poolConfig.transferAuthority,
7666
+ tokenVault: poolConfig.tokenVault,
7667
+ tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
7668
+ receivingTokenAccount: receivingTokenAccount,
7669
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7670
+ receivingTokenMint: poolConfig.tokenMint,
7671
+ })
7672
+ .instruction()];
7673
+ case 4:
7674
+ withdrawUnclaimedTokensInstruction = _a.sent();
7675
+ instructions.push(withdrawUnclaimedTokensInstruction);
7676
+ return [3, 6];
7677
+ case 5:
7678
+ err_58 = _a.sent();
7679
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7680
+ throw err_58;
8054
7681
  case 6: return [2, {
8055
7682
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8056
7683
  additionalSigners: additionalSigners
@@ -8059,7 +7686,7 @@ var PerpetualsClient = (function () {
8059
7686
  });
8060
7687
  }); };
8061
7688
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8062
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_64;
7689
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
8063
7690
  return __generator(this, function (_a) {
8064
7691
  switch (_a.label) {
8065
7692
  case 0:
@@ -8096,9 +7723,55 @@ var PerpetualsClient = (function () {
8096
7723
  instructions.push(initRevenueTokenAccountInstruction);
8097
7724
  return [3, 4];
8098
7725
  case 3:
8099
- err_64 = _a.sent();
8100
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_64);
8101
- throw err_64;
7726
+ err_59 = _a.sent();
7727
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7728
+ throw err_59;
7729
+ case 4: return [2, {
7730
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7731
+ additionalSigners: additionalSigners
7732
+ }];
7733
+ }
7734
+ });
7735
+ }); };
7736
+ this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7737
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7738
+ return __generator(this, function (_a) {
7739
+ switch (_a.label) {
7740
+ case 0:
7741
+ publicKey = this.provider.wallet.publicKey;
7742
+ preInstructions = [];
7743
+ instructions = [];
7744
+ postInstructions = [];
7745
+ additionalSigners = [];
7746
+ _a.label = 1;
7747
+ case 1:
7748
+ _a.trys.push([1, 3, , 4]);
7749
+ rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7750
+ return [4, this.program.methods
7751
+ .initRebateVault({
7752
+ allowRebatePayout: allowRebatePayout
7753
+ })
7754
+ .accounts({
7755
+ admin: publicKey,
7756
+ multisig: this.multisig.publicKey,
7757
+ transferAuthority: poolConfig.transferAuthority,
7758
+ perpetuals: this.perpetuals.publicKey,
7759
+ rebateMint: rebateCustodyMint,
7760
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
7761
+ rebateVault: poolConfig.rebateVault,
7762
+ systemProgram: web3_js_1.SystemProgram.programId,
7763
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7764
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
7765
+ })
7766
+ .instruction()];
7767
+ case 2:
7768
+ initRebateVaultInstruction = _a.sent();
7769
+ instructions.push(initRebateVaultInstruction);
7770
+ return [3, 4];
7771
+ case 3:
7772
+ err_60 = _a.sent();
7773
+ console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7774
+ throw err_60;
8102
7775
  case 4: return [2, {
8103
7776
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8104
7777
  additionalSigners: additionalSigners
@@ -8107,7 +7780,7 @@ var PerpetualsClient = (function () {
8107
7780
  });
8108
7781
  }); };
8109
7782
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8110
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_65;
7783
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
8111
7784
  return __generator(this, function (_a) {
8112
7785
  switch (_a.label) {
8113
7786
  case 0:
@@ -8146,9 +7819,9 @@ var PerpetualsClient = (function () {
8146
7819
  instructions.push(distributeTokenRewardInstruction);
8147
7820
  return [3, 4];
8148
7821
  case 3:
8149
- err_65 = _a.sent();
8150
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_65);
8151
- throw err_65;
7822
+ err_61 = _a.sent();
7823
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7824
+ throw err_61;
8152
7825
  case 4: return [2, {
8153
7826
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8154
7827
  additionalSigners: additionalSigners
@@ -8157,7 +7830,7 @@ var PerpetualsClient = (function () {
8157
7830
  });
8158
7831
  }); };
8159
7832
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
8160
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_66;
7833
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
8161
7834
  return __generator(this, function (_a) {
8162
7835
  switch (_a.label) {
8163
7836
  case 0:
@@ -8185,9 +7858,9 @@ var PerpetualsClient = (function () {
8185
7858
  instructions.push(setTokenStakeLevelInstruction);
8186
7859
  return [3, 4];
8187
7860
  case 3:
8188
- err_66 = _a.sent();
8189
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_66);
8190
- throw err_66;
7861
+ err_62 = _a.sent();
7862
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7863
+ throw err_62;
8191
7864
  case 4: return [2, {
8192
7865
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8193
7866
  additionalSigners: additionalSigners
@@ -8196,7 +7869,7 @@ var PerpetualsClient = (function () {
8196
7869
  });
8197
7870
  }); };
8198
7871
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8199
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_67;
7872
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8200
7873
  return __generator(this, function (_a) {
8201
7874
  switch (_a.label) {
8202
7875
  case 0:
@@ -8228,9 +7901,9 @@ var PerpetualsClient = (function () {
8228
7901
  instructions.push(setTokenRewardInstruction);
8229
7902
  return [3, 4];
8230
7903
  case 3:
8231
- err_67 = _a.sent();
8232
- console.log("perpClient setTokenRewardInstruction error:: ", err_67);
8233
- throw err_67;
7904
+ err_63 = _a.sent();
7905
+ console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7906
+ throw err_63;
8234
7907
  case 4: return [2, {
8235
7908
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8236
7909
  additionalSigners: additionalSigners
@@ -8239,7 +7912,7 @@ var PerpetualsClient = (function () {
8239
7912
  });
8240
7913
  }); };
8241
7914
  this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
8242
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_68;
7915
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
8243
7916
  return __generator(this, function (_a) {
8244
7917
  switch (_a.label) {
8245
7918
  case 0:
@@ -8268,9 +7941,9 @@ var PerpetualsClient = (function () {
8268
7941
  instructions.push(resizeInternalOracleInstruction);
8269
7942
  return [3, 4];
8270
7943
  case 3:
8271
- err_68 = _a.sent();
8272
- console.log("perpClient resizeInternalOracleInstruction error:: ", err_68);
8273
- throw err_68;
7944
+ err_64 = _a.sent();
7945
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7946
+ throw err_64;
8274
7947
  case 4: return [2, {
8275
7948
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8276
7949
  additionalSigners: additionalSigners