@strkfarm/sdk 2.0.0-dev.1 → 2.0.0-dev.11

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.js CHANGED
@@ -76,6 +76,7 @@ __export(index_exports, {
76
76
  PRICE_ROUTER: () => PRICE_ROUTER,
77
77
  PasswordJsonCryptoUtil: () => PasswordJsonCryptoUtil,
78
78
  PositionSide: () => PositionSide,
79
+ PositionTypeAvnuExtended: () => PositionTypeAvnuExtended,
79
80
  Pragma: () => Pragma,
80
81
  Pricer: () => Pricer,
81
82
  PricerBase: () => PricerBase,
@@ -4474,20 +4475,13 @@ var EkuboQuoter = class _EkuboQuoter {
4474
4475
  async getDexPrice(baseToken, quoteToken, amount) {
4475
4476
  const lstTokenInfo = baseToken;
4476
4477
  const lstUnderlyingTokenInfo = quoteToken;
4477
- console.log("lstTokenInfo", lstTokenInfo);
4478
- console.log("lstUnderlyingTokenInfo", lstUnderlyingTokenInfo);
4479
- console.log("amount", amount);
4480
4478
  const quote = await this.getQuote(
4481
4479
  lstTokenInfo.address.address,
4482
4480
  lstUnderlyingTokenInfo.address.address,
4483
4481
  amount
4484
4482
  );
4485
- console.log("quote", quote);
4486
4483
  const outputAmount = Web3Number.fromWei(quote.total_calculated, lstUnderlyingTokenInfo.decimals);
4487
- console.log("outputAmount", outputAmount);
4488
- console.log("amount", amount);
4489
4484
  const price = outputAmount.toNumber() / amount.toNumber();
4490
- console.log("price", price);
4491
4485
  logger.verbose(`${_EkuboQuoter.name}:: LST Dex Price: ${price}`);
4492
4486
  return price;
4493
4487
  }
@@ -4506,16 +4500,12 @@ var EkuboQuoter = class _EkuboQuoter {
4506
4500
  // debt collateral
4507
4501
  async getSwapLimitAmount(fromToken, toToken, amount, max_slippage = 2e-3) {
4508
4502
  const isExactAmountIn = amount.greaterThanOrEqualTo(0);
4509
- console.log("isExactAmountIn", isExactAmountIn);
4510
4503
  logger.verbose(`${_EkuboQuoter.name}::getSwapLimitAmount isExactAmountIn: ${isExactAmountIn}, fromToken: ${fromToken.symbol}, toToken: ${toToken.symbol}, amount: ${amount}`);
4511
4504
  const isYieldToken = this.tokenMarketData.isAPYSupported(toToken);
4512
4505
  console.log("isYieldToken", isYieldToken);
4513
4506
  const baseToken = isExactAmountIn ? toToken : fromToken;
4514
4507
  const quoteToken = isExactAmountIn ? fromToken : toToken;
4515
- console.log("baseToken", baseToken);
4516
- console.log("quoteToken", quoteToken);
4517
4508
  const dexPrice = await this.getDexPrice(baseToken, quoteToken, amount);
4518
- console.log("dexPrice", dexPrice);
4519
4509
  const trueExchangeRate = isYieldToken ? await this.tokenMarketData.getTruePrice(baseToken) : dexPrice;
4520
4510
  console.log("trueExchangeRate", trueExchangeRate);
4521
4511
  if (isExactAmountIn) {
@@ -28163,6 +28153,7 @@ var vesu_multiple_abi_default = [
28163
28153
  var AVNU_API = "https://starknet.api.avnu.fi/swap/v2/quotes";
28164
28154
  var USDC_TOKEN_DECIMALS = 6;
28165
28155
  var USDC_TOKEN_ADDRESS = "0x053C91253BC9682c04929cA02ED00b3E423f6710D2ee7e0D5EBB06F3eCF368A8";
28156
+ var BUFFER_USDC_IN_WITHDRAWAL = 5;
28166
28157
  var WBTC_TOKEN_ADDRESS = "0x3fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac";
28167
28158
  var WBTC_TOKEN_DECIMALS = 8;
28168
28159
  var MAINTENANCE_MARGIN = 0.01;
@@ -28178,7 +28169,8 @@ var STRK_API_RPC = process.env.STRK_API_RPC ?? "https://mainnet.starknet.a5a.ch"
28178
28169
  var MAX_RETRIES = Number(process.env.MAX_RETRIES ?? 3);
28179
28170
  var MAX_DELAY = Number(process.env.MAX_DELAY ?? 100);
28180
28171
  var EXTEND_MARKET_NAME = "BTC-USD";
28181
- var LIMIT_BALANCE = Number(process.env.LIMIT_BALANCE ?? 10);
28172
+ var LIMIT_BALANCE = Number(process.env.LIMIT_BALANCE ?? 0.05);
28173
+ var LIMIT_BALANCE_VALUE = 10;
28182
28174
  var REBALANCER_INTERVAL = Number(process.env.REBALANCER_INTERVAL ?? 18e4);
28183
28175
  var WITHDRAWAL_INTERVAL = Number(process.env.WITHDRAWAL_INTERVAL ?? 18e6);
28184
28176
  var INVESTING_INTERVAL = Number(process.env.INVESTING_INTERVAL ?? 18e4);
@@ -28196,8 +28188,6 @@ var PRICE_MAX_SLIPPAGE_EKUBO = Number(process.env.PRICE_MAX_SLIPPAGE_EKUBO ?? 5e
28196
28188
  var MINIMUM_DEBT_AMOUNT_VESU_FOR_REBALANCING = Number(process.env.MINIMUM_DEBT_AMOUNT_VESU_FOR_REBALANCING ?? 1);
28197
28189
  var MINIMUM_EXTENDED_POSITION_SIZE = 1e-4;
28198
28190
  var MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP = 1e-5;
28199
- var MAX_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED = 700;
28200
- var MIN_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED = -100;
28201
28191
 
28202
28192
  // src/strategies/vesu-extended-strategy/utils/helper.ts
28203
28193
  var returnFormattedAmount = (amount, toTokenDecimals) => {
@@ -28217,8 +28207,7 @@ var calculateAmountDistribution = async (amount, client, marketName, collateralP
28217
28207
  vesu_leverage: 0
28218
28208
  };
28219
28209
  }
28220
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28221
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
28210
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28222
28211
  const vesuBTCExposureUSD = collateralUnits.multipliedBy(collateralPrice);
28223
28212
  const numerator1 = vesu_leverage * amount + vesuBTCExposureUSD.toNumber();
28224
28213
  const numerator2 = extendedExposureUSD.toNumber();
@@ -28254,8 +28243,7 @@ var calculateAmountDistributionForWithdrawal = async (amountInUsdc, collateralPr
28254
28243
  logger.error("error getting extended positions");
28255
28244
  return null;
28256
28245
  }
28257
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
28258
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
28246
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, USDC_TOKEN_DECIMALS) : new Web3Number(0, USDC_TOKEN_DECIMALS);
28259
28247
  const vesuExposureUSD = collateralUnits.multipliedBy(collateralPrice);
28260
28248
  if (vesuExposureUSD.lessThan(0)) {
28261
28249
  return {
@@ -28273,9 +28261,14 @@ var calculateAmountDistributionForWithdrawal = async (amountInUsdc, collateralPr
28273
28261
  vesu_leverage
28274
28262
  };
28275
28263
  }
28264
+ console.log("the vesu exposure usd is", vesuExposureUSD.toNumber());
28265
+ console.log("the extended exposure usd is", extendedExposureUSD.toNumber());
28266
+ console.log("the amount in usdc is", amountInUsdc.toNumber());
28267
+ console.log("the extended leverage is", extended_leverage);
28268
+ console.log("the vesu leverage is", vesu_leverage);
28276
28269
  const numerator1 = amountInUsdc.multipliedBy(extended_leverage);
28277
- const numerator2 = vesuExposureUSD.multipliedBy(vesu_leverage);
28278
- const numerator3 = extendedExposureUSD.multipliedBy(extended_leverage).multipliedBy(-1);
28270
+ const numerator2 = vesuExposureUSD;
28271
+ const numerator3 = extendedExposureUSD.multipliedBy(-1);
28279
28272
  const finalNumerator = numerator1.plus(numerator2).plus(numerator3);
28280
28273
  const denominator = extended_leverage + vesu_leverage;
28281
28274
  const vesuAmountInUSDC = finalNumerator.dividedBy(denominator);
@@ -28285,6 +28278,7 @@ var calculateAmountDistributionForWithdrawal = async (amountInUsdc, collateralPr
28285
28278
  "the extended amount in usdc is",
28286
28279
  extendedAmountInUSDC.toNumber()
28287
28280
  );
28281
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
28288
28282
  return {
28289
28283
  vesu_amount: vesuAmountInUSDC,
28290
28284
  extended_amount: extendedAmountInUSDC,
@@ -28306,10 +28300,10 @@ var calculateExtendedLevergae = () => {
28306
28300
  const extended_leverage_max = 1 / (MAINTENANCE_MARGIN + MAX_PRICE_DROP_PERCENTAGE);
28307
28301
  return Math.floor(extended_leverage_max);
28308
28302
  };
28309
- var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LTV_BTC_USDC, addedAmount, collateralPrice, isDeposit) => {
28303
+ var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LIQUIDATION_RATIO, addedAmount, collateralPrice, isDeposit) => {
28310
28304
  try {
28311
- const marginAmount = addedAmount.multipliedBy(isDeposit ? 1 : -1);
28312
- const numerator1 = collateralAmount.plus(addedAmount).multipliedBy(collateralPrice).multipliedBy(maxLtv);
28305
+ const addedCollateral = addedAmount.multipliedBy(isDeposit ? 1 : -1);
28306
+ const numerator1 = collateralAmount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(maxLtv);
28313
28307
  const numerator2 = debtAmount.multipliedBy(debtPrice).multipliedBy(TARGET_HF);
28314
28308
  const denominator = TARGET_HF - maxLtv;
28315
28309
  const x_debt_usd = numerator1.minus(numerator2).dividedBy(denominator);
@@ -28344,16 +28338,16 @@ var calculateAmountDepositOnExtendedWhenIncurringLosses = async (client) => {
28344
28338
  const extendedHoldings = await client.getHoldings();
28345
28339
  const extended_leverage = calculateExtendedLevergae();
28346
28340
  const latestPosition = (await client.getPositions()).data.pop();
28347
- console.log("the latest position is", latestPosition, extendedHoldings);
28348
28341
  if (!extendedHoldings || !latestPosition) {
28349
28342
  logger.error(`error getting extended position: extendedHoldings=${extendedHoldings}, latestPosition=${latestPosition}`);
28350
28343
  return null;
28351
28344
  }
28352
- const positionValueInUSD = latestPosition.value;
28345
+ const positionValueInUSD = new Web3Number(latestPosition.value, USDC_TOKEN_DECIMALS);
28353
28346
  const equity = extendedHoldings.data.equity;
28354
- const deposit = Number(positionValueInUSD) / extended_leverage - Number(equity);
28355
- return new Web3Number(Math.floor(deposit / 0.2) * 0.2, USDC_TOKEN_DECIMALS);
28347
+ const deposit = positionValueInUSD.dividedBy(extended_leverage).minus(equity).toFixed(2);
28348
+ return new Web3Number(deposit, USDC_TOKEN_DECIMALS);
28356
28349
  } catch (err) {
28350
+ logger.error(`error calculating amount deposit on extended when incurring losses: ${err}`);
28357
28351
  return null;
28358
28352
  }
28359
28353
  };
@@ -28431,21 +28425,36 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28431
28425
  vaultAllocator: config.vaultAllocator,
28432
28426
  id: ""
28433
28427
  });
28434
- this.tokenMarketData = new TokenMarketData(this.config.pricer, this.config.networkConfig);
28428
+ this.minimumVesuMovementAmount = config.minimumVesuMovementAmount ?? 5;
28429
+ this.tokenMarketData = new TokenMarketData(
28430
+ this.config.pricer,
28431
+ this.config.networkConfig
28432
+ );
28435
28433
  }
28436
28434
  async getAPY(supportedPosition) {
28437
28435
  const CACHE_KEY = `apy_${this.config.poolId.address}_${supportedPosition.asset.symbol}`;
28438
28436
  const cacheData = this.getCache(CACHE_KEY);
28439
- console.log(`${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(cacheData)}`, this.vesuAdapter.config.poolId.shortString(), this.vesuAdapter.config.collateral.symbol, this.vesuAdapter.config.debt.symbol);
28437
+ console.log(
28438
+ `${_VesuMultiplyAdapter.name}::getAPY cacheData: ${JSON.stringify(
28439
+ cacheData
28440
+ )}`,
28441
+ this.vesuAdapter.config.poolId.shortString(),
28442
+ this.vesuAdapter.config.collateral.symbol,
28443
+ this.vesuAdapter.config.debt.symbol
28444
+ );
28440
28445
  if (cacheData) {
28441
28446
  return cacheData;
28442
28447
  }
28443
28448
  try {
28444
28449
  const allVesuPools = await VesuAdapter.getVesuPools();
28445
28450
  const asset = supportedPosition.asset;
28446
- const pool = allVesuPools.pools.find((p) => this.vesuAdapter.config.poolId.eqString(import_starknet21.num.getHexString(p.id)));
28451
+ const pool = allVesuPools.pools.find(
28452
+ (p) => this.vesuAdapter.config.poolId.eqString(import_starknet21.num.getHexString(p.id))
28453
+ );
28447
28454
  if (!pool) {
28448
- logger.warn(`VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`);
28455
+ logger.warn(
28456
+ `VesuMultiplyAdapter: Pool not found for token ${asset.symbol}`
28457
+ );
28449
28458
  return {
28450
28459
  apy: 0,
28451
28460
  type: "base" /* BASE */
@@ -28455,7 +28464,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28455
28464
  (a) => a.symbol.toLowerCase() === asset.symbol.toLowerCase()
28456
28465
  )?.stats;
28457
28466
  if (!assetStats) {
28458
- logger.warn(`VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`);
28467
+ logger.warn(
28468
+ `VesuMultiplyAdapter: Asset stats not found for token ${asset.symbol}`
28469
+ );
28459
28470
  return {
28460
28471
  apy: 0,
28461
28472
  type: "base" /* BASE */
@@ -28466,7 +28477,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28466
28477
  apy = Number(assetStats.borrowApr?.value || 0) / 1e18;
28467
28478
  } else {
28468
28479
  const isAssetBTC = asset.symbol.toLowerCase().includes("btc");
28469
- const baseAPY = Number(isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0) / 1e18;
28480
+ const baseAPY = Number(
28481
+ isAssetBTC ? assetStats.btcFiSupplyApr?.value + assetStats.supplyApy?.value : assetStats.supplyApy?.value || 0
28482
+ ) / 1e18;
28470
28483
  const rewardAPY = Number(assetStats.defiSpringSupplyApr?.value || "0") / 1e18;
28471
28484
  const isSupported = this.tokenMarketData.isAPYSupported(asset);
28472
28485
  apy = baseAPY + rewardAPY;
@@ -28482,7 +28495,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28482
28495
  this.setCache(CACHE_KEY, result, 3e5);
28483
28496
  return result;
28484
28497
  } catch (error) {
28485
- logger.error(`VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`, error);
28498
+ logger.error(
28499
+ `VesuMultiplyAdapter: Error getting APY for ${supportedPosition.asset.symbol}:`,
28500
+ error
28501
+ );
28486
28502
  throw error;
28487
28503
  }
28488
28504
  }
@@ -28495,12 +28511,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28495
28511
  try {
28496
28512
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28497
28513
  this.vesuAdapter.pricer = this.config.pricer;
28498
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28514
+ const positions = await this.vesuAdapter.getPositions(
28515
+ this.config.networkConfig
28516
+ );
28499
28517
  let position = positions.find(
28500
28518
  (p) => p.token.address.eq(supportedPosition.asset.address)
28501
28519
  );
28502
28520
  if (!position) {
28503
- logger.warn(`VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`);
28521
+ logger.warn(
28522
+ `VesuMultiplyAdapter: Position not found for token ${supportedPosition.asset.symbol}`
28523
+ );
28504
28524
  return {
28505
28525
  amount: new Web3Number("0", supportedPosition.asset.decimals),
28506
28526
  remarks: "Position not found"
@@ -28513,12 +28533,18 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28513
28533
  this.setCache(CACHE_KEY, position, 6e4);
28514
28534
  return position;
28515
28535
  } catch (error) {
28516
- logger.error(`VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`, error);
28536
+ logger.error(
28537
+ `VesuMultiplyAdapter: Error getting position for ${supportedPosition.asset.symbol}:`,
28538
+ error
28539
+ );
28517
28540
  throw error;
28518
28541
  }
28519
28542
  }
28520
28543
  async maxBorrowableAPY() {
28521
- const collateralAPY = await this.getAPY({ asset: this.config.collateral, isDebt: false });
28544
+ const collateralAPY = await this.getAPY({
28545
+ asset: this.config.collateral,
28546
+ isDebt: false
28547
+ });
28522
28548
  const apy = collateralAPY.apy * 0.8;
28523
28549
  return apy;
28524
28550
  }
@@ -28528,9 +28554,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28528
28554
  try {
28529
28555
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28530
28556
  this.vesuAdapter.pricer = this.config.pricer;
28531
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28532
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28533
- const debtPosition = positions.find((p) => p.token.address.eq(debt.address));
28557
+ const positions = await this.vesuAdapter.getPositions(
28558
+ this.config.networkConfig
28559
+ );
28560
+ const collateralPosition = positions.find(
28561
+ (p) => p.token.address.eq(collateral.address)
28562
+ );
28563
+ const debtPosition = positions.find(
28564
+ (p) => p.token.address.eq(debt.address)
28565
+ );
28534
28566
  if (!collateralPosition || !debtPosition) {
28535
28567
  throw new Error("Could not find current positions");
28536
28568
  }
@@ -28540,13 +28572,23 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28540
28572
  debt,
28541
28573
  maxBorrowableAPY
28542
28574
  );
28543
- logger.verbose(`VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`);
28544
- const debtCap = await this.vesuAdapter.getDebtCap(this.config.networkConfig);
28575
+ logger.verbose(
28576
+ `VesuMultiplyAdapter: Max borrowable: ${maxBorrowable.toNumber()}`
28577
+ );
28578
+ const debtCap = await this.vesuAdapter.getDebtCap(
28579
+ this.config.networkConfig
28580
+ );
28545
28581
  logger.verbose(`VesuMultiplyAdapter: Debt cap: ${debtCap.toNumber()}`);
28546
28582
  const actualMaxBorrowable = maxBorrowable.minimum(debtCap);
28547
- logger.verbose(`VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`);
28548
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
28549
- const collateralPrice = await this.config.pricer.getPrice(collateral.symbol);
28583
+ logger.verbose(
28584
+ `VesuMultiplyAdapter: Actual max borrowable: ${actualMaxBorrowable.toNumber()}`
28585
+ );
28586
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
28587
+ this.config.networkConfig
28588
+ );
28589
+ const collateralPrice = await this.config.pricer.getPrice(
28590
+ collateral.symbol
28591
+ );
28550
28592
  if (collateralPrice.price === 0) {
28551
28593
  throw new Error("Collateral price is 0");
28552
28594
  }
@@ -28564,14 +28606,25 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28564
28606
  );
28565
28607
  const maxDepositAmount = amount ? amount.minimum(maxCollateralFromDebt) : maxCollateralFromDebt;
28566
28608
  const usdValue = await this.getUSDValue(collateral, maxDepositAmount);
28567
- logger.verbose(`VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`);
28568
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28569
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28609
+ logger.verbose(
28610
+ `VesuMultiplyAdapter: Max deposit::USD value: ${usdValue}, amount: ${maxDepositAmount.toNumber()}`
28611
+ );
28612
+ const apys = await Promise.all([
28613
+ this.getAPY({ asset: collateral, isDebt: false }),
28614
+ this.getAPY({ asset: debt, isDebt: true })
28615
+ ]);
28616
+ logger.verbose(
28617
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28618
+ );
28570
28619
  const borrowAmountUSD = actualMaxBorrowable.multipliedBy(debtPrice.price);
28571
- logger.verbose(`VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`);
28620
+ logger.verbose(
28621
+ `VesuMultiplyAdapter: Borrow amount: ${actualMaxBorrowable.toNumber()}, borrow amount USD: ${borrowAmountUSD.toNumber()}`
28622
+ );
28572
28623
  const netCollateralUSD = usdValue + borrowAmountUSD.toNumber();
28573
28624
  const netAPY = (apys[0].apy * netCollateralUSD + apys[1].apy * borrowAmountUSD.toNumber()) / usdValue;
28574
- logger.verbose(`VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`);
28625
+ logger.verbose(
28626
+ `VesuMultiplyAdapter: Max deposit amount: ${maxDepositAmount.toNumber()}, netAPY: ${netAPY}`
28627
+ );
28575
28628
  return {
28576
28629
  tokenInfo: collateral,
28577
28630
  amount: maxDepositAmount,
@@ -28584,7 +28637,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28584
28637
  protocol: this.protocol
28585
28638
  };
28586
28639
  } catch (error) {
28587
- logger.error(`VesuMultiplyAdapter: Error calculating max deposit:`, error);
28640
+ logger.error(
28641
+ `VesuMultiplyAdapter: Error calculating max deposit:`,
28642
+ error
28643
+ );
28588
28644
  throw error;
28589
28645
  }
28590
28646
  }
@@ -28594,9 +28650,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28594
28650
  try {
28595
28651
  this.vesuAdapter.networkConfig = this.config.networkConfig;
28596
28652
  this.vesuAdapter.pricer = this.config.pricer;
28597
- const positions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28598
- const collateralPosition = positions.find((p) => p.token.address.eq(collateral.address));
28599
- const debtPosition = positions.find((p) => p.token.address.eq(this.config.debt.address));
28653
+ const positions = await this.vesuAdapter.getPositions(
28654
+ this.config.networkConfig
28655
+ );
28656
+ const collateralPosition = positions.find(
28657
+ (p) => p.token.address.eq(collateral.address)
28658
+ );
28659
+ const debtPosition = positions.find(
28660
+ (p) => p.token.address.eq(this.config.debt.address)
28661
+ );
28600
28662
  if (!collateralPosition || !debtPosition) {
28601
28663
  throw new Error("Could not find current positions");
28602
28664
  }
@@ -28606,11 +28668,20 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28606
28668
  const result = maxWithdrawable.greaterThan(0) ? maxWithdrawable : new Web3Number("0", collateral.decimals);
28607
28669
  const usdValue = await this.getUSDValue(collateral, result);
28608
28670
  const debtUSD = debtPosition.usdValue;
28609
- logger.verbose(`VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`);
28610
- const apys = await Promise.all([this.getAPY({ asset: collateral, isDebt: false }), this.getAPY({ asset: debt, isDebt: true })]);
28611
- logger.verbose(`VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`);
28671
+ logger.verbose(
28672
+ `VesuMultiplyAdapter: Debt USD: ${debtUSD}, collateral USD: ${usdValue}`
28673
+ );
28674
+ const apys = await Promise.all([
28675
+ this.getAPY({ asset: collateral, isDebt: false }),
28676
+ this.getAPY({ asset: debt, isDebt: true })
28677
+ ]);
28678
+ logger.verbose(
28679
+ `VesuMultiplyAdapter: Apys: ${apys[0].apy}, ${apys[1].apy}`
28680
+ );
28612
28681
  const netAPY = usdValue - debtUSD > 0 ? (apys[0].apy * usdValue + apys[1].apy * debtUSD) / (usdValue - debtUSD) : 0;
28613
- logger.verbose(`VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`);
28682
+ logger.verbose(
28683
+ `VesuMultiplyAdapter: Max withdraw amount: ${result.toNumber()}, netAPY: ${netAPY}`
28684
+ );
28614
28685
  return {
28615
28686
  tokenInfo: collateral,
28616
28687
  amount: result,
@@ -28623,14 +28694,19 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28623
28694
  protocol: this.protocol
28624
28695
  };
28625
28696
  } catch (error) {
28626
- logger.error(`VesuMultiplyAdapter: Error calculating max withdraw:`, error);
28697
+ logger.error(
28698
+ `VesuMultiplyAdapter: Error calculating max withdraw:`,
28699
+ error
28700
+ );
28627
28701
  throw error;
28628
28702
  }
28629
28703
  }
28630
28704
  _getDepositLeaf() {
28631
28705
  const collateral = this.config.collateral;
28632
28706
  const debt = this.config.debt;
28633
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28707
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28708
+ this.config.poolId
28709
+ );
28634
28710
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28635
28711
  return [
28636
28712
  // Approval step for collateral
@@ -28694,7 +28770,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28694
28770
  ];
28695
28771
  }
28696
28772
  _getWithdrawLeaf() {
28697
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28773
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28774
+ this.config.poolId
28775
+ );
28698
28776
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28699
28777
  const collateral = this.config.collateral;
28700
28778
  const debt = this.config.debt;
@@ -28725,7 +28803,7 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28725
28803
  this.config.debt.address.toBigInt(),
28726
28804
  this.config.vaultAllocator.toBigInt()
28727
28805
  ],
28728
- sanitizer: SIMPLE_SANITIZER_V2,
28806
+ sanitizer: isV2 ? SIMPLE_SANITIZER_V2 : SIMPLE_SANITIZER,
28729
28807
  // vmw = vesu multiply withdraw
28730
28808
  id: `vmw_${this.config.poolId.shortString()}_${collateral.symbol}_${debt.symbol}`
28731
28809
  },
@@ -28751,33 +28829,51 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28751
28829
  const leafConfigs = this._getDepositLeaf();
28752
28830
  const leaves = leafConfigs.map((config) => {
28753
28831
  const { target, method, packedArguments, sanitizer, id } = config;
28754
- const leaf = this.constructSimpleLeafData({
28755
- id,
28756
- target,
28757
- method,
28758
- packedArguments
28759
- }, sanitizer);
28832
+ const leaf = this.constructSimpleLeafData(
28833
+ {
28834
+ id,
28835
+ target,
28836
+ method,
28837
+ packedArguments
28838
+ },
28839
+ sanitizer
28840
+ );
28760
28841
  return leaf;
28761
28842
  });
28762
- return { leaves, callConstructor: this.getDepositCall.bind(this) };
28843
+ return {
28844
+ leaves,
28845
+ callConstructor: this.getDepositCall.bind(
28846
+ this
28847
+ )
28848
+ };
28763
28849
  }
28764
28850
  getWithdrawAdapter() {
28765
28851
  const leafConfigs = this._getWithdrawLeaf();
28766
28852
  const leaves = leafConfigs.map((config) => {
28767
28853
  const { target, method, packedArguments, sanitizer, id } = config;
28768
- const leaf = this.constructSimpleLeafData({
28769
- id,
28770
- target,
28771
- method,
28772
- packedArguments
28773
- }, sanitizer);
28854
+ const leaf = this.constructSimpleLeafData(
28855
+ {
28856
+ id,
28857
+ target,
28858
+ method,
28859
+ packedArguments
28860
+ },
28861
+ sanitizer
28862
+ );
28774
28863
  return leaf;
28775
28864
  });
28776
- return { leaves, callConstructor: this.getWithdrawCall.bind(this) };
28865
+ return {
28866
+ leaves,
28867
+ callConstructor: this.getWithdrawCall.bind(
28868
+ this
28869
+ )
28870
+ };
28777
28871
  }
28778
28872
  async getDepositCall(params) {
28779
28873
  const collateral = this.config.collateral;
28780
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28874
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28875
+ this.config.poolId
28876
+ );
28781
28877
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28782
28878
  const uint256MarginAmount = import_starknet21.uint256.bnToUint256(params.amount.toWei());
28783
28879
  return [
@@ -28849,7 +28945,9 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28849
28945
  ];
28850
28946
  }
