@strkfarm/sdk 2.0.0-dev.4 → 2.0.0-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28390,8 +28390,7 @@ var calculateAmountDistribution = async (amount, client, marketName, collateralP
28390
28390
  vesu_leverage: 0
28391
28391
  };
28392
28392
  }
28393
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28394
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
28393
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28395
28394
  const vesuBTCExposureUSD = collateralUnits.multipliedBy(collateralPrice);
28396
28395
  const numerator1 = vesu_leverage * amount + vesuBTCExposureUSD.toNumber();
28397
28396
  const numerator2 = extendedExposureUSD.toNumber();
@@ -28609,21 +28608,35 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28609
28608
  vaultAllocator: config.vaultAllocator,
28610
28609
  id: ""
28611
28610
  });
28612
- this.tokenMarketData = new TokenMarketData(this.config.pricer, this.config.networkConfig);
28611
+ this.tokenMarketData = new TokenMarketData(
28612
+ this.config.pricer,
28613
+ this.config.networkConfig
28614
+ );
28613
28615
  }
28614
28616
  async getAPY(supportedPosition) {
28615
28617
  const CACHE_KEY = `apy_${this.config.poolId.address}_${supportedPosition.asset.symbol}`;
28616
28618
  const cacheData = this.getCache(CACHE_KEY);
28617
- console.log(`${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(cacheData)}`, this.vesuAdapter.config.poolId.shortString(), this.vesuAdapter.config.collateral.symbol, this.vesuAdapter.config.debt.symbol);
28619
+ console.log(
28620
+ `${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(
28621
+ cacheData
28622
+ )}`,
28623
+ this.vesuAdapter.config.poolId.shortString(),
28624
+ this.vesuAdapter.config.collateral.symbol,
28625
+ this.vesuAdapter.config.debt.symbol
28626
+ );
28618
28627
  if (cacheData) {
28619
28628
  return cacheData;
28620
28629
  }
28621
28630
  try {
28622
28631
  const allVesuPools = await VesuAdapter.getVesuPools();
28623
28632
  const asset = supportedPosition.asset;
28624
- const pool = allVesuPools.pools.find((p) => this.vesuAdapter.config.poolId.eqString(num9.getHexString(p.id)));
28633
+ const pool = allVesuPools.pools.find(
28634
+ (p) => this.vesuAdapter.config.poolId.eqString(num9.getHexString(p.id))
28635
+ );
28625
28636
  if (!pool) {
28626
- logger.warn(`VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`);
28637
+ logger.warn(
28638
+ `VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`
28639
+ );
28627
28640
  return {
28628
28641
  apy: 0,
28629
28642
  type: "base" /* BASE */
@@ -28633,7 +28646,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28633
28646
  (a) => a.symbol.toLowerCase() === asset.symbol.toLowerCase()
28634
28647
  )?.stats;
28635
28648
  if (!assetStats) {
28636
- logger.warn(`VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`);
28649
+ logger.warn(
28650
+ `VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`
28651
+ );
28637
28652
  return {
28638
28653
  apy: 0,
28639
28654
  type: "base" /* BASE */
@@ -28644,7 +28659,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28644
28659
  apy = Number(assetStats.borrowApr?.value || 0) / 1e18;
28645
28660
  } else {
28646
28661
  const isAssetBTC = asset.symbol.toLowerCase().includes("btc");
28647
- const baseAPY = Number(isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0) / 1e18;
28662
+ const baseAPY = Number(
28663
+ isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0
28664
+ ) / 1e18;
28648
28665
  const rewardAPY = Number(assetStats.defiSpringSupplyApr?.value || "0") / 1e18;
28649
28666
  const isSupported = this.tokenMarketData.isAPYSupported(asset);
28650
28667
  apy = baseAPY + rewardAPY;
@@ -28660,7 +28677,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28660
28677
  this.setCache(CACHE_KEY, result, 3e5);
28661
28678
  return result;
28662
28679
  } catch (error) {
28663
- logger.error(`VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`, error);
28680
+ logger.error(
28681
+ `VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`,
28682
+ error
28683
+ );
28664
28684
  throw error;
28665
28685
  }
28666
28686
  }
@@ -28673,12 +28693,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28673
28693
  try {
28674
28694
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28675
28695
  this.vesuAdapter.pricer = this.config.pricer;
28676
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28696
+ const positions = await this.vesuAdapter.getPositions(
28697
+ this.config.networkConfig
28698
+ );
28677
28699
  let position = positions.find(
28678
28700
  (p) => p.token.address.eq(supportedPosition.asset.address)
28679
28701
  );
28680
28702
  if (!position) {
28681
- logger.warn(`VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`);
28703
+ logger.warn(
28704
+ `VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`
28705
+ );
28682
28706
  return {
28683
28707
  amount: new Web3Number("0", supportedPosition.asset.decimals),
28684
28708
  remarks: "Position not found"
@@ -28691,12 +28715,18 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28691
28715
  this.setCache(CACHE_KEY, position, 6e4);
28692
28716
  return position;
28693
28717
  } catch (error) {
28694
- logger.error(`VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`, error);
28718
+ logger.error(
28719
+ `VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`,
28720
+ error
28721
+ );
28695
28722
  throw error;
28696
28723
  }
28697
28724
  }
28698
28725
  async maxBorrowableAPY() {
28699
- const collateralAPY = await this.getAPY({ asset: this.config.collateral, isDebt: false });
28726
+ const collateralAPY = await this.getAPY({
28727
+ asset: this.config.collateral,
28728
+ isDebt: false
28729
+ });
28700
28730
  const apy = collateralAPY.apy * 0.8;
28701
28731
  return apy;
28702
28732
  }
@@ -28706,9 +28736,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28706
28736
  try {
28707
28737
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28708
28738
  this.vesuAdapter.pricer = this.config.pricer;
28709
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28710
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28711
- const debtPosition = positions.find((p) => p.token.address.eq(debt.address));
28739
+ const positions = await this.vesuAdapter.getPositions(
28740
+ this.config.networkConfig
28741
+ );
28742
+ const collateralPosition = positions.find(
28743
+ (p) => p.token.address.eq(collateral.address)
28744
+ );
28745
+ const debtPosition = positions.find(
28746
+ (p) => p.token.address.eq(debt.address)
28747
+ );
28712
28748
  if (!collateralPosition || !debtPosition) {
28713
28749
  throw new Error("Could not find current positions");
28714
28750
  }
@@ -28718,13 +28754,23 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28718
28754
  debt,
28719
28755
  maxBorrowableAPY
28720
28756
  );
28721
- logger.verbose(`VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`);
28722
- const debtCap = await this.vesuAdapter.getDebtCap(this.config.networkConfig);
28757
+ logger.verbose(
28758
+ `VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`
28759
+ );
28760
+ const debtCap = await this.vesuAdapter.getDebtCap(
28761
+ this.config.networkConfig
28762
+ );
28723
28763
  logger.verbose(`VesuMultiplyAdapter: Debt cap: ${debtCap.toNumber()}`);
28724
28764
  const actualMaxBorrowable = maxBorrowable.minimum(debtCap);
28725
- logger.verbose(`VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`);
28726
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
28727
- const collateralPrice = await this.config.pricer.getPrice(collateral.symbol);
28765
+ logger.verbose(
28766
+ `VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`
28767
+ );
28768
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
28769
+ this.config.networkConfig
28770
+ );
28771
+ const collateralPrice = await this.config.pricer.getPrice(
28772
+ collateral.symbol
28773
+ );
28728
28774
  if (collateralPrice.price === 0) {
28729
28775
  throw new Error("Collateral price is 0");
28730
28776
  }
@@ -28742,14 +28788,25 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28742
28788
  );
28743
28789
  const maxDepositAmount = amount ? amount.minimum(maxCollateralFromDebt) : maxCollateralFromDebt;
28744
28790
  const usdValue = await this.getUSDValue(collateral, maxDepositAmount);
28745
- logger.verbose(`VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`);
28746
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28747
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28791
+ logger.verbose(
28792
+ `VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`
28793
+ );
28794
+ const apys = await Promise.all([
28795
+ this.getAPY({ asset: collateral, isDebt: false }),
28796
+ this.getAPY({ asset: debt, isDebt: true })
28797
+ ]);
28798
+ logger.verbose(
28799
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28800
+ );
28748
28801
  const borrowAmountUSD = actualMaxBorrowable.multipliedBy(debtPrice.price);
28749
- logger.verbose(`VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`);
28802
+ logger.verbose(
28803
+ `VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`
28804
+ );
28750
28805
  const netCollateralUSD = usdValue + borrowAmountUSD.toNumber();
28751
28806
  const netAPY = (apys[0].apy * netCollateralUSD + apys[1].apy * borrowAmountUSD.toNumber()) / usdValue;
28752
- logger.verbose(`VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`);
28807
+ logger.verbose(
28808
+ `VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`
28809
+ );
28753
28810
  return {
28754
28811
  tokenInfo: collateral,
28755
28812
  amount: maxDepositAmount,
@@ -28762,7 +28819,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28762
28819
  protocol: this.protocol
28763
28820
  };
28764
28821
  } catch (error) {
28765
- logger.error(`VesuMultiplyAdapter: Error calculating max deposit:`, error);
28822
+ logger.error(
28823
+ `VesuMultiplyAdapter: Error calculating max deposit:`,
28824
+ error
28825
+ );
28766
28826
  throw error;
28767
28827
  }
28768
28828
  }
