@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.
package/dist/index.mjs CHANGED
@@ -28065,8 +28065,7 @@ var calculateAmountDistribution = async (amount, client, marketName, collateralP
28065
28065
  vesu_leverage: 0
28066
28066
  };
28067
28067
  }
28068
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28069
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
28068
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28070
28069
  const vesuBTCExposureUSD = collateralUnits.multipliedBy(collateralPrice);
28071
28070
  const numerator1 = vesu_leverage * amount + vesuBTCExposureUSD.toNumber();
28072
28071
  const numerator2 = extendedExposureUSD.toNumber();
@@ -28284,21 +28283,35 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28284
28283
  vaultAllocator: config.vaultAllocator,
28285
28284
  id: ""
28286
28285
  });
28287
- this.tokenMarketData = new TokenMarketData(this.config.pricer, this.config.networkConfig);
28286
+ this.tokenMarketData = new TokenMarketData(
28287
+ this.config.pricer,
28288
+ this.config.networkConfig
28289
+ );
28288
28290
  }
28289
28291
  async getAPY(supportedPosition) {
28290
28292
  const CACHE_KEY = `apy_${this.config.poolId.address}_${supportedPosition.asset.symbol}`;
28291
28293
  const cacheData = this.getCache(CACHE_KEY);
28292
- console.log(`${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(cacheData)}`, this.vesuAdapter.config.poolId.shortString(), this.vesuAdapter.config.collateral.symbol, this.vesuAdapter.config.debt.symbol);
28294
+ console.log(
28295
+ `${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(
28296
+ cacheData
28297
+ )}`,
28298
+ this.vesuAdapter.config.poolId.shortString(),
28299
+ this.vesuAdapter.config.collateral.symbol,
28300
+ this.vesuAdapter.config.debt.symbol
28301
+ );
28293
28302
  if (cacheData) {
28294
28303
  return cacheData;
28295
28304
  }
28296
28305
  try {
28297
28306
  const allVesuPools = await VesuAdapter.getVesuPools();
28298
28307
  const asset = supportedPosition.asset;
28299
- const pool = allVesuPools.pools.find((p) => this.vesuAdapter.config.poolId.eqString(num9.getHexString(p.id)));
28308
+ const pool = allVesuPools.pools.find(
28309
+ (p) => this.vesuAdapter.config.poolId.eqString(num9.getHexString(p.id))
28310
+ );
28300
28311
  if (!pool) {
28301
- logger.warn(`VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`);
28312
+ logger.warn(
28313
+ `VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`
28314
+ );
28302
28315
  return {
28303
28316
  apy: 0,
28304
28317
  type: "base" /* BASE */
@@ -28308,7 +28321,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28308
28321
  (a) => a.symbol.toLowerCase() === asset.symbol.toLowerCase()
28309
28322
  )?.stats;
28310
28323
  if (!assetStats) {
28311
- logger.warn(`VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`);
28324
+ logger.warn(
28325
+ `VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`
28326
+ );
28312
28327
  return {
28313
28328
  apy: 0,
28314
28329
  type: "base" /* BASE */
@@ -28319,7 +28334,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28319
28334
  apy = Number(assetStats.borrowApr?.value || 0) / 1e18;
28320
28335
  } else {
28321
28336
  const isAssetBTC = asset.symbol.toLowerCase().includes("btc");
28322
- const baseAPY = Number(isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0) / 1e18;
28337
+ const baseAPY = Number(
28338
+ isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0
28339
+ ) / 1e18;
28323
28340
  const rewardAPY = Number(assetStats.defiSpringSupplyApr?.value || "0") / 1e18;
28324
28341
  const isSupported = this.tokenMarketData.isAPYSupported(asset);
28325
28342
  apy = baseAPY + rewardAPY;
@@ -28335,7 +28352,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28335
28352
  this.setCache(CACHE_KEY, result, 3e5);
28336
28353
  return result;
28337
28354
  } catch (error) {
28338
- logger.error(`VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`, error);
28355
+ logger.error(
28356
+ `VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`,
28357
+ error
28358
+ );
28339
28359
  throw error;
28340
28360
  }
28341
28361
  }
@@ -28348,12 +28368,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28348
28368
  try {
28349
28369
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28350
28370
  this.vesuAdapter.pricer = this.config.pricer;
28351
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28371
+ const positions = await this.vesuAdapter.getPositions(
28372
+ this.config.networkConfig
28373
+ );
28352
28374
  let position = positions.find(
28353
28375
  (p) => p.token.address.eq(supportedPosition.asset.address)
28354
28376
  );
28355
28377
  if (!position) {
28356
- logger.warn(`VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`);
28378
+ logger.warn(
28379
+ `VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`
28380
+ );
28357
28381
  return {
28358
28382
  amount: new Web3Number("0", supportedPosition.asset.decimals),
28359
28383
  remarks: "Position not found"
@@ -28366,12 +28390,18 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28366
28390
  this.setCache(CACHE_KEY, position, 6e4);
28367
28391
  return position;
28368
28392
  } catch (error) {
28369
- logger.error(`VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`, error);
28393
+ logger.error(
28394
+ `VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`,
28395
+ error
28396
+ );
28370
28397
  throw error;
28371
28398
  }
28372
28399
  }
28373
28400
  async maxBorrowableAPY() {
28374
- const collateralAPY = await this.getAPY({ asset: this.config.collateral, isDebt: false });
28401
+ const collateralAPY = await this.getAPY({
28402
+ asset: this.config.collateral,
28403
+ isDebt: false
28404
+ });
28375
28405
  const apy = collateralAPY.apy * 0.8;
28376
28406
  return apy;
28377
28407
  }
@@ -28381,9 +28411,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28381
28411
  try {
28382
28412
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28383
28413
  this.vesuAdapter.pricer = this.config.pricer;
28384
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28385
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28386
- const debtPosition = positions.find((p) => p.token.address.eq(debt.address));
28414
+ const positions = await this.vesuAdapter.getPositions(
28415
+ this.config.networkConfig
28416
+ );
28417
+ const collateralPosition = positions.find(
28418
+ (p) => p.token.address.eq(collateral.address)
28419
+ );
28420
+ const debtPosition = positions.find(
28421
+ (p) => p.token.address.eq(debt.address)
28422
+ );
28387
28423
  if (!collateralPosition || !debtPosition) {
28388
28424
  throw new Error("Could not find current positions");
28389
28425
  }
@@ -28393,13 +28429,23 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28393
28429
  debt,
28394
28430
  maxBorrowableAPY
28395
28431
  );
28396
- logger.verbose(`VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`);
28397
- const debtCap = await this.vesuAdapter.getDebtCap(this.config.networkConfig);
28432
+ logger.verbose(
28433
+ `VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`
28434
+ );
28435
+ const debtCap = await this.vesuAdapter.getDebtCap(
28436
+ this.config.networkConfig
28437
+ );
28398
28438
  logger.verbose(`VesuMultiplyAdapter: Debt cap: ${debtCap.toNumber()}`);
28399
28439
  const actualMaxBorrowable = maxBorrowable.minimum(debtCap);
28400
- logger.verbose(`VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`);
28401
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
28402
- const collateralPrice = await this.config.pricer.getPrice(collateral.symbol);
28440
+ logger.verbose(
28441
+ `VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`
28442
+ );
28443
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
28444
+ this.config.networkConfig
28445
+ );
28446
+ const collateralPrice = await this.config.pricer.getPrice(
28447
+ collateral.symbol
28448
+ );
28403
28449
  if (collateralPrice.price === 0) {
28404
28450
  throw new Error("Collateral price is 0");
28405
28451
  }
@@ -28417,14 +28463,25 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28417
28463
  );
28418
28464
  const maxDepositAmount = amount ? amount.minimum(maxCollateralFromDebt) : maxCollateralFromDebt;
28419
28465
  const usdValue = await this.getUSDValue(collateral, maxDepositAmount);
28420
- logger.verbose(`VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`);
28421
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28422
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28466
+ logger.verbose(
28467
+ `VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`
28468
+ );
28469
+ const apys = await Promise.all([
28470
+ this.getAPY({ asset: collateral, isDebt: false }),
28471
+ this.getAPY({ asset: debt, isDebt: true })
28472
+ ]);
28473
+ logger.verbose(
28474
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28475
+ );
28423
28476
  const borrowAmountUSD = actualMaxBorrowable.multipliedBy(debtPrice.price);
28424
- logger.verbose(`VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`);
28477
+ logger.verbose(
28478
+ `VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`
28479
+ );
28425
28480
  const netCollateralUSD = usdValue + borrowAmountUSD.toNumber();
28426
28481
  const netAPY = (apys[0].apy * netCollateralUSD + apys[1].apy * borrowAmountUSD.toNumber()) / usdValue;
28427
- logger.verbose(`VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`);
28482
+ logger.verbose(
28483
+ `VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`
28484
+ );
28428
28485
  return {
28429
28486
  tokenInfo: collateral,
28430
28487
  amount: maxDepositAmount,
@@ -28437,7 +28494,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28437
28494
  protocol: this.protocol
28438
28495
  };
28439
28496
  } catch (error) {
28440
- logger.error(`VesuMultiplyAdapter: Error calculating max deposit:`, error);
28497
+ logger.error(
28498
+ `VesuMultiplyAdapter: Error calculating max deposit:`,
28499
+ error
28500
+ );
28441
28501
  throw error;
28442
28502
  }
28443
28503
  }
