flash-sdk 1.0.134 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -74,6 +74,7 @@ var rpc_1 = require("./utils/rpc");
74
74
  var utils_1 = require("./utils");
75
75
  var constants_1 = require("./constants");
76
76
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
77
+ var getNftAccounts_1 = require("./utils/getNftAccounts");
77
78
  var PerpetualsClient = (function () {
78
79
  function PerpetualsClient(provider, programId, composabilityProgramId, opts) {
79
80
  var _this = this;
@@ -249,34 +250,28 @@ var PerpetualsClient = (function () {
249
250
  return [2, this.program.account.multisig.fetch(this.multisig.publicKey)];
250
251
  });
251
252
  }); };
252
- this.getPositionKey = function (wallet, poolName, tokenMint, side) {
253
- var pool = _this.getPoolKey(poolName);
254
- var custody = _this.getCustodyKey(poolName, tokenMint);
255
- return _this.findProgramAddress("position", [
256
- wallet,
257
- pool,
258
- custody,
259
- side === "long" ? [1] : [2],
260
- ]).publicKey;
261
- };
262
253
  this.getPosition = function (postionKey) { return __awaiter(_this, void 0, void 0, function () {
263
254
  return __generator(this, function (_a) {
264
255
  return [2, this.program.account.position.fetch(postionKey)];
265
256
  });
266
257
  }); };
