flash-sdk 9.0.3 → 9.0.4-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -459,16 +459,13 @@ var PerpetualsClient = (function () {
459
459
  };
460
460
  };
461
461
  this.getRemoveLiquidityAmountAndFeeSync = function (lpAmountIn, poolAccount, outputTokenPrice, outputTokenEmaPrice, outputTokenCustodyAccount, lpTokenSupply, poolAumUsdMax, poolConfig) {
462
- if (outputTokenCustodyAccount.isVirtual) {
463
- throw new Error("Cannot remove liquidity in virtual Custody");
464
- }
465
462
  if (!outputTokenPrice.exponent.eq(outputTokenEmaPrice.exponent)) {
466
463
  throw new Error("exponent mistach");
467
464
  }
468
465
  var minMaxPrice = _this.getMinAndMaxOraclePriceSync(outputTokenPrice, outputTokenEmaPrice, outputTokenCustodyAccount);
469
466
  var removeAmountUsd = (poolAumUsdMax.mul(lpAmountIn)).div(lpTokenSupply);
470
467
  var removeAmount;
471
- var oneOracle = OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(10).pow(outputTokenPrice.exponent.abs()), exponent: outputTokenPrice.exponent, confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
468
+ var oneOracle = OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(Math.pow(10, 8)), exponent: new anchor_1.BN(-8), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
472
469
  if (outputTokenCustodyAccount.isStable && minMaxPrice.min != minMaxPrice.max && minMaxPrice.max.price.lt(oneOracle.price)) {
473
470
  removeAmount = oneOracle.getTokenAmount(removeAmountUsd, outputTokenCustodyAccount.decimals);
474
471
  }
@@ -496,15 +493,9 @@ var PerpetualsClient = (function () {
496
493
  case types_1.FeesAction.SwapOut:
497
494
  fees = inputTokenCustodyAccount.fees.swapOut;
498
495
  break;
499
- case types_1.FeesAction.StableSwapIn:
500
- fees = inputTokenCustodyAccount.fees.stableSwapIn;
501
- break;
502
- case types_1.FeesAction.StableSwapOut:
503
- fees = inputTokenCustodyAccount.fees.stableSwapOut;
504
- break;
505
496
  }
506
497
  if (inputTokenCustodyAccount.fees.mode == types_1.FeesMode.Fixed) {
507
- return { feeBps: fees.targetFee, feeAmount: anchor_1.BN.max(amountAdd, amountRemove).mul(fees.targetFee).div(new anchor_1.BN(constants_1.RATE_POWER)) };
498
+ return { feeBps: fees.minFee, feeAmount: anchor_1.BN.max(amountAdd, amountRemove).mul(fees.minFee).div(new anchor_1.BN(constants_1.RATE_POWER)) };
508
499
  }
509
500
  var newRatio = _this.getNewRatioHelper(amountAdd, amountRemove, inputTokenCustodyAccount, maxOraclePrice, poolAumUsdMax);
510
501
  var index = poolAccount.custodies.findIndex(function (c) { return c.equals(inputTokenCustodyAccount.publicKey); });
@@ -569,7 +560,6 @@ var PerpetualsClient = (function () {
569
560
  }
570
561
  else {
571
562
  minPrice.price = maxPrice.price.sub(maxPrice.confidence);
572
- maxPrice.price = maxPrice.price.add(maxPrice.confidence);
573
563
  return {
574
564
  min: minPrice,
575
565
  max: maxPrice
@@ -583,6 +573,38 @@ var PerpetualsClient = (function () {
583
573
  };
584
574
  }
585
575
  };
576
+ this.getMinAndMaxPriceSync = function (price, emaPrice, custodyAccount) {
577
+ var minPrice = price;
578
+ var divergenceBps;
579
+ if (custodyAccount.isStable) {
580
+ divergenceBps = price.getDivergenceFactor(OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(10).pow(price.exponent.abs()), exponent: price.exponent, confidence: price.confidence, timestamp: price.timestamp }));
581
+ }
582
+ else {
583
+ divergenceBps = price.getDivergenceFactor(emaPrice);
584
+ }
585
+ if (divergenceBps.gte(custodyAccount.oracle.maxDivergenceBps)) {
586
+ var factorBps = custodyAccount.oracle.maxDivergenceBps.isZero ? constants_1.BN_ZERO : (divergenceBps.mul(new anchor_1.BN(constants_1.BPS_POWER))).div(custodyAccount.oracle.maxDivergenceBps);
587
+ var confBps = (price.confidence.muln(constants_1.BPS_POWER)).div(price.price);
588
+ if (confBps.lt(custodyAccount.oracle.maxConfBps)) {
589
+ var confFactor = anchor_1.BN.min(factorBps, new anchor_1.BN(50000));
590
+ var confScale = (price.confidence.mul(confFactor)).div(new anchor_1.BN(constants_1.BPS_POWER));
591
+ minPrice.price = price.price.sub(confScale);
592
+ }
593
+ else {
594
+ minPrice.price = price.price.sub(price.confidence);
595
+ }
596
+ }
597
+ else {
598
+ return {
599
+ min: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price,
600
+ max: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price
601
+ };
602
+ }
603
+ return {
604
+ min: minPrice.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price,
605
+ max: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price
606
+ };
607
+ };
586
608
  this.checkIfPriceStaleOrCustom = function (price, emaPrice, custodyAccount, timestampInSeconds) {
587
609
  if (timestampInSeconds.lt(price.timestamp)) {
588
610
  throw new Error("current time cannot be timepassed");
@@ -616,24 +638,41 @@ var PerpetualsClient = (function () {
616
638
  var averageEntryPrice = totalValue.div(totalSize);
617
639
  return averageEntryPrice;
618
640
  };
619
- this.getLeverageSync = function (sizeUsd, collateralAmount, collateralMinOraclePrice, collateralTokenDecimals, pnlUsd) {
620
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenDecimals);
621
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd);
622
- if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
623
- return sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
641
+ this.getLeverageContractHelper = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
642
+ var pnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
643
+ var exitFee = _this.getExitFeeSync(positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice);
644
+ var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
645
+ var unsettledFeesUsd = exitFee.exitFeeUsd.add(lockFeeUsd);
646
+ var lossUsd = pnl.lossUsd.add(unsettledFeesUsd);
647
+ var currentMarginUsd = constants_1.BN_ZERO;
648
+ if (isInitial) {
649
+ currentMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
650
+ }
651
+ else {
652
+ currentMarginUsd = positionAccount.collateralUsd.add(pnl.profitUsd).sub(lossUsd);
653
+ }
654
+ if (currentMarginUsd.gt(constants_1.BN_ZERO)) {
655
+ return positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentMarginUsd);
624
656
  }
625
657
  else {
626
658
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
627
659
  }
628
660
  };
629
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap, pnlUsd) {
661
+ this.getLeverageSync = function (positionAccount, finalCollateralUsd, finalSizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig) {
662
+ positionAccount = positionAccount.clone();
663
+ positionAccount.sizeUsd = finalSizeUsd;
664
+ positionAccount.sizeAmount = targetPrice.getTokenAmount(finalSizeUsd, targetCustodyAccount.decimals);
665
+ positionAccount.collateralUsd = finalCollateralUsd;
666
+ return _this.getLeverageContractHelper(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, isInitial, poolConfig);
667
+ };
668
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, pnlUsd) {
630
669
  var finalCollateralAmount = constants_1.BN_ZERO;
631
670
  if (!inputDeltaAmount.isZero()) {
632
671
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
633
672
  finalCollateralAmount = inputDeltaAmount;
634
673
  }
635
674
  else {
636
- var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
675
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(inputDeltaAmount, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
637
676
  finalCollateralAmount = swapAmountOut;
638
677
  }
639
678
  }
@@ -659,9 +698,8 @@ var PerpetualsClient = (function () {
659
698
  entryOraclePrice.price = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryOraclePrice.price, sizeDeltaAmount);
660
699
  }
661
700
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
662
- var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
663
- var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
664
- var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
701
+ var finalCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(finalCollateralAmount, collateralTokenCustodyAccount.decimals);
702
+ var currentCollateralUsdIncludingPnl = finalCollateralUsd.add(pnlUsd).sub(openFeeUsd);
665
703
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
666
704
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
667
705
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
@@ -700,12 +738,13 @@ var PerpetualsClient = (function () {
700
738
  var sizeDeltaUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
701
739
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
702
740
  }
703
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
741
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
742
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
743
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
704
744
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
705
- var lockFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
706
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryOraclePrice, lockFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
745
+ var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
746
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
707
747
  var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
708
- var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
709
748
  var feeUsd = constants_1.BN_ZERO;
710
749
  var feeAmount = constants_1.BN_ZERO;
711
750
  var feeUsdAfterDiscount = constants_1.BN_ZERO;
@@ -714,11 +753,11 @@ var PerpetualsClient = (function () {
714
753
  }
715
754
  else {
716
755
  feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
717
- feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
756
+ feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
718
757
  if (discountBps.gt(constants_1.BN_ZERO)) {
719
758
  feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
720
759
  feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
721
- feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
760
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralMinMaxPrice.min.price);
722
761
  }
723
762
  else {
724
763
  feeUsdAfterDiscount = feeUsd;
@@ -777,25 +816,26 @@ var PerpetualsClient = (function () {
777
816
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
778
817
  throw new Error("Delta Amounts cannot be negative ");
779
818
  }
780
- resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
781
- resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
782
819
  if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
783
820
  throw new Error("cannot remove/close more than collateral/Size");
784
821
  }
785
822
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
786
823
  var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
787
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
824
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
825
+ var collateralDeltaUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
826
+ resultingPositionAccount.collateralUsd = resultingPositionAccount.collateralUsd.sub(collateralDeltaUsd);
827
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
788
828
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
789
- var lockAndUnsettledFee = collateralTokenMinOraclePrice.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
829
+ var lockAndUnsettledFee = collateralMinMaxPrice.min.getTokenAmount(lockAndUnsettledFeeUsd, collateralCustodyAccount.decimals);
790
830
  var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
791
831
  var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
792
- var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
832
+ var exitFeeAmount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
793
833
  var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
794
834
  var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
795
835
  if (discountBps.gt(constants_1.BN_ZERO)) {
796
836
  exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
797
837
  exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
798
- exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
838
+ exitFeeAmountAfterDiscount = collateralMinMaxPrice.max.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
799
839
  }
800
840
  else {
801
841
  exitFeeUsdAfterDiscount = exitFeeUsd;
@@ -805,7 +845,7 @@ var PerpetualsClient = (function () {
805
845
  price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
806
846
  });
807
847
  resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
808
- var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
848
+ var liquidationPrice = _this.getLiquidationPriceContractHelper(positionEntryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount);
809
849
  return {
810
850
  exitOraclePrice: exitOraclePrice,
811
851
  borrowFeeUsd: lockAndUnsettledFeeUsd,
@@ -818,12 +858,11 @@ var PerpetualsClient = (function () {
818
858
  };
819
859
  };
820
860
  this.getTradeSpread = function (targetCustodyAccount, sizeUsd) {
821
- if (targetCustodyAccount.pricing.tradeSpreadMax.isZero() || sizeUsd.isZero()) {
861
+ if (targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin).isZero() || sizeUsd.isZero()) {
822
862
  return constants_1.BN_ZERO;
823
863
  }
824
- var slope = (targetCustodyAccount.pricing.tradeSpreadMax
825
- .sub(targetCustodyAccount.pricing.tradeSpreadMin)
826
- .mul(new anchor_1.BN(10).pow(new anchor_1.BN(constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))).div(targetCustodyAccount.pricing.maxPositionLockedUsd);
864
+ var slope = ((targetCustodyAccount.pricing.tradeSpreadMax.sub(targetCustodyAccount.pricing.tradeSpreadMin)).mul(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS)))))
865
+ .div(targetCustodyAccount.pricing.maxPositionSizeUsd);
827
866
  var variable = (slope.mul(sizeUsd)).div(new anchor_1.BN(Math.pow(10, (constants_1.RATE_DECIMALS + constants_1.BPS_DECIMALS))));
828
867
  var finalSpread = targetCustodyAccount.pricing.tradeSpreadMin.add(variable);
829
868
  return finalSpread;
@@ -838,21 +877,11 @@ var PerpetualsClient = (function () {
838
877
  var exitOraclePrice = OraclePrice_1.OraclePrice.from({ price: exitPriceBN, exponent: maxPrice.exponent, confidence: maxPrice.confidence, timestamp: maxPrice.timestamp });
839
878
  return exitOraclePrice;
840
879
  };
841
- this.getExitOraclePriceWithoutSpreadSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
842
- var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
843
- if ((0, types_1.isVariant)(side, 'long')) {
844
- return minPrice;
845
- }
846
- else {
847
- return maxPrice;
848
- }
849
- };
850
880
  this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
851
881
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
852
- var collateralTokenMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min.price;
882
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
853
883
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
854
- var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
855
- .multipliedBy(collateralTokenMinPriceUi);
884
+ var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals)).multipliedBy(collateralTokenMinPriceUi);
856
885
  var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
857
886
  if (!discountBps.isZero()) {
858
887
  var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
@@ -860,23 +889,23 @@ var PerpetualsClient = (function () {
860
889
  }
861
890
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
862
891
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
863
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
864
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, lockedUsd);
892
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toString(), constants_1.USD_DECIMALS);
893
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
865
894
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
866
895
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
867
896
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
868
897
  };
869
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap, discountBps) {
898
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig, discountBps) {
870
899
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
871
900
  var finalCollateralAmount = constants_1.BN_ZERO;
872
901
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
873
902
  finalCollateralAmount = amountIn;
874
903
  }
875
904
  else {
876
- var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountOut;
905
+ var swapAmountOut = _this.getSwapAmountAndFeesSync(amountIn, constants_1.BN_ZERO, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountOut;
877
906
  finalCollateralAmount = swapAmountOut;
878
907
  }
879
- var collateralTokenMinPrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min.price;
908
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
880
909
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
881
910
  var collateralAmtMinUsdUi = new bignumber_js_1.default(finalCollateralAmount.toString()).dividedBy(Math.pow(10, collateralTokenCustodyAccount.decimals))
882
911
  .multipliedBy(collateralTokenMinPriceUi);
@@ -887,15 +916,15 @@ var PerpetualsClient = (function () {
887
916
  }
888
917
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
889
918
  .dividedBy(new bignumber_js_1.default(1).plus((new bignumber_js_1.default(2).multipliedBy(openPosFeeRateUi)).multipliedBy(leverage)));
890
- var lockedUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
891
- var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, lockedUsd);
919
+ var sizeUsd = (0, utils_1.uiDecimalsToNative)(sizeUsdUi.toFixed(constants_1.USD_DECIMALS), constants_1.USD_DECIMALS);
920
+ var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
892
921
  var entryPriceUsdUi = new bignumber_js_1.default(entryOraclePrice.toUiPrice(constants_1.ORACLE_EXPONENT));
893
922
  var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
894
923
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
895
924
  };
896
925
  this.getCollateralAmountWithFeeFromLeverageAndSize = function (sizeAmount, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
897
926
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
898
- var collateralTokenMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min.price;
927
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
899
928
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
900
929
  var sizeUsd = targetPrice.getAssetAmountUsd(sizeAmount, targetCustodyAccount.decimals);
901
930
  var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount, sizeUsd);
@@ -911,8 +940,8 @@ var PerpetualsClient = (function () {
911
940
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
912
941
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
913
942
  };
914
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfigPosition, poolConfigSwap) {
915
- var collateralTokenMinPrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min.price;
943
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, swapPoolAumUsdMax, poolConfig) {
944
+ var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
916
945
  var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
917
946
  var sizeUsd = targetTokenPrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
918
947
  var entryOraclePrice = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, sizeUsd);
@@ -928,11 +957,11 @@ var PerpetualsClient = (function () {
928
957
  collateralInInputToken = collateralAmountWithFee;
929
958
  }
930
959
  else {
931
- collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfigSwap).minAmountIn;
960
+ collateralInInputToken = _this.getSwapAmountAndFeesSync(constants_1.BN_ZERO, collateralAmountWithFee, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, swapOutTokenPrice, swapOutTokenEmaPrice, swapOutTokenCustodyAccount, swapPoolAumUsdMax, poolConfig).minAmountIn;
932
961
  }
933
962
  return collateralInInputToken;
934
963
  };
935
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
964
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, maxPayOffBps, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps, debugLogs) {
936
965
  if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
937
966
  if (debugLogs === void 0) { debugLogs = false; }
938
967
  if (!marketConfig.marketAccount.equals(positionAccount.market)) {
@@ -954,10 +983,9 @@ var PerpetualsClient = (function () {
954
983
  var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
955
984
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
956
985
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
957
- positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
958
986
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
959
- positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
960
- positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
987
+ positionDelta.collateralUsd = (positionAccount.collateralUsd.mul(closeRatio)).div(decimalPower);
988
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
961
989
  positionDelta.degenSizeUsd = positionAccount.degenSizeUsd.mul(closeRatio).div(decimalPower);
962
990
  var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
963
991
  var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
@@ -967,30 +995,37 @@ var PerpetualsClient = (function () {
967
995
  }
968
996
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
969
997
  var totalFeesUsd = (exitFeeUsd.add(lockAndUnsettledFeeUsd));
970
- var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
998
+ var currentCollateralUsd = positionDelta.collateralUsd;
971
999
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
972
- var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
973
- var closeAmount, feesAmount;
1000
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(currentCollateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionDelta.lockedAmount, collateralCustodyAccount.decimals));
974
1001
  if (debugLogs) {
975
1002
  console.log("assetsUsd.sub(liabilityUsd):", collateralCustodyAccount.decimals, assetsUsd.toString(), liabilityUsd.toString(), assetsUsd.sub(liabilityUsd).toString());
976
1003
  }
1004
+ var closeAmountUsd, feesAmountUsd;
977
1005
  if (assetsUsd.gte(liabilityUsd)) {
978
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
979
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, collateralCustodyAccount.decimals);
1006
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1007
+ feesAmountUsd = totalFeesUsd;
1008
+ }
1009
+ else {
1010
+ closeAmountUsd = constants_1.BN_ZERO;
1011
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1012
+ }
1013
+ var closeAmount = collateralMinMaxPrice.max.getTokenAmount(closeAmountUsd, collateralCustodyAccount.decimals);
1014
+ var newLockAmount = collateralMinMaxPrice.max.getTokenAmount(_this.getLockedUsd(constants_1.BN_ZERO, closeAmountUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals);
1015
+ if (newLockAmount.gt(positionDelta.lockedAmount)) {
1016
+ positionDelta.lockedAmount = constants_1.BN_ZERO;
980
1017
  }
981
1018
  else {
982
- closeAmount = constants_1.BN_ZERO;
983
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1019
+ positionDelta.lockedAmount = positionDelta.lockedAmount.sub(newLockAmount);
984
1020
  }
985
1021
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
986
1022
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
987
1023
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
988
- newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
989
1024
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
990
- newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount);
1025
+ newPosition.collateralUsd = positionAccount.collateralUsd.sub(positionDelta.collateralUsd);
991
1026
  newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
992
- newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
993
1027
  newPosition.degenSizeUsd = positionAccount.degenSizeUsd.sub(positionDelta.degenSizeUsd);
1028
+ newPosition.collateralUsd = newPosition.collateralUsd.add(closeAmountUsd);
994
1029
  var feeUsdWithDiscount = constants_1.BN_ZERO;
995
1030
  var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
996
1031
  if (discountBps.gt(constants_1.BN_ZERO)) {
@@ -1004,29 +1039,30 @@ var PerpetualsClient = (function () {
1004
1039
  feeUsdWithDiscount = feeUsdWithDiscount.add(lockAndUnsettledFeeUsd);
1005
1040
  if (keepLevSame) {
1006
1041
  var collateralAmountReceived = closeAmount;
1007
- var collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(collateralAmountReceived, collateralCustodyAccount.decimals);
1008
- var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount), maxWithdrawableAmount = _a.maxWithdrawableAmount, diff = _a.diff;
1042
+ var collateralAmountReceivedUsd = closeAmountUsd;
1043
+ var _a = _this.getMaxWithdrawableAmountSyncInternal(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig), maxWithdrawableAmount = _a.maxWithdrawableAmount, maxWithdrawableAmountUsd = _a.maxWithdrawableAmountUsd, diffUsd = _a.diffUsd;
1009
1044
  if (debugLogs) {
1010
1045
  console.log("maxWithdrawableAmount ", maxWithdrawableAmount.toString(), keepLevSame);
1011
1046
  console.log("collateralAmountReceived ", collateralAmountReceived.toString(), keepLevSame);
1012
1047
  }
1013
- if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1048
+ if (collateralAmountReceivedUsd.lt(constants_1.BN_ZERO)) {
1014
1049
  collateralAmountReceived = constants_1.BN_ZERO;
1015
- collateralAmountRecievedUsd = constants_1.BN_ZERO;
1050
+ collateralAmountReceivedUsd = constants_1.BN_ZERO;
1016
1051
  }
1017
- else if (collateralAmountReceived.gt(maxWithdrawableAmount)) {
1052
+ else if (collateralAmountReceivedUsd.gt(maxWithdrawableAmountUsd)) {
1018
1053
  if (debugLogs) {
1019
1054
  console.log("exceeding to redicing maxWithdrawableAmount ", maxWithdrawableAmount.toString(), collateralAmountReceived.toString());
1020
1055
  }
1021
1056
  collateralAmountReceived = maxWithdrawableAmount;
1022
- collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1057
+ collateralAmountReceivedUsd = maxWithdrawableAmountUsd;
1023
1058
  }
1024
1059
  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 });
1025
- var finalInterestUsd = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1026
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, entryPrice, finalInterestUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1060
+ newPosition.collateralUsd = newPosition.collateralUsd.sub(collateralAmountReceivedUsd);
1061
+ var lockAndUnsettledFeeUsdNew = _this.getLockFeeAndUnsettledUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1062
+ var finalLiquidationPrice = _this.getLiquidationPriceContractHelper(entryPrice, lockAndUnsettledFeeUsdNew, side, targetCustodyAccount, newPosition);
1027
1063
  var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1028
1064
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1029
- var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, constants_1.BN_ZERO);
1065
+ var newLev = _this.getLeverageSync(newPosition, newPosition.collateralUsd, newPosition.sizeUsd, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, false, poolConfig);
1030
1066
  return {
1031
1067
  newSizeUsd: newPosition.sizeUsd,
1032
1068
  feeUsd: feeUsd,
@@ -1034,8 +1070,9 @@ var PerpetualsClient = (function () {
1034
1070
  lockAndUnsettledFeeUsd: lockAndUnsettledFeeUsd,
1035
1071
  newLev: newLev,
1036
1072
  liquidationPrice: finalLiquidationPrice,
1037
- collateralAmountRecieved: collateralAmountReceived,
1038
- newCollateralAmount: newPosition.collateralAmount.add(diff),
1073
+ collateralAmountReceived: collateralAmountReceived,
1074
+ collateralAmountReceivedUsd: collateralAmountReceivedUsd,
1075
+ newCollateralUsd: newPosition.collateralUsd.add(diffUsd),
1039
1076
  newPnl: finalPnlUsd
1040
1077
  };
1041
1078
  }
@@ -1043,8 +1080,7 @@ var PerpetualsClient = (function () {
1043
1080
  throw "only same leverage is supported for now";
1044
1081
  }
1045
1082
  };
1046
- this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, closeAmount, errorBandwidthPercentageUi) {
1047
- if (closeAmount === void 0) { closeAmount = constants_1.BN_ZERO; }
1083
+ this.getMaxWithdrawableAmountSyncInternal = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1048
1084
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1049
1085
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1050
1086
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
@@ -1053,60 +1089,87 @@ var PerpetualsClient = (function () {
1053
1089
  (new anchor_1.BN(targetCustodyAccount.pricing.maxInitDegenLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100))
1054
1090
  : (new anchor_1.BN(targetCustodyAccount.pricing.maxInitLeverage)).mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1055
1091
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1056
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1092
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1057
1093
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1058
1094
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1059
1095
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1060
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount.add(closeAmount), collateralCustodyAccount.decimals);
1061
1096
  var availableInitMarginUsd = constants_1.BN_ZERO;
1062
- if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1063
- availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1097
+ if (profitLoss.lossUsd.lt(positionAccount.collateralUsd)) {
1098
+ availableInitMarginUsd = positionAccount.collateralUsd.sub(lossUsd);
1064
1099
  }
1065
1100
  else {
1066
1101
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1067
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1102
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1068
1103
  }
1069
1104
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1070
1105
  if (maxRemovableCollateralUsd.isNeg()) {
1071
- return { maxWithdrawableAmount: constants_1.BN_ZERO, diff: constants_1.BN_ZERO };
1106
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO, diffUsd: constants_1.BN_ZERO };
1072
1107
  }
1073
1108
  var maxWithdrawableAmount = constants_1.BN_ZERO;
1074
- var diff = constants_1.BN_ZERO;
1109
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1110
+ var diffUsd = constants_1.BN_ZERO;
1075
1111
  var remainingCollateralUsd = availableInitMarginUsd.sub(maxRemovableCollateralUsd);
1076
1112
  var isDegenMode = positionAccount.isDegenMode();
1077
1113
  if (remainingCollateralUsd.lt(new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd))) {
1078
- diff = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1079
- var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diff);
1114
+ diffUsd = (new anchor_1.BN(isDegenMode ? targetCustodyAccount.pricing.minDegenCollateralUsd : targetCustodyAccount.pricing.minCollateralUsd)).sub(remainingCollateralUsd);
1115
+ var updatedMaxRemovableCollateralUsd = maxRemovableCollateralUsd.sub(diffUsd);
1080
1116
  if (updatedMaxRemovableCollateralUsd.isNeg()) {
1081
- 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 };
1082
1118
  }
1083
1119
  else {
1084
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1120
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(updatedMaxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1121
+ maxWithdrawableAmountUsd = updatedMaxRemovableCollateralUsd;
1085
1122
  }
1086
1123
  }
1087
1124
  else {
1088
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1125
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1126
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1089
1127
  }
1090
- return { maxWithdrawableAmount: maxWithdrawableAmount, diff: diff };
1128
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd, diffUsd: diffUsd };
1091
1129
  };
1092
- this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1130
+ this.getFinalCloseAmountUsdSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1093
1131
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1094
1132
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1095
1133
  var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1096
1134
  var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1097
1135
  var totalFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd));