@@ -28447,9 +28507,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28447
28507
  try {
28448
28508
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28449
28509
  this.vesuAdapter.pricer = this.config.pricer;
28450
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28451
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28452
- const debtPosition = positions.find((p) => p.token.address.eq(this.config.debt.address));
28510
+ const positions = await this.vesuAdapter.getPositions(
28511
+ this.config.networkConfig
28512
+ );
28513
+ const collateralPosition = positions.find(
28514
+ (p) => p.token.address.eq(collateral.address)
28515
+ );
28516
+ const debtPosition = positions.find(
28517
+ (p) => p.token.address.eq(this.config.debt.address)
28518
+ );
28453
28519
  if (!collateralPosition || !debtPosition) {
28454
28520
  throw new Error("Could not find current positions");
28455
28521
  }
@@ -28459,11 +28525,20 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28459
28525
  const result = maxWithdrawable.greaterThan(0) ? maxWithdrawable : new Web3Number("0", collateral.decimals);
28460
28526
  const usdValue = await this.getUSDValue(collateral, result);
28461
28527
  const debtUSD = debtPosition.usdValue;
28462
- logger.verbose(`VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`);
28463
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28464
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28528
+ logger.verbose(
28529
+ `VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`
28530
+ );
28531
+ const apys = await Promise.all([
28532
+ this.getAPY({ asset: collateral, isDebt: false }),
28533
+ this.getAPY({ asset: debt, isDebt: true })
28534
+ ]);
28535
+ logger.verbose(
28536
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28537
+ );
28465
28538
  const netAPY = usdValue - debtUSD > 0 ? (apys[0].apy * usdValue + apys[1].apy * debtUSD) / (usdValue - debtUSD) : 0;
28466
- logger.verbose(`VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`);
28539
+ logger.verbose(
28540
+ `VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`
28541
+ );
28467
28542
  return {
28468
28543
  tokenInfo: collateral,
28469
28544
  amount: result,
@@ -28476,14 +28551,19 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28476
28551
  protocol: this.protocol
28477
28552
  };
28478
28553
  } catch (error) {
28479
- logger.error(`VesuMultiplyAdapter: Error calculating max withdraw:`, error);
28554
+ logger.error(
28555
+ `VesuMultiplyAdapter: Error calculating max withdraw:`,
28556
+ error
28557
+ );
28480
28558
  throw error;
28481
28559
  }
28482
28560
  }
28483
28561
  _getDepositLeaf() {
28484
28562
  const collateral = this.config.collateral;
28485
28563
  const debt = this.config.debt;
28486
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28564
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28565
+ this.config.poolId
28566
+ );
28487
28567
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28488
28568
  return [
28489
28569
  // Approval step for collateral
@@ -28547,7 +28627,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28547
28627
  ];
28548
28628
  }
28549
28629
  _getWithdrawLeaf() {
28550
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28630
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28631
+ this.config.poolId
28632
+ );
28551
28633
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28552
28634
  const collateral = this.config.collateral;
28553
28635
  const debt = this.config.debt;
@@ -28604,33 +28686,51 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28604
28686
  const leafConfigs = this._getDepositLeaf();