267
- this.getUserPosition = function (wallet, poolName, tokenMint, side) { return __awaiter(_this, void 0, void 0, function () {
258
+ this.getUserPosition = function (owner, targetCustody, collateralCustody, side) { return __awaiter(_this, void 0, void 0, function () {
268
259
  return __generator(this, function (_a) {
269
- return [2, this.program.account.position.fetch(this.getPositionKey(wallet, poolName, tokenMint, side))];
260
+ return [2, this.program.account.position.fetch(this.getPositionKey(owner, targetCustody, collateralCustody, side))];
270
261
  });
271
262
  }); };
272
263
  this.getUserPositions = function (wallet, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
273
- var positionKeys, positionsDatas;
264
+ var marketAccountsPks, positionKeys, positionsDatas;
274
265
  var _this = this;
275
266
  var _a;
276
267
  return __generator(this, function (_b) {
277
268
  switch (_b.label) {
278
269
  case 0:
279
- positionKeys = __spreadArray(__spreadArray([], poolConfig.getNonStableTokens().map(function (mint) { return _this.getPositionKey(wallet, poolConfig.poolName, mint, 'long'); }), true), poolConfig.getNonStableTokens().map(function (mint) { return _this.getPositionKey(wallet, poolConfig.poolName, mint, 'short'); }), true);
270
+ marketAccountsPks = poolConfig.getAllMarketPks();
271
+ positionKeys = marketAccountsPks.map(function (f) { return _this.findProgramAddress("position", [
272
+ wallet,
273
+ f
274
+ ]); }).map(function (p) { return p.publicKey; });
280
275
  return [4, this.provider.connection.getMultipleAccountsInfo(positionKeys)];
281
276
  case 1:
282
277
  positionsDatas = (_a = (_b.sent())) !== null && _a !== void 0 ? _a : [];
@@ -405,11 +400,18 @@ var PerpetualsClient = (function () {
405
400
  }
406
401
  });
407
402
  }); };
408
- this.addPool = function (name) { return __awaiter(_this, void 0, void 0, function () {
403
+ this.addPool = function (name, maxAumUsd, permissions, metadataSymbol, metadataTitle, metadataUri) { return __awaiter(_this, void 0, void 0, function () {
409
404
  return __generator(this, function (_a) {
410
405
  switch (_a.label) {
411
406
  case 0: return [4, this.program.methods
412
- .addPool({ name: name })
407
+ .addPool({
408
+ name: name,
409
+ maxAumUsd: maxAumUsd,
410
+ permissions: permissions,
411
+ metadataSymbol: metadataSymbol,
412
+ metadataTitle: metadataTitle,
413
+ metadataUri: metadataUri
414
+ })
413
415
  .accounts({
414
416
  admin: this.provider.wallet.publicKey,
415
417
  multisig: this.multisig.publicKey,
@@ -456,7 +458,7 @@ var PerpetualsClient = (function () {
456
458
  }
457
459
  });
458
460
  }); };
459
- this.addCustody = function (poolName, tokenMint, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios) { return __awaiter(_this, void 0, void 0, function () {
461
+ this.addCustody = function (poolName, tokenMint, isStable, isVirtual, oracle, pricing, permissions, fees, borrowRate, ratios, depegAdjustment) { return __awaiter(_this, void 0, void 0, function () {
460
462
  var trx_id, error_1;
461
463
  return __generator(this, function (_a) {
462
464
  switch (_a.label) {
@@ -472,6 +474,7 @@ var PerpetualsClient = (function () {
472
474
  fees: fees,
473
475
  borrowRate: borrowRate,
474
476
  ratios: ratios,
477
+ depegAdjustment: depegAdjustment
475
478
  })
476
479
  .accounts({
477
480
  admin: this.admin,
@@ -570,28 +573,28 @@ var PerpetualsClient = (function () {
570
573
  });
571
574
  }); };
572
575
  this.getLiquidationState = function (wallet, poolName, tokenMint, collateralMint, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
573
- var _a, _b;
576
+ var targetCustody, collateralCustody, _a, _b;
574
577
  var _c;
575
578
  return __generator(this, function (_d) {
576
579
  switch (_d.label) {
577
580
  case 0:
581
+ targetCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
582
+ collateralCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
578
583
  _b = (_a = this.program.methods
579
584
  .getLiquidationState({}))
580
585
  .accounts;
581
586
  _c = {
582
587
  perpetuals: this.perpetuals.publicKey,
583
588
  pool: this.getPoolKey(poolName),
584
- position: this.getPositionKey(wallet, poolName, tokenMint, side),
585
- custody: this.getCustodyKey(poolName, tokenMint)
589
+ position: this.getPositionKey(wallet, targetCustody, collateralCustody, side),
590
+ targetCustody: this.getCustodyKey(poolName, tokenMint)
586
591
  };
587
592
  return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
588
593
  case 1:
589
- _c.custodyOracleAccount = _d.sent(),
590
- _c.custodyCustomOracleAccount = poolConfig.backupOracle,
591
- _c.collateralCustody = this.getCustodyKey(poolName, collateralMint),
592
- _c.collateralCustodyCustomOracleAccount = poolConfig.backupOracle;
594
+ _c.targetOracleAccount = _d.sent(),
595
+ _c.collateralCustody = this.getCustodyKey(poolName, collateralMint);
593
596
  return [4, this.getCustodyOracleAccountKey(poolName, collateralMint)];
594
- case 2: return [4, _b.apply(_a, [(_c.collateralCustodyOracleAccount = _d.sent(),
597
+ case 2: return [4, _b.apply(_a, [(_c.collateralOracleAccount = _d.sent(),
595
598
  _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
596
599
  _c)])
597
600
  .view()
@@ -603,69 +606,34 @@ var PerpetualsClient = (function () {
603
606
  }
604
607
  });
605
608
  }); };
606
- this.validateCollectivePnl = function (marketSymbol, collateralSymbol, poolConfig, poolName, side) { return __awaiter(_this, void 0, void 0, function () {
607
- var marketCustodyConfig, collateralCustodyConfig;
608
- return __generator(this, function (_a) {
609
- switch (_a.label) {
610
- case 0:
611
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
612
- collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
613
- return [4, this.program.methods
614
- .validateCollectivePnl({ side: side })
615
- .accounts({
616
- perpetuals: this.perpetuals.publicKey,
617
- pool: this.getPoolKey(poolName),
618
- custody: marketCustodyConfig.custodyAccount,
619
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
620
- custodyCustomOracleAccount: poolConfig.backupOracle,
621
- collateralCustody: collateralCustodyConfig.custodyAccount,
622
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
623
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
624
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
625
- })
626
- .remainingAccounts([])
627
- .rpc()
628
- .catch(function (err) {
629
- console.error(err);
630
- throw err;
631
- })];
632
- case 1:
633
- _a.sent();
634
- return [2];
635
- }
636
- });
637
- }); };
638
- this.liquidate = function (wallet, poolConfig, tokenMint, collateralMint, side, receivingAccount, rewardsReceivingAccount) { return __awaiter(_this, void 0, void 0, function () {
639
- var poolName, _a, _b;
609
+ this.liquidate = function (wallet, poolConfig, tokenMint, collateralMint, side) { return __awaiter(_this, void 0, void 0, function () {
610
+ var poolName, market, targetCustody, collateralCustody, _a, _b;
640
611
  var _c;
641
612
  return __generator(this, function (_d) {
642
613
  switch (_d.label) {
643
614
  case 0:
644
615
  poolName = poolConfig.poolName;
616
+ market = poolConfig.getMarketPk(this.getCustodyKey(poolName, tokenMint), this.getCustodyKey(poolName, collateralMint), side === 'long' ? types_1.Side.Long : types_1.Side.Short);
617
+ targetCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
618
+ collateralCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
645
619
  _b = (_a = this.program.methods
646
620
  .liquidate({}))
647
621
  .accounts;
648
622
  _c = {
649
623
  signer: this.provider.wallet.publicKey,
650
- receivingAccount: receivingAccount,
651
- rewardsReceivingAccount: rewardsReceivingAccount,
652
- transferAuthority: this.authority.publicKey,
653
624
  perpetuals: this.perpetuals.publicKey,
654
625
  pool: this.getPoolKey(poolName),
655
- position: this.getPositionKey(wallet, poolName, tokenMint, side),
656
- custody: this.getCustodyKey(poolName, tokenMint)
626
+ position: this.getPositionKey(wallet, targetCustody, collateralCustody, side),
627
+ market: market,
628
+ targetCustody: this.getCustodyKey(poolName, tokenMint)
657
629
  };
658
630
  return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
659
631
  case 1:
660
- _c.custodyOracleAccount = _d.sent(),
632
+ _c.targetOracleAccount = _d.sent(),
661
633
  _c.collateralCustody = this.getCustodyKey(poolName, collateralMint);
662
634
  return [4, this.getCustodyOracleAccountKey(poolName, collateralMint)];
663
- case 2: return [4, _b.apply(_a, [(_c.collateralCustodyOracleAccount = _d.sent(),
664
- _c.collateralCustodyTokenAccount = this.getCustodyTokenAccountKey(poolName, collateralMint),
665
- _c.collateralCustodyCustomOracleAccount = poolConfig.backupOracle,
666
- _c.custodyCustomOracleAccount = poolConfig.backupOracle,
635
+ case 2: return [4, _b.apply(_a, [(_c.collateralOracleAccount = _d.sent(),
667
636
  _c.eventAuthority = this.eventAuthority.publicKey,
668
- _c.tokenProgram = spl_token_1.TOKEN_PROGRAM_ID,
669
637
  _c.program = this.program.programId,
670
638
  _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
671
639
  _c)])
@@ -775,12 +743,15 @@ var PerpetualsClient = (function () {
775
743
  }
776
744
  });
777
745
  }); };
778
- this.getEntryPriceAndFeeView = function (poolName, tokenMint, collateral, size, side) { return __awaiter(_this, void 0, void 0, function () {
779
- var _a, _b;
746
+ this.getEntryPriceAndFeeView = function (tokenMint, collateralMint, collateral, size, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
747
+ var targetCustody, collateralCustody, market, _a, _b;
780
748
  var _c;
781
749
  return __generator(this, function (_d) {
782
750
  switch (_d.label) {
783
751
  case 0:
752
+ targetCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
753
+ collateralCustody = this.getCustodyKey(poolConfig.poolName, collateralMint);
754
+ market = poolConfig.getMarketPk(targetCustody, collateralCustody, side === 'long' ? types_1.Side.Long : types_1.Side.Short);
784
755
  _b = (_a = this.program.methods
785
756
  .getEntryPriceAndFee({
786
757
  collateral: collateral,
@@ -790,11 +761,16 @@ var PerpetualsClient = (function () {
790
761
  .accounts;
791
762
  _c = {
792
763
  perpetuals: this.perpetuals.publicKey,
793
- pool: this.getPoolKey(poolName),
794
- custody: this.getCustodyKey(poolName, tokenMint)
764
+ pool: poolConfig.poolAddress,
765
+ targetCustody: targetCustody
795
766
  };
796
- return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
797
- case 1: return [4, _b.apply(_a, [(_c.custodyOracleAccount = _d.sent(),
767
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, tokenMint)];
768
+ case 1:
769
+ _c.targetOracleAccount = _d.sent(),
770
+ _c.collateralCustody = collateralCustody;
771
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, collateralMint)];
772
+ case 2: return [4, _b.apply(_a, [(_c.collateralOracleAccount = _d.sent(),
773
+ _c.market = market,
798
774
  _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
799
775
  _c)])
800
776
  .view()
@@ -802,27 +778,35 @@ var PerpetualsClient = (function () {
802
778
  console.error(err);
803
779
  throw err;
804
780
  })];
805
- case 2: return [2, _d.sent()];
781
+ case 3: return [2, _d.sent()];
806
782
  }
807
783
  });
808
784
  }); };
809
- this.getExitPriceAndFeeView = function (wallet, poolName, tokenMint, side) { return __awaiter(_this, void 0, void 0, function () {
810
- var _a, _b;
785
+ this.getExitPriceAndFeeView = function (wallet, tokenMint, collateralMint, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
786
+ var targetCustody, collateralCustody, market, _a, _b;
811
787
  var _c;
812
788
  return __generator(this, function (_d) {
813
789
  switch (_d.label) {
814
790
  case 0:
791
+ targetCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
792
+ collateralCustody = this.getCustodyKey(poolConfig.poolName, collateralMint);
793
+ market = poolConfig.getMarketPk(targetCustody, collateralCustody, side === 'long' ? types_1.Side.Long : types_1.Side.Short);
815
794
  _b = (_a = this.program.methods
816
795
  .getExitPriceAndFee({}))
817
796
  .accounts;
818
797
  _c = {
819
798
  perpetuals: this.perpetuals.publicKey,
820
- pool: this.getPoolKey(poolName),
821
- position: this.getPositionKey(wallet, poolName, tokenMint, side),
822
- custody: this.getCustodyKey(poolName, tokenMint)
799
+ pool: poolConfig.poolAddress,
800
+ position: this.getPositionKey(wallet, targetCustody, collateralCustody, side),
801
+ targetCustody: this.getCustodyKey(poolConfig.poolName, tokenMint)
823
802
  };
824
- return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
825
- case 1: return [4, _b.apply(_a, [(_c.custodyOracleAccount = _d.sent(),
803
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, tokenMint)];
804
+ case 1:
805
+ _c.targetOracleAccount = _d.sent(),
806
+ _c.collateralCustody = this.getCustodyKey(poolConfig.poolName, collateralMint);
807
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, collateralMint)];
808
+ case 2: return [4, _b.apply(_a, [(_c.collateralOracleAccount = _d.sent(),
809
+ _c.market = market,
826
810
  _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
827
811
  _c)])
828
812
  .view()
@@ -830,63 +814,35 @@ var PerpetualsClient = (function () {
830
814
  console.error(err);
831
815
  throw err;
832
816
  })];
833
- case 2: return [2, _d.sent()];
817
+ case 3: return [2, _d.sent()];
834
818
  }
835
819
  });
836
820
  }); };
837
- this.getLiquidationPriceView = function (wallet, poolName, tokenMint, side, addCollateral, removeCollateral) {
838
- if (addCollateral === void 0) { addCollateral = new anchor_1.BN(0); }
839
- if (removeCollateral === void 0) { removeCollateral = new anchor_1.BN(0); }
840
- return __awaiter(_this, void 0, void 0, function () {
841
- var _a, _b;
842
- var _c;
843
- return __generator(this, function (_d) {
844
- switch (_d.label) {
845
- case 0:
846
- _b = (_a = this.program.methods
847
- .getLiquidationPrice({
848
- addCollateralDelta: addCollateral,
849
- removeCollateralDelta: removeCollateral,
850
- }))
851
- .accounts;
852
- _c = {
853
- perpetuals: this.perpetuals.publicKey,
854
- pool: this.getPoolKey(poolName),
855
- position: this.getPositionKey(wallet, poolName, tokenMint, side),
856
- custody: this.getCustodyKey(poolName, tokenMint)
857
- };
858
- return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
859
- case 1: return [4, _b.apply(_a, [(_c.custodyOracleAccount = _d.sent(),
860
- _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
861
- _c)])
862
- .view()
863
- .catch(function (err) {
864
- console.error(err);
865
- throw err;
866
- })];
867
- case 2: return [2, _d.sent()];
868
- }
869
- });
870
- });
871
- };
872
- this.getPnlView = function (wallet, poolName, tokenMint, side) { return __awaiter(_this, void 0, void 0, function () {
873
- var pos, _a, _b;
821
+ this.getPnlView = function (wallet, tokenMint, collateralMint, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
822
+ var targetCustody, collateralCustody, market, pos, _a, _b;
874
823
  var _c;
875
824
  return __generator(this, function (_d) {
876
825
  switch (_d.label) {
877
826
  case 0:
878
- pos = this.getPositionKey(wallet, poolName, tokenMint, side);
827
+ targetCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
828
+ collateralCustody = this.getCustodyKey(poolConfig.poolName, collateralMint);
829
+ market = poolConfig.getMarketPk(targetCustody, collateralCustody, side === 'long' ? types_1.Side.Long : types_1.Side.Short);
830
+ pos = this.getPositionKey(wallet, targetCustody, collateralCustody, side);
879
831
  _b = (_a = this.program.methods
880
832
  .getPnl({}))
881
833
  .accounts;
882
834
  _c = {
883
835
  perpetuals: this.perpetuals.publicKey,
884
- pool: this.getPoolKey(poolName),
836
+ pool: poolConfig.poolAddress,
885
837
  position: pos,
886
- custody: this.getCustodyKey(poolName, tokenMint)
838
+ targetCustody: this.getCustodyKey(poolConfig.poolName, tokenMint)
887
839
  };
888
- return [4, this.getCustodyOracleAccountKey(poolName, tokenMint)];
889
- case 1: return [4, _b.apply(_a, [(_c.custodyOracleAccount = _d.sent(),
840
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, tokenMint)];
841
+ case 1:
842
+ _c.custodyOracleAccount = _d.sent(),
843
+ _c.collateralCustody = this.getCustodyKey(poolConfig.poolName, tokenMint);
844
+ return [4, this.getCustodyOracleAccountKey(poolConfig.poolName, collateralMint)];
845
+ case 2: return [4, _b.apply(_a, [(_c.collateralOracleAccount = _d.sent(),
890
846
  _c.ixSysvar = web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
891
847
  _c)])
892
848
  .view()
@@ -894,11 +850,11 @@ var PerpetualsClient = (function () {
894
850
  console.error(err);
895
851
  throw err;
896
852
  })];
897
- case 2: return [2, _d.sent()];
853
+ case 3: return [2, _d.sent()];
898
854
  }
899
855
  });
900
856
  }); };
901
- this.getSwapAmountAndFeesView = function (poolName, tokenMintIn, tokenMintOut, amountIn) { return __awaiter(_this, void 0, void 0, function () {
857
+ this.getSwapAmountAndFeesView = function (poolName, tokenMintIn, tokenMintOut, amountIn, useFeePool) { return __awaiter(_this, void 0, void 0, function () {
902
858
  var _a, _b;
903
859
  var _c;
904
860
  return __generator(this, function (_d) {
@@ -907,6 +863,7 @@ var PerpetualsClient = (function () {
907
863
  _b = (_a = this.program.methods
908
864
  .getSwapAmountAndFees({
909
865
  amountIn: amountIn,
866
+ useFeePool: useFeePool
910
867
  }))
911
868
  .accounts;
912
869
  _c = {
@@ -1053,47 +1010,64 @@ var PerpetualsClient = (function () {
1053
1010
  return { feeBps: fee, feeAmount: feeAmount };
1054
1011
  };
1055
1012
  this.getMinAndMaxOraclePriceSync = function (price, emaPrice, custodyAccount) {
1056
- var minPrice = price;
1057
- var deviation;
1013
+ var maxPriceUsd = price.scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1014
+ var minPriceUsd = maxPriceUsd.scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1015
+ var divergenceBps;
1058
1016
  if (custodyAccount.isStable) {
1059
- deviation = price.getDeviationFactor(OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(10).pow(price.exponent.abs()), exponent: price.exponent, confidence: price.confidence, timestamp: price.timestamp }));
1017
+ divergenceBps = maxPriceUsd.getDeviationFactor(OraclePrice_1.OraclePrice.from({
1018
+ price: new anchor_1.BN(10).pow(maxPriceUsd.exponent.abs()),
1019
+ exponent: maxPriceUsd.exponent,
1020
+ confidence: maxPriceUsd.confidence,
1021
+ timestamp: maxPriceUsd.timestamp
1022
+ }));
1060
1023
  }
1061
1024
  else {
1062
- deviation = price.getDeviationFactor(emaPrice);
1063
- }
1064
- if (deviation.gte(custodyAccount.oracle.maxDeviationThreshold)) {
1065
- var confFactor = (price.confidence.muln(constants_1.BPS_POWER)).div(price.price);
1066
- if (confFactor.lt(custodyAccount.oracle.maxPriceError)) {
1067
- minPrice.price = price.price.sub(price.confidence);
1025
+ var emaPriceInPriceDecimals = emaPrice.scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1026
+ divergenceBps = maxPriceUsd.getDeviationFactor(emaPriceInPriceDecimals);
1027
+ }
1028
+ if (divergenceBps.gte(custodyAccount.oracle.maxDivergenceBps)) {
1029
+ var factorBps = (divergenceBps.mul(new anchor_1.BN(constants_1.BPS_POWER))).div(custodyAccount.oracle.maxDivergenceBps);
1030
+ var confBps = (maxPriceUsd.confidence.muln(constants_1.BPS_POWER)).div(maxPriceUsd.price);
1031
+ if (confBps.lt(custodyAccount.oracle.maxConfBps)) {
1032
+ var confFactor = anchor_1.BN.min(factorBps, new anchor_1.BN(50000));
1033
+ var confScale = (maxPriceUsd.confidence.mul(confFactor)).div(new anchor_1.BN(constants_1.BPS_POWER));
1034
+ minPriceUsd.price = maxPriceUsd.price.sub(confScale);
1035
+ return {
1036
+ min: minPriceUsd,
1037
+ max: maxPriceUsd
1038
+ };
1068
1039
  }
1069
1040
  else {
1070
- minPrice.price = price.price.sub(price.confidence);
1041
+ minPriceUsd.price = maxPriceUsd.price.sub(maxPriceUsd.confidence);
1042
+ return {
1043
+ min: minPriceUsd,
1044
+ max: maxPriceUsd
1045
+ };
1071
1046
  }
1072
1047
  }
1073
1048
  else {
1074
1049
  return {
1075
- min: price,
1076
- max: price
1050
+ min: maxPriceUsd,
1051
+ max: maxPriceUsd
1077
1052
  };
1078
1053
  }
1079
- return {
1080
- min: minPrice,
1081
- max: price
1082
- };
1083
1054
  };
1084
1055
  this.getMinAndMaxPriceSync = function (price, emaPrice, custodyAccount) {
1085
1056
  var minPrice = price;
1086
- var deviation;
1057
+ var divergenceBps;
1087
1058
  if (custodyAccount.isStable) {
1088
- deviation = price.getDeviationFactor(OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(10).pow(price.exponent.abs()), exponent: price.exponent, confidence: price.confidence, timestamp: price.timestamp }));
1059
+ divergenceBps = price.getDeviationFactor(OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(10).pow(price.exponent.abs()), exponent: price.exponent, confidence: price.confidence, timestamp: price.timestamp }));
1089
1060
  }
1090
1061
  else {
1091
- deviation = price.getDeviationFactor(emaPrice);
1062
+ divergenceBps = price.getDeviationFactor(emaPrice);
1092
1063
  }
1093
- if (deviation.gte(custodyAccount.oracle.maxDeviationThreshold)) {
1094
- var confFactor = (price.confidence.muln(constants_1.BPS_POWER)).div(price.price);
1095
- if (confFactor.lt(custodyAccount.oracle.maxPriceError)) {
1096
- minPrice.price = price.price.sub(price.confidence);
1064
+ if (divergenceBps.gte(custodyAccount.oracle.maxDivergenceBps)) {
1065
+ var factorBps = (divergenceBps.mul(new anchor_1.BN(constants_1.BPS_POWER))).div(custodyAccount.oracle.maxDivergenceBps);
1066
+ var confBps = (price.confidence.muln(constants_1.BPS_POWER)).div(price.price);
1067
+ if (confBps.lt(custodyAccount.oracle.maxConfBps)) {
1068
+ var confFactor = anchor_1.BN.min(factorBps, new anchor_1.BN(50000));
1069
+ var confScale = (price.confidence.mul(confFactor)).div(new anchor_1.BN(constants_1.BPS_POWER));
1070
+ minPrice.price = price.price.sub(confScale);
1097
1071
  }
1098
1072
  else {
1099
1073
  minPrice.price = price.price.sub(price.confidence);
@@ -1101,13 +1075,13 @@ var PerpetualsClient = (function () {
1101
1075
  }
1102
1076
  else {
1103
1077
  return {
1104
- min: price.scale_to_exponent(new anchor_1.BN(constants_1.PRICE_DECIMALS).neg()).price,
1105
- max: price.scale_to_exponent(new anchor_1.BN(constants_1.PRICE_DECIMALS).neg()).price
1078
+ min: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price,
1079
+ max: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price
1106
1080
  };
1107
1081
  }
1108
1082
  return {
1109
- min: minPrice.scale_to_exponent(new anchor_1.BN(constants_1.PRICE_DECIMALS).neg()).price,
1110
- max: price.scale_to_exponent(new anchor_1.BN(constants_1.PRICE_DECIMALS).neg()).price
1083
+ min: minPrice.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price,
1084
+ max: price.scale_to_exponent(new anchor_1.BN(constants_1.USD_DECIMALS).neg()).price
1111
1085
  };
1112
1086
  };
1113
1087
  this.checkIfPriceStaleOrCustom = function (price, emaPrice, custodyAccount, timestampInSeconds) {
@@ -1124,9 +1098,9 @@ var PerpetualsClient = (function () {
1124
1098
  else {
1125
1099
  deviation = price.getDeviationFactor(emaPrice);
1126
1100
  }
1127
- if (deviation.gte(custodyAccount.oracle.maxDeviationThreshold)) {
1101
+ if (deviation.gte(custodyAccount.oracle.maxDivergenceBps)) {
1128
1102
  var confFactor = (price.confidence.muln(constants_1.BPS_POWER)).div(price.price);
1129
- if (confFactor.lt(custodyAccount.oracle.maxPriceError)) {
1103
+ if (confFactor.lt(custodyAccount.oracle.maxConfBps)) {
1130
1104
  return false;
1131
1105
  }
1132
1106
  else {
@@ -1153,7 +1127,7 @@ var PerpetualsClient = (function () {
1153
1127
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
1154
1128
  }
1155
1129
  };
1156
- this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig, pnlUsd) {
1130
+ this.getLeverageAtAmountEntryWithSwapSync = function (positionAccount, inputDeltaAmount, sizeDeltaAmount, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, poolAumUsdMax, poolConfig, pnlUsd) {
1157
1131
  var finalCollateralAmount = constants_1.BN_ZERO;
1158
1132
  if (!inputDeltaAmount.isZero()) {
1159
1133
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
@@ -1164,12 +1138,12 @@ var PerpetualsClient = (function () {
1164
1138
  finalCollateralAmount = swapAmountOut;
1165
1139
  }
1166
1140
  }
1167
- var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1141
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount);
1168
1142
  var openFeeUsd = constants_1.BN_ZERO;
1169
1143
  if (sizeDeltaAmount != constants_1.BN_ZERO) {
1170
- var newEntryPriceOracle = new OraclePrice_1.OraclePrice({ price: entryPriceBN, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: marketTokenPrice.confidence, timestamp: marketTokenPrice.timestamp });
1171
- var sizeDeltaUsd = newEntryPriceOracle.getAssetAmountUsd(sizeDeltaAmount, marketTokenCustodyAccount.decimals);
1172
- openFeeUsd = sizeDeltaUsd.mul(marketTokenCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1144
+ var newEntryPriceOracle = new OraclePrice_1.OraclePrice({ price: entryPriceUsdBN, exponent: new anchor_1.BN(constants_1.USD_DECIMALS).neg(), confidence: targetTokenPrice.confidence, timestamp: targetTokenPrice.timestamp });
1145
+ var sizeDeltaUsd = newEntryPriceOracle.getAssetAmountUsd(sizeDeltaAmount, targetTokenCustodyAccount.decimals);
1146
+ openFeeUsd = sizeDeltaUsd.mul(targetTokenCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1173
1147
  }
1174
1148
  if (positionAccount === null) {
1175
1149
  var data = __assign({}, types_1.DEFAULT_POSITION);
@@ -1177,15 +1151,22 @@ var PerpetualsClient = (function () {
1177
1151
  }
1178
1152
  else {
1179
1153
  positionAccount = positionAccount.clone();
1180
- entryPriceBN = _this.getAveragePriceSync(positionAccount.price, positionAccount.sizeAmount, entryPriceBN, sizeDeltaAmount);
1154
+ var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1155
+ price: positionAccount.entryPrice.price,
1156
+ exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
1157
+ confidence: constants_1.BN_ZERO,
1158
+ timestamp: constants_1.BN_ZERO
1159
+ })
1160
+ .scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1161
+ entryPriceUsdBN = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryPriceUsdBN, sizeDeltaAmount);
1181
1162
  }
1182
1163
  var collateralMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1183
1164
  var collateralAmount = positionAccount.collateralAmount.add(finalCollateralAmount);
1184
1165
  var currentCollateralUsd = collateralMinOraclePrice.getAssetAmountUsd(collateralAmount, collateralTokenCustodyAccount.decimals);
1185
1166
  var currentCollateralUsdIncludingPnl = currentCollateralUsd.add(pnlUsd).sub(openFeeUsd);
1186
1167
  var sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1187
- var entryOraclePrice = new OraclePrice_1.OraclePrice({ price: entryPriceBN, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: marketTokenPrice.confidence, timestamp: marketTokenPrice.timestamp });
1188
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, marketTokenCustodyAccount.decimals);
1168
+ var entryOraclePrice = new OraclePrice_1.OraclePrice({ price: entryPriceUsdBN, exponent: new anchor_1.BN(constants_1.USD_DECIMALS).neg(), confidence: targetTokenPrice.confidence, timestamp: targetTokenPrice.timestamp });
1169
+ var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeAmount, targetTokenCustodyAccount.decimals);
1189
1170
  if (currentCollateralUsdIncludingPnl.gt(constants_1.BN_ZERO)) {
1190
1171
  return sizeAmountUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentCollateralUsdIncludingPnl);
1191
1172
  }
@@ -1193,99 +1174,168 @@ var PerpetualsClient = (function () {
1193
1174
  return new anchor_1.BN(Number.MAX_SAFE_INTEGER);
1194
1175
  }
1195
1176
  };
1196
- this.getEntryPriceAndFeeSync = function (positionAccount, collateralDeltaAmount, sizeDeltaAmount, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1177
+ this.getEntryPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
1178
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1197
1179
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1198
1180
  throw new Error("Delta Amounts cannot be negative.");
1199
1181
  }
1200
- var entryPriceBN = _this.getEntryPriceSync(side, marketPrice, marketEmaPrice, marketCustodyAccount);
1182
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount);
1183
+ var oracleEntryPrice = OraclePrice_1.OraclePrice.from({ price: entryPriceUsdBN, exponent: new anchor_1.BN(-1 * constants_1.USD_DECIMALS), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1201
1184
  if (positionAccount === null) {
1202
1185
  var data = __assign({}, types_1.DEFAULT_POSITION);
1203
1186
  positionAccount = PositionAccount_1.PositionAccount.from(web3_js_1.PublicKey.default, data);
1187
+ var sizeUsd = oracleEntryPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
1188
+ positionAccount.sizeUsd = sizeUsd;
1189
+ positionAccount.sizeDecimals = targetCustodyAccount.decimals;
1190
+ positionAccount.collateralDecimals = collateralCustodyAccount.decimals;
1191
+ positionAccount.lockedDecimals = collateralCustodyAccount.decimals;
1204
1192
  }
1205
1193
  else {
1206
1194
  positionAccount = positionAccount.clone();
1207
- entryPriceBN = _this.getAveragePriceSync(positionAccount.price, positionAccount.sizeAmount, entryPriceBN, sizeDeltaAmount);
1195
+ var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1196
+ price: positionAccount.entryPrice.price,
1197
+ exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
1198
+ confidence: constants_1.BN_ZERO,
1199
+ timestamp: constants_1.BN_ZERO
1200
+ })
1201
+ .scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1202
+ entryPriceUsdBN = _this.getAveragePriceSync(positionEntryPrice.price, positionAccount.sizeAmount, entryPriceUsdBN, sizeDeltaAmount);
1203
+ var sizeDeltaUsd = oracleEntryPrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
1204
+ positionAccount.sizeUsd = positionAccount.sizeUsd.add(sizeDeltaUsd);
1208
1205
  }
1209
1206
  positionAccount.collateralAmount = positionAccount.collateralAmount.add(collateralDeltaAmount);
1210
1207
  positionAccount.sizeAmount = positionAccount.sizeAmount.add(sizeDeltaAmount);
1211
- var interestAmountUsd = _this.getInterestAmountUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1212
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryPriceBN, interestAmountUsd, positionAccount.unrealizedLossUsd, side, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1213
- var entryOraclePrice = new OraclePrice_1.OraclePrice({ price: entryPriceBN, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: marketPrice.confidence, timestamp: marketPrice.timestamp });
1214
- var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, marketCustodyAccount.decimals);
1208
+ var lockFeeUsd = _this.getLockFeeUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1209
+ var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, entryPriceUsdBN, lockFeeUsd, positionAccount.unsettledFeesUsd, marketCorrelation, side, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
1210
+ var entryOraclePrice = new OraclePrice_1.OraclePrice({ price: entryPriceUsdBN, exponent: new anchor_1.BN(constants_1.USD_DECIMALS).neg(), confidence: targetPrice.confidence, timestamp: targetPrice.timestamp });
1211
+ var sizeAmountUsd = entryOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
1215
1212
  var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1216
1213
  var feeUsd = constants_1.BN_ZERO;
1217
1214
  var feeAmount = constants_1.BN_ZERO;
1215
+ var feeUsdAfterDiscount = constants_1.BN_ZERO;
1216
+ var feeAmountAfterDiscount = constants_1.BN_ZERO;
1218
1217
  if (positionAccount !== null && sizeDeltaAmount.isZero()) {
1219
1218
  }
1220
1219
  else {
1221
- feeUsd = sizeAmountUsd.mul(marketCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1220
+ feeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.openPosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1222
1221
  feeAmount = feeUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
1222
+ if (discountBps.gt(constants_1.BN_ZERO)) {
1223
+ feeUsdAfterDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
1224
+ feeUsdAfterDiscount = feeUsd.sub(feeUsdAfterDiscount);
1225
+ feeAmountAfterDiscount = feeUsdAfterDiscount.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
1226
+ }
1227
+ else {
1228
+ feeUsdAfterDiscount = feeUsd;
1229
+ feeAmountAfterDiscount = feeAmount;
1230
+ }
1223
1231
  }
1224
1232
  return {
1225
- entryPrice: entryPriceBN,
1233
+ entryPrice: entryPriceUsdBN,
1226
1234
  feeUsd: feeUsd,
1227
1235
  feeAmount: feeAmount,
1236
+ feeUsdAfterDiscount: feeUsdAfterDiscount,
1237
+ feeAmountAfterDiscount: feeAmountAfterDiscount,
1228
1238
  liquidationPrice: liquidationPrice
1229
1239
  };
1230
1240
  };
1231
- this.getEntryPriceSync = function (side, marketPrice, marketEmaPrice, marketCustodyAccount) {
1232
- var _a = _this.getMinAndMaxPriceSync(marketPrice, marketEmaPrice, marketCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
1233
- var entryPriceBN = side ===
1234
- types_1.Side.Long ?
1235
- maxPrice.add(maxPrice.mul(marketCustodyAccount.pricing.tradeSpreadLong).div(new anchor_1.BN(constants_1.BPS_POWER))) :
1236
- minPrice.sub(minPrice.mul(marketCustodyAccount.pricing.tradeSpreadShort).div(new anchor_1.BN(constants_1.BPS_POWER)));
1241
+ this.getEntryPriceUsdSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
1242
+ var _a = _this.getMinAndMaxPriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
1243
+ var entryPriceBN = (0, types_1.isVariant)(side, 'long') === types_1.Side.Long ?
1244
+ maxPrice.add(maxPrice.mul(targetCustodyAccount.pricing.tradeSpreadLong).div(new anchor_1.BN(constants_1.BPS_POWER))) :
1245
+ minPrice.sub(minPrice.mul(targetCustodyAccount.pricing.tradeSpreadShort).div(new anchor_1.BN(constants_1.BPS_POWER)));
1237
1246
  return entryPriceBN;
1238
1247
  };
1239
- this.getExitPriceAndFeeSync = function (positionAccount, collateralDeltaAmount, sizeDeltaAmount, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1240
- positionAccount = positionAccount.clone();
1248
+ this.getExitFeeSync = function (positionAccount, targetCustody, collateralCustodyAccount, collateralPrice, collateralEmaPrice) {
1249
+ var exitFeeUsd = positionAccount.sizeUsd.mul(targetCustody.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1250
+ var collateralTokenMinOraclePrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1251
+ var exitFeeAmount = collateralTokenMinOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
1252
+ return {
1253
+ exitFeeAmount: exitFeeAmount,
1254
+ exitFeeUsd: exitFeeUsd
1255
+ };
1256
+ };
1257
+ this.getExitPriceAndFeeSync = function (positionAccount, marketCorrelation, collateralDeltaAmount, sizeDeltaAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, discountBps) {
1258
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1259
+ var resultingPositionAccount = positionAccount.clone();
1241
1260
  if (collateralDeltaAmount.isNeg() || sizeDeltaAmount.isNeg()) {
1242
1261
  throw new Error("Delta Amounts cannot be negative ");
1243
1262
  }
1244
- positionAccount.collateralAmount = positionAccount.collateralAmount.sub(collateralDeltaAmount);
1245
- positionAccount.sizeAmount = positionAccount.sizeAmount.sub(sizeDeltaAmount);
1246
- if (positionAccount.collateralAmount.isNeg() || positionAccount.sizeAmount.isNeg()) {
1263
+ resultingPositionAccount.collateralAmount = resultingPositionAccount.collateralAmount.sub(collateralDeltaAmount);
1264
+ resultingPositionAccount.sizeAmount = resultingPositionAccount.sizeAmount.sub(sizeDeltaAmount);
1265
+ if (resultingPositionAccount.collateralAmount.isNeg() || resultingPositionAccount.sizeAmount.isNeg()) {
1247
1266
  throw new Error("cannot remove/close more than collateral/Size");
1248
1267
  }
1249
- var exitPriceBN = _this.getExitPriceSync(side, marketPrice, marketEmaPrice, marketCustodyAccount);
1268
+ var exitOraclePrice = _this.getExitOraclePriceSync(side, targetPrice, targetEmaPrice, targetCustodyAccount);
1250
1269
  var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralTokenMinOraclePrice = _a.min, collateralTokenMaxOraclePrice = _a.max;
1251
- var interestAmountUsd = _this.getInterestAmountUsdForPosition(positionAccount, collateralCustodyAccount, currentTimestamp);
1252
- var interestAmount = interestAmountUsd.mul(new anchor_1.BN(Math.pow(10, collateralCustodyAccount.decimals))).div(collateralTokenMinOraclePrice.price);
1253
- var exitOraclePrice = new OraclePrice_1.OraclePrice({ price: exitPriceBN, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: marketPrice.confidence, timestamp: marketPrice.timestamp });
1254
- var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, marketCustodyAccount.decimals);
1255
- var feeUsd = sizeAmountUsd.mul(marketCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1256
- var feeAmount = collateralTokenMaxOraclePrice.getTokenAmount(feeUsd, collateralCustodyAccount.decimals);
1257
- var liquidationPrice = _this.getLiquidationPriceSync(positionAccount.collateralAmount, positionAccount.sizeAmount, exitPriceBN, interestAmountUsd, positionAccount.unrealizedLossUsd, side, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1270
+ var lockFeeUsd = _this.getLockFeeUsdForPosition(resultingPositionAccount, collateralCustodyAccount, currentTimestamp);
1271
+ var lockFee = collateralTokenMinOraclePrice.getTokenAmount(lockFeeUsd, collateralCustodyAccount.decimals);
1272
+ var sizeAmountUsd = exitOraclePrice.getAssetAmountUsd(sizeDeltaAmount, targetCustodyAccount.decimals);
1273
+ var exitFeeUsd = sizeAmountUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1274
+ var exitFeeAmount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsd, collateralCustodyAccount.decimals);
1275
+ var exitFeeUsdAfterDiscount = constants_1.BN_ZERO;
1276
+ var exitFeeAmountAfterDiscount = constants_1.BN_ZERO;
1277
+ if (discountBps.gt(constants_1.BN_ZERO)) {
1278
+ exitFeeUsdAfterDiscount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
1279
+ exitFeeUsdAfterDiscount = exitFeeUsd.sub(exitFeeUsdAfterDiscount);
1280
+ exitFeeAmountAfterDiscount = collateralTokenMaxOraclePrice.getTokenAmount(exitFeeUsdAfterDiscount, collateralCustodyAccount.decimals);
1281
+ }
1282
+ else {
1283
+ exitFeeUsdAfterDiscount = exitFeeUsd;
1284
+ exitFeeAmountAfterDiscount = exitFeeAmount;
1285
+ }
1286
+ var positionEntryOraclePrice = new OraclePrice_1.OraclePrice({
1287
+ price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
1288
+ }).scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1289
+ var positionEntryPriceUsd = positionEntryOraclePrice.price;
1290
+ resultingPositionAccount.sizeUsd = positionEntryOraclePrice.getAssetAmountUsd(resultingPositionAccount.sizeAmount, targetCustodyAccount.decimals);
1291
+ var liquidationPrice = _this.getLiquidationPriceSync(resultingPositionAccount.collateralAmount, resultingPositionAccount.sizeAmount, positionEntryPriceUsd, lockFeeUsd, resultingPositionAccount.unsettledFeesUsd, marketCorrelation, side, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount);
1258
1292
  return {
1259
- exitPrice: exitPriceBN,
1260
- borrowFeeUsd: interestAmountUsd,
1261
- borrowFeeAmount: interestAmount,
1262
- exitFeeUsd: feeUsd,
1263
- exitFeeAmount: feeAmount,
1293
+ exitPrice: exitOraclePrice.scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS)).price,
1294
+ borrowFeeUsd: lockFeeUsd,
1295
+ borrowFeeAmount: lockFee,
1296
+ exitFeeUsd: exitFeeUsd,
1297
+ exitFeeAmount: exitFeeAmount,
1298
+ exitFeeUsdAfterDiscount: exitFeeUsdAfterDiscount,
1299
+ exitFeeAmountAfterDiscount: exitFeeAmountAfterDiscount,
1264
1300
  liquidationPrice: liquidationPrice
1265
1301
  };
1266
1302
  };
1267
- this.getExitPriceSync = function (side, marketPrice, marketEmaPrice, marketCustodyAccount) {
1268
- var _a = _this.getMinAndMaxPriceSync(marketPrice, marketEmaPrice, marketCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
1269
- var exitPriceBN = side ===
1270
- types_1.Side.Long ?
1271
- minPrice.sub(minPrice.mul(marketCustodyAccount.pricing.tradeSpreadShort).div(new anchor_1.BN(constants_1.BPS_POWER))) :
1272
- maxPrice.add(maxPrice.mul(marketCustodyAccount.pricing.tradeSpreadLong).div(new anchor_1.BN(constants_1.BPS_POWER)));
1303
+ this.getExitPriceSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
1304
+ var _a = _this.getMinAndMaxPriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
1305
+ var exitPriceBN = (0, types_1.isVariant)(side, 'long') ?
1306
+ minPrice.sub(minPrice.mul(targetCustodyAccount.pricing.tradeSpreadShort).div(new anchor_1.BN(constants_1.BPS_POWER))) :
1307
+ maxPrice.add(maxPrice.mul(targetCustodyAccount.pricing.tradeSpreadLong).div(new anchor_1.BN(constants_1.BPS_POWER)));
1273
1308
  return exitPriceBN;
1274
1309
  };
1275
- this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1310
+ this.getExitOraclePriceSync = function (side, targetPrice, targetEmaPrice, targetCustodyAccount) {
1311
+ var _a = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount), minPrice = _a.min, maxPrice = _a.max;
1312
+ if ((0, types_1.isVariant)(side, 'long')) {
1313
+ return minPrice;
1314
+ }
1315
+ else {
1316
+ return maxPrice;
1317
+ }
1318
+ };
1319
+ this.getSizeAmountFromLeverageAndCollateral = function (collateralAmtWithFee, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
1320
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1276
1321
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1277
- var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1278
- var entryPriceBN = _this.getEntryPriceSync(side, marketPrice, marketEmaPrice, marketCustodyAccount);
1279
- var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1322
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1323
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount);
1324
+ var entryPriceUsdUi = new bignumber_js_1.default(entryPriceUsdBN.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1280
1325
  var collateralAmtMinUsdUi = new bignumber_js_1.default(collateralAmtWithFee.toString()).dividedBy(Math.pow(10, collateralToken.decimals))
1281
1326
  .multipliedBy(collateralTokenMinPriceUi);
1282
- var openPosFeeRateUi = new bignumber_js_1.default(marketCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1327
+ var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1328
+ if (!discountBps.isZero()) {
1329
+ var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
1330
+ openPosFeeRateUi = openPosFeeRateUi.multipliedBy(new bignumber_js_1.default(1).minus(discountBpsUi));
1331
+ }
1283
1332
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
1284
1333
  .dividedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage)));
1285
- var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1334
+ var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
1286
1335
  return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketToken.decimals, bignumber_js_1.default.ROUND_DOWN), marketToken.decimals);
1287
1336
  };
1288
- this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1337
+ this.getSizeAmountWithSwapSync = function (amountIn, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, poolAumUsdMax, poolConfig, discountBps) {
1338
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1289
1339
  var finalCollateralAmount = constants_1.BN_ZERO;
1290
1340
  if (inputTokenCustodyAccount.publicKey.equals(collateralTokenCustodyAccount.publicKey)) {
1291
1341
  finalCollateralAmount = amountIn;
@@ -1296,37 +1346,46 @@ var PerpetualsClient = (function () {
1296
1346
  finalCollateralAmount = swapAmountOut;
1297
1347
  }
1298
1348
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1299
- var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1300
- var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1301
- var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1349
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1350
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount);
1351
+ var entryPriceUsdUi = new bignumber_js_1.default(entryPriceUsdBN.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1302
1352
  var collateralAmtMinUsdUi = new bignumber_js_1.default(finalCollateralAmount.toString()).dividedBy(Math.pow(10, collateralTokenCustodyAccount.decimals))
1303
1353
  .multipliedBy(collateralTokenMinPriceUi);
1304
- var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1354
+ var openPosFeeRateUi = new bignumber_js_1.default(targetTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1355
+ if (!discountBps.isZero()) {
1356
+ var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
1357
+ openPosFeeRateUi = openPosFeeRateUi.multipliedBy(new bignumber_js_1.default(1).minus(discountBpsUi));
1358
+ }
1305
1359
  var sizeUsdUi = collateralAmtMinUsdUi.multipliedBy(leverage)
1306
1360
  .dividedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage)));
1307
- var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUi);
1308
- return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(marketTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), marketTokenCustodyAccount.decimals);
1361
+ var sizeAmountUi = sizeUsdUi.dividedBy(entryPriceUsdUi);
1362
+ return (0, utils_1.uiDecimalsToNative)(sizeAmountUi.toFixed(targetTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), targetTokenCustodyAccount.decimals);
1309
1363
  };
1310
- this.getCollateralAmountWithFeeFromLeverageAndSize = function (sizeAmount, leverage, marketToken, collateralToken, side, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1364
+ this.getCollateralAmountWithFeeFromLeverageAndSize = function (sizeAmount, leverage, marketToken, collateralToken, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, discountBps) {
1365
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1311
1366
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1312
- var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1313
- var entryPriceBN = _this.getEntryPriceSync(side, marketPrice, marketEmaPrice, marketCustodyAccount);
1314
- var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1315
- var openPosFeeRateUi = new bignumber_js_1.default(marketCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1367
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1368
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, targetCustodyAccount);
1369
+ var entryPriceUsdUi = new bignumber_js_1.default(entryPriceUsdBN.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1370
+ var openPosFeeRateUi = new bignumber_js_1.default(targetCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1371
+ if (!discountBps.isZero()) {
1372
+ var discountBpsUi = new bignumber_js_1.default(discountBps.toString()).dividedBy(Math.pow(10, constants_1.BPS_DECIMALS));
1373
+ openPosFeeRateUi = openPosFeeRateUi.multipliedBy(new bignumber_js_1.default(1).minus(discountBpsUi));
1374
+ }
1316
1375
  var sizeAmountUi = new bignumber_js_1.default(sizeAmount.toString()).dividedBy(Math.pow(10, marketToken.decimals));
1317
- var sizeUsdUi = entryPriceUi.multipliedBy(sizeAmountUi);
1376
+ var sizeUsdUi = entryPriceUsdUi.multipliedBy(sizeAmountUi);
1318
1377
  var collateralWithFeeUsdUi = sizeUsdUi.multipliedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage))).dividedBy(leverage);
1319
1378
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1320
1379
  return (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralToken.decimals, bignumber_js_1.default.ROUND_DOWN), collateralToken.decimals);
1321
1380
  };
1322
- this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1381
+ this.getCollateralAmountWithSwapSync = function (sizeAmount, leverage, side, poolAccount, inputTokenPrice, inputTokenEmaPrice, inputTokenCustodyAccount, collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount, poolAumUsdMax, poolConfig) {
1323
1382
  var collateralTokenMinPrice = _this.getMinAndMaxPriceSync(collateralTokenPrice, collateralTokenEmaPrice, collateralTokenCustodyAccount).min;
1324
- var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1325
- var entryPriceBN = _this.getEntryPriceSync(side, marketTokenPrice, marketTokenEmaPrice, marketTokenCustodyAccount);
1326
- var entryPriceUi = new bignumber_js_1.default(entryPriceBN.toString()).dividedBy(Math.pow(10, constants_1.PRICE_DECIMALS));
1327
- var openPosFeeRateUi = new bignumber_js_1.default(marketTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1328
- var sizeAmountUi = new bignumber_js_1.default(sizeAmount.toString()).dividedBy(Math.pow(10, marketTokenCustodyAccount.decimals));
1329
- var sizeUsdUi = entryPriceUi.multipliedBy(sizeAmountUi);
1383
+ var collateralTokenMinPriceUi = new bignumber_js_1.default(collateralTokenMinPrice.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1384
+ var entryPriceUsdBN = _this.getEntryPriceUsdSync(side, targetTokenPrice, targetTokenEmaPrice, targetTokenCustodyAccount);
1385
+ var entryPriceUsdUi = new bignumber_js_1.default(entryPriceUsdBN.toString()).dividedBy(Math.pow(10, constants_1.USD_DECIMALS));
1386
+ var openPosFeeRateUi = new bignumber_js_1.default(targetTokenCustodyAccount.fees.openPosition.toString()).dividedBy(Math.pow(10, constants_1.RATE_DECIMALS));
1387
+ var sizeAmountUi = new bignumber_js_1.default(sizeAmount.toString()).dividedBy(Math.pow(10, targetTokenCustodyAccount.decimals));
1388
+ var sizeUsdUi = entryPriceUsdUi.multipliedBy(sizeAmountUi);
1330
1389
  var collateralWithFeeUsdUi = sizeUsdUi.multipliedBy(new bignumber_js_1.default(1).plus(openPosFeeRateUi.multipliedBy(leverage))).dividedBy(leverage);
1331
1390
  var collateralAmtWithFeeUi = collateralWithFeeUsdUi.dividedBy(collateralTokenMinPriceUi);
1332
1391
  var collateralAmountWithFee = (0, utils_1.uiDecimalsToNative)(collateralAmtWithFeeUi.toFixed(collateralTokenCustodyAccount.decimals, bignumber_js_1.default.ROUND_DOWN), collateralTokenCustodyAccount.decimals);
@@ -1340,56 +1399,76 @@ var PerpetualsClient = (function () {
1340
1399
  }
1341
1400
  return collateralInInputToken;
1342
1401
  };
1343
- this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, sizeDeltaUsd, keepLevSame, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1344
- if (!marketCustodyAccount.publicKey.equals(positionAccount.custody)) {
1402
+ this.getDecreaseSizeCollateralAndFeeSync = function (positionAccount, marketCorrelation, sizeDeltaUsd, keepLevSame, targetPrice, targetEmaPrice, marketConfig, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, side, poolConfig, discountBps) {
1403
+ if (discountBps === void 0) { discountBps = constants_1.BN_ZERO; }
1404
+ if (!marketConfig.marketAccount.equals(positionAccount.market)) {
1405
+ throw new Error("marketCustodyAccount mismatch");
1406
+ }
1407
+ if (!targetCustodyAccount.publicKey.equals(marketConfig.targetCustody)) {
1345
1408
  throw new Error("marketCustodyAccount mismatch");
1346
1409
  }
1347
- if (!collateralCustodyAccount.publicKey.equals(positionAccount.collateralCustody)) {
1410
+ if (!collateralCustodyAccount.publicKey.equals(marketConfig.collateralCustody)) {
1348
1411
  throw new Error("collateralCustodyAccount mismatch");
1349
1412
  }
1350
1413
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1351
- var marketMinMaxPrice = _this.getMinAndMaxOraclePriceSync(marketPrice, marketEmaPrice, marketCustodyAccount);
1414
+ var marketMinMaxPrice = _this.getMinAndMaxOraclePriceSync(targetPrice, targetEmaPrice, targetCustodyAccount);
1352
1415
  var positionDelta = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1353
- var sizeDeltaAmount = marketMinMaxPrice.max.getTokenAmount(sizeDeltaUsd, marketCustodyAccount.decimals);
1416
+ var positionEntryOraclePrice = new OraclePrice_1.OraclePrice({
1417
+ price: positionAccount.entryPrice.price, exponent: new anchor_1.BN(positionAccount.entryPrice.exponent), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO
1418
+ });
1419
+ var sizeDeltaAmount = positionEntryOraclePrice.getTokenAmount(sizeDeltaUsd, targetCustodyAccount.decimals);
1354
1420
  positionDelta.sizeAmount = sizeDeltaAmount;
1355
- var decimalPower = new anchor_1.BN(Math.pow(10, marketCustodyAccount.decimals));
1421
+ var decimalPower = new anchor_1.BN(Math.pow(10, targetCustodyAccount.decimals));
1356
1422
  var closeRatio = (positionDelta.sizeAmount.mul(decimalPower)).div(positionAccount.sizeAmount);
1357
1423
  positionDelta.sizeUsd = (positionAccount.sizeUsd.mul(closeRatio)).div(decimalPower);
1358
- positionDelta.borrowSizeUsd = (positionAccount.borrowSizeUsd.mul(closeRatio)).div(decimalPower);
1359
- positionDelta.unrealizedLossUsd = (positionAccount.unrealizedLossUsd.mul(closeRatio)).div(decimalPower);
1424
+ positionDelta.unsettledFeesUsd = (positionAccount.unsettledFeesUsd.mul(closeRatio)).div(decimalPower);
1360
1425
  positionDelta.lockedAmount = (positionAccount.lockedAmount.mul(closeRatio)).div(decimalPower);
1426
+ positionDelta.lockedUsd = (positionAccount.lockedUsd.mul(closeRatio)).div(decimalPower);
1361
1427
  positionDelta.collateralAmount = (positionAccount.collateralAmount.mul(closeRatio)).div(decimalPower);
1362
- var newPnl = _this.getPnlSync(positionDelta, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1428
+ var newPnl = _this.getPnlSync(positionDelta, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1429
+ var exitFeeUsd = positionDelta.sizeUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1430
+ if (discountBps.gt(constants_1.BN_ZERO)) {
1431
+ var discount = exitFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
1432
+ exitFeeUsd = exitFeeUsd.sub(discount);
1433
+ }
1434
+ var lockFeeUsd = _this.getLockFeeUsdForPosition(positionDelta, collateralCustodyAccount, currentTimestamp);
1435
+ var unsettledFeesUsd = (exitFeeUsd.add(lockFeeUsd)).add(positionDelta.unsettledFeesUsd);
1363
1436
  var currentCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(positionDelta.collateralAmount, collateralCustodyAccount.decimals);
1364
- var availableAmountUsd;
1365
- if (newPnl.profitUsd.gt(constants_1.BN_ZERO)) {
1366
- availableAmountUsd = currentCollateralUsd.add(newPnl.profitUsd);
1367
- }
1368
- else if (newPnl.lossUsd.lt(currentCollateralUsd)) {
1369
- availableAmountUsd = currentCollateralUsd.sub(newPnl.lossUsd);
1437
+ var liabilityUsd = newPnl.lossUsd.add(unsettledFeesUsd);
1438
+ var assetsUsd = newPnl.profitUsd.add(currentCollateralUsd);
1439
+ var closeAmount, feesAmount;
1440
+ if (assetsUsd.gte(liabilityUsd)) {
1441
+ closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), collateralCustodyAccount.decimals);
1442
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(unsettledFeesUsd, collateralCustodyAccount.decimals);
1370
1443
  }
1371
1444
  else {
1372
- availableAmountUsd = constants_1.BN_ZERO;
1445
+ closeAmount = constants_1.BN_ZERO;
1446
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), collateralCustodyAccount.decimals);
1373
1447
  }
1374
- var closeAmount = collateralMinMaxPrice.max.getTokenAmount(availableAmountUsd, collateralCustodyAccount.decimals);
1375
- var maxAmount = (positionDelta.lockedAmount.sub(newPnl.exitFeeAmount.add(newPnl.borrowFeeAmount))).add(positionDelta.collateralAmount);
1376
- closeAmount = anchor_1.BN.min(closeAmount, maxAmount);
1377
1448
  var newPosition = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1378
1449
  newPosition.sizeAmount = positionAccount.sizeAmount.sub(positionDelta.sizeAmount);
1379
1450
  newPosition.sizeUsd = positionAccount.sizeUsd.sub(positionDelta.sizeUsd);
1380
- newPosition.borrowSizeUsd = positionAccount.borrowSizeUsd.sub(positionDelta.borrowSizeUsd);
1451
+ newPosition.lockedUsd = positionAccount.lockedUsd.sub(positionDelta.lockedUsd);
1381
1452
  newPosition.lockedAmount = positionAccount.lockedAmount.sub(positionDelta.lockedAmount);
1382
- newPosition.unrealizedLossUsd = positionAccount.unrealizedLossUsd.sub(positionDelta.unrealizedLossUsd);
1453
+ newPosition.unsettledFeesUsd = positionAccount.unsettledFeesUsd.sub(positionDelta.unsettledFeesUsd);
1383
1454
  newPosition.collateralAmount = positionAccount.collateralAmount.sub(positionDelta.collateralAmount).add(closeAmount);
1384
1455
  newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1385
- var feeUsd = sizeDeltaUsd.mul(marketCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1456
+ var feeUsdWithDiscount = constants_1.BN_ZERO;
1457
+ var feeUsd = sizeDeltaUsd.mul(targetCustodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1458
+ if (discountBps.gt(constants_1.BN_ZERO)) {
1459
+ feeUsdWithDiscount = feeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
1460
+ feeUsdWithDiscount = exitFeeUsd.sub(feeUsdWithDiscount);
1461
+ }
1462
+ else {
1463
+ feeUsdWithDiscount = feeUsd;
1464
+ }
1386
1465
  if (keepLevSame) {
1387
- var previousPnl = _this.getPnlSync(positionAccount, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1466
+ var previousPnl = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1388
1467
  var pnlUsd = previousPnl.profitUsd.sub(previousPnl.lossUsd);
1389
1468
  var currentlev = _this.getLeverageSync(positionAccount.sizeUsd, positionAccount.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, pnlUsd);
1390
1469
  var collateralAmountRecievedUsd = newPosition.collateralUsd.sub(newPosition.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(currentlev));
1391
1470
  var collateralAmountReceived = collateralMinMaxPrice.max.getTokenAmount(collateralAmountRecievedUsd, collateralCustodyAccount.decimals);
1392
- var maxWithdrawableAmount = _this.getMaxWithdrawableAmountSync(newPosition, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1471
+ var maxWithdrawableAmount = _this.getMaxWithdrawableAmountSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig);
1393
1472
  if (collateralAmountReceived.lt(constants_1.BN_ZERO)) {
1394
1473
  collateralAmountReceived = constants_1.BN_ZERO;
1395
1474
  collateralAmountRecievedUsd = constants_1.BN_ZERO;
@@ -1398,17 +1477,22 @@ var PerpetualsClient = (function () {
1398
1477
  collateralAmountReceived = maxWithdrawableAmount;
1399
1478
  collateralAmountRecievedUsd = collateralMinMaxPrice.min.getAssetAmountUsd(maxWithdrawableAmount, collateralCustodyAccount.decimals);
1400
1479
  }
1401
- var collateralFeeUsd = collateralAmountRecievedUsd.mul(marketCustodyAccount.fees.removeCollateral).div(new anchor_1.BN(constants_1.RATE_POWER));
1480
+ var collateralFeeUsd = collateralAmountRecievedUsd.mul(targetCustodyAccount.fees.removeCollateral).div(new anchor_1.BN(constants_1.RATE_POWER));
1481
+ if (discountBps.gt(constants_1.BN_ZERO)) {
1482
+ var discount = collateralFeeUsd.mul(discountBps).div(new anchor_1.BN(constants_1.BPS_POWER));
1483
+ collateralFeeUsd = exitFeeUsd.sub(discount);
1484
+ }
1402
1485
  newPosition.collateralAmount = newPosition.collateralAmount.sub(collateralAmountReceived);
1403
1486
  newPosition.collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(newPosition.collateralAmount, collateralCustodyAccount.decimals);
1404
- var finalInterestUsd = _this.getInterestAmountUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1405
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, newPosition.price, finalInterestUsd, newPosition.unrealizedLossUsd, newPosition.side, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1406
- var finalPnl = _this.getPnlSync(newPosition, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1487
+ var finalInterestUsd = _this.getLockFeeUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1488
+ var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, newPosition.entryPrice.price, finalInterestUsd, newPosition.unsettledFeesUsd, marketCorrelation, side, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1489
+ var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1407
1490
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1408
1491
  var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, finalPnlUsd);
1409
1492
  return {
1410
1493
  newSizeUsd: newPosition.sizeUsd,
1411
1494
  feeUsd: feeUsd.add(collateralFeeUsd),
1495
+ feeUsdWithDiscount: feeUsdWithDiscount.add(collateralFeeUsd),
1412
1496
  newLev: newLev,
1413
1497
  liquidationPrice: finalLiquidationPrice,
1414
1498
  collateralAmountRecieved: collateralAmountReceived,
@@ -1417,9 +1501,9 @@ var PerpetualsClient = (function () {
1417
1501
  };
1418
1502
  }
1419
1503
  else {
1420
- var finalInterestUsd = _this.getInterestAmountUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1421
- var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, newPosition.price, finalInterestUsd, newPosition.unrealizedLossUsd, newPosition.side, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1422
- var finalPnl = _this.getPnlSync(newPosition, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1504
+ var finalInterestUsd = _this.getLockFeeUsdForPosition(newPosition, collateralCustodyAccount, currentTimestamp);
1505
+ var finalLiquidationPrice = _this.getLiquidationPriceSync(newPosition.collateralAmount, newPosition.sizeAmount, newPosition.entryPrice.price, finalInterestUsd, newPosition.unsettledFeesUsd, marketCorrelation, side, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, newPosition);
1506
+ var finalPnl = _this.getPnlSync(newPosition, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1423
1507
  var finalPnlUsd = finalPnl.profitUsd.sub(finalPnl.lossUsd);
1424
1508
  var newLev = _this.getLeverageSync(newPosition.sizeUsd, newPosition.collateralAmount, collateralMinMaxPrice.min, collateralCustodyAccount.decimals, finalPnlUsd);
1425
1509
  var collateralAmountReceived = newPosition.collateralAmount.sub(positionAccount.collateralAmount);
@@ -1429,6 +1513,7 @@ var PerpetualsClient = (function () {
1429
1513
  return {
1430
1514
  newSizeUsd: newPosition.sizeUsd,
1431
1515
  feeUsd: feeUsd,
1516
+ feeUsdWithDiscount: feeUsdWithDiscount,
1432
1517
  newLev: newLev,
1433
1518
  liquidationPrice: finalLiquidationPrice,
1434
1519
  collateralAmountRecieved: collateralAmountReceived,
@@ -1437,41 +1522,38 @@ var PerpetualsClient = (function () {
1437
1522
  };
1438
1523
  }
1439
1524
  };
1440
- this.getFinalCloseAmountSync = function (positionAccount, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1525
+ this.getFinalCloseAmountSync = function (positionAccount, marketCorrelation, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig) {
1441
1526
  var position = PositionAccount_1.PositionAccount.from(positionAccount.publicKey, __assign({}, positionAccount));
1442
1527
  var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount);
1443
1528
  var collateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, collateralCustodyAccount.decimals);
1444
- var newPnl = _this.getPnlSync(position, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1445
- var pnlUsd;
1446
- if (newPnl.profitUsd.gt(constants_1.BN_ZERO)) {
1447
- pnlUsd = newPnl.profitUsd;
1448
- }
1449
- else if (newPnl.lossUsd.lt(collateralUsd)) {
1450
- pnlUsd = newPnl.lossUsd.neg();
1529
+ var newPnl = _this.getPnlSync(position, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1530
+ var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, marketCorrelation, positionAccount.collateralAmount, positionAccount.sizeAmount, side, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1531
+ var unsettledFeesUsd = (exitPriceAndFee.exitFeeUsd.add(exitPriceAndFee.borrowFeeUsd)).add(positionAccount.unsettledFeesUsd);
1532
+ var liabilityUsd = newPnl.lossUsd.add(unsettledFeesUsd);
1533
+ var assetsUsd = newPnl.profitUsd.add(collateralMinMaxPrice.min.getAssetAmountUsd(positionAccount.collateralAmount, positionAccount.collateralDecimals));
1534
+ var closeAmount, feesAmount;
1535
+ if (assetsUsd.gt(liabilityUsd)) {
1536
+ closeAmount = collateralMinMaxPrice.max.getTokenAmount(assetsUsd.sub(liabilityUsd), position.collateralDecimals);
1537
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(unsettledFeesUsd, positionAccount.collateralDecimals);
1451
1538
  }
1452
1539
  else {
1453
- pnlUsd = constants_1.BN_ZERO;
1540
+ closeAmount = constants_1.BN_ZERO;
1541
+ feesAmount = collateralMinMaxPrice.min.getTokenAmount(assetsUsd.sub(newPnl.lossUsd), positionAccount.collateralDecimals);
1454
1542
  }
1455
- var finalUsd = collateralUsd.add(pnlUsd);
1456
- var finalAmount = constants_1.BN_ZERO;
1457
- var feeUsd = newPnl.exitFeeUsd.add(newPnl.borrowFeeUsd);
1458
- if (!finalUsd.isNeg()) {
1459
- finalAmount = collateralMinMaxPrice.min.getTokenAmount(finalUsd, collateralCustodyAccount.decimals);
1460
- }
1461
- return { finalAmount: finalAmount, feeUsd: feeUsd };
1543
+ return { closeAmount: closeAmount, feesAmount: feesAmount };
1462
1544
  };
1463
- this.getMaxWithdrawableAmountSync = function (positionAccount, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, errorBandwidthPercentageUi) {
1545
+ this.getMaxWithdrawableAmountSync = function (positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, poolConfig, errorBandwidthPercentageUi) {
1464
1546
  if (errorBandwidthPercentageUi === void 0) { errorBandwidthPercentageUi = 5; }
1465
1547
  if (errorBandwidthPercentageUi > 100 || errorBandwidthPercentageUi < 0) {
1466
1548
  throw new Error("errorBandwidthPercentageUi cannot be >100 or <0");
1467
1549
  }
1468
- var MAX_INIT_LEVERAGE = marketCustodyAccount.pricing.maxInitialLeverage.mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1469
- var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub(marketCustodyAccount.pricing.minCollateralUsd.mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1550
+ var MAX_INIT_LEVERAGE = targetCustodyAccount.pricing.maxInitialLeverage.mul(new anchor_1.BN(100 - errorBandwidthPercentageUi)).div(new anchor_1.BN(100));
1551
+ var maxRemoveableCollateralUsdAfterMinRequired = positionAccount.collateralUsd.sub(targetCustodyAccount.pricing.minCollateralUsd.mul(new anchor_1.BN(100 + errorBandwidthPercentageUi)).div(new anchor_1.BN(100)));
1470
1552
  if (maxRemoveableCollateralUsdAfterMinRequired.isNeg()) {
1471
1553
  console.log("THIS cannot happen but still");
1472
1554
  return constants_1.BN_ZERO;
1473
1555
  }
1474
- var profitLoss = _this.getPnlSync(positionAccount, marketPrice, marketEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1556
+ var profitLoss = _this.getPnlSync(positionAccount, targetPrice, targetEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, targetCustodyAccount.pricing.delaySeconds, poolConfig);
1475
1557
  var _a = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount), collateralMinPrice = _a.min, collateralMaxPrice = _a.max;
1476
1558
  var currentCollateralUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1477
1559
  var availableInitMarginUsd = constants_1.BN_ZERO;
@@ -1495,133 +1577,142 @@ var PerpetualsClient = (function () {
1495
1577
  }
1496
1578
  return maxWithdrawableAmount;
1497
1579
  };
1498
- this.getCumulativeInterestSync = function (custodyAccount, currentTimestamp) {
1499
- var cumulativeInterest = constants_1.BN_ZERO;
1580
+ this.getCumulativeLockFeeSync = function (custodyAccount, currentTimestamp) {
1581
+ var cumulativeLockFee = constants_1.BN_ZERO;
1500
1582
  if (currentTimestamp.gt(custodyAccount.borrowRateState.lastUpdate)) {
1501
- cumulativeInterest = (currentTimestamp
1583
+ cumulativeLockFee = (currentTimestamp
1502
1584
  .sub(custodyAccount.borrowRateState.lastUpdate))
1503
1585
  .mul(custodyAccount.borrowRateState.currentRate)
1504
1586
  .div(new anchor_1.BN(3600))
1505
- .add(custodyAccount.borrowRateState.cumulativeInterest);
1587
+ .add(custodyAccount.borrowRateState.cumulativeLockFee);
1506
1588
  }
1507
1589
  else {
1508
- cumulativeInterest = custodyAccount.borrowRateState.cumulativeInterest;
1590
+ cumulativeLockFee = custodyAccount.borrowRateState.cumulativeLockFee;
1509
1591
  }
1510
- return cumulativeInterest;
1592
+ return cumulativeLockFee;
1511
1593
  };
1512
- this.getInterestAmountUsdForPosition = function (position, collateralCustodyAccount, currentTimestamp) {
1513
- var cumulativeInterest = _this.getCumulativeInterestSync(collateralCustodyAccount, currentTimestamp);
1514
- var interestAmountUsd = constants_1.BN_ZERO;
1515
- if (cumulativeInterest.gt(position.cumulativeInterestSnapshot)) {
1516
- interestAmountUsd = cumulativeInterest.sub(position.cumulativeInterestSnapshot).mul(position.borrowSizeUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1594
+ this.getLockFeeUsdForPosition = function (position, collateralCustodyAccount, currentTimestamp) {
1595
+ var cumulativeLockFee = _this.getCumulativeLockFeeSync(collateralCustodyAccount, currentTimestamp);
1596
+ var lockFeeUsd = constants_1.BN_ZERO;
1597
+ if (cumulativeLockFee.gt(position.cumulativeLockFeeSnapshot)) {
1598
+ lockFeeUsd = cumulativeLockFee.sub(position.cumulativeLockFeeSnapshot).mul(position.lockedUsd).div(new anchor_1.BN(constants_1.RATE_POWER));
1517
1599
  }
1518
- return interestAmountUsd;
1600
+ return lockFeeUsd;
1519
1601
  };
1520
- this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryPrice, interestAmountUsd, unrealizedLossUsd, side, custodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount) {
1602
+ this.getLiquidationPriceSync = function (collateralAmount, sizeAmount, entryPriceUsd, lockFeeUsd, unsettledFeesUsd, marketCorrelation, side, custodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, positionAccount) {
1521
1603
  if (collateralAmount.isZero() || sizeAmount.isZero()) {
1522
1604
  return constants_1.BN_ZERO;
1523
1605
  }
1524
- var entryPriceOracle = new OraclePrice_1.OraclePrice({ price: entryPrice, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1525
- var sizeUsd = entryPriceOracle.getAssetAmountUsd(sizeAmount, custodyAccount.decimals);
1526
- var exitFeeUsd = sizeUsd.mul(custodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1527
- var currentUnrealisedUsd = exitFeeUsd.add(interestAmountUsd).add(unrealizedLossUsd);
1528
- var liablityThresholdUsd = sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(custodyAccount.pricing.maxLeverage).add(currentUnrealisedUsd);
1606
+ var exitFeeUsd = positionAccount.sizeUsd.mul(custodyAccount.fees.closePosition).div(new anchor_1.BN(constants_1.RATE_POWER));
1607
+ var unsettledLossUsd = exitFeeUsd.add(lockFeeUsd).add(unsettledFeesUsd);
1608
+ var liablityThresholdUsd = positionAccount.sizeUsd.mul(new anchor_1.BN(constants_1.BPS_POWER)).div(custodyAccount.pricing.maxLeverage).add(unsettledLossUsd);
1529
1609
  var collateralMinPriceOracle = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1530
1610
  var currentCollateralUsd = collateralMinPriceOracle.getAssetAmountUsd(collateralAmount, collateralCustodyAccount.decimals);
1531
- var maxLossUsd = sizeUsd.add(currentCollateralUsd);
1532
- var sizeDecimals = (0, utils_1.scaleToExponent)(sizeAmount, new anchor_1.BN(-1 * custodyAccount.decimals), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1533
- var collateralDecimals = (0, utils_1.scaleToExponent)(collateralAmount, new anchor_1.BN(-1 * custodyAccount.decimals), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1611
+ var nominalSolvency;
1612
+ if (currentCollateralUsd.gt(liablityThresholdUsd)) {
1613
+ nominalSolvency = true;
1614
+ }
1615
+ else {
1616
+ nominalSolvency = false;
1617
+ }
1618
+ var remainingMarginUsd, requiredMarginUsd;
1619
+ if (nominalSolvency) {
1620
+ remainingMarginUsd = currentCollateralUsd.sub(liablityThresholdUsd);
1621
+ requiredMarginUsd = constants_1.BN_ZERO;
1622
+ }
1623
+ else {
1624
+ remainingMarginUsd = constants_1.BN_ZERO;
1625
+ requiredMarginUsd = liablityThresholdUsd.sub(currentCollateralUsd);
1626
+ }
1534
1627
  var liquidationPrice = constants_1.BN_ZERO;
1535
1628
  if ((0, types_1.isVariant)(side, 'long')) {
1536
- if (!custodyAccount.isVirtual) {
1537
- liquidationPrice = sizeUsd.add(liablityThresholdUsd).mul(new anchor_1.BN(Math.pow(10, constants_1.PRICE_DECIMALS))).div(sizeDecimals.add(collateralDecimals));
1629
+ if (marketCorrelation) {
1630
+ liquidationPrice = positionAccount.sizeUsd.add(liablityThresholdUsd).mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals))).div(sizeAmount.add(collateralAmount));
1631
+ }
1632
+ else if (nominalSolvency) {
1633
+ var priceDiscount = (remainingMarginUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals)))).div(sizeAmount);
1634
+ liquidationPrice = entryPriceUsd.sub(priceDiscount);
1538
1635
  }
1539
1636
  else {
1540
- var sum = sizeUsd.add(liablityThresholdUsd);
1541
- liquidationPrice = sum.sub(currentCollateralUsd).mul(new anchor_1.BN(Math.pow(10, constants_1.PRICE_DECIMALS))).div(sizeDecimals);
1637
+ var pricePremium = (requiredMarginUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals)))).div(sizeAmount);
1638
+ liquidationPrice = entryPriceUsd.add(pricePremium);
1542
1639
  }
1543
1640
  }
1544
1641
  else {
1545
- liquidationPrice = maxLossUsd.sub(liablityThresholdUsd).mul(new anchor_1.BN(Math.pow(10, constants_1.PRICE_DECIMALS))).div(sizeDecimals);
1642
+ if (nominalSolvency) {
1643
+ var pricePremium = (remainingMarginUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals)))).div(sizeAmount);
1644
+ liquidationPrice = entryPriceUsd.add(pricePremium);
1645
+ }
1646
+ else {
1647
+ var priceDiscount = (requiredMarginUsd.mul(new anchor_1.BN(10).pow(new anchor_1.BN(positionAccount.sizeDecimals)))).div(sizeAmount);
1648
+ liquidationPrice = entryPriceUsd.sub(priceDiscount);
1649
+ }
1546
1650
  }
1547
1651
  return liquidationPrice.isNeg() ? constants_1.BN_ZERO : liquidationPrice;
1548
1652
  };
1549
- this.getPnlSync = function (positionAccount, marketTokenPrice, marketTokenEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp) {
1550
- if (positionAccount.sizeUsd.isZero() || positionAccount.price.isZero()) {
1653
+ this.getPnlSync = function (positionAccount, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp, delay, poolConfig) {
1654
+ if (positionAccount.sizeUsd.isZero() || positionAccount.entryPrice.price.isZero()) {
1551
1655
  return {
1552
1656
  profitUsd: constants_1.BN_ZERO,
1553
1657
  lossUsd: constants_1.BN_ZERO,
1554
- exitFeeUsd: constants_1.BN_ZERO,
1555
- borrowFeeUsd: constants_1.BN_ZERO,
1556
- exitFeeAmount: constants_1.BN_ZERO,
1557
- borrowFeeAmount: constants_1.BN_ZERO
1558
1658
  };
1559
1659
  }
1660
+ var side = poolConfig.getMarketConfigByPk(positionAccount.market).side;
1661
+ var exitPrice = _this.getExitPriceSync(side, targetTokenPrice, targetTokenEmaPrice, targetCustodyAccount);
1560
1662
  var collateralMinPrice = _this.getMinAndMaxOraclePriceSync(collateralPrice, collateralEmaPrice, collateralCustodyAccount).min;
1561
- var exitPriceAndFee = _this.getExitPriceAndFeeSync(positionAccount, positionAccount.collateralAmount, positionAccount.sizeAmount, positionAccount.side, marketTokenPrice, marketTokenEmaPrice, marketCustodyAccount, collateralPrice, collateralEmaPrice, collateralCustodyAccount, currentTimestamp);
1562
- var unrealizedLossUsd = (exitPriceAndFee.borrowFeeUsd.add(exitPriceAndFee.exitFeeUsd)).add(positionAccount.unrealizedLossUsd);
1563
- var priceDiffProfit, priceDiffLoss;
1564
- if ((0, types_1.isVariant)(positionAccount.side, 'long')) {
1565
- if (exitPriceAndFee.exitPrice.gt(positionAccount.price)) {
1566
- priceDiffProfit = exitPriceAndFee.exitPrice.sub(positionAccount.price);
1567
- priceDiffLoss = constants_1.BN_ZERO;
1663
+ var priceDiffProfitUsd, priceDiffLossUsd;
1664
+ var positionEntryPrice = OraclePrice_1.OraclePrice.from({
1665
+ price: positionAccount.entryPrice.price,
1666
+ exponent: new anchor_1.BN(positionAccount.entryPrice.exponent),
1667
+ confidence: constants_1.BN_ZERO,
1668
+ timestamp: constants_1.BN_ZERO
1669
+ })
1670
+ .scale_to_exponent(new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
1671
+ if ((0, types_1.isVariant)(side, 'long')) {
1672
+ if (exitPrice.gt(positionEntryPrice.price)) {
1673
+ if (currentTimestamp.gt(positionAccount.updateTime.add(delay))) {
1674
+ priceDiffProfitUsd = exitPrice.sub(positionEntryPrice.price);
1675
+ priceDiffLossUsd = constants_1.BN_ZERO;
1676
+ }
1677
+ else {
1678
+ priceDiffProfitUsd = constants_1.BN_ZERO;
1679
+ priceDiffLossUsd = constants_1.BN_ZERO;
1680
+ }
1568
1681
  }
1569
1682
  else {
1570
- priceDiffProfit = constants_1.BN_ZERO;
1571
- priceDiffLoss = positionAccount.price.sub(exitPriceAndFee.exitPrice);
1683
+ priceDiffProfitUsd = constants_1.BN_ZERO;
1684
+ priceDiffLossUsd = positionEntryPrice.price.sub(exitPrice);
1572
1685
  }
1573
1686
  }
1574
1687
  else {
1575
- if (exitPriceAndFee.exitPrice.lt(positionAccount.price)) {
1576
- priceDiffProfit = positionAccount.price.sub(exitPriceAndFee.exitPrice);
1577
- priceDiffLoss = constants_1.BN_ZERO;
1688
+ if (exitPrice.lt(positionEntryPrice.price)) {
1689
+ if (currentTimestamp.gt(positionAccount.updateTime.add(delay))) {
1690
+ priceDiffProfitUsd = positionEntryPrice.price.sub(exitPrice);
1691
+ priceDiffLossUsd = constants_1.BN_ZERO;
1692
+ }
1693
+ else {
1694
+ priceDiffProfitUsd = constants_1.BN_ZERO;
1695
+ priceDiffLossUsd = constants_1.BN_ZERO;
1696
+ }
1578
1697
  }
1579
1698
  else {
1580
- priceDiffProfit = constants_1.BN_ZERO;
1581
- priceDiffLoss = exitPriceAndFee.exitPrice.sub(positionAccount.price);
1699
+ priceDiffProfitUsd = constants_1.BN_ZERO;
1700
+ priceDiffLossUsd = exitPrice.sub(positionEntryPrice.price);
1582
1701
  }
1583
1702
  }
1584
1703
  ;
1585
- if (priceDiffProfit.gt(constants_1.BN_ZERO)) {
1586
- var priceDiffOracle = new OraclePrice_1.OraclePrice({ price: priceDiffProfit, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1587
- var potentialProfitUsd = priceDiffOracle.getAssetAmountUsd(positionAccount.sizeAmount, marketCustodyAccount.decimals);
1588
- if (potentialProfitUsd.gte(unrealizedLossUsd)) {
1589
- var curProfitUsd = potentialProfitUsd.sub(unrealizedLossUsd);
1590
- var maxProfitUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, collateralCustodyAccount.decimals);
1591
- return {
1592
- profitUsd: anchor_1.BN.min(maxProfitUsd, curProfitUsd),
1593
- lossUsd: constants_1.BN_ZERO,
1594
- exitFeeUsd: exitPriceAndFee.exitFeeUsd,
1595
- borrowFeeUsd: exitPriceAndFee.borrowFeeUsd,
1596
- exitFeeAmount: exitPriceAndFee.exitFeeAmount,
1597
- borrowFeeAmount: exitPriceAndFee.borrowFeeAmount
1598
- };
1599
- }
1600
- else {
1601
- var curLossUsd = unrealizedLossUsd.sub(potentialProfitUsd);
1602
- var curMarginUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1603
- return {
1604
- profitUsd: constants_1.BN_ZERO,
1605
- lossUsd: anchor_1.BN.min(curLossUsd, curMarginUsd),
1606
- exitFeeUsd: exitPriceAndFee.exitFeeUsd,
1607
- borrowFeeUsd: exitPriceAndFee.borrowFeeUsd,
1608
- exitFeeAmount: exitPriceAndFee.exitFeeAmount,
1609
- borrowFeeAmount: exitPriceAndFee.borrowFeeAmount
1610
- };
1611
- }
1704
+ var priceDiffProfitOracle = new OraclePrice_1.OraclePrice({ price: priceDiffProfitUsd, exponent: new anchor_1.BN(constants_1.USD_DECIMALS).neg(), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1705
+ var priceDiffLossOracle = new OraclePrice_1.OraclePrice({ price: priceDiffLossUsd, exponent: new anchor_1.BN(constants_1.USD_DECIMALS).neg(), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1706
+ if (priceDiffProfitUsd.gt(constants_1.BN_ZERO)) {
1707
+ return {
1708
+ profitUsd: anchor_1.BN.min(priceDiffProfitOracle.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals), collateralMinPrice.getAssetAmountUsd(positionAccount.lockedAmount, positionAccount.lockedDecimals)),
1709
+ lossUsd: constants_1.BN_ZERO,
1710
+ };
1612
1711
  }
1613
1712
  else {
1614
- var priceDiffOracle = new OraclePrice_1.OraclePrice({ price: priceDiffLoss, exponent: new anchor_1.BN(constants_1.PRICE_DECIMALS).neg(), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
1615
- var potentialLossUsd = priceDiffOracle.getAssetAmountUsd(positionAccount.sizeAmount, marketCustodyAccount.decimals);
1616
- potentialLossUsd = potentialLossUsd.add(unrealizedLossUsd);
1617
- var curMarginUsd = collateralMinPrice.getAssetAmountUsd(positionAccount.collateralAmount, collateralCustodyAccount.decimals);
1618
1713
  return {
1619
1714
  profitUsd: constants_1.BN_ZERO,
1620
- lossUsd: anchor_1.BN.min(potentialLossUsd, curMarginUsd),
1621
- exitFeeUsd: exitPriceAndFee.exitFeeUsd,
1622
- borrowFeeUsd: exitPriceAndFee.borrowFeeUsd,
1623
- exitFeeAmount: exitPriceAndFee.exitFeeAmount,
1624
- borrowFeeAmount: exitPriceAndFee.borrowFeeAmount
1715
+ lossUsd: priceDiffLossOracle.getAssetAmountUsd(positionAccount.sizeAmount, positionAccount.sizeDecimals),
1625
1716
  };
1626
1717
  }
1627
1718
  };
@@ -1688,7 +1779,7 @@ var PerpetualsClient = (function () {
1688
1779
  };
1689
1780
  }
1690
1781
  };
1691
- this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, aum_calc_mode, currentTime) {
1782
+ this.getAssetsUnderManagementUsdSync = function (poolAccount, tokenPrices, tokenEmaPrices, custodies, markets, aumCalcMode, currentTime, poolConfig) {
1692
1783
  var poolAmountUsd = constants_1.BN_ZERO;
1693
1784
  for (var index = 0; index < custodies.length; index++) {
1694
1785
  if (custodies.length != poolAccount.custodies.length || !custodies[index].publicKey.equals(poolAccount.custodies[index])) {
@@ -1698,36 +1789,39 @@ var PerpetualsClient = (function () {
1698
1789
  throw Error("token prices length incorrect");
1699
1790
  }
1700
1791
  var tokenMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[index], tokenEmaPrices[index], custodies[index]);
1701
- var aum_token_price = void 0;
1702
- if ((0, types_1.isVariant)(aum_calc_mode, "min")) {
1703
- aum_token_price = tokenMinMaxPrice.min;
1704
- }
1705
- else if ((0, types_1.isVariant)(aum_calc_mode, "max")) {
1706
- aum_token_price = tokenMinMaxPrice.max;
1707
- }
1708
- var token_amount_usd = aum_token_price.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1792
+ var token_amount_usd = tokenMinMaxPrice.max.getAssetAmountUsd(custodies[index].assets.owned, custodies[index].decimals);
1709
1793
  poolAmountUsd = poolAmountUsd.add(token_amount_usd);
1710
- if (!custodies[index].isStable) {
1711
- var longPnl = _this.getPnlSync(custodies[index].getCollectivePosition(types_1.Side.Long), tokenPrices[index], tokenEmaPrices[index], custodies[index], tokenPrices[index], tokenEmaPrices[index], custodies[index], currentTime);
1712
- var shortPnl = _this.getPnlSync(custodies[index].getCollectivePosition(types_1.Side.Short), tokenPrices[index], tokenEmaPrices[index], custodies[index], tokenPrices[0], tokenEmaPrices[0], custodies[0], currentTime);
1713
- poolAmountUsd = poolAmountUsd.add(longPnl.lossUsd);
1714
- poolAmountUsd = poolAmountUsd.add(shortPnl.lossUsd);
1715
- poolAmountUsd = poolAmountUsd.sub(longPnl.profitUsd);
1716
- poolAmountUsd = poolAmountUsd.sub(shortPnl.profitUsd);
1794
+ }
1795
+ if ((0, types_1.isVariant)(aumCalcMode, "includePnl")) {
1796
+ var poolEquityUsd = poolAmountUsd;
1797
+ for (var index = 0; index < markets.length; index++) {
1798
+ if (markets.length != poolAccount.markets.length || !markets[index].publicKey.equals(poolAccount.markets[index])) {
1799
+ throw Error("incorrect markets");
1800
+ }
1801
+ var position = markets[index].getCollectivePosition();
1802
+ var collectivePnl = _this.getPnlSync(position, tokenPrices[markets[index].targetCustodyId.toNumber()], tokenEmaPrices[markets[index].targetCustodyId.toNumber()], custodies[markets[index].targetCustodyId.toNumber()], tokenPrices[markets[index].collateralCustodyId.toNumber()], tokenEmaPrices[markets[index].collateralCustodyId.toNumber()], custodies[markets[index].collateralCustodyId.toNumber()], currentTime, custodies[markets[index].targetCustodyId.toNumber()].pricing.delaySeconds, poolConfig);
1803
+ var collateralMinMaxPrice = _this.getMinAndMaxOraclePriceSync(tokenPrices[markets[index].collateralCustodyId.toNumber()], tokenEmaPrices[markets[index].collateralCustodyId.toNumber()], custodies[markets[index].collateralCustodyId.toNumber()]);
1804
+ var collectiveCollateralUsd = collateralMinMaxPrice.min.getAssetAmountUsd(position.collateralAmount, position.collateralDecimals);
1805
+ var collectiveLossUsd = anchor_1.BN.min(collectivePnl.lossUsd, collectiveCollateralUsd);
1806
+ poolEquityUsd = (poolEquityUsd.add(collectiveLossUsd)).sub(collectivePnl.profitUsd);
1717
1807
  }
1808
+ return { poolAmountUsd: poolAmountUsd, poolEquityUsd: poolEquityUsd };
1809
+ }
1810
+ else {
1811
+ return { poolAmountUsd: poolAmountUsd, poolEquityUsd: constants_1.BN_ZERO };
1718
1812
  }
1719
- return poolAmountUsd;
1720
1813
  };
1721
- this.openPosition = function (marketSymbol, collateralSymbol, priceAfterSlippage, collateralWithfee, size, side, poolConfig, skipBalanceChecks) {
1814
+ this.openPosition = function (targetSymbol, collateralSymbol, priceWithSlippage, collateralWithfee, size, side, poolConfig, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege, skipBalanceChecks) {
1722
1815
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
1723
1816
  return __awaiter(_this, void 0, void 0, function () {
1724
- var publicKey, marketCustodyConfig, collateralCustodyConfig, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
1817
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, marketAccount, userCollateralTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, positionAccount, params, instruction;
1725
1818
  return __generator(this, function (_c) {
1726
1819
  switch (_c.label) {
1727
1820
  case 0:
1728
1821
  publicKey = this.provider.wallet.publicKey;
1729
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
1822
+ targetCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
1730
1823
  collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1824
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
1731
1825
  return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey)];
1732
1826
  case 1:
1733
1827
  userCollateralTokenAccount = _c.sent();
@@ -1780,42 +1874,37 @@ var PerpetualsClient = (function () {
1780
1874
  }
1781
1875
  _c.label = 7;
1782
1876
  case 7:
1783
- positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1784
- Buffer.from("position"),
1785
- publicKey.toBuffer(),
1786
- poolConfig.poolAddress.toBuffer(),
1787
- marketCustodyConfig.custodyAccount.toBuffer(),
1788
- (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1789
- ], this.programId)[0];
1877
+ positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
1790
1878
  params = {
1791
- price: priceAfterSlippage,
1792
- collateral: collateralWithfee,
1793
- size: size,
1794
- side: side,
1879
+ priceWithSlippage: priceWithSlippage,
1880
+ collateralAmount: collateralWithfee,
1881
+ sizeAmount: size,
1882
+ privilege: privilege
1795
1883
  };
1796
1884
  return [4, this.program.methods
1797
1885
  .openPosition(params)
1798
1886
  .accounts({
1799
- delegate: publicKey,
1800
1887
  owner: publicKey,
1888
+ feePayer: publicKey,
1801
1889
  fundingAccount: collateralSymbol == 'SOL' ? wrappedSolAccount.publicKey : userCollateralTokenAccount,
1802
- transferAuthority: poolConfig.transferAuthority,
1803
1890
  perpetuals: poolConfig.perpetuals,
1804
1891
  pool: poolConfig.poolAddress,
1805
1892
  position: positionAccount,
1806
- custody: marketCustodyConfig.custodyAccount,
1807
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
1808
- custodyCustomOracleAccount: poolConfig.backupOracle,
1893
+ market: marketAccount,
1894
+ targetCustody: targetCustodyConfig.custodyAccount,
1895
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
1809
1896
  collateralCustody: collateralCustodyConfig.custodyAccount,
1810
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
1811
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
1897
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
1812
1898
  collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
1813
- eventAuthority: this.eventAuthority.publicKey,
1814
1899
  systemProgram: web3_js_1.SystemProgram.programId,
1815
1900
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1901
+ eventAuthority: this.eventAuthority.publicKey,
1816
1902
  program: this.programId,
1903
+ transferAuthority: this.authority.publicKey,
1817
1904
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
1818
- }).instruction()];
1905
+ })
1906
+ .remainingAccounts(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true))
1907
+ .instruction()];
1819
1908
  case 8:
1820
1909
  instruction = _c.sent();
1821
1910
  instructions.push(instruction);
@@ -1827,17 +1916,18 @@ var PerpetualsClient = (function () {
1827
1916
  });
1828
1917
  });
1829
1918
  };
1830
- this.openPositionWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, priceAfterSlippage, size, side, poolConfig, skipBalanceChecks) {
1919
+ this.openPositionWithSwap = function (targetSymbol, collateralSymbol, inputSymbol, amountIn, minAmountOut, priceWithSlippage, size, side, swapPoolConfig, positionPoolConfig, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege, skipBalanceChecks) {
1831
1920
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
1832
1921
  return __awaiter(_this, void 0, void 0, function () {
1833
- var publicKey, marketCustodyConfig, collateralCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _c, custody, poolAumInstruction, instruction;
1922
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, outputCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userOutputTokenAccount, marketAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _c, custody, instruction;
1834
1923
  return __generator(this, function (_d) {
1835
1924
  switch (_d.label) {
1836
1925
  case 0:
1837
1926
  publicKey = this.provider.wallet.publicKey;
1838
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
1839
- collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1840
- inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
1927
+ targetCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
1928
+ collateralCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1929
+ outputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
1930
+ inputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
1841
1931
  if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
1842
1932
  throw "Don't use Swap, just call Open position";
1843
1933
  }
@@ -1876,7 +1966,7 @@ var PerpetualsClient = (function () {
1876
1966
  additionalSigners.push(wrappedSolAccount);
1877
1967
  return [3, 6];
1878
1968
  case 3:
1879
- userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(inputSymbol).mintKey, publicKey);
1969
+ userInputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(swapPoolConfig.getTokenFromSymbol(inputSymbol).mintKey, publicKey);
1880
1970
  return [4, (0, utils_1.checkIfAccountExists)(userInputTokenAccount, this.provider.connection)];
1881
1971
  case 4:
1882
1972
  if (!(_d.sent())) {
@@ -1892,23 +1982,17 @@ var PerpetualsClient = (function () {
1892
1982
  }
1893
1983
  _d.label = 6;
1894
1984
  case 6:
1895
- userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
1896
- return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
1985
+ userOutputTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(swapPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
1986
+ return [4, (0, utils_1.checkIfAccountExists)(userOutputTokenAccount, this.provider.connection)];
1897
1987
  case 7:
1898
1988
  if (!(_d.sent())) {
1899
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
1989
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userOutputTokenAccount, publicKey, swapPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
1900
1990
  }
1901
- positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
1902
- Buffer.from("position"),
1903
- publicKey.toBuffer(),
1904
- poolConfig.poolAddress.toBuffer(),
1905
- marketCustodyConfig.custodyAccount.toBuffer(),
1906
- (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
1907
- ], this.programId)[0];
1991
+ marketAccount = positionPoolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
1992
+ positionAccount = positionPoolConfig.getPositionFromMarketPk(publicKey, marketAccount);
1908
1993
  custodyAccountMetas = [];
1909
1994
  custodyOracleAccountMetas = [];
1910
- custodyCustomOracles = [];
1911
- for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
1995
+ for (_i = 0, _c = swapPoolConfig.custodies; _i < _c.length; _i++) {
1912
1996
  custody = _c[_i];
1913
1997
  custodyAccountMetas.push({
1914
1998
  pubkey: custody.custodyAccount,
@@ -1920,61 +2004,45 @@ var PerpetualsClient = (function () {
1920
2004
  isSigner: false,
1921
2005
  isWritable: false,
1922
2006
  });
1923
- custodyCustomOracles.push({
1924
- pubkey: poolConfig.backupOracle,
1925
- isSigner: false,
1926
- isWritable: false,
1927
- });
1928
2007
  }
1929
- return [4, this.program.methods
1930
- .updatePoolAum()
1931
- .accounts({
1932
- payer: publicKey,
1933
- perpetuals: poolConfig.perpetuals,
1934
- pool: poolConfig.poolAddress,
1935
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
1936
- })
1937
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
1938
- .instruction()];
1939
- case 8:
1940
- poolAumInstruction = _d.sent();
1941
- preInstructions.push(poolAumInstruction);
1942
2008
  return [4, this.programPerpComposability.methods
1943
2009
  .swapAndOpen({
1944
2010
  amountIn: amountIn,
1945
2011
  minAmountOut: minAmountOut,
1946
- openPrice: priceAfterSlippage,
1947
- openSize: size,
1948
- side: side,
2012
+ openPriceWithSlippage: priceWithSlippage,
2013
+ openSizeAmount: size,
2014
+ privilege: privilege
1949
2015
  })
1950
2016
  .accounts({
1951
- delegate: publicKey,
2017
+ perpProgram: this.programId,
1952
2018
  owner: publicKey,
1953
2019
  fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
1954
- receivingAccount: userCollateralTokenAccount,
1955
- transferAuthority: poolConfig.transferAuthority,
1956
- perpetuals: poolConfig.perpetuals,
1957
- pool: poolConfig.poolAddress,
2020
+ receivingAccount: userOutputTokenAccount,
2021
+ transferAuthority: swapPoolConfig.transferAuthority,
2022
+ perpetuals: swapPoolConfig.perpetuals,
2023
+ swapPool: swapPoolConfig.poolAddress,
1958
2024
  receivingCustody: inputCustodyConfig.custodyAccount,
1959
2025
  receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
1960
- receivingCustodyCustomOracleAccount: poolConfig.backupOracle,
1961
2026
  receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
1962
- dispensingCustody: collateralCustodyConfig.custodyAccount,
1963
- dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
1964
- dispensingCustodyCustomOracleAccount: poolConfig.backupOracle,
1965
- dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2027
+ dispensingCustody: outputCustodyConfig.custodyAccount,
2028
+ dispensingCustodyOracleAccount: outputCustodyConfig.oracleAddress,
2029
+ dispensingCustodyTokenAccount: outputCustodyConfig.tokenAccount,
2030
+ positionPool: positionPoolConfig.poolAddress,
1966
2031
  position: positionAccount,
1967
- custody: marketCustodyConfig.custodyAccount,
1968
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
1969
- custodyCustomOracleAccount: poolConfig.backupOracle,
2032
+ market: marketAccount,
2033
+ targetCustody: targetCustodyConfig.custodyAccount,
2034
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2035
+ collateralCustody: collateralCustodyConfig.custodyAccount,
2036
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2037
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
1970
2038
  eventAuthority: this.eventAuthority.publicKey,
1971
2039
  systemProgram: web3_js_1.SystemProgram.programId,
1972
2040
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1973
- perpProgram: this.programId,
1974
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2041
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
1975
2042
  })
2043
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true), custodyAccountMetas, true), custodyOracleAccountMetas, true))
1976
2044
  .instruction()];
1977
- case 9:
2045
+ case 8:
1978
2046
  instruction = _d.sent();
1979
2047
  instructions.push(instruction);
1980
2048
  return [2, {
@@ -1985,11 +2053,11 @@ var PerpetualsClient = (function () {
1985
2053
  });
1986
2054
  });
1987
2055
  };
1988
- this.closePosition = function (marketSymbol, collateralSymbol, priceAfterSlippage, side, poolConfig, createUserATA, closeUsersWSOLATA) {
2056
+ this.closePosition = function (marketSymbol, collateralSymbol, priceWithSlippage, side, poolConfig, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege, createUserATA, closeUsersWSOLATA) {
1989
2057
  if (createUserATA === void 0) { createUserATA = true; }
1990
2058
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
1991
2059
  return __awaiter(_this, void 0, void 0, function () {
1992
- var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, marketCustodyConfig, positionAccount, params, instruction, closeWsolATAIns, error_2;
2060
+ var publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, collateralCustodyConfig, targetCustodyConfig, marketAccount, positionAccount, instruction, closeWsolATAIns, error_2;
1993
2061
  return __generator(this, function (_b) {
1994
2062
  switch (_b.label) {
1995
2063
  case 0:
@@ -2038,39 +2106,35 @@ var PerpetualsClient = (function () {
2038
2106
  _b.label = 7;
2039
2107
  case 7:
2040
2108
  collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2041
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2042
- positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
2043
- Buffer.from("position"),
2044
- publicKey.toBuffer(),
2045
- poolConfig.poolAddress.toBuffer(),
2046
- marketCustodyConfig.custodyAccount.toBuffer(),
2047
- (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
2048
- ], this.programId)[0];
2049
- params = {
2050
- price: priceAfterSlippage,
2051
- };
2109
+ targetCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2110
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2111
+ positionAccount = poolConfig.getPositionFromMarketPk(publicKey, marketAccount);
2052
2112
  return [4, this.program.methods
2053
- .closePosition(params)
2113
+ .closePosition({
2114
+ priceWithSlippage: priceWithSlippage,
2115
+ privilege: privilege
2116
+ })
2054
2117
  .accounts({
2055
- delegate: publicKey,
2118
+ feePayer: publicKey,
2056
2119
  owner: publicKey,
2057
2120
  receivingAccount: collateralSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
2058
2121
  transferAuthority: poolConfig.transferAuthority,
2059
2122
  perpetuals: poolConfig.perpetuals,
2060
2123
  pool: poolConfig.poolAddress,
2061
2124
  position: positionAccount,
2062
- custody: marketCustodyConfig.custodyAccount,
2063
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2064
- custodyCustomOracleAccount: poolConfig.backupOracle,
2125
+ market: marketAccount,
2126
+ targetCustody: targetCustodyConfig.custodyAccount,
2127
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2065
2128
  collateralCustody: collateralCustodyConfig.custodyAccount,
2066
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2067
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
2129
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2068
2130
  collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2069
2131
  eventAuthority: this.eventAuthority.publicKey,
2070
2132
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2071
2133
  program: this.programId,
2072
2134
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2073
- }).instruction()];
2135
+ })
2136
+ .remainingAccounts(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true))
2137
+ .instruction()];
2074
2138
  case 8:
2075
2139
  instruction = _b.sent();
2076
2140
  instructions.push(instruction);
@@ -2091,15 +2155,16 @@ var PerpetualsClient = (function () {
2091
2155
  });
2092
2156
  });
2093
2157
  };
2094
- this.closePositionWithSwap = function (marketSymbol, outputSymbol, collateralSymbol, minAmountOut, priceAfterSlippage, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
2095
- var publicKey, marketCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _a, custody, poolAumInstruction, instruction;
2158
+ this.closePositionWithSwap = function (targetSymbol, outputSymbol, collateralSymbol, minAmountOut, priceAfterSlippage, side, swapPoolConfig, positionPoolConfig, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege) { return __awaiter(_this, void 0, void 0, function () {
2159
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, inputCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody, instruction;
2096
2160
  return __generator(this, function (_b) {
2097
2161
  switch (_b.label) {
2098
2162
  case 0:
2099
2163
  publicKey = this.provider.wallet.publicKey;
2100
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2101
- collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2102
- outputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(outputSymbol).mintKey); });
2164
+ targetCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
2165
+ collateralCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2166
+ inputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2167
+ outputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey); });
2103
2168
  if (outputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
2104
2169
  throw "Dont use swap, just call close position";
2105
2170
  }
@@ -2128,33 +2193,27 @@ var PerpetualsClient = (function () {
2128
2193
  ];
2129
2194
  additionalSigners.push(wrappedSolAccount);
2130
2195
  return [3, 5];
2131
- case 2: return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(outputSymbol).mintKey, publicKey)];
2196
+ case 2: return [4, (0, spl_token_1.getAssociatedTokenAddress)(swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey, publicKey)];
2132
2197
  case 3:
2133
2198
  userReceivingTokenAccount = _b.sent();
2134
2199
  return [4, (0, utils_1.checkIfAccountExists)(userReceivingTokenAccount, this.provider.connection)];
2135
2200
  case 4:
2136
2201
  if (!(_b.sent())) {
2137
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(outputSymbol).mintKey));
2202
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey));
2138
2203
  }
2139
2204
  _b.label = 5;
2140
2205
  case 5:
2141
- userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
2206
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
2142
2207
  return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
2143
2208
  case 6:
2144
2209
  if (!(_b.sent())) {
2145
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
2210
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
2146
2211
  }
2147
- positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
2148
- Buffer.from("position"),
2149
- publicKey.toBuffer(),
2150
- poolConfig.poolAddress.toBuffer(),
2151
- marketCustodyConfig.custodyAccount.toBuffer(),
2152
- (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
2153
- ], this.programId)[0];
2212
+ marketAccount = positionPoolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2213
+ positionAccount = positionPoolConfig.getPositionFromMarketPk(publicKey, marketAccount);
2154
2214
  custodyAccountMetas = [];
2155
2215
  custodyOracleAccountMetas = [];
2156
- custodyCustomOracles = [];
2157
- for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
2216
+ for (_i = 0, _a = swapPoolConfig.custodies; _i < _a.length; _i++) {
2158
2217
  custody = _a[_i];
2159
2218
  custodyAccountMetas.push({
2160
2219
  pubkey: custody.custodyAccount,
@@ -2166,57 +2225,41 @@ var PerpetualsClient = (function () {
2166
2225
  isSigner: false,
2167
2226
  isWritable: false,
2168
2227
  });
2169
- custodyCustomOracles.push({
2170
- pubkey: poolConfig.backupOracle,
2171
- isSigner: false,
2172
- isWritable: false,
2173
- });
2174
2228
  }
2175
- return [4, this.program.methods
2176
- .updatePoolAum()
2177
- .accounts({
2178
- payer: publicKey,
2179
- perpetuals: poolConfig.perpetuals,
2180
- pool: poolConfig.poolAddress,
2181
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2182
- })
2183
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2184
- .instruction()];
2185
- case 7:
2186
- poolAumInstruction = _b.sent();
2187
- preInstructions.push(poolAumInstruction);
2188
2229
  return [4, this.programPerpComposability.methods
2189
2230
  .closeAndSwap({
2190
2231
  minAmountOut: minAmountOut,
2191
2232
  closePrice: priceAfterSlippage,
2192
2233
  })
2193
2234
  .accounts({
2194
- delegate: publicKey,
2235
+ perpProgram: this.programId,
2195
2236
  owner: publicKey,
2196
2237
  fundingAccount: userCollateralTokenAccount,
2197
2238
  receivingAccount: outputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
2198
- transferAuthority: poolConfig.transferAuthority,
2199
- perpetuals: poolConfig.perpetuals,
2200
- pool: poolConfig.poolAddress,
2201
- receivingCustody: collateralCustodyConfig.custodyAccount,
2202
- receivingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2203
- receivingCustodyCustomOracleAccount: poolConfig.backupOracle,
2204
- receivingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2239
+ transferAuthority: swapPoolConfig.transferAuthority,
2240
+ perpetuals: swapPoolConfig.perpetuals,
2241
+ swapPool: swapPoolConfig.poolAddress,
2242
+ receivingCustody: inputCustodyConfig.custodyAccount,
2243
+ receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
2244
+ receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
2205
2245
  dispensingCustody: outputCustodyConfig.custodyAccount,
2206
2246
  dispensingCustodyOracleAccount: outputCustodyConfig.oracleAddress,
2207
- dispensingCustodyCustomOracleAccount: poolConfig.backupOracle,
2208
2247
  dispensingCustodyTokenAccount: outputCustodyConfig.tokenAccount,
2248
+ positionPool: positionPoolConfig.poolAddress,
2209
2249
  position: positionAccount,
2210
- custody: marketCustodyConfig.custodyAccount,
2211
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2212
- custodyCustomOracleAccount: poolConfig.backupOracle,
2250
+ market: marketAccount,
2251
+ targetCustody: targetCustodyConfig.custodyAccount,
2252
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2253
+ collateralCustody: collateralCustodyConfig.custodyAccount,
2254
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2255
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2213
2256
  eventAuthority: this.eventAuthority.publicKey,
2214
2257
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2215
- perpProgram: this.programId,
2216
2258
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2217
2259
  })
2260
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true), custodyAccountMetas, true), custodyOracleAccountMetas, true))
2218
2261
  .instruction()];
2219
- case 8:
2262
+ case 7:
2220
2263
  instruction = _b.sent();
2221
2264
  instructions.push(instruction);
2222
2265
  return [2, {
@@ -2226,12 +2269,13 @@ var PerpetualsClient = (function () {
2226
2269
  }
2227
2270
  });
2228
2271
  }); };
2229
- this.swap = function (userInputTokenSymbol, userOutputTokenSymbol, amountIn, minAmountOut, poolConfig, createUserATA, unWrapSol, skipBalanceChecks) {
2272
+ this.swap = function (userInputTokenSymbol, userOutputTokenSymbol, amountIn, minAmountOut, poolConfig, useFeesPool, createUserATA, unWrapSol, skipBalanceChecks) {
2273
+ if (useFeesPool === void 0) { useFeesPool = false; }
2230
2274
  if (createUserATA === void 0) { createUserATA = true; }
2231
2275
  if (unWrapSol === void 0) { unWrapSol = false; }
2232
2276
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2233
2277
  return __awaiter(_this, void 0, void 0, function () {
2234
- 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, custodyCustomOracles, _i, _e, custody, poolAumInstruction, params, inx, closeWsolATAIns, err_2;
2278
+ 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, _i, _e, custody, params, inx, closeWsolATAIns, err_2;
2235
2279
  return __generator(this, function (_f) {
2236
2280
  switch (_f.label) {
2237
2281
  case 0:
@@ -2287,7 +2331,7 @@ var PerpetualsClient = (function () {
2287
2331
  additionalSigners: additionalSigners
2288
2332
  }];
2289
2333
  case 6:
2290
- _f.trys.push([6, 22, , 23]);
2334
+ _f.trys.push([6, 21, , 22]);
2291
2335
  if (!(userInputTokenSymbol == 'SOL')) return [3, 9];
2292
2336
  console.log("userInputTokenSymbol === sol", userInputTokenSymbol);
2293
2337
  wrappedSolAccount = new web3_js_1.Keypair();
@@ -2373,7 +2417,6 @@ var PerpetualsClient = (function () {
2373
2417
  case 19:
2374
2418
  custodyAccountMetas = [];
2375
2419
  custodyOracleAccountMetas = [];
2376
- custodyCustomOracles = [];
2377
2420
  for (_i = 0, _e = poolConfig.custodies; _i < _e.length; _i++) {
2378
2421
  custody = _e[_i];
2379
2422
  custodyAccountMetas.push({
@@ -2386,33 +2429,15 @@ var PerpetualsClient = (function () {
2386
2429
  isSigner: false,
2387
2430
  isWritable: false,
2388
2431
  });
2389
- custodyCustomOracles.push({
2390
- pubkey: poolConfig.backupOracle,
2391
- isSigner: false,
2392
- isWritable: false,
2393
- });
2394
2432
  }
2395
- return [4, this.program.methods
2396
- .updatePoolAum()
2397
- .accounts({
2398
- payer: publicKey,
2399
- perpetuals: poolConfig.perpetuals,
2400
- pool: poolConfig.poolAddress,
2401
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2402
- })
2403
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2404
- .instruction()];
2405
- case 20:
2406
- poolAumInstruction = _f.sent();
2407
- preInstructions.push(poolAumInstruction);
2408
2433
  params = {
2409
2434
  amountIn: amountIn,
2410
2435
  minAmountOut: minAmountOut,
2436
+ useFeesPool: useFeesPool
2411
2437
  };
2412
2438
  return [4, this.program.methods
2413
2439
  .swap(params)
2414
2440
  .accounts({
2415
- delegate: publicKey,
2416
2441
  owner: publicKey,
2417
2442
  fundingAccount: userInputTokenSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
2418
2443
  receivingAccount: userOutputTokenSymbol == 'SOL' ? wrappedSolAccount.publicKey : userOutputTokenAccount,
@@ -2421,31 +2446,30 @@ var PerpetualsClient = (function () {
2421
2446
  pool: poolConfig.poolAddress,
2422
2447
  receivingCustody: userInputCustodyConfig.custodyAccount,
2423
2448
  receivingCustodyOracleAccount: userInputCustodyConfig.oracleAddress,
2424
- receivingCustodyCustomOracleAccount: poolConfig.backupOracle,
2425
2449
  receivingCustodyTokenAccount: userInputCustodyConfig.tokenAccount,
2426
2450
  dispensingCustody: userOutputCustodyConfig.custodyAccount,
2427
2451
  dispensingCustodyOracleAccount: userOutputCustodyConfig.oracleAddress,
2428
- dispensingCustodyCustomOracleAccount: poolConfig.backupOracle,
2429
2452
  dispensingCustodyTokenAccount: userOutputCustodyConfig.tokenAccount,
2430
2453
  eventAuthority: this.eventAuthority.publicKey,
2431
2454
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2432
2455
  program: this.programId,
2433
2456
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2434
2457
  })
2458
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
2435
2459
  .instruction()];
2436
- case 21:
2460
+ case 20:
2437
2461
  inx = _f.sent();
2438
2462
  instructions.push(inx);
2439
2463
  if (userOutputTokenSymbol == 'SOL' && unWrapSol) {
2440
2464
  closeWsolATAIns = (0, spl_token_1.createCloseAccountInstruction)(userOutputTokenAccount, publicKey, publicKey);
2441
2465
  instructions.push(closeWsolATAIns);
2442
2466
  }
2443
- return [3, 23];
2444
- case 22:
2467
+ return [3, 22];
2468
+ case 21:
2445
2469
  err_2 = _f.sent();
2446
2470
  console.error("perpClient Swap error:: ", err_2);
2447
2471
  throw err_2;
2448
- case 23: return [2, {
2472
+ case 22: return [2, {
2449
2473
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
2450
2474
  additionalSigners: additionalSigners
2451
2475
  }];
@@ -2453,17 +2477,18 @@ var PerpetualsClient = (function () {
2453
2477
  });
2454
2478
  });
2455
2479
  };
2456
- this.addCollateral = function (collateralWithFee, marketSymbol, collateralSymbol, positionPubKey, poolConfig, skipBalanceChecks) {
2480
+ this.addCollateral = function (collateralWithFee, targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, skipBalanceChecks) {
2457
2481
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2458
2482
  return __awaiter(_this, void 0, void 0, function () {
2459
- var publicKey, collateralCustodyConfig, marketCustodyConfig, userPayingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, solBal, tokenAccountBalance, _b, instruction;
2483
+ var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, userPayingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, accCreationLamports, lamports, unWrappedSolBalance, _a, solBal, tokenAccountBalance, _b, instruction;
2460
2484
  return __generator(this, function (_c) {
2461
2485
  switch (_c.label) {
2462
2486
  case 0:
2463
2487
  publicKey = this.provider.wallet.publicKey;
2464
2488
  collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2465
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2466
- if (!collateralCustodyConfig || !marketCustodyConfig) {
2489
+ targetCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
2490
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2491
+ if (!collateralCustodyConfig || !targetCustodyConfig) {
2467
2492
  throw "payTokenCustody not found";
2468
2493
  }
2469
2494
  userPayingTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(collateralCustodyConfig.mintKey, publicKey);
@@ -2523,19 +2548,16 @@ var PerpetualsClient = (function () {
2523
2548
  case 7: return [4, this.program.methods.addCollateral({
2524
2549
  collateralDelta: collateralWithFee
2525
2550
  }).accounts({
2526
- delegate: publicKey,
2527
2551
  owner: publicKey,
2528
2552
  position: positionPubKey,
2553
+ market: marketAccount,
2529
2554
  fundingAccount: collateralSymbol == 'SOL' ? wrappedSolAccount.publicKey : userPayingTokenAccount,
2530
- transferAuthority: poolConfig.transferAuthority,
2531
2555
  perpetuals: poolConfig.perpetuals,
2532
2556
  pool: poolConfig.poolAddress,
2533
- custody: marketCustodyConfig.custodyAccount,
2534
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2535
- custodyCustomOracleAccount: poolConfig.backupOracle,
2557
+ targetCustody: targetCustodyConfig.custodyAccount,
2558
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2536
2559
  collateralCustody: collateralCustodyConfig.custodyAccount,
2537
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2538
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
2560
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2539
2561
  collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2540
2562
  eventAuthority: this.eventAuthority.publicKey,
2541
2563
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
@@ -2554,18 +2576,19 @@ var PerpetualsClient = (function () {
2554
2576
  });
2555
2577
  });
2556
2578
  };
2557
- this.addCollateralWithSwap = function (marketSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, positionPubKey, poolConfig, skipBalanceChecks) {
2579
+ this.addCollateralWithSwap = function (targetSymbol, inputSymbol, collateralSymbol, amountIn, minAmountOut, side, positionPubKey, swapPoolConfig, positionPoolConfig, skipBalanceChecks) {
2558
2580
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
2559
2581
  return __awaiter(_this, void 0, void 0, function () {
2560
- var publicKey, collateralCustodyConfig, marketCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _c, custody, poolAumInstruction, instruction;
2582
+ var publicKey, collateralCustodyConfig, targetCustodyConfig, outputCustodyConfig, inputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userInputTokenAccount, accCreationLamports, lamports, unWrappedSolBalance, _a, tokenAccountBalance, _b, userCollateralTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _c, custody, marketAccount, instruction;
2561
2583
  return __generator(this, function (_d) {
2562
2584
  switch (_d.label) {
2563
2585
  case 0:
2564
2586
  publicKey = this.provider.wallet.publicKey;
2565
- collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2566
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2567
- inputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
2568
- if (!collateralCustodyConfig || !marketCustodyConfig || !inputCustodyConfig) {
2587
+ collateralCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2588
+ targetCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
2589
+ outputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
2590
+ inputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(inputSymbol).mintKey); });
2591
+ if (!collateralCustodyConfig || !targetCustodyConfig || !inputCustodyConfig) {
2569
2592
  throw "payTokenCustody not found";
2570
2593
  }
2571
2594
  if (inputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
@@ -2631,8 +2654,7 @@ var PerpetualsClient = (function () {
2631
2654
  }
2632
2655
  custodyAccountMetas = [];
2633
2656
  custodyOracleAccountMetas = [];
2634
- custodyCustomOracles = [];
2635
- for (_i = 0, _c = poolConfig.custodies; _i < _c.length; _i++) {
2657
+ for (_i = 0, _c = swapPoolConfig.custodies; _i < _c.length; _i++) {
2636
2658
  custody = _c[_i];
2637
2659
  custodyAccountMetas.push({
2638
2660
  pubkey: custody.custodyAccount,
@@ -2644,55 +2666,40 @@ var PerpetualsClient = (function () {
2644
2666
  isSigner: false,
2645
2667
  isWritable: false,
2646
2668
  });
2647
- custodyCustomOracles.push({
2648
- pubkey: poolConfig.backupOracle,
2649
- isSigner: false,
2650
- isWritable: false,
2651
- });
2652
2669
  }
2653
- return [4, this.program.methods
2654
- .updatePoolAum()
2655
- .accounts({
2656
- payer: publicKey,
2657
- perpetuals: poolConfig.perpetuals,
2658
- pool: poolConfig.poolAddress,
2659
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
2660
- })
2661
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2662
- .instruction()];
2663
- case 8:
2664
- poolAumInstruction = _d.sent();
2665
- preInstructions.push(poolAumInstruction);
2670
+ marketAccount = positionPoolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2666
2671
  return [4, this.programPerpComposability.methods.swapAndAddCollateral({
2667
2672
  amountIn: amountIn,
2668
2673
  minAmountOut: minAmountOut,
2669
2674
  }).accounts({
2670
- delegate: publicKey,
2675
+ perpProgram: this.programId,
2671
2676
  owner: publicKey,
2672
- position: positionPubKey,
2673
2677
  fundingAccount: inputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userInputTokenAccount,
2674
2678
  receivingAccount: userCollateralTokenAccount,
2675
- transferAuthority: poolConfig.transferAuthority,
2676
- perpetuals: poolConfig.perpetuals,
2677
- pool: poolConfig.poolAddress,
2679
+ transferAuthority: swapPoolConfig.transferAuthority,
2680
+ perpetuals: swapPoolConfig.perpetuals,
2681
+ swapPool: swapPoolConfig.poolAddress,
2678
2682
  receivingCustody: inputCustodyConfig.custodyAccount,
2679
2683
  receivingCustodyOracleAccount: inputCustodyConfig.oracleAddress,
2680
- receivingCustodyCustomOracleAccount: poolConfig.backupOracle,
2681
2684
  receivingCustodyTokenAccount: inputCustodyConfig.tokenAccount,
2682
- dispensingCustody: collateralCustodyConfig.custodyAccount,
2683
- dispensingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2684
- dispensingCustodyCustomOracleAccount: poolConfig.backupOracle,
2685
- dispensingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2686
- custody: marketCustodyConfig.custodyAccount,
2687
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2688
- custodyCustomOracleAccount: poolConfig.backupOracle,
2685
+ dispensingCustody: outputCustodyConfig.custodyAccount,
2686
+ dispensingCustodyOracleAccount: outputCustodyConfig.oracleAddress,
2687
+ dispensingCustodyTokenAccount: outputCustodyConfig.tokenAccount,
2688
+ positionPool: positionPoolConfig.poolAddress,
2689
+ position: positionPubKey,
2690
+ market: marketAccount,
2691
+ targetCustody: targetCustodyConfig.custodyAccount,
2692
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2693
+ collateralCustody: collateralCustodyConfig.custodyAccount,
2694
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2695
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2689
2696
  eventAuthority: this.eventAuthority.publicKey,
2690
2697
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2691
- perpProgram: this.programId,
2692
2698
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2693
2699
  })
2700
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
2694
2701
  .instruction()];
2695
- case 9:
2702
+ case 8:
2696
2703
  instruction = _d.sent();
2697
2704
  instructions.push(instruction);
2698
2705
  return [2, {
@@ -2703,11 +2710,11 @@ var PerpetualsClient = (function () {
2703
2710
  });
2704
2711
  });
2705
2712
  };
2706
- this.removeCollateral = function (collateralWithFee, marketSymbol, collateralSymbol, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA) {
2713
+ this.removeCollateral = function (collateralWithFee, marketSymbol, collateralSymbol, side, positionPubKey, poolConfig, createUserATA, closeUsersWSOLATA) {
2707
2714
  if (createUserATA === void 0) { createUserATA = true; }
2708
2715
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
2709
2716
  return __awaiter(_this, void 0, void 0, function () {
2710
- var publicKey, collateralCustodyConfig, marketCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, instruction, closeWsolATAIns, error_3;
2717
+ var publicKey, collateralCustodyConfig, targetCustodyConfig, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lamports, _a, marketAccount, instruction, closeWsolATAIns, error_3;
2711
2718
  return __generator(this, function (_b) {
2712
2719
  switch (_b.label) {
2713
2720
  case 0:
@@ -2715,10 +2722,10 @@ var PerpetualsClient = (function () {
2715
2722
  collateralCustodyConfig = poolConfig.custodies.find(function (i) {
2716
2723
  return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey);
2717
2724
  });
2718
- marketCustodyConfig = poolConfig.custodies.find(function (i) {
2725
+ targetCustodyConfig = poolConfig.custodies.find(function (i) {
2719
2726
  return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey);
2720
2727
  });
2721
- if (!collateralCustodyConfig || !marketCustodyConfig) {
2728
+ if (!collateralCustodyConfig || !targetCustodyConfig) {
2722
2729
  throw "collateralCustodyConfig/marketCustodyConfig not found";
2723
2730
  }
2724
2731
  preInstructions = [];
@@ -2765,31 +2772,31 @@ var PerpetualsClient = (function () {
2765
2772
  preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
2766
2773
  }
2767
2774
  _b.label = 7;
2768
- case 7: return [4, this.program.methods
2769
- .removeCollateral({
2770
- collateralDelta: collateralWithFee,
2771
- })
2772
- .accounts({
2773
- delegate: publicKey,
2774
- owner: publicKey,
2775
- receivingAccount: collateralSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
2776
- transferAuthority: poolConfig.transferAuthority,
2777
- perpetuals: poolConfig.perpetuals,
2778
- pool: poolConfig.poolAddress,
2779
- position: positionPubKey,
2780
- custody: marketCustodyConfig.custodyAccount,
2781
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2782
- custodyCustomOracleAccount: poolConfig.backupOracle,
2783
- collateralCustody: collateralCustodyConfig.custodyAccount,
2784
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2785
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
2786
- collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2787
- eventAuthority: this.eventAuthority.publicKey,
2788
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2789
- program: this.programId,
2790
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2791
- })
2792
- .instruction()];
2775
+ case 7:
2776
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2777
+ return [4, this.program.methods
2778
+ .removeCollateral({
2779
+ collateralDelta: collateralWithFee,
2780
+ })
2781
+ .accounts({
2782
+ owner: publicKey,
2783
+ receivingAccount: collateralSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
2784
+ transferAuthority: poolConfig.transferAuthority,
2785
+ perpetuals: poolConfig.perpetuals,
2786
+ pool: poolConfig.poolAddress,
2787
+ position: positionPubKey,
2788
+ market: marketAccount,
2789
+ targetCustody: targetCustodyConfig.custodyAccount,
2790
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2791
+ collateralCustody: collateralCustodyConfig.custodyAccount,
2792
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2793
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2794
+ eventAuthority: this.eventAuthority.publicKey,
2795
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2796
+ program: this.programId,
2797
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2798
+ })
2799
+ .instruction()];
2793
2800
  case 8:
2794
2801
  instruction = _b.sent();
2795
2802
  instructions.push(instruction);
@@ -2810,15 +2817,16 @@ var PerpetualsClient = (function () {
2810
2817
  });
2811
2818
  });
2812
2819
  };
2813
- this.RemoveCollateralWithSwap = function (marketSymbol, collateralSymbol, outputSymbol, minAmountOut, collateralDelta, side, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
2814
- var publicKey, marketCustodyConfig, collateralCustodyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _a, custody, poolAumInstruction, instruction;
2820
+ this.removeCollateralWithSwap = function (targetSymbol, collateralSymbol, outputSymbol, minAmountOut, collateralDelta, side, swapPoolConfig, positionPoolConfig) { return __awaiter(_this, void 0, void 0, function () {
2821
+ var publicKey, targetCustodyConfig, collateralCustodyConfig, inputCusotdyConfig, outputCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userReceivingTokenAccount, lamports, userCollateralTokenAccount, marketAccount, positionAccount, custodyAccountMetas, custodyOracleAccountMetas, _i, _a, custody, instruction;
2815
2822
  return __generator(this, function (_b) {
2816
2823
  switch (_b.label) {
2817
2824
  case 0:
2818
2825
  publicKey = this.provider.wallet.publicKey;
2819
- marketCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey); });
2820
- collateralCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2821
- outputCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(outputSymbol).mintKey); });
2826
+ targetCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(targetSymbol).mintKey); });
2827
+ collateralCustodyConfig = positionPoolConfig.custodies.find(function (i) { return i.mintKey.equals(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2828
+ inputCusotdyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey); });
2829
+ outputCustodyConfig = swapPoolConfig.custodies.find(function (i) { return i.mintKey.equals(swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey); });
2822
2830
  if (outputCustodyConfig.mintKey.equals(collateralCustodyConfig.mintKey)) {
2823
2831
  throw "Dont use swap, just call remove collateral";
2824
2832
  }
@@ -2847,33 +2855,27 @@ var PerpetualsClient = (function () {
2847
2855
  ];
2848
2856
  additionalSigners.push(wrappedSolAccount);
2849
2857
  return [3, 5];
2850
- case 2: return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(outputSymbol).mintKey, publicKey)];
2858
+ case 2: return [4, (0, spl_token_1.getAssociatedTokenAddress)(swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey, publicKey)];
2851
2859
  case 3:
2852
2860
  userReceivingTokenAccount = _b.sent();
2853
2861
  return [4, (0, utils_1.checkIfAccountExists)(userReceivingTokenAccount, this.provider.connection)];
2854
2862
  case 4:
2855
2863
  if (!(_b.sent())) {
2856
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(outputSymbol).mintKey));
2864
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, swapPoolConfig.getTokenFromSymbol(outputSymbol).mintKey));
2857
2865
  }
2858
2866
  _b.label = 5;
2859
2867
  case 5:
2860
- userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
2868
+ userCollateralTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey, publicKey);
2861
2869
  return [4, (0, utils_1.checkIfAccountExists)(userCollateralTokenAccount, this.provider.connection)];
2862
2870
  case 6:
2863
2871
  if (!(_b.sent())) {
2864
- preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, poolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
2872
+ preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userCollateralTokenAccount, publicKey, positionPoolConfig.getTokenFromSymbol(collateralSymbol).mintKey));
2865
2873
  }
2866
- positionAccount = web3_js_1.PublicKey.findProgramAddressSync([
2867
- Buffer.from("position"),
2868
- publicKey.toBuffer(),
2869
- poolConfig.poolAddress.toBuffer(),
2870
- marketCustodyConfig.custodyAccount.toBuffer(),
2871
- (0, types_1.isVariant)(side, 'long') ? Buffer.from([1]) : Buffer.from([2]),
2872
- ], this.programId)[0];
2874
+ marketAccount = positionPoolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2875
+ positionAccount = positionPoolConfig.getPositionFromMarketPk(publicKey, marketAccount);
2873
2876
  custodyAccountMetas = [];
2874
2877
  custodyOracleAccountMetas = [];
2875
- custodyCustomOracles = [];
2876
- for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
2878
+ for (_i = 0, _a = swapPoolConfig.custodies; _i < _a.length; _i++) {
2877
2879
  custody = _a[_i];
2878
2880
  custodyAccountMetas.push({
2879
2881
  pubkey: custody.custodyAccount,
@@ -2885,57 +2887,41 @@ var PerpetualsClient = (function () {
2885
2887
  isSigner: false,
2886
2888
  isWritable: false,
2887
2889
  });
2888
- custodyCustomOracles.push({
2889
- pubkey: poolConfig.backupOracle,
2890
- isSigner: false,
2891
- isWritable: false,
2892
- });
2893
2890
  }
2894
- return [4, this.program.methods
2895
- .updatePoolAum()
2896
- .accounts({
2897
- payer: publicKey,
2898
- perpetuals: poolConfig.perpetuals,
2899
- pool: poolConfig.poolAddress,
2900
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2901
- })
2902
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
2903
- .instruction()];
2904
- case 7:
2905
- poolAumInstruction = _b.sent();
2906
- preInstructions.push(poolAumInstruction);
2907
2891
  return [4, this.programPerpComposability.methods
2908
2892
  .removeCollateralAndSwap({
2909
2893
  minAmountOut: minAmountOut,
2910
2894
  collateralDelta: collateralDelta,
2911
2895
  })
2912
2896
  .accounts({
2913
- delegate: publicKey,
2897
+ perpProgram: this.programId,
2914
2898
  owner: publicKey,
2915
2899
  fundingAccount: userCollateralTokenAccount,
2916
2900
  receivingAccount: outputSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
2917
- transferAuthority: poolConfig.transferAuthority,
2918
- perpetuals: poolConfig.perpetuals,
2919
- pool: poolConfig.poolAddress,
2920
- receivingCustody: collateralCustodyConfig.custodyAccount,
2921
- receivingCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2922
- receivingCustodyCustomOracleAccount: poolConfig.backupOracle,
2923
- receivingCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2901
+ transferAuthority: swapPoolConfig.transferAuthority,
2902
+ perpetuals: swapPoolConfig.perpetuals,
2903
+ swapPool: swapPoolConfig.poolAddress,
2904
+ receivingCustody: inputCusotdyConfig.custodyAccount,
2905
+ receivingCustodyOracleAccount: inputCusotdyConfig.oracleAddress,
2906
+ receivingCustodyTokenAccount: inputCusotdyConfig.tokenAccount,
2924
2907
  dispensingCustody: outputCustodyConfig.custodyAccount,
2925
2908
  dispensingCustodyOracleAccount: outputCustodyConfig.oracleAddress,
2926
- dispensingCustodyCustomOracleAccount: poolConfig.backupOracle,
2927
2909
  dispensingCustodyTokenAccount: outputCustodyConfig.tokenAccount,
2910
+ positionPool: positionPoolConfig.poolAddress,
2928
2911
  position: positionAccount,
2929
- custody: marketCustodyConfig.custodyAccount,
2930
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2931
- custodyCustomOracleAccount: poolConfig.backupOracle,
2912
+ market: marketAccount,
2913
+ targetCustody: targetCustodyConfig.custodyAccount,
2914
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2915
+ collateralCustody: collateralCustodyConfig.custodyAccount,
2916
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2917
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2932
2918
  eventAuthority: this.eventAuthority.publicKey,
2933
2919
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2934
- perpProgram: this.programId,
2935
2920
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2936
2921
  })
2922
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true))
2937
2923
  .instruction()];
2938
- case 8:
2924
+ case 7:
2939
2925
  instruction = _b.sent();
2940
2926
  instructions.push(instruction);
2941
2927
  return [2, {
@@ -2945,8 +2931,8 @@ var PerpetualsClient = (function () {
2945
2931
  }
2946
2932
  });
2947
2933
  }); };
2948
- this.increaseSize = function (marketSymbol, collateralSymbol, positionPubKey, poolConfig, price, sizeDelta) { return __awaiter(_this, void 0, void 0, function () {
2949
- var publicKey, collateralCustodyConfig, marketCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, params, instruction;
2934
+ this.increaseSize = function (targetSymbol, collateralSymbol, positionPubKey, side, poolConfig, priceWithSlippage, sizeDelta, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege) { return __awaiter(_this, void 0, void 0, function () {
2935
+ var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
2950
2936
  return __generator(this, function (_a) {
2951
2937
  switch (_a.label) {
2952
2938
  case 0:
@@ -2954,38 +2940,41 @@ var PerpetualsClient = (function () {
2954
2940
  collateralCustodyConfig = poolConfig.custodies.find(function (i) {
2955
2941
  return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey);
2956
2942
  });
2957
- marketCustodyConfig = poolConfig.custodies.find(function (i) {
2958
- return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey);
2943
+ targetCustodyConfig = poolConfig.custodies.find(function (i) {
2944
+ return i.mintKey.equals(poolConfig.getTokenFromSymbol(targetSymbol).mintKey);
2959
2945
  });
2960
- if (!collateralCustodyConfig || !marketCustodyConfig) {
2946
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
2947
+ if (!collateralCustodyConfig || !targetCustodyConfig) {
2961
2948
  throw "collateralCustodyConfig/marketCustodyConfig not found";
2962
2949
  }
2963
2950
  preInstructions = [];
2964
2951
  instructions = [];
2965
2952
  postInstructions = [];
2966
2953
  additionalSigners = [];
2967
- params = {
2968
- price: price,
2969
- sizeDelta: sizeDelta
2970
- };
2971
2954
  return [4, this.program.methods
2972
- .increaseSize(params)
2955
+ .increaseSize({
2956
+ priceWithSlippage: priceWithSlippage,
2957
+ sizeDelta: sizeDelta,
2958
+ privilege: privilege
2959
+ })
2973
2960
  .accounts({
2974
- delegate: publicKey,
2975
2961
  owner: publicKey,
2962
+ transferAuthority: poolConfig.transferAuthority,
2976
2963
  perpetuals: poolConfig.perpetuals,
2977
2964
  pool: poolConfig.poolAddress,
2978
2965
  position: positionPubKey,
2979
- custody: marketCustodyConfig.custodyAccount,
2980
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
2981
- custodyCustomOracleAccount: poolConfig.backupOracle,
2966
+ market: marketAccount,
2967
+ targetCustody: targetCustodyConfig.custodyAccount,
2968
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
2982
2969
  collateralCustody: collateralCustodyConfig.custodyAccount,
2983
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
2984
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
2970
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
2971
+ collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
2972
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2985
2973
  eventAuthority: this.eventAuthority.publicKey,
2986
2974
  program: this.programId,
2987
2975
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
2988
2976
  })
2977
+ .remainingAccounts(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true))
2989
2978
  .instruction()];
2990
2979
  case 1:
2991
2980
  instruction = _a.sent();
@@ -2997,8 +2986,8 @@ var PerpetualsClient = (function () {
2997
2986
  }
2998
2987
  });
2999
2988
  }); };
3000
- this.decreaseSize = function (marketSymbol, collateralSymbol, positionPubKey, poolConfig, priceAfterSlippage, sizeDelta) { return __awaiter(_this, void 0, void 0, function () {
3001
- var publicKey, collateralCustodyConfig, marketCustodyConfig, preInstructions, instructions, postInstructions, additionalSigners, params, instruction;
2989
+ this.decreaseSize = function (targetSymbol, collateralSymbol, side, positionPubKey, poolConfig, priceWithSlippage, sizeDelta, nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege) { return __awaiter(_this, void 0, void 0, function () {
2990
+ var publicKey, collateralCustodyConfig, targetCustodyConfig, marketAccount, preInstructions, instructions, postInstructions, additionalSigners, instruction;
3002
2991
  return __generator(this, function (_a) {
3003
2992
  switch (_a.label) {
3004
2993
  case 0:
@@ -3006,39 +2995,41 @@ var PerpetualsClient = (function () {
3006
2995
  collateralCustodyConfig = poolConfig.custodies.find(function (i) {
3007
2996
  return i.mintKey.equals(poolConfig.getTokenFromSymbol(collateralSymbol).mintKey);
3008
2997
  });
3009
- marketCustodyConfig = poolConfig.custodies.find(function (i) {
3010
- return i.mintKey.equals(poolConfig.getTokenFromSymbol(marketSymbol).mintKey);
2998
+ targetCustodyConfig = poolConfig.custodies.find(function (i) {
2999
+ return i.mintKey.equals(poolConfig.getTokenFromSymbol(targetSymbol).mintKey);
3011
3000
  });
3012
- if (!collateralCustodyConfig || !marketCustodyConfig) {
3001
+ marketAccount = poolConfig.getMarketPk(targetCustodyConfig.custodyAccount, collateralCustodyConfig.custodyAccount, side);
3002
+ if (!collateralCustodyConfig || !targetCustodyConfig) {
3013
3003
  throw "collateralCustodyConfig/marketCustodyConfig not found";
3014
3004
  }
3015
3005
  preInstructions = [];
3016
3006
  instructions = [];
3017
3007
  postInstructions = [];
3018
3008
  additionalSigners = [];
3019
- params = {
3020
- price: priceAfterSlippage,
3021
- sizeDelta: sizeDelta
3022
- };
3023
3009
  return [4, this.program.methods
3024
- .decreaseSize(params)
3010
+ .decreaseSize({
3011
+ priceWithSlippage: priceWithSlippage,
3012
+ sizeDelta: sizeDelta,
3013
+ privilege: privilege
3014
+ })
3025
3015
  .accounts({
3026
- delegate: publicKey,
3027
3016
  owner: publicKey,
3017
+ transferAuthority: poolConfig.transferAuthority,
3028
3018
  perpetuals: poolConfig.perpetuals,
3029
3019
  pool: poolConfig.poolAddress,
3030
3020
  position: positionPubKey,
3031
- custody: marketCustodyConfig.custodyAccount,
3032
- custodyOracleAccount: marketCustodyConfig.oracleAddress,
3033
- custodyCustomOracleAccount: poolConfig.backupOracle,
3021
+ market: marketAccount,
3022
+ targetCustody: targetCustodyConfig.custodyAccount,
3023
+ targetOracleAccount: targetCustodyConfig.oracleAddress,
3034
3024
  collateralCustody: collateralCustodyConfig.custodyAccount,
3035
- collateralCustodyOracleAccount: collateralCustodyConfig.oracleAddress,
3036
- collateralCustodyCustomOracleAccount: poolConfig.backupOracle,
3025
+ collateralOracleAccount: collateralCustodyConfig.oracleAddress,
3037
3026
  collateralCustodyTokenAccount: collateralCustodyConfig.tokenAccount,
3027
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3038
3028
  eventAuthority: this.eventAuthority.publicKey,
3039
3029
  program: this.programId,
3040
3030
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
3041
3031
  })
3032
+ .remainingAccounts(__spreadArray([], (0, getNftAccounts_1.getNftAccounts)(nftTradingAccount, nftReferralAccount, nftRebateTokenAccount, privilege), true))
3042
3033
  .instruction()];
3043
3034
  case 1:
3044
3035
  instruction = _a.sent();
@@ -3053,9 +3044,9 @@ var PerpetualsClient = (function () {
3053
3044
  this.addLiquidity = function (payTokenSymbol, tokenAmountIn, minLpAmountOut, poolConfig, skipBalanceChecks) {
3054
3045
  if (skipBalanceChecks === void 0) { skipBalanceChecks = false; }
3055
3046
  return __awaiter(_this, void 0, void 0, function () {
3056
- var publicKey, payTokenCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userPayingTokenAccount, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _a, custody, accCreationLamports, lamports, unWrappedSolBalance, _b, tokenAccountBalance, _c, poolAumInstruction, instruction, err_3;
3057
- return __generator(this, function (_d) {
3058
- switch (_d.label) {
3047
+ var publicKey, payTokenCustodyConfig, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, userPayingTokenAccount, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, accCreationLamports, lamports, unWrappedSolBalance, _d, tokenAccountBalance, _e, instruction, err_3;
3048
+ return __generator(this, function (_f) {
3049
+ switch (_f.label) {
3059
3050
  case 0:
3060
3051
  publicKey = this.provider.wallet.publicKey;
3061
3052
  payTokenCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(payTokenSymbol).mintKey); });
@@ -3066,18 +3057,18 @@ var PerpetualsClient = (function () {
3066
3057
  instructions = [];
3067
3058
  postInstructions = [];
3068
3059
  additionalSigners = [];
3069
- _d.label = 1;
3060
+ _f.label = 1;
3070
3061
  case 1:
3071
- _d.trys.push([1, 13, , 14]);
3062
+ _f.trys.push([1, 12, , 13]);
3072
3063
  return [4, (0, spl_token_1.getAssociatedTokenAddress)(payTokenCustodyConfig.mintKey, publicKey)];
3073
3064
  case 2:
3074
- userPayingTokenAccount = _d.sent();
3065
+ userPayingTokenAccount = _f.sent();
3075
3066
  return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
3076
3067
  case 3:
3077
- lpTokenAccount = _d.sent();
3068
+ lpTokenAccount = _f.sent();
3078
3069
  custodyAccountMetas = [];
3079
3070
  custodyOracleAccountMetas = [];
3080
- custodyCustomOracles = [];
3071
+ markets = [];
3081
3072
  for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
3082
3073
  custody = _a[_i];
3083
3074
  custodyAccountMetas.push({
@@ -3090,15 +3081,18 @@ var PerpetualsClient = (function () {
3090
3081
  isSigner: false,
3091
3082
  isWritable: false,
3092
3083
  });
3093
- custodyCustomOracles.push({
3094
- pubkey: poolConfig.backupOracle,
3084
+ }
3085
+ for (_b = 0, _c = poolConfig.markets; _b < _c.length; _b++) {
3086
+ market = _c[_b];
3087
+ markets.push({
3088
+ pubkey: market.marketAccount,
3095
3089
  isSigner: false,
3096
3090
  isWritable: false,
3097
3091
  });
3098
3092
  }
3099
3093
  return [4, (0, utils_1.checkIfAccountExists)(lpTokenAccount, this.provider.connection)];
3100
3094
  case 4:
3101
- if (!(_d.sent())) {
3095
+ if (!(_f.sent())) {
3102
3096
  instructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, lpTokenAccount, publicKey, poolConfig.lpTokenMint));
3103
3097
  }
3104
3098
  if (!(payTokenSymbol == 'SOL')) return [3, 7];
@@ -3106,13 +3100,13 @@ var PerpetualsClient = (function () {
3106
3100
  wrappedSolAccount = new web3_js_1.Keypair();
3107
3101
  return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
3108
3102
  case 5:
3109
- accCreationLamports = (_d.sent());
3103
+ accCreationLamports = (_f.sent());
3110
3104
  console.log("accCreationLamports:", accCreationLamports);
3111
3105
  lamports = tokenAmountIn.add(new anchor_1.BN(accCreationLamports));
3112
- _b = anchor_1.BN.bind;
3106
+ _d = anchor_1.BN.bind;
3113
3107
  return [4, this.provider.connection.getBalance(publicKey)];
3114
3108
  case 6:
3115
- unWrappedSolBalance = new (_b.apply(anchor_1.BN, [void 0, _d.sent()]))();
3109
+ unWrappedSolBalance = new (_d.apply(anchor_1.BN, [void 0, _f.sent()]))();
3116
3110
  if (unWrappedSolBalance.lt(lamports)) {
3117
3111
  throw "Insufficient SOL Funds";
3118
3112
  }
@@ -3133,64 +3127,50 @@ var PerpetualsClient = (function () {
3133
3127
  return [3, 10];
3134
3128
  case 7: return [4, (0, utils_1.checkIfAccountExists)(userPayingTokenAccount, this.provider.connection)];
3135
3129
  case 8:
3136
- if (!(_d.sent())) {
3130
+ if (!(_f.sent())) {
3137
3131
  throw "Insufficient Funds , token Account doesn't exist";
3138
3132
  }
3139
3133
  if (!!skipBalanceChecks) return [3, 10];
3140
- _c = anchor_1.BN.bind;
3134
+ _e = anchor_1.BN.bind;
3141
3135
  return [4, this.provider.connection.getTokenAccountBalance(userPayingTokenAccount)];
3142
3136
  case 9:
3143
- tokenAccountBalance = new (_c.apply(anchor_1.BN, [void 0, (_d.sent()).value.amount]))();
3137
+ tokenAccountBalance = new (_e.apply(anchor_1.BN, [void 0, (_f.sent()).value.amount]))();
3144
3138
  if (tokenAccountBalance.lt(tokenAmountIn)) {
3145
3139
  throw "Insufficient Funds need more ".concat(tokenAmountIn.sub(tokenAccountBalance), " tokens");
3146
3140
  }
3147
- _d.label = 10;
3141
+ _f.label = 10;
3148
3142
  case 10: return [4, this.program.methods
3149
- .updatePoolAum()
3143
+ .addLiquidity({
3144
+ amountIn: tokenAmountIn,
3145
+ minLpAmountOut: minLpAmountOut
3146
+ })
3150
3147
  .accounts({
3151
- payer: publicKey,
3148
+ owner: publicKey,
3149
+ fundingAccount: payTokenSymbol == 'SOL' ? wrappedSolAccount.publicKey : userPayingTokenAccount,
3150
+ lpTokenAccount: lpTokenAccount,
3151
+ transferAuthority: poolConfig.transferAuthority,
3152
3152
  perpetuals: poolConfig.perpetuals,
3153
3153
  pool: poolConfig.poolAddress,
3154
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3154
+ custody: payTokenCustodyConfig.custodyAccount,
3155
+ custodyOracleAccount: payTokenCustodyConfig.oracleAddress,
3156
+ custodyTokenAccount: payTokenCustodyConfig.tokenAccount,
3157
+ lpTokenMint: poolConfig.lpTokenMint,
3158
+ eventAuthority: this.eventAuthority.publicKey,
3159
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3160
+ program: this.programId,
3161
+ ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
3155
3162
  })
3156
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
3163
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), markets, true))
3157
3164
  .instruction()];
3158
3165
  case 11:
3159
- poolAumInstruction = _d.sent();
3160
- preInstructions.push(poolAumInstruction);
3161
- return [4, this.program.methods
3162
- .addLiquidity({
3163
- amountIn: tokenAmountIn,
3164
- minLpAmountOut: minLpAmountOut
3165
- })
3166
- .accounts({
3167
- delegate: publicKey,
3168
- owner: publicKey,
3169
- fundingAccount: payTokenSymbol == 'SOL' ? wrappedSolAccount.publicKey : userPayingTokenAccount,
3170
- lpTokenAccount: lpTokenAccount,
3171
- transferAuthority: poolConfig.transferAuthority,
3172
- perpetuals: poolConfig.perpetuals,
3173
- pool: poolConfig.poolAddress,
3174
- custody: payTokenCustodyConfig.custodyAccount,
3175
- custodyOracleAccount: payTokenCustodyConfig.oracleAddress,
3176
- custodyCustomOracleAccount: poolConfig.backupOracle,
3177
- custodyTokenAccount: payTokenCustodyConfig.tokenAccount,
3178
- lpTokenMint: poolConfig.lpTokenMint,
3179
- eventAuthority: this.eventAuthority.publicKey,
3180
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3181
- program: this.programId,
3182
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
3183
- })
3184
- .instruction()];
3185
- case 12:
3186
- instruction = _d.sent();
3166
+ instruction = _f.sent();
3187
3167
  instructions.push(instruction);
3188
- return [3, 14];
3189
- case 13:
3190
- err_3 = _d.sent();
3168
+ return [3, 13];
3169
+ case 12:
3170
+ err_3 = _f.sent();
3191
3171
  console.error("perpClient addLiquidity error:: ", err_3);
3192
3172
  throw err_3;
3193
- case 14: return [2, {
3173
+ case 13: return [2, {
3194
3174
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3195
3175
  additionalSigners: additionalSigners
3196
3176
  }];
@@ -3203,9 +3183,9 @@ var PerpetualsClient = (function () {
3203
3183
  if (createUserATA === void 0) { createUserATA = true; }
3204
3184
  if (closeUsersWSOLATA === void 0) { closeUsersWSOLATA = false; }
3205
3185
  return __awaiter(_this, void 0, void 0, function () {
3206
- var recieveTokenCustodyConfig, publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, custodyCustomOracles, _i, _a, custody, lamports, _b, poolAumInstruction, removeLiquidityTx, closeInx, closeWsolATAIns, err_4;
3207
- return __generator(this, function (_c) {
3208
- switch (_c.label) {
3186
+ var recieveTokenCustodyConfig, publicKey, userReceivingTokenAccount, wrappedSolAccount, preInstructions, instructions, postInstructions, additionalSigners, lpTokenAccount, custodyAccountMetas, custodyOracleAccountMetas, markets, _i, _a, custody, _b, _c, market, lamports, _d, removeLiquidityTx, closeInx, closeWsolATAIns, err_4;
3187
+ return __generator(this, function (_e) {
3188
+ switch (_e.label) {
3209
3189
  case 0:
3210
3190
  recieveTokenCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(recieveTokenSymbol).mintKey); });
3211
3191
  if (!recieveTokenCustodyConfig) {
@@ -3216,15 +3196,15 @@ var PerpetualsClient = (function () {
3216
3196
  instructions = [];
3217
3197
  postInstructions = [];
3218
3198
  additionalSigners = [];
3219
- _c.label = 1;
3199
+ _e.label = 1;
3220
3200
  case 1:
3221
- _c.trys.push([1, 11, , 12]);
3201
+ _e.trys.push([1, 10, , 11]);
3222
3202
  return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
3223
3203
  case 2:
3224
- lpTokenAccount = _c.sent();
3204
+ lpTokenAccount = _e.sent();
3225
3205
  custodyAccountMetas = [];
3226
3206
  custodyOracleAccountMetas = [];
3227
- custodyCustomOracles = [];
3207
+ markets = [];
3228
3208
  for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
3229
3209
  custody = _a[_i];
3230
3210
  custodyAccountMetas.push({
@@ -3237,8 +3217,11 @@ var PerpetualsClient = (function () {
3237
3217
  isSigner: false,
3238
3218
  isWritable: false,
3239
3219
  });
3240
- custodyCustomOracles.push({
3241
- pubkey: poolConfig.backupOracle,
3220
+ }
3221
+ for (_b = 0, _c = poolConfig.markets; _b < _c.length; _b++) {
3222
+ market = _c[_b];
3223
+ markets.push({
3224
+ pubkey: market.marketAccount,
3242
3225
  isSigner: false,
3243
3226
  isWritable: false,
3244
3227
  });
@@ -3248,7 +3231,7 @@ var PerpetualsClient = (function () {
3248
3231
  userReceivingTokenAccount = wrappedSolAccount.publicKey;
3249
3232
  return [4, (0, spl_token_1.getMinimumBalanceForRentExemptAccount)(this.provider.connection)];
3250
3233
  case 3:
3251
- lamports = (_c.sent());
3234
+ lamports = (_e.sent());
3252
3235
  preInstructions = [
3253
3236
  web3_js_1.SystemProgram.createAccount({
3254
3237
  fromPubkey: publicKey,
@@ -3266,31 +3249,19 @@ var PerpetualsClient = (function () {
3266
3249
  return [3, 8];
3267
3250
  case 4: return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.getTokenFromSymbol(recieveTokenSymbol).mintKey, publicKey)];
3268
3251
  case 5:
3269
- userReceivingTokenAccount = _c.sent();
3270
- _b = createUserATA;
3271
- if (!_b) return [3, 7];
3252
+ userReceivingTokenAccount = _e.sent();
3253
+ _d = createUserATA;
3254
+ if (!_d) return [3, 7];
3272
3255
  return [4, (0, utils_1.checkIfAccountExists)(userReceivingTokenAccount, this.provider.connection)];
3273
3256
  case 6:
3274
- _b = !(_c.sent());
3275
- _c.label = 7;
3257
+ _d = !(_e.sent());
3258
+ _e.label = 7;
3276
3259
  case 7:
3277
- if (_b) {
3260
+ if (_d) {
3278
3261
  preInstructions.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(publicKey, userReceivingTokenAccount, publicKey, poolConfig.getTokenFromSymbol(recieveTokenSymbol).mintKey));
3279
3262
  }
3280
- _c.label = 8;
3281
- case 8: return [4, this.program.methods
3282
- .updatePoolAum()
3283
- .accounts({
3284
- payer: publicKey,
3285
- perpetuals: poolConfig.perpetuals,
3286
- pool: poolConfig.poolAddress,
3287
- ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
3288
- })
3289
- .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), custodyCustomOracles, true))
3290
- .instruction()];
3291
- case 9:
3292
- poolAumInstruction = _c.sent();
3293
- preInstructions.push(poolAumInstruction);
3263
+ _e.label = 8;
3264
+ case 8:
3294
3265
  console.log("liquidityAmountIn", liquidityAmountIn.toString());
3295
3266
  return [4, this.program.methods
3296
3267
  .removeLiquidity({
@@ -3298,7 +3269,6 @@ var PerpetualsClient = (function () {
3298
3269
  minAmountOut: minTokenAmountOut
3299
3270
  })
3300
3271
  .accounts({
3301
- delegate: publicKey,
3302
3272
  owner: publicKey,
3303
3273
  receivingAccount: recieveTokenSymbol == 'SOL' ? wrappedSolAccount.publicKey : userReceivingTokenAccount,
3304
3274
  lpTokenAccount: lpTokenAccount,
@@ -3307,7 +3277,6 @@ var PerpetualsClient = (function () {
3307
3277
  pool: poolConfig.poolAddress,
3308
3278
  custody: recieveTokenCustodyConfig.custodyAccount,
3309
3279
  custodyOracleAccount: recieveTokenCustodyConfig.oracleAddress,
3310
- custodyCustomOracleAccount: poolConfig.backupOracle,
3311
3280
  custodyTokenAccount: recieveTokenCustodyConfig.tokenAccount,
3312
3281
  lpTokenMint: poolConfig.lpTokenMint,
3313
3282
  eventAuthority: this.eventAuthority.publicKey,
@@ -3315,9 +3284,10 @@ var PerpetualsClient = (function () {
3315
3284
  program: this.programId,
3316
3285
  ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY
3317
3286
  })
3287
+ .remainingAccounts(__spreadArray(__spreadArray(__spreadArray([], custodyAccountMetas, true), custodyOracleAccountMetas, true), markets, true))
3318
3288
  .instruction()];
3319
- case 10:
3320
- removeLiquidityTx = _c.sent();
3289
+ case 9:
3290
+ removeLiquidityTx = _e.sent();
3321
3291
  instructions.push(removeLiquidityTx);
3322
3292
  if (closeLpATA) {
3323
3293
  closeInx = (0, spl_token_1.createCloseAccountInstruction)(lpTokenAccount, publicKey, publicKey);
@@ -3327,12 +3297,12 @@ var PerpetualsClient = (function () {
3327
3297
  closeWsolATAIns = (0, spl_token_1.createCloseAccountInstruction)(userReceivingTokenAccount, publicKey, publicKey);
3328
3298
  postInstructions.push(closeWsolATAIns);
3329
3299
  }
3330
- return [3, 12];
3331
- case 11:
3332
- err_4 = _c.sent();
3300
+ return [3, 11];
3301
+ case 10:
3302
+ err_4 = _e.sent();
3333
3303
  console.log("perpClient removeLiquidity error:: ", err_4);
3334
3304
  throw err_4;
3335
- case 12: return [2, {
3305
+ case 11: return [2, {
3336
3306
  instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3337
3307
  additionalSigners: additionalSigners
3338
3308
  }];
@@ -3340,6 +3310,574 @@ var PerpetualsClient = (function () {
3340
3310
  });
3341
3311
  });
3342
3312
  };
3313
+ this.addReferral = function (nftTradingAccount, nftReferralAccount) { return __awaiter(_this, void 0, void 0, function () {
3314
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, addReferralInstruction, err_5;
3315
+ return __generator(this, function (_a) {
3316
+ switch (_a.label) {
3317
+ case 0:
3318
+ publicKey = this.provider.wallet.publicKey;
3319
+ preInstructions = [];
3320
+ instructions = [];
3321
+ postInstructions = [];
3322
+ additionalSigners = [];
3323
+ _a.label = 1;
3324
+ case 1:
3325
+ _a.trys.push([1, 3, , 4]);
3326
+ return [4, this.program.methods
3327
+ .createReferral({})
3328
+ .accounts({
3329
+ owner: publicKey,
3330
+ feePayer: publicKey,
3331
+ referralAccount: nftReferralAccount,
3332
+ tradingAccount: nftTradingAccount,
3333
+ systemProgram: web3_js_1.SystemProgram.programId,
3334
+ })
3335
+ .instruction()];
3336
+ case 2:
3337
+ addReferralInstruction = _a.sent();
3338
+ instructions.push(addReferralInstruction);
3339
+ return [3, 4];
3340
+ case 3:
3341
+ err_5 = _a.sent();
3342
+ console.log("perpClient addReferral error:: ", err_5);
3343
+ throw err_5;
3344
+ case 4: return [2, {
3345
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3346
+ additionalSigners: additionalSigners
3347
+ }];
3348
+ }
3349
+ });
3350
+ }); };
3351
+ this.createNftTradingAccount = function (nftMint, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3352
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, nftTokenAccount, createNftTradingAccountInstruction, err_6;
3353
+ return __generator(this, function (_a) {
3354
+ switch (_a.label) {
3355
+ case 0:
3356
+ publicKey = this.provider.wallet.publicKey;
3357
+ preInstructions = [];
3358
+ instructions = [];
3359
+ postInstructions = [];
3360
+ additionalSigners = [];
3361
+ _a.label = 1;
3362
+ case 1:
3363
+ _a.trys.push([1, 4, , 5]);
3364
+ nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
3365
+ Buffer.from("trading"),
3366
+ nftMint.toBuffer(),
3367
+ ], this.programId)[0];
3368
+ metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
3369
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey)];
3370
+ case 2:
3371
+ nftTokenAccount = _a.sent();
3372
+ return [4, this.program.methods
3373
+ .createTradingAccount({
3374
+ collectionIndex: 0
3375
+ })
3376
+ .accounts({
3377
+ feePayer: publicKey,
3378
+ perpetuals: poolConfig.perpetuals,
3379
+ nftMint: nftMint,
3380
+ nftTokenAccount: nftTokenAccount,
3381
+ tradingAccount: nftTradingAccount,
3382
+ metadataAccount: metadataAccount,
3383
+ systemProgram: web3_js_1.SystemProgram.programId
3384
+ })
3385
+ .instruction()];
3386
+ case 3:
3387
+ createNftTradingAccountInstruction = _a.sent();
3388
+ instructions.push(createNftTradingAccountInstruction);
3389
+ return [3, 5];
3390
+ case 4:
3391
+ err_6 = _a.sent();
3392
+ console.log("perpClient createNftAccount error:: ", err_6);
3393
+ throw err_6;
3394
+ case 5: return [2, {
3395
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3396
+ additionalSigners: additionalSigners
3397
+ }];
3398
+ }
3399
+ });
3400
+ }); };
3401
+ this.updateNftAccount = function (nftMint) { return __awaiter(_this, void 0, void 0, function () {
3402
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, nftReferralAccount, nftTokenAccount, updateNftTradingAccountInstruction, err_7;
3403
+ return __generator(this, function (_a) {
3404
+ switch (_a.label) {
3405
+ case 0:
3406
+ publicKey = this.provider.wallet.publicKey;
3407
+ preInstructions = [];
3408
+ instructions = [];
3409
+ postInstructions = [];
3410
+ additionalSigners = [];
3411
+ _a.label = 1;
3412
+ case 1:
3413
+ _a.trys.push([1, 4, , 5]);
3414
+ nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
3415
+ Buffer.from("trading"),
3416
+ nftMint.toBuffer(),
3417
+ ], this.programId)[0];
3418
+ nftReferralAccount = web3_js_1.PublicKey.findProgramAddressSync([
3419
+ Buffer.from("referral"),
3420
+ publicKey.toBuffer(),
3421
+ ], this.programId)[0];
3422
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(nftMint, publicKey)];
3423
+ case 2:
3424
+ nftTokenAccount = _a.sent();
3425
+ return [4, this.program.methods
3426
+ .updateTradingAccount({})
3427
+ .accounts({
3428
+ owner: publicKey,
3429
+ feePayer: publicKey,
3430
+ nftTokenAccount: nftTokenAccount,
3431
+ referralAccount: nftReferralAccount,
3432
+ tradingAccount: nftTradingAccount
3433
+ })
3434
+ .instruction()];
3435
+ case 3:
3436
+ updateNftTradingAccountInstruction = _a.sent();
3437
+ instructions.push(updateNftTradingAccountInstruction);
3438
+ return [3, 5];
3439
+ case 4:
3440
+ err_7 = _a.sent();
3441
+ console.log("perpClient updateNftAccount error:: ", err_7);
3442
+ throw err_7;
3443
+ case 5: return [2, {
3444
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3445
+ additionalSigners: additionalSigners
3446
+ }];
3447
+ }
3448
+ });
3449
+ }); };
3450
+ this.levelUp = function (poolConfig, nftMint) { return __awaiter(_this, void 0, void 0, function () {
3451
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, nftTradingAccount, metadataAccount, levelUpInstruction, err_8;
3452
+ return __generator(this, function (_a) {
3453
+ switch (_a.label) {
3454
+ case 0:
3455
+ publicKey = this.provider.wallet.publicKey;
3456
+ preInstructions = [];
3457
+ instructions = [];
3458
+ postInstructions = [];
3459
+ additionalSigners = [];
3460
+ _a.label = 1;
3461
+ case 1:
3462
+ _a.trys.push([1, 3, , 4]);
3463
+ nftTradingAccount = web3_js_1.PublicKey.findProgramAddressSync([
3464
+ Buffer.from("trading"),
3465
+ nftMint.toBuffer(),
3466
+ ], this.programId)[0];
3467
+ metadataAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("metadata"), constants_1.METAPLEX_PROGRAM_ID.toBuffer(), nftMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
3468
+ return [4, this.program.methods
3469
+ .levelUp({})
3470
+ .accounts({
3471
+ owner: publicKey,
3472
+ perpetuals: this.perpetuals.publicKey,
3473
+ pool: poolConfig.poolAddress,
3474
+ metadataAccount: metadataAccount,
3475
+ metadataProgram: constants_1.METAPLEX_PROGRAM_ID,
3476
+ tradingAccount: nftTradingAccount,
3477
+ transferAuthority: this.authority.publicKey,
3478
+ })
3479
+ .instruction()];
3480
+ case 2:
3481
+ levelUpInstruction = _a.sent();
3482
+ instructions.push(levelUpInstruction);
3483
+ return [3, 4];
3484
+ case 3:
3485
+ err_8 = _a.sent();
3486
+ console.log("perpClient levelUp error:: ", err_8);
3487
+ throw err_8;
3488
+ case 4: return [2, {
3489
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3490
+ additionalSigners: additionalSigners
3491
+ }];
3492
+ }
3493
+ });
3494
+ }); };
3495
+ this.initStake = function (rewardSymbol, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3496
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, stakedLpTokenAccount, rewardCustodyConfig, initStakeInstruction, err_9;
3497
+ return __generator(this, function (_a) {
3498
+ switch (_a.label) {
3499
+ case 0:
3500
+ publicKey = this.provider.wallet.publicKey;
3501
+ preInstructions = [];
3502
+ instructions = [];
3503
+ postInstructions = [];
3504
+ additionalSigners = [];
3505
+ _a.label = 1;
3506
+ case 1:
3507
+ _a.trys.push([1, 3, , 4]);
3508
+ lpTokenMint = poolConfig.lpTokenMint;
3509
+ stakedLpTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("staked_lp_token_account"), poolConfig.poolAddress.toBuffer(), lpTokenMint.toBuffer()], this.programId)[0];
3510
+ rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
3511
+ return [4, this.program.methods
3512
+ .initStaking({})
3513
+ .accounts({
3514
+ admin: publicKey,
3515
+ multisig: this.multisig.publicKey,
3516
+ transferAuthority: poolConfig.transferAuthority,
3517
+ perpetuals: this.perpetuals.publicKey,
3518
+ pool: poolConfig.poolAddress,
3519
+ custody: rewardCustodyConfig.custodyAccount,
3520
+ lpTokenMint: lpTokenMint,
3521
+ stakedLpTokenAccount: stakedLpTokenAccount,
3522
+ systemProgram: web3_js_1.SystemProgram.programId,
3523
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3524
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY
3525
+ })
3526
+ .instruction()];
3527
+ case 2:
3528
+ initStakeInstruction = _a.sent();
3529
+ instructions.push(initStakeInstruction);
3530
+ return [3, 4];
3531
+ case 3:
3532
+ err_9 = _a.sent();
3533
+ console.log("perpClient InitStaking error:: ", err_9);
3534
+ throw err_9;
3535
+ case 4: return [2, {
3536
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3537
+ additionalSigners: additionalSigners
3538
+ }];
3539
+ }
3540
+ });
3541
+ }); };
3542
+ this.depositStake = function (depositAmount, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3543
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, poolFlpTokenAccount, flpStakeAccount, userLpTokenAccount, depositStakeInstruction, err_10;
3544
+ return __generator(this, function (_a) {
3545
+ switch (_a.label) {
3546
+ case 0:
3547
+ publicKey = this.provider.wallet.publicKey;
3548
+ preInstructions = [];
3549
+ instructions = [];
3550
+ postInstructions = [];
3551
+ additionalSigners = [];
3552
+ _a.label = 1;
3553
+ case 1:
3554
+ _a.trys.push([1, 4, , 5]);
3555
+ lpTokenMint = poolConfig.lpTokenMint;
3556
+ poolFlpTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("staked_lp_token_account"), poolConfig.poolAddress.toBuffer(), lpTokenMint.toBuffer()], this.programId)[0];
3557
+ flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), poolConfig.poolAddress.toBuffer()], this.programId)[0];
3558
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
3559
+ case 2:
3560
+ userLpTokenAccount = _a.sent();
3561
+ return [4, this.program.methods
3562
+ .depositStake({
3563
+ depositAmount: depositAmount
3564
+ })
3565
+ .accounts({
3566
+ owner: publicKey,
3567
+ feePayer: publicKey,
3568
+ fundingFlpTokenAccount: userLpTokenAccount,
3569
+ transferAuthority: poolConfig.transferAuthority,
3570
+ perpetuals: this.perpetuals.publicKey,
3571
+ pool: poolConfig.poolAddress,
3572
+ flpStakeAccount: flpStakeAccount,
3573
+ poolFlpTokenAccount: poolFlpTokenAccount,
3574
+ systemProgram: web3_js_1.SystemProgram.programId,
3575
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3576
+ eventAuthority: this.eventAuthority.publicKey,
3577
+ })
3578
+ .instruction()];
3579
+ case 3:
3580
+ depositStakeInstruction = _a.sent();
3581
+ instructions.push(depositStakeInstruction);
3582
+ return [3, 5];
3583
+ case 4:
3584
+ err_10 = _a.sent();
3585
+ console.log("perpClient depositStaking error:: ", err_10);
3586
+ throw err_10;
3587
+ case 5: return [2, {
3588
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3589
+ additionalSigners: additionalSigners
3590
+ }];
3591
+ }
3592
+ });
3593
+ }); };
3594
+ this.activeStake = function (rewardSymbol, poolName, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3595
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, flpStakeAccountMetas, _i, _a, custody, activateStakeInstruction, err_11;
3596
+ return __generator(this, function (_b) {
3597
+ switch (_b.label) {
3598
+ case 0:
3599
+ publicKey = this.provider.wallet.publicKey;
3600
+ preInstructions = [];
3601
+ instructions = [];
3602
+ postInstructions = [];
3603
+ additionalSigners = [];
3604
+ _b.label = 1;
3605
+ case 1:
3606
+ _b.trys.push([1, 3, , 4]);
3607
+ rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
3608
+ rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
3609
+ pool = this.getPoolKey(poolName);
3610
+ feeDistributionTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("custody_token_account"), pool.toBuffer(), rewardCustodyMint.toBuffer()], this.programId)[0];
3611
+ custodyAccountMetas = [];
3612
+ flpStakeAccountMetas = [];
3613
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
3614
+ custody = _a[_i];
3615
+ custodyAccountMetas.push({
3616
+ pubkey: custody.custodyAccount,
3617
+ isSigner: false,
3618
+ isWritable: false,
3619
+ });
3620
+ }
3621
+ return [4, this.program.methods
3622
+ .activateStake({})
3623
+ .accounts({
3624
+ perpetuals: this.perpetuals.publicKey,
3625
+ pool: pool,
3626
+ rewardCustody: rewardCustodyConfig.custodyAccount,
3627
+ feeDistributionTokenAccount: feeDistributionTokenAccount,
3628
+ })
3629
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), flpStakeAccountMetas, true))
3630
+ .instruction()];
3631
+ case 2:
3632
+ activateStakeInstruction = _b.sent();
3633
+ instructions.push(activateStakeInstruction);
3634
+ return [3, 4];
3635
+ case 3:
3636
+ err_11 = _b.sent();
3637
+ console.log("perpClient activateStaking error:: ", err_11);
3638
+ throw err_11;
3639
+ case 4: return [2, {
3640
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3641
+ additionalSigners: additionalSigners
3642
+ }];
3643
+ }
3644
+ });
3645
+ }); };
3646
+ this.unstakeRequest = function (unstakeAmount, poolName, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3647
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolFlpTokenAccount, flpStakeAccount, userLpTokenAccount, unstakeRequestInstruction, err_12;
3648
+ return __generator(this, function (_a) {
3649
+ switch (_a.label) {
3650
+ case 0:
3651
+ publicKey = this.provider.wallet.publicKey;
3652
+ preInstructions = [];
3653
+ instructions = [];
3654
+ postInstructions = [];
3655
+ additionalSigners = [];
3656
+ _a.label = 1;
3657
+ case 1:
3658
+ _a.trys.push([1, 4, , 5]);
3659
+ lpTokenMint = poolConfig.lpTokenMint;
3660
+ pool = this.getPoolKey(poolName);
3661
+ poolFlpTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("staked_lp_token_account"), pool.toBuffer(), lpTokenMint.toBuffer()], this.programId)[0];
3662
+ flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], this.programId)[0];
3663
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
3664
+ case 2:
3665
+ userLpTokenAccount = _a.sent();
3666
+ return [4, this.program.methods
3667
+ .unstakeRequest({
3668
+ unstakeAmount: unstakeAmount
3669
+ })
3670
+ .accounts({
3671
+ owner: publicKey,
3672
+ fundingFlpTokenAccount: userLpTokenAccount,
3673
+ transferAuthority: poolConfig.transferAuthority,
3674
+ perpetuals: this.perpetuals.publicKey,
3675
+ pool: pool,
3676
+ flpStakeAccount: flpStakeAccount,
3677
+ poolFlpTokenAccount: poolFlpTokenAccount,
3678
+ systemProgram: web3_js_1.SystemProgram.programId,
3679
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3680
+ eventAuthority: this.eventAuthority.publicKey,
3681
+ })
3682
+ .instruction()];
3683
+ case 3:
3684
+ unstakeRequestInstruction = _a.sent();
3685
+ instructions.push(unstakeRequestInstruction);
3686
+ return [3, 5];
3687
+ case 4:
3688
+ err_12 = _a.sent();
3689
+ console.log("perpClient unstakeRequest error:: ", err_12);
3690
+ throw err_12;
3691
+ case 5: return [2, {
3692
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3693
+ additionalSigners: additionalSigners
3694
+ }];
3695
+ }
3696
+ });
3697
+ }); };
3698
+ this.deactiveStake = function (rewardSymbol, poolName, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3699
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, rewardCustodyMint, rewardCustodyConfig, pool, feeDistributionTokenAccount, custodyAccountMetas, flpStakeAccountMetas, _i, _a, custody, deactivateStakeInstruction, err_13;
3700
+ return __generator(this, function (_b) {
3701
+ switch (_b.label) {
3702
+ case 0:
3703
+ publicKey = this.provider.wallet.publicKey;
3704
+ preInstructions = [];
3705
+ instructions = [];
3706
+ postInstructions = [];
3707
+ additionalSigners = [];
3708
+ _b.label = 1;
3709
+ case 1:
3710
+ _b.trys.push([1, 3, , 4]);
3711
+ rewardCustodyMint = poolConfig.getTokenFromSymbol(rewardSymbol).mintKey;
3712
+ rewardCustodyConfig = poolConfig.custodies.find(function (i) { return i.mintKey.equals(poolConfig.getTokenFromSymbol(rewardSymbol).mintKey); });
3713
+ pool = this.getPoolKey(poolName);
3714
+ feeDistributionTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("custody_token_account"), pool.toBuffer(), rewardCustodyMint.toBuffer()], this.programId)[0];
3715
+ custodyAccountMetas = [];
3716
+ flpStakeAccountMetas = [];
3717
+ for (_i = 0, _a = poolConfig.custodies; _i < _a.length; _i++) {
3718
+ custody = _a[_i];
3719
+ custodyAccountMetas.push({
3720
+ pubkey: custody.custodyAccount,
3721
+ isSigner: false,
3722
+ isWritable: false,
3723
+ });
3724
+ }
3725
+ return [4, this.program.methods
3726
+ .deactivateStake({})
3727
+ .accounts({
3728
+ perpetuals: this.perpetuals.publicKey,
3729
+ pool: pool,
3730
+ rewardCustody: rewardCustodyConfig.custodyAccount,
3731
+ feeDistributionTokenAccount: feeDistributionTokenAccount,
3732
+ })
3733
+ .remainingAccounts(__spreadArray(__spreadArray([], custodyAccountMetas, true), flpStakeAccountMetas, true))
3734
+ .instruction()];
3735
+ case 2:
3736
+ deactivateStakeInstruction = _b.sent();
3737
+ instructions.push(deactivateStakeInstruction);
3738
+ return [3, 4];
3739
+ case 3:
3740
+ err_13 = _b.sent();
3741
+ console.log("perpClient deactivateStaking error:: ", err_13);
3742
+ throw err_13;
3743
+ case 4: return [2, {
3744
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3745
+ additionalSigners: additionalSigners
3746
+ }];
3747
+ }
3748
+ });
3749
+ }); };
3750
+ this.withdrawStake = function (withdrawAmount, poolName, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3751
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, lpTokenMint, pool, poolFlpTokenAccount, flpStakeAccount, userLpTokenAccount, withdrawStakeInstruction, err_14;
3752
+ return __generator(this, function (_a) {
3753
+ switch (_a.label) {
3754
+ case 0:
3755
+ publicKey = this.provider.wallet.publicKey;
3756
+ preInstructions = [];
3757
+ instructions = [];
3758
+ postInstructions = [];
3759
+ additionalSigners = [];
3760
+ _a.label = 1;
3761
+ case 1:
3762
+ _a.trys.push([1, 4, , 5]);
3763
+ lpTokenMint = poolConfig.lpTokenMint;
3764
+ pool = this.getPoolKey(poolName);
3765
+ poolFlpTokenAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("staked_lp_token_account"), pool.toBuffer(), lpTokenMint.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
3766
+ flpStakeAccount = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("stake"), publicKey.toBuffer(), pool.toBuffer()], constants_1.METAPLEX_PROGRAM_ID)[0];
3767
+ return [4, (0, spl_token_1.getAssociatedTokenAddress)(poolConfig.lpTokenMint, publicKey)];
3768
+ case 2:
3769
+ userLpTokenAccount = _a.sent();
3770
+ return [4, this.program.methods
3771
+ .withdrawStake({
3772
+ withdrawAmount: withdrawAmount
3773
+ })
3774
+ .accounts({
3775
+ owner: publicKey,
3776
+ receivingFlpTokenAccount: userLpTokenAccount,
3777
+ transferAuthority: poolConfig.transferAuthority,
3778
+ perpetuals: this.perpetuals.publicKey,
3779
+ pool: pool,
3780
+ flpStakeAccount: flpStakeAccount,
3781
+ poolFlpTokenAccount: poolFlpTokenAccount,
3782
+ systemProgram: web3_js_1.SystemProgram.programId,
3783
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
3784
+ eventAuthority: this.eventAuthority.publicKey,
3785
+ })
3786
+ .instruction()];
3787
+ case 3:
3788
+ withdrawStakeInstruction = _a.sent();
3789
+ instructions.push(withdrawStakeInstruction);
3790
+ return [3, 5];
3791
+ case 4:
3792
+ err_14 = _a.sent();
3793
+ console.log("perpClient withdrawStake error:: ", err_14);
3794
+ throw err_14;
3795
+ case 5: return [2, {
3796
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3797
+ additionalSigners: additionalSigners
3798
+ }];
3799
+ }
3800
+ });
3801
+ }); };
3802
+ this.setPoolConfig = function (permissions, oracleAuthority, maxAumUsd, stakingFeeShareBps, poolConfig) { return __awaiter(_this, void 0, void 0, function () {
3803
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPoolConfigInstruction, err_15;
3804
+ return __generator(this, function (_a) {
3805
+ switch (_a.label) {
3806
+ case 0:
3807
+ publicKey = this.provider.wallet.publicKey;
3808
+ preInstructions = [];
3809
+ instructions = [];
3810
+ postInstructions = [];
3811
+ additionalSigners = [];
3812
+ _a.label = 1;
3813
+ case 1:
3814
+ _a.trys.push([1, 3, , 4]);
3815
+ return [4, this.program.methods
3816
+ .setPoolConfig({
3817
+ permissions: permissions,
3818
+ oracleAuthority: oracleAuthority,
3819
+ maxAumUsd: maxAumUsd,
3820
+ stakingFeeShareBps: stakingFeeShareBps
3821
+ })
3822
+ .accounts({
3823
+ admin: publicKey,
3824
+ multisig: this.multisig.publicKey,
3825
+ pool: poolConfig.poolAddress
3826
+ })
3827
+ .instruction()];
3828
+ case 2:
3829
+ setPoolConfigInstruction = _a.sent();
3830
+ instructions.push(setPoolConfigInstruction);
3831
+ return [3, 4];
3832
+ case 3:
3833
+ err_15 = _a.sent();
3834
+ console.log("perpClient setPool error:: ", err_15);
3835
+ throw err_15;
3836
+ case 4: return [2, {
3837
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3838
+ additionalSigners: additionalSigners
3839
+ }];
3840
+ }
3841
+ });
3842
+ }); };
3843
+ this.setPermissions = function (permissions) { return __awaiter(_this, void 0, void 0, function () {
3844
+ var publicKey, preInstructions, instructions, postInstructions, additionalSigners, setPermissionsInstruction, err_16;
3845
+ return __generator(this, function (_a) {
3846
+ switch (_a.label) {
3847
+ case 0:
3848
+ publicKey = this.provider.wallet.publicKey;
3849
+ preInstructions = [];
3850
+ instructions = [];
3851
+ postInstructions = [];
3852
+ additionalSigners = [];
3853
+ _a.label = 1;
3854
+ case 1:
3855
+ _a.trys.push([1, 3, , 4]);
3856
+ return [4, this.program.methods
3857
+ .setPermissions({
3858
+ permissions: permissions,
3859
+ })
3860
+ .accounts({
3861
+ admin: publicKey,
3862
+ multisig: this.multisig.publicKey,
3863
+ perpetuals: this.perpetuals.publicKey
3864
+ })
3865
+ .instruction()];
3866
+ case 2:
3867
+ setPermissionsInstruction = _a.sent();
3868
+ instructions.push(setPermissionsInstruction);
3869
+ return [3, 4];
3870
+ case 3:
3871
+ err_16 = _a.sent();
3872
+ console.log("perpClient setPool error:: ", err_16);
3873
+ throw err_16;
3874
+ case 4: return [2, {
3875
+ instructions: __spreadArray(__spreadArray(__spreadArray([], preInstructions, true), instructions, true), postInstructions, true),
3876
+ additionalSigners: additionalSigners
3877
+ }];
3878
+ }
3879
+ });
3880
+ }); };
3343
3881
  this.provider = provider;
3344
3882
  (0, anchor_1.setProvider)(provider);
3345
3883
  this.program = new anchor_1.Program(perpetuals_1.IDL, programId);
@@ -3358,6 +3896,19 @@ var PerpetualsClient = (function () {
3358
3896
  return this.toString(10);
3359
3897
  };
3360
3898
  }
3899
+ PerpetualsClient.prototype.getMarketPk = function (targetCustody, collateralCustody, side) {
3900
+ return this.findProgramAddress("market", [
3901
+ targetCustody,
3902
+ collateralCustody,
3903
+ side === 'long' ? [1] : [2],
3904
+ ]).publicKey;
3905
+ };
3906
+ PerpetualsClient.prototype.getPositionKey = function (owner, targetCustody, collateralCustody, side) {
3907
+ return this.findProgramAddress("position", [
3908
+ owner,
3909
+ this.getMarketPk(targetCustody, collateralCustody, side),
3910
+ ]).publicKey;
3911
+ };
3361
3912
  PerpetualsClient.prototype.getNewRatioHelper = function (amountAdd, amountRemove, custodyAccount, maxPrice, poolAumUsdMax) {
3362
3913
  var newRatio = constants_1.BN_ZERO;
3363
3914
  var maxPriceOracle = OraclePrice_1.OraclePrice.from({ price: new anchor_1.BN(maxPrice), exponent: new anchor_1.BN(-8), confidence: constants_1.BN_ZERO, timestamp: constants_1.BN_ZERO });
@@ -3383,37 +3934,71 @@ var PerpetualsClient = (function () {
3383
3934
  }
3384
3935
  return newRatio;
3385
3936
  };
3386
- PerpetualsClient.prototype.getPriceAfterSlippage = function (isEntry, slippageBps, marketPrice, marketEmaPrice, side, custody) {
3937
+ PerpetualsClient.prototype.getPriceAfterSlippageOld = function (isEntry, slippageBps, targetPrice, targetEmaPrice, side, custody) {
3938
+ if (isEntry) {
3939
+ var current_price_usd = this.getEntryPriceUsdSync(side, targetPrice, targetEmaPrice, custody);
3940
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price_usd, new anchor_1.BN(-1 * constants_1.USD_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
3941
+ if ((0, types_1.isVariant)(side, 'long')) {
3942
+ return { price: current_price_usd.add(spread_i), exponent: targetPrice.exponent.toNumber() };
3943
+ }
3944
+ else {
3945
+ if (spread_i.lt(current_price_usd)) {
3946
+ return { price: current_price_usd.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
3947
+ }
3948
+ else {
3949
+ return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
3950
+ }
3951
+ ;
3952
+ }
3953
+ }
3954
+ else {
3955
+ var current_price = this.getExitPriceSync(side, targetPrice, targetEmaPrice, custody);
3956
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, new anchor_1.BN(-1 * constants_1.USD_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
3957
+ if ((0, types_1.isVariant)(side, 'long')) {
3958
+ if (spread_i.lt(current_price)) {
3959
+ return { price: current_price.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
3960
+ }
3961
+ else {
3962
+ return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
3963
+ }
3964
+ ;
3965
+ }
3966
+ else {
3967
+ return { price: current_price.add(spread_i), exponent: targetPrice.exponent.toNumber() };
3968
+ }
3969
+ }
3970
+ };
3971
+ PerpetualsClient.prototype.getPriceAfterSlippage = function (isEntry, slippageBps, targetPrice, side) {
3387
3972
  if (isEntry) {
3388
- var current_price = this.getEntryPriceSync(side, marketPrice, marketEmaPrice, custody);
3389
- var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, new anchor_1.BN(-1 * constants_1.PRICE_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.PRICE_DECIMALS));
3973
+ var current_price = targetPrice.price;
3974
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, new anchor_1.BN(-1 * constants_1.USD_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
3390
3975
  if ((0, types_1.isVariant)(side, 'long')) {
3391
- return current_price.add(spread_i);
3976
+ return { price: current_price.add(spread_i), exponent: targetPrice.exponent.toNumber() };
3392
3977
  }
3393
3978
  else {
3394
3979
  if (spread_i.lt(current_price)) {
3395
- return current_price.sub(spread_i);
3980
+ return { price: current_price.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
3396
3981
  }
3397
3982
  else {
3398
- return constants_1.BN_ZERO;
3983
+ return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
3399
3984
  }
3400
3985
  ;
3401
3986
  }
3402
3987
  }
3403
3988
  else {
3404
- var current_price = this.getExitPriceSync(side, marketPrice, marketEmaPrice, custody);
3405
- var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, new anchor_1.BN(-1 * constants_1.PRICE_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.PRICE_DECIMALS));
3989
+ var current_price = targetPrice.price;
3990
+ var spread_i = (0, utils_1.checkedDecimalCeilMul)(current_price, new anchor_1.BN(-1 * constants_1.USD_DECIMALS), slippageBps, new anchor_1.BN(-1 * constants_1.BPS_DECIMALS), new anchor_1.BN(-1 * constants_1.USD_DECIMALS));
3406
3991
  if ((0, types_1.isVariant)(side, 'long')) {
3407
3992
  if (spread_i.lt(current_price)) {
3408
- return current_price.sub(spread_i);
3993
+ return { price: current_price.sub(spread_i), exponent: targetPrice.exponent.toNumber() };
3409
3994
  }
3410
3995
  else {
3411
- return constants_1.BN_ZERO;
3996
+ return { price: constants_1.BN_ZERO, exponent: targetPrice.exponent.toNumber() };
3412
3997
  }
3413
3998
  ;
3414
3999
  }
3415
4000
  else {
3416
- return current_price.add(spread_i);
4001
+ return { price: current_price.add(spread_i), exponent: targetPrice.exponent.toNumber() };
3417
4002
  }
3418
4003
  }
3419
4004
  };