1098
1136
  var liabilityUsd = newPnl.lossUsd.add(totalFeesUsd);
1099
- var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1100
- var closeAmount, feesAmount;
1137
+ var assetsUsd = anchor_1.BN.min(newPnl.profitUsd.add(positionAccount.collateralUsd), collateralMinMaxPrice.max.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals));
1138
+ var closeAmountUsd, feesAmountUsd;
1101
1139
  if (assetsUsd.gt(liabilityUsd)) {
1102
- closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1103
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(totalFeesUsd, positionAccount.collateralDecimals);
1140
+ closeAmountUsd = assetsUsd.sub(liabilityUsd);
1141
+ feesAmountUsd = totalFeesUsd;
1104
1142
  }
1105
1143
  else {
1106
- closeAmount = constants_1.BN_ZERO;
1107
- feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1144
+ closeAmountUsd = constants_1.BN_ZERO;
1145
+ feesAmountUsd = assetsUsd.sub(newPnl.lossUsd);
1108
1146
  }
1109
- return { closeAmount: closeAmount, feesAmount: feesAmount };
1147
+ return { closeAmountUsd: closeAmountUsd, feesAmountUsd: feesAmountUsd };
1148
+ };
1149
+ this.getMaxAddableCollateralSync = function (positionAccount, targetCustodyAccount, collateralCustodyAccount, collateralPrice, collateralEmaPrice, errorBandwidthPercentageUi) {
1150
+ if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1151
+ if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1152
+ throw new Error('errorBandwidthPercentageUi cannot be >100 or <0');
1153
+ }
1154
+ var rawMinInitLev = positionAccount.isDegenMode()
1155
+ ? new anchor_1.BN(targetCustodyAccount.pricing.minInitDegenLeverage)
1156
+ : new anchor_1.BN(targetCustodyAccount.pricing.minInitLeverage);
1157
+ var MIN_INIT_LEVERAGE = rawMinInitLev
1158
+ .mul(new anchor_1.BN(100 + errorBandwidthPercentageUi))
1159
+ .div(new anchor_1.BN(100));
1160
+ var requiredCollateralUsdForMinLev = positionAccount.sizeUsd
1161
+ .muln(constants_1.BPS_POWER)
1162
+ .div(MIN_INIT_LEVERAGE);
1163
+ var currentCollateralUsd = positionAccount.collateralUsd;
1164
+ var maxAddableCollateralUsd = requiredCollateralUsdForMinLev.gt(currentCollateralUsd)
1165
+ ? requiredCollateralUsdForMinLev.sub(currentCollateralUsd)
1166
+ : constants_1.BN_ZERO;
1167
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1168
+ var maxAddableAmount = collateralMinMaxPrice.min.getTokenAmount(maxAddableCollateralUsd, collateralCustodyAccount.decimals);
1169
+ return {
1170
+ maxAddableAmount: maxAddableAmount,
1171
+ maxAddableAmountUsd: maxAddableCollateralUsd,
1172
+ };
1110
1173
  };
1111
1174
  this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1112
1175
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
@@ -1119,34 +1182,37 @@ var PerpetualsClient = (function () {
1119
1182
  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)));
1120
1183
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1121
1184
  console.log("THIS cannot happen but still");
1122
- return constants_1.BN_ZERO;
1185
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1123
1186
  }
1124
1187
  var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1125
- var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1188
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1126
1189
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1127
1190
  var lockAndUnsettledFeeUsd = _this.getLockFeeAndUnsettledUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1128
1191
  var lossUsd = profitLoss.lossUsd.add(exitFeeUsd).add(lockAndUnsettledFeeUsd);
1129
- var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1192
+ var currentCollateralUsd = positionAccount.collateralUsd;
1130
1193
  var availableInitMarginUsd = constants_1.BN_ZERO;
1131
1194
  if (profitLoss.lossUsd.lt(currentCollateralUsd)) {
1132
1195
  availableInitMarginUsd = currentCollateralUsd.sub(lossUsd);
1133
1196
  }
1134
1197
  else {
1135
1198
  console.log("profitLoss.lossUsd > coll :: should have been liquidated");
1136
- return constants_1.BN_ZERO;
1199
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1137
1200
  }
1138
1201
  var maxRemovableCollateralUsd = availableInitMarginUsd.sub(positionAccount.sizeUsd.muln(constants_1.BPS_POWER).div(MAX_INIT_LEVERAGE));
1139
1202
  if (maxRemovableCollateralUsd.isNeg()) {
1140
- return constants_1.BN_ZERO;
1203
+ return { maxWithdrawableAmount: constants_1.BN_ZERO, maxWithdrawableAmountUsd: constants_1.BN_ZERO };
1141
1204
  }
1142
1205
  var maxWithdrawableAmount;
1206
+ var maxWithdrawableAmountUsd = constants_1.BN_ZERO;
1143
1207
  if (maxRemoveableCollateralUsdAfterMinRequired.lt(maxRemovableCollateralUsd)) {
1144
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1208
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemoveableCollateralUsdAfterMinRequired, collateralCustodyAccount.decimals);
1209
+ maxWithdrawableAmountUsd = maxRemoveableCollateralUsdAfterMinRequired;
1145
1210
  }
1146
1211
  else {
1147
- maxWithdrawableAmount = collateralMaxPrice.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1212
+ maxWithdrawableAmount = collateralMinMaxPrice.max.getTokenAmount(maxRemovableCollateralUsd, collateralCustodyAccount.decimals);
1213
+ maxWithdrawableAmountUsd = maxRemovableCollateralUsd;
1148
1214
  }
1149
- return maxWithdrawableAmount;
1215
+ return { maxWithdrawableAmount: maxWithdrawableAmount, maxWithdrawableAmountUsd: maxWithdrawableAmountUsd };
1150
1216
  };
1151
1217
  this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1152
1218
  var cumulativeLockFee = constants_1.BN_ZERO;
@@ -1184,12 +1250,12 @@ var PerpetualsClient = (function () {
1184
1250
  var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1185
1251
  var lockFeeUsd = constants_1.BN_ZERO;
1186
1252
  if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1187
- lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1253
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.sizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1188
1254
  }
1189
1255
  lockFeeUsd = lockFeeUsd.add(position.unsettledFeesUsd);
1190
1256
  return lockFeeUsd;
1191
1257
  };
1192
- this.getLockedUsd = function (sideUsd, side, marketCorrelation, maxPayOffBps) {
1258
+ this.getLockedUsd = function (sizeUsd, collateralUsd, side, marketCorrelation, maxPayOffBps) {
1193
1259
  var maxPayOffBpsNew = constants_1.BN_ZERO;
1194
1260
  if (marketCorrelation || (0, types_1.isVariant)(side, 'short')) {
1195
1261
  maxPayOffBpsNew = anchor_1.BN.min(new anchor_1.BN(constants_1.BPS_POWER), maxPayOffBps);
@@ -1197,193 +1263,146 @@ var PerpetualsClient = (function () {
1197
1263
  else {
1198
1264
  maxPayOffBpsNew = maxPayOffBps;
1199
1265
  }
1200
- var lockedUsd = (sideUsd.mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1266
+ var lockedUsd = ((sizeUsd.add(collateralUsd)).mul(maxPayOffBpsNew)).div(new anchor_1.BN(constants_1.BPS_POWER));
1201
1267
  return lockedUsd;
1202
1268
  };
1203
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1269
+ this.getLiquidationPriceContractHelper = function (entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, positionAccount) {
1204
1270
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1205
1271
  price: constants_1.BN_ZERO,
1206
1272
  exponent: constants_1.BN_ZERO,
1207
1273
  confidence: constants_1.BN_ZERO,
1208
1274
  timestamp: constants_1.BN_ZERO
1209
1275
  });
1210
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1211
- return zeroOraclePrice;
1212
- }
1213
1276
  if (positionAccount.entryPrice.exponent && !entryOraclePrice.exponent.eq(new anchor_1.BN(positionAccount.entryPrice.exponent))) {
1214
1277
  throw new Error("Exponent mismatch : ".concat(positionAccount.entryPrice.exponent, " & ").concat(entryOraclePrice.exponent.toString(), " ").concat(entryOraclePrice === null || entryOraclePrice === void 0 ? void 0 : entryOraclePrice.toUiPrice(8)));
1215
1278
  }
1216
1279
  var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1217
1280
  var unsettledLossUsd = exitFeeUsd.add(lockAndUnsettledFeeUsd);
1218
1281
  var liablitiesUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1219
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1220
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1221
1282
  var liquidationPrice;
1222
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1223
- var newCollateralAmount = void 0;
1224
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1225
- newCollateralAmount = collateralAmount;
1283
+ if (positionAccount.collateralUsd.gte(liablitiesUsd)) {
1284
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1285
+ price: (positionAccount.collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1286
+ .div(positionAccount.sizeAmount),
1287
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1288
+ confidence: constants_1.BN_ZERO,
1289
+ timestamp: constants_1.BN_ZERO
1290
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1291
+ if ((0, types_1.isVariant)(side, 'long')) {
1292
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1293
+ price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1294
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1295
+ confidence: constants_1.BN_ZERO,
1296
+ timestamp: constants_1.BN_ZERO
1297
+ });
1226
1298
  }
1227
1299
  else {
1228
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1229
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1230
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1300
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1301
+ price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1302
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1303
+ confidence: constants_1.BN_ZERO,
1304
+ timestamp: constants_1.BN_ZERO
1305
+ });
1231
1306
  }
1232
- var lp = OraclePrice_1.OraclePrice.from({
1233
- price: (positionAccount.sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1234
- .div(sizeAmount.add(newCollateralAmount)),
1307
+ }
1308
+ else {
1309
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1310
+ price: (liablitiesUsd.sub(positionAccount.collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1311
+ .div(positionAccount.sizeAmount),
1235
1312
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1236
1313
  confidence: constants_1.BN_ZERO,
1237
1314
  timestamp: constants_1.BN_ZERO
1238
- });
1239
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1240
- }
1241
- else {
1242
- var assetsUsd = collateralMinMaxPriceOracle.min.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1243
- if (assetsUsd.gte(liablitiesUsd)) {
1244
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1245
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1246
- .div(positionAccount.sizeAmount),
1247
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1315
+ }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1316
+ if ((0, types_1.isVariant)(side, 'long')) {
1317
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1318
+ price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1319
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1248
1320
  confidence: constants_1.BN_ZERO,
1249
1321
  timestamp: constants_1.BN_ZERO
1250
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1251
- if ((0, types_1.isVariant)(side, 'long')) {
1252
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1253
- price: entryOraclePrice.price.sub(priceDiffLossOracle.price),
1254
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1255
- confidence: constants_1.BN_ZERO,
1256
- timestamp: constants_1.BN_ZERO
1257
- });
1258
- }
1259
- else {
1260
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1261
- price: entryOraclePrice.price.add(priceDiffLossOracle.price),
1262
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1263
- confidence: constants_1.BN_ZERO,
1264
- timestamp: constants_1.BN_ZERO
1265
- });
1266
- }
1322
+ });
1267
1323
  }
1268
1324
  else {
1269
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1270
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (positionAccount.sizeDecimals + 3))))
1271
- .div(positionAccount.sizeAmount),
1272
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1325
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1326
+ price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1327
+ exponent: new anchor_1.BN(entryOraclePrice.exponent),
1273
1328
  confidence: constants_1.BN_ZERO,
1274
1329
  timestamp: constants_1.BN_ZERO
1275
- }).scale_to_exponent(new anchor_1.BN(entryOraclePrice.exponent));
1276
- if ((0, types_1.isVariant)(side, 'long')) {
1277
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1278
- price: entryOraclePrice.price.add(priceDiffProfitOracle.price),
1279
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1280
- confidence: constants_1.BN_ZERO,
1281
- timestamp: constants_1.BN_ZERO
1282
- });
1283
- }
1284
- else {
1285
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1286
- price: entryOraclePrice.price.sub(priceDiffProfitOracle.price),
1287
- exponent: new anchor_1.BN(entryOraclePrice.exponent),
1288
- confidence: constants_1.BN_ZERO,
1289
- timestamp: constants_1.BN_ZERO
1290
- });
1291
- }
1330
+ });
1292
1331
  }
1293
1332
  }
1294
1333
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1295
1334
  };
1296
- this.getLiquidationPriceWithOrder = function (collateralAmount, collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1335
+ this.getLiquidationPriceSync = function (collateralUsd, sizeAmount, entryOraclePrice, lockAndUnsettledFeeUsd, side, targetPrice, targetCustodyAccount, positionAccount) {
1336
+ var newPositionAccount = positionAccount.clone();
1337
+ newPositionAccount.sizeAmount = sizeAmount;
1338
+ newPositionAccount.sizeUsd = targetPrice.getAssetAmountUsd(sizeAmount, targetCustodyAccount.decimals);
1339
+ newPositionAccount.collateralUsd = collateralUsd;
1340
+ return _this.getLiquidationPriceContractHelper(entryOraclePrice, lockAndUnsettledFeeUsd, side, targetCustodyAccount, newPositionAccount);
1341
+ };
1342
+ this.getLiquidationPriceWithOrder = function (collateralUsd, sizeAmount, sizeUsd, sizeDecimals, limitOraclePrice, side, targetCustodyAccount) {
1297
1343
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1298
1344
  price: constants_1.BN_ZERO,
1299
1345
  exponent: constants_1.BN_ZERO,
1300
1346
  confidence: constants_1.BN_ZERO,
1301
1347
  timestamp: constants_1.BN_ZERO
1302
1348
  });
1303
- if (collateralAmount.isZero() || sizeAmount.isZero()) {
1304
- return zeroOraclePrice;
1305
- }
1306
1349
  var exitFeeUsd = sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1307
1350
  var unsettledLossUsd = exitFeeUsd;
1308
1351
  var liablitiesUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(new anchor_1.BN(targetCustodyAccount.pricing.maxLeverage)).add(unsettledLossUsd);
1309
- var targetMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1310
- var collateralMinMaxPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1311
1352
  var liquidationPrice;
1312
- if (marketCorrelation && (0, types_1.isVariant)(side, 'long')) {
1313
- var newCollateralAmount = void 0;
1314
- if (targetCustodyAccount.mint == collateralCustodyAccount.mint) {
1315
- newCollateralAmount = collateralAmount;
1353
+ if (collateralUsd.gte(liablitiesUsd)) {
1354
+ var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1355
+ price: (collateralUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1356
+ .div(sizeAmount),
1357
+ exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1358
+ confidence: constants_1.BN_ZERO,
1359
+ timestamp: constants_1.BN_ZERO
1360
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1361
+ if ((0, types_1.isVariant)(side, 'long')) {
1362
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1363
+ price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1364
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1365
+ confidence: constants_1.BN_ZERO,
1366
+ timestamp: constants_1.BN_ZERO
1367
+ });
1316
1368
  }
1317
1369
  else {
1318
- var pairPrice = collateralMinMaxPriceOracle.min.price.mul(new anchor_1.BN(10).pow(collateralMinMaxPriceOracle.min.exponent)).div(targetMinMaxPriceOracle.max.price);
1319
- var swapPrice = pairPrice.sub(pairPrice.mul(collateralCustodyAccount.pricing.swapSpread).div(new anchor_1.BN(constants_1.BPS_POWER)));
1320
- newCollateralAmount = (0, utils_1.checkedDecimalMul)(collateralAmount, new anchor_1.BN(-1 * collateralCustodyAccount.decimals), swapPrice, collateralMinMaxPriceOracle.min.exponent, new anchor_1.BN(-1 * targetCustodyAccount.decimals));
1370
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1371
+ price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1372
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1373
+ confidence: constants_1.BN_ZERO,
1374
+ timestamp: constants_1.BN_ZERO
1375
+ });
1321
1376
  }