@@ -28772,9 +28832,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28772
28832
  try {
28773
28833
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28774
28834
  this.vesuAdapter.pricer = this.config.pricer;
28775
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28776
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28777
- const debtPosition = positions.find((p) => p.token.address.eq(this.config.debt.address));
28835
+ const positions = await this.vesuAdapter.getPositions(
28836
+ this.config.networkConfig
28837
+ );
28838
+ const collateralPosition = positions.find(
28839
+ (p) => p.token.address.eq(collateral.address)
28840
+ );
28841
+ const debtPosition = positions.find(
28842
+ (p) => p.token.address.eq(this.config.debt.address)
28843
+ );
28778
28844
  if (!collateralPosition || !debtPosition) {
28779
28845
  throw new Error("Could not find current positions");
28780
28846
  }
@@ -28784,11 +28850,20 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28784
28850
  const result = maxWithdrawable.greaterThan(0) ? maxWithdrawable : new Web3Number("0", collateral.decimals);
28785
28851
  const usdValue = await this.getUSDValue(collateral, result);
28786
28852
  const debtUSD = debtPosition.usdValue;
28787
- logger.verbose(`VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`);
28788
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28789
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28853
+ logger.verbose(
28854
+ `VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`
28855
+ );
28856
+ const apys = await Promise.all([
28857
+ this.getAPY({ asset: collateral, isDebt: false }),
28858
+ this.getAPY({ asset: debt, isDebt: true })
28859
+ ]);
28860
+ logger.verbose(
28861
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28862
+ );
28790
28863
  const netAPY = usdValue - debtUSD > 0 ? (apys[0].apy * usdValue + apys[1].apy * debtUSD) / (usdValue - debtUSD) : 0;
28791
- logger.verbose(`VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`);
28864
+ logger.verbose(
28865
+ `VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`
28866
+ );
28792
28867
  return {
28793
28868
  tokenInfo: collateral,
28794
28869
  amount: result,
@@ -28801,14 +28876,19 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28801
28876
  protocol: this.protocol
28802
28877
  };
28803
28878
  } catch (error) {
28804
- logger.error(`VesuMultiplyAdapter: Error calculating max withdraw:`, error);
28879
+ logger.error(
28880
+ `VesuMultiplyAdapter: Error calculating max withdraw:`,
28881
+ error
28882
+ );
28805
28883
  throw error;
28806
28884
  }
28807
28885
  }
28808
28886
  _getDepositLeaf() {
28809
28887
  const collateral = this.config.collateral;
28810
28888
  const debt = this.config.debt;
28811
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28889
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28890
+ this.config.poolId
28891
+ );
28812
28892
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28813
28893
  return [
28814
28894
  // Approval step for collateral
@@ -28872,7 +28952,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28872
28952
  ];
28873
28953
  }
28874
28954
  _getWithdrawLeaf() {
28875
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28955
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28956
+ this.config.poolId
28957
+ );
28876
28958
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28877
28959
  const collateral = this.config.collateral;
28878
28960
  const debt = this.config.debt;
@@ -28929,33 +29011,51 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28929
29011
  const leafConfigs = this._getDepositLeaf();