28605
28687
  const leaves = leafConfigs.map((config) => {
28606
28688
  const { target, method, packedArguments, sanitizer, id } = config;
28607
- const leaf = this.constructSimpleLeafData({
28608
- id,
28609
- target,
28610
- method,
28611
- packedArguments
28612
- }, sanitizer);
28689
+ const leaf = this.constructSimpleLeafData(
28690
+ {
28691
+ id,
28692
+ target,
28693
+ method,
28694
+ packedArguments
28695
+ },
28696
+ sanitizer
28697
+ );
28613
28698
  return leaf;
28614
28699
  });
28615
- return { leaves, callConstructor: this.getDepositCall.bind(this) };
28700
+ return {
28701
+ leaves,
28702
+ callConstructor: this.getDepositCall.bind(
28703
+ this
28704
+ )
28705
+ };
28616
28706
  }
28617
28707
  getWithdrawAdapter() {
28618
28708
  const leafConfigs = this._getWithdrawLeaf();
28619
28709
  const leaves = leafConfigs.map((config) => {
28620
28710
  const { target, method, packedArguments, sanitizer, id } = config;
28621
- const leaf = this.constructSimpleLeafData({
28622
- id,
28623
- target,
28624
- method,
28625
- packedArguments
28626
- }, sanitizer);
28711
+ const leaf = this.constructSimpleLeafData(
28712
+ {
28713
+ id,
28714
+ target,
28715
+ method,
28716
+ packedArguments
28717
+ },
28718
+ sanitizer
28719
+ );
28627
28720
  return leaf;
28628
28721
  });
28629
- return { leaves, callConstructor: this.getWithdrawCall.bind(this) };
28722
+ return {
28723
+ leaves,
28724
+ callConstructor: this.getWithdrawCall.bind(
28725
+ this
28726
+ )
28727
+ };
28630
28728
  }
28631
28729
  async getDepositCall(params) {
28632
28730
  const collateral = this.config.collateral;
28633
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28731
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28732
+ this.config.poolId
28733
+ );
28634
28734
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28635
28735
  const uint256MarginAmount = uint25612.bnToUint256(params.amount.toWei());
28636
28736
  return [
@@ -28702,7 +28802,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28702
28802
  ];
28703
28803
  }
28704
28804
  async getWithdrawCall(params) {
28705
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28805
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28806
+ this.config.poolId
28807
+ );
28706
28808
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28707
28809
  return [
28708
28810
  // Switch delegation on
@@ -28757,7 +28859,11 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28757
28859
  ];
28758
28860
  }
28759
28861
  async getMultiplyCallCalldata(params, isDeposit) {
28760
- logger.verbose(`${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(params)}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`);
28862
+ logger.verbose(
28863
+ `${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(
28864
+ params
28865
+ )}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`
28866
+ );
28761
28867
  const { isV2 } = getVesuSingletonAddress(this.config.poolId);
28762
28868
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28763
28869
  const multiplyContract = new Contract12({
@@ -28767,42 +28873,83 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28767
28873
  });
28768
28874
  let leverSwap = [];
28769
28875
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28770
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28771
- const collateralisation = await this.vesuAdapter.getCollateralization(this.config.networkConfig);
28876
+ const existingPositions = await this.vesuAdapter.getPositions(
28877
+ this.config.networkConfig
28878
+ );
28879
+ const collateralisation = await this.vesuAdapter.getCollateralization(
28880
+ this.config.networkConfig
28881
+ );
28772
28882
  const existingCollateralInfo = existingPositions[0];
28773
28883
  const existingDebtInfo = existingPositions[1];
28774
28884
  const isDexPriceRequired = existingDebtInfo.token.symbol !== "USDC";
28775
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(existingCollateralInfo)},
28776
- existingDebtInfo: ${JSON.stringify(existingDebtInfo)}, collateralisation: ${JSON.stringify(collateralisation)}`);
28885
+ logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(
28886
+ existingCollateralInfo
28887
+ )},
28888
+ existingDebtInfo: ${JSON.stringify(
28889
+ existingDebtInfo
28890
+ )}, collateralisation: ${JSON.stringify(collateralisation)}`);
28777
28891
  const collateralPrice = collateralisation[0].usdValue > 0 ? collateralisation[0].usdValue / existingCollateralInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.collateral.symbol)).price;
28778
28892
  const debtPrice = collateralisation[1].usdValue > 0 ? collateralisation[1].usdValue / existingDebtInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.debt.symbol)).price;