1322
- var lp = OraclePrice_1.OraclePrice.from({
1323
- price: (sizeUsd.add(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1324
- .div(sizeAmount.add(newCollateralAmount)),
1377
+ }
1378
+ else {
1379
+ var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1380
+ price: (liablitiesUsd.sub(collateralUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1381
+ .div(sizeAmount),
1325
1382
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1326
1383
  confidence: constants_1.BN_ZERO,
1327
1384
  timestamp: constants_1.BN_ZERO
1328
- });
1329
- liquidationPrice = lp.scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1330
- }
1331
- else {
1332
- var assetsUsd = collateralUsd;
1333
- if (assetsUsd.gte(liablitiesUsd)) {
1334
- var priceDiffLossOracle = OraclePrice_1.OraclePrice.from({
1335
- price: (assetsUsd.sub(liablitiesUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1336
- .div(sizeAmount),
1337
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1385
+ }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1386
+ if ((0, types_1.isVariant)(side, 'long')) {
1387
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1388
+ price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1389
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1338
1390
  confidence: constants_1.BN_ZERO,
1339
1391
  timestamp: constants_1.BN_ZERO
1340
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1341
- if ((0, types_1.isVariant)(side, 'long')) {
1342
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1343
- price: limitOraclePrice.price.sub(priceDiffLossOracle.price),
1344
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1345
- confidence: constants_1.BN_ZERO,
1346
- timestamp: constants_1.BN_ZERO
1347
- });
1348
- }
1349
- else {
1350
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1351
- price: limitOraclePrice.price.add(priceDiffLossOracle.price),
1352
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1353
- confidence: constants_1.BN_ZERO,
1354
- timestamp: constants_1.BN_ZERO
1355
- });
1356
- }
1392
+ });
1357
1393
  }
1358
1394
  else {
1359
- var priceDiffProfitOracle = OraclePrice_1.OraclePrice.from({
1360
- price: (liablitiesUsd.sub(assetsUsd)).mul(new anchor_1.BN(Math.pow(10, (sizeDecimals + 3))))
1361
- .div(sizeAmount),
1362
- exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1395
+ liquidationPrice = OraclePrice_1.OraclePrice.from({
1396
+ price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1397
+ exponent: new anchor_1.BN(limitOraclePrice.exponent),
1363
1398
  confidence: constants_1.BN_ZERO,
1364
1399
  timestamp: constants_1.BN_ZERO
1365
- }).scale_to_exponent(new anchor_1.BN(limitOraclePrice.exponent));
1366
- if ((0, types_1.isVariant)(side, 'long')) {
1367
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1368
- price: limitOraclePrice.price.add(priceDiffProfitOracle.price),
1369
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1370
- confidence: constants_1.BN_ZERO,
1371
- timestamp: constants_1.BN_ZERO
1372
- });
1373
- }
1374
- else {
1375
- liquidationPrice = OraclePrice_1.OraclePrice.from({
1376
- price: limitOraclePrice.price.sub(priceDiffProfitOracle.price),
1377
- exponent: new anchor_1.BN(limitOraclePrice.exponent),
1378
- confidence: constants_1.BN_ZERO,
1379
- timestamp: constants_1.BN_ZERO
1380
- });
1381
- }
1400
+ });
1382
1401
  }
1383
1402
  }
1384
1403
  return liquidationPrice.price.isNeg() ? zeroOraclePrice : liquidationPrice;
1385
1404
  };