28851
28947
  async getWithdrawCall(params) {
28852
- const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(this.config.poolId);
28948
+ const { addr: vesuSingleton, isV2 } = getVesuSingletonAddress(
28949
+ this.config.poolId
28950
+ );
28853
28951
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28854
28952
  return [
28855
28953
  // Switch delegation on
@@ -28874,7 +28972,7 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28874
28972
  },
28875
28973
  // Vesu multiply call
28876
28974
  {
28877
- sanitizer: SIMPLE_SANITIZER_V2,
28975
+ sanitizer: isV2 ? SIMPLE_SANITIZER_V2 : SIMPLE_SANITIZER,
28878
28976
  call: {
28879
28977
  contractAddress: vesuMultiply,
28880
28978
  selector: import_starknet21.hash.getSelectorFromName("modify_lever"),
@@ -28904,7 +29002,11 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28904
29002
  ];
28905
29003
  }
28906
29004
  async getMultiplyCallCalldata(params, isDeposit) {
28907
- logger.verbose(`${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(params)}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`);
29005
+ logger.verbose(
29006
+ `${_VesuMultiplyAdapter.name}::getMultiplyCallCalldata params: ${JSON.stringify(
29007
+ params
29008
+ )}, isDeposit: ${isDeposit}, collateral: ${this.config.collateral.symbol}, debt: ${this.config.debt.symbol}`
29009
+ );
28908
29010
  const { isV2 } = getVesuSingletonAddress(this.config.poolId);
28909
29011
  const vesuMultiply = isV2 ? this.vesuAdapter.VESU_MULTIPLY : this.vesuAdapter.VESU_MULTIPLY_V1;
28910
29012
  const multiplyContract = new import_starknet21.Contract({
@@ -28914,42 +29016,83 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28914
29016
  });
28915
29017
  let leverSwap = [];
28916
29018
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28917
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
28918
- const collateralisation = await this.vesuAdapter.getCollateralization(this.config.networkConfig);
29019
+ const existingPositions = await this.vesuAdapter.getPositions(
29020
+ this.config.networkConfig
29021
+ );
29022
+ const collateralisation = await this.vesuAdapter.getCollateralization(
29023
+ this.config.networkConfig
29024
+ );
28919
29025
  const existingCollateralInfo = existingPositions[0];
28920
29026
  const existingDebtInfo = existingPositions[1];
28921
29027
  const isDexPriceRequired = existingDebtInfo.token.symbol !== "USDC";
28922
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(existingCollateralInfo)},
28923
- existingDebtInfo: ${JSON.stringify(existingDebtInfo)}, collateralisation: ${JSON.stringify(collateralisation)}`);
29028
+ logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall existingCollateralInfo: ${JSON.stringify(
29029
+ existingCollateralInfo
29030
+ )},
29031
+ existingDebtInfo: ${JSON.stringify(
29032
+ existingDebtInfo
29033
+ )}, collateralisation: ${JSON.stringify(collateralisation)}`);
28924
29034
  const collateralPrice = collateralisation[0].usdValue > 0 ? collateralisation[0].usdValue / existingCollateralInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.collateral.symbol)).price;
28925
29035
  const debtPrice = collateralisation[1].usdValue > 0 ? collateralisation[1].usdValue / existingDebtInfo.amount.toNumber() : (await this.config.pricer.getPrice(this.config.debt.symbol)).price;
28926
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`);
28927
- const legLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
28928
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
28929
- const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(this.config.collateral, this.config.debt, this.config.quoteAmountToFetchPrice) : 1;
28930
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`);
29036
+ logger.debug(
29037
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall collateralPrice: ${collateralPrice}, debtPrice: ${debtPrice}`
29038
+ );
29039
+ const legLTV = await this.vesuAdapter.getLTVConfig(
29040
+ this.config.networkConfig
29041
+ );
29042
+ const ekuboQuoter = new EkuboQuoter(
29043
+ this.config.networkConfig,
29044
+ this.config.pricer
29045
+ );
29046
+ const dexPrice = isDexPriceRequired ? await ekuboQuoter.getDexPrice(
29047
+ this.config.collateral,
29048
+ this.config.debt,
29049
+ this.config.quoteAmountToFetchPrice
29050
+ ) : 1;
29051
+ logger.verbose(
29052
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall dexPrice: ${dexPrice}, ltv: ${legLTV}`
29053
+ );
28931
29054
  const addedCollateral = params.amount.multipliedBy(isDeposit ? 1 : -1);
28932
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`);
29055
+ logger.verbose(
29056
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall addedCollateral: ${addedCollateral}`
29057
+ );
28933
29058
  const numeratorPart1 = existingCollateralInfo.amount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(legLTV);
28934
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`);
29059
+ logger.verbose(
29060
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}`
29061
+ );
28935
29062
  const numeratorPart2 = existingDebtInfo.amount.multipliedBy(debtPrice).multipliedBy(this.config.targetHealthFactor);
28936
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`);
29063
+ logger.verbose(
29064
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart2: ${numeratorPart2}`
29065
+ );
28937
29066
  const denominatorPart = this.config.targetHealthFactor - legLTV / dexPrice;
28938
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`);
29067
+ logger.verbose(
29068
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall denominatorPart: ${denominatorPart}`
29069
+ );
28939
29070
  const x_debt_usd = numeratorPart1.minus(numeratorPart2).dividedBy(denominatorPart);