28930
29012
  const leaves = leafConfigs.map((config) => {
28931
29013
  const { target, method, packedArguments, sanitizer, id } = config;
28932
- const leaf = this.constructSimpleLeafData({
28933
- id,
28934
- target,
28935
- method,
28936
- packedArguments
28937
- }, sanitizer);
29014
+ const leaf = this.constructSimpleLeafData(
29015
+ {
29016
+ id,
29017
+ target,
29018
+ method,
29019
+ packedArguments
29020
+ },
29021
+ sanitizer
29022
+ );
28938
29023
  return leaf;
28939
29024
  });
28940
- return { leaves, callConstructor: this.getDepositCall.bind(this) };
29025
+ return {
29026
+ leaves,
29027
+ callConstructor: this.getDepositCall.bind(
29028
+ this
29029
+ )
29030
+ };
28941
29031
  }
28942
29032
  getWithdrawAdapter() {
28943
29033
  const leafConfigs = this._getWithdrawLeaf();
28944
29034
  const leaves = leafConfigs.map((config) => {
28945
29035
  const { target, method, packedArguments, sanitizer, id } = config;
28946
- const leaf = this.constructSimpleLeafData({
28947
- id,
28948
- target,
28949
- method,
28950
- packedArguments
28951
- }, sanitizer);
29036
+ const leaf = this.constructSimpleLeafData(
29037
+ {
29038
+ id,
29039
+ target,
29040
+ method,
29041
+ packedArguments
29042
+ },
29043
+ sanitizer
29044
+ );
28952
29045
  return leaf;
28953
29046
  });
28954
- return { leaves, callConstructor: this.getWithdrawCall.bind(this) };
29047
+ return {
29048
+ leaves,
29049
+ callConstructor: this.getWithdrawCall.bind(
29050
+ this
29051
+ )
29052
+ };
28955
29053
  }
28956
29054
  async getDepositCall(params) {
28957
29055
  const collateral = this.config.collateral;
28958
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
29056
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
29057
+ this.config.poolId
29058
+ );
28959
29059
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28960
29060
  const uint256MarginAmount = uint25612.bnToUint256(params.amount.toWei());
28961
29061
  return [
@@ -29027,7 +29127,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29027
29127
  ];
29028
29128
  }
29029
29129
  async getWithdrawCall(params) {
29030
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
29130
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
29131
+ this.config.poolId
29132
+ );
29031
29133
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
29032
29134
  return [
29033
29135
  // Switch delegation on
@@ -29082,7 +29184,11 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29082
29184
  ];
29083
29185
  }
29084
29186
  async getMultiplyCallCalldata(params, isDeposit) {
29085
- logger.verbose(`${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(params)}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`);
29187
+ logger.verbose(
29188
+ `${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(
29189
+ params
29190
+ )}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`
29191
+ );
29086
29192
  const { isV2 } = getVesuSingletonAddress(this.config.poolId);
29087
29193
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
29088
29194
  const multiplyContract = new Contract12({
@@ -29092,42 +29198,83 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29092
29198
  });
29093
29199
  let leverSwap = [];
29094
29200
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29095
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
29096
- const collateralisation = await this.vesuAdapter.getCollateralization(this.config.networkConfig);
29201
+ const existingPositions = await this.vesuAdapter.getPositions(
29202
+ this.config.networkConfig
29203
+ );
29204
+ const collateralisation = await this.vesuAdapter.getCollateralization(
29205
+ this.config.networkConfig
29206
+ );
29097
29207
  const existingCollateralInfo = existingPositions[0];
29098
29208
  const existingDebtInfo = existingPositions[1];
29099
29209
  const isDexPriceRequired = existingDebtInfo.token.symbol !== "USDC";
29100
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(existingCollateralInfo)},
29101
- existingDebtInfo: ${JSON.stringify(existingDebtInfo)}, collateralisation: ${JSON.stringify(collateralisation)}`);
29210
+ logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(
29211
+ existingCollateralInfo
29212
+ )},
29213
+ existingDebtInfo: ${JSON.stringify(
29214
+ existingDebtInfo
29215
+ )}, collateralisation: ${JSON.stringify(collateralisation)}`);
29102
29216
  const collateralPrice = collateralisation[0].usdValue > 0 ? collateralisation[0].usdValue / existingCollateralInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.collateral.symbol)).price;
29103
29217
  const debtPrice = collateralisation[1].usdValue > 0 ? collateralisation[1].usdValue / existingDebtInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.debt.symbol)).price;