28779
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
28780
- const legLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
28781
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
28782
- const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(this.config.collateral, this.config.debt, this.config.quoteAmountToFetchPrice) : 1;
28783
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`);
28893
+ logger.debug(
28894
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`
28895
+ );
28896
+ const legLTV = await this.vesuAdapter.getLTVConfig(
28897
+ this.config.networkConfig
28898
+ );
28899
+ const ekuboQuoter = new EkuboQuoter(
28900
+ this.config.networkConfig,
28901
+ this.config.pricer
28902
+ );
28903
+ const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(
28904
+ this.config.collateral,
28905
+ this.config.debt,
28906
+ this.config.quoteAmountToFetchPrice
28907
+ ) : 1;
28908
+ logger.verbose(
28909
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`
28910
+ );
28784
28911
  const addedCollateral = params.amount.multipliedBy(isDeposit ? 1 : -1);
28785
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`);
28912
+ logger.verbose(
28913
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`
28914
+ );
28786
28915
  const numeratorPart1 = existingCollateralInfo.amount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(legLTV);
28787
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`);
28916
+ logger.verbose(
28917
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`
28918
+ );
28788
28919
  const numeratorPart2 = existingDebtInfo.amount.multipliedBy(debtPrice).multipliedBy(this.config.targetHealthFactor);
28789
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`);
28920
+ logger.verbose(
28921
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`
28922
+ );
28790
28923
  const denominatorPart = this.config.targetHealthFactor - legLTV / dexPrice;
28791
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`);
28924
+ logger.verbose(
28925
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`
28926
+ );
28792
28927
  const x_debt_usd = numeratorPart1.minus(numeratorPart2).dividedBy(denominatorPart);
28793
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`);
28794
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`);
28795
- let debtAmount = new Web3Number(x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals), this.config.debt.decimals);
28928
+ logger.verbose(
28929
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`
28930
+ );
28931
+ logger.debug(
28932
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`
28933
+ );
28934
+ let debtAmount = new Web3Number(
28935
+ x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals),
28936
+ this.config.debt.decimals
28937
+ );
28796
28938
  const marginAmount = addedCollateral;
28797
28939
  const collateralToken = this.config.collateral;
28798
28940
  const debtToken = this.config.debt;
28799
- const debtAmountInCollateralUnits = new Web3Number(debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0), collateralToken.decimals);
28941
+ const debtAmountInCollateralUnits = new Web3Number(
28942
+ debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0),
28943
+ collateralToken.decimals
28944
+ );
28800
28945
  const isIncrease = debtAmount.greaterThanOrEqualTo(0);
28801
28946
  if (isIncrease && debtAmount.lessThan(0)) {
28802
28947
  } else if (!isIncrease && debtAmount.greaterThan(0)) {
28803
28948
  debtAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28804
28949
  }
28805
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`);
28950
+ logger.verbose(
28951
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`
28952
+ );
28806
28953
  if (!debtAmount.isZero()) {
28807
28954
  try {
28808
28955
  const swapQuote = await ekuboQuoter.getQuote(
@@ -28812,26 +28959,49 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28812
28959
  // negative for exact amount out
28813
28960
  );
28814
28961
  if (swapQuote.price_impact < 0.01) {
28815
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
28962
+ leverSwap = debtAmount.isNegative() ? ekuboQuoter.getVesuMultiplyQuote(
28963
+ swapQuote,
28964
+ collateralToken,
28965
+ debtToken
28966
+ ) : ekuboQuoter.getVesuMultiplyQuote(
28967
+ swapQuote,
28968
+ debtToken,
28969
+ collateralToken
28970
+ );
28816
28971
  const MAX_SLIPPAGE = 2e-3;
28817
28972
  if (debtAmount.greaterThan(0)) {
28818
28973
  leverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
28819
28974
  } else if (debtAmount.lessThan(0)) {
28820
28975
  leverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
28821
28976
  } else {
28822
- leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28977
+ leverSwapLimitAmount = Web3Number.fromWei(
28978
+ 0,
28979
+ this.config.debt.decimals
28980
+ );
28823
28981
  }
28824
28982
  await new Promise((resolve) => setTimeout(resolve, 1e4));
28825
28983
  } else {
28826
- throw new Error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
28984
+ throw new Error(
28985
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
28986
+ );
28827
28987
  }
28828
28988
  } catch (error) {
28829
- throw new Error(`VesuMultiplyAdapter: Failed to get swap quote: ${error}`);
28989
+ throw new Error(
28990
+ `VesuMultiplyAdapter: Failed to get swap quote: ${error}`
28991
+ );
28830
28992
  }
28831
28993
  }
28832
- const multiplyParams = await this.getLeverParams(isIncrease, params, leverSwap, leverSwapLimitAmount);
28994
+ const multiplyParams = await this.getLeverParams(
28995
+ isIncrease,
28996
+ params,
28997
+ leverSwap,
28998
+ leverSwapLimitAmount
28999
+ );
28833
29000
  const call = multiplyContract.populate("modify_lever", {
28834
- modify_lever_params: this.formatMultiplyParams(isIncrease, multiplyParams)
29001
+ modify_lever_params: this.formatMultiplyParams(
29002
+ isIncrease,
29003
+ multiplyParams
29004
+ )
28835
29005
  });
28836
29006
  return call.calldata;
28837
29007
  }
@@ -28845,7 +29015,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28845
29015
  add_margin: params.amount,
28846
29016
  // multiplied by collateral decimals in format
28847
29017
  margin_swap: [],
28848
- margin_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29018
+ margin_swap_limit_amount: Web3Number.fromWei(
29019
+ 0,
29020
+ this.config.collateral.decimals
29021
+ ),
28849
29022
  lever_swap: leverSwap,
28850
29023
  lever_swap_limit_amount: leverSwapLimitAmount
28851
29024
  } : {
@@ -28859,7 +29032,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28859
29032
  lever_swap_limit_amount: leverSwapLimitAmount,
28860
29033
  lever_swap_weights: [],
28861
29034
  withdraw_swap: [],
28862
- withdraw_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29035
+ withdraw_swap_limit_amount: Web3Number.fromWei(
29036
+ 0,
29037
+ this.config.collateral.decimals
29038
+ ),
28863
29039
  withdraw_swap_weights: [],
28864
29040
  close_position: false
28865
29041
  };
@@ -28875,12 +29051,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28875
29051
  });
28876
29052
  let leverSwap = [];
28877
29053
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28878
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
29054
+ const existingPositions = await this.vesuAdapter.getPositions(
29055
+ this.config.networkConfig
29056
+ );
28879
29057
  const existingCollateralInfo = existingPositions[0];
28880
29058
  const existingDebtInfo = existingPositions[1];
28881
29059
  const collateralToken = this.config.collateral;
28882
29060
  const debtToken = this.config.debt;
28883
- const collateralPrice = await this.config.pricer.getPrice(collateralToken.symbol);
29061
+ const collateralPrice = await this.config.pricer.getPrice(
29062
+ collateralToken.symbol
29063
+ );
28884
29064
  const debtPrice = await this.config.pricer.getPrice(debtToken.symbol);
28885
29065
  const { deltadebtAmountUnits: debtAmountToRepay } = calculateDebtReductionAmountForWithdrawal(
28886
29066
  existingDebtInfo.amount,
@@ -28894,8 +29074,14 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28894
29074
  if (!debtAmountToRepay) {
28895
29075
  throw new Error("error calculating debt amount to repay");
28896
29076
  }
28897
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
28898
- const debtInDebtUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
29077
+ const ekuboQuoter = new EkuboQuoter(
29078
+ this.config.networkConfig,
29079
+ this.config.pricer
29080
+ );
29081
+ const debtInDebtUnits = new Web3Number(
29082
+ debtAmountToRepay,
29083
+ debtToken.decimals
29084
+ ).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
28899
29085
  const swapQuote = await ekuboQuoter.getQuote(
28900
29086
  debtToken.address.address,
28901
29087
  collateralToken.address.address,
@@ -28903,12 +29089,23 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28903
29089
  );
28904
29090
  const MAX_SLIPPAGE = 2e-3;
28905
29091
  if (swapQuote.price_impact < 25e-4) {
28906
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, collateralToken, debtToken);
29092
+ leverSwap = ekuboQuoter.getVesuMultiplyQuote(
29093
+ swapQuote,
29094
+ collateralToken,
29095
+ debtToken
29096
+ );
28907
29097
  } else {
28908
- logger.error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
29098
+ logger.error(
29099
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
29100
+ );
28909
29101
  }
28910
29102
  leverSwapLimitAmount = new Web3Number(debtAmountToRepay, debtToken.decimals).abs().multipliedBy(1 + MAX_SLIPPAGE);
28911
- const multiplyParams = await this.getLeverParams(false, params, leverSwap, leverSwapLimitAmount);
29103
+ const multiplyParams = await this.getLeverParams(
29104
+ false,
29105
+ params,
29106
+ leverSwap,
29107
+ leverSwapLimitAmount
29108
+ );
28912
29109
  const call = multiplyContract.populate("modify_lever", {
28913
29110
  modify_lever_params: this.formatMultiplyParams(false, multiplyParams)
28914
29111
  });
@@ -28918,100 +29115,132 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28918
29115
  if (isIncrease) {
28919
29116
  const _params2 = params;
28920
29117
  return {
28921
- action: new CairoCustomEnum3({ IncreaseLever: {
28922
- pool_id: _params2.pool_id.toBigInt(),
28923
- collateral_asset: _params2.collateral_asset.toBigInt(),
28924
- debt_asset: _params2.debt_asset.toBigInt(),
28925
- user: _params2.user.toBigInt(),
28926
- add_margin: BigInt(_params2.add_margin.toWei()),
28927
- margin_swap: _params2.margin_swap.map((swap) => ({
29118
+ action: new CairoCustomEnum3({
29119
+ IncreaseLever: {
29120
+ pool_id: _params2.pool_id.toBigInt(),
29121
+ collateral_asset: _params2.collateral_asset.toBigInt(),
29122
+ debt_asset: _params2.debt_asset.toBigInt(),
29123
+ user: _params2.user.toBigInt(),
29124
+ add_margin: BigInt(_params2.add_margin.toWei()),
29125
+ margin_swap: _params2.margin_swap.map((swap) => ({
29126
+ route: swap.route.map((route) => ({
29127
+ pool_key: {
29128
+ token0: route.pool_key.token0.toBigInt(),
29129
+ token1: route.pool_key.token1.toBigInt(),
29130
+ fee: route.pool_key.fee,
29131
+ tick_spacing: route.pool_key.tick_spacing,
29132
+ extension: BigInt(
29133
+ num9.hexToDecimalString(route.pool_key.extension)
29134
+ )
29135
+ },
29136
+ sqrt_ratio_limit: uint25612.bnToUint256(
29137
+ route.sqrt_ratio_limit.toWei()
29138
+ ),
29139
+ skip_ahead: BigInt(100)
29140
+ })),
29141
+ token_amount: {
29142
+ token: swap.token_amount.token.toBigInt(),
29143
+ amount: swap.token_amount.amount.toI129()
29144
+ }
29145
+ })),
29146
+ margin_swap_limit_amount: BigInt(
29147
+ _params2.margin_swap_limit_amount.toWei()
29148
+ ),
29149
+ lever_swap: _params2.lever_swap.map((swap) => ({
29150
+ route: swap.route.map((route) => ({
29151
+ pool_key: {
29152
+ token0: route.pool_key.token0.toBigInt(),
29153
+ token1: route.pool_key.token1.toBigInt(),
29154
+ fee: route.pool_key.fee,
29155
+ tick_spacing: route.pool_key.tick_spacing,
29156
+ extension: BigInt(
29157
+ num9.hexToDecimalString(route.pool_key.extension)
29158
+ )
29159
+ },
29160
+ sqrt_ratio_limit: uint25612.bnToUint256(
29161
+ route.sqrt_ratio_limit.toWei()
29162
+ ),
29163
+ skip_ahead: BigInt(0)
29164
+ })),
29165
+ token_amount: {
29166
+ token: swap.token_amount.token.toBigInt(),
29167
+ amount: swap.token_amount.amount.toI129()
29168
+ }
29169
+ })),
29170
+ lever_swap_limit_amount: BigInt(
29171
+ _params2.lever_swap_limit_amount.toWei()
29172
+ )
29173
+ }
29174
+ })
29175
+ };
29176
+ }
29177
+ const _params = params;
29178
+ return {
29179
+ action: new CairoCustomEnum3({
29180
+ DecreaseLever: {
29181
+ pool_id: _params.pool_id.toBigInt(),
29182
+ collateral_asset: _params.collateral_asset.toBigInt(),
29183
+ debt_asset: _params.debt_asset.toBigInt(),
29184
+ user: _params.user.toBigInt(),
29185
+ sub_margin: BigInt(_params.sub_margin.toWei()),
29186
+ recipient: _params.recipient.toBigInt(),
29187
+ lever_swap: _params.lever_swap.map((swap) => ({
28928
29188
  route: swap.route.map((route) => ({
28929
29189
  pool_key: {
28930
29190
  token0: route.pool_key.token0.toBigInt(),
28931
29191
  token1: route.pool_key.token1.toBigInt(),
28932
29192
  fee: route.pool_key.fee,
28933
29193
  tick_spacing: route.pool_key.tick_spacing,
28934
- extension: BigInt(num9.hexToDecimalString(route.pool_key.extension))
29194
+ extension: ContractAddr.from(
29195
+ route.pool_key.extension
29196
+ ).toBigInt()
28935
29197
  },
28936
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
28937
- skip_ahead: BigInt(100)
29198
+ sqrt_ratio_limit: uint25612.bnToUint256(
29199
+ route.sqrt_ratio_limit.toWei()
29200
+ ),
29201
+ skip_ahead: BigInt(route.skip_ahead.toWei())
28938
29202
  })),
28939
29203
  token_amount: {
28940
29204
  token: swap.token_amount.token.toBigInt(),
28941
29205
  amount: swap.token_amount.amount.toI129()
28942
29206
  }
28943
29207
  })),
28944
- margin_swap_limit_amount: BigInt(_params2.margin_swap_limit_amount.toWei()),
28945
- lever_swap: _params2.lever_swap.map((swap) => ({
29208
+ lever_swap_limit_amount: BigInt(
29209
+ _params.lever_swap_limit_amount.toWei()
29210
+ ),
29211
+ lever_swap_weights: _params.lever_swap_weights.map(
29212
+ (weight) => BigInt(weight.toWei())
29213
+ ),
29214
+ withdraw_swap: _params.withdraw_swap.map((swap) => ({
28946
29215
  route: swap.route.map((route) => ({
28947
29216
  pool_key: {
28948
29217
  token0: route.pool_key.token0.toBigInt(),
28949
29218
  token1: route.pool_key.token1.toBigInt(),
28950
29219
  fee: route.pool_key.fee,
28951
29220
  tick_spacing: route.pool_key.tick_spacing,
28952
- extension: BigInt(num9.hexToDecimalString(route.pool_key.extension))
29221
+ extension: ContractAddr.from(
29222
+ route.pool_key.extension
29223
+ ).toBigInt()
28953
29224
  },
28954
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
28955
- skip_ahead: BigInt(0)
29225
+ sqrt_ratio_limit: uint25612.bnToUint256(
29226
+ route.sqrt_ratio_limit.toWei()
29227
+ ),
29228
+ skip_ahead: BigInt(route.skip_ahead.toWei())
28956
29229
  })),
28957
29230
  token_amount: {
28958
29231
  token: swap.token_amount.token.toBigInt(),
28959
29232
  amount: swap.token_amount.amount.toI129()
28960
29233
  }
28961
29234
  })),
28962
- lever_swap_limit_amount: BigInt(_params2.lever_swap_limit_amount.toWei())
28963
- } })
28964
- };
28965
- }
28966
- const _params = params;
28967
- return {
28968
- action: new CairoCustomEnum3({ DecreaseLever: {
28969
- pool_id: _params.pool_id.toBigInt(),
28970
- collateral_asset: _params.collateral_asset.toBigInt(),
28971
- debt_asset: _params.debt_asset.toBigInt(),
28972
- user: _params.user.toBigInt(),
28973
- sub_margin: BigInt(_params.sub_margin.toWei()),
28974
- recipient: _params.recipient.toBigInt(),
28975
- lever_swap: _params.lever_swap.map((swap) => ({
28976
- route: swap.route.map((route) => ({
28977
- pool_key: {
28978
- token0: route.pool_key.token0.toBigInt(),
28979
- token1: route.pool_key.token1.toBigInt(),
28980
- fee: route.pool_key.fee,
28981
- tick_spacing: route.pool_key.tick_spacing,
28982
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
28983
- },
28984
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
28985
- skip_ahead: BigInt(route.skip_ahead.toWei())
28986
- })),
28987
- token_amount: {
28988
- token: swap.token_amount.token.toBigInt(),
28989
- amount: swap.token_amount.amount.toI129()
28990
- }
28991
- })),
28992
- lever_swap_limit_amount: BigInt(_params.lever_swap_limit_amount.toWei()),
28993
- lever_swap_weights: _params.lever_swap_weights.map((weight) => BigInt(weight.toWei())),
28994
- withdraw_swap: _params.withdraw_swap.map((swap) => ({
28995
- route: swap.route.map((route) => ({
28996
- pool_key: {
28997
- token0: route.pool_key.token0.toBigInt(),
28998
- token1: route.pool_key.token1.toBigInt(),
28999
- fee: route.pool_key.fee,
29000
- tick_spacing: route.pool_key.tick_spacing,
29001
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
29002
- },
29003
- sqrt_ratio_limit: uint25612.bnToUint256(route.sqrt_ratio_limit.toWei()),
29004
- skip_ahead: BigInt(route.skip_ahead.toWei())
29005
- })),
29006
- token_amount: {
29007
- token: swap.token_amount.token.toBigInt(),
29008
- amount: swap.token_amount.amount.toI129()
29009
- }
29010
- })),
29011
- withdraw_swap_limit_amount: BigInt(_params.withdraw_swap_limit_amount.toWei()),
29012
- withdraw_swap_weights: _params.withdraw_swap_weights.map((weight) => BigInt(weight.toWei())),
29013
- close_position: _params.close_position
29014
- } })
29235
+ withdraw_swap_limit_amount: BigInt(
29236
+ _params.withdraw_swap_limit_amount.toWei()
29237
+ ),
29238
+ withdraw_swap_weights: _params.withdraw_swap_weights.map(
29239
+ (weight) => BigInt(weight.toWei())
29240
+ ),
29241
+ close_position: _params.close_position
29242
+ }
29243
+ })
29015
29244
  };
29016
29245
  }
29017
29246
  async getHealthFactor() {
@@ -29020,11 +29249,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29020
29249
  }
29021
29250
  async getNetAPY() {
29022
29251
  const positions = await this.getPositions();
29023
- logger.verbose(`${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`);
29252
+ logger.verbose(
29253
+ `${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`
29254
+ );
29024
29255
  const allZero = positions.every((p) => p.usdValue === 0);
29025
29256
  if (allZero) {
29026
29257
  const collateralUSD = 1e3;
29027
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
29258
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
29259
+ this.config.networkConfig
29260
+ );
29028
29261
  const targetHF = this.config.targetHealthFactor;
29029
29262
  const maxDebt = HealthFactorMath.getMaxDebtAmountOnLooping(
29030
29263
  new Web3Number(collateralUSD, this.config.collateral.decimals),
@@ -29401,7 +29634,10 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29401
29634
  //abstract means the method has no implementation in this class; instead, child classes must implement it.
29402
29635
  async getAPY(supportedPosition) {
29403
29636
  const side = supportedPosition.isDebt ? "LONG" : "SHORT";
29404
- const fundingRates = await this.client.getFundingRates(this.config.extendedMarketName, side);
29637
+ const fundingRates = await this.client.getFundingRates(
29638
+ this.config.extendedMarketName,
29639
+ side
29640
+ );
29405
29641
  if (fundingRates.status !== "OK") {
29406
29642
  logger.error("error getting funding rates", fundingRates);
29407
29643
  return { apy: 0, type: "base" /* BASE */ };
@@ -29445,14 +29681,14 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29445
29681
  });
29446
29682
  }
29447
29683
  _getDepositLeaf() {
29448
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29684
+ const usdceToken = Global.getDefaultTokens().find(
29685
+ (token) => token.symbol === "USDCe"
29686
+ );
29449
29687
  return [
29450
29688
  {
29451
29689
  target: this.config.supportedPositions[0].asset.address,
29452
29690
  method: "approve",
29453
- packedArguments: [
29454
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
29455
- ],
29691
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29456
29692
  id: `extended_approve_${this.config.supportedPositions[0].asset.symbol}`,
29457
29693
  sanitizer: AVNU_LEGACY_SANITIZER
29458
29694
  },
@@ -29483,25 +29719,33 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29483
29719
  const leafConfigs = this._getSwapFromLegacyLeaf();
29484
29720
  const leaves = leafConfigs.map((config) => {
29485
29721
  const { target, method, packedArguments, sanitizer, id } = config;
29486
- const leaf = this.constructSimpleLeafData({
29487
- id,
29488
- target,
29489
- method,
29490
- packedArguments
29491
- }, sanitizer);
29722
+ const leaf = this.constructSimpleLeafData(
29723
+ {
29724
+ id,
29725
+ target,
29726
+ method,
29727
+ packedArguments
29728
+ },
29729
+ sanitizer
29730
+ );
29492
29731
  return leaf;
29493
29732
  });
29494
- return { leaves, callConstructor: this.getSwapFromLegacyCall.bind(this) };
29733
+ return {
29734
+ leaves,
29735
+ callConstructor: this.getSwapFromLegacyCall.bind(
29736
+ this
29737
+ )
29738
+ };
29495
29739
  }
29496
29740
  _getSwapFromLegacyLeaf() {
29497
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29741
+ const usdceToken = Global.getDefaultTokens().find(
29742
+ (token) => token.symbol === "USDCe"
29743
+ );
29498
29744
  return [
29499
29745
  {
29500
29746
  target: usdceToken.address,
29501
29747
  method: "approve",
29502
- packedArguments: [
29503
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
29504
- ],
29748
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29505
29749
  id: `extendedswaplegacyapprove_${usdceToken.symbol}`,
29506
29750
  sanitizer: AVNU_LEGACY_SANITIZER
29507
29751
  },
@@ -29520,11 +29764,13 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29520
29764
  async getDepositCall(params) {
29521
29765
  try {
29522
29766
  const usdcToken = this.config.supportedPositions[0].asset;
29523
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29524
- const salt = Math.floor(
29525
- Math.random() * 10 ** usdcToken.decimals
29767
+ const usdceToken = Global.getDefaultTokens().find(
29768
+ (token) => token.symbol === "USDCe"
29769
+ );
29770
+ const salt = Math.floor(Math.random() * 10 ** usdcToken.decimals);
29771
+ const amount = uint25613.bnToUint256(
29772
+ params.amount.multipliedBy(10).toWei()
29526
29773
  );
29527
- const amount = uint25613.bnToUint256(params.amount.multipliedBy(10).toWei());
29528
29774
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
29529
29775
  usdcToken.address.toString(),
29530
29776
  usdceToken.address.toString(),
@@ -29537,7 +29783,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29537
29783
  logger.error("error getting quotes from avnu");
29538
29784
  return [];
29539
29785
  }
29540
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
29786
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
29787
+ quotes
29788
+ );
29541
29789
  const swapCallData = getCalldata[0];
29542
29790
  return [
29543
29791
  {
@@ -29613,8 +29861,12 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29613
29861
  async getSwapFromLegacyCall(params) {
29614
29862
  try {
29615
29863
  const usdcToken = this.config.supportedPositions[0].asset;
29616
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29617
- const amount = uint25613.bnToUint256(params.amount.multipliedBy(10).toWei());
29864
+ const usdceToken = Global.getDefaultTokens().find(
29865
+ (token) => token.symbol === "USDCe"
29866
+ );
29867
+ const amount = uint25613.bnToUint256(
29868
+ params.amount.multipliedBy(10).toWei()
29869
+ );
29618
29870
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
29619
29871
  usdceToken.address.toString(),
29620
29872
  usdcToken.address.toString(),
@@ -29627,7 +29879,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29627
29879
  logger.error("error getting quotes from avnu");
29628
29880
  return [];
29629
29881
  }
29630
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
29882
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
29883
+ quotes
29884
+ );
29631
29885
  const swapCallData = getCalldata[0];
29632
29886
  return [
29633
29887
  {
@@ -29675,9 +29929,14 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29675
29929
  if (!this.client) {
29676
29930
  throw new Error("Client not initialized");
29677
29931
  }
29678
- const withdrawalRequest = await this.client.withdrawUSDC(amount.toFixed(2));
29932
+ const withdrawalRequest = await this.client.withdrawUSDC(
29933
+ amount.toFixed(2)
29934
+ );
29679
29935
  if (withdrawalRequest.status === "OK") {
29680
- const withdrawalStatus = await this.getDepositOrWithdrawalStatus(withdrawalRequest.data, "WITHDRAWAL" /* WITHDRAWAL */);
29936
+ const withdrawalStatus = await this.getDepositOrWithdrawalStatus(
29937
+ withdrawalRequest.data,
29938
+ "WITHDRAWAL" /* WITHDRAWAL */
29939
+ );
29681
29940
  return withdrawalStatus;
29682
29941
  }
29683
29942
  return false;
@@ -29750,17 +30009,34 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29750
30009
  logger.error("error initializing client");
29751
30010
  return null;
29752
30011
  }
29753
- const orderhistory = await this.getOrderHistory(marketName);
30012
+ let orderhistory = await this.getOrderHistory(marketName);
29754
30013
  if (!orderhistory || orderhistory.length === 0) {
29755
- logger.error(`error getting order: ${orderId}`);
29756
- return null;
30014
+ logger.error(`error getting order history: ${orderId}`);
30015
+ } else {
30016
+ const order = orderhistory.slice(0, 5).find((order2) => order2.id.toString() === orderId);
30017
+ if (order) {
30018
+ return order;
30019
+ }
29757
30020
  }
29758
- const order = orderhistory.slice(0, 3).find((order2) => order2.id.toString() === orderId);
29759
- if (!order) {
29760
- logger.error(`error getting order: ${order}`);
29761
- return null;
30021
+ for (let attempt = 1; attempt <= 3; attempt++) {
30022
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
30023
+ orderhistory = await this.getOrderHistory(marketName);
30024
+ if (!orderhistory || orderhistory.length === 0) {
30025
+ logger.error(
30026
+ `error getting order history on retry ${attempt}: ${orderId}`
30027
+ );
30028
+ continue;
30029
+ }
30030
+ const order = orderhistory.slice(0, 5).find((order2) => order2.id.toString() === orderId);
30031
+ if (order) {
30032
+ return order;
30033
+ }
30034
+ logger.error(
30035
+ `order not found in top 5 entries on retry ${attempt}: ${orderId}`
30036
+ );
29762
30037
  }
29763
- return order;
30038
+ logger.error(`error getting order after all retries: ${orderId}`);
30039
+ return null;
29764
30040
  }
29765
30041
  async fetchOrderBookBTCUSDC() {
29766
30042
  try {
@@ -29833,7 +30109,10 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29833
30109
  return null;
29834
30110
  }
29835
30111
  await new Promise((resolve) => setTimeout(resolve, 5e3));
29836
- const openOrder = await this.getOrderStatus(result.position_id, this.config.extendedMarketName);
30112
+ const openOrder = await this.getOrderStatus(
30113
+ result.position_id,
30114
+ this.config.extendedMarketName
30115
+ );
29837
30116
  if (!openOrder || openOrder.status !== "FILLED" /* FILLED */) {
29838
30117
  if (attempt >= maxAttempts) {
29839
30118
  logger.error("Max retries reached \u2014 could not verify open position");
@@ -29856,7 +30135,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29856
30135
  };
29857
30136
  }
29858
30137
  } catch (err) {
29859
- logger.error(`createShortOrder failed on attempt ${attempt}: ${err.message}`);
30138
+ logger.error(
30139
+ `createShortOrder failed on attempt ${attempt}: ${err.message}`
30140
+ );
29860
30141
  if (attempt < maxAttempts) {
29861
30142
  const backoff = 1200 * attempt;
29862
30143
  logger.info(`Retrying after ${backoff}ms...`);
@@ -29901,13 +30182,17 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29901
30182
  operationsStatus: ["COMPLETED" /* COMPLETED */]
29902
30183
  });
29903
30184
  if (operationsType === "DEPOSIT" /* DEPOSIT */) {
29904
- const myTransferStatus = transferHistory.data.find((operation) => operation.transactionHash === orderId);
30185
+ const myTransferStatus = transferHistory.data.find(
30186
+ (operation) => operation.transactionHash === orderId
30187
+ );
29905
30188
  if (!myTransferStatus) {
29906
30189
  return true;
29907
30190
  }
29908
30191
  return true;
29909
30192
  } else {
29910
- const myTransferStatus = transferHistory.data.find((operation) => operation.id.toString() === orderId.toString());
30193
+ const myTransferStatus = transferHistory.data.find(
30194
+ (operation) => operation.id.toString() === orderId.toString()
30195
+ );
29911
30196
  if (!myTransferStatus) {
29912
30197
  return true;
29913
30198
  }
@@ -33525,6 +33810,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33525
33810
  toToken.decimals,
33526
33811
  true
33527
33812
  );
33813
+ console.log(`${_AvnuAdapter.name}::getDepositCall quote: ${quote?.sellAmountInUsd}`);
33528
33814
  if (!quote) {
33529
33815
  logger.error("error getting quote from avnu");
33530
33816
  return [];
@@ -33643,7 +33929,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33643
33929
  }
33644
33930
  throw new Error("Failed to fetch quote after retries");
33645
33931
  }
33646
- async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e3) {
33932
+ async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 5e3) {
33647
33933
  try {
33648
33934
  const fromToken = this.config.supportedPositions[0].asset;
33649
33935
  const toToken = this.config.supportedPositions[1].asset;
@@ -33883,7 +34169,8 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33883
34169
  }
33884
34170
  const balance = await this.getUnusedBalance();
33885
34171
  const usdcBalanceOnExtended = await extendedAdapter.getExtendedDepositAmount();
33886
- const amountToInvest = balance.amount.plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
34172
+ const amountToInvest = new Web3Number(balance.usdValue, USDC_TOKEN_DECIMALS).plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
34173
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest amountToInvest: ${amountToInvest.toNumber()}`);
33887
34174
  if (amountToInvest.lessThan(0)) {
33888
34175
  return {
33889
34176
  shouldInvest: false,
@@ -33936,6 +34223,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33936
34223
  vesuLeverage: 0
33937
34224
  };
33938
34225
  }
34226
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest vesu_amount: ${vesu_amount.toNumber()}, extended_amount: ${extended_amount.toNumber()}`);
33939
34227
  return {
33940
34228
  shouldInvest: true,
33941
34229
  vesuAmount: vesu_amount,
@@ -34015,15 +34303,15 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34015
34303
  }
34016
34304
  const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
34017
34305
  const usdcAmountOnExtended = parseFloat(
34018
- extendedHoldings.availableForTrade
34306
+ extendedHoldings.availableForWithdrawal
34019
34307
  );
34020
- if (extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended).greaterThan(0)) {
34308
+ if (extendedAmount.minus(usdcAmountOnExtended).greaterThan(0)) {
34021
34309
  try {
34022
34310
  const { calls: extendedCalls } = await this.moveAssets(
34023
34311
  {
34024
34312
  to: Protocols.EXTENDED.name,
34025
34313
  from: Protocols.VAULT.name,
34026
- amount: extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended)
34314
+ amount: extendedAmount.minus(usdcAmountOnExtended)
34027
34315
  },
34028
34316
  extendedAdapter,
34029
34317
  vesuAdapter
@@ -34130,7 +34418,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34130
34418
  const withdrawalFromExtended = await extendedAdapter.withdrawFromExtended(params.amount);
34131
34419
  if (withdrawalFromExtended) {
34132
34420
  const extendedHoldings2 = await extendedAdapter.getExtendedDepositAmount();
34133
- logger.info(`extendedHoldings after withdrawal ${extendedHoldings2}`);
34421
+ logger.info(`extendedHoldings after withdrawal ${extendedHoldings2?.availableForWithdrawal}`);
34134
34422
  await new Promise((resolve) => setTimeout(resolve, 1e4));
34135
34423
  const calls = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
34136
34424
  if (calls.length > 0) {
@@ -34261,7 +34549,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34261
34549
  };
34262
34550
  }
34263
34551
  const extendedHoldingAmount = new Web3Number(
34264
- extendedHoldings.availableForTrade,
34552
+ extendedHoldings.availableForWithdrawal,
34265
34553
  USDC_TOKEN_DECIMALS
34266
34554
  );
34267
34555
  const {
@@ -34321,7 +34609,6 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34321
34609
  extendedAmountInBTC: new Web3Number(0, 0),
34322
34610
  calls: []
34323
34611
  };
34324
- ;
34325
34612
  }
34326
34613
  }
34327
34614
  async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter) {