28940
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`);
28941
- logger.debug(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`);
28942
- let debtAmount = new Web3Number(x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals), this.config.debt.decimals);
29071
+ logger.verbose(
29072
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall x_debt_usd: ${x_debt_usd}`
29073
+ );
29074
+ logger.debug(
29075
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall numeratorPart1: ${numeratorPart1}, numeratorPart2: ${numeratorPart2}, denominatorPart: ${denominatorPart}`
29076
+ );
29077
+ let debtAmount = new Web3Number(
29078
+ x_debt_usd.dividedBy(debtPrice).toFixed(this.config.debt.decimals),
29079
+ this.config.debt.decimals
29080
+ );
28943
29081
  const marginAmount = addedCollateral;
28944
29082
  const collateralToken = this.config.collateral;
28945
29083
  const debtToken = this.config.debt;
28946
- const debtAmountInCollateralUnits = new Web3Number(debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0), collateralToken.decimals);
29084
+ const debtAmountInCollateralUnits = new Web3Number(
29085
+ debtAmount.multipliedBy(debtPrice).dividedBy(collateralPrice).multipliedBy(10 ** collateralToken.decimals).toFixed(0),
29086
+ collateralToken.decimals
29087
+ );
28947
29088
  const isIncrease = debtAmount.greaterThanOrEqualTo(0);
28948
29089
  if (isIncrease && debtAmount.lessThan(0)) {
28949
29090
  } else if (!isIncrease && debtAmount.greaterThan(0)) {
28950
29091
  debtAmount = Web3Number.fromWei(0, this.config.debt.decimals);
28951
29092
  }
28952
- logger.verbose(`${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`);
29093
+ logger.verbose(
29094
+ `${_VesuMultiplyAdapter.name}::getVesuMultiplyCall debtAmount: ${debtAmount}, marginAmount: ${marginAmount}`
29095
+ );
28953
29096
  if (!debtAmount.isZero()) {
28954
29097
  try {
28955
29098
  const swapQuote = await ekuboQuoter.getQuote(
@@ -28959,32 +29102,49 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28959
29102
  // negative for exact amount out
28960
29103
  );
28961
29104
  if (swapQuote.price_impact < 0.01) {
28962
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
29105
+ leverSwap = debtAmount.isNegative() ? ekuboQuoter.getVesuMultiplyQuote(
29106
+ swapQuote,
29107
+ collateralToken,
29108
+ debtToken
29109
+ ) : ekuboQuoter.getVesuMultiplyQuote(
29110
+ swapQuote,
29111
+ debtToken,
29112
+ collateralToken
29113
+ );
28963
29114
  const MAX_SLIPPAGE = 2e-3;
28964
29115
  if (debtAmount.greaterThan(0)) {
28965
- console.log("debtAmountInCollateralUnits", debtAmountInCollateralUnits.toNumber());
28966
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(debtToken, collateralToken, debtAmount, MAX_SLIPPAGE);
28967
- const anotherleverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
28968
- console.log("anotherleverSwapLimitAmount", anotherleverSwapLimitAmount, leverSwapLimitAmount);
29116
+ leverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
28969
29117
  } else if (debtAmount.lessThan(0)) {
28970
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(collateralToken, debtToken, debtAmountInCollateralUnits.multipliedBy(-1), MAX_SLIPPAGE);
28971
- const anotherleverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
28972
- console.log("anotherleverSwapLimitAmount", anotherleverSwapLimitAmount, leverSwapLimitAmount);
29118
+ leverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
28973
29119
  } else {
28974
- leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29120
+ leverSwapLimitAmount = Web3Number.fromWei(
29121
+ 0,
29122
+ this.config.debt.decimals
29123
+ );
28975
29124
  }
28976
29125
  await new Promise((resolve) => setTimeout(resolve, 1e4));
28977
- console.log("leverSwapLimitAmount", leverSwapLimitAmount);
28978
29126
  } else {
28979
- throw new Error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
29127
+ throw new Error(
29128
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
29129
+ );
28980
29130
  }
28981
29131
  } catch (error) {
28982
- throw new Error(`VesuMultiplyAdapter: Failed to get swap quote: ${error}`);
29132
+ throw new Error(
29133
+ `VesuMultiplyAdapter: Failed to get swap quote: ${error}`
29134
+ );
28983
29135
  }
28984
29136
  }
28985
- const multiplyParams = await this.getLeverParams(isIncrease, params, leverSwap, leverSwapLimitAmount);
29137
+ const multiplyParams = await this.getLeverParams(
29138
+ isIncrease,
29139
+ params,
29140
+ leverSwap,
29141
+ leverSwapLimitAmount
29142
+ );
28986
29143
  const call = multiplyContract.populate("modify_lever", {
28987
- modify_lever_params: this.formatMultiplyParams(isIncrease, multiplyParams)
29144
+ modify_lever_params: this.formatMultiplyParams(
29145
+ isIncrease,
29146
+ multiplyParams
29147
+ )
28988
29148
  });
28989
29149
  return call.calldata;
28990
29150
  }
@@ -28998,7 +29158,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
28998
29158
  add_margin: params.amount,
28999
29159
  // multiplied by collateral decimals in format
29000
29160
  margin_swap: [],
29001
- margin_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29161
+ margin_swap_limit_amount: Web3Number.fromWei(
29162
+ 0,
29163
+ this.config.collateral.decimals
29164
+ ),
29002
29165
  lever_swap: leverSwap,
29003
29166
  lever_swap_limit_amount: leverSwapLimitAmount
29004
29167
  } : {
@@ -29012,7 +29175,10 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29012
29175
  lever_swap_limit_amount: leverSwapLimitAmount,
29013
29176
  lever_swap_weights: [],
29014
29177
  withdraw_swap: [],
29015
- withdraw_swap_limit_amount: Web3Number.fromWei(0, this.config.collateral.decimals),
29178
+ withdraw_swap_limit_amount: Web3Number.fromWei(
29179
+ 0,
29180
+ this.config.collateral.decimals
29181
+ ),
29016
29182
  withdraw_swap_weights: [],
29017
29183
  close_position: false
29018
29184
  };
@@ -29028,12 +29194,16 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29028
29194
  });
29029
29195
  let leverSwap = [];
29030
29196
  let leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
29031
- const existingPositions = await this.vesuAdapter.getPositions(this.config.networkConfig);
29197
+ const existingPositions = await this.vesuAdapter.getPositions(
29198
+ this.config.networkConfig
29199
+ );
29032
29200
  const existingCollateralInfo = existingPositions[0];
29033
29201
  const existingDebtInfo = existingPositions[1];
29034
29202
  const collateralToken = this.config.collateral;
29035
29203
  const debtToken = this.config.debt;
29036
- const collateralPrice = await this.config.pricer.getPrice(collateralToken.symbol);
29204
+ const collateralPrice = await this.config.pricer.getPrice(
29205
+ collateralToken.symbol
29206
+ );
29037
29207
  const debtPrice = await this.config.pricer.getPrice(debtToken.symbol);
29038
29208
  const { deltadebtAmountUnits: debtAmountToRepay } = calculateDebtReductionAmountForWithdrawal(
29039
29209
  existingDebtInfo.amount,
@@ -29044,27 +29214,41 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29044
29214
  debtPrice.price,
29045
29215
  debtToken.decimals
29046
29216
  );
29047
- console.log("debtAmountToRepay", debtAmountToRepay);
29048
29217
  if (!debtAmountToRepay) {
29049
29218
  throw new Error("error calculating debt amount to repay");
29050
29219
  }
29051
- const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
29052
- const debtInDebtUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
29053
- const debtInCollateralUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(collateralPrice.price).multipliedBy(10 ** collateralToken.decimals);
29220
+ const ekuboQuoter = new EkuboQuoter(
29221
+ this.config.networkConfig,
29222
+ this.config.pricer
29223
+ );
29224
+ const debtInDebtUnits = new Web3Number(
29225
+ debtAmountToRepay,
29226
+ debtToken.decimals
29227
+ ).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
29054
29228
  const swapQuote = await ekuboQuoter.getQuote(
29055
29229
  debtToken.address.address,
29056
29230
  collateralToken.address.address,
29057
29231
  debtInDebtUnits
29058
29232
  );
29059
29233
  const MAX_SLIPPAGE = 2e-3;