29104
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
29105
- const legLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
29106
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
29107
- const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(this.config.collateral, this.config.debt, this.config.quoteAmountToFetchPrice) : 1;
29108
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`);
29218
+ logger.debug(
29219
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`
29220
+ );
29221
+ const legLTV = await this.vesuAdapter.getLTVConfig(
29222
+ this.config.networkConfig
29223
+ );
29224
+ const ekuboQuoter = new EkuboQuoter(
29225
+ this.config.networkConfig,
29226
+ this.config.pricer
29227
+ );
29228
+ const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(
29229
+ this.config.collateral,
29230
+ this.config.debt,
29231
+ this.config.quoteAmountToFetchPrice
29232
+ ) : 1;
29233
+ logger.verbose(
29234
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`
29235
+ );
29109
29236
  const addedCollateral = params.amount.multipliedBy(isDeposit ? 1 : -1);
29110
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`);
29237
+ logger.verbose(
29238
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`
29239
+ );
29111
29240
  const numeratorPart1 = existingCollateralInfo.amount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(legLTV);
29112
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`);
29241
+ logger.verbose(
29242
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`
29243
+ );
29113
29244
  const numeratorPart2 = existingDebtInfo.amount.multipliedBy(debtPrice).multipliedBy(this.config.targetHealthFactor);
29114
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`);
29245
+ logger.verbose(
29246
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`
29247
+ );
29115
29248
  const denominatorPart = this.config.targetHealthFactor - legLTV / dexPrice;
29116
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`);
29249
+ logger.verbose(
29250
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`
29251
+ );
29117
29252
  const x_debt_usd = numeratorPart1.minus(numeratorPart2).dividedBy(denominatorPart);
29118
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`);
29119
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`);
29120
- let debtAmount = new Web3Number(x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals), this.config.debt.decimals);
29253
+ logger.verbose(
29254
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`
29255
+ );
29256
+ logger.debug(
29257
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`
29258
+ );
29259
+ let debtAmount = new Web3Number(
29260
+ x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals),
29261
+ this.config.debt.decimals
29262
+ );
29121
29263
  const marginAmount = addedCollateral;
29122
29264
  const collateralToken = this.config.collateral;
29123
29265
  const debtToken = this.config.debt;
29124
- const debtAmountInCollateralUnits = new Web3Number(debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0), collateralToken.decimals);
29266
+ const debtAmountInCollateralUnits = new Web3Number(
29267
+ debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0),
29268
+ collateralToken.decimals
29269
+ );
29125
29270
  const isIncrease = debtAmount.greaterThanOrEqualTo(0);
29126
29271
  if (isIncrease && debtAmount.lessThan(0)) {
29127
29272
  } else if (!isIncrease && debtAmount.greaterThan(0)) {
29128
29273
  debtAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29129
29274
  }
29130
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`);
29275
+ logger.verbose(
29276
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`
29277
+ );
29131
29278
  if (!debtAmount.isZero()) {
29132
29279
  try {
29133
29280
  const swapQuote = await ekuboQuoter.getQuote(
@@ -29137,26 +29284,49 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29137
29284
  // negative for exact amount out
29138
29285
  );
29139
29286
  if (swapQuote.price_impact < 0.01) {
29140
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
29287
+ leverSwap = debtAmount.isNegative() ? ekuboQuoter.getVesuMultiplyQuote(
29288
+ swapQuote,
29289
+ collateralToken,
29290
+ debtToken
29291
+ ) : ekuboQuoter.getVesuMultiplyQuote(
29292
+ swapQuote,
29293
+ debtToken,
29294
+ collateralToken
29295
+ );
29141
29296
  const MAX_SLIPPAGE = 2e-3;
29142
29297
  if (debtAmount.greaterThan(0)) {
29143
29298
  leverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
29144
29299
  } else if (debtAmount.lessThan(0)) {
29145
29300
  leverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
29146
29301
  } else {
29147
- leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29302
+ leverSwapLimitAmount = Web3Number.fromWei(
29303
+ 0,
29304
+ this.config.debt.decimals
29305
+ );
29148
29306
  }
29149
29307
  await new Promise((resolve) => setTimeout(resolve, 1e4));
29150
29308
  } else {
29151
- throw new Error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
29309
+ throw new Error(
29310
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
29311
+ );
29152
29312
  }
29153
29313
  } catch (error) {
29154
- throw new Error(`VesuMultiplyAdapter: Failed to get swap quote: ${error}`);
29314
+ throw new Error(
29315
+ `VesuMultiplyAdapter: Failed to get swap quote: ${error}`
29316
+ );
29155
29317
  }
29156
29318
  }
29157
- const multiplyParams = await this.getLeverParams(isIncrease, params, leverSwap, leverSwapLimitAmount);
29319
+ const multiplyParams = await this.getLeverParams(
29320
+ isIncrease,
29321
+ params,
29322
+ leverSwap,
29323
+ leverSwapLimitAmount
29324
+ );
29158
29325
  const call = multiplyContract.populate("modify_lever", {
29159
- modify_lever_params: this.formatMultiplyParams(isIncrease, multiplyParams)
29326
+ modify_lever_params: this.formatMultiplyParams(
29327
+ isIncrease,
29328
+ multiplyParams
29329
+ )
29160
29330
  });
29161
29331
  return call.calldata;
29162
29332
  }
@@ -29170,7 +29340,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29170
29340
  add_margin: params.amount,
29171
29341
  // multiplied by collateral decimals in format
29172
29342
  margin_swap: [],
29173
- margin_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29343
+ margin_swap_limit_amount: Web3Number.fromWei(
29344
+ 0,
29345
+ this.config.collateral.decimals
29346
+ ),
29174
29347
  lever_swap: leverSwap,
29175
29348
  lever_swap_limit_amount: leverSwapLimitAmount
29176
29349
  } : {
@@ -29184,7 +29357,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29184
29357
  lever_swap_limit_amount: leverSwapLimitAmount,
29185
29358
  lever_swap_weights: [],
29186
29359
  withdraw_swap: [],
29187
- withdraw_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29360
+ withdraw_swap_limit_amount: Web3Number.fromWei(
29361
+ 0,
29362
+ this.config.collateral.decimals
29363
+ ),
29188
29364
  withdraw_swap_weights: [],
29189
29365
  close_position: false
29190
29366
  };
@@ -29200,12 +29376,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29200
29376
  });
29201
29377
  let leverSwap = [];
29202
29378
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29203
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
29379
+ const existingPositions = await this.vesuAdapter.getPositions(
29380
+ this.config.networkConfig
29381
+ );
29204
29382
  const existingCollateralInfo = existingPositions[0];
29205
29383
  const existingDebtInfo = existingPositions[1];
29206
29384
  const collateralToken = this.config.collateral;
29207
29385
  const debtToken = this.config.debt;
29208
- const collateralPrice = await this.config.pricer.getPrice(collateralToken.symbol);
29386
+ const collateralPrice = await this.config.pricer.getPrice(
29387
+ collateralToken.symbol
29388
+ );
29209
29389
  const debtPrice = await this.config.pricer.getPrice(debtToken.symbol);
29210
29390
  const { deltadebtAmountUnits: debtAmountToRepay } = calculateDebtReductionAmountForWithdrawal(
29211
29391
  existingDebtInfo.amount,
@@ -29219,8 +29399,14 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29219
29399
  if (!debtAmountToRepay) {
29220
29400
  throw new Error("error calculating debt amount to repay");
29221
29401
  }
29222
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
29223
- const debtInDebtUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
29402
+ const ekuboQuoter = new EkuboQuoter(
29403
+ this.config.networkConfig,
29404
+ this.config.pricer
29405
+ );
29406
+ const debtInDebtUnits = new Web3Number(
29407
+ debtAmountToRepay,
29408
+ debtToken.decimals
29409
+ ).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
29224
29410
  const swapQuote = await ekuboQuoter.getQuote(
29225
29411
  debtToken.address.address,
29226
29412
  collateralToken.address.address,
@@ -29228,12 +29414,23 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29228
29414
  );
29229
29415
  const MAX_SLIPPAGE = 2e-3;
29230
29416
  if (swapQuote.price_impact < 25e-4) {
29231
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, collateralToken, debtToken);
29417
+ leverSwap = ekuboQuoter.getVesuMultiplyQuote(
29418
+ swapQuote,
29419
+ collateralToken,
29420
+ debtToken
29421
+ );
29232
29422
  } else {
29233
- logger.error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
29423
+ logger.error(
29424
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
29425
+ );
29234
29426
  }
29235
29427
  leverSwapLimitAmount = new Web3Number(debtAmountToRepay, debtToken.decimals).abs().multipliedBy(1 + MAX_SLIPPAGE);
29236
- const multiplyParams = await this.getLeverParams(false, params, leverSwap, leverSwapLimitAmount);
29428
+ const multiplyParams = await this.getLeverParams(
29429
+ false,
29430
+ params,
29431
+ leverSwap,
29432
+ leverSwapLimitAmount
29433
+ );
29237
29434
  const call = multiplyContract.populate("modify_lever", {
29238
29435
  modify_lever_params: this.formatMultiplyParams(false, multiplyParams)
29239
29436
  });
@@ -29243,100 +29440,132 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29243
29440
  if (isIncrease) {
29244
29441
  const _params2 = params;
29245
29442
  return {
29246
- action: new CairoCustomEnum3({ IncreaseLever: {
29247
- pool_id: _params2.pool_id.toBigInt(),
29248
- collateral_asset: _params2.collateral_asset.toBigInt(),
29249
- debt_asset: _params2.debt_asset.toBigInt(),
29250
- user: _params2.user.toBigInt(),
29251
- add_margin: BigInt(_params2.add_margin.toWei()),
29252
- margin_swap: _params2.margin_swap.map((swap) => ({
29443
+ action: new CairoCustomEnum3({
29444
+ IncreaseLever: {
29445
+ pool_id: _params2.pool_id.toBigInt(),
29446
+ collateral_asset: _params2.collateral_asset.toBigInt(),
29447
+ debt_asset: _params2.debt_asset.toBigInt(),
29448
+ user: _params2.user.toBigInt(),
29449
+ add_margin: BigInt(_params2.add_margin.toWei()),
29450
+ margin_swap: _params2.margin_swap.map((swap) => ({
29451
+ route: swap.route.map((route) => ({
29452
+ pool_key: {
29453
+ token0: route.pool_key.token0.toBigInt(),
29454
+ token1: route.pool_key.token1.toBigInt(),
29455
+ fee: route.pool_key.fee,
29456
+ tick_spacing: route.pool_key.tick_spacing,
29457
+ extension: BigInt(
29458
+ num9.hexToDecimalString(route.pool_key.extension)
29459
+ )
29460
+ },
29461
+ sqrt_ratio_limit: uint25612.bnToUint256(
29462
+ route.sqrt_ratio_limit.toWei()
29463
+ ),
29464
+ skip_ahead: BigInt(100)
29465
+ })),
29466
+ token_amount: {
29467
+ token: swap.token_amount.token.toBigInt(),
29468
+ amount: swap.token_amount.amount.toI129()
29469
+ }
29470
+ })),
29471
+ margin_swap_limit_amount: BigInt(
29472
+ _params2.margin_swap_limit_amount.toWei()
29473
+ ),
29474
+ lever_swap: _params2.lever_swap.map((swap) => ({
29475
+ route: swap.route.map((route) => ({
29476
+ pool_key: {
29477
+ token0: route.pool_key.token0.toBigInt(),
29478
+ token1: route.pool_key.token1.toBigInt(),
29479
+ fee: route.pool_key.fee,
29480
+ tick_spacing: route.pool_key.tick_spacing,
29481
+ extension: BigInt(
29482
+ num9.hexToDecimalString(route.pool_key.extension)
29483
+ )
29484
+ },
29485
+ sqrt_ratio_limit: uint25612.bnToUint256(
29486
+ route.sqrt_ratio_limit.toWei()
29487
+ ),
29488
+ skip_ahead: BigInt(0)
29489
+ })),
29490
+ token_amount: {
29491
+ token: swap.token_amount.token.toBigInt(),
29492
+ amount: swap.token_amount.amount.toI129()
29493
+ }
29494
+ })),
29495
+ lever_swap_limit_amount: BigInt(
29496
+ _params2.lever_swap_limit_amount.toWei()
29497
+ )
29498
+ }
29499
+ })
29500
+ };
29501
+ }
29502
+ const _params = params;
29503
+ return {
29504
+ action: new CairoCustomEnum3({
29505
+ DecreaseLever: {
29506
+ pool_id: _params.pool_id.toBigInt(),
29507
+ collateral_asset: _params.collateral_asset.toBigInt(),
29508
+ debt_asset: _params.debt_asset.toBigInt(),
29509
+ user: _params.user.toBigInt(),
29510
+ sub_margin: BigInt(_params.sub_margin.toWei()),
29511
+ recipient: _params.recipient.toBigInt(),
29512
+ lever_swap: _params.lever_swap.map((swap) => ({
29253
29513
  route: swap.route.map((route) => ({
29254
29514
  pool_key: {
29255
29515
  token0: route.pool_key.token0.toBigInt(),
29256
29516
  token1: route.pool_key.token1.toBigInt(),
29257
29517
  fee: route.pool_key.fee,
29258
29518
  tick_spacing: route.pool_key.tick_spacing,
29259
- extension: BigInt(num9.hexToDecimalString(route.pool_key.extension))
29519
+ extension: ContractAddr.from(
29520
+ route.pool_key.extension
29521
+ ).toBigInt()
29260
29522
  },
29261
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
29262
- skip_ahead: BigInt(100)
29523
+ sqrt_ratio_limit: uint25612.bnToUint256(
29524
+ route.sqrt_ratio_limit.toWei()
29525
+ ),
29526
+ skip_ahead: BigInt(route.skip_ahead.toWei())
29263
29527
  })),
29264
29528
  token_amount: {
29265
29529
  token: swap.token_amount.token.toBigInt(),
29266
29530
  amount: swap.token_amount.amount.toI129()
29267
29531
  }
29268
29532
  })),
29269
- margin_swap_limit_amount: BigInt(_params2.margin_swap_limit_amount.toWei()),
29270
- lever_swap: _params2.lever_swap.map((swap) => ({
29533
+ lever_swap_limit_amount: BigInt(
29534
+ _params.lever_swap_limit_amount.toWei()
29535
+ ),
29536
+ lever_swap_weights: _params.lever_swap_weights.map(
29537
+ (weight) => BigInt(weight.toWei())
29538
+ ),
29539
+ withdraw_swap: _params.withdraw_swap.map((swap) => ({
29271
29540
  route: swap.route.map((route) => ({
29272
29541
  pool_key: {
29273
29542
  token0: route.pool_key.token0.toBigInt(),
29274
29543
  token1: route.pool_key.token1.toBigInt(),
29275
29544
  fee: route.pool_key.fee,
29276
29545
  tick_spacing: route.pool_key.tick_spacing,
29277
- extension: BigInt(num9.hexToDecimalString(route.pool_key.extension))
29546
+ extension: ContractAddr.from(
29547
+ route.pool_key.extension
29548
+ ).toBigInt()
29278
29549
  },
29279
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
29280
- skip_ahead: BigInt(0)
29550
+ sqrt_ratio_limit: uint25612.bnToUint256(
29551
+ route.sqrt_ratio_limit.toWei()
29552
+ ),
29553
+ skip_ahead: BigInt(route.skip_ahead.toWei())
29281
29554
  })),
29282
29555
  token_amount: {
29283
29556
  token: swap.token_amount.token.toBigInt(),
29284
29557
  amount: swap.token_amount.amount.toI129()
29285
29558
  }
29286
29559
  })),
29287
- lever_swap_limit_amount: BigInt(_params2.lever_swap_limit_amount.toWei())
29288
- } })
29289
- };
29290
- }
29291
- const _params = params;
29292
- return {
29293
- action: new CairoCustomEnum3({ DecreaseLever: {
29294
- pool_id: _params.pool_id.toBigInt(),
29295
- collateral_asset: _params.collateral_asset.toBigInt(),
29296
- debt_asset: _params.debt_asset.toBigInt(),
29297
- user: _params.user.toBigInt(),
29298
- sub_margin: BigInt(_params.sub_margin.toWei()),
29299
- recipient: _params.recipient.toBigInt(),
29300
- lever_swap: _params.lever_swap.map((swap) => ({
29301
- route: swap.route.map((route) => ({
29302
- pool_key: {
29303
- token0: route.pool_key.token0.toBigInt(),
29304
- token1: route.pool_key.token1.toBigInt(),
29305
- fee: route.pool_key.fee,
29306
- tick_spacing: route.pool_key.tick_spacing,
29307
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
29308
- },
29309
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
29310
- skip_ahead: BigInt(route.skip_ahead.toWei())
29311
- })),
29312
- token_amount: {
29313
- token: swap.token_amount.token.toBigInt(),
29314
- amount: swap.token_amount.amount.toI129()
29315
- }
29316
- })),
29317
- lever_swap_limit_amount: BigInt(_params.lever_swap_limit_amount.toWei()),
29318
- lever_swap_weights: _params.lever_swap_weights.map((weight) => BigInt(weight.toWei())),
29319
- withdraw_swap: _params.withdraw_swap.map((swap) => ({
29320
- route: swap.route.map((route) => ({
29321
- pool_key: {
29322
- token0: route.pool_key.token0.toBigInt(),
29323
- token1: route.pool_key.token1.toBigInt(),
29324
- fee: route.pool_key.fee,
29325
- tick_spacing: route.pool_key.tick_spacing,
29326
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
29327
- },
29328
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
29329
- skip_ahead: BigInt(route.skip_ahead.toWei())
29330
- })),
29331
- token_amount: {
29332
- token: swap.token_amount.token.toBigInt(),
29333
- amount: swap.token_amount.amount.toI129()
29334
- }
29335
- })),
29336
- withdraw_swap_limit_amount: BigInt(_params.withdraw_swap_limit_amount.toWei()),
29337
- withdraw_swap_weights: _params.withdraw_swap_weights.map((weight) => BigInt(weight.toWei())),
29338
- close_position: _params.close_position
29339
- } })
29560
+ withdraw_swap_limit_amount: BigInt(
29561
+ _params.withdraw_swap_limit_amount.toWei()
29562
+ ),
29563
+ withdraw_swap_weights: _params.withdraw_swap_weights.map(
29564
+ (weight) => BigInt(weight.toWei())
29565
+ ),
29566
+ close_position: _params.close_position
29567
+ }
29568
+ })
29340
29569
  };
29341
29570
  }
29342
29571
  async getHealthFactor() {
@@ -29345,11 +29574,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29345
29574
  }
29346
29575
  async getNetAPY() {
29347
29576
  const positions = await this.getPositions();
29348
- logger.verbose(`${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`);
29577
+ logger.verbose(
29578
+ `${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`
29579
+ );
29349
29580
  const allZero = positions.every((p) => p.usdValue === 0);
29350
29581
  if (allZero) {
29351
29582
  const collateralUSD = 1e3;
29352
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
29583
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
29584
+ this.config.networkConfig
29585
+ );
29353
29586
  const targetHF = this.config.targetHealthFactor;
29354
29587
  const maxDebt = HealthFactorMath.getMaxDebtAmountOnLooping(
29355
29588
  new Web3Number(collateralUSD, this.config.collateral.decimals),
@@ -29390,7 +29623,10 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29390
29623
  //abstract means the method has no implementation in this class; instead, child classes must implement it.
29391
29624
  async getAPY(supportedPosition) {
29392
29625
  const side = supportedPosition.isDebt ? "LONG" : "SHORT";
29393
- const fundingRates = await this.client.getFundingRates(this.config.extendedMarketName, side);
29626
+ const fundingRates = await this.client.getFundingRates(
29627
+ this.config.extendedMarketName,
29628
+ side
29629
+ );
29394
29630
  if (fundingRates.status !== "OK") {
29395
29631
  logger.error("error getting funding rates", fundingRates);
29396
29632
  return { apy: 0, type: "base" /* BASE */ };
@@ -29434,14 +29670,14 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29434
29670
  });
29435
29671
  }
29436
29672
  _getDepositLeaf() {
29437
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29673
+ const usdceToken = Global.getDefaultTokens().find(
29674
+ (token) => token.symbol === "USDCe"
29675
+ );
29438
29676
  return [
29439
29677
  {
29440
29678
  target: this.config.supportedPositions[0].asset.address,
29441
29679
  method: "approve",
29442
- packedArguments: [
29443
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
29444
- ],
29680
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29445
29681
  id: `extended_approve_${this.config.supportedPositions[0].asset.symbol}`,
29446
29682
  sanitizer: AVNU_LEGACY_SANITIZER
29447
29683
  },
@@ -29472,25 +29708,33 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29472
29708
  const leafConfigs = this._getSwapFromLegacyLeaf();
29473
29709
  const leaves = leafConfigs.map((config) => {
29474
29710
  const { target, method, packedArguments, sanitizer, id } = config;
29475
- const leaf = this.constructSimpleLeafData({
29476
- id,
29477
- target,
29478
- method,
29479
- packedArguments
29480
- }, sanitizer);
29711
+ const leaf = this.constructSimpleLeafData(
29712
+ {
29713
+ id,
29714
+ target,
29715
+ method,
29716
+ packedArguments
29717
+ },
29718
+ sanitizer
29719
+ );
29481
29720
  return leaf;
29482
29721
  });
29483
- return { leaves, callConstructor: this.getSwapFromLegacyCall.bind(this) };
29722
+ return {
29723
+ leaves,
29724
+ callConstructor: this.getSwapFromLegacyCall.bind(
29725
+ this
29726
+ )
29727
+ };
29484
29728
  }
29485
29729
  _getSwapFromLegacyLeaf() {
29486
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29730
+ const usdceToken = Global.getDefaultTokens().find(
29731
+ (token) => token.symbol === "USDCe"
29732
+ );
29487
29733
  return [
29488
29734
  {
29489
29735
  target: usdceToken.address,
29490
29736
  method: "approve",
29491
- packedArguments: [
29492
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
29493
- ],
29737
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29494
29738
  id: `extendedswaplegacyapprove_${usdceToken.symbol}`,
29495
29739
  sanitizer: AVNU_LEGACY_SANITIZER
29496
29740
  },
@@ -29509,11 +29753,13 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29509
29753
  async getDepositCall(params) {
29510
29754
  try {
29511
29755
  const usdcToken = this.config.supportedPositions[0].asset;
29512
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29513
- const salt = Math.floor(
29514
- Math.random() * 10 ** usdcToken.decimals
29756
+ const usdceToken = Global.getDefaultTokens().find(
29757
+ (token) => token.symbol === "USDCe"
29758
+ );
29759
+ const salt = Math.floor(Math.random() * 10 ** usdcToken.decimals);
29760
+ const amount = uint25613.bnToUint256(
29761
+ params.amount.multipliedBy(10).toWei()
29515
29762
  );
29516
- const amount = uint25613.bnToUint256(params.amount.multipliedBy(10).toWei());
29517
29763
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
29518
29764
  usdcToken.address.toString(),
29519
29765
  usdceToken.address.toString(),
@@ -29526,7 +29772,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29526
29772
  logger.error("error getting quotes from avnu");
29527
29773
  return [];
29528
29774
  }
29529
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
29775
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
29776
+ quotes
29777
+ );
29530
29778
  const swapCallData = getCalldata[0];
29531
29779
  return [
29532
29780
  {
@@ -29602,8 +29850,12 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29602
29850
  async getSwapFromLegacyCall(params) {
29603
29851
  try {
29604
29852
  const usdcToken = this.config.supportedPositions[0].asset;
29605
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29606
- const amount = uint25613.bnToUint256(params.amount.multipliedBy(10).toWei());
29853
+ const usdceToken = Global.getDefaultTokens().find(
29854
+ (token) => token.symbol === "USDCe"
29855
+ );
29856
+ const amount = uint25613.bnToUint256(
29857
+ params.amount.multipliedBy(10).toWei()
29858
+ );
29607
29859
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
29608
29860
  usdceToken.address.toString(),
29609
29861
  usdcToken.address.toString(),
@@ -29616,7 +29868,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29616
29868
  logger.error("error getting quotes from avnu");
29617
29869
  return [];
29618
29870
  }
29619
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
29871
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
29872
+ quotes
29873
+ );
29620
29874
  const swapCallData = getCalldata[0];
29621
29875
  return [
29622
29876
  {
@@ -29664,9 +29918,14 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29664
29918
  if (!this.client) {
29665
29919
  throw new Error("Client not initialized");
29666
29920
  }
29667
- const withdrawalRequest = await this.client.withdrawUSDC(amount.toFixed(2));
29921
+ const withdrawalRequest = await this.client.withdrawUSDC(
29922
+ amount.toFixed(2)
29923
+ );
29668
29924
  if (withdrawalRequest.status === "OK") {
29669
- const withdrawalStatus = await this.getDepositOrWithdrawalStatus(withdrawalRequest.data, "WITHDRAWAL" /* WITHDRAWAL */);
29925
+ const withdrawalStatus = await this.getDepositOrWithdrawalStatus(
29926
+ withdrawalRequest.data,
29927
+ "WITHDRAWAL" /* WITHDRAWAL */
29928
+ );
29670
29929
  return withdrawalStatus;
29671
29930
  }
29672
29931
  return false;
@@ -29739,17 +29998,34 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29739
29998
  logger.error("error initializing client");
29740
29999
  return null;
29741
30000
  }
29742
- const orderhistory = await this.getOrderHistory(marketName);
30001
+ let orderhistory = await this.getOrderHistory(marketName);
29743
30002
  if (!orderhistory || orderhistory.length === 0) {
29744
- logger.error(`error getting order: ${orderId}`);
29745
- return null;
30003
+ logger.error(`error getting order history: ${orderId}`);
30004
+ } else {
30005
+ const order = orderhistory.slice(0, 5).find((order2) => order2.id.toString() === orderId);
30006
+ if (order) {
30007
+ return order;
30008
+ }
29746
30009
  }
29747
- const order = orderhistory.slice(0, 3).find((order2) => order2.id.toString() === orderId);
29748
- if (!order) {
29749
- logger.error(`error getting order: ${order}`);
29750
- return null;
30010
+ for (let attempt = 1; attempt <= 3; attempt++) {
30011
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
30012
+ orderhistory = await this.getOrderHistory(marketName);
30013
+ if (!orderhistory || orderhistory.length === 0) {
30014
+ logger.error(
30015
+ `error getting order history on retry ${attempt}: ${orderId}`
30016
+ );
30017
+ continue;
30018
+ }
30019
+ const order = orderhistory.slice(0, 5).find((order2) => order2.id.toString() === orderId);
30020
+ if (order) {
30021
+ return order;
30022
+ }
30023
+ logger.error(
30024
+ `order not found in top 5 entries on retry ${attempt}: ${orderId}`
30025
+ );
29751
30026
  }
29752
- return order;
30027
+ logger.error(`error getting order after all retries: ${orderId}`);
30028
+ return null;
29753
30029
  }
29754
30030
  async fetchOrderBookBTCUSDC() {
29755
30031
  try {
@@ -29822,7 +30098,10 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29822
30098
  return null;
29823
30099
  }
29824
30100
  await new Promise((resolve) => setTimeout(resolve, 5e3));
29825
- const openOrder = await this.getOrderStatus(result.position_id, this.config.extendedMarketName);
30101
+ const openOrder = await this.getOrderStatus(
30102
+ result.position_id,
30103
+ this.config.extendedMarketName
30104
+ );
29826
30105
  if (!openOrder || openOrder.status !== "FILLED" /* FILLED */) {
29827
30106
  if (attempt >= maxAttempts) {
29828
30107
  logger.error("Max retries reached \u2014 could not verify open position");
@@ -29845,7 +30124,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29845
30124
  };
29846
30125
  }
29847
30126
  } catch (err) {
29848
- logger.error(`createShortOrder failed on attempt ${attempt}: ${err.message}`);
30127
+ logger.error(
30128
+ `createShortOrder failed on attempt ${attempt}: ${err.message}`
30129
+ );
29849
30130
  if (attempt < maxAttempts) {
29850
30131
  const backoff = 1200 * attempt;
29851
30132
  logger.info(`Retrying after ${backoff}ms...`);
@@ -29890,13 +30171,17 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29890
30171
  operationsStatus: ["COMPLETED" /* COMPLETED */]
29891
30172
  });
29892
30173
  if (operationsType === "DEPOSIT" /* DEPOSIT */) {
29893
- const myTransferStatus = transferHistory.data.find((operation) => operation.transactionHash === orderId);
30174
+ const myTransferStatus = transferHistory.data.find(
30175
+ (operation) => operation.transactionHash === orderId
30176
+ );
29894
30177
  if (!myTransferStatus) {
29895
30178
  return true;
29896
30179
  }
29897
30180
  return true;
29898
30181
  } else {
29899
- const myTransferStatus = transferHistory.data.find((operation) => operation.id.toString() === orderId.toString());
30182
+ const myTransferStatus = transferHistory.data.find(
30183
+ (operation) => operation.id.toString() === orderId.toString()
30184
+ );
29900
30185
  if (!myTransferStatus) {
29901
30186
  return true;
29902
30187
  }
@@ -33514,6 +33799,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33514
33799
  toToken.decimals,
33515
33800
  true
33516
33801
  );
33802
+ console.log(`${_AvnuAdapter.name}::getDepositCall quote: ${quote?.sellAmountInUsd}`);
33517
33803
  if (!quote) {
33518
33804
  logger.error("error getting quote from avnu");
33519
33805
  return [];
@@ -33632,7 +33918,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33632
33918
  }
33633
33919
  throw new Error("Failed to fetch quote after retries");
33634
33920
  }
33635
- async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e3) {
33921
+ async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 5e3) {
33636
33922
  try {
33637
33923
  const fromToken = this.config.supportedPositions[0].asset;
33638
33924
  const toToken = this.config.supportedPositions[1].asset;
@@ -33872,7 +34158,8 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33872
34158
  }
33873
34159
  const balance = await this.getUnusedBalance();
33874
34160
  const usdcBalanceOnExtended = await extendedAdapter.getExtendedDepositAmount();
33875
- const amountToInvest = balance.amount.plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
34161
+ const amountToInvest = new Web3Number(balance.usdValue, USDC_TOKEN_DECIMALS).plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
34162
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest amountToInvest: ${amountToInvest.toNumber()}`);
33876
34163
  if (amountToInvest.lessThan(0)) {
33877
34164
  return {
33878
34165
  shouldInvest: false,
@@ -33925,6 +34212,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33925
34212
  vesuLeverage: 0
33926
34213
  };
33927
34214
  }
34215
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest vesu_amount: ${vesu_amount.toNumber()}, extended_amount: ${extended_amount.toNumber()}`);
33928
34216
  return {
33929
34217
  shouldInvest: true,
33930
34218
  vesuAmount: vesu_amount,
@@ -34004,15 +34292,15 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34004
34292
  }
34005
34293
  const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
34006
34294
  const usdcAmountOnExtended = parseFloat(
34007
- extendedHoldings.availableForTrade
34295
+ extendedHoldings.availableForWithdrawal
34008
34296
  );
34009
- if (extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended).greaterThan(0)) {
34297
+ if (extendedAmount.minus(usdcAmountOnExtended).greaterThan(0)) {
34010
34298
  try {
34011
34299
  const { calls: extendedCalls } = await this.moveAssets(
34012
34300
  {
34013
34301
  to: Protocols.EXTENDED.name,
34014
34302
  from: Protocols.VAULT.name,
34015
- amount: extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended)
34303
+ amount: extendedAmount.minus(usdcAmountOnExtended)
34016
34304
  },
34017
34305
  extendedAdapter,
34018
34306
  vesuAdapter
@@ -34119,7 +34407,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34119
34407
  const withdrawalFromExtended = await extendedAdapter.withdrawFromExtended(params.amount);
34120
34408
  if (withdrawalFromExtended) {
34121
34409
  const extendedHoldings2 = await extendedAdapter.getExtendedDepositAmount();
34122
- logger.info(`extendedHoldings after withdrawal ${extendedHoldings2}`);
34410
+ logger.info(`extendedHoldings after withdrawal ${extendedHoldings2?.availableForWithdrawal}`);
34123
34411
  await new Promise((resolve) => setTimeout(resolve, 1e4));
34124
34412
  const calls = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
34125
34413
  if (calls.length > 0) {
@@ -34250,7 +34538,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34250
34538
  };
34251
34539
  }
34252
34540
  const extendedHoldingAmount = new Web3Number(
34253
- extendedHoldings.availableForTrade,
34541
+ extendedHoldings.availableForWithdrawal,
34254
34542
  USDC_TOKEN_DECIMALS
34255
34543
  );
34256
34544
  const {
@@ -34310,7 +34598,6 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34310
34598
  extendedAmountInBTC: new Web3Number(0, 0),
34311
34599
  calls: []
34312
34600
  };
34313
- ;
34314
34601
  }
34315
34602
  }
34316
34603
  async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter) {