1386
- this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, positionAccount) {
1405
+ this.getMaxProfitPriceSync = function (entryPrice, marketCorrelation, side, collateralPrice, positionAccount) {
1387
1406
  var zeroOraclePrice = OraclePrice_1.OraclePrice.from({
1388
1407
  price: constants_1.BN_ZERO,
1389
1408
  exponent: constants_1.BN_ZERO,
@@ -1394,7 +1413,7 @@ var PerpetualsClient = (function () {
1394
1413
  return zeroOraclePrice;
1395
1414
  }
1396
1415
  var priceDiffProfit = OraclePrice_1.OraclePrice.from({
1397
- price: positionAccount.lockedUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1416
+ price: (collateralPrice.price.mul(positionAccount.lockedAmount)).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals + 3)))
1398
1417
  .div(positionAccount.sizeAmount),
1399
1418
  exponent: new anchor_1.BN(-1 * constants_1.RATE_DECIMALS),
1400
1419
  confidence: constants_1.BN_ZERO,
@@ -1422,7 +1441,7 @@ var PerpetualsClient = (function () {
1422
1441
  }
1423
1442
  return maxProfitPrice.price.isNeg() ? zeroOraclePrice : maxProfitPrice;
1424
1443
  };
1425
- this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1444
+ this.getEstimateProfitLossforTpSlEntry = function (positionAccount, isTakeProfit, userEntrytpSlOraclePrice, collateralDeltaAmount, sizeDeltaAmount, side, marketCorrelation, maxPayOffBps, marketAccountPk, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, poolConfig) {
1426
1445
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1427
1446
  throw new Error("Delta Amounts cannot be negative.");
1428
1447
  }
@@ -1452,10 +1471,9 @@ var PerpetualsClient = (function () {
1452
1471
  positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1453
1472
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1454
1473
  positionAccount.market = marketAccountPk;
1455
- positionAccount.lockedUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1456
- positionAccount.lockedAmount = collateralPrice.getTokenAmount(positionAccount.lockedUsd, collateralCustodyAccount.decimals);
1457
- positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1458
- positionAccount.collateralUsd = collateralPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1474
+ var collateralDeltaUsd = collateralPrice.getAssetAmountUsd(collateralDeltaAmount, collateralCustodyAccount.decimals);
1475
+ positionAccount.collateralUsd = positionAccount.collateralUsd.add(collateralDeltaUsd);
1476
+ positionAccount.lockedAmount = positionAccount.lockedAmount.add(collateralPrice.getTokenAmount(_this.getLockedUsd(sizeDeltaUsd, collateralDeltaUsd, side, marketCorrelation, maxPayOffBps), collateralCustodyAccount.decimals));
1459
1477
  var currentTime = new anchor_1.BN((0, utils_1.getUnixTs)());
1460
1478
  var pnl = _this.getPnlSync(positionAccount, userEntrytpSlOraclePrice, userEntrytpSlOraclePrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTime, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1461
1479
  var pnlUsd = pnl.profitUsd.sub(pnl.lossUsd);
@@ -1527,6 +1545,9 @@ var PerpetualsClient = (function () {
1527
1545
  });
1528
1546
  };
1529
1547
  this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1548
+ return _this.getPnlContractHelper(positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig);
1549
+ };
1550
+ this.getPnlContractHelper = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1530
1551
  if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1531
1552
  return {
1532
1553
  profitUsd: constants_1.BN_ZERO,
@@ -1534,7 +1555,8 @@ var PerpetualsClient = (function () {
1534
1555
  };
1535
1556
  }
1536
1557
  var side = poolConfig.getMarketConfigByPk(positionAccount.market).side;
1537
- var exitOraclePrice = _this.getExitOraclePriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, positionAccount.sizeUsd);
1558
+ var sizeUsd = targetTokenPrice.getAssetAmountUsd(positionAccount.sizeAmount, targetCustodyAccount.decimals);
1559
+ var exitOraclePrice = _this.getExitOraclePriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, sizeUsd);
1538
1560
  var collateralMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1539
1561
  var priceDiffProfit, priceDiffLoss;
1540
1562
  var positionEntryPrice = OraclePrice_1.OraclePrice.from({
@@ -1584,7 +1606,7 @@ var PerpetualsClient = (function () {
1584
1606
  }
1585
1607
  if (priceDiffProfit.price.gt(constants_1.BN_ZERO)) {
1586
1608
  return {
1587
- profitUsd: anchor_1.BN.min(priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1609
+ profitUsd: priceDiffProfit.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1588
1610
  lossUsd: constants_1.BN_ZERO,
1589
1611
  };
1590
1612
  }
@@ -1675,6 +1697,9 @@ var PerpetualsClient = (function () {
1675
1697
  }
1676
1698
  };
1677
1699
  this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1700
+ return _this.getAssetsUnderManagementUsdContractHelper(poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig);
1701
+ };
1702
+ this.getAssetsUnderManagementUsdContractHelper = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1678
1703
  var poolAmountUsd = constants_1.BN_ZERO;
1679
1704
  for (var index = 0; index < custodies.length; index++) {
1680
1705
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1687,6 +1712,7 @@ var PerpetualsClient = (function () {
1687
1712
  var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1688
1713
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1689
1714
  }
1715
+ poolAmountUsd = poolAmountUsd.sub(poolAccount.feesObligationUsd.add(poolAccount.rebateObligationUsd));
1690
1716
  if (aumCalcMode === "includePnl") {
1691
1717
  var poolEquityUsd = poolAmountUsd;
1692
1718
  for (var index = 0; index < markets.length; index++) {
@@ -1696,11 +1722,12 @@ var PerpetualsClient = (function () {
1696
1722
  var targetCustodyId = poolAccount.getCustodyId(markets[index].targetCustody);
1697
1723
  var collateralCustodyId = poolAccount.getCustodyId(markets[index].collateralCustody);
1698
1724
  var position = markets[index].getCollectivePosition();
1725
+ poolEquityUsd = poolEquityUsd.sub(position.collateralUsd);
1699
1726
  var collectivePnl = _this.getPnlSync(position, tokenPrices[targetCustodyId], tokenEmaPrices[targetCustodyId], custodies[targetCustodyId], tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId], currentTime, custodies[targetCustodyId].pricing.delaySeconds, poolConfig);
1700
1727
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[collateralCustodyId], tokenEmaPrices[collateralCustodyId], custodies[collateralCustodyId]);
1701
- var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1702
- var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1703
- poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1728
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, position.collateralUsd);
1729
+ var collectiveProfitUsd = anchor_1.BN.min(collectivePnl.profitUsd, collateralMinMaxPrice.max.getAssetAmountUsd(position.lockedAmount, custodies[collateralCustodyId].decimals).sub(position.collateralUsd));
1730
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectiveProfitUsd);
1704
1731
  }
1705
1732
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1706
1733
  }
@@ -1708,14 +1735,6 @@ var PerpetualsClient = (function () {
1708
1735
  return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1709
1736
  }
1710
1737
  };
1711
- this.getNftFinalDiscount = function (perpetualsAccount, nftTradingAccount, currentTime) {
1712
- if (currentTime.sub(nftTradingAccount.timestamp).lt(constants_1.DAY_SECONDS) && nftTradingAccount.counter.gt(new anchor_1.BN(perpetualsAccount.tradeLimit))) {
1713
- return { discountBn: constants_1.BN_ZERO };
1714
- }
1715
- else {
1716
- return { discountBn: perpetualsAccount.tradingDiscount[nftTradingAccount.level - 1] };
1717
- }
1718
- };
1719
1738
  this.getFeeDiscount = function (perpetualsAccount, tokenStakeAccount, currentTime) {
1720
1739
  if (tokenStakeAccount.level === 0) {
1721
1740
  return { discountBn: constants_1.BN_ZERO };
@@ -1800,7 +1819,7 @@ var PerpetualsClient = (function () {
1800
1819
  });
1801
1820
  };
1802
1821
  this.getStakedLpTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
1803
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, result, index, res;
1822
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_1, token, _a, custodies_2, custody, _b, _c, market, transaction, backUpOracleInstruction, setCULimitIx, result, index, res;
1804
1823
  var _d;
1805
1824
  return __generator(this, function (_e) {
1806
1825
  switch (_e.label) {
@@ -1848,6 +1867,8 @@ var PerpetualsClient = (function () {
1848
1867
  return [4, backUpOracleInstructionPromise];
1849
1868
  case 2:
1850
1869
  backUpOracleInstruction = _e.sent();
1870
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1871
+ transaction.instructions.unshift(setCULimitIx);
1851
1872
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
1852
1873
  return [4, this.viewHelper.simulateTransaction(transaction)];
1853
1874
  case 3:
@@ -1914,7 +1935,7 @@ var PerpetualsClient = (function () {
1914
1935
  args_1[_i - 4] = arguments[_i];
1915
1936
  }
1916
1937
  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) {
1917
- var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
1938
+ var custodies, custodyMetas, marketMetas, _a, custodies_5, token, _b, custodies_6, custody, _c, _d, market, depositCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
1918
1939
  var _e;
1919
1940
  if (userPublicKey === void 0) { userPublicKey = undefined; }
1920
1941
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -1965,6 +1986,8 @@ var PerpetualsClient = (function () {
1965
1986
  .transaction()];
1966
1987
  case 1:
1967
1988
  transaction = _f.sent();
1989
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
1990
+ transaction.instructions.unshift(setCULimitIx);
1968
1991
  if (!enableBackupOracle) return [3, 3];
1969
1992
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
1970
1993
  case 2:
@@ -1974,6 +1997,14 @@ var PerpetualsClient = (function () {
1974
1997
  case 3: return [4, this.viewHelper.simulateTransaction(transaction, userPublicKey)];
1975
1998
  case 4:
1976
1999
  result = _f.sent();
2000
+ if (result.value.err) {
2001
+ console.error('error Simulation failed:::', result);
2002
+ return [2, {
2003
+ amount: undefined,
2004
+ fee: undefined,
2005
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2006
+ }];
2007
+ }
1977
2008
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getAddLiquidityAmountAndFee'; });
1978
2009
  res = this.viewHelper.decodeLogs(result, index, 'getAddLiquidityAmountAndFee');
1979
2010
  return [2, {
@@ -1990,7 +2021,7 @@ var PerpetualsClient = (function () {
1990
2021
  args_1[_i - 4] = arguments[_i];
1991
2022
  }
1992
2023
  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) {
1993
- var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, backUpOracleInstruction, result, index, res;
2024
+ var custodies, custodyMetas, marketMetas, _a, custodies_7, token, _b, custodies_8, custody, _c, _d, market, removeCustodyConfig, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
1994
2025
  var _e;
1995
2026
  if (userPublicKey === void 0) { userPublicKey = undefined; }
1996
2027
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2041,6 +2072,8 @@ var PerpetualsClient = (function () {
2041
2072
  .transaction()];
2042
2073
  case 1:
2043
2074
  transaction = _f.sent();
2075
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2076
+ transaction.instructions.unshift(setCULimitIx);
2044
2077
  if (!enableBackupOracle) return [3, 3];
2045
2078
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2046
2079
  case 2:
@@ -2052,9 +2085,11 @@ var PerpetualsClient = (function () {
2052
2085
  result = _f.sent();
2053
2086
  index = perpetuals_1.IDL.instructions.findIndex(function (f) { return f.name === 'getRemoveLiquidityAmountAndFee'; });
2054
2087
  if (result.value.err) {
2088
+ console.error('error Simulation failed:', result);
2055
2089
  return [2, {
2056
- amount: new anchor_1.BN(0),
2057
- fee: new anchor_1.BN(0),
2090
+ amount: undefined,
2091
+ fee: undefined,
2092
+ error: 'Simulation failed: ' + JSON.stringify(result.value.err),
2058
2093
  }];
2059
2094
  }
2060
2095
  res = this.viewHelper.decodeLogs(result, index, 'getRemoveLiquidityAmountAndFee');
@@ -2067,7 +2102,7 @@ var PerpetualsClient = (function () {
2067
2102
  });
2068
2103
  };
2069
2104
  this.getCompoundingLPTokenPrice = function (poolKey, POOL_CONFIG) { return __awaiter(_this, void 0, void 0, function () {
2070
- var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, result, index, res;
2105
+ var backUpOracleInstructionPromise, custodies, custodyMetas, marketMetas, _i, custodies_9, token, _a, custodies_10, custody, _b, _c, market, backUpOracleInstruction, transaction, setCULimitIx, result, index, res;
2071
2106
  var _d;
2072
2107
  return __generator(this, function (_e) {
2073
2108
  switch (_e.label) {
@@ -2115,6 +2150,8 @@ var PerpetualsClient = (function () {
2115
2150
  .transaction()];
2116
2151
  case 2:
2117
2152
  transaction = _e.sent();
2153
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2154
+ transaction.instructions.unshift(setCULimitIx);
2118
2155
  (_d = transaction.instructions).unshift.apply(_d, backUpOracleInstruction);
2119
2156
  return [4, this.viewHelper.simulateTransaction(transaction)];
2120
2157
  case 3:
@@ -2131,7 +2168,7 @@ var PerpetualsClient = (function () {
2131
2168
  args_1[_i - 4] = arguments[_i];
2132
2169
  }
2133
2170
  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) {
2134
- var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2171
+ var custodies, custodyMetas, marketMetas, _a, custodies_11, token, _b, custodies_12, custody, _c, _d, market, depositCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2135
2172
  var _e;
2136
2173
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2137
2174
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2186,6 +2223,8 @@ var PerpetualsClient = (function () {
2186
2223
  .transaction()];
2187
2224
  case 1:
2188
2225
  transaction = _f.sent();
2226
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2227
+ transaction.instructions.unshift(setCULimitIx);
2189
2228
  if (!enableBackupOracle) return [3, 3];
2190
2229
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2191
2230
  case 2:
@@ -2211,7 +2250,7 @@ var PerpetualsClient = (function () {
2211
2250
  args_1[_i - 4] = arguments[_i];
2212
2251
  }
2213
2252
  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) {
2214
- var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, backUpOracleInstruction, result, index, res;
2253
+ var custodies, custodyMetas, marketMetas, _a, custodies_13, token, _b, custodies_14, custody, _c, _d, market, removeCustodyConfig, rewardCustody, transaction, setCULimitIx, backUpOracleInstruction, result, index, res;
2215
2254
  var _e;
2216
2255
  if (userPublicKey === void 0) { userPublicKey = undefined; }
2217
2256
  if (enableBackupOracle === void 0) { enableBackupOracle = false; }
@@ -2266,6 +2305,8 @@ var PerpetualsClient = (function () {
2266
2305
  .transaction()];
2267
2306
  case 1:
2268
2307
  transaction = _f.sent();
2308
+ setCULimitIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 450000 });
2309
+ transaction.instructions.unshift(setCULimitIx);
2269
2310
  if (!enableBackupOracle) return [3, 3];
2270
2311
  return [4, (0, backupOracle_1.createBackupOracleInstruction)(POOL_CONFIG.poolAddress.toBase58(), true)];
2271
2312
  case 2:
@@ -2460,11 +2501,10 @@ var PerpetualsClient = (function () {
2460
2501
  for (var _i = 8; _i < arguments.length; _i++) {
2461
2502
  args_1[_i - 8] = arguments[_i];
2462
2503
  }
2463
- 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) {
2504
+ 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) {
2464
2505
  var publicKey, targetCustodyConfig, collateralCustodyConfig, collateralToken, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
2465
2506
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2466
2507
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2467
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2468
2508
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2469
2509
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2470
2510
  return __generator(this, function (_c) {
@@ -2557,7 +2597,7 @@ var PerpetualsClient = (function () {
2557
2597
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2558
2598
  fundingMint: collateralCustodyConfig.mintKey
2559
2599
  })
2560
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2600
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2561
2601
  .instruction()];
2562
2602
  case 7:
2563
2603
  instruction = _c.sent();
@@ -2575,11 +2615,10 @@ var PerpetualsClient = (function () {
2575
2615
  for (var _i = 6; _i < arguments.length; _i++) {
2576
2616
  args_1[_i - 6] = arguments[_i];
2577
2617
  }
2578
- 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) {
2618
+ 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) {
2579
2619
  var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_1;
2580
2620
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2581
2621
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2582
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2583
2622
  if (createUserATA === void 0) { createUserATA = true; }
2584
2623
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2585
2624
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -2658,7 +2697,7 @@ var PerpetualsClient = (function () {
2658
2697
  collateralMint: collateralCustodyConfig.mintKey,
2659
2698
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2660
2699
  })
2661
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2700
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2662
2701
  .instruction()];
2663
2702
  case 6:
2664
2703
  instruction = _b.sent();
@@ -2680,16 +2719,15 @@ var PerpetualsClient = (function () {
2680
2719
  });
2681
2720
  });
2682
2721
  };
2683
- this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, minCollateralAmountOut_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2722
+ this.swapAndOpen = function (targetTokenSymbol_1, collateralTokenSymbol_1, userInputTokenSymbol_1, amountIn_1, priceWithSlippage_1, sizeAmount_1, side_1, poolConfig_1, privilege_1) {
2684
2723
  var args_1 = [];
2685
- for (var _i = 10; _i < arguments.length; _i++) {
2686
- args_1[_i - 10] = arguments[_i];
2724
+ for (var _i = 9; _i < arguments.length; _i++) {
2725
+ args_1[_i - 9] = arguments[_i];
2687
2726
  }
2688
- 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) {
2689
- 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;
2727
+ 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) {
2728
+ 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;
2690
2729
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2691
2730
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2692
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2693
2731
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2694
2732
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2695
2733
  return __generator(this, function (_c) {
@@ -2783,18 +2821,10 @@ var PerpetualsClient = (function () {
2783
2821
  }
2784
2822
  _c.label = 10;
2785
2823
  case 10:
2786
- rebateMintAccount = {
2787
- pubkey: collateralCustodyConfig.mintKey,
2788
- isSigner: false,
2789
- isWritable: false
2790
- };
2791
- _c.label = 11;
2792
- case 11:
2793
- _c.trys.push([11, 13, , 14]);
2824
+ _c.trys.push([10, 12, , 13]);
2794
2825
  return [4, this.program.methods
2795
2826
  .swapAndOpen({
2796
2827
  amountIn: amountIn,
2797
- minCollateralAmountOut: minCollateralAmountOut,
2798
2828
  priceWithSlippage: priceWithSlippage,
2799
2829
  sizeAmount: sizeAmount,
2800
2830
  privilege: privilege
@@ -2825,17 +2855,17 @@ var PerpetualsClient = (function () {
2825
2855
  collateralMint: collateralCustodyConfig.mintKey,
2826
2856
  collateralTokenProgram: poolConfig.getTokenFromSymbol(collateralTokenSymbol).isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2827
2857
  })
2828
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2858
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2829
2859
  .instruction()];
2830
- case 12:
2860
+ case 11:
2831
2861
  inx = _c.sent();
2832
2862
  instructions.push(inx);
2833
- return [3, 14];
2834
- case 13:
2863
+ return [3, 13];
2864
+ case 12:
2835
2865
  err_3 = _c.sent();
2836
2866
  console.error("perpClient SwapAndOpen error:: ", err_3);
2837
2867
  throw err_3;
2838
- case 14: return [2, {
2868
+ case 13: return [2, {
2839
2869
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2840
2870
  additionalSigners: additionalSigners
2841
2871
  }];
@@ -2843,16 +2873,15 @@ var PerpetualsClient = (function () {
2843
2873
  });
2844
2874
  });
2845
2875
  };
2846
- this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, minSwapAmountOut_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2876
+ this.closeAndSwap = function (targetTokenSymbol_1, userOutputTokenSymbol_1, collateralTokenSymbol_1, priceWithSlippage_1, side_1, poolConfig_1, privilege_1) {
2847
2877
  var args_1 = [];
2848
- for (var _i = 8; _i < arguments.length; _i++) {
2849
- args_1[_i - 8] = arguments[_i];
2878
+ for (var _i = 7; _i < arguments.length; _i++) {
2879
+ args_1[_i - 7] = arguments[_i];
2850
2880
  }
2851
- 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) {
2852
- var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, rebateMintAccount, inx, err_4;
2881
+ 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) {
2882
+ var publicKey, userOutputCustodyConfig, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, collateralToken, userOutputToken, lamports, userCollateralTokenAccount, inx, err_4;
2853
2883
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
2854
2884
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
2855
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
2856
2885
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
2857
2886
  return __generator(this, function (_a) {
2858
2887
  switch (_a.label) {
@@ -2918,18 +2947,12 @@ var PerpetualsClient = (function () {
2918
2947
  if (!(_a.sent())) {
2919
2948
  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));
2920
2949
  }
2921
- rebateMintAccount = {
2922
- pubkey: collateralCustodyConfig.mintKey,
2923
- isSigner: false,
2924
- isWritable: false
2925
- };
2926
2950
  _a.label = 5;
2927
2951
  case 5:
2928
2952
  _a.trys.push([5, 7, , 8]);
2929
2953
  return [4, this.program.methods
2930
2954
  .closeAndSwap({
2931
2955
  priceWithSlippage: priceWithSlippage,
2932
- minSwapAmountOut: minSwapAmountOut,
2933
2956
  privilege: privilege
2934
2957
  })
2935
2958
  .accounts({
@@ -2958,7 +2981,7 @@ var PerpetualsClient = (function () {
2958
2981
  collateralMint: collateralCustodyConfig.mintKey,
2959
2982
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
2960
2983
  })
2961
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
2984
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
2962
2985
  .instruction()];
2963
2986
  case 6:
2964
2987
  inx = _a.sent();
@@ -3079,12 +3102,12 @@ var PerpetualsClient = (function () {
3079
3102
  });
3080
3103
  });
3081
3104
  };
3082
- this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, minCollateralAmountOut_1, side_1, positionPubKey_1, poolConfig_1) {
3105
+ this.swapAndAddCollateral = function (targetSymbol_1, inputSymbol_1, collateralSymbol_1, amountIn_1, side_1, positionPubKey_1, poolConfig_1) {
3083
3106
  var args_1 = [];
3084
- for (var _i = 8; _i < arguments.length; _i++) {
3085
- args_1[_i - 8] = arguments[_i];
3107
+ for (var _i = 7; _i < arguments.length; _i++) {
3108
+ args_1[_i - 7] = arguments[_i];
3086
3109
  }
3087
- 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) {
3110
+ 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) {
3088
3111
  var publicKey, collateralCustodyConfig, targetCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, marketAccount, instruction;
3089
3112
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3090
3113
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
@@ -3163,7 +3186,6 @@ var PerpetualsClient = (function () {
3163
3186
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3164
3187
  return [4, this.program.methods.swapAndAddCollateral({
3165
3188
  amountIn: amountIn,
3166
- minCollateralAmountOut: minCollateralAmountOut,
3167
3189
  }).accounts({
3168
3190
  owner: publicKey,
3169
3191
  feePayer: publicKey,
@@ -3199,12 +3221,12 @@ var PerpetualsClient = (function () {
3199
3221
  });
3200
3222
  });
3201
3223
  };
3202
- this.removeCollateral = function (collateralWithFee_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3224
+ this.removeCollateral = function (collateralDeltaUsd_1, marketSymbol_1, collateralSymbol_1, side_1, positionPubKey_1, poolConfig_1) {
3203
3225
  var args_1 = [];
3204
3226
  for (var _i = 6; _i < arguments.length; _i++) {
3205
3227
  args_1[_i - 6] = arguments[_i];
3206
3228
  }
3207
- 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) {
3229
+ 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) {
3208
3230
  var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_2;
3209
3231
  if (createUserATA === void 0) { createUserATA = true; }
3210
3232
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
@@ -3268,7 +3290,7 @@ var PerpetualsClient = (function () {
3268
3290
  marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3269
3291
  return [4, this.program.methods
3270
3292
  .removeCollateral({
3271
- collateralDelta: collateralWithFee,
3293
+ collateralDeltaUsd: collateralDeltaUsd,
3272
3294
  })
3273
3295
  .accounts({
3274
3296
  owner: publicKey,
@@ -3310,12 +3332,12 @@ var PerpetualsClient = (function () {
3310
3332
  });
3311
3333
  });
3312
3334
  };
3313
- this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, minSwapAmountOut_1, collateralDelta_1, side_1, poolConfig_1) {
3335
+ this.removeCollateralAndSwap = function (targetSymbol_1, collateralSymbol_1, outputSymbol_1, collateralDeltaUsd_1, side_1, poolConfig_1) {
3314
3336
  var args_1 = [];
3315
- for (var _i = 7; _i < arguments.length; _i++) {
3316
- args_1[_i - 7] = arguments[_i];
3337
+ for (var _i = 6; _i < arguments.length; _i++) {
3338
+ args_1[_i - 6] = arguments[_i];
3317
3339
  }
3318
- 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) {
3340
+ 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) {
3319
3341
  var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, instruction;
3320
3342
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
3321
3343
  return __generator(this, function (_a) {
@@ -3372,8 +3394,7 @@ var PerpetualsClient = (function () {
3372
3394
  positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
3373
3395
  return [4, this.program.methods
3374
3396
  .removeCollateralAndSwap({
3375
- collateralDelta: collateralDelta,
3376
- minSwapAmountOut: minSwapAmountOut,
3397
+ collateralDeltaUsd: collateralDeltaUsd,
3377
3398
  })
3378
3399
  .accounts({
3379
3400
  owner: publicKey,
@@ -3418,11 +3439,10 @@ var PerpetualsClient = (function () {
3418
3439
  for (var _i = 8; _i < arguments.length; _i++) {
3419
3440
  args_1[_i - 8] = arguments[_i];
3420
3441
  }
3421
- 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) {
3442
+ 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) {
3422
3443
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3423
3444
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3424
3445
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3425
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3426
3446
  return __generator(this, function (_a) {
3427
3447
  switch (_a.label) {
3428
3448
  case 0:
@@ -3465,7 +3485,7 @@ var PerpetualsClient = (function () {
3465
3485
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3466
3486
  collateralMint: collateralCustodyConfig.mintKey
3467
3487
  })
3468
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3488
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3469
3489
  .instruction()];
3470
3490
  case 1:
3471
3491
  instruction = _a.sent();
@@ -3483,11 +3503,10 @@ var PerpetualsClient = (function () {
3483
3503
  for (var _i = 8; _i < arguments.length; _i++) {
3484
3504
  args_1[_i - 8] = arguments[_i];
3485
3505
  }
3486
- 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) {
3506
+ 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) {
3487
3507
  var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3488
3508
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
3489
3509
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
3490
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
3491
3510
  return __generator(this, function (_a) {
3492
3511
  switch (_a.label) {
3493
3512
  case 0:
@@ -3530,7 +3549,7 @@ var PerpetualsClient = (function () {
3530
3549
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3531
3550
  collateralMint: collateralCustodyConfig.mintKey
3532
3551
  })
3533
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
3552
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
3534
3553
  .instruction()];
3535
3554
  case 1:
3536
3555
  instruction = _a.sent();
@@ -3997,119 +4016,8 @@ var PerpetualsClient = (function () {
3997
4016
  }
3998
4017
  });
3999
4018
  }); };
4000
- this.updateNftAccount = function (nftMint, updateReferer, updateBooster, flpStakeAccounts) { return __awaiter(_this, void 0, void 0, function () {
4001
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, flpStakeAccountMetas, _i, flpStakeAccounts_1, flpStakeAccountPk, updateNftTradingAccountInstruction, err_8;
4002
- return __generator(this, function (_a) {
4003
- switch (_a.label) {
4004
- case 0:
4005
- publicKey = this.provider.wallet.publicKey;
4006
- preInstructions = [];
4007
- instructions = [];
4008
- postInstructions = [];
4009
- additionalSigners = [];
4010
- _a.label = 1;
4011
- case 1:
4012
- _a.trys.push([1, 4, , 5]);
4013
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4014
- Buffer.from("trading"),
4015
- nftMint.toBuffer(),
4016
- ], this.programId)[0];
4017
- nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
4018
- Buffer.from("referral"),
4019
- publicKey.toBuffer(),
4020
- ], this.programId)[0];
4021
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey, true)];
4022
- case 2:
4023
- nftTokenAccount = _a.sent();
4024
- flpStakeAccountMetas = [];
4025
- for (_i = 0, flpStakeAccounts_1 = flpStakeAccounts; _i < flpStakeAccounts_1.length; _i++) {
4026
- flpStakeAccountPk = flpStakeAccounts_1[_i];
4027
- flpStakeAccountMetas.push({
4028
- pubkey: flpStakeAccountPk,
4029
- isSigner: false,
4030
- isWritable: true,
4031
- });
4032
- }
4033
- return [4, this.program.methods
4034
- .updateTradingAccount({
4035
- updateReferer: updateReferer,
4036
- updateBooster: updateBooster
4037
- })
4038
- .accounts({
4039
- owner: publicKey,
4040
- feePayer: publicKey,
4041
- nftTokenAccount: nftTokenAccount,
4042
- referralAccount: nftReferralAccount,
4043
- tradingAccount: nftTradingAccount
4044
- })
4045
- .instruction()];
4046
- case 3:
4047
- updateNftTradingAccountInstruction = _a.sent();
4048
- instructions.push(updateNftTradingAccountInstruction);
4049
- return [3, 5];
4050
- case 4:
4051
- err_8 = _a.sent();
4052
- console.log("perpClient updateNftAccount error:: ", err_8);
4053
- throw err_8;
4054
- case 5: return [2, {
4055
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4056
- additionalSigners: additionalSigners
4057
- }];
4058
- }
4059
- });
4060
- }); };
4061
- this.levelUp = function (poolConfig, nftMint, authorizationRulesAccount) { return __awaiter(_this, void 0, void 0, function () {
4062
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_9;
4063
- return __generator(this, function (_a) {
4064
- switch (_a.label) {
4065
- case 0:
4066
- publicKey = this.provider.wallet.publicKey;
4067
- preInstructions = [];
4068
- instructions = [];
4069
- postInstructions = [];
4070
- additionalSigners = [];
4071
- _a.label = 1;
4072
- case 1:
4073
- _a.trys.push([1, 3, , 4]);
4074
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
4075
- Buffer.from("trading"),
4076
- nftMint.toBuffer(),
4077
- ], this.programId)[0];
4078
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
4079
- return [4, this.program.methods
4080
- .levelUp({})
4081
- .accounts({
4082
- owner: publicKey,
4083
- perpetuals: this.perpetuals.publicKey,
4084
- pool: poolConfig.poolAddress,
4085
- metadataAccount: metadataAccount,
4086
- nftMint: nftMint,
4087
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
4088
- tradingAccount: nftTradingAccount,
4089
- transferAuthority: this.authority.publicKey,
4090
- authorizationRulesAccount: authorizationRulesAccount,
4091
- authorizationRulesProgram: new web3_js_1.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg'),
4092
- systemProgram: web3_js_1.SystemProgram.programId,
4093
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
4094
- })
4095
- .instruction()];
4096
- case 2:
4097
- levelUpInstruction = _a.sent();
4098
- instructions.push(levelUpInstruction);
4099
- return [3, 4];
4100
- case 3:
4101
- err_9 = _a.sent();
4102
- console.log("perpClient levelUp error:: ", err_9);
4103
- throw err_9;
4104
- case 4: return [2, {
4105
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4106
- additionalSigners: additionalSigners
4107
- }];
4108
- }
4109
- });
4110
- }); };
4111
4019
  this.depositStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4112
- var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
4020
+ var preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_8;
4113
4021
  return __generator(this, function (_a) {
4114
4022
  switch (_a.label) {
4115
4023
  case 0:
@@ -4151,9 +4059,9 @@ var PerpetualsClient = (function () {
4151
4059
  instructions.push(depositStakeInstruction);
4152
4060
  return [3, 5];
4153
4061
  case 4:
4154
- err_10 = _a.sent();
4155
- console.log("perpClient depositStaking error:: ", err_10);
4156
- throw err_10;
4062
+ err_8 = _a.sent();
4063
+ console.log("perpClient depositStaking error:: ", err_8);
4064
+ throw err_8;
4157
4065
  case 5: return [2, {
4158
4066
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4159
4067
  additionalSigners: additionalSigners
@@ -4162,7 +4070,7 @@ var PerpetualsClient = (function () {
4162
4070
  });
4163
4071
  }); };
4164
4072
  this.refreshStakeWithAllFlpStakeAccounts = function (rewardSymbol, poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4165
- var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_11;
4073
+ var rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_1, flpStakeAccountPk, refreshStakeInstruction, err_9;
4166
4074
  return __generator(this, function (_c) {
4167
4075
  switch (_c.label) {
4168
4076
  case 0:
@@ -4209,9 +4117,9 @@ var PerpetualsClient = (function () {
4209
4117
  refreshStakeInstruction = _c.sent();
4210
4118
  return [2, refreshStakeInstruction];
4211
4119
  case 2:
4212
- err_11 = _c.sent();
4213
- console.log("perpClient refreshStaking error:: ", err_11);
4214
- throw err_11;
4120
+ err_9 = _c.sent();
4121
+ console.log("perpClient refreshStaking error:: ", err_9);
4122
+ throw err_9;
4215
4123
  case 3: return [2];
4216
4124
  }
4217
4125
  });
@@ -4222,7 +4130,7 @@ var PerpetualsClient = (function () {
4222
4130
  args_1[_i - 3] = arguments[_i];
4223
4131
  }
4224
4132
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, flpStakeAccountPk_1], args_1, true), void 0, function (rewardSymbol, poolConfig, flpStakeAccountPk, userPublicKey) {
4225
- var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_12;
4133
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, _a, _b, custody, stakeAccountMetas, tokenStakeAccount, refreshStakeInstruction, err_10;
4226
4134
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4227
4135
  return __generator(this, function (_c) {
4228
4136
  switch (_c.label) {
@@ -4270,9 +4178,9 @@ var PerpetualsClient = (function () {
4270
4178
  refreshStakeInstruction = _c.sent();
4271
4179
  return [2, refreshStakeInstruction];
4272
4180
  case 2:
4273
- err_12 = _c.sent();
4274
- console.log("perpClient refreshStaking error:: ", err_12);
4275
- throw err_12;
4181
+ err_10 = _c.sent();
4182
+ console.log("perpClient refreshStaking error:: ", err_10);
4183
+ throw err_10;
4276
4184
  case 3: return [2];
4277
4185
  }
4278
4186
  });
@@ -4284,7 +4192,7 @@ var PerpetualsClient = (function () {
4284
4192
  args_1[_i - 3] = arguments[_i];
4285
4193
  }
4286
4194
  return __awaiter(_this, __spreadArray([rewardSymbol_1, unstakeAmount_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, unstakeAmount, poolConfig, userPublicKey) {
4287
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_13;
4195
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, pool, flpStakeAccount, tokenStakeAccount, tokenStakeAccounts, _a, unstakeInstantInstruction, err_11;
4288
4196
  if (userPublicKey === void 0) { userPublicKey = undefined; }
4289
4197
  return __generator(this, function (_b) {
4290
4198
  switch (_b.label) {
@@ -4336,9 +4244,9 @@ var PerpetualsClient = (function () {
4336
4244
  instructions.push(unstakeInstantInstruction);
4337
4245
  return [3, 6];
4338
4246
  case 5:
4339
- err_13 = _b.sent();
4340
- console.log("perpClient unstakeInstant error:: ", err_13);
4341
- throw err_13;
4247
+ err_11 = _b.sent();
4248
+ console.log("perpClient unstakeInstant error:: ", err_11);
4249
+ throw err_11;
4342
4250
  case 6: return [2, {
4343
4251
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4344
4252
  additionalSigners: additionalSigners
@@ -4348,7 +4256,7 @@ var PerpetualsClient = (function () {
4348
4256
  });
4349
4257
  };
4350
4258
  this.setFeeShareBps = function (poolConfig, flpStakeAccountPks) { return __awaiter(_this, void 0, void 0, function () {
4351
- var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_14;
4259
+ var publicKey, pool, custodyAccountMetas, _i, _a, custody, maxFlpStakeAccountPkLength, flpStakeAccountMetas, _b, flpStakeAccountPks_2, flpStakeAccountPk, refreshStakeInstruction, err_12;
4352
4260
  return __generator(this, function (_c) {
4353
4261
  switch (_c.label) {
4354
4262
  case 0:
@@ -4392,15 +4300,15 @@ var PerpetualsClient = (function () {
4392
4300
  refreshStakeInstruction = _c.sent();
4393
4301
  return [2, refreshStakeInstruction];
4394
4302
  case 2:
4395
- err_14 = _c.sent();
4396
- console.log("perpClient refreshStaking error:: ", err_14);
4397
- throw err_14;
4303
+ err_12 = _c.sent();
4304
+ console.log("perpClient refreshStaking error:: ", err_12);
4305
+ throw err_12;
4398
4306
  case 3: return [2];
4399
4307
  }
4400
4308
  });
4401
4309
  }); };
4402
4310
  this.unstakeRequest = function (unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4403
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_15;
4311
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, unstakeRequestInstruction, err_13;
4404
4312
  return __generator(this, function (_a) {
4405
4313
  switch (_a.label) {
4406
4314
  case 0:
@@ -4434,9 +4342,9 @@ var PerpetualsClient = (function () {
4434
4342
  instructions.push(unstakeRequestInstruction);
4435
4343
  return [3, 4];
4436
4344
  case 3:
4437
- err_15 = _a.sent();
4438
- console.log("perpClient unstakeRequest error:: ", err_15);
4439
- throw err_15;
4345
+ err_13 = _a.sent();
4346
+ console.log("perpClient unstakeRequest error:: ", err_13);
4347
+ throw err_13;
4440
4348
  case 4: return [2, {
4441
4349
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4442
4350
  additionalSigners: additionalSigners
@@ -4450,7 +4358,7 @@ var PerpetualsClient = (function () {
4450
4358
  args_1[_i - 1] = arguments[_i];
4451
4359
  }
4452
4360
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, pendingActivation, deactivated, createUserLPTA, userPublicKey) {
4453
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_16;
4361
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolStakedLpVault, flpStakeAccount, userLpTokenAccount, _a, withdrawStakeInstruction, err_14;
4454
4362
  if (pendingActivation === void 0) { pendingActivation = true; }
4455
4363
  if (deactivated === void 0) { deactivated = true; }
4456
4364
  if (createUserLPTA === void 0) { createUserLPTA = true; }
@@ -4506,9 +4414,9 @@ var PerpetualsClient = (function () {
4506
4414
  instructions.push(withdrawStakeInstruction);
4507
4415
  return [3, 6];
4508
4416
  case 5:
4509
- err_16 = _b.sent();
4510
- console.log("perpClient withdrawStake error:: ", err_16);
4511
- throw err_16;
4417
+ err_14 = _b.sent();
4418
+ console.log("perpClient withdrawStake error:: ", err_14);
4419
+ throw err_14;
4512
4420
  case 6: return [2, {
4513
4421
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4514
4422
  additionalSigners: additionalSigners
@@ -4523,7 +4431,7 @@ var PerpetualsClient = (function () {
4523
4431
  args_1[_i - 3] = arguments[_i];
4524
4432
  }
4525
4433
  return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, tokenStakeAccount_1], args_1, true), void 0, function (rewardSymbol, poolConfig, tokenStakeAccount, createUserATA) {
4526
- var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_17;
4434
+ var publicKey, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tokenStakeAccounts, withdrawStakeInstruction, err_15;
4527
4435
  if (createUserATA === void 0) { createUserATA = true; }
4528
4436
  return __generator(this, function (_b) {
4529
4437
  switch (_b.label) {
@@ -4584,9 +4492,9 @@ var PerpetualsClient = (function () {
4584
4492
  instructions.push(withdrawStakeInstruction);
4585
4493
  return [3, 6];
4586
4494
  case 5:
4587
- err_17 = _b.sent();
4588
- console.log("perpClient withdrawStake error:: ", err_17);
4589
- throw err_17;
4495
+ err_15 = _b.sent();
4496
+ console.log("perpClient withdrawStake error:: ", err_15);
4497
+ throw err_15;
4590
4498
  case 6: return [2, {
4591
4499
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
4592
4500
  additionalSigners: additionalSigners
@@ -4601,7 +4509,7 @@ var PerpetualsClient = (function () {
4601
4509
  args_1[_i - 5] = arguments[_i];
4602
4510
  }
4603
4511
  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) {
4604
- 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;
4512
+ var publicKey, preInstructions, instructions, additionalSigners, postInstructions, rewardCustody, inCustodyConfig, lpTokenMint, compoundingTokenMint, wrappedSolAccount, lpTokenAccount, compoundingTokenAccount, fundingAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, lamports, unWrappedSolBalance, _e, addCompoundingLiquidity, err_16;
4605
4513
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
4606
4514
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4607
4515
  if (userPublicKey === void 0) { userPublicKey = undefined; }
@@ -4729,8 +4637,8 @@ var PerpetualsClient = (function () {
4729
4637
  instructions.push(addCompoundingLiquidity);
4730
4638
  return [3, 10];
4731
4639
  case 9:
4732
- err_18 = _f.sent();
4733
- console.log("perpClient addCompoundingLiquidity error:: ", err_18);
4640
+ err_16 = _f.sent();
4641
+ console.log("perpClient addCompoundingLiquidity error:: ", err_16);
4734
4642
  return [3, 10];
4735
4643
  case 10: return [2, {
4736
4644
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4746,7 +4654,7 @@ var PerpetualsClient = (function () {
4746
4654
  args_1[_i - 5] = arguments[_i];
4747
4655
  }
4748
4656
  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) {
4749
- 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;
4657
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, outCustodyConfig, lpTokenMint, compoundingTokenMint, lamports, _a, custodyAccountMetas, custodyOracleAccountMetas, markets, _b, _c, custody, _d, _e, market, compoundingTokenAccount, removeCompoundingLiquidity, err_17;
4750
4658
  if (createUserATA === void 0) { createUserATA = true; }
4751
4659
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
4752
4660
  if (userPublicKey === void 0) { userPublicKey = undefined; }
@@ -4858,8 +4766,8 @@ var PerpetualsClient = (function () {
4858
4766
  instructions.push(removeCompoundingLiquidity);
4859
4767
  return [3, 8];
4860
4768
  case 7:
4861
- err_19 = _f.sent();
4862
- console.log("perpClient removeCompoundingLiquidity error:: ", err_19);
4769
+ err_17 = _f.sent();
4770
+ console.log("perpClient removeCompoundingLiquidity error:: ", err_17);
4863
4771
  return [3, 8];
4864
4772
  case 8: return [2, {
4865
4773
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4875,7 +4783,7 @@ var PerpetualsClient = (function () {
4875
4783
  args_1[_i - 3] = arguments[_i];
4876
4784
  }
4877
4785
  return __awaiter(_this, __spreadArray([amount_1, rewardTokenMint_1, poolConfig_1], args_1, true), void 0, function (amount, rewardTokenMint, poolConfig, createUserATA) {
4878
- 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;
4786
+ 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;
4879
4787
  if (createUserATA === void 0) { createUserATA = true; }
4880
4788
  return __generator(this, function (_g) {
4881
4789
  switch (_g.label) {
@@ -4973,8 +4881,8 @@ var PerpetualsClient = (function () {
4973
4881
  instructions.push(migrateStake);
4974
4882
  return [3, 8];
4975
4883
  case 7:
4976
- err_20 = _g.sent();
4977
- console.log("perpClient migrateStake error:: ", err_20);
4884
+ err_18 = _g.sent();
4885
+ console.log("perpClient migrateStake error:: ", err_18);
4978
4886
  return [3, 8];
4979
4887
  case 8: return [2, {
4980
4888
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -4985,7 +4893,7 @@ var PerpetualsClient = (function () {
4985
4893
  });
4986
4894
  };
4987
4895
  this.migrateFlp = function (amount, rewardTokenMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
4988
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_21;
4896
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, lpTokenMint, compoundingTokenMint, compoudingTokenAccount, flpStakeAccount, poolStakedLpVault, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, migrateFlp, err_19;
4989
4897
  return __generator(this, function (_d) {
4990
4898
  switch (_d.label) {
4991
4899
  case 0:
@@ -5057,8 +4965,8 @@ var PerpetualsClient = (function () {
5057
4965
  instructions.push(migrateFlp);
5058
4966
  return [3, 4];
5059
4967
  case 3:
5060
- err_21 = _d.sent();
5061
- console.log("perpClient migrateFlp error:: ", err_21);
4968
+ err_19 = _d.sent();
4969
+ console.log("perpClient migrateFlp error:: ", err_19);
5062
4970
  return [3, 4];
5063
4971
  case 4: return [2, {
5064
4972
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
@@ -5073,7 +4981,7 @@ var PerpetualsClient = (function () {
5073
4981
  args_1[_i - 1] = arguments[_i];
5074
4982
  }
5075
4983
  return __awaiter(_this, __spreadArray([poolConfig_1], args_1, true), void 0, function (poolConfig, rewardTokenSymbol) {
5076
- var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_22;
4984
+ var instructions, additionalSigners, rewardCustody, lpTokenMint, custodyAccountMetas, custodyOracleAccountMetas, markets, _a, _b, custody, _c, _d, market, compoundingFee, err_20;
5077
4985
  if (rewardTokenSymbol === void 0) { rewardTokenSymbol = 'USDC'; }
5078
4986
  return __generator(this, function (_e) {
5079
4987
  switch (_e.label) {
@@ -5131,8 +5039,8 @@ var PerpetualsClient = (function () {
5131
5039
  instructions.push(compoundingFee);
5132
5040
  return [3, 4];
5133
5041
  case 3:
5134
- err_22 = _e.sent();
5135
- console.log("perpClient compoundingFee error:: ", err_22);
5042
+ err_20 = _e.sent();
5043
+ console.log("perpClient compoundingFee error:: ", err_20);
5136
5044
  return [3, 4];
5137
5045
  case 4: return [2, {
5138
5046
  instructions: __spreadArray([], instructions, true),
@@ -5142,84 +5050,61 @@ var PerpetualsClient = (function () {
5142
5050
  });
5143
5051
  });
5144
5052
  };
5145
- this.burnAndClaim = function (owner, nftMint, poolConfig, createAta) { return __awaiter(_this, void 0, void 0, function () {
5146
- var preInstructions, instructions, postInstructions, additionalSigners, userTokenAccount, _a, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndClaimInstruction, err_23;
5147
- return __generator(this, function (_b) {
5148
- switch (_b.label) {
5053
+ this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5054
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_21;
5055
+ return __generator(this, function (_a) {
5056
+ switch (_a.label) {
5149
5057
  case 0:
5150
5058
  preInstructions = [];
5151
5059
  instructions = [];
5152
5060
  postInstructions = [];
5153
5061
  additionalSigners = [];
5154
- _b.label = 1;
5062
+ _a.label = 1;
5155
5063
  case 1:
5156
- _b.trys.push([1, 7, , 8]);
5157
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, owner, true)];
5158
- case 2:
5159
- userTokenAccount = _b.sent();
5160
- _a = createAta;
5161
- if (!_a) return [3, 4];
5064
+ _a.trys.push([1, 4, , 5]);
5065
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5066
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.tokenMint, owner, true);
5162
5067
  return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5163
- case 3:
5164
- _a = !(_b.sent());
5165
- _b.label = 4;
5166
- case 4:
5167
- if (_a) {
5168
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, userTokenAccount, owner, poolConfig.tokenMint));
5068
+ case 2:
5069
+ if (!(_a.sent())) {
5070
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(feePayer, userTokenAccount, owner, poolConfig.tokenMint));
5169
5071
  }
5170
- return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, owner, true)];
5171
- case 5:
5172
- nftTokenAccount = _b.sent();
5173
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5174
- Buffer.from("trading"),
5175
- nftMint.toBuffer(),
5176
- ], this.programId)[0];
5177
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5178
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5179
- 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];
5180
- 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];
5181
5072
  return [4, this.program.methods
5182
- .burnAndClaim({})
5073
+ .depositTokenStake({
5074
+ depositAmount: depositAmount
5075
+ })
5183
5076
  .accounts({
5184
5077
  owner: owner,
5185
- receivingTokenAccount: userTokenAccount,
5078
+ feePayer: feePayer,
5079
+ fundingTokenAccount: userTokenAccount,
5186
5080
  perpetuals: this.perpetuals.publicKey,
5187
5081
  tokenVault: poolConfig.tokenVault,
5188
5082
  tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5189
- metadataAccount: metadataAccount,
5190
- collectionMetadata: collectionMetadata,
5191
- edition: edition,
5192
- tokenRecord: tokenRecord,
5193
- tradingAccount: nftTradingAccount,
5194
- transferAuthority: poolConfig.transferAuthority,
5195
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5196
- nftMint: nftMint,
5197
- nftTokenAccount: nftTokenAccount,
5083
+ tokenStakeAccount: tokenStakeAccount,
5198
5084
  systemProgram: web3_js_1.SystemProgram.programId,
5199
5085
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5200
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5201
5086
  eventAuthority: this.eventAuthority.publicKey,
5202
5087
  program: this.programId,
5203
- receivingTokenMint: poolConfig.tokenMint,
5088
+ tokenMint: poolConfig.tokenMint,
5204
5089
  })
5205
5090
  .instruction()];
5206
- case 6:
5207
- burnAndClaimInstruction = _b.sent();
5208
- instructions.push(burnAndClaimInstruction);
5209
- return [3, 8];
5210
- case 7:
5211
- err_23 = _b.sent();
5212
- console.log("perpClient burnAndClaimInstruction error:: ", err_23);
5213
- throw err_23;
5214
- case 8: return [2, {
5091
+ case 3:
5092
+ depositTokenStakeInstruction = _a.sent();
5093
+ instructions.push(depositTokenStakeInstruction);
5094
+ return [3, 5];
5095
+ case 4:
5096
+ err_21 = _a.sent();
5097
+ console.log("perpClient depositStakingInstruction error:: ", err_21);
5098
+ throw err_21;
5099
+ case 5: return [2, {
5215
5100
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5216
5101
  additionalSigners: additionalSigners
5217
5102
  }];
5218
5103
  }
5219
5104
  });
5220
5105
  }); };
5221
- this.burnAndStake = function (owner, feePayer, nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5222
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, nftTokenAccount, nftTradingAccount, metadataAccount, collectionMetadata, edition, tokenRecord, burnAndStakeInstruction, err_24;
5106
+ this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5107
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_22;
5223
5108
  return __generator(this, function (_a) {
5224
5109
  switch (_a.label) {
5225
5110
  case 0:
@@ -5231,125 +5116,10 @@ var PerpetualsClient = (function () {
5231
5116
  case 1:
5232
5117
  _a.trys.push([1, 3, , 4]);
5233
5118
  tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5234
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, owner, true);
5235
- nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
5236
- Buffer.from("trading"),
5237
- nftMint.toBuffer(),
5238
- ], this.programId)[0];
5239
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5240
- collectionMetadata = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), poolConfig.nftCollectionAddress.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5241
- 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];
5242
- 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];
5243
5119
  return [4, this.program.methods
5244
- .burnAndStake({})
5245
- .accounts({
5246
- owner: owner,
5247
- feePayer: feePayer,
5248
- perpetuals: this.perpetuals.publicKey,
5249
- tokenVault: poolConfig.tokenVault,
5250
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5251
- tokenStakeAccount: tokenStakeAccount,
5252
- metadataAccount: metadataAccount,
5253
- collectionMetadata: collectionMetadata,
5254
- edition: edition,
5255
- tokenRecord: tokenRecord,
5256
- tradingAccount: nftTradingAccount,
5257
- transferAuthority: poolConfig.transferAuthority,
5258
- metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
5259
- nftMint: nftMint,
5260
- nftTokenAccount: nftTokenAccount,
5261
- systemProgram: web3_js_1.SystemProgram.programId,
5262
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5263
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5264
- eventAuthority: this.eventAuthority.publicKey,
5265
- program: this.programId
5266
- })
5267
- .instruction()];
5268
- case 2:
5269
- burnAndStakeInstruction = _a.sent();
5270
- instructions.push(burnAndStakeInstruction);
5271
- return [3, 4];
5272
- case 3:
5273
- err_24 = _a.sent();
5274
- console.log("perpClient burnAndStakeInstruction error:: ", err_24);
5275
- throw err_24;
5276
- case 4: return [2, {
5277
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5278
- additionalSigners: additionalSigners
5279
- }];
5280
- }
5281
- });
5282
- }); };
5283
- this.depositTokenStake = function (owner, feePayer, depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5284
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, depositTokenStakeInstruction, err_25;
5285
- return __generator(this, function (_a) {
5286
- switch (_a.label) {
5287
- case 0:
5288
- preInstructions = [];
5289
- instructions = [];
5290
- postInstructions = [];
5291
- additionalSigners = [];
5292
- _a.label = 1;
5293
- case 1:
5294
- _a.trys.push([1, 4, , 5]);
5295
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5296
- userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.tokenMint, owner, true);
5297
- return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5298
- case 2:
5299
- if (!(_a.sent())) {
5300
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(feePayer, userTokenAccount, owner, poolConfig.tokenMint));
5301
- }
5302
- return [4, this.program.methods
5303
- .depositTokenStake({
5304
- depositAmount: depositAmount
5305
- })
5306
- .accounts({
5307
- owner: owner,
5308
- feePayer: feePayer,
5309
- fundingTokenAccount: userTokenAccount,
5310
- perpetuals: this.perpetuals.publicKey,
5311
- tokenVault: poolConfig.tokenVault,
5312
- tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
5313
- tokenStakeAccount: tokenStakeAccount,
5314
- systemProgram: web3_js_1.SystemProgram.programId,
5315
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5316
- eventAuthority: this.eventAuthority.publicKey,
5317
- program: this.programId,
5318
- tokenMint: poolConfig.tokenMint,
5319
- })
5320
- .instruction()];
5321
- case 3:
5322
- depositTokenStakeInstruction = _a.sent();
5323
- instructions.push(depositTokenStakeInstruction);
5324
- return [3, 5];
5325
- case 4:
5326
- err_25 = _a.sent();
5327
- console.log("perpClient depositStakingInstruction error:: ", err_25);
5328
- throw err_25;
5329
- case 5: return [2, {
5330
- instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5331
- additionalSigners: additionalSigners
5332
- }];
5333
- }
5334
- });
5335
- }); };
5336
- this.unstakeTokenRequest = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5337
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, unstakeTokenRequestInstruction, err_26;
5338
- return __generator(this, function (_a) {
5339
- switch (_a.label) {
5340
- case 0:
5341
- preInstructions = [];
5342
- instructions = [];
5343
- postInstructions = [];
5344
- additionalSigners = [];
5345
- _a.label = 1;
5346
- case 1:
5347
- _a.trys.push([1, 3, , 4]);
5348
- tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5349
- return [4, this.program.methods
5350
- .unstakeTokenRequest({
5351
- unstakeAmount: unstakeAmount
5352
- })
5120
+ .unstakeTokenRequest({
5121
+ unstakeAmount: unstakeAmount
5122
+ })
5353
5123
  .accounts({
5354
5124
  owner: owner,
5355
5125
  tokenVault: poolConfig.tokenVault,
@@ -5363,9 +5133,9 @@ var PerpetualsClient = (function () {
5363
5133
  instructions.push(unstakeTokenRequestInstruction);
5364
5134
  return [3, 4];
5365
5135
  case 3:
5366
- err_26 = _a.sent();
5367
- console.log("perpClient unstakeTokenRequestInstruction error:: ", err_26);
5368
- throw err_26;
5136
+ err_22 = _a.sent();
5137
+ console.log("perpClient unstakeTokenRequestInstruction error:: ", err_22);
5138
+ throw err_22;
5369
5139
  case 4: return [2, {
5370
5140
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5371
5141
  additionalSigners: additionalSigners
@@ -5374,7 +5144,7 @@ var PerpetualsClient = (function () {
5374
5144
  });
5375
5145
  }); };
5376
5146
  this.unstakeTokenInstant = function (owner, unstakeAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5377
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_27;
5147
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, unstakeTokenInstantInstruction, err_23;
5378
5148
  return __generator(this, function (_a) {
5379
5149
  switch (_a.label) {
5380
5150
  case 0:
@@ -5415,9 +5185,9 @@ var PerpetualsClient = (function () {
5415
5185
  instructions.push(unstakeTokenInstantInstruction);
5416
5186
  return [3, 5];
5417
5187
  case 4:
5418
- err_27 = _a.sent();
5419
- console.log("perpClient unstakeTokenInstantInstruction error:: ", err_27);
5420
- throw err_27;
5188
+ err_23 = _a.sent();
5189
+ console.log("perpClient unstakeTokenInstantInstruction error:: ", err_23);
5190
+ throw err_23;
5421
5191
  case 5: return [2, {
5422
5192
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5423
5193
  additionalSigners: additionalSigners
@@ -5426,7 +5196,7 @@ var PerpetualsClient = (function () {
5426
5196
  });
5427
5197
  }); };
5428
5198
  this.withdrawToken = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5429
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_28;
5199
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, withdrawTokenInstruction, err_24;
5430
5200
  return __generator(this, function (_a) {
5431
5201
  switch (_a.label) {
5432
5202
  case 0:
@@ -5467,9 +5237,9 @@ var PerpetualsClient = (function () {
5467
5237
  instructions.push(withdrawTokenInstruction);
5468
5238
  return [3, 5];
5469
5239
  case 4:
5470
- err_28 = _a.sent();
5471
- console.log("perpClient withdrawTokenInstruction error:: ", err_28);
5472
- throw err_28;
5240
+ err_24 = _a.sent();
5241
+ console.log("perpClient withdrawTokenInstruction error:: ", err_24);
5242
+ throw err_24;
5473
5243
  case 5: return [2, {
5474
5244
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5475
5245
  additionalSigners: additionalSigners
@@ -5478,7 +5248,7 @@ var PerpetualsClient = (function () {
5478
5248
  });
5479
5249
  }); };
5480
5250
  this.cancelUnstakeRequest = function (owner, withdrawRequestId, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5481
- var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_29;
5251
+ var preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, cancelUnstakeRequestInstruction, err_25;
5482
5252
  return __generator(this, function (_a) {
5483
5253
  switch (_a.label) {
5484
5254
  case 0:
@@ -5507,9 +5277,9 @@ var PerpetualsClient = (function () {
5507
5277
  instructions.push(cancelUnstakeRequestInstruction);
5508
5278
  return [3, 4];
5509
5279
  case 3:
5510
- err_29 = _a.sent();
5511
- console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_29);
5512
- throw err_29;
5280
+ err_25 = _a.sent();
5281
+ console.log("perpClient cancelUnstakeRequestInstruction error:: ", err_25);
5282
+ throw err_25;
5513
5283
  case 4: return [2, {
5514
5284
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5515
5285
  additionalSigners: additionalSigners
@@ -5523,7 +5293,7 @@ var PerpetualsClient = (function () {
5523
5293
  args_1[_i - 2] = arguments[_i];
5524
5294
  }
5525
5295
  return __awaiter(_this, __spreadArray([owner_1, poolConfig_1], args_1, true), void 0, function (owner, poolConfig, createUserATA) {
5526
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_30;
5296
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, userTokenAccount, _a, collectTokenRewardInstruction, err_26;
5527
5297
  if (createUserATA === void 0) { createUserATA = true; }
5528
5298
  return __generator(this, function (_b) {
5529
5299
  switch (_b.label) {
@@ -5569,9 +5339,9 @@ var PerpetualsClient = (function () {
5569
5339
  instructions.push(collectTokenRewardInstruction);
5570
5340
  return [3, 6];
5571
5341
  case 5:
5572
- err_30 = _b.sent();
5573
- console.log("perpClient collectTokenRewardInstruction error:: ", err_30);
5574
- throw err_30;
5342
+ err_26 = _b.sent();
5343
+ console.log("perpClient collectTokenRewardInstruction error:: ", err_26);
5344
+ throw err_26;
5575
5345
  case 6: return [2, {
5576
5346
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5577
5347
  additionalSigners: additionalSigners
@@ -5586,7 +5356,7 @@ var PerpetualsClient = (function () {
5586
5356
  args_1[_i - 3] = arguments[_i];
5587
5357
  }
5588
5358
  return __awaiter(_this, __spreadArray([owner_1, rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rewardSymbol, poolConfig, createUserATA) {
5589
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_31;
5359
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, tokenStakeAccount, userTokenAccount, _a, collectRevenueInstruction, err_27;
5590
5360
  if (createUserATA === void 0) { createUserATA = true; }
5591
5361
  return __generator(this, function (_b) {
5592
5362
  switch (_b.label) {
@@ -5633,9 +5403,9 @@ var PerpetualsClient = (function () {
5633
5403
  instructions.push(collectRevenueInstruction);
5634
5404
  return [3, 6];
5635
5405
  case 5:
5636
- err_31 = _b.sent();
5637
- console.log("perpClient collectRevenueInstruction error:: ", err_31);
5638
- throw err_31;
5406
+ err_27 = _b.sent();
5407
+ console.log("perpClient collectRevenueInstruction error:: ", err_27);
5408
+ throw err_27;
5639
5409
  case 6: return [2, {
5640
5410
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5641
5411
  additionalSigners: additionalSigners
@@ -5644,179 +5414,18 @@ var PerpetualsClient = (function () {
5644
5414
  });
5645
5415
  });
5646
5416
  };
5647
- this.initRewardVault = function (nftCount, rewardSymbol, collectionMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5648
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fbNftProgramData, rewardVault, rewardTokenAccount, nftTransferAuthority, initRewardVault, err_32;
5649
- return __generator(this, function (_a) {
5650
- switch (_a.label) {
5651
- case 0:
5652
- publicKey = this.provider.wallet.publicKey;
5653
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5654
- instructions = [];
5655
- additionalSigners = [];
5656
- _a.label = 1;
5657
- case 1:
5658
- _a.trys.push([1, 3, , 4]);
5659
- fbNftProgramData = web3_js_1.PublicKey.findProgramAddressSync([this.programFbnftReward.programId.toBuffer()], new web3_js_1.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"))[0];
5660
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5661
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5662
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5663
- return [4, this.programFbnftReward.methods
5664
- .initRewardVault({
5665
- nftCount: nftCount
5666
- })
5667
- .accounts({
5668
- admin: publicKey,
5669
- transferAuthority: nftTransferAuthority,
5670
- rewardVault: rewardVault,
5671
- rewardMint: rewardCustodyMint,
5672
- rewardTokenAccount: rewardTokenAccount,
5673
- collectionMint: collectionMint,
5674
- programData: fbNftProgramData,
5675
- systemProgram: web3_js_1.SystemProgram.programId,
5676
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5677
- rent: web3_js_1.SYSVAR_RENT_PUBKEY
5678
- })
5679
- .instruction()];
5680
- case 2:
5681
- initRewardVault = _a.sent();
5682
- instructions.push(initRewardVault);
5683
- return [3, 4];
5684
- case 3:
5685
- err_32 = _a.sent();
5686
- console.log("perpClient InitRewardVault error:: ", err_32);
5687
- throw err_32;
5688
- case 4: return [2, {
5689
- instructions: __spreadArray([], instructions, true),
5690
- additionalSigners: additionalSigners
5691
- }];
5692
- }
5693
- });
5694
- }); };
5695
- this.distributeReward = function (rewardAmount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5696
- var publicKey, rewardCustodyMint, instructions, additionalSigners, fundingAccount, rewardVault, rewardTokenAccount, distributeReward, err_33;
5697
- return __generator(this, function (_a) {
5698
- switch (_a.label) {
5699
- case 0:
5700
- publicKey = this.provider.wallet.publicKey;
5701
- rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
5702
- instructions = [];
5703
- additionalSigners = [];
5704
- _a.label = 1;
5705
- case 1:
5706
- _a.trys.push([1, 3, , 4]);
5707
- fundingAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true);
5708
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5709
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5710
- return [4, this.programFbnftReward.methods
5711
- .distributeRewards({
5712
- rewardAmount: rewardAmount
5713
- })
5714
- .accounts({
5715
- admin: publicKey,
5716
- fundingAccount: fundingAccount,
5717
- rewardVault: rewardVault,
5718
- rewardTokenAccount: rewardTokenAccount,
5719
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5720
- })
5721
- .instruction()];
5722
- case 2:
5723
- distributeReward = _a.sent();
5724
- instructions.push(distributeReward);
5725
- return [3, 4];
5726
- case 3:
5727
- err_33 = _a.sent();
5728
- console.log("perpClient distributeReward error:: ", err_33);
5729
- throw err_33;
5730
- case 4: return [2, {
5731
- instructions: __spreadArray([], instructions, true),
5732
- additionalSigners: additionalSigners
5733
- }];
5734
- }
5735
- });
5736
- }); };
5737
- this.collectNftReward = function (rewardSymbol_1, poolConfig_1, nftMint_1) {
5417
+ this.collectRebate = function (owner_1, rebateSymbol_1, poolConfig_1) {
5738
5418
  var args_1 = [];
5739
5419
  for (var _i = 3; _i < arguments.length; _i++) {
5740
5420
  args_1[_i - 3] = arguments[_i];
5741
5421
  }
5742
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1, nftMint_1], args_1, true), void 0, function (rewardSymbol, poolConfig, nftMint, createUserATA) {
5743
- var publicKey, rewardToken, rewardCustodyMint, instructions, additionalSigners, nftTokenAccount, metadataAccount, receivingTokenAccount, _a, rewardRecord, rewardVault, rewardTokenAccount, nftTransferAuthority, collectNftReward, err_34;
5422
+ return __awaiter(_this, __spreadArray([owner_1, rebateSymbol_1, poolConfig_1], args_1, true), void 0, function (owner, rebateSymbol, poolConfig, createUserATA) {
5423
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateMint, tokenStakeAccount, userTokenAccount, _a, collectRebateInstruction, err_28;
5744
5424
  if (createUserATA === void 0) { createUserATA = true; }
5745
5425
  return __generator(this, function (_b) {
5746
5426
  switch (_b.label) {
5747
5427
  case 0:
5748
5428
  publicKey = this.provider.wallet.publicKey;
5749
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5750
- rewardCustodyMint = rewardToken.mintKey;
5751
- instructions = [];
5752
- additionalSigners = [];
5753
- _b.label = 1;
5754
- case 1:
5755
- _b.trys.push([1, 5, , 6]);
5756
- nftTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(nftMint, publicKey, true);
5757
- metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
5758
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5759
- _a = createUserATA;
5760
- if (!_a) return [3, 3];
5761
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5762
- case 2:
5763
- _a = !(_b.sent());
5764
- _b.label = 3;
5765
- case 3:
5766
- if (_a) {
5767
- 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));
5768
- }
5769
- rewardRecord = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_record"), nftMint.toBuffer()], this.programFbnftReward.programId)[0];
5770
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5771
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5772
- nftTransferAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("transfer_authority")], this.programFbnftReward.programId)[0];
5773
- return [4, this.programFbnftReward.methods
5774
- .collectReward()
5775
- .accounts({
5776
- owner: publicKey,
5777
- feePayer: publicKey,
5778
- nftMint: nftMint,
5779
- nftTokenAccount: nftTokenAccount,
5780
- metadataAccount: metadataAccount,
5781
- receivingAccount: receivingTokenAccount,
5782
- rewardRecord: rewardRecord,
5783
- rewardVault: rewardVault,
5784
- rewardTokenAccount: rewardTokenAccount,
5785
- transferAuthority: nftTransferAuthority,
5786
- systemProgram: web3_js_1.SystemProgram.programId,
5787
- tokenProgram: rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID,
5788
- })
5789
- .instruction()];
5790
- case 4:
5791
- collectNftReward = _b.sent();
5792
- instructions.push(collectNftReward);
5793
- return [3, 6];
5794
- case 5:
5795
- err_34 = _b.sent();
5796
- throw err_34;
5797
- case 6: return [2, {
5798
- instructions: __spreadArray([], instructions, true),
5799
- additionalSigners: additionalSigners
5800
- }];
5801
- }
5802
- });
5803
- });
5804
- };
5805
- this.collectAndDistributeFee = function (rewardSymbol_1, poolConfig_1) {
5806
- var args_1 = [];
5807
- for (var _i = 2; _i < arguments.length; _i++) {
5808
- args_1[_i - 2] = arguments[_i];
5809
- }
5810
- return __awaiter(_this, __spreadArray([rewardSymbol_1, poolConfig_1], args_1, true), void 0, function (rewardSymbol, poolConfig, createUserATA, nftTradingAccount) {
5811
- var publicKey, rewardToken, rewardCustodyMint, rewardCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, pool, flpStakeAccount, receivingTokenAccount, _a, tradingAccount, rewardVault, rewardTokenAccount, withdrawStakeInstruction, err_35;
5812
- if (createUserATA === void 0) { createUserATA = true; }
5813
- return __generator(this, function (_b) {
5814
- switch (_b.label) {
5815
- case 0:
5816
- publicKey = this.provider.wallet.publicKey;
5817
- rewardToken = poolConfig.getTokenFromSymbol(rewardSymbol);
5818
- rewardCustodyMint = rewardToken.mintKey;
5819
- rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(rewardToken.mintKey); });
5820
5429
  preInstructions = [];
5821
5430
  instructions = [];
5822
5431
  postInstructions = [];
@@ -5824,59 +5433,43 @@ var PerpetualsClient = (function () {
5824
5433
  _b.label = 1;
5825
5434
  case 1:
5826
5435
  _b.trys.push([1, 5, , 6]);
5827
- pool = poolConfig.poolAddress;
5828
- flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.program.programId)[0];
5829
- receivingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rewardCustodyMint, publicKey, true, rewardToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID);
5436
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5437
+ tokenStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("token_stake"), owner.toBuffer()], this.programId)[0];
5438
+ userTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(rebateMint, owner, true);
5830
5439
  _a = createUserATA;
5831
5440
  if (!_a) return [3, 3];
5832
- return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
5441
+ return [4, (0, utils_1.checkIfAccountExists)(userTokenAccount, this.provider.connection)];
5833
5442
  case 2:
5834
5443
  _a = !(_b.sent());
5835
5444
  _b.label = 3;
5836
5445
  case 3:
5837
5446
  if (_a) {
5838
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, rewardCustodyMint));
5839
- }
5840
- tradingAccount = [];
5841
- if (nftTradingAccount) {
5842
- tradingAccount.push({
5843
- pubkey: nftTradingAccount,
5844
- isSigner: false,
5845
- isWritable: true,
5846
- });
5447
+ instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userTokenAccount, publicKey, rebateMint));
5847
5448
  }
5848
- rewardVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_vault")], this.programFbnftReward.programId)[0];
5849
- rewardTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("reward_token_account")], this.programFbnftReward.programId)[0];
5850
- return [4, this.programPerpComposability.methods
5851
- .collectAndDistributeFee()
5449
+ return [4, this.program.methods
5450
+ .collectRebate()
5852
5451
  .accounts({
5853
- perpProgram: this.programId,
5854
- owner: publicKey,
5855
- receivingTokenAccount: receivingTokenAccount,
5856
- transferAuthority: poolConfig.transferAuthority,
5452
+ owner: owner,
5453
+ receivingTokenAccount: userTokenAccount,
5857
5454
  perpetuals: this.perpetuals.publicKey,
5858
- pool: pool,
5859
- feeCustody: rewardCustodyConfig.custodyAccount,
5860
- flpStakeAccount: flpStakeAccount,
5861
- feeCustodyTokenAccount: rewardCustodyConfig.tokenAccount,
5862
- systemProgram: web3_js_1.SystemProgram.programId,
5455
+ transferAuthority: poolConfig.transferAuthority,
5456
+ rebateVault: poolConfig.rebateVault,
5457
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5458
+ tokenStakeAccount: tokenStakeAccount,
5863
5459
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5864
5460
  eventAuthority: this.eventAuthority.publicKey,
5865
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
5866
- fbnftRewardsProgram: this.programFbnftReward.programId,
5867
- rewardVault: rewardVault,
5868
- rewardTokenAccount: rewardTokenAccount
5461
+ program: this.programId,
5462
+ receivingTokenMint: rebateMint,
5869
5463
  })
5870
- .remainingAccounts(tradingAccount)
5871
5464
  .instruction()];
5872
5465
  case 4:
5873
- withdrawStakeInstruction = _b.sent();
5874
- instructions.push(withdrawStakeInstruction);
5466
+ collectRebateInstruction = _b.sent();
5467
+ instructions.push(collectRebateInstruction);
5875
5468
  return [3, 6];
5876
5469
  case 5:
5877
- err_35 = _b.sent();
5878
- console.log("perpClient withdrawStake error:: ", err_35);
5879
- throw err_35;
5470
+ err_28 = _b.sent();
5471
+ console.log("perpClient collectRebateInstruction error:: ", err_28);
5472
+ throw err_28;
5880
5473
  case 6: return [2, {
5881
5474
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5882
5475
  additionalSigners: additionalSigners
@@ -5885,13 +5478,60 @@ var PerpetualsClient = (function () {
5885
5478
  });
5886
5479
  });
5887
5480
  };
5481
+ this.settleRebates = function (rebateSymbol, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
5482
+ var preInstructions, instructions, postInstructions, additionalSigners, rewardCustody, rebateMint, settleRebatesInstruction, err_29;
5483
+ return __generator(this, function (_a) {
5484
+ switch (_a.label) {
5485
+ case 0:
5486
+ preInstructions = [];
5487
+ instructions = [];
5488
+ postInstructions = [];
5489
+ additionalSigners = [];
5490
+ _a.label = 1;
5491
+ case 1:
5492
+ _a.trys.push([1, 3, , 4]);
5493
+ rewardCustody = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
5494
+ rebateMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
5495
+ return [4, this.program.methods
5496
+ .settleRebates()
5497
+ .accounts({
5498
+ transferAuthority: poolConfig.transferAuthority,
5499
+ perpetuals: this.perpetuals.publicKey,
5500
+ pool: poolConfig.poolAddress,
5501
+ rewardCustody: rewardCustody.custodyAccount,
5502
+ rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
5503
+ rewardCustodyTokenAccount: rewardCustody.tokenAccount,
5504
+ rebateVault: poolConfig.rebateVault,
5505
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
5506
+ tokenMint: rebateMint,
5507
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
5508
+ eventAuthority: this.eventAuthority.publicKey,
5509
+ program: this.programId,
5510
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
5511
+ })
5512
+ .instruction()];
5513
+ case 2:
5514
+ settleRebatesInstruction = _a.sent();
5515
+ instructions.push(settleRebatesInstruction);
5516
+ return [3, 4];
5517
+ case 3:
5518
+ err_29 = _a.sent();
5519
+ console.log("perpClient settleRebatesInstruction error:: ", err_29);
5520
+ throw err_29;
5521
+ case 4: return [2, {
5522
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
5523
+ additionalSigners: additionalSigners
5524
+ }];
5525
+ }
5526
+ });
5527
+ }); };
5888
5528
  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) {
5889
5529
  var args_1 = [];
5890
5530
  for (var _i = 11; _i < arguments.length; _i++) {
5891
5531
  args_1[_i - 11] = arguments[_i];
5892
5532
  }
5893
5533
  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) {
5894
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_36;
5534
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, userReserveTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, orderAccount, placeLimitOrder, err_30;
5895
5535
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
5896
5536
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
5897
5537
  return __generator(this, function (_c) {
@@ -5997,9 +5637,9 @@ var PerpetualsClient = (function () {
5997
5637
  instructions.push(placeLimitOrder);
5998
5638
  return [3, 10];
5999
5639
  case 9:
6000
- err_36 = _c.sent();
6001
- console.log("perpClient placeLimitOrder error:: ", err_36);
6002
- throw err_36;
5640
+ err_30 = _c.sent();
5641
+ console.log("perpClient placeLimitOrder error:: ", err_30);
5642
+ throw err_30;
6003
5643
  case 10: return [2, {
6004
5644
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6005
5645
  additionalSigners: additionalSigners
@@ -6014,7 +5654,7 @@ var PerpetualsClient = (function () {
6014
5654
  args_1[_i - 11] = arguments[_i];
6015
5655
  }
6016
5656
  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) {
6017
- var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_37;
5657
+ var publicKey, targetCustodyConfig, reserveCustodyConfig, collateralCustodyConfig, receiveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, wrappedSolAccount, userReceivingTokenAccount, lamports, _a, positionAccount, orderAccount, editLimitOrder, err_31;
6018
5658
  if (createUserATA === void 0) { createUserATA = true; }
6019
5659
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6020
5660
  return __generator(this, function (_b) {
@@ -6105,9 +5745,9 @@ var PerpetualsClient = (function () {
6105
5745
  instructions.push(editLimitOrder);
6106
5746
  return [3, 8];
6107
5747
  case 7:
6108
- err_37 = _b.sent();
6109
- console.log("perpClient editLimitOrder error:: ", err_37);
6110
- throw err_37;
5748
+ err_31 = _b.sent();
5749
+ console.log("perpClient editLimitOrder error:: ", err_31);
5750
+ throw err_31;
6111
5751
  case 8: return [2, {
6112
5752
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6113
5753
  additionalSigners: additionalSigners
@@ -6121,11 +5761,10 @@ var PerpetualsClient = (function () {
6121
5761
  for (var _i = 7; _i < arguments.length; _i++) {
6122
5762
  args_1[_i - 7] = arguments[_i];
6123
5763
  }
6124
- 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) {
6125
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_38;
5764
+ 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) {
5765
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitOrder, err_32;
6126
5766
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6127
5767
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6128
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6129
5768
  return __generator(this, function (_a) {
6130
5769
  switch (_a.label) {
6131
5770
  case 0:
@@ -6168,16 +5807,16 @@ var PerpetualsClient = (function () {
6168
5807
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6169
5808
  collateralMint: collateralCustodyConfig.mintKey,
6170
5809
  })
6171
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5810
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6172
5811
  .instruction()];
6173
5812
  case 2:
6174
5813
  executeLimitOrder = _a.sent();
6175
5814
  instructions.push(executeLimitOrder);
6176
5815
  return [3, 4];
6177
5816
  case 3:
6178
- err_38 = _a.sent();
6179
- console.log("perpClient executeLimitOrder error:: ", err_38);
6180
- throw err_38;
5817
+ err_32 = _a.sent();
5818
+ console.log("perpClient executeLimitOrder error:: ", err_32);
5819
+ throw err_32;
6181
5820
  case 4: return [2, {
6182
5821
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6183
5822
  additionalSigners: additionalSigners
@@ -6191,11 +5830,10 @@ var PerpetualsClient = (function () {
6191
5830
  for (var _i = 8; _i < arguments.length; _i++) {
6192
5831
  args_1[_i - 8] = arguments[_i];
6193
5832
  }
6194
- 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) {
6195
- var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_39;
5833
+ 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) {
5834
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, reserveCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, executeLimitWithSwap, err_33;
6196
5835
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6197
5836
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6198
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6199
5837
  return __generator(this, function (_a) {
6200
5838
  switch (_a.label) {
6201
5839
  case 0:
@@ -6241,16 +5879,16 @@ var PerpetualsClient = (function () {
6241
5879
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6242
5880
  collateralMint: collateralCustodyConfig.mintKey,
6243
5881
  })
6244
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
5882
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6245
5883
  .instruction()];
6246
5884
  case 2:
6247
5885
  executeLimitWithSwap = _a.sent();
6248
5886
  instructions.push(executeLimitWithSwap);
6249
5887
  return [3, 4];
6250
5888
  case 3:
6251
- err_39 = _a.sent();
6252
- console.log("perpClient executeLimitWithSwap error:: ", err_39);
6253
- throw err_39;
5889
+ err_33 = _a.sent();
5890
+ console.log("perpClient executeLimitWithSwap error:: ", err_33);
5891
+ throw err_33;
6254
5892
  case 4: return [2, {
6255
5893
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6256
5894
  additionalSigners: additionalSigners
@@ -6260,7 +5898,7 @@ var PerpetualsClient = (function () {
6260
5898
  });
6261
5899
  };
6262
5900
  this.placeTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6263
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_40;
5901
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, placeTriggerOrder, err_34;
6264
5902
  return __generator(this, function (_a) {
6265
5903
  switch (_a.label) {
6266
5904
  case 0:
@@ -6308,9 +5946,9 @@ var PerpetualsClient = (function () {
6308
5946
  instructions.push(placeTriggerOrder);
6309
5947
  return [3, 4];
6310
5948
  case 3:
6311
- err_40 = _a.sent();
6312
- console.log("perpClient placeTriggerOrder error:: ", err_40);
6313
- throw err_40;
5949
+ err_34 = _a.sent();
5950
+ console.log("perpClient placeTriggerOrder error:: ", err_34);
5951
+ throw err_34;
6314
5952
  case 4: return [2, {
6315
5953
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6316
5954
  additionalSigners: additionalSigners
@@ -6319,7 +5957,7 @@ var PerpetualsClient = (function () {
6319
5957
  });
6320
5958
  }); };
6321
5959
  this.editTriggerOrder = function (targetSymbol, collateralSymbol, receiveSymbol, side, orderId, triggerPrice, deltaSizeAmount, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6322
- var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_41;
5960
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, receivingCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, positionAccount, orderAccount, editTriggerOrder, err_35;
6323
5961
  return __generator(this, function (_a) {
6324
5962
  switch (_a.label) {
6325
5963
  case 0:
@@ -6366,9 +6004,9 @@ var PerpetualsClient = (function () {
6366
6004
  instructions.push(editTriggerOrder);
6367
6005
  return [3, 4];
6368
6006
  case 3:
6369
- err_41 = _a.sent();
6370
- console.log("perpClient editTriggerOrder error:: ", err_41);
6371
- throw err_41;
6007
+ err_35 = _a.sent();
6008
+ console.log("perpClient editTriggerOrder error:: ", err_35);
6009
+ throw err_35;
6372
6010
  case 4: return [2, {
6373
6011
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6374
6012
  additionalSigners: additionalSigners
@@ -6377,7 +6015,7 @@ var PerpetualsClient = (function () {
6377
6015
  });
6378
6016
  }); };
6379
6017
  this.cancelTriggerOrder = function (targetSymbol, collateralSymbol, side, orderId, isStopLoss, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6380
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_42;
6018
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, cancelTriggerOrder, err_36;
6381
6019
  return __generator(this, function (_a) {
6382
6020
  switch (_a.label) {
6383
6021
  case 0:
@@ -6410,9 +6048,9 @@ var PerpetualsClient = (function () {
6410
6048
  instructions.push(cancelTriggerOrder);
6411
6049
  return [3, 4];
6412
6050
  case 3:
6413
- err_42 = _a.sent();
6414
- console.log("perpClient cancelTriggerOrder error:: ", err_42);
6415
- throw err_42;
6051
+ err_36 = _a.sent();
6052
+ console.log("perpClient cancelTriggerOrder error:: ", err_36);
6053
+ throw err_36;
6416
6054
  case 4: return [2, {
6417
6055
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6418
6056
  additionalSigners: additionalSigners
@@ -6421,7 +6059,7 @@ var PerpetualsClient = (function () {
6421
6059
  });
6422
6060
  }); };
6423
6061
  this.cancelAllTriggerOrders = function (targetSymbol, collateralSymbol, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6424
- var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_43;
6062
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, orderAccount, positionAccount, cancelAllTriggerOrders, err_37;
6425
6063
  return __generator(this, function (_a) {
6426
6064
  switch (_a.label) {
6427
6065
  case 0:
@@ -6452,9 +6090,9 @@ var PerpetualsClient = (function () {
6452
6090
  instructions.push(cancelAllTriggerOrders);
6453
6091
  return [3, 4];
6454
6092
  case 3:
6455
- err_43 = _a.sent();
6456
- console.log("perpClient cancelAllTriggerOrders error:: ", err_43);
6457
- throw err_43;
6093
+ err_37 = _a.sent();
6094
+ console.log("perpClient cancelAllTriggerOrders error:: ", err_37);
6095
+ throw err_37;
6458
6096
  case 4: return [2, {
6459
6097
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6460
6098
  additionalSigners: additionalSigners
@@ -6467,13 +6105,12 @@ var PerpetualsClient = (function () {
6467
6105
  for (var _i = 9; _i < arguments.length; _i++) {
6468
6106
  args_1[_i - 9] = arguments[_i];
6469
6107
  }
6470
- 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) {
6471
- 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;
6108
+ 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) {
6109
+ 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;
6472
6110
  if (createUserATA === void 0) { createUserATA = true; }
6473
6111
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6474
6112
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6475
6113
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6476
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6477
6114
  return __generator(this, function (_e) {
6478
6115
  switch (_e.label) {
6479
6116
  case 0:
@@ -6568,16 +6205,16 @@ var PerpetualsClient = (function () {
6568
6205
  collateralMint: collateralCustodyConfig.mintKey,
6569
6206
  collateralTokenProgram: collateralToken.isToken2022 ? spl_token_1.TOKEN_2022_PROGRAM_ID : spl_token_1.TOKEN_PROGRAM_ID
6570
6207
  })
6571
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6208
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6572
6209
  .instruction()];
6573
6210
  case 8:
6574
6211
  executeTriggerWithSwap = _e.sent();
6575
6212
  instructions.push(executeTriggerWithSwap);
6576
6213
  return [3, 10];
6577
6214
  case 9:
6578
- err_44 = _e.sent();
6579
- console.log("perpClient executeTriggerWithSwap error:: ", err_44);
6580
- throw err_44;
6215
+ err_38 = _e.sent();
6216
+ console.log("perpClient executeTriggerWithSwap error:: ", err_38);
6217
+ throw err_38;
6581
6218
  case 10: return [2, {
6582
6219
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6583
6220
  additionalSigners: additionalSigners
@@ -6591,13 +6228,12 @@ var PerpetualsClient = (function () {
6591
6228
  for (var _i = 8; _i < arguments.length; _i++) {
6592
6229
  args_1[_i - 8] = arguments[_i];
6593
6230
  }
6594
- 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) {
6595
- var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_45;
6231
+ 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) {
6232
+ var payerPubkey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, _a, positionAccount, orderAccount, executeTriggerOrder, err_39;
6596
6233
  if (createUserATA === void 0) { createUserATA = true; }
6597
6234
  if (ephemeralSignerPubkey === void 0) { ephemeralSignerPubkey = undefined; }
6598
6235
  if (tokenStakeAccount === void 0) { tokenStakeAccount = web3_js_1.PublicKey.default; }
6599
6236
  if (userReferralAccount === void 0) { userReferralAccount = web3_js_1.PublicKey.default; }
6600
- if (rebateTokenAccount === void 0) { rebateTokenAccount = web3_js_1.PublicKey.default; }
6601
6237
  return __generator(this, function (_b) {
6602
6238
  switch (_b.label) {
6603
6239
  case 0:
@@ -6657,16 +6293,16 @@ var PerpetualsClient = (function () {
6657
6293
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
6658
6294
  receivingMint: collateralCustodyConfig.mintKey
6659
6295
  })
6660
- .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, rebateTokenAccount, privilege), true))
6296
+ .remainingAccounts(__spreadArray([], (0, getReferralAccounts_1.getReferralAccounts)(tokenStakeAccount, userReferralAccount, privilege), true))
6661
6297
  .instruction()];
6662
6298
  case 6:
6663
6299
  executeTriggerOrder = _b.sent();
6664
6300
  instructions.push(executeTriggerOrder);
6665
6301
  return [3, 8];
6666
6302
  case 7:
6667
- err_45 = _b.sent();
6668
- console.log("perpClient executeTriggerOrder error:: ", err_45);
6669
- throw err_45;
6303
+ err_39 = _b.sent();
6304
+ console.log("perpClient executeTriggerOrder error:: ", err_39);
6305
+ throw err_39;
6670
6306
  case 8: return [2, {
6671
6307
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6672
6308
  additionalSigners: additionalSigners
@@ -6681,7 +6317,7 @@ var PerpetualsClient = (function () {
6681
6317
  args_1[_i - 5] = arguments[_i];
6682
6318
  }
6683
6319
  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) {
6684
- 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;
6320
+ 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;
6685
6321
  if (useFeesPool === void 0) { useFeesPool = false; }
6686
6322
  if (createUserATA === void 0) { createUserATA = true; }
6687
6323
  if (unWrapSol === void 0) { unWrapSol = false; }
@@ -6886,9 +6522,9 @@ var PerpetualsClient = (function () {
6886
6522
  }
6887
6523
  return [3, 20];
6888
6524
  case 19:
6889
- err_46 = _g.sent();
6890
- console.error("perpClient Swap error:: ", err_46);
6891
- throw err_46;
6525
+ err_40 = _g.sent();
6526
+ console.error("perpClient Swap error:: ", err_40);
6527
+ throw err_40;
6892
6528
  case 20: return [2, {
6893
6529
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6894
6530
  additionalSigners: additionalSigners
@@ -6898,7 +6534,7 @@ var PerpetualsClient = (function () {
6898
6534
  });
6899
6535
  };
6900
6536
  this.swapFeeInternal = function (rewardTokenSymbol, swapTokenSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6901
- var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_47;
6537
+ var rewardCustody, custody, publicKey, preInstructions, instructions, postInstructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody_1, params, inx, err_41;
6902
6538
  return __generator(this, function (_b) {
6903
6539
  switch (_b.label) {
6904
6540
  case 0:
@@ -6943,11 +6579,7 @@ var PerpetualsClient = (function () {
6943
6579
  rewardCustody: rewardCustody.custodyAccount,
6944
6580
  rewardCustodyOracleAccount: this.useExtOracleAccount ? rewardCustody.extOracleAccount : rewardCustody.intOracleAccount,
6945
6581
  rewardCustodyTokenAccount: rewardCustody.tokenAccount,
6946
- custody: custody.custodyAccount,
6947
- custodyOracleAccount: this.useExtOracleAccount ? custody.extOracleAccount : custody.intOracleAccount,
6948
- custodyTokenAccount: custody.tokenAccount,
6949
6582
  eventAuthority: this.eventAuthority.publicKey,
6950
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
6951
6583
  program: this.programId,
6952
6584
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
6953
6585
  })
@@ -6958,9 +6590,9 @@ var PerpetualsClient = (function () {
6958
6590
  instructions.push(inx);
6959
6591
  return [3, 4];
6960
6592
  case 3:
6961
- err_47 = _b.sent();
6962
- console.error("perpClient Swap error:: ", err_47);
6963
- throw err_47;
6593
+ err_41 = _b.sent();
6594
+ console.error("perpClient Swap error:: ", err_41);
6595
+ throw err_41;
6964
6596
  case 4: return [2, {
6965
6597
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
6966
6598
  additionalSigners: additionalSigners
@@ -6969,7 +6601,7 @@ var PerpetualsClient = (function () {
6969
6601
  });
6970
6602
  }); };
6971
6603
  this.setLpTokenPrice = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
6972
- var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_48;
6604
+ var instructions, additionalSigners, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, setLpTokenPriceInstruction, err_42;
6973
6605
  return __generator(this, function (_d) {
6974
6606
  switch (_d.label) {
6975
6607
  case 0:
@@ -7017,9 +6649,9 @@ var PerpetualsClient = (function () {
7017
6649
  instructions.push(setLpTokenPriceInstruction);
7018
6650
  return [3, 4];
7019
6651
  case 3:
7020
- err_48 = _d.sent();
7021
- console.log("perpClient setLpTokenPriceInstruction error:: ", err_48);
7022
- throw err_48;
6652
+ err_42 = _d.sent();
6653
+ console.log("perpClient setLpTokenPriceInstruction error:: ", err_42);
6654
+ throw err_42;
7023
6655
  case 4: return [2, {
7024
6656
  instructions: __spreadArray([], instructions, true),
7025
6657
  additionalSigners: additionalSigners
@@ -7067,7 +6699,7 @@ var PerpetualsClient = (function () {
7067
6699
  });
7068
6700
  }); };
7069
6701
  this.setAdminSigners = function (admins, minSignatures) { return __awaiter(_this, void 0, void 0, function () {
7070
- var adminMetas, _i, admins_2, admin, err_49;
6702
+ var adminMetas, _i, admins_2, admin, err_43;
7071
6703
  return __generator(this, function (_a) {
7072
6704
  switch (_a.label) {
7073
6705
  case 0:
@@ -7097,11 +6729,11 @@ var PerpetualsClient = (function () {
7097
6729
  _a.sent();
7098
6730
  return [3, 4];
7099
6731
  case 3:
7100
- err_49 = _a.sent();
6732
+ err_43 = _a.sent();
7101
6733
  if (this.printErrors) {
7102
- console.error("setAdminSigners err:", err_49);
6734
+ console.error("setAdminSigners err:", err_43);
7103
6735
  }
7104
- throw err_49;
6736
+ throw err_43;
7105
6737
  case 4: return [2];
7106
6738
  }
7107
6739
  });
@@ -7290,7 +6922,7 @@ var PerpetualsClient = (function () {
7290
6922
  });
7291
6923
  }); };
7292
6924
  this.protocolWithdrawFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7293
- var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_50;
6925
+ var publicKey, custodyConfig, receivingTokenAccount, instructions, additionalSigners, withdrawFeesIx, err_44;
7294
6926
  return __generator(this, function (_a) {
7295
6927
  switch (_a.label) {
7296
6928
  case 0:
@@ -7323,9 +6955,9 @@ var PerpetualsClient = (function () {
7323
6955
  instructions.push(withdrawFeesIx);
7324
6956
  return [3, 5];
7325
6957
  case 4:
7326
- err_50 = _a.sent();
7327
- console.log("perpClient setPool error:: ", err_50);
7328
- throw err_50;
6958
+ err_44 = _a.sent();
6959
+ console.log("perpClient setPool error:: ", err_44);
6960
+ throw err_44;
7329
6961
  case 5: return [2, {
7330
6962
  instructions: __spreadArray([], instructions, true),
7331
6963
  additionalSigners: additionalSigners
@@ -7334,7 +6966,7 @@ var PerpetualsClient = (function () {
7334
6966
  });
7335
6967
  }); };
7336
6968
  this.moveProtocolFees = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7337
- var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_51;
6969
+ var publicKey, custodyConfig, instructions, additionalSigners, moveProtocolFeesIx, err_45;
7338
6970
  return __generator(this, function (_a) {
7339
6971
  switch (_a.label) {
7340
6972
  case 0:
@@ -7368,9 +7000,9 @@ var PerpetualsClient = (function () {
7368
7000
  instructions.push(moveProtocolFeesIx);
7369
7001
  return [3, 4];
7370
7002
  case 3:
7371
- err_51 = _a.sent();
7372
- console.log("perpClient setPool error:: ", err_51);
7373
- throw err_51;
7003
+ err_45 = _a.sent();
7004
+ console.log("perpClient setPool error:: ", err_45);
7005
+ throw err_45;
7374
7006
  case 4: return [2, {
7375
7007
  instructions: __spreadArray([], instructions, true),
7376
7008
  additionalSigners: additionalSigners
@@ -7379,7 +7011,7 @@ var PerpetualsClient = (function () {
7379
7011
  });
7380
7012
  }); };
7381
7013
  this.setProtocolFeeShareBps = function (feeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7382
- var publicKey, setProtocolFeeShareBpsIx, err_52;
7014
+ var publicKey, setProtocolFeeShareBpsIx, err_46;
7383
7015
  return __generator(this, function (_a) {
7384
7016
  switch (_a.label) {
7385
7017
  case 0:
@@ -7399,15 +7031,15 @@ var PerpetualsClient = (function () {
7399
7031
  setProtocolFeeShareBpsIx = _a.sent();
7400
7032
  return [2, setProtocolFeeShareBpsIx];
7401
7033
  case 2:
7402
- err_52 = _a.sent();
7403
- console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_52);
7404
- throw err_52;
7034
+ err_46 = _a.sent();
7035
+ console.log("perpClient setProtocolFeeShareBpsIx error:: ", err_46);
7036
+ throw err_46;
7405
7037
  case 3: return [2];
7406
7038
  }
7407
7039
  });
7408
7040
  }); };
7409
7041
  this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
7410
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_53;
7042
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_47;
7411
7043
  return __generator(this, function (_a) {
7412
7044
  switch (_a.label) {
7413
7045
  case 0:
@@ -7434,9 +7066,9 @@ var PerpetualsClient = (function () {
7434
7066
  instructions.push(setPermissionsInstruction);
7435
7067
  return [3, 4];
7436
7068
  case 3:
7437
- err_53 = _a.sent();
7438
- console.log("perpClient setPool error:: ", err_53);
7439
- throw err_53;
7069
+ err_47 = _a.sent();
7070
+ console.log("perpClient setPool error:: ", err_47);
7071
+ throw err_47;
7440
7072
  case 4: return [2, {
7441
7073
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7442
7074
  additionalSigners: additionalSigners
@@ -7445,7 +7077,7 @@ var PerpetualsClient = (function () {
7445
7077
  });
7446
7078
  }); };
7447
7079
  this.reimburse = function (tokenMint, amountIn, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7448
- var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_54;
7080
+ var custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, instructions, additionalSigners, custodyConfig, reimburse, _d, _e, err_48;
7449
7081
  var _f;
7450
7082
  return __generator(this, function (_g) {
7451
7083
  switch (_g.label) {
@@ -7506,9 +7138,9 @@ var PerpetualsClient = (function () {
7506
7138
  instructions.push(reimburse);
7507
7139
  return [3, 5];
7508
7140
  case 4:
7509
- err_54 = _g.sent();
7510
- console.log("perpClient setPool error:: ", err_54);
7511
- throw err_54;
7141
+ err_48 = _g.sent();
7142
+ console.log("perpClient setPool error:: ", err_48);
7143
+ throw err_48;
7512
7144
  case 5: return [2, {
7513
7145
  instructions: __spreadArray([], instructions, true),
7514
7146
  additionalSigners: additionalSigners
@@ -7516,8 +7148,8 @@ var PerpetualsClient = (function () {
7516
7148
  }
7517
7149
  });
7518
7150
  }); };
7519
- this.setInternalOraclePrice = function (tokenMint, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7520
- var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_55;
7151
+ this.setInternalOraclePrice = function (tokenMint, useCurrentTime, price, expo, conf, ema, publishTime, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7152
+ var instructions, additionalSigners, custodyConfig, setInternalOraclePrice, err_49;
7521
7153
  return __generator(this, function (_a) {
7522
7154
  switch (_a.label) {
7523
7155
  case 0:
@@ -7529,6 +7161,7 @@ var PerpetualsClient = (function () {
7529
7161
  _a.trys.push([1, 3, , 4]);
7530
7162
  return [4, this.program.methods
7531
7163
  .setInternalOraclePrice({
7164
+ useCurrentTime: useCurrentTime,
7532
7165
  price: price,
7533
7166
  expo: expo,
7534
7167
  conf: conf,
@@ -7550,9 +7183,9 @@ var PerpetualsClient = (function () {
7550
7183
  instructions.push(setInternalOraclePrice);
7551
7184
  return [3, 4];
7552
7185
  case 3:
7553
- err_55 = _a.sent();
7554
- console.log("perpClient setInternalOracleAccount error:: ", err_55);
7555
- throw err_55;
7186
+ err_49 = _a.sent();
7187
+ console.log("perpClient setInternalOracleAccount error:: ", err_49);
7188
+ throw err_49;
7556
7189
  case 4: return [2, {
7557
7190
  instructions: __spreadArray([], instructions, true),
7558
7191
  additionalSigners: additionalSigners
@@ -7560,8 +7193,8 @@ var PerpetualsClient = (function () {
7560
7193
  }
7561
7194
  });
7562
7195
  }); };
7563
- this.setInternalOraclePriceBatch = function (tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7564
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_56;
7196
+ this.setInternalOraclePriceBatch = function (useCurrentTime, tokenMintList, tokenInternalPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7197
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_1, _i, tokenMintList_1, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_50;
7565
7198
  return __generator(this, function (_a) {
7566
7199
  switch (_a.label) {
7567
7200
  case 0:
@@ -7572,11 +7205,6 @@ var PerpetualsClient = (function () {
7572
7205
  accountMetas = [];
7573
7206
  _loop_1 = function (tokenMint) {
7574
7207
  var custody = ALL_CUSTODY_CONFIGS.find(function (i) { return i.mintKey.equals(tokenMint); });
7575
- accountMetas.push({
7576
- pubkey: custody.custodyAccount,
7577
- isSigner: false,
7578
- isWritable: false,
7579
- });
7580
7208
  accountMetas.push({
7581
7209
  pubkey: custody.intOracleAccount,
7582
7210
  isSigner: false,
@@ -7599,6 +7227,7 @@ var PerpetualsClient = (function () {
7599
7227
  _a.trys.push([1, 3, , 4]);
7600
7228
  return [4, this.program.methods
7601
7229
  .setInternalCurrentPrice({
7230
+ useCurrentTime: useCurrentTime,
7602
7231
  prices: tokenInternalPrices
7603
7232
  })
7604
7233
  .accounts({
@@ -7611,9 +7240,9 @@ var PerpetualsClient = (function () {
7611
7240
  instructions.push(setInternalOraclePrice);
7612
7241
  return [3, 4];
7613
7242
  case 3:
7614
- err_56 = _a.sent();
7615
- console.log("perpClient setInternalOracleAccount error:: ", err_56);
7616
- throw err_56;
7243
+ err_50 = _a.sent();
7244
+ console.log("perpClient setInternalOracleAccount error:: ", err_50);
7245
+ throw err_50;
7617
7246
  case 4: return [2, {
7618
7247
  instructions: __spreadArray([], instructions, true),
7619
7248
  additionalSigners: additionalSigners
@@ -7622,7 +7251,7 @@ var PerpetualsClient = (function () {
7622
7251
  });
7623
7252
  }); };
7624
7253
  this.setInternalOracleEmaPriceBatch = function (tokenMintList, tokenInternalEmaPrices, POOL_CONFIGS) { return __awaiter(_this, void 0, void 0, function () {
7625
- var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_57;
7254
+ var ALL_CUSTODY_CONFIGS, accountMetas, _loop_2, _i, tokenMintList_2, tokenMint, instructions, additionalSigners, setInternalOraclePrice, err_51;
7626
7255
  return __generator(this, function (_a) {
7627
7256
  switch (_a.label) {
7628
7257
  case 0:
@@ -7633,21 +7262,11 @@ var PerpetualsClient = (function () {
7633
7262
  accountMetas = [];
7634
7263
  _loop_2 = function (tokenMint) {
7635
7264
  var custody = ALL_CUSTODY_CONFIGS.find(function (i) { return i.mintKey.equals(tokenMint); });
7636
- accountMetas.push({
7637
- pubkey: custody.custodyAccount,
7638
- isSigner: false,
7639
- isWritable: false,
7640
- });
7641
7265
  accountMetas.push({
7642
7266
  pubkey: custody.intOracleAccount,
7643
7267
  isSigner: false,
7644
7268
  isWritable: true,
7645
7269
  });
7646
- accountMetas.push({
7647
- pubkey: custody.extOracleAccount,
7648
- isSigner: false,
7649
- isWritable: false,
7650
- });
7651
7270
  };
7652
7271
  for (_i = 0, tokenMintList_2 = tokenMintList; _i < tokenMintList_2.length; _i++) {
7653
7272
  tokenMint = tokenMintList_2[_i];
@@ -7672,9 +7291,9 @@ var PerpetualsClient = (function () {
7672
7291
  instructions.push(setInternalOraclePrice);
7673
7292
  return [3, 4];
7674
7293
  case 3:
7675
- err_57 = _a.sent();
7676
- console.log("perpClient setInternalOracleAccount error:: ", err_57);
7677
- throw err_57;
7294
+ err_51 = _a.sent();
7295
+ console.log("perpClient setInternalOracleAccount error:: ", err_51);
7296
+ throw err_51;
7678
7297
  case 4: return [2, {
7679
7298
  instructions: __spreadArray([], instructions, true),
7680
7299
  additionalSigners: additionalSigners
@@ -7683,7 +7302,7 @@ var PerpetualsClient = (function () {
7683
7302
  });
7684
7303
  }); };
7685
7304
  this.renameFlp = function (flag, lpTokenName, lpTokenSymbol, lpTokenUri, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7686
- var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_58;
7305
+ var publicKey, instructions, additionalSigners, lpTokenMint, lpMetadataAccount, renameFlp, err_52;
7687
7306
  return __generator(this, function (_a) {
7688
7307
  switch (_a.label) {
7689
7308
  case 0:
@@ -7721,8 +7340,8 @@ var PerpetualsClient = (function () {
7721
7340
  instructions.push(renameFlp);
7722
7341
  return [3, 4];
7723
7342
  case 3:
7724
- err_58 = _a.sent();
7725
- console.log("perpClient renameFlp error:: ", err_58);
7343
+ err_52 = _a.sent();
7344
+ console.log("perpClient renameFlp error:: ", err_52);
7726
7345
  return [3, 4];
7727
7346
  case 4: return [2, {
7728
7347
  instructions: __spreadArray([], instructions, true),
@@ -7732,7 +7351,7 @@ var PerpetualsClient = (function () {
7732
7351
  });
7733
7352
  }); };
7734
7353
  this.initStake = function (stakingFeeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7735
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_59;
7354
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_53;
7736
7355
  return __generator(this, function (_a) {
7737
7356
  switch (_a.label) {
7738
7357
  case 0:
@@ -7770,9 +7389,9 @@ var PerpetualsClient = (function () {
7770
7389
  instructions.push(initStakeInstruction);
7771
7390
  return [3, 4];
7772
7391
  case 3:
7773
- err_59 = _a.sent();
7774
- console.log("perpClient InitStaking error:: ", err_59);
7775
- throw err_59;
7392
+ err_53 = _a.sent();
7393
+ console.log("perpClient InitStaking error:: ", err_53);
7394
+ throw err_53;
7776
7395
  case 4: return [2, {
7777
7396
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7778
7397
  additionalSigners: additionalSigners
@@ -7781,7 +7400,7 @@ var PerpetualsClient = (function () {
7781
7400
  });
7782
7401
  }); };
7783
7402
  this.initCompounding = function (feeShareBps, metadataTitle, metadataSymbol, metadataUri, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7784
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_60;
7403
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyConfig, compoundingTokenMint, compoundingVault, metadataAccount, initCompoundingInstruction, err_54;
7785
7404
  return __generator(this, function (_a) {
7786
7405
  switch (_a.label) {
7787
7406
  case 0:
@@ -7810,7 +7429,6 @@ var PerpetualsClient = (function () {
7810
7429
  transferAuthority: poolConfig.transferAuthority,
7811
7430
  perpetuals: this.perpetuals.publicKey,
7812
7431
  pool: poolConfig.poolAddress,
7813
- custody: rewardCustodyConfig.custodyAccount,
7814
7432
  lpTokenMint: poolConfig.stakedLpTokenMint,
7815
7433
  compoundingVault: compoundingVault,
7816
7434
  compoundingTokenMint: compoundingTokenMint,
@@ -7826,9 +7444,9 @@ var PerpetualsClient = (function () {
7826
7444
  instructions.push(initCompoundingInstruction);
7827
7445
  return [3, 4];
7828
7446
  case 3:
7829
- err_60 = _a.sent();
7830
- console.log("perpClient initCompounding error:: ", err_60);
7831
- throw err_60;
7447
+ err_54 = _a.sent();
7448
+ console.log("perpClient initCompounding error:: ", err_54);
7449
+ throw err_54;
7832
7450
  case 4: return [2, {
7833
7451
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7834
7452
  additionalSigners: additionalSigners
@@ -7837,7 +7455,7 @@ var PerpetualsClient = (function () {
7837
7455
  });
7838
7456
  }); };
7839
7457
  this.initTokenVault = function (token_permissions, tokens_to_distribute, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7840
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_61;
7458
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenMint, fundingTokenAccount, initTokenVaultInstruction, err_55;
7841
7459
  return __generator(this, function (_a) {
7842
7460
  switch (_a.label) {
7843
7461
  case 0:
@@ -7878,9 +7496,9 @@ var PerpetualsClient = (function () {
7878
7496
  instructions.push(initTokenVaultInstruction);
7879
7497
  return [3, 4];
7880
7498
  case 3:
7881
- err_61 = _a.sent();
7882
- console.log("perpClient InitTokenVaultInstruction error:: ", err_61);
7883
- throw err_61;
7499
+ err_55 = _a.sent();
7500
+ console.log("perpClient InitTokenVaultInstruction error:: ", err_55);
7501
+ throw err_55;
7884
7502
  case 4: return [2, {
7885
7503
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7886
7504
  additionalSigners: additionalSigners
@@ -7889,7 +7507,7 @@ var PerpetualsClient = (function () {
7889
7507
  });
7890
7508
  }); };
7891
7509
  this.setTokenVaultConfig = function (token_permissions, withdrawTimeLimit, withdrawInstantFee, stakeLevel, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7892
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_62;
7510
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setTokenVaultConfigInstruction, err_56;
7893
7511
  return __generator(this, function (_a) {
7894
7512
  switch (_a.label) {
7895
7513
  case 0:
@@ -7920,9 +7538,9 @@ var PerpetualsClient = (function () {
7920
7538
  instructions.push(setTokenVaultConfigInstruction);
7921
7539
  return [3, 4];
7922
7540
  case 3:
7923
- err_62 = _a.sent();
7924
- console.log("perpClient setTokenVaultConfigInstruction error:: ", err_62);
7925
- throw err_62;
7541
+ err_56 = _a.sent();
7542
+ console.log("perpClient setTokenVaultConfigInstruction error:: ", err_56);
7543
+ throw err_56;
7926
7544
  case 4: return [2, {
7927
7545
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7928
7546
  additionalSigners: additionalSigners
@@ -7931,7 +7549,7 @@ var PerpetualsClient = (function () {
7931
7549
  });
7932
7550
  }); };
7933
7551
  this.withdrawInstantFee = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7934
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_63;
7552
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawInstantFeeInstruction, err_57;
7935
7553
  return __generator(this, function (_a) {
7936
7554
  switch (_a.label) {
7937
7555
  case 0:
@@ -7970,9 +7588,59 @@ var PerpetualsClient = (function () {
7970
7588
  instructions.push(withdrawInstantFeeInstruction);
7971
7589
  return [3, 6];
7972
7590
  case 5:
7973
- err_63 = _a.sent();
7974
- console.log("perpClient withdrawInstantFeeInstruction error:: ", err_63);
7975
- throw err_63;
7591
+ err_57 = _a.sent();
7592
+ console.log("perpClient withdrawInstantFeeInstruction error:: ", err_57);
7593
+ throw err_57;
7594
+ case 6: return [2, {
7595
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7596
+ additionalSigners: additionalSigners
7597
+ }];
7598
+ }
7599
+ });
7600
+ }); };
7601
+ this.withdrawUnclaimedTokens = function (poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7602
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, receivingTokenAccount, withdrawUnclaimedTokensInstruction, err_58;
7603
+ return __generator(this, function (_a) {
7604
+ switch (_a.label) {
7605
+ case 0:
7606
+ publicKey = this.provider.wallet.publicKey;
7607
+ preInstructions = [];
7608
+ instructions = [];
7609
+ postInstructions = [];
7610
+ additionalSigners = [];
7611
+ _a.label = 1;
7612
+ case 1:
7613
+ _a.trys.push([1, 5, , 6]);
7614
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.tokenMint, publicKey, true)];
7615
+ case 2:
7616
+ receivingTokenAccount = _a.sent();
7617
+ return [4, (0, utils_1.checkIfAccountExists)(receivingTokenAccount, this.provider.connection)];
7618
+ case 3:
7619
+ if (!(_a.sent())) {
7620
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, receivingTokenAccount, publicKey, poolConfig.tokenMint));
7621
+ }
7622
+ return [4, this.program.methods
7623
+ .withdrawUnclaimedTokens({})
7624
+ .accounts({
7625
+ admin: publicKey,
7626
+ multisig: this.multisig.publicKey,
7627
+ perpetuals: this.perpetuals.publicKey,
7628
+ transferAuthority: poolConfig.transferAuthority,
7629
+ tokenVault: poolConfig.tokenVault,
7630
+ tokenVaultTokenAccount: poolConfig.tokenVaultTokenAccount,
7631
+ receivingTokenAccount: receivingTokenAccount,
7632
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7633
+ receivingTokenMint: poolConfig.tokenMint,
7634
+ })
7635
+ .instruction()];
7636
+ case 4:
7637
+ withdrawUnclaimedTokensInstruction = _a.sent();
7638
+ instructions.push(withdrawUnclaimedTokensInstruction);
7639
+ return [3, 6];
7640
+ case 5:
7641
+ err_58 = _a.sent();
7642
+ console.log("perpClient withdrawUnclaimedTokensInstruction error:: ", err_58);
7643
+ throw err_58;
7976
7644
  case 6: return [2, {
7977
7645
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7978
7646
  additionalSigners: additionalSigners
@@ -7981,7 +7649,7 @@ var PerpetualsClient = (function () {
7981
7649
  });
7982
7650
  }); };
7983
7651
  this.initRevenueTokenAccount = function (feeShareBps, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7984
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_64;
7652
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, initRevenueTokenAccountInstruction, err_59;
7985
7653
  return __generator(this, function (_a) {
7986
7654
  switch (_a.label) {
7987
7655
  case 0:
@@ -8018,9 +7686,55 @@ var PerpetualsClient = (function () {
8018
7686
  instructions.push(initRevenueTokenAccountInstruction);
8019
7687
  return [3, 4];
8020
7688
  case 3:
8021
- err_64 = _a.sent();
8022
- console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_64);
8023
- throw err_64;
7689
+ err_59 = _a.sent();
7690
+ console.log("perpClient initRevenueTokenAccountInstruction error:: ", err_59);
7691
+ throw err_59;
7692
+ case 4: return [2, {
7693
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7694
+ additionalSigners: additionalSigners
7695
+ }];
7696
+ }
7697
+ });
7698
+ }); };
7699
+ this.initRebateVault = function (allowRebatePayout, rebateSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
7700
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rebateCustodyMint, initRebateVaultInstruction, err_60;
7701
+ return __generator(this, function (_a) {
7702
+ switch (_a.label) {
7703
+ case 0:
7704
+ publicKey = this.provider.wallet.publicKey;
7705
+ preInstructions = [];
7706
+ instructions = [];
7707
+ postInstructions = [];
7708
+ additionalSigners = [];
7709
+ _a.label = 1;
7710
+ case 1:
7711
+ _a.trys.push([1, 3, , 4]);
7712
+ rebateCustodyMint = poolConfig.getTokenFromSymbol(rebateSymbol).mintKey;
7713
+ return [4, this.program.methods
7714
+ .initRebateVault({
7715
+ allowRebatePayout: allowRebatePayout
7716
+ })
7717
+ .accounts({
7718
+ admin: publicKey,
7719
+ multisig: this.multisig.publicKey,
7720
+ transferAuthority: poolConfig.transferAuthority,
7721
+ perpetuals: this.perpetuals.publicKey,
7722
+ rebateMint: rebateCustodyMint,
7723
+ rebateTokenAccount: poolConfig.rebateTokenAccount,
7724
+ rebateVault: poolConfig.rebateVault,
7725
+ systemProgram: web3_js_1.SystemProgram.programId,
7726
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
7727
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
7728
+ })
7729
+ .instruction()];
7730
+ case 2:
7731
+ initRebateVaultInstruction = _a.sent();
7732
+ instructions.push(initRebateVaultInstruction);
7733
+ return [3, 4];
7734
+ case 3:
7735
+ err_60 = _a.sent();
7736
+ console.log("perpClient initRebateVaultInstruction error:: ", err_60);
7737
+ throw err_60;
8024
7738
  case 4: return [2, {
8025
7739
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8026
7740
  additionalSigners: additionalSigners
@@ -8029,7 +7743,7 @@ var PerpetualsClient = (function () {
8029
7743
  });
8030
7744
  }); };
8031
7745
  this.distributeTokenReward = function (amount, epochCount, rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8032
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_65;
7746
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, fundingTokenAccount, revenueFundingTokenAccount, distributeTokenRewardInstruction, err_61;
8033
7747
  return __generator(this, function (_a) {
8034
7748
  switch (_a.label) {
8035
7749
  case 0:
@@ -8068,9 +7782,9 @@ var PerpetualsClient = (function () {
8068
7782
  instructions.push(distributeTokenRewardInstruction);
8069
7783
  return [3, 4];
8070
7784
  case 3:
8071
- err_65 = _a.sent();
8072
- console.log("perpClient distributeTokenRewardInstruction error:: ", err_65);
8073
- throw err_65;
7785
+ err_61 = _a.sent();
7786
+ console.log("perpClient distributeTokenRewardInstruction error:: ", err_61);
7787
+ throw err_61;
8074
7788
  case 4: return [2, {
8075
7789
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8076
7790
  additionalSigners: additionalSigners
@@ -8079,7 +7793,7 @@ var PerpetualsClient = (function () {
8079
7793
  });
8080
7794
  }); };
8081
7795
  this.setTokenStakeLevel = function (owner, stakeLevel) { return __awaiter(_this, void 0, void 0, function () {
8082
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_66;
7796
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenStakeLevelInstruction, err_62;
8083
7797
  return __generator(this, function (_a) {
8084
7798
  switch (_a.label) {
8085
7799
  case 0:
@@ -8107,9 +7821,9 @@ var PerpetualsClient = (function () {
8107
7821
  instructions.push(setTokenStakeLevelInstruction);
8108
7822
  return [3, 4];
8109
7823
  case 3:
8110
- err_66 = _a.sent();
8111
- console.log("perpClient setTokenStakeLevelInstruction error:: ", err_66);
8112
- throw err_66;
7824
+ err_62 = _a.sent();
7825
+ console.log("perpClient setTokenStakeLevelInstruction error:: ", err_62);
7826
+ throw err_62;
8113
7827
  case 4: return [2, {
8114
7828
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8115
7829
  additionalSigners: additionalSigners
@@ -8118,7 +7832,7 @@ var PerpetualsClient = (function () {
8118
7832
  });
8119
7833
  }); };
8120
7834
  this.setTokenReward = function (owner, amount, epochCount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
8121
- var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_67;
7835
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, tokenStakeAccount, setTokenRewardInstruction, err_63;
8122
7836
  return __generator(this, function (_a) {
8123
7837
  switch (_a.label) {
8124
7838
  case 0:
@@ -8150,9 +7864,49 @@ var PerpetualsClient = (function () {
8150
7864
  instructions.push(setTokenRewardInstruction);
8151
7865
  return [3, 4];
8152
7866
  case 3:
8153
- err_67 = _a.sent();
8154
- console.log("perpClient setTokenRewardInstruction error:: ", err_67);
8155
- throw err_67;
7867
+ err_63 = _a.sent();
7868
+ console.log("perpClient setTokenRewardInstruction error:: ", err_63);
7869
+ throw err_63;
7870
+ case 4: return [2, {
7871
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
7872
+ additionalSigners: additionalSigners
7873
+ }];
7874
+ }
7875
+ });
7876
+ }); };
7877
+ this.resizeInternalOracle = function (extOracle, tokenMint, intOracleAccount) { return __awaiter(_this, void 0, void 0, function () {
7878
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, resizeInternalOracleInstruction, err_64;
7879
+ return __generator(this, function (_a) {
7880
+ switch (_a.label) {
7881
+ case 0:
7882
+ publicKey = this.provider.wallet.publicKey;
7883
+ preInstructions = [];
7884
+ instructions = [];
7885
+ postInstructions = [];
7886
+ additionalSigners = [];
7887
+ _a.label = 1;
7888
+ case 1:
7889
+ _a.trys.push([1, 3, , 4]);
7890
+ return [4, this.program.methods
7891
+ .resizeInternalOracle({
7892
+ extOracle: extOracle
7893
+ })
7894
+ .accounts({
7895
+ admin: publicKey,
7896
+ multisig: this.multisig.publicKey,
7897
+ custodyTokenMint: tokenMint,
7898
+ intOracleAccount: intOracleAccount,
7899
+ systemProgram: web3_js_1.SystemProgram.programId,
7900
+ })
7901
+ .instruction()];
7902
+ case 2:
7903
+ resizeInternalOracleInstruction = _a.sent();
7904
+ instructions.push(resizeInternalOracleInstruction);
7905
+ return [3, 4];
7906
+ case 3:
7907
+ err_64 = _a.sent();
7908
+ console.log("perpClient resizeInternalOracleInstruction error:: ", err_64);
7909
+ throw err_64;
8156
7910
  case 4: return [2, {
8157
7911
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
8158
7912
  additionalSigners: additionalSigners
@@ -8230,13 +7984,13 @@ var PerpetualsClient = (function () {
8230
7984
  PerpetualsClient.prototype.getPriceAfterSlippage = function (isEntry, slippageBps, targetPrice, side) {
8231
7985
  if (isEntry) {
8232
7986
  var currentPrice = targetPrice.price;
8233
- var slippage = (0, utils_1.checkedDecimalCeilMul)(currentPrice, targetPrice.exponent, slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), targetPrice.exponent);
7987
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(currentPrice, targetPrice.exponent, slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), targetPrice.exponent);
8234
7988
  if ((0, types_1.isVariant)(side, 'long')) {
8235
- return { price: currentPrice.add(slippage), exponent: targetPrice.exponent.toNumber() };
7989
+ return { price: currentPrice.add(spread_i), exponent: targetPrice.exponent.toNumber() };
8236
7990
  }
8237
7991
  else {
8238
- if (slippage.lt(currentPrice)) {
8239
- return { price: currentPrice.sub(slippage), exponent: targetPrice.exponent.toNumber() };
7992
+ if (spread_i.lt(currentPrice)) {
7993
+ return { price: currentPrice.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
8240
7994
  }
8241
7995
  else {
8242
7996
  return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
@@ -8246,10 +8000,10 @@ var PerpetualsClient = (function () {
8246
8000
  }
8247
8001
  else {
8248
8002
  var current_price = targetPrice.price;
8249
- var slippage = (0, utils_1.checkedDecimalCeilMul)(current_price, targetPrice.exponent, slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), targetPrice.exponent);
8003
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, targetPrice.exponent, slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), targetPrice.exponent);
8250
8004
  if ((0, types_1.isVariant)(side, 'long')) {
8251
- if (slippage.lt(current_price)) {
8252
- return { price: current_price.sub(slippage), exponent: targetPrice.exponent.toNumber() };
8005
+ if (spread_i.lt(current_price)) {
8006
+ return { price: current_price.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
8253
8007
  }
8254
8008
  else {
8255
8009
  return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
@@ -8257,7 +8011,7 @@ var PerpetualsClient = (function () {
8257
8011
  ;
8258
8012
  }
8259
8013
  else {
8260
- return { price: current_price.add(slippage), exponent: targetPrice.exponent.toNumber() };
8014
+ return { price: current_price.add(spread_i), exponent: targetPrice.exponent.toNumber() };
8261
8015
  }
8262
8016
  }
8263
8017
  };