29060
- if (swapQuote.price_impact < 0.025) {
29061
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
29234
+ if (swapQuote.price_impact < 25e-4) {
29235
+ leverSwap = ekuboQuoter.getVesuMultiplyQuote(
29236
+ swapQuote,
29237
+ collateralToken,
29238
+ debtToken
29239
+ );
29062
29240
  } else {
29063
- logger.error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
29241
+ logger.error(
29242
+ `VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`
29243
+ );
29064
29244
  }
29065
- const anotherLeverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(collateralToken, debtToken, debtInDebtUnits, MAX_SLIPPAGE);
29066
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(debtToken, collateralToken, debtInCollateralUnits, MAX_SLIPPAGE);
29067
- const multiplyParams = await this.getLeverParams(false, params, leverSwap, leverSwapLimitAmount);
29245
+ leverSwapLimitAmount = new Web3Number(debtAmountToRepay, debtToken.decimals).abs().multipliedBy(1 + MAX_SLIPPAGE);
29246
+ const multiplyParams = await this.getLeverParams(
29247
+ false,
29248
+ params,
29249
+ leverSwap,
29250
+ leverSwapLimitAmount
29251
+ );
29068
29252
  const call = multiplyContract.populate("modify_lever", {
29069
29253
  modify_lever_params: this.formatMultiplyParams(false, multiplyParams)
29070
29254
  });
@@ -29074,100 +29258,132 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29074
29258
  if (isIncrease) {
29075
29259
  const _params2 = params;
29076
29260
  return {
29077
- action: new import_starknet21.CairoCustomEnum({ IncreaseLever: {
29078
- pool_id: _params2.pool_id.toBigInt(),
29079
- collateral_asset: _params2.collateral_asset.toBigInt(),
29080
- debt_asset: _params2.debt_asset.toBigInt(),
29081
- user: _params2.user.toBigInt(),
29082
- add_margin: BigInt(_params2.add_margin.toWei()),
29083
- margin_swap: _params2.margin_swap.map((swap) => ({
29261
+ action: new import_starknet21.CairoCustomEnum({
29262
+ IncreaseLever: {
29263
+ pool_id: _params2.pool_id.toBigInt(),
29264
+ collateral_asset: _params2.collateral_asset.toBigInt(),
29265
+ debt_asset: _params2.debt_asset.toBigInt(),
29266
+ user: _params2.user.toBigInt(),
29267
+ add_margin: BigInt(_params2.add_margin.toWei()),
29268
+ margin_swap: _params2.margin_swap.map((swap) => ({
29269
+ route: swap.route.map((route) => ({
29270
+ pool_key: {
29271
+ token0: route.pool_key.token0.toBigInt(),
29272
+ token1: route.pool_key.token1.toBigInt(),
29273
+ fee: route.pool_key.fee,
29274
+ tick_spacing: route.pool_key.tick_spacing,
29275
+ extension: BigInt(
29276
+ import_starknet21.num.hexToDecimalString(route.pool_key.extension)
29277
+ )
29278
+ },
29279
+ sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(
29280
+ route.sqrt_ratio_limit.toWei()
29281
+ ),
29282
+ skip_ahead: BigInt(100)
29283
+ })),
29284
+ token_amount: {
29285
+ token: swap.token_amount.token.toBigInt(),
29286
+ amount: swap.token_amount.amount.toI129()
29287
+ }
29288
+ })),
29289
+ margin_swap_limit_amount: BigInt(
29290
+ _params2.margin_swap_limit_amount.toWei()
29291
+ ),
29292
+ lever_swap: _params2.lever_swap.map((swap) => ({
29293
+ route: swap.route.map((route) => ({
29294
+ pool_key: {
29295
+ token0: route.pool_key.token0.toBigInt(),
29296
+ token1: route.pool_key.token1.toBigInt(),
29297
+ fee: route.pool_key.fee,
29298
+ tick_spacing: route.pool_key.tick_spacing,
29299
+ extension: BigInt(
29300
+ import_starknet21.num.hexToDecimalString(route.pool_key.extension)
29301
+ )
29302
+ },
29303
+ sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(
29304
+ route.sqrt_ratio_limit.toWei()
29305
+ ),
29306
+ skip_ahead: BigInt(0)
29307
+ })),
29308
+ token_amount: {
29309
+ token: swap.token_amount.token.toBigInt(),
29310
+ amount: swap.token_amount.amount.toI129()
29311
+ }
29312
+ })),
29313
+ lever_swap_limit_amount: BigInt(
29314
+ _params2.lever_swap_limit_amount.toWei()
29315
+ )
29316
+ }
29317
+ })
29318
+ };
29319
+ }
29320
+ const _params = params;
29321
+ return {
29322
+ action: new import_starknet21.CairoCustomEnum({
29323
+ DecreaseLever: {
29324
+ pool_id: _params.pool_id.toBigInt(),
29325
+ collateral_asset: _params.collateral_asset.toBigInt(),
29326
+ debt_asset: _params.debt_asset.toBigInt(),
29327
+ user: _params.user.toBigInt(),
29328
+ sub_margin: BigInt(_params.sub_margin.toWei()),
29329
+ recipient: _params.recipient.toBigInt(),
29330
+ lever_swap: _params.lever_swap.map((swap) => ({
29084
29331
  route: swap.route.map((route) => ({
29085
29332
  pool_key: {
29086
29333
  token0: route.pool_key.token0.toBigInt(),
29087
29334
  token1: route.pool_key.token1.toBigInt(),
29088
29335
  fee: route.pool_key.fee,
29089
29336
  tick_spacing: route.pool_key.tick_spacing,
29090
- extension: BigInt(import_starknet21.num.hexToDecimalString(route.pool_key.extension))
29337
+ extension: ContractAddr.from(
29338
+ route.pool_key.extension
29339
+ ).toBigInt()
29091
29340
  },
29092
- sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(route.sqrt_ratio_limit.toWei()),
29093
- skip_ahead: BigInt(100)
29341
+ sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(
29342
+ route.sqrt_ratio_limit.toWei()
29343
+ ),
29344
+ skip_ahead: BigInt(route.skip_ahead.toWei())
29094
29345
  })),
29095
29346
  token_amount: {
29096
29347
  token: swap.token_amount.token.toBigInt(),
29097
29348
  amount: swap.token_amount.amount.toI129()
29098
29349
  }
29099
29350
  })),
29100
- margin_swap_limit_amount: BigInt(_params2.margin_swap_limit_amount.toWei()),
29101
- lever_swap: _params2.lever_swap.map((swap) => ({
29351
+ lever_swap_limit_amount: BigInt(
29352
+ _params.lever_swap_limit_amount.toWei()
29353
+ ),
29354
+ lever_swap_weights: _params.lever_swap_weights.map(
29355
+ (weight) => BigInt(weight.toWei())
29356
+ ),
29357
+ withdraw_swap: _params.withdraw_swap.map((swap) => ({
29102
29358
  route: swap.route.map((route) => ({
29103
29359
  pool_key: {
29104
29360
  token0: route.pool_key.token0.toBigInt(),
29105
29361
  token1: route.pool_key.token1.toBigInt(),
29106
29362
  fee: route.pool_key.fee,
29107
29363
  tick_spacing: route.pool_key.tick_spacing,
29108
- extension: BigInt(import_starknet21.num.hexToDecimalString(route.pool_key.extension))
29364
+ extension: ContractAddr.from(
29365
+ route.pool_key.extension
29366
+ ).toBigInt()
29109
29367
  },
29110
- sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(route.sqrt_ratio_limit.toWei()),
29111
- skip_ahead: BigInt(0)
29368
+ sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(
29369
+ route.sqrt_ratio_limit.toWei()
29370
+ ),
29371
+ skip_ahead: BigInt(route.skip_ahead.toWei())
29112
29372
  })),
29113
29373
  token_amount: {
29114
29374
  token: swap.token_amount.token.toBigInt(),
29115
29375
  amount: swap.token_amount.amount.toI129()
29116
29376
  }
29117
29377
  })),
29118
- lever_swap_limit_amount: BigInt(_params2.lever_swap_limit_amount.toWei())
29119
- } })
29120
- };
29121
- }
29122
- const _params = params;
29123
- return {
29124
- action: new import_starknet21.CairoCustomEnum({ DecreaseLever: {
29125
- pool_id: _params.pool_id.toBigInt(),
29126
- collateral_asset: _params.collateral_asset.toBigInt(),
29127
- debt_asset: _params.debt_asset.toBigInt(),
29128
- user: _params.user.toBigInt(),
29129
- sub_margin: BigInt(_params.sub_margin.toWei()),
29130
- recipient: _params.recipient.toBigInt(),
29131
- lever_swap: _params.lever_swap.map((swap) => ({
29132
- route: swap.route.map((route) => ({
29133
- pool_key: {
29134
- token0: route.pool_key.token0.toBigInt(),
29135
- token1: route.pool_key.token1.toBigInt(),
29136
- fee: route.pool_key.fee,
29137
- tick_spacing: route.pool_key.tick_spacing,
29138
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
29139
- },
29140
- sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(route.sqrt_ratio_limit.toWei()),
29141
- skip_ahead: BigInt(route.skip_ahead.toWei())
29142
- })),
29143
- token_amount: {
29144
- token: swap.token_amount.token.toBigInt(),
29145
- amount: swap.token_amount.amount.toI129()
29146
- }
29147
- })),
29148
- lever_swap_limit_amount: BigInt(_params.lever_swap_limit_amount.toWei()),
29149
- lever_swap_weights: _params.lever_swap_weights.map((weight) => BigInt(weight.toWei())),
29150
- withdraw_swap: _params.withdraw_swap.map((swap) => ({
29151
- route: swap.route.map((route) => ({
29152
- pool_key: {
29153
- token0: route.pool_key.token0.toBigInt(),
29154
- token1: route.pool_key.token1.toBigInt(),
29155
- fee: route.pool_key.fee,
29156
- tick_spacing: route.pool_key.tick_spacing,
29157
- extension: ContractAddr.from(route.pool_key.extension).toBigInt()
29158
- },
29159
- sqrt_ratio_limit: import_starknet21.uint256.bnToUint256(route.sqrt_ratio_limit.toWei()),
29160
- skip_ahead: BigInt(route.skip_ahead.toWei())
29161
- })),
29162
- token_amount: {
29163
- token: swap.token_amount.token.toBigInt(),
29164
- amount: swap.token_amount.amount.toI129()
29165
- }
29166
- })),
29167
- withdraw_swap_limit_amount: BigInt(_params.withdraw_swap_limit_amount.toWei()),
29168
- withdraw_swap_weights: _params.withdraw_swap_weights.map((weight) => BigInt(weight.toWei())),
29169
- close_position: _params.close_position
29170
- } })
29378
+ withdraw_swap_limit_amount: BigInt(
29379
+ _params.withdraw_swap_limit_amount.toWei()
29380
+ ),
29381
+ withdraw_swap_weights: _params.withdraw_swap_weights.map(
29382
+ (weight) => BigInt(weight.toWei())
29383
+ ),
29384
+ close_position: _params.close_position
29385
+ }
29386
+ })
29171
29387
  };
29172
29388
  }
29173
29389
  async getHealthFactor() {
@@ -29176,11 +29392,15 @@ var VesuMultiplyAdapter = class _VesuMultiplyAdapter extends BaseAdapter {
29176
29392
  }
29177
29393
  async getNetAPY() {
29178
29394
  const positions = await this.getPositions();
29179
- logger.verbose(`${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`);
29395
+ logger.verbose(
29396
+ `${this.name}::getNetAPY: positions: ${JSON.stringify(positions)}`
29397
+ );
29180
29398
  const allZero = positions.every((p) => p.usdValue === 0);
29181
29399
  if (allZero) {
29182
29400
  const collateralUSD = 1e3;
29183
- const maxLTV = await this.vesuAdapter.getLTVConfig(this.config.networkConfig);
29401
+ const maxLTV = await this.vesuAdapter.getLTVConfig(
29402
+ this.config.networkConfig
29403
+ );
29184
29404
  const targetHF = this.config.targetHealthFactor;
29185
29405
  const maxDebt = HealthFactorMath.getMaxDebtAmountOnLooping(
29186
29406
  new Web3Number(collateralUSD, this.config.collateral.decimals),
@@ -29323,7 +29543,22 @@ var ExtendedWrapper = class {
29323
29543
  `HTTP ${response.status}: ${errorData.detail || response.statusText}`
29324
29544
  );
29325
29545
  }
29326
- const data = await response.json();
29546
+ const text = await response.text();
29547
+ const MAX_SAFE_INTEGER_STR = "9007199254740991";
29548
+ const largeIntegerRegex = /"data"\s*:\s*(\d{16,})/g;
29549
+ const modifiedText = text.replace(largeIntegerRegex, (match, largeInt) => {
29550
+ if (largeInt.length > MAX_SAFE_INTEGER_STR.length || largeInt.length === MAX_SAFE_INTEGER_STR.length && largeInt > MAX_SAFE_INTEGER_STR) {
29551
+ return `"data":"${largeInt}"`;
29552
+ }
29553
+ return match;
29554
+ });
29555
+ const data = JSON.parse(modifiedText);
29556
+ if (data && typeof data.data === "string" && /^\d+$/.test(data.data)) {
29557
+ const numValue = Number(data.data);
29558
+ if (Number.isSafeInteger(numValue)) {
29559
+ data.data = numValue;
29560
+ }
29561
+ }
29327
29562
  return data;
29328
29563
  } catch (error) {
29329
29564
  lastError = error;
@@ -29383,6 +29618,7 @@ var ExtendedWrapper = class {
29383
29618
  }
29384
29619
  /**
29385
29620
  * Initiate a withdrawal from Extended Exchange
29621
+ * Returns data as number | string to preserve precision for large integers
29386
29622
  */
29387
29623
  async withdraw(request) {
29388
29624
  return this.makeRequest("/api/v1/withdraw", {
@@ -29521,6 +29757,7 @@ var ExtendedWrapper = class {
29521
29757
  }
29522
29758
  /**
29523
29759
  * Withdraw USDC (convenience method)
29760
+ * Returns data as number | string to preserve precision for large integers
29524
29761
  */
29525
29762
  async withdrawUSDC(amount) {
29526
29763
  return this.withdraw({ amount, asset: "USDC" });
@@ -29552,12 +29789,17 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29552
29789
  timeout: this.config.extendedTimeout,
29553
29790
  retries: this.config.extendedRetries
29554
29791
  });
29792
+ this.minimumExtendedMovementAmount = this.config.minimumExtendedMovementAmount ?? 5;
29555
29793
  this.client = client;
29794
+ this.retryDelayForOrderStatus = this.config.retryDelayForOrderStatus ?? 3e3;
29556
29795
  }
29557
29796
  //abstract means the method has no implementation in this class; instead, child classes must implement it.
29558
29797
  async getAPY(supportedPosition) {
29559
29798
  const side = supportedPosition.isDebt ? "LONG" : "SHORT";
29560
- const fundingRates = await this.client.getFundingRates(this.config.extendedMarketName, side);
29799
+ const fundingRates = await this.client.getFundingRates(
29800
+ this.config.extendedMarketName,
29801
+ side
29802
+ );
29561
29803
  if (fundingRates.status !== "OK") {
29562
29804
  logger.error("error getting funding rates", fundingRates);
29563
29805
  return { apy: 0, type: "base" /* BASE */ };
@@ -29601,14 +29843,14 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29601
29843
  });
29602
29844
  }
29603
29845
  _getDepositLeaf() {
29604
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29846
+ const usdceToken = Global.getDefaultTokens().find(
29847
+ (token) => token.symbol === "USDCe"
29848
+ );
29605
29849
  return [
29606
29850
  {
29607
29851
  target: this.config.supportedPositions[0].asset.address,
29608
29852
  method: "approve",
29609
- packedArguments: [
29610
- AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
29611
- ],
29853
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29612
29854
  id: `extended_approve_${this.config.supportedPositions[0].asset.symbol}`,
29613
29855
  sanitizer: AVNU_LEGACY_SANITIZER
29614
29856
  },
@@ -29635,17 +29877,62 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29635
29877
  }
29636
29878
  ];
29637
29879
  }
29880
+ getSwapFromLegacyLeaf() {
29881
+ const leafConfigs = this._getSwapFromLegacyLeaf();
29882
+ const leaves = leafConfigs.map((config) => {
29883
+ const { target, method, packedArguments, sanitizer, id } = config;
29884
+ const leaf = this.constructSimpleLeafData(
29885
+ {
29886
+ id,
29887
+ target,
29888
+ method,
29889
+ packedArguments
29890
+ },
29891
+ sanitizer
29892
+ );
29893
+ return leaf;
29894
+ });
29895
+ return {
29896
+ leaves,
29897
+ callConstructor: this.getSwapFromLegacyCall.bind(
29898
+ this
29899
+ )
29900
+ };
29901
+ }
29902
+ _getSwapFromLegacyLeaf() {
29903
+ const usdceToken = Global.getDefaultTokens().find(
29904
+ (token) => token.symbol === "USDCe"
29905
+ );
29906
+ return [
29907
+ {
29908
+ target: usdceToken.address,
29909
+ method: "approve",
29910
+ packedArguments: [AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()],
29911
+ id: `extendedswaplegacyapprove_${usdceToken.symbol}`,
29912
+ sanitizer: AVNU_LEGACY_SANITIZER
29913
+ },
29914
+ {
29915
+ target: AVNU_EXCHANGE_FOR_LEGACY_USDC,
29916
+ method: "swap_to_new",
29917
+ packedArguments: [],
29918
+ id: `extended_swap_to_new_${usdceToken.symbol}`,
29919
+ sanitizer: AVNU_LEGACY_SANITIZER
29920
+ }
29921
+ ];
29922
+ }
29638
29923
  _getWithdrawLeaf() {
29639
29924
  return [];
29640
29925
  }
29641
29926
  async getDepositCall(params) {
29642
29927
  try {
29643
29928
  const usdcToken = this.config.supportedPositions[0].asset;
29644
- const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
29645
- const salt = Math.floor(
29646
- Math.random() * 10 ** usdcToken.decimals
29929
+ const usdceToken = Global.getDefaultTokens().find(
29930
+ (token) => token.symbol === "USDCe"
29931
+ );
29932
+ const salt = Math.floor(Math.random() * 10 ** usdcToken.decimals);
29933
+ const amount = import_starknet22.uint256.bnToUint256(
29934
+ params.amount.multipliedBy(10).toWei()
29647
29935
  );
29648
- const amount = import_starknet22.uint256.bnToUint256(params.amount.multipliedBy(10).toWei());
29649
29936
  const quotes = await this.config.avnuAdapter.getQuotesAvnu(
29650
29937
  usdcToken.address.toString(),
29651
29938
  usdceToken.address.toString(),
@@ -29658,7 +29945,9 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29658
29945
  logger.error("error getting quotes from avnu");
29659
29946
  return [];
29660
29947
  }
29661
- const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
29948
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
29949
+ quotes
29950
+ );
29662
29951
  const swapCallData = getCalldata[0];
29663
29952
  return [
29664
29953
  {
@@ -29715,6 +30004,76 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29715
30004
  return [];
29716
30005
  }
29717
30006
  }
30007
+ getProofsForFromLegacySwap(tree) {
30008
+ let proofGroups = [];
30009
+ const ids = this.getSwapFromLegacyLeaf().leaves.map((l) => l.readableId);
30010
+ for (const [i, v] of tree.entries()) {
30011
+ if (ids.includes(v.readableId)) {
30012
+ proofGroups.push(tree.getProof(i));
30013
+ }
30014
+ }
30015
+ if (proofGroups.length != ids.length) {
30016
+ throw new Error(`Not all proofs found for IDs: ${ids.join(", ")}`);
30017
+ }
30018
+ return {
30019
+ proofs: proofGroups,
30020
+ callConstructor: this.getSwapFromLegacyCall.bind(this)
30021
+ };
30022
+ }
30023
+ async getSwapFromLegacyCall(params) {
30024
+ try {
30025
+ const usdcToken = this.config.supportedPositions[0].asset;
30026
+ const usdceToken = Global.getDefaultTokens().find(
30027
+ (token) => token.symbol === "USDCe"
30028
+ );
30029
+ const amount = import_starknet22.uint256.bnToUint256(
30030
+ params.amount.multipliedBy(10).toWei()
30031
+ );
30032
+ const quotes = await this.config.avnuAdapter.getQuotesAvnu(
30033
+ usdceToken.address.toString(),
30034
+ usdcToken.address.toString(),
30035
+ params.amount.toNumber(),
30036
+ this.config.avnuAdapter.config.vaultAllocator.address.toString(),
30037
+ usdcToken.decimals,
30038
+ false
30039
+ );
30040
+ if (!quotes) {
30041
+ logger.error("error getting quotes from avnu");
30042
+ return [];
30043
+ }
30044
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(
30045
+ quotes
30046
+ );
30047
+ const swapCallData = getCalldata[0];
30048
+ return [
30049
+ {
30050
+ sanitizer: AVNU_LEGACY_SANITIZER,
30051
+ call: {
30052
+ contractAddress: usdceToken.address,
30053
+ selector: import_starknet22.hash.getSelectorFromName("approve"),
30054
+ calldata: [
30055
+ AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt(),
30056
+ toBigInt(amount.low.toString()),
30057
+ // amount low
30058
+ toBigInt(amount.high.toString())
30059
+ // amount high
30060
+ ]
30061
+ }
30062
+ },
30063
+ {
30064
+ sanitizer: AVNU_LEGACY_SANITIZER,
30065
+ call: {
30066
+ contractAddress: AVNU_EXCHANGE_FOR_LEGACY_USDC,
30067
+ selector: import_starknet22.hash.getSelectorFromName("swap_to_new"),
30068
+ calldata: swapCallData
30069
+ }
30070
+ }
30071
+ ];
30072
+ } catch (error) {
30073
+ logger.error(`Error creating Deposit Call: ${error}`);
30074
+ return [];
30075
+ }
30076
+ }
29718
30077
  //Swap wbtc to usdc
29719
30078
  async getWithdrawCall(params) {
29720
30079
  try {
@@ -29730,13 +30089,60 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29730
30089
  async withdrawFromExtended(amount) {
29731
30090
  try {
29732
30091
  if (!this.client) {
29733
- throw new Error("Client not initialized");
30092
+ logger.error("Client not initialized");
30093
+ return false;
29734
30094
  }
29735
- const withdrawalRequest = this.client.withdrawUSDC(amount.toString());
29736
- if ((await withdrawalRequest).status === "OK") {
29737
- console.log("Withdrawal request successful");
29738
- return true;
30095
+ if (amount.lessThanOrEqualTo(0)) {
30096
+ logger.error(
30097
+ `Invalid withdrawal amount: ${amount.toNumber()}. Amount must be positive.`
30098
+ );
30099
+ return false;
30100
+ }
30101
+ if (amount.lessThanOrEqualTo(this.minimumExtendedMovementAmount)) {
30102
+ logger.warn(
30103
+ `Withdrawal amount ${amount.toNumber()} is below minimum Extended movement amount ${this.minimumExtendedMovementAmount}. Skipping withdrawal.`
30104
+ );
30105
+ return false;
30106
+ }
30107
+ const holdings = await this.getExtendedDepositAmount();
30108
+ if (!holdings) {
30109
+ logger.error(
30110
+ "Cannot get holdings - unable to validate withdrawal amount"
30111
+ );
30112
+ return false;
30113
+ }
30114
+ const availableForWithdrawal = parseFloat(
30115
+ holdings.availableForWithdrawal
30116
+ );
30117
+ if (!Number.isFinite(availableForWithdrawal) || availableForWithdrawal < 0) {
30118
+ logger.error(
30119
+ `Invalid availableForWithdrawal: ${holdings.availableForWithdrawal}. Expected a finite, non-negative number.`
30120
+ );
30121
+ return false;
30122
+ }
30123
+ const withdrawalAmount = amount.toNumber();
30124
+ if (withdrawalAmount > availableForWithdrawal) {
30125
+ logger.error(
30126
+ `Withdrawal amount ${withdrawalAmount} exceeds available balance ${availableForWithdrawal}`
30127
+ );
30128
+ return false;
30129
+ }
30130
+ logger.info(
30131
+ `Withdrawing ${withdrawalAmount} from Extended. Available balance: ${availableForWithdrawal}`
30132
+ );
30133
+ const withdrawalRequest = await this.client.withdrawUSDC(
30134
+ amount.toFixed(2)
30135
+ );
30136
+ if (withdrawalRequest.status === "OK") {
30137
+ const withdrawalStatus = await this.getDepositOrWithdrawalStatus(
30138
+ withdrawalRequest.data,
30139
+ "WITHDRAWAL" /* WITHDRAWAL */
30140
+ );
30141
+ return withdrawalStatus;
29739
30142
  }
30143
+ logger.error(
30144
+ `Withdrawal request failed with status: ${withdrawalRequest.status}`
30145
+ );
29740
30146
  return false;
29741
30147
  } catch (error) {
29742
30148
  logger.error(`Error creating Withdraw Call: ${error}`);
@@ -29747,21 +30153,44 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29747
30153
  return Promise.resolve(1);
29748
30154
  }
29749
30155
  async getExtendedDepositAmount() {
29750
- if (this.client === null) {
29751
- logger.error("error initializing client");
29752
- return void 0;
29753
- }
29754
- const result = await this.client.getHoldings();
29755
- if (!result) {
29756
- logger.error(`error getting holdings: ${result}`);
29757
- return void 0;
29758
- }
29759
- const holdings = result.data;
29760
- if (!holdings) {
29761
- logger.error(`error getting holdings: ${holdings}`);
30156
+ try {
30157
+ if (this.client === null) {
30158
+ logger.error("error initializing client - client is null");
30159
+ return void 0;
30160
+ }
30161
+ const result = await this.client.getHoldings();
30162
+ if (!result) {
30163
+ logger.error("error getting holdings - API returned null/undefined");
30164
+ return void 0;
30165
+ }
30166
+ if (result.status && result.status !== "OK") {
30167
+ logger.error(
30168
+ `error getting holdings - API returned status: ${result.status}`
30169
+ );
30170
+ return void 0;
30171
+ }
30172
+ const holdings = result.data;
30173
+ if (!holdings) {
30174
+ logger.warn(
30175
+ "holdings data is null/undefined - treating as zero balance"
30176
+ );
30177
+ return {
30178
+ collateral_name: "",
30179
+ balance: "0",
30180
+ equity: "0",
30181
+ availableForTrade: "0",
30182
+ availableForWithdrawal: "0",
30183
+ unrealisedPnl: "0",
30184
+ initialMargin: "0",
30185
+ marginRatio: "0",
30186
+ updatedTime: Date.now()
30187
+ };
30188
+ }
30189
+ return holdings;
30190
+ } catch (error) {
30191
+ logger.error(`error getting holdings - exception: ${error}`);
29762
30192
  return void 0;
29763
30193
  }
29764
- return holdings;
29765
30194
  }
29766
30195
  async setLeverage(leverage, marketName) {
29767
30196
  if (this.client === null) {
@@ -29803,21 +30232,24 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29803
30232
  return result.data;
29804
30233
  }
29805
30234
  async getOrderStatus(orderId, marketName) {
29806
- if (this.client === null) {
29807
- logger.error("error initializing client");
29808
- return null;
29809
- }
29810
- const orderhistory = await this.getOrderHistory(marketName);
29811
- if (!orderhistory || orderhistory.length === 0) {
29812
- logger.error(`error getting order: ${orderId}`);
30235
+ try {
30236
+ if (this.client === null) {
30237
+ logger.error("error initializing client");
30238
+ return null;
30239
+ }
30240
+ const orderhistory = await this.getOrderHistory(marketName);
30241
+ if (!orderhistory || orderhistory.length === 0) {
30242
+ return null;
30243
+ }
30244
+ const order = orderhistory.slice(0, 20).find((order2) => order2.id.toString() === orderId);
30245
+ if (order) {
30246
+ return order;
30247
+ }
29813
30248
  return null;
29814
- }
29815
- const order = orderhistory.slice(0, 3).find((order2) => order2.id.toString() === orderId);
29816
- if (!order) {
29817
- logger.error(`error getting order: ${order}`);
30249
+ } catch (error) {
30250
+ logger.error(`error getting order status: ${error}`);
29818
30251
  return null;
29819
30252
  }
29820
- return order;
29821
30253
  }
29822
30254
  async fetchOrderBookBTCUSDC() {
29823
30255
  try {
@@ -29868,14 +30300,40 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29868
30300
  logger.error("error depositing or setting leverage");
29869
30301
  return null;
29870
30302
  }
29871
- const positions = await this.getAllOpenPositions();
29872
- if (positions === null) {
30303
+ const { ask, bid } = await this.fetchOrderBookBTCUSDC();
30304
+ if (!ask || !bid || ask.lessThanOrEqualTo(0) || bid.lessThanOrEqualTo(0)) {
30305
+ logger.error(
30306
+ `Invalid orderbook prices: ask=${ask?.toNumber()}, bid=${bid?.toNumber()}`
30307
+ );
29873
30308
  return null;
29874
30309
  }
29875
- const { ask, bid } = await this.fetchOrderBookBTCUSDC();
29876
30310
  const spread = ask.minus(bid);
29877
- let price = ask.plus(bid).div(2);
29878
- side === "SELL" /* SELL */ ? price = price.minus(spread.times(0.2 * attempt)) : price = price.plus(spread.times(0.2 * attempt));
30311
+ const midPrice = ask.plus(bid).div(2);
30312
+ const MAX_PRICE_DEVIATION_MULTIPLIER = 0.5;
30313
+ const priceAdjustmentMultiplier = Math.min(
30314
+ 0.2 * attempt,
30315
+ MAX_PRICE_DEVIATION_MULTIPLIER
30316
+ );
30317
+ const priceAdjustment = spread.times(priceAdjustmentMultiplier);
30318
+ let price = midPrice;
30319
+ if (side === "SELL" /* SELL */) {
30320
+ price = midPrice.minus(priceAdjustment);
30321
+ } else {
30322
+ price = midPrice.plus(priceAdjustment);
30323
+ }
30324
+ const maxDeviation = midPrice.times(0.5);
30325
+ if (price.minus(midPrice).abs().greaterThan(maxDeviation)) {
30326
+ logger.error(
30327
+ `Price deviation too large on attempt ${attempt}: price=${price.toNumber()}, midPrice=${midPrice.toNumber()}, deviation=${price.minus(midPrice).abs().toNumber()}`
30328
+ );
30329
+ if (attempt >= maxAttempts) {
30330
+ return null;
30331
+ }
30332
+ price = side === "SELL" /* SELL */ ? midPrice.minus(maxDeviation) : midPrice.plus(maxDeviation);
30333
+ }
30334
+ logger.info(
30335
+ `createOrder attempt ${attempt}/${maxAttempts}: side=${side}, midPrice=${midPrice.toNumber()}, adjustedPrice=${price.toNumber()}, adjustment=${priceAdjustmentMultiplier * 100}%`
30336
+ );
29879
30337
  const amount_in_token = (btcAmount * parseInt(leverage)).toFixed(
29880
30338
  this.config.extendedPrecision
29881
30339
  );
@@ -29886,14 +30344,57 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29886
30344
  price.toFixed(0),
29887
30345
  side
29888
30346
  );
29889
- if (!result) {
30347
+ if (!result || !result.position_id) {
30348
+ logger.error("Failed to create order - no position_id returned");
29890
30349
  return null;
29891
30350
  }
29892
- await new Promise((resolve) => setTimeout(resolve, 5e3));
29893
- const openOrder = await this.getOrderStatus(result.position_id, this.config.extendedMarketName);
29894
- if (!openOrder || openOrder.status !== "FILLED" /* FILLED */) {
30351
+ const positionId = result.position_id;
30352
+ logger.info(
30353
+ `Order created with position_id: ${positionId}. Waiting for API to update...`
30354
+ );
30355
+ let openOrder = await this.getOrderStatus(
30356
+ positionId,
30357
+ this.config.extendedMarketName
30358
+ );
30359
+ const maxStatusRetries = 3;
30360
+ const statusRetryDelay = 5e3;
30361
+ if (!openOrder) {
30362
+ logger.warn(
30363
+ `Order ${positionId} not found in API yet. Retrying status fetch (max ${maxStatusRetries} times)...`
30364
+ );
30365
+ for (let statusRetry = 1; statusRetry <= maxStatusRetries; statusRetry++) {
30366
+ await new Promise((resolve) => setTimeout(resolve, statusRetryDelay));
30367
+ openOrder = await this.getOrderStatus(
30368
+ positionId,
30369
+ this.config.extendedMarketName
30370
+ );
30371
+ if (openOrder) {
30372
+ logger.info(
30373
+ `Order ${positionId} found after ${statusRetry} status retry(ies)`
30374
+ );
30375
+ break;
30376
+ }
30377
+ logger.warn(
30378
+ `Order ${positionId} still not found after ${statusRetry}/${maxStatusRetries} status retries`
30379
+ );
30380
+ }
30381
+ }
30382
+ if (openOrder && openOrder.status === "FILLED" /* FILLED */) {
30383
+ logger.info(
30384
+ `Order ${positionId} successfully filled with quantity ${openOrder.qty}`
30385
+ );
30386
+ return {
30387
+ position_id: positionId,
30388
+ btc_exposure: openOrder.qty
30389
+ };
30390
+ } else if (openOrder && openOrder.status !== "FILLED" /* FILLED */) {
30391
+ logger.warn(
30392
+ `Order ${positionId} found but status is ${openOrder.status}, not FILLED. Retrying order creation...`
30393
+ );
29895
30394
  if (attempt >= maxAttempts) {
29896
- logger.error("Max retries reached \u2014 could not verify open position");
30395
+ logger.error(
30396
+ `Max retries reached \u2014 order ${positionId} status is ${openOrder.status}, not FILLED`
30397
+ );
29897
30398
  return null;
29898
30399
  } else {
29899
30400
  const backoff = 2e3 * attempt;
@@ -29907,16 +30408,21 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29907
30408
  );
29908
30409
  }
29909
30410
  } else {
30411
+ logger.warn(
30412
+ `Order ${positionId} not found in API after ${maxStatusRetries} status retries (API update delayed ~30s). We got position_id from creation, so order exists. Returning position_id - status will be checked in next loop iteration.`
30413
+ );
29910
30414
  return {
29911
- position_id: result.position_id,
29912
- btc_exposure: openOrder.qty
30415
+ position_id: positionId,
30416
+ btc_exposure: amount_in_token
29913
30417
  };
29914
30418
  }
29915
30419
  } catch (err) {
29916
- logger.error(`createShortOrder failed on attempt ${attempt}: ${err.message}`);
30420
+ logger.error(
30421
+ `createShortOrder failed on attempt ${attempt}: ${err.message}`
30422
+ );
29917
30423
  if (attempt < maxAttempts) {
29918
30424
  const backoff = 1200 * attempt;
29919
- console.log(`Retrying after ${backoff}ms...`);
30425
+ logger.info(`Retrying after ${backoff}ms...`);
29920
30426
  await new Promise((resolve) => setTimeout(resolve, backoff));
29921
30427
  return this.createOrder(
29922
30428
  leverage,
@@ -29947,34 +30453,106 @@ var ExtendedAdapter = class _ExtendedAdapter extends BaseAdapter {
29947
30453
  }
29948
30454
  return null;
29949
30455
  } catch (err) {
29950
- console.log("Error opening short extended position", err);
30456
+ logger.error(`Error opening short extended position, ${err}`);
29951
30457
  return null;
29952
30458
  }
29953
30459
  }
29954
30460
  async getDepositOrWithdrawalStatus(orderId, operationsType) {
29955
- try {
29956
- let transferHistory = await this.client.getAssetOperations({
29957
- operationsType: [operationsType],
29958
- operationsStatus: ["COMPLETED" /* COMPLETED */]
29959
- });
29960
- console.log("transferHistory", transferHistory);
29961
- if (operationsType === "DEPOSIT" /* DEPOSIT */) {
29962
- const myTransferStatus = transferHistory.data.find((operation) => operation.transactionHash === orderId);
29963
- if (!myTransferStatus) {
29964
- return false;
30461
+ const maxAttempts = 15;
30462
+ const retryDelayMs = 3e4;
30463
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
30464
+ try {
30465
+ let transferHistory = await this.client.getAssetOperations({
30466
+ operationsType: [operationsType],
30467
+ operationsStatus: ["COMPLETED" /* COMPLETED */]
30468
+ });
30469
+ if (operationsType === "DEPOSIT" /* DEPOSIT */) {
30470
+ const myTransferStatus = transferHistory.data.find(
30471
+ (operation) => operation.transactionHash === orderId
30472
+ );
30473
+ if (!myTransferStatus) {
30474
+ if (attempt < maxAttempts) {
30475
+ logger.info(
30476
+ `Deposit operation not found for transactionHash ${orderId}, retrying (attempt ${attempt}/${maxAttempts})...`
30477
+ );
30478
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
30479
+ continue;
30480
+ }
30481
+ logger.warn(
30482
+ `Deposit operation not found for transactionHash ${orderId} after ${maxAttempts} attempts`
30483
+ );
30484
+ return false;
30485
+ }
30486
+ if (myTransferStatus.status === "COMPLETED" /* COMPLETED */) {
30487
+ logger.info(
30488
+ `Deposit operation ${orderId} completed successfully`
30489
+ );
30490
+ return true;
30491
+ } else {
30492
+ if (attempt < maxAttempts) {
30493
+ logger.info(
30494
+ `Deposit operation ${orderId} found but status is ${myTransferStatus.status}, not COMPLETED. Retrying (attempt ${attempt}/${maxAttempts})...`
30495
+ );
30496
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
30497
+ continue;
30498
+ }
30499
+ logger.warn(
30500
+ `Deposit operation ${orderId} status is ${myTransferStatus.status} after ${maxAttempts} attempts, expected COMPLETED`
30501
+ );
30502
+ return false;
30503
+ }
30504
+ } else {
30505
+ const myTransferStatus = transferHistory.data.find(
30506
+ (operation) => operation.id === orderId.toString()
30507
+ );
30508
+ if (!myTransferStatus) {
30509
+ if (attempt < maxAttempts) {
30510
+ logger.info(
30511
+ `Withdrawal status not found for orderId ${orderId} in completed operations, retrying (attempt ${attempt}/${maxAttempts})...`
30512
+ );
30513
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
30514
+ continue;
30515
+ }
30516
+ logger.warn(
30517
+ `Withdrawal operation not found for orderId ${orderId} after ${maxAttempts} attempts`
30518
+ );
30519
+ return false;
30520
+ }
30521
+ if (myTransferStatus.status === "COMPLETED" /* COMPLETED */) {
30522
+ logger.info(
30523
+ `Withdrawal operation ${orderId} completed successfully`
30524
+ );
30525
+ return true;
30526
+ } else {
30527
+ if (attempt < maxAttempts) {
30528
+ logger.info(
30529
+ `Withdrawal operation ${orderId} found but status is ${myTransferStatus.status}, not COMPLETED. Retrying (attempt ${attempt}/${maxAttempts})...`
30530
+ );
30531
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
30532
+ continue;
30533
+ }
30534
+ logger.warn(
30535
+ `Withdrawal operation ${orderId} status is ${myTransferStatus.status} after ${maxAttempts} attempts, expected COMPLETED`
30536
+ );
30537
+ return false;
30538
+ }
29965
30539
  }
29966
- return true;
29967
- } else {
29968
- const myTransferStatus = transferHistory.data.find((operation) => operation.id === orderId);
29969
- if (!myTransferStatus) {
29970
- return false;
30540
+ } catch (err) {
30541
+ logger.error(
30542
+ `error getting deposit or withdrawal status (attempt ${attempt}/${maxAttempts}): ${err}`
30543
+ );
30544
+ if (attempt < maxAttempts) {
30545
+ logger.info(`Retrying after ${retryDelayMs}ms...`);
30546
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
30547
+ continue;
29971
30548
  }
29972
- return true;
30549
+ logger.error(
30550
+ `Max retry attempts reached for getDepositOrWithdrawalStatus`
30551
+ );
30552
+ return false;
29973
30553
  }
29974
- } catch (err) {
29975
- logger.error(`error getting deposit or withdrawal status: ${err}`);
29976
- return false;
29977
30554
  }
30555
+ return false;
29978
30556
  }
29979
30557
  };
29980
30558
 
@@ -30060,6 +30638,11 @@ var AUMTypes = /* @__PURE__ */ ((AUMTypes2) => {
30060
30638
  AUMTypes2["DEFISPRING"] = "defispring";
30061
30639
  return AUMTypes2;
30062
30640
  })(AUMTypes || {});
30641
+ var PositionTypeAvnuExtended = /* @__PURE__ */ ((PositionTypeAvnuExtended2) => {
30642
+ PositionTypeAvnuExtended2["OPEN"] = "open";
30643
+ PositionTypeAvnuExtended2["CLOSE"] = "close";
30644
+ return PositionTypeAvnuExtended2;
30645
+ })(PositionTypeAvnuExtended || {});
30063
30646
  var UNIVERSAL_MANAGE_IDS = /* @__PURE__ */ ((UNIVERSAL_MANAGE_IDS2) => {
30064
30647
  UNIVERSAL_MANAGE_IDS2["FLASH_LOAN"] = "flash_loan_init";
30065
30648
  UNIVERSAL_MANAGE_IDS2["VESU_LEG1"] = "vesu_leg1";
@@ -33240,7 +33823,8 @@ function getLooperSettings(lstSymbol, underlyingSymbol, vaultSettings, pool1) {
33240
33823
  minHealthFactor: vaultSettings.minHealthFactor,
33241
33824
  quoteAmountToFetchPrice: vaultSettings.quoteAmountToFetchPrice,
33242
33825
  ...baseAdapterConfig,
33243
- supportedPositions: [{ asset: lstToken, isDebt: false }, { asset: Global.getDefaultTokens().find((token) => token.symbol === position), isDebt: true }]
33826
+ supportedPositions: [{ asset: lstToken, isDebt: false }, { asset: Global.getDefaultTokens().find((token) => token.symbol === position), isDebt: true }],
33827
+ minimumVesuMovementAmount: 0
33244
33828
  }));
33245
33829
  const unusedBalanceAdapter = new UnusedBalanceAdapter({
33246
33830
  ...baseAdapterConfig
@@ -33556,7 +34140,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33556
34140
  packedArguments: [
33557
34141
  fromToken.address.toBigInt(),
33558
34142
  //wbtc
33559
- fromToken.address.toBigInt(),
34143
+ toToken.address.toBigInt(),
33560
34144
  //usdc
33561
34145
  vaultAllocator.toBigInt()
33562
34146
  ],
@@ -33570,13 +34154,11 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33570
34154
  }
33571
34155
  async getDepositCall(params) {
33572
34156
  try {
33573
- console.log("params.amount", params.amount);
33574
34157
  const fromToken = this.config.supportedPositions[0].asset;
33575
34158
  const toToken = this.config.supportedPositions[1].asset;
33576
34159
  const vaultAllocator = ContractAddr.from(
33577
34160
  this.config.vaultAllocator.address
33578
34161
  );
33579
- console.log("vaultAllocator", vaultAllocator);
33580
34162
  const quote = await this.getQuotesAvnu(
33581
34163
  fromToken.address.toString(),
33582
34164
  toToken.address.toString(),
@@ -33632,7 +34214,6 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33632
34214
  const vaultAllocator = ContractAddr.from(
33633
34215
  this.config.vaultAllocator.address
33634
34216
  );
33635
- console.log("params.amount", params.amount);
33636
34217
  const quote = await this.getQuotesAvnu(
33637
34218
  fromToken.address.toString(),
33638
34219
  toToken.address.toString(),
@@ -33651,8 +34232,6 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33651
34232
  );
33652
34233
  const swapCallData = getCalldata[0];
33653
34234
  const amount = import_starknet24.uint256.bnToUint256(params.amount.toWei());
33654
- console.log("amount", amount);
33655
- console.log("swapCallData", swapCallData);
33656
34235
  return [
33657
34236
  {
33658
34237
  sanitizer: SIMPLE_SANITIZER,
@@ -33706,7 +34285,7 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33706
34285
  }
33707
34286
  throw new Error("Failed to fetch quote after retries");
33708
34287
  }
33709
- async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e4) {
34288
+ async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 5e3) {
33710
34289
  try {
33711
34290
  const fromToken = this.config.supportedPositions[0].asset;
33712
34291
  const toToken = this.config.supportedPositions[1].asset;
@@ -33727,14 +34306,12 @@ var AvnuAdapter = class _AvnuAdapter extends BaseAdapter {
33727
34306
  return dataObject2;
33728
34307
  }
33729
34308
  const btcPrice = await this.getPriceOfToken(toToken.address.toString());
33730
- console.log("btcPrice", btcPrice);
33731
34309
  if (!btcPrice) {
33732
34310
  logger.error(`error getting btc price: ${btcPrice}`);
33733
34311
  return null;
33734
34312
  }
33735
34313
  const estimatedUsdcAmount = Math.floor(amount * btcPrice);
33736
34314
  const targetBtcBig = BigInt(returnFormattedAmount(amount, toTokenDecimals));
33737
- console.log("targetBtcBig", targetBtcBig);
33738
34315
  let low = BigInt(
33739
34316
  Math.floor(
33740
34317
  estimatedUsdcAmount * 10 ** fromToken.decimals * 0.9
@@ -33837,6 +34414,23 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33837
34414
  debtPrice
33838
34415
  };
33839
34416
  }
34417
+ async getUnusedBalanceUSDCE() {
34418
+ const usdceToken = Global.getDefaultTokens().find(
34419
+ (token) => token.symbol === "USDCe"
34420
+ );
34421
+ const balance = await new ERC20(this.config).balanceOf(
34422
+ usdceToken.address,
34423
+ WALLET_ADDRESS,
34424
+ usdceToken.decimals
34425
+ );
34426
+ const price = await this.pricer.getPrice(usdceToken.symbol);
34427
+ const usdValue = Number(balance.toFixed(usdceToken.decimals)) * price.price;
34428
+ return {
34429
+ tokenInfo: usdceToken,
34430
+ amount: balance,
34431
+ usdValue
34432
+ };
34433
+ }
33840
34434
  async getUnusedBalanceWBTC() {
33841
34435
  const collateralToken = this.metadata.additionalInfo.borrowable_assets[0];
33842
34436
  const balance = await new ERC20(this.config).balanceOf(
@@ -33882,22 +34476,30 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33882
34476
  }
33883
34477
  return extendedAdapter.adapter;
33884
34478
  }
33885
- async moveAssetsToVaultAllocator(amount) {
34479
+ async moveAssetsToVaultAllocator(amount, extendedAdapter) {
33886
34480
  try {
33887
- const usdcToken = Global.getDefaultTokens().find(
33888
- (token) => token.symbol === "USDC"
34481
+ const usdceToken = Global.getDefaultTokens().find(
34482
+ (token) => token.symbol === "USDCe"
33889
34483
  );
33890
34484
  const approveCall = new ERC20(this.config).approve(
33891
- usdcToken.address,
34485
+ usdceToken.address,
33892
34486
  this.metadata.additionalInfo.vaultAllocator,
33893
34487
  amount
33894
34488
  );
33895
34489
  const transferCall = new ERC20(this.config).transfer(
33896
- usdcToken.address,
34490
+ usdceToken.address,
33897
34491
  this.metadata.additionalInfo.vaultAllocator,
33898
34492
  amount
33899
34493
  );
33900
- return [approveCall, transferCall];
34494
+ const proofsInfo = extendedAdapter.getProofsForFromLegacySwap(
34495
+ this.getMerkleTree()
34496
+ );
34497
+ const proofGroups = proofsInfo.proofs;
34498
+ const call = this.getManageCall(
34499
+ proofGroups,
34500
+ await proofsInfo.callConstructor({ amount })
34501
+ );
34502
+ return [approveCall, transferCall, call];
33901
34503
  } catch (err) {
33902
34504
  logger.error(`error moving assets to vault allocator: ${err}`);
33903
34505
  return [];
@@ -33905,11 +34507,13 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33905
34507
  }
33906
34508
  async shouldInvest() {
33907
34509
  try {
34510
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest starting`);
33908
34511
  const vesuAdapter = await this.getVesuAdapter();
33909
34512
  const extendedAdapter = await this.getExtendedAdapter();
33910
- if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
34513
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest adapters fetched: vesuAdapter=${!!vesuAdapter}, extendedAdapter=${!!extendedAdapter}, extendedAdapter.client=${!!extendedAdapter?.client}`);
34514
+ if (!vesuAdapter) {
33911
34515
  logger.error(
33912
- `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
34516
+ `Vesu adapter not configured in metadata. This is a configuration issue, not a temporary failure.`
33913
34517
  );
33914
34518
  return {
33915
34519
  shouldInvest: false,
@@ -33921,10 +34525,87 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33921
34525
  vesuLeverage: 0
33922
34526
  };
33923
34527
  }
34528
+ if (!extendedAdapter) {
34529
+ logger.error(
34530
+ `Extended adapter not configured in metadata. This is a configuration issue, not a temporary failure.`
34531
+ );
34532
+ return {
34533
+ shouldInvest: false,
34534
+ vesuAmount: new Web3Number(0, 0),
34535
+ extendedAmount: new Web3Number(0, 0),
34536
+ extendedLeverage: 0,
34537
+ collateralPrice: 0,
34538
+ debtPrice: 0,
34539
+ vesuLeverage: 0
34540
+ };
34541
+ }
34542
+ if (!extendedAdapter.client) {
34543
+ logger.error(
34544
+ `Extended adapter client not initialized. This may be a temporary initialization failure - check network connectivity and API availability.`
34545
+ );
34546
+ return {
34547
+ shouldInvest: false,
34548
+ vesuAmount: new Web3Number(0, 0),
34549
+ extendedAmount: new Web3Number(0, 0),
34550
+ extendedLeverage: 0,
34551
+ collateralPrice: 0,
34552
+ debtPrice: 0,
34553
+ vesuLeverage: 0
34554
+ };
34555
+ }
34556
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest calling getUnusedBalance`);
33924
34557
  const balance = await this.getUnusedBalance();
34558
+ if (!Number.isFinite(balance.usdValue) || balance.usdValue < 0) {
34559
+ logger.error(
34560
+ `Invalid balance.usdValue: ${balance.usdValue}. Expected a finite, non-negative number.`
34561
+ );
34562
+ return {
34563
+ shouldInvest: false,
34564
+ vesuAmount: new Web3Number(0, 0),
34565
+ extendedAmount: new Web3Number(0, 0),
34566
+ extendedLeverage: 0,
34567
+ collateralPrice: 0,
34568
+ debtPrice: 0,
34569
+ vesuLeverage: 0
34570
+ };
34571
+ }
34572
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest balance: ${balance.usdValue}`);
33925
34573
  const usdcBalanceOnExtended = await extendedAdapter.getExtendedDepositAmount();
33926
- const amountToInvest = balance.amount.plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).minus(LIMIT_BALANCE);
33927
- if (amountToInvest.lessThan(0)) {
34574
+ if (usdcBalanceOnExtended) {
34575
+ const availableForWithdrawal = parseFloat(usdcBalanceOnExtended.availableForWithdrawal);
34576
+ if (!Number.isFinite(availableForWithdrawal) || availableForWithdrawal < 0) {
34577
+ logger.error(
34578
+ `Invalid usdcBalanceOnExtended.availableForWithdrawal: ${usdcBalanceOnExtended.availableForWithdrawal}. Expected a finite, non-negative number.`
34579
+ );
34580
+ return {
34581
+ shouldInvest: false,
34582
+ vesuAmount: new Web3Number(0, 0),
34583
+ extendedAmount: new Web3Number(0, 0),
34584
+ extendedLeverage: 0,
34585
+ collateralPrice: 0,
34586
+ debtPrice: 0,
34587
+ vesuLeverage: 0
34588
+ };
34589
+ }
34590
+ }
34591
+ const amountToInvest = new Web3Number(balance.usdValue, USDC_TOKEN_DECIMALS).plus(usdcBalanceOnExtended?.availableForWithdrawal ?? 0).multipliedBy(1 - LIMIT_BALANCE);
34592
+ const amountToInvestNumber = amountToInvest.toNumber();
34593
+ if (!Number.isFinite(amountToInvestNumber)) {
34594
+ logger.error(
34595
+ `Invalid amountToInvest calculation result: ${amountToInvestNumber}. Calculation may have produced NaN or Infinity.`
34596
+ );
34597
+ return {
34598
+ shouldInvest: false,
34599
+ vesuAmount: new Web3Number(0, 0),
34600
+ extendedAmount: new Web3Number(0, 0),
34601
+ extendedLeverage: 0,
34602
+ collateralPrice: 0,
34603
+ debtPrice: 0,
34604
+ vesuLeverage: 0
34605
+ };
34606
+ }
34607
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest amountToInvest: ${amountToInvestNumber}`);
34608
+ if (amountToInvest.lessThan(LIMIT_BALANCE_VALUE)) {
33928
34609
  return {
33929
34610
  shouldInvest: false,
33930
34611
  vesuAmount: new Web3Number(0, 0),
@@ -33953,6 +34634,34 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33953
34634
  collateralPrice,
33954
34635
  debtPrice
33955
34636
  } = await this.getAssetPrices();
34637
+ if (!Number.isFinite(collateralPrice.price) || collateralPrice.price <= 0) {
34638
+ logger.error(
34639
+ `Invalid collateralPrice: ${collateralPrice.price}. Expected a finite, positive number.`
34640
+ );
34641
+ return {
34642
+ shouldInvest: false,
34643
+ vesuAmount: new Web3Number(0, 0),
34644
+ extendedAmount: new Web3Number(0, 0),
34645
+ extendedLeverage: 0,
34646
+ collateralPrice: 0,
34647
+ debtPrice: 0,
34648
+ vesuLeverage: 0
34649
+ };
34650
+ }
34651
+ if (!Number.isFinite(debtPrice.price) || debtPrice.price <= 0) {
34652
+ logger.error(
34653
+ `Invalid debtPrice: ${debtPrice.price}. Expected a finite, positive number.`
34654
+ );
34655
+ return {
34656
+ shouldInvest: false,
34657
+ vesuAmount: new Web3Number(0, 0),
34658
+ extendedAmount: new Web3Number(0, 0),
34659
+ extendedLeverage: 0,
34660
+ collateralPrice: 0,
34661
+ debtPrice: 0,
34662
+ vesuLeverage: 0
34663
+ };
34664
+ }
33956
34665
  const { vesu_amount, extended_amount, extended_leverage, vesu_leverage } = await calculateAmountDistribution(
33957
34666
  amountToInvest.toNumber(),
33958
34667
  extendedAdapter.client,
@@ -33976,6 +34685,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
33976
34685
  vesuLeverage: 0
33977
34686
  };
33978
34687
  }
34688
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldInvest vesu_amount: ${vesu_amount.toNumber()}, extended_amount: ${extended_amount.toNumber()}`);
33979
34689
  return {
33980
34690
  shouldInvest: true,
33981
34691
  vesuAmount: vesu_amount,
@@ -34002,18 +34712,48 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34002
34712
  try {
34003
34713
  const vesuAdapter = await this.getVesuAdapter();
34004
34714
  const extendedAdapter = await this.getExtendedAdapter();
34005
- let calls = [];
34006
34715
  if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
34007
34716
  logger.error(
34008
34717
  `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
34009
34718
  );
34010
- return calls;
34719
+ return [];
34720
+ }
34721
+ const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
34722
+ if (!extendedHoldings) {
34723
+ logger.error(`error getting extended holdings: ${extendedHoldings}`);
34724
+ return [];
34011
34725
  }
34012
- console.log("extendedAmount", extendedAmount);
34013
- console.log("vesuAmount", vesuAmount);
34014
- if (extendedAmount.lessThan(0)) {
34726
+ const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
34727
+ const usdcAmountOnExtendedAvailableForWithdrawal = parseFloat(
34728
+ extendedHoldings.availableForWithdrawal
34729
+ );
34730
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldMoveAssets calculating movements - Extended current: ${usdcAmountOnExtendedAvailableForWithdrawal}, Wallet: ${usdcAmountInWallet.toNumber()}, Target Extended: ${extendedAmount.toNumber()}, Target Vesu: ${vesuAmount.toNumber()}`);
34731
+ let totalExtendedWithdrawal = new Web3Number(0, USDC_TOKEN_DECIMALS);
34732
+ let totalExtendedDeposit = new Web3Number(0, USDC_TOKEN_DECIMALS);
34733
+ if (extendedAmount.isNegative() && extendedAmount.abs().greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
34734
+ totalExtendedWithdrawal = totalExtendedWithdrawal.plus(extendedAmount.abs());
34735
+ }
34736
+ const extendedTargetAmount = extendedAmount.abs();
34737
+ let projectedExtendedBalance = usdcAmountOnExtendedAvailableForWithdrawal;
34738
+ if (extendedAmount.isNegative()) {
34739
+ projectedExtendedBalance = projectedExtendedBalance - extendedAmount.abs().toNumber();
34740
+ }
34741
+ const extendedAmountDifference = extendedTargetAmount.minus(projectedExtendedBalance);
34742
+ const extendedAmountDifferenceAbs = extendedAmountDifference.abs();
34743
+ if (extendedAmountDifference.lessThan(0)) {
34744
+ totalExtendedWithdrawal = totalExtendedWithdrawal.plus(extendedAmountDifferenceAbs);
34745
+ } else if (extendedAmountDifference.greaterThan(0)) {
34746
+ totalExtendedDeposit = totalExtendedDeposit.plus(extendedAmountDifference);
34747
+ }
34748
+ const vesuTargetAmount = vesuAmount.abs();
34749
+ const projectedWalletBalance = usdcAmountInWallet.plus(totalExtendedWithdrawal).minus(totalExtendedDeposit);
34750
+ let vesuAmountDifference = vesuTargetAmount.minus(projectedWalletBalance);
34751
+ const vesuAmountDifferenceAbs = vesuAmountDifference.abs();
34752
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::shouldMoveAssets calculated movements - Extended withdrawal: ${totalExtendedWithdrawal.toNumber()}, Extended deposit: ${totalExtendedDeposit.toNumber()}, Extended diff: ${extendedAmountDifference.toNumber()}, Projected wallet: ${projectedWalletBalance.toNumber()}, Vesu diff: ${vesuAmountDifference.toNumber()}`);
34753
+ let calls = [];
34754
+ if (extendedAmount.isNegative() && extendedAmount.abs().greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
34015
34755
  try {
34016
- const extendedCalls = await this.moveAssets(
34756
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
34017
34757
  {
34018
34758
  to: Protocols.VAULT.name,
34019
34759
  from: Protocols.EXTENDED.name,
@@ -34022,14 +34762,18 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34022
34762
  extendedAdapter,
34023
34763
  vesuAdapter
34024
34764
  );
34025
- calls.push(...extendedCalls);
34765
+ if (extendedStatus) {
34766
+ calls.push(...extendedCalls);
34767
+ } else {
34768
+ return [];
34769
+ }
34026
34770
  } catch (err) {
34027
34771
  logger.error(`Failed moving assets to vault: ${err}`);
34028
34772
  }
34029
34773
  }
34030
- if (vesuAmount.lessThan(0)) {
34774
+ if (vesuAmount.isNegative() && vesuAmount.abs().greaterThan(vesuAdapter.minimumVesuMovementAmount)) {
34031
34775
  try {
34032
- const vesuCalls = await this.moveAssets(
34776
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
34033
34777
  {
34034
34778
  to: Protocols.EXTENDED.name,
34035
34779
  from: Protocols.VESU.name,
@@ -34039,49 +34783,83 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34039
34783
  vesuAdapter
34040
34784
  );
34041
34785
  calls.push(...vesuCalls);
34786
+ if (!vesuStatus) {
34787
+ return [];
34788
+ }
34042
34789
  } catch (err) {
34043
34790
  logger.error(`Failed moving assets to vault: ${err}`);
34044
34791
  }
34045
34792
  }
34046
- const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
34047
- if (!extendedHoldings) {
34048
- logger.error(`error getting extended holdings: ${extendedHoldings}`);
34049
- return calls;
34050
- }
34051
- const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
34052
- const usdcAmountOnExtended = parseFloat(
34053
- extendedHoldings.availableForWithdrawal
34054
- );
34055
- if (extendedAmount.minus(usdcAmountOnExtended).greaterThan(0)) {
34056
- try {
34057
- const extendedCalls = await this.moveAssets(
34058
- {
34059
- to: Protocols.EXTENDED.name,
34060
- from: Protocols.VAULT.name,
34061
- amount: extendedAmount.minus(usdcAmountOnExtended)
34062
- },
34063
- extendedAdapter,
34064
- vesuAdapter
34065
- );
34066
- calls.push(...extendedCalls);
34067
- } catch (err) {
34068
- logger.error(`Failed moving assets to extended: ${err}`);
34793
+ if (extendedAmountDifferenceAbs.greaterThan(extendedAdapter.minimumExtendedMovementAmount)) {
34794
+ if (extendedAmountDifference.greaterThan(0)) {
34795
+ try {
34796
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
34797
+ {
34798
+ to: Protocols.EXTENDED.name,
34799
+ from: Protocols.VAULT.name,
34800
+ amount: extendedAmountDifference
34801
+ },
34802
+ extendedAdapter,
34803
+ vesuAdapter
34804
+ );
34805
+ if (extendedStatus) {
34806
+ calls.push(...extendedCalls);
34807
+ } else {
34808
+ logger.error(`Failed to move assets to extended - operation returned false status`);
34809
+ return [];
34810
+ }
34811
+ } catch (err) {
34812
+ logger.error(`Failed moving assets to extended: ${err}`);
34813
+ return [];
34814
+ }
34815
+ } else if (extendedAmountDifference.lessThan(0)) {
34816
+ try {
34817
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
34818
+ {
34819
+ to: Protocols.VAULT.name,
34820
+ from: Protocols.EXTENDED.name,
34821
+ amount: extendedAmountDifferenceAbs
34822
+ },
34823
+ extendedAdapter,
34824
+ vesuAdapter
34825
+ );
34826
+ if (extendedStatus) {
34827
+ calls.push(...extendedCalls);
34828
+ } else {
34829
+ logger.error(`Failed to withdraw from extended - operation returned false status`);
34830
+ return [];
34831
+ }
34832
+ } catch (err) {
34833
+ logger.error(`Failed moving assets from extended to vault: ${err}`);
34834
+ return [];
34835
+ }
34069
34836
  }
34070
34837
  }
34071
- if (vesuAmount.minus(usdcAmountInWallet).greaterThan(0)) {
34072
- try {
34073
- const vesuCalls = await this.moveAssets(
34074
- {
34075
- to: Protocols.VESU.name,
34076
- from: Protocols.EXTENDED.name,
34077
- amount: vesuAmount.minus(usdcAmountInWallet)
34078
- },
34079
- extendedAdapter,
34080
- vesuAdapter
34838
+ if (vesuAmountDifferenceAbs.greaterThan(vesuAdapter.minimumVesuMovementAmount)) {
34839
+ if (vesuAmountDifference.lessThanOrEqualTo(0)) {
34840
+ logger.warn(
34841
+ `Vesu amount difference is negative or zero: ${vesuAmountDifference.toNumber()}. Skipping operation.`
34081
34842
  );
34082
- calls.push(...vesuCalls);
34083
- } catch (err) {
34084
- logger.error(`Failed moving assets to vault: ${err}`);
34843
+ } else {
34844
+ try {
34845
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
34846
+ {
34847
+ to: Protocols.VAULT.name,
34848
+ from: Protocols.EXTENDED.name,
34849
+ amount: vesuAmountDifference
34850
+ },
34851
+ extendedAdapter,
34852
+ vesuAdapter
34853
+ );
34854
+ if (!vesuStatus) {
34855
+ logger.error(`Failed to move assets to vesu - operation returned false status`);
34856
+ return [];
34857
+ }
34858
+ calls.push(...vesuCalls);
34859
+ } catch (err) {
34860
+ logger.error(`Failed moving assets to vault: ${err}`);
34861
+ return [];
34862
+ }
34085
34863
  }
34086
34864
  }
34087
34865
  return calls;
@@ -34092,12 +34870,47 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34092
34870
  }
34093
34871
  async moveAssets(params, extendedAdapter, vesuAdapter) {
34094
34872
  try {
34873
+ if (params.amount.lessThanOrEqualTo(0)) {
34874
+ logger.error(
34875
+ `Invalid amount for moveAssets: ${params.amount.toNumber()}. Amount must be positive.`
34876
+ );
34877
+ return {
34878
+ calls: [],
34879
+ status: false
34880
+ };
34881
+ }
34882
+ const amountAbs = params.amount.abs();
34883
+ if (params.from === Protocols.EXTENDED.name || params.to === Protocols.EXTENDED.name) {
34884
+ if (amountAbs.lessThanOrEqualTo(extendedAdapter.minimumExtendedMovementAmount)) {
34885
+ logger.warn(
34886
+ `Amount ${amountAbs.toNumber()} is below minimum Extended movement amount ${extendedAdapter.minimumExtendedMovementAmount}. Skipping operation.`
34887
+ );
34888
+ return {
34889
+ calls: [],
34890
+ status: false
34891
+ };
34892
+ }
34893
+ }
34894
+ if (params.from === Protocols.VESU.name || params.to === Protocols.VESU.name) {
34895
+ if (amountAbs.lessThanOrEqualTo(vesuAdapter.minimumVesuMovementAmount)) {
34896
+ logger.warn(
34897
+ `Amount ${amountAbs.toNumber()} is below minimum Vesu movement amount ${vesuAdapter.minimumVesuMovementAmount}. Skipping operation.`
34898
+ );
34899
+ return {
34900
+ calls: [],
34901
+ status: false
34902
+ };
34903
+ }
34904
+ }
34095
34905
  const avnuAdapter = await this.getAvnuAdapter();
34096
34906
  if (!avnuAdapter) {
34097
34907
  logger.error(`avnu adapter not found: ${avnuAdapter}`);
34098
- return [];
34908
+ return {
34909
+ calls: [],
34910
+ status: false
34911
+ };
34099
34912
  }
34100
- logger.info("moveAssets params", params);
34913
+ logger.info(`moveAssets params, ${JSON.stringify(params)}`);
34101
34914
  const collateralToken = vesuAdapter.config.supportedPositions[0].asset;
34102
34915
  const {
34103
34916
  collateralPrice
@@ -34114,21 +34927,78 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34114
34927
  await proofsInfo.callConstructor({ amount: params.amount })
34115
34928
  );
34116
34929
  calls.push(call);
34117
- return calls;
34930
+ return {
34931
+ calls: [call],
34932
+ status: true
34933
+ };
34118
34934
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.EXTENDED.name) {
34935
+ const extendedLeverage = calculateExtendedLevergae();
34936
+ const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
34937
+ if (!extendedHoldings) {
34938
+ logger.error(`error getting extended holdings: ${extendedHoldings}`);
34939
+ return {
34940
+ calls: [],
34941
+ status: false
34942
+ };
34943
+ }
34944
+ const extendedHoldingAmount = new Web3Number(
34945
+ extendedHoldings.availableForWithdrawal,
34946
+ USDC_TOKEN_DECIMALS
34947
+ );
34948
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets extendedHoldingAmount: ${extendedHoldingAmount.toNumber()}`);
34949
+ if (params.amount.abs().greaterThan(extendedHoldingAmount)) {
34950
+ const leftAmountAfterWithdrawalAmountInAccount = params.amount.abs().minus(extendedHoldingAmount);
34951
+ logger.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets leftAmountAfterWithdrawalAmountInAccount: ${leftAmountAfterWithdrawalAmountInAccount.toNumber()}`);
34952
+ const btcAmount = leftAmountAfterWithdrawalAmountInAccount.dividedBy(collateralPrice.price);
34953
+ const openLongPosition = btcAmount.multipliedBy(3).greaterThan(MINIMUM_EXTENDED_POSITION_SIZE) ? await extendedAdapter.createOrder(
34954
+ extendedLeverage.toString(),
34955
+ btcAmount.toNumber(),
34956
+ "BUY" /* BUY */
34957
+ ) : await extendedAdapter.createOrder(
34958
+ extendedLeverage.toString(),
34959
+ 35e-6,
34960
+ // just in case amount falls short then we need to create a withdrawal
34961
+ "BUY" /* BUY */
34962
+ );
34963
+ if (!openLongPosition) {
34964
+ logger.error(`error opening long position: ${openLongPosition}`);
34965
+ }
34966
+ const updatedHoldings = await extendedAdapter.getExtendedDepositAmount();
34967
+ if (!updatedHoldings || new Web3Number(updatedHoldings.availableForWithdrawal, USDC_TOKEN_DECIMALS).lessThan(params.amount.abs())) {
34968
+ logger.error(`Insufficient balance after opening position. Available: ${updatedHoldings?.availableForWithdrawal}, Needed: ${params.amount.abs()}`);
34969
+ return { calls: [], status: false };
34970
+ }
34971
+ }
34119
34972
  const withdrawalFromExtended = await extendedAdapter.withdrawFromExtended(params.amount);
34120
34973
  if (withdrawalFromExtended) {
34121
- const calls = await this.moveAssetsToVaultAllocator(params.amount);
34974
+ const extendedHoldings2 = await extendedAdapter.getExtendedDepositAmount();
34975
+ logger.info(`extendedHoldings after withdrawal ${extendedHoldings2?.availableForWithdrawal}`);
34976
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
34977
+ const calls = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
34122
34978
  if (calls.length > 0) {
34123
- return calls;
34979
+ return {
34980
+ calls,
34981
+ status: true
34982
+ };
34124
34983
  }
34125
34984
  } else {
34126
34985
  logger.error("withdrawal from extended failed");
34986
+ return {
34987
+ calls: [],
34988
+ status: false
34989
+ };
34127
34990
  }
34128
- return [];
34129
34991
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.VESU.name) {
34992
+ const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, "close" /* CLOSE */);
34993
+ if (!isPriceDifferenceBetweenAvnuAndExtended) {
34994
+ logger.warn(`price difference between avnu and extended doesn't fit the range for close position, ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
34995
+ return {
34996
+ calls: [],
34997
+ status: false
34998
+ };
34999
+ }
34130
35000
  const vesuAmountInBTC = new Web3Number(
34131
- params.amount.dividedBy(collateralPrice.price).toNumber(),
35001
+ params.amount.dividedBy(collateralPrice.price).toFixed(WBTC_TOKEN_DECIMALS),
34132
35002
  collateralToken.decimals
34133
35003
  );
34134
35004
  const proofsInfo = vesuAdapter.getProofs(false, this.getMerkleTree());
@@ -34146,8 +35016,19 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34146
35016
  await swapProofsInfo.callConstructor({ amount: vesuAmountInBTC })
34147
35017
  );
34148
35018
  calls.push(swapCall);
34149
- return calls;
35019
+ return {
35020
+ calls,
35021
+ status: true
35022
+ };
34150
35023
  } else if (params.to === Protocols.EXTENDED.name && params.from === Protocols.VESU.name) {
35024
+ const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, "close" /* CLOSE */);
35025
+ if (!isPriceDifferenceBetweenAvnuAndExtended) {
35026
+ logger.warn(`price difference between avnu and extended doesn't fit the range for close position, ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
35027
+ return {
35028
+ calls: [],
35029
+ status: false
35030
+ };
35031
+ }
34151
35032
  const vesuAmountInBTC = new Web3Number(
34152
35033
  params.amount.dividedBy(collateralPrice.price).toNumber(),
34153
35034
  collateralToken.decimals
@@ -34177,13 +35058,21 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34177
35058
  await proofsInfoDeposit.callConstructor({ amount: params.amount })
34178
35059
  );
34179
35060
  calls.push(callDeposit);
34180
- return calls;
35061
+ return {
35062
+ calls,
35063
+ status: true
35064
+ };
34181
35065
  }
34182
- console.warn("moveAssets received unsupported route:", params);
34183
- return [];
35066
+ return {
35067
+ calls: [],
35068
+ status: false
35069
+ };
34184
35070
  } catch (err) {
34185
35071
  logger.error(`error moving assets: ${err}`);
34186
- return [];
35072
+ return {
35073
+ calls: [],
35074
+ status: false
35075
+ };
34187
35076
  }
34188
35077
  }
34189
35078
  async handleDeposit() {
@@ -34203,7 +35092,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34203
35092
  };
34204
35093
  }
34205
35094
  const extendedLeverage = calculateExtendedLevergae();
34206
- const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter);
35095
+ const isPriceDifferenceBetweenAvnuAndExtended = await this.checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, "open" /* OPEN */);
34207
35096
  if (!isPriceDifferenceBetweenAvnuAndExtended) {
34208
35097
  logger.error("price difference between avnu and extended doesn't fit the range");
34209
35098
  return {
@@ -34220,6 +35109,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34220
35109
  };
34221
35110
  }
34222
35111
  const extendedPositionValue = position.length > 0 ? parseFloat(position[0].value) : 0;
35112
+ const BUFFER_AMOUNT_IN_AVAILABLE_FOR_TRADE = BUFFER_USDC_IN_WITHDRAWAL;
34223
35113
  const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
34224
35114
  if (!extendedHoldings) {
34225
35115
  logger.error(`error getting extended holdings: ${extendedHoldings}`);
@@ -34238,12 +35128,11 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34238
35128
  const { collateralPrice } = await this.getAssetPrices();
34239
35129
  const { vesuAmountInBTC, extendedAmountInBTC } = calculateVesUPositionSizeGivenExtended(
34240
35130
  extendedPositionValue,
34241
- extendedHoldingAmount,
35131
+ extendedHoldingAmount.minus(BUFFER_AMOUNT_IN_AVAILABLE_FOR_TRADE),
34242
35132
  collateralTokenAmount,
34243
35133
  collateralPrice.price
34244
35134
  );
34245
- console.log("vesuAmountInBTC", vesuAmountInBTC);
34246
- console.log("extendedAmountInBTC", extendedAmountInBTC);
35135
+ logger.info(`vesuAmountInBTC ${vesuAmountInBTC}, extendedAmountInBTC ${extendedAmountInBTC}`);
34247
35136
  let calls = [];
34248
35137
  if (vesuAmountInBTC.greaterThan(MINIMUM_EXTENDED_POSITION_SIZE)) {
34249
35138
  const proofsInfo = vesuAdapter.getProofs(true, this.getMerkleTree());
@@ -34256,7 +35145,6 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34256
35145
  );
34257
35146
  const { amount: wbtcAmountInVaultAllocator } = await this.getUnusedBalanceWBTC();
34258
35147
  if (wbtcAmountInVaultAllocator.lessThan(vesuAmountInBTC)) {
34259
- console.log("error wbtc amount in vault allocator is less than vesu amount in btc", wbtcAmountInVaultAllocator, vesuAmountInBTC);
34260
35148
  const swapProofsInfo = avnuAdapter.getProofs(true, this.getMerkleTree());
34261
35149
  const swapProofGroups = swapProofsInfo.proofs;
34262
35150
  const swapCall = this.getManageCall(
@@ -34291,68 +35179,98 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34291
35179
  extendedAmountInBTC: new Web3Number(0, 0),
34292
35180
  calls: []
34293
35181
  };
34294
- ;
34295
35182
  }
34296
35183
  }
34297
- async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter) {
35184
+ async checkPriceDifferenceBetweenAvnuAndExtended(extendedAdapter, vesuAdapter, avnuAdapter, positionType) {
34298
35185
  const {
34299
35186
  ask,
34300
35187
  bid
34301
35188
  } = await extendedAdapter.fetchOrderBookBTCUSDC();
34302
35189
  const price = ask.plus(bid).dividedBy(2);
34303
- const btcToken = vesuAdapter.config.supportedPositions[1].asset;
35190
+ const btcToken = vesuAdapter.config.supportedPositions[0].asset;
34304
35191
  const btcPriceAvnu = await avnuAdapter.getPriceOfToken(btcToken.address.toString());
34305
35192
  if (!btcPriceAvnu) {
34306
35193
  logger.error(`error getting btc price avnu: ${btcPriceAvnu}`);
34307
35194
  return false;
34308
35195
  }
34309
- const priceDifference = price.minus(btcPriceAvnu).toNumber();
34310
- if (priceDifference < MAX_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED && priceDifference > MIN_PRICE_DIFFERENCE_BETWEEN_AVNU_AND_EXTENDED) {
34311
- return true;
35196
+ const priceDifference = new Web3Number(price.minus(btcPriceAvnu).toFixed(2), 0);
35197
+ if (priceDifference.isNegative()) {
35198
+ return false;
35199
+ }
35200
+ if (positionType === "open" /* OPEN */) {
35201
+ logger.info(`price difference between avnu and extended for open position: ${priceDifference.toNumber()}, minimumExtendedPriceDifferenceForSwapOpen: ${avnuAdapter.config.minimumExtendedPriceDifferenceForSwapOpen}`);
35202
+ const result = priceDifference.greaterThanOrEqualTo(avnuAdapter.config.minimumExtendedPriceDifferenceForSwapOpen);
35203
+ logger.info(`result: ${result}`);
35204
+ return result;
35205
+ } else {
35206
+ logger.info(`price difference between avnu and extended for close position: ${priceDifference.toNumber()}, maximumExtendedPriceDifferenceForSwapClosing: ${avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing}`);
35207
+ const result = priceDifference.lessThanOrEqualTo(avnuAdapter.config.maximumExtendedPriceDifferenceForSwapClosing);
35208
+ logger.info(`result: ${result}`);
35209
+ return result;
34312
35210
  }
34313
- logger.error(`price difference between avnu and extended doesn't fit the range, priceDifference: ${priceDifference}`);
34314
- return false;
34315
35211
  }
34316
35212
  async handleWithdraw(amount) {
34317
35213
  try {
34318
35214
  const usdcBalanceVaultAllocator = await this.getUnusedBalance();
34319
- const usdcBalanceDifference = amount.minus(usdcBalanceVaultAllocator.usdValue);
35215
+ const usdcBalanceDifference = amount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcBalanceVaultAllocator.usdValue);
34320
35216
  logger.info(`usdcBalanceDifference, ${usdcBalanceDifference.toNumber()}`);
35217
+ let calls = [];
35218
+ let status = true;
34321
35219
  if (usdcBalanceDifference.lessThan(0)) {
34322
- const withdrawCall = await this.getBringLiquidityCall({
34323
- amount
35220
+ const withdrawCall2 = await this.getBringLiquidityCall({
35221
+ amount: usdcBalanceVaultAllocator.amount
34324
35222
  });
34325
- logger.info("withdraw call", withdrawCall);
34326
- return [withdrawCall];
35223
+ logger.info("withdraw call", withdrawCall2);
35224
+ calls.push(withdrawCall2);
35225
+ return {
35226
+ calls,
35227
+ status: true
35228
+ };
34327
35229
  }
34328
35230
  const vesuAdapter = await this.getVesuAdapter();
34329
35231
  const extendedAdapter = await this.getExtendedAdapter();
34330
35232
  if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
35233
+ status = false;
34331
35234
  logger.error(
34332
35235
  `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
34333
35236
  );
34334
- return [];
35237
+ return {
35238
+ calls,
35239
+ status
35240
+ };
34335
35241
  }
34336
35242
  const { collateralTokenAmount } = await vesuAdapter.vesuAdapter.getAssetPrices();
34337
35243
  const {
34338
35244
  collateralPrice
34339
35245
  } = await this.getAssetPrices();
34340
35246
  const extendedPositon = await extendedAdapter.getAllOpenPositions();
35247
+ if (!extendedPositon) {
35248
+ status = false;
35249
+ logger.error("error getting extended position", extendedPositon);
35250
+ return {
35251
+ calls,
35252
+ status
35253
+ };
35254
+ }
34341
35255
  const amountDistributionForWithdrawal = await calculateAmountDistributionForWithdrawal(
34342
- amount,
35256
+ usdcBalanceDifference,
34343
35257
  collateralPrice.price,
34344
35258
  collateralTokenAmount,
34345
35259
  extendedPositon
34346
35260
  );
34347
35261
  if (!amountDistributionForWithdrawal) {
35262
+ status = false;
34348
35263
  logger.error(
34349
35264
  `error calculating amount distribution for withdrawal: ${amountDistributionForWithdrawal}`
34350
35265
  );
34351
- return [];
35266
+ return {
35267
+ calls,
35268
+ status
35269
+ };
34352
35270
  }
34353
35271
  const { vesu_amount, extended_amount } = amountDistributionForWithdrawal;
34354
- if (vesu_amount.greaterThan(0)) {
34355
- const result = await this.moveAssets(
35272
+ if (status && vesu_amount.greaterThan(0)) {
35273
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
34356
35274
  {
34357
35275
  amount: vesu_amount,
34358
35276
  from: Protocols.VESU.name,
@@ -34361,10 +35279,11 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34361
35279
  extendedAdapter,
34362
35280
  vesuAdapter
34363
35281
  );
34364
- return result;
35282
+ status = vesuStatus;
35283
+ calls.push(...vesuCalls);
34365
35284
  }
34366
- if (extended_amount.greaterThan(0)) {
34367
- const result = await this.moveAssets(
35285
+ if (status && extended_amount.greaterThan(0)) {
35286
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
34368
35287
  {
34369
35288
  amount: extended_amount,
34370
35289
  from: Protocols.EXTENDED.name,
@@ -34373,12 +35292,32 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34373
35292
  extendedAdapter,
34374
35293
  vesuAdapter
34375
35294
  );
34376
- return result;
35295
+ status = extendedStatus;
35296
+ if (status) {
35297
+ calls.push(...extendedCalls);
35298
+ } else {
35299
+ logger.error("error moving assets to vault: extendedStatus: ${extendedStatus}");
35300
+ return {
35301
+ calls: [],
35302
+ status
35303
+ };
35304
+ }
34377
35305
  }
34378
- return [];
35306
+ const withdrawCall = await this.getBringLiquidityCall({
35307
+ amount
35308
+ });
35309
+ logger.info("withdraw call", withdrawCall);
35310
+ calls.push(withdrawCall);
35311
+ return {
35312
+ calls,
35313
+ status
35314
+ };
34379
35315
  } catch (err) {
34380
35316
  logger.error(`error handling withdrawal: ${err}`);
34381
- return [];
35317
+ return {
35318
+ calls: [],
35319
+ status: false
35320
+ };
34382
35321
  }
34383
35322
  }
34384
35323
  async getAUM() {
@@ -34426,7 +35365,7 @@ var VesuExtendedMultiplierStrategy = class _VesuExtendedMultiplierStrategy exten
34426
35365
  };
34427
35366
  }
34428
35367
  };
34429
- function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendUrl, extendedApiKey, vaultIdExtended) {
35368
+ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, extendedBackendUrl, extendedApiKey, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
34430
35369
  vaultSettings.leafAdapters = [];
34431
35370
  const wbtcToken = Global.getDefaultTokens().find(
34432
35371
  (token) => token.symbol === lstSymbol
@@ -34450,7 +35389,9 @@ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, e
34450
35389
  ...baseAdapterConfig,
34451
35390
  avnuContract: AVNU_MIDDLEWARE,
34452
35391
  slippage: 0.01,
34453
- baseUrl: AVNU_QUOTE_URL
35392
+ baseUrl: AVNU_QUOTE_URL,
35393
+ minimumExtendedPriceDifferenceForSwapOpen,
35394
+ maximumExtendedPriceDifferenceForSwapClosing
34454
35395
  });
34455
35396
  const extendedAdapter = new ExtendedAdapter({
34456
35397
  ...baseAdapterConfig,
@@ -34466,7 +35407,10 @@ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, e
34466
35407
  extendedBaseUrl: "https://api.starknet.extended.exchange",
34467
35408
  extendedMarketName: "BTC-USD",
34468
35409
  extendedPrecision: 5,
34469
- avnuAdapter
35410
+ avnuAdapter,
35411
+ retryDelayForOrderStatus: minimumExtendedRetriesDelayForOrderStatus ?? 3e3,
35412
+ minimumExtendedMovementAmount: minimumExtendedMovementAmount ?? 5
35413
+ //5 usdcs
34470
35414
  });
34471
35415
  const vesuMultiplyAdapter = new VesuMultiplyAdapter({
34472
35416
  poolId: pool1,
@@ -34479,7 +35423,9 @@ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, e
34479
35423
  supportedPositions: [
34480
35424
  { asset: wbtcToken, isDebt: false },
34481
35425
  { asset: usdcToken, isDebt: true }
34482
- ]
35426
+ ],
35427
+ minimumVesuMovementAmount: minimumVesuMovementAmount ?? 5
35428
+ //5 usdc
34483
35429
  });
34484
35430
  const unusedBalanceAdapter = new UnusedBalanceAdapter({
34485
35431
  ...baseAdapterConfig
@@ -34512,6 +35458,7 @@ function getLooperSettings2(lstSymbol, underlyingSymbol, vaultSettings, pool1, e
34512
35458
  () => vesuMultiplyAdapter.getWithdrawLeaf()
34513
35459
  );
34514
35460
  vaultSettings.leafAdapters.push(() => extendedAdapter.getDepositLeaf());
35461
+ vaultSettings.leafAdapters.push(() => extendedAdapter.getSwapFromLegacyLeaf());
34515
35462
  vaultSettings.leafAdapters.push(() => avnuAdapter.getDepositLeaf());
34516
35463
  vaultSettings.leafAdapters.push(() => avnuAdapter.getWithdrawLeaf());
34517
35464
  vaultSettings.leafAdapters.push(
@@ -34574,11 +35521,11 @@ function VaultDescription2(lstSymbol, underlyingSymbol) {
34574
35521
  ] });
34575
35522
  }
34576
35523
  var re7UsdcPrimeDevansh = {
34577
- vaultAddress: ContractAddr.from("0x520a2e945dd0762e5284fc1b012f62ca04e238e105eb362d5e0ce208928729d"),
34578
- manager: ContractAddr.from("0x6abe24d31cbc16d7c4acb2421a826f96273e225b4a2d168d91e65123da0bfb9"),
34579
- vaultAllocator: ContractAddr.from("0x6e4f716e22efb164ee4a831233e513f45396ad3be4cff3c07386be0226febed"),
34580
- redeemRequestNFT: ContractAddr.from("0x66060e1874e05506b18e6029188ec49bf231a411ad57642311bbdf3cb22e5f"),
34581
- aumOracle: ContractAddr.from("0x301d883b9b45c76132638e39326b3f464c492599623263d405ec0df991e27ab"),
35524
+ vaultAddress: ContractAddr.from("0x7efaff77601813ca674c1ffe0479fc0361c0f5099f64a67d4793b80382750c2"),
35525
+ manager: ContractAddr.from("0x2579342f53fbf2f775b0c71d24f162aaf1d3e466edea09a6c51e77a95bd986d"),
35526
+ vaultAllocator: ContractAddr.from("0x46ee6073484a669631e8f88b9f357b0b073cee1bc47752fc32453dd6c1efd7b"),
35527
+ redeemRequestNFT: ContractAddr.from("0x1d66120b0a76068454ea36276d9f404b0a980083dcaebbf6d9f4ad154a79dbe"),
35528
+ aumOracle: ContractAddr.from("0x419a5e8b5a1fe5b2586e64409d5cfdb1712791aaa9361264730227563d4e140"),
34582
35529
  leafAdapters: [],
34583
35530
  adapters: [],
34584
35531
  targetHealthFactor: 1.4,
@@ -34593,12 +35540,12 @@ var re7UsdcPrimeDevansh = {
34593
35540
  borrowable_assets: [Global.getDefaultTokens().find((token) => token.symbol === "WBTC")],
34594
35541
  minimumWBTCDifferenceForAvnuSwap: MINIMUM_WBTC_DIFFERENCE_FOR_AVNU_SWAP
34595
35542
  };
34596
- var VesuExtendedTestStrategies = (extendedBackendUrl, extendedApiKey, vaultIdExtended) => {
35543
+ var VesuExtendedTestStrategies = (extendedBackendUrl, extendedApiKey, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) => {
34597
35544
  return [
34598
- getStrategySettingsVesuExtended("WBTC", "USDC", re7UsdcPrimeDevansh, false, false, extendedBackendUrl, extendedApiKey, vaultIdExtended)
35545
+ getStrategySettingsVesuExtended("WBTC", "USDC", re7UsdcPrimeDevansh, false, false, extendedBackendUrl, extendedApiKey, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing)
34599
35546
  ];
34600
35547
  };
34601
- function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendUrl, extendedApiKey, vaultIdExtended) {
35548
+ function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses, isPreview = false, isLST, extendedBackendUrl, extendedApiKey, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing) {
34602
35549
  return {
34603
35550
  name: `Extended Test ${underlyingSymbol}`,
34604
35551
  description: getDescription2(lstSymbol, underlyingSymbol),
@@ -34606,7 +35553,7 @@ function getStrategySettingsVesuExtended(lstSymbol, underlyingSymbol, addresses,
34606
35553
  launchBlock: 0,
34607
35554
  type: "Other",
34608
35555
  depositTokens: [Global.getDefaultTokens().find((token) => token.symbol === underlyingSymbol)],
34609
- additionalInfo: getLooperSettings2(lstSymbol, underlyingSymbol, addresses, VesuPools.Re7USDCPrime, extendedBackendUrl, extendedApiKey, vaultIdExtended),
35556
+ additionalInfo: getLooperSettings2(lstSymbol, underlyingSymbol, addresses, VesuPools.Re7USDCPrime, extendedBackendUrl, extendedApiKey, vaultIdExtended, minimumExtendedMovementAmount, minimumVesuMovementAmount, minimumExtendedRetriesDelayForOrderStatus, minimumExtendedPriceDifferenceForSwapOpen, maximumExtendedPriceDifferenceForSwapClosing),
34610
35557
  risk: {
34611
35558
  riskFactor: _riskFactor3,
34612
35559
  netRisk: _riskFactor3.reduce((acc, curr) => acc + curr.value * curr.weight, 0) / _riskFactor3.reduce((acc, curr) => acc + curr.weight, 0),
@@ -38883,6 +39830,7 @@ var deployer_default = Deployer;
38883
39830
  PRICE_ROUTER,
38884
39831
  PasswordJsonCryptoUtil,
38885
39832
  PositionSide,
39833
+ PositionTypeAvnuExtended,
38886
39834
  Pragma,
38887
39835
  Pricer,
38888
39836
  PricerBase,