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

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.
@@ -55997,20 +55997,13 @@ ${JSON.stringify(data, null, 2)}`;
55997
55997
  async getDexPrice(baseToken, quoteToken, amount) {
55998
55998
  const lstTokenInfo = baseToken;
55999
55999
  const lstUnderlyingTokenInfo = quoteToken;
56000
- console.log("lstTokenInfo", lstTokenInfo);
56001
- console.log("lstUnderlyingTokenInfo", lstUnderlyingTokenInfo);
56002
- console.log("amount", amount);
56003
56000
  const quote = await this.getQuote(
56004
56001
  lstTokenInfo.address.address,
56005
56002
  lstUnderlyingTokenInfo.address.address,
56006
56003
  amount
56007
56004
  );
56008
- console.log("quote", quote);
56009
56005
  const outputAmount = Web3Number.fromWei(quote.total_calculated, lstUnderlyingTokenInfo.decimals);
56010
- console.log("outputAmount", outputAmount);
56011
- console.log("amount", amount);
56012
56006
  const price = outputAmount.toNumber() / amount.toNumber();
56013
- console.log("price", price);
56014
56007
  logger2.verbose(`${_EkuboQuoter.name}:: LST Dex Price: ${price}`);
56015
56008
  return price;
56016
56009
  }
@@ -56029,16 +56022,12 @@ ${JSON.stringify(data, null, 2)}`;
56029
56022
  // debt collateral
56030
56023
  async getSwapLimitAmount(fromToken, toToken, amount, max_slippage = 2e-3) {
56031
56024
  const isExactAmountIn = amount.greaterThanOrEqualTo(0);
56032
- console.log("isExactAmountIn", isExactAmountIn);
56033
56025
  logger2.verbose(`${_EkuboQuoter.name}::getSwapLimitAmount isExactAmountIn: ${isExactAmountIn}, fromToken: ${fromToken.symbol}, toToken: ${toToken.symbol}, amount: ${amount}`);
56034
56026
  const isYieldToken = this.tokenMarketData.isAPYSupported(toToken);
56035
56027
  console.log("isYieldToken", isYieldToken);
56036
56028
  const baseToken = isExactAmountIn ? toToken : fromToken;
56037
56029
  const quoteToken = isExactAmountIn ? fromToken : toToken;
56038
- console.log("baseToken", baseToken);
56039
- console.log("quoteToken", quoteToken);
56040
56030
  const dexPrice = await this.getDexPrice(baseToken, quoteToken, amount);
56041
- console.log("dexPrice", dexPrice);
56042
56031
  const trueExchangeRate = isYieldToken ? await this.tokenMarketData.getTruePrice(baseToken) : dexPrice;
56043
56032
  console.log("trueExchangeRate", trueExchangeRate);
56044
56033
  if (isExactAmountIn) {
@@ -92375,6 +92364,7 @@ spurious results.`);
92375
92364
  var AVNU_API = "https://starknet.api.avnu.fi/swap/v2/quotes";
92376
92365
  var USDC_TOKEN_DECIMALS = 6;
92377
92366
  var USDC_TOKEN_ADDRESS = "0x053C91253BC9682c04929cA02ED00b3E423f6710D2ee7e0D5EBB06F3eCF368A8";
92367
+ var BUFFER_USDC_IN_WITHDRAWAL = 5;
92378
92368
  var WBTC_TOKEN_ADDRESS = "0x3fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac";
92379
92369
  var WBTC_TOKEN_DECIMALS = 8;
92380
92370
  var MAINTENANCE_MARGIN = 0.01;
@@ -92466,8 +92456,7 @@ spurious results.`);
92466
92456
  logger2.error("error getting extended positions");
92467
92457
  return null;
92468
92458
  }
92469
- const extendedBTCExposure = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].size, WBTC_TOKEN_DECIMALS) : new Web3Number(0, WBTC_TOKEN_DECIMALS);
92470
- const extendedExposureUSD = extendedBTCExposure.multipliedBy(collateralPrice);
92459
+ const extendedExposureUSD = extendedPosition.length > 0 ? new Web3Number(extendedPosition[0].value, USDC_TOKEN_DECIMALS) : new Web3Number(0, USDC_TOKEN_DECIMALS);
92471
92460
  const vesuExposureUSD = collateralUnits.multipliedBy(collateralPrice);
92472
92461
  if (vesuExposureUSD.lessThan(0)) {
92473
92462
  return {
@@ -92485,9 +92474,14 @@ spurious results.`);
92485
92474
  vesu_leverage
92486
92475
  };
92487
92476
  }
92477
+ console.log("the vesu exposure usd is", vesuExposureUSD.toNumber());
92478
+ console.log("the extended exposure usd is", extendedExposureUSD.toNumber());
92479
+ console.log("the amount in usdc is", amountInUsdc.toNumber());
92480
+ console.log("the extended leverage is", extended_leverage);
92481
+ console.log("the vesu leverage is", vesu_leverage);
92488
92482
  const numerator1 = amountInUsdc.multipliedBy(extended_leverage);
92489
- const numerator2 = vesuExposureUSD.multipliedBy(vesu_leverage);
92490
- const numerator3 = extendedExposureUSD.multipliedBy(extended_leverage).multipliedBy(-1);
92483
+ const numerator2 = vesuExposureUSD;
92484
+ const numerator3 = extendedExposureUSD.multipliedBy(-1);
92491
92485
  const finalNumerator = numerator1.plus(numerator2).plus(numerator3);
92492
92486
  const denominator = extended_leverage + vesu_leverage;
92493
92487
  const vesuAmountInUSDC = finalNumerator.dividedBy(denominator);
@@ -92497,6 +92491,7 @@ spurious results.`);
92497
92491
  "the extended amount in usdc is",
92498
92492
  extendedAmountInUSDC.toNumber()
92499
92493
  );
92494
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
92500
92495
  return {
92501
92496
  vesu_amount: vesuAmountInUSDC,
92502
92497
  extended_amount: extendedAmountInUSDC,
@@ -92518,10 +92513,10 @@ spurious results.`);
92518
92513
  const extended_leverage_max = 1 / (MAINTENANCE_MARGIN + MAX_PRICE_DROP_PERCENTAGE);
92519
92514
  return Math.floor(extended_leverage_max);
92520
92515
  };
92521
- var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LTV_BTC_USDC, addedAmount, collateralPrice, isDeposit) => {
92516
+ var calculateDebtAmount = (collateralAmount, debtAmount, debtPrice, maxLtv = MAX_LIQUIDATION_RATIO, addedAmount, collateralPrice, isDeposit) => {
92522
92517
  try {
92523
- const marginAmount = addedAmount.multipliedBy(isDeposit ? 1 : -1);
92524
- const numerator1 = collateralAmount.plus(addedAmount).multipliedBy(collateralPrice).multipliedBy(maxLtv);
92518
+ const addedCollateral = addedAmount.multipliedBy(isDeposit ? 1 : -1);
92519
+ const numerator1 = collateralAmount.plus(addedCollateral).multipliedBy(collateralPrice).multipliedBy(maxLtv);
92525
92520
  const numerator2 = debtAmount.multipliedBy(debtPrice).multipliedBy(TARGET_HF);
92526
92521
  const denominator = TARGET_HF - maxLtv;
92527
92522
  const x_debt_usd = numerator1.minus(numerator2).dividedBy(denominator);
@@ -92556,7 +92551,6 @@ spurious results.`);
92556
92551
  const extendedHoldings = await client.getHoldings();
92557
92552
  const extended_leverage = calculateExtendedLevergae();
92558
92553
  const latestPosition = (await client.getPositions()).data.pop();
92559
- console.log("the latest position is", latestPosition, extendedHoldings);
92560
92554
  if (!extendedHoldings || !latestPosition) {
92561
92555
  logger2.error(`error getting extended position: extendedHoldings=${extendedHoldings}, latestPosition=${latestPosition}`);
92562
92556
  return null;
@@ -92937,7 +92931,7 @@ spurious results.`);
92937
92931
  this.config.debt.address.toBigInt(),
92938
92932
  this.config.vaultAllocator.toBigInt()
92939
92933
  ],
92940
- sanitizer: SIMPLE_SANITIZER_V2,
92934
+ sanitizer: isV2 ? SIMPLE_SANITIZER_V2 : SIMPLE_SANITIZER,
92941
92935
  // vmw = vesu multiply withdraw
92942
92936
  id: `vmw_${this.config.poolId.shortString()}_${collateral.symbol}_${debt.symbol}`
92943
92937
  },
@@ -93086,7 +93080,7 @@ spurious results.`);
93086
93080
  },
93087
93081
  // Vesu multiply call
93088
93082
  {
93089
- sanitizer: SIMPLE_SANITIZER_V2,
93083
+ sanitizer: isV2 ? SIMPLE_SANITIZER_V2 : SIMPLE_SANITIZER,
93090
93084
  call: {
93091
93085
  contractAddress: vesuMultiply,
93092
93086
  selector: hash_exports.getSelectorFromName("modify_lever"),
@@ -93174,19 +93168,13 @@ spurious results.`);
93174
93168
  leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
93175
93169
  const MAX_SLIPPAGE = 2e-3;
93176
93170
  if (debtAmount.greaterThan(0)) {
93177
- console.log("debtAmountInCollateralUnits", debtAmountInCollateralUnits.toNumber());
93178
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(debtToken, collateralToken, debtAmount, MAX_SLIPPAGE);
93179
- const anotherleverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
93180
- console.log("anotherleverSwapLimitAmount", anotherleverSwapLimitAmount, leverSwapLimitAmount);
93171
+ leverSwapLimitAmount = debtAmount.multipliedBy(1 + MAX_SLIPPAGE);
93181
93172
  } else if (debtAmount.lessThan(0)) {
93182
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(collateralToken, debtToken, debtAmountInCollateralUnits.multipliedBy(-1), MAX_SLIPPAGE);
93183
- const anotherleverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
93184
- console.log("anotherleverSwapLimitAmount", anotherleverSwapLimitAmount, leverSwapLimitAmount);
93173
+ leverSwapLimitAmount = debtAmount.abs().multipliedBy(1 - MAX_SLIPPAGE);
93185
93174
  } else {
93186
93175
  leverSwapLimitAmount = Web3Number.fromWei(0, this.config.debt.decimals);
93187
93176
  }
93188
93177
  await new Promise((resolve) => setTimeout(resolve, 1e4));
93189
- console.log("leverSwapLimitAmount", leverSwapLimitAmount);
93190
93178
  } else {
93191
93179
  throw new Error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
93192
93180
  }
@@ -93256,26 +93244,23 @@ spurious results.`);
93256
93244
  debtPrice.price,
93257
93245
  debtToken.decimals
93258
93246
  );
93259
- console.log("debtAmountToRepay", debtAmountToRepay);
93260
93247
  if (!debtAmountToRepay) {
93261
93248
  throw new Error("error calculating debt amount to repay");
93262
93249
  }
93263
93250
  const ekuboQuoter = new EkuboQuoter(this.config.networkConfig, this.config.pricer);
93264
93251
  const debtInDebtUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(debtPrice.price).multipliedBy(10 ** debtToken.decimals);
93265
- const debtInCollateralUnits = new Web3Number(debtAmountToRepay, debtToken.decimals).dividedBy(collateralPrice.price).multipliedBy(10 ** collateralToken.decimals);
93266
93252
  const swapQuote = await ekuboQuoter.getQuote(
93267
93253
  debtToken.address.address,
93268
93254
  collateralToken.address.address,
93269
93255
  debtInDebtUnits
93270
93256
  );
93271
93257
  const MAX_SLIPPAGE = 2e-3;
93272
- if (swapQuote.price_impact < 0.025) {
93273
- leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, debtToken, collateralToken);
93258
+ if (swapQuote.price_impact < 25e-4) {
93259
+ leverSwap = ekuboQuoter.getVesuMultiplyQuote(swapQuote, collateralToken, debtToken);
93274
93260
  } else {
93275
93261
  logger2.error(`VesuMultiplyAdapter: Price impact too high (${swapQuote.price_impact}), skipping swap`);
93276
93262
  }
93277
- const anotherLeverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(collateralToken, debtToken, debtInDebtUnits, MAX_SLIPPAGE);
93278
- leverSwapLimitAmount = await ekuboQuoter.getSwapLimitAmount(debtToken, collateralToken, debtInCollateralUnits, MAX_SLIPPAGE);
93263
+ leverSwapLimitAmount = new Web3Number(debtAmountToRepay, debtToken.decimals).abs().multipliedBy(1 + MAX_SLIPPAGE);
93279
93264
  const multiplyParams = await this.getLeverParams(false, params, leverSwap, leverSwapLimitAmount);
93280
93265
  const call = multiplyContract.populate("modify_lever", {
93281
93266
  modify_lever_params: this.formatMultiplyParams(false, multiplyParams)
@@ -93509,6 +93494,41 @@ spurious results.`);
93509
93494
  }
93510
93495
  ];
93511
93496
  }
93497
+ getSwapFromLegacyLeaf() {
93498
+ const leafConfigs = this._getSwapFromLegacyLeaf();
93499
+ const leaves = leafConfigs.map((config3) => {
93500
+ const { target, method, packedArguments, sanitizer, id } = config3;
93501
+ const leaf = this.constructSimpleLeafData({
93502
+ id,
93503
+ target,
93504
+ method,
93505
+ packedArguments
93506
+ }, sanitizer);
93507
+ return leaf;
93508
+ });
93509
+ return { leaves, callConstructor: this.getSwapFromLegacyCall.bind(this) };
93510
+ }
93511
+ _getSwapFromLegacyLeaf() {
93512
+ const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93513
+ return [
93514
+ {
93515
+ target: usdceToken.address,
93516
+ method: "approve",
93517
+ packedArguments: [
93518
+ AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt()
93519
+ ],
93520
+ id: `extendedswaplegacyapprove_${usdceToken.symbol}`,
93521
+ sanitizer: AVNU_LEGACY_SANITIZER
93522
+ },
93523
+ {
93524
+ target: AVNU_EXCHANGE_FOR_LEGACY_USDC,
93525
+ method: "swap_to_new",
93526
+ packedArguments: [],
93527
+ id: `extended_swap_to_new_${usdceToken.symbol}`,
93528
+ sanitizer: AVNU_LEGACY_SANITIZER
93529
+ }
93530
+ ];
93531
+ }
93512
93532
  _getWithdrawLeaf() {
93513
93533
  return [];
93514
93534
  }
@@ -93589,6 +93609,70 @@ spurious results.`);
93589
93609
  return [];
93590
93610
  }
93591
93611
  }
93612
+ getProofsForFromLegacySwap(tree) {
93613
+ let proofGroups = [];
93614
+ const ids = this.getSwapFromLegacyLeaf().leaves.map((l) => l.readableId);
93615
+ for (const [i, v] of tree.entries()) {
93616
+ if (ids.includes(v.readableId)) {
93617
+ proofGroups.push(tree.getProof(i));
93618
+ }
93619
+ }
93620
+ if (proofGroups.length != ids.length) {
93621
+ throw new Error(`Not all proofs found for IDs: ${ids.join(", ")}`);
93622
+ }
93623
+ return {
93624
+ proofs: proofGroups,
93625
+ callConstructor: this.getSwapFromLegacyCall.bind(this)
93626
+ };
93627
+ }
93628
+ async getSwapFromLegacyCall(params) {
93629
+ try {
93630
+ const usdcToken = this.config.supportedPositions[0].asset;
93631
+ const usdceToken = Global.getDefaultTokens().find((token) => token.symbol === "USDCe");
93632
+ const amount = uint256_exports.bnToUint256(params.amount.multipliedBy(10).toWei());
93633
+ const quotes = await this.config.avnuAdapter.getQuotesAvnu(
93634
+ usdceToken.address.toString(),
93635
+ usdcToken.address.toString(),
93636
+ params.amount.toNumber(),
93637
+ this.config.avnuAdapter.config.vaultAllocator.address.toString(),
93638
+ usdcToken.decimals,
93639
+ false
93640
+ );
93641
+ if (!quotes) {
93642
+ logger2.error("error getting quotes from avnu");
93643
+ return [];
93644
+ }
93645
+ const getCalldata = await this.config.avnuAdapter.getSwapCallData(quotes);
93646
+ const swapCallData = getCalldata[0];
93647
+ return [
93648
+ {
93649
+ sanitizer: AVNU_LEGACY_SANITIZER,
93650
+ call: {
93651
+ contractAddress: usdceToken.address,
93652
+ selector: hash_exports.getSelectorFromName("approve"),
93653
+ calldata: [
93654
+ AVNU_EXCHANGE_FOR_LEGACY_USDC.toBigInt(),
93655
+ toBigInt3(amount.low.toString()),
93656
+ // amount low
93657
+ toBigInt3(amount.high.toString())
93658
+ // amount high
93659
+ ]
93660
+ }
93661
+ },
93662
+ {
93663
+ sanitizer: AVNU_LEGACY_SANITIZER,
93664
+ call: {
93665
+ contractAddress: AVNU_EXCHANGE_FOR_LEGACY_USDC,
93666
+ selector: hash_exports.getSelectorFromName("swap_to_new"),
93667
+ calldata: swapCallData
93668
+ }
93669
+ }
93670
+ ];
93671
+ } catch (error2) {
93672
+ logger2.error(`Error creating Deposit Call: ${error2}`);
93673
+ return [];
93674
+ }
93675
+ }
93592
93676
  //Swap wbtc to usdc
93593
93677
  async getWithdrawCall(params) {
93594
93678
  try {
@@ -93606,10 +93690,10 @@ spurious results.`);
93606
93690
  if (!this.client) {
93607
93691
  throw new Error("Client not initialized");
93608
93692
  }
93609
- const withdrawalRequest = this.client.withdrawUSDC(amount.toString());
93610
- if ((await withdrawalRequest).status === "OK") {
93611
- console.log("Withdrawal request successful");
93612
- return true;
93693
+ const withdrawalRequest = await this.client.withdrawUSDC(amount.toFixed(2));
93694
+ if (withdrawalRequest.status === "OK") {
93695
+ const withdrawalStatus = await this.getDepositOrWithdrawalStatus(withdrawalRequest.data, "WITHDRAWAL" /* WITHDRAWAL */);
93696
+ return withdrawalStatus;
93613
93697
  }
93614
93698
  return false;
93615
93699
  } catch (error2) {
@@ -93790,7 +93874,7 @@ spurious results.`);
93790
93874
  logger2.error(`createShortOrder failed on attempt ${attempt}: ${err2.message}`);
93791
93875
  if (attempt < maxAttempts) {
93792
93876
  const backoff = 1200 * attempt;
93793
- console.log(`Retrying after ${backoff}ms...`);
93877
+ logger2.info(`Retrying after ${backoff}ms...`);
93794
93878
  await new Promise((resolve) => setTimeout(resolve, backoff));
93795
93879
  return this.createOrder(
93796
93880
  leverage,
@@ -93821,7 +93905,7 @@ spurious results.`);
93821
93905
  }
93822
93906
  return null;
93823
93907
  } catch (err2) {
93824
- console.log("Error opening short extended position", err2);
93908
+ logger2.error(`Error opening short extended position, ${err2}`);
93825
93909
  return null;
93826
93910
  }
93827
93911
  }
@@ -93831,17 +93915,16 @@ spurious results.`);
93831
93915
  operationsType: [operationsType],
93832
93916
  operationsStatus: ["COMPLETED" /* COMPLETED */]
93833
93917
  });
93834
- console.log("transferHistory", transferHistory);
93835
93918
  if (operationsType === "DEPOSIT" /* DEPOSIT */) {
93836
93919
  const myTransferStatus = transferHistory.data.find((operation) => operation.transactionHash === orderId);
93837
93920
  if (!myTransferStatus) {
93838
- return false;
93921
+ return true;
93839
93922
  }
93840
93923
  return true;
93841
93924
  } else {
93842
- const myTransferStatus = transferHistory.data.find((operation) => operation.id === orderId);
93925
+ const myTransferStatus = transferHistory.data.find((operation) => operation.id.toString() === orderId.toString());
93843
93926
  if (!myTransferStatus) {
93844
- return false;
93927
+ return true;
93845
93928
  }
93846
93929
  return true;
93847
93930
  }
@@ -97425,7 +97508,7 @@ spurious results.`);
97425
97508
  packedArguments: [
97426
97509
  fromToken.address.toBigInt(),
97427
97510
  //wbtc
97428
- fromToken.address.toBigInt(),
97511
+ toToken.address.toBigInt(),
97429
97512
  //usdc
97430
97513
  vaultAllocator.toBigInt()
97431
97514
  ],
@@ -97439,13 +97522,11 @@ spurious results.`);
97439
97522
  }
97440
97523
  async getDepositCall(params) {
97441
97524
  try {
97442
- console.log("params.amount", params.amount);
97443
97525
  const fromToken = this.config.supportedPositions[0].asset;
97444
97526
  const toToken = this.config.supportedPositions[1].asset;
97445
97527
  const vaultAllocator = ContractAddr.from(
97446
97528
  this.config.vaultAllocator.address
97447
97529
  );
97448
- console.log("vaultAllocator", vaultAllocator);
97449
97530
  const quote = await this.getQuotesAvnu(
97450
97531
  fromToken.address.toString(),
97451
97532
  toToken.address.toString(),
@@ -97501,7 +97582,6 @@ spurious results.`);
97501
97582
  const vaultAllocator = ContractAddr.from(
97502
97583
  this.config.vaultAllocator.address
97503
97584
  );
97504
- console.log("params.amount", params.amount);
97505
97585
  const quote = await this.getQuotesAvnu(
97506
97586
  fromToken.address.toString(),
97507
97587
  toToken.address.toString(),
@@ -97520,8 +97600,6 @@ spurious results.`);
97520
97600
  );
97521
97601
  const swapCallData = getCalldata[0];
97522
97602
  const amount = uint256_exports.bnToUint256(params.amount.toWei());
97523
- console.log("amount", amount);
97524
- console.log("swapCallData", swapCallData);
97525
97603
  return [
97526
97604
  {
97527
97605
  sanitizer: SIMPLE_SANITIZER,
@@ -97575,7 +97653,7 @@ spurious results.`);
97575
97653
  }
97576
97654
  throw new Error("Failed to fetch quote after retries");
97577
97655
  }
97578
- async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e4) {
97656
+ async getQuotesAvnu(from_token_address, to_token_address, amount, takerAddress, toTokenDecimals, usdcToBtc, maxIterations = 5, tolerance = 1e3) {
97579
97657
  try {
97580
97658
  const fromToken = this.config.supportedPositions[0].asset;
97581
97659
  const toToken = this.config.supportedPositions[1].asset;
@@ -97596,14 +97674,12 @@ spurious results.`);
97596
97674
  return dataObject2;
97597
97675
  }
97598
97676
  const btcPrice = await this.getPriceOfToken(toToken.address.toString());
97599
- console.log("btcPrice", btcPrice);
97600
97677
  if (!btcPrice) {
97601
97678
  logger2.error(`error getting btc price: ${btcPrice}`);
97602
97679
  return null;
97603
97680
  }
97604
97681
  const estimatedUsdcAmount = Math.floor(amount * btcPrice);
97605
97682
  const targetBtcBig = BigInt(returnFormattedAmount(amount, toTokenDecimals));
97606
- console.log("targetBtcBig", targetBtcBig);
97607
97683
  let low = BigInt(
97608
97684
  Math.floor(
97609
97685
  estimatedUsdcAmount * 10 ** fromToken.decimals * 0.9
@@ -97706,6 +97782,23 @@ spurious results.`);
97706
97782
  debtPrice
97707
97783
  };
97708
97784
  }
97785
+ async getUnusedBalanceUSDCE() {
97786
+ const usdceToken = Global.getDefaultTokens().find(
97787
+ (token) => token.symbol === "USDCe"
97788
+ );
97789
+ const balance = await new ERC20(this.config).balanceOf(
97790
+ usdceToken.address,
97791
+ WALLET_ADDRESS,
97792
+ usdceToken.decimals
97793
+ );
97794
+ const price = await this.pricer.getPrice(usdceToken.symbol);
97795
+ const usdValue = Number(balance.toFixed(usdceToken.decimals)) * price.price;
97796
+ return {
97797
+ tokenInfo: usdceToken,
97798
+ amount: balance,
97799
+ usdValue
97800
+ };
97801
+ }
97709
97802
  async getUnusedBalanceWBTC() {
97710
97803
  const collateralToken = this.metadata.additionalInfo.borrowable_assets[0];
97711
97804
  const balance = await new ERC20(this.config).balanceOf(
@@ -97751,22 +97844,30 @@ spurious results.`);
97751
97844
  }
97752
97845
  return extendedAdapter.adapter;
97753
97846
  }
97754
- async moveAssetsToVaultAllocator(amount) {
97847
+ async moveAssetsToVaultAllocator(amount, extendedAdapter) {
97755
97848
  try {
97756
- const usdcToken = Global.getDefaultTokens().find(
97757
- (token) => token.symbol === "USDC"
97849
+ const usdceToken = Global.getDefaultTokens().find(
97850
+ (token) => token.symbol === "USDCe"
97758
97851
  );
97759
97852
  const approveCall = new ERC20(this.config).approve(
97760
- usdcToken.address,
97853
+ usdceToken.address,
97761
97854
  this.metadata.additionalInfo.vaultAllocator,
97762
97855
  amount
97763
97856
  );
97764
97857
  const transferCall = new ERC20(this.config).transfer(
97765
- usdcToken.address,
97858
+ usdceToken.address,
97766
97859
  this.metadata.additionalInfo.vaultAllocator,
97767
97860
  amount
97768
97861
  );
97769
- return [approveCall, transferCall];
97862
+ const proofsInfo = extendedAdapter.getProofsForFromLegacySwap(
97863
+ this.getMerkleTree()
97864
+ );
97865
+ const proofGroups = proofsInfo.proofs;
97866
+ const call = this.getManageCall(
97867
+ proofGroups,
97868
+ await proofsInfo.callConstructor({ amount })
97869
+ );
97870
+ return [approveCall, transferCall, call];
97770
97871
  } catch (err2) {
97771
97872
  logger2.error(`error moving assets to vault allocator: ${err2}`);
97772
97873
  return [];
@@ -97878,11 +97979,9 @@ spurious results.`);
97878
97979
  );
97879
97980
  return calls;
97880
97981
  }
97881
- console.log("extendedAmount", extendedAmount);
97882
- console.log("vesuAmount", vesuAmount);
97883
97982
  if (extendedAmount.lessThan(0)) {
97884
97983
  try {
97885
- const extendedCalls = await this.moveAssets(
97984
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
97886
97985
  {
97887
97986
  to: Protocols.VAULT.name,
97888
97987
  from: Protocols.EXTENDED.name,
@@ -97891,14 +97990,18 @@ spurious results.`);
97891
97990
  extendedAdapter,
97892
97991
  vesuAdapter
97893
97992
  );
97894
- calls.push(...extendedCalls);
97993
+ if (extendedStatus) {
97994
+ calls.push(...extendedCalls);
97995
+ } else {
97996
+ return [];
97997
+ }
97895
97998
  } catch (err2) {
97896
97999
  logger2.error(`Failed moving assets to vault: ${err2}`);
97897
98000
  }
97898
98001
  }
97899
98002
  if (vesuAmount.lessThan(0)) {
97900
98003
  try {
97901
- const vesuCalls = await this.moveAssets(
98004
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
97902
98005
  {
97903
98006
  to: Protocols.EXTENDED.name,
97904
98007
  from: Protocols.VESU.name,
@@ -97908,6 +98011,9 @@ spurious results.`);
97908
98011
  vesuAdapter
97909
98012
  );
97910
98013
  calls.push(...vesuCalls);
98014
+ if (!vesuStatus) {
98015
+ return [];
98016
+ }
97911
98017
  } catch (err2) {
97912
98018
  logger2.error(`Failed moving assets to vault: ${err2}`);
97913
98019
  }
@@ -97919,15 +98025,15 @@ spurious results.`);
97919
98025
  }
97920
98026
  const usdcAmountInWallet = (await this.getUnusedBalance()).amount;
97921
98027
  const usdcAmountOnExtended = parseFloat(
97922
- extendedHoldings.availableForWithdrawal
98028
+ extendedHoldings.availableForTrade
97923
98029
  );
97924
- if (extendedAmount.minus(usdcAmountOnExtended).greaterThan(0)) {
98030
+ if (extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended).greaterThan(0)) {
97925
98031
  try {
97926
- const extendedCalls = await this.moveAssets(
98032
+ const { calls: extendedCalls } = await this.moveAssets(
97927
98033
  {
97928
98034
  to: Protocols.EXTENDED.name,
97929
98035
  from: Protocols.VAULT.name,
97930
- amount: extendedAmount.minus(usdcAmountOnExtended)
98036
+ amount: extendedAmount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcAmountOnExtended)
97931
98037
  },
97932
98038
  extendedAdapter,
97933
98039
  vesuAdapter
@@ -97939,15 +98045,18 @@ spurious results.`);
97939
98045
  }
97940
98046
  if (vesuAmount.minus(usdcAmountInWallet).greaterThan(0)) {
97941
98047
  try {
97942
- const vesuCalls = await this.moveAssets(
98048
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
97943
98049
  {
97944
- to: Protocols.VESU.name,
98050
+ to: Protocols.VAULT.name,
97945
98051
  from: Protocols.EXTENDED.name,
97946
98052
  amount: vesuAmount.minus(usdcAmountInWallet)
97947
98053
  },
97948
98054
  extendedAdapter,
97949
98055
  vesuAdapter
97950
98056
  );
98057
+ if (!vesuStatus) {
98058
+ return [];
98059
+ }
97951
98060
  calls.push(...vesuCalls);
97952
98061
  } catch (err2) {
97953
98062
  logger2.error(`Failed moving assets to vault: ${err2}`);
@@ -97964,9 +98073,12 @@ spurious results.`);
97964
98073
  const avnuAdapter = await this.getAvnuAdapter();
97965
98074
  if (!avnuAdapter) {
97966
98075
  logger2.error(`avnu adapter not found: ${avnuAdapter}`);
97967
- return [];
98076
+ return {
98077
+ calls: [],
98078
+ status: false
98079
+ };
97968
98080
  }
97969
- logger2.info("moveAssets params", params);
98081
+ logger2.info(`moveAssets params, ${JSON.stringify(params)}`);
97970
98082
  const collateralToken = vesuAdapter.config.supportedPositions[0].asset;
97971
98083
  const {
97972
98084
  collateralPrice
@@ -97983,18 +98095,67 @@ spurious results.`);
97983
98095
  await proofsInfo.callConstructor({ amount: params.amount })
97984
98096
  );
97985
98097
  calls.push(call);
97986
- return calls;
98098
+ return {
98099
+ calls: [call],
98100
+ status: true
98101
+ };
97987
98102
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.EXTENDED.name) {
98103
+ const extendedLeverage = calculateExtendedLevergae();
98104
+ const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98105
+ if (!extendedHoldings) {
98106
+ logger2.error(`error getting extended holdings: ${extendedHoldings}`);
98107
+ return {
98108
+ calls: [],
98109
+ status: false
98110
+ };
98111
+ }
98112
+ const extendedHoldingAmount = new Web3Number(
98113
+ extendedHoldings.availableForWithdrawal,
98114
+ USDC_TOKEN_DECIMALS
98115
+ );
98116
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets extendedHoldingAmount: ${extendedHoldingAmount.toNumber()}`);
98117
+ if (params.amount.abs().greaterThan(extendedHoldingAmount)) {
98118
+ const leftAmountAfterWithdrawalAmountInAccount = params.amount.abs().minus(extendedHoldingAmount);
98119
+ logger2.info(`${_VesuExtendedMultiplierStrategy.name}::moveAssets leftAmountAfterWithdrawalAmountInAccount: ${leftAmountAfterWithdrawalAmountInAccount.toNumber()}`);
98120
+ const btcAmount = leftAmountAfterWithdrawalAmountInAccount.dividedBy(collateralPrice.price);
98121
+ const openLongPosition = btcAmount.multipliedBy(3).greaterThan(MINIMUM_EXTENDED_POSITION_SIZE) ? await extendedAdapter.createOrder(
98122
+ extendedLeverage.toString(),
98123
+ btcAmount.toNumber(),
98124
+ "BUY" /* BUY */
98125
+ ) : await extendedAdapter.createOrder(
98126
+ extendedLeverage.toString(),
98127
+ 35e-6,
98128
+ // just in case amount falls short then we need to create a withdrawal
98129
+ "BUY" /* BUY */
98130
+ );
98131
+ if (!openLongPosition) {
98132
+ logger2.error(`error opening long position: ${openLongPosition}`);
98133
+ return {
98134
+ calls: [],
98135
+ status: false
98136
+ };
98137
+ }
98138
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
98139
+ }
97988
98140
  const withdrawalFromExtended = await extendedAdapter.withdrawFromExtended(params.amount);
97989
98141
  if (withdrawalFromExtended) {
97990
- const calls = await this.moveAssetsToVaultAllocator(params.amount);
98142
+ const extendedHoldings2 = await extendedAdapter.getExtendedDepositAmount();
98143
+ logger2.info(`extendedHoldings after withdrawal ${extendedHoldings2}`);
98144
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
98145
+ const calls = await this.moveAssetsToVaultAllocator(params.amount, extendedAdapter);
97991
98146
  if (calls.length > 0) {
97992
- return calls;
98147
+ return {
98148
+ calls,
98149
+ status: true
98150
+ };
97993
98151
  }
97994
98152
  } else {
97995
98153
  logger2.error("withdrawal from extended failed");
98154
+ return {
98155
+ calls: [],
98156
+ status: false
98157
+ };
97996
98158
  }
97997
- return [];
97998
98159
  } else if (params.to === Protocols.VAULT.name && params.from === Protocols.VESU.name) {
97999
98160
  const vesuAmountInBTC = new Web3Number(
98000
98161
  params.amount.dividedBy(collateralPrice.price).toNumber(),
@@ -98015,7 +98176,10 @@ spurious results.`);
98015
98176
  await swapProofsInfo.callConstructor({ amount: vesuAmountInBTC })
98016
98177
  );
98017
98178
  calls.push(swapCall);
98018
- return calls;
98179
+ return {
98180
+ calls,
98181
+ status: true
98182
+ };
98019
98183
  } else if (params.to === Protocols.EXTENDED.name && params.from === Protocols.VESU.name) {
98020
98184
  const vesuAmountInBTC = new Web3Number(
98021
98185
  params.amount.dividedBy(collateralPrice.price).toNumber(),
@@ -98046,13 +98210,21 @@ spurious results.`);
98046
98210
  await proofsInfoDeposit.callConstructor({ amount: params.amount })
98047
98211
  );
98048
98212
  calls.push(callDeposit);
98049
- return calls;
98213
+ return {
98214
+ calls,
98215
+ status: true
98216
+ };
98050
98217
  }
98051
- console.warn("moveAssets received unsupported route:", params);
98052
- return [];
98218
+ return {
98219
+ calls: [],
98220
+ status: false
98221
+ };
98053
98222
  } catch (err2) {
98054
98223
  logger2.error(`error moving assets: ${err2}`);
98055
- return [];
98224
+ return {
98225
+ calls: [],
98226
+ status: false
98227
+ };
98056
98228
  }
98057
98229
  }
98058
98230
  async handleDeposit() {
@@ -98089,6 +98261,7 @@ spurious results.`);
98089
98261
  };
98090
98262
  }
98091
98263
  const extendedPositionValue = position.length > 0 ? parseFloat(position[0].value) : 0;
98264
+ const BUFFER_AMOUNT_IN_AVAILABLE_FOR_TRADE = BUFFER_USDC_IN_WITHDRAWAL;
98092
98265
  const extendedHoldings = await extendedAdapter.getExtendedDepositAmount();
98093
98266
  if (!extendedHoldings) {
98094
98267
  logger2.error(`error getting extended holdings: ${extendedHoldings}`);
@@ -98098,7 +98271,7 @@ spurious results.`);
98098
98271
  };
98099
98272
  }
98100
98273
  const extendedHoldingAmount = new Web3Number(
98101
- extendedHoldings.availableForWithdrawal,
98274
+ extendedHoldings.availableForTrade,
98102
98275
  USDC_TOKEN_DECIMALS
98103
98276
  );
98104
98277
  const {
@@ -98107,12 +98280,11 @@ spurious results.`);
98107
98280
  const { collateralPrice } = await this.getAssetPrices();
98108
98281
  const { vesuAmountInBTC, extendedAmountInBTC } = calculateVesUPositionSizeGivenExtended(
98109
98282
  extendedPositionValue,
98110
- extendedHoldingAmount,
98283
+ extendedHoldingAmount.minus(BUFFER_AMOUNT_IN_AVAILABLE_FOR_TRADE),
98111
98284
  collateralTokenAmount,
98112
98285
  collateralPrice.price
98113
98286
  );
98114
- console.log("vesuAmountInBTC", vesuAmountInBTC);
98115
- console.log("extendedAmountInBTC", extendedAmountInBTC);
98287
+ logger2.info(`vesuAmountInBTC ${vesuAmountInBTC}, extendedAmountInBTC ${extendedAmountInBTC}`);
98116
98288
  let calls = [];
98117
98289
  if (vesuAmountInBTC.greaterThan(MINIMUM_EXTENDED_POSITION_SIZE)) {
98118
98290
  const proofsInfo = vesuAdapter.getProofs(true, this.getMerkleTree());
@@ -98125,7 +98297,6 @@ spurious results.`);
98125
98297
  );
98126
98298
  const { amount: wbtcAmountInVaultAllocator } = await this.getUnusedBalanceWBTC();
98127
98299
  if (wbtcAmountInVaultAllocator.lessThan(vesuAmountInBTC)) {
98128
- console.log("error wbtc amount in vault allocator is less than vesu amount in btc", wbtcAmountInVaultAllocator, vesuAmountInBTC);
98129
98300
  const swapProofsInfo = avnuAdapter.getProofs(true, this.getMerkleTree());
98130
98301
  const swapProofGroups = swapProofsInfo.proofs;
98131
98302
  const swapCall = this.getManageCall(
@@ -98169,7 +98340,7 @@ spurious results.`);
98169
98340
  bid
98170
98341
  } = await extendedAdapter.fetchOrderBookBTCUSDC();
98171
98342
  const price = ask.plus(bid).dividedBy(2);
98172
- const btcToken = vesuAdapter.config.supportedPositions[1].asset;
98343
+ const btcToken = vesuAdapter.config.supportedPositions[0].asset;
98173
98344
  const btcPriceAvnu = await avnuAdapter.getPriceOfToken(btcToken.address.toString());
98174
98345
  if (!btcPriceAvnu) {
98175
98346
  logger2.error(`error getting btc price avnu: ${btcPriceAvnu}`);
@@ -98185,43 +98356,65 @@ spurious results.`);
98185
98356
  async handleWithdraw(amount) {
98186
98357
  try {
98187
98358
  const usdcBalanceVaultAllocator = await this.getUnusedBalance();
98188
- const usdcBalanceDifference = amount.minus(usdcBalanceVaultAllocator.usdValue);
98359
+ const usdcBalanceDifference = amount.plus(BUFFER_USDC_IN_WITHDRAWAL).minus(usdcBalanceVaultAllocator.usdValue);
98189
98360
  logger2.info(`usdcBalanceDifference, ${usdcBalanceDifference.toNumber()}`);
98361
+ let calls = [];
98362
+ let status = true;
98190
98363
  if (usdcBalanceDifference.lessThan(0)) {
98191
- const withdrawCall = await this.getBringLiquidityCall({
98192
- amount
98364
+ const withdrawCall2 = await this.getBringLiquidityCall({
98365
+ amount: usdcBalanceVaultAllocator.amount
98193
98366
  });
98194
- logger2.info("withdraw call", withdrawCall);
98195
- return [withdrawCall];
98367
+ logger2.info("withdraw call", withdrawCall2);
98368
+ calls.push(withdrawCall2);
98369
+ return {
98370
+ calls,
98371
+ status: true
98372
+ };
98196
98373
  }
98197
98374
  const vesuAdapter = await this.getVesuAdapter();
98198
98375
  const extendedAdapter = await this.getExtendedAdapter();
98199
98376
  if (!vesuAdapter || !extendedAdapter || !extendedAdapter.client) {
98377
+ status = false;
98200
98378
  logger2.error(
98201
98379
  `vesu or extended adapter not found: vesuAdapter=${vesuAdapter}, extendedAdapter=${extendedAdapter}`
98202
98380
  );
98203
- return [];
98381
+ return {
98382
+ calls,
98383
+ status
98384
+ };
98204
98385
  }
98205
98386
  const { collateralTokenAmount } = await vesuAdapter.vesuAdapter.getAssetPrices();
98206
98387
  const {
98207
98388
  collateralPrice
98208
98389
  } = await this.getAssetPrices();
98209
98390
  const extendedPositon = await extendedAdapter.getAllOpenPositions();
98391
+ if (!extendedPositon) {
98392
+ status = false;
98393
+ logger2.error("error getting extended position", extendedPositon);
98394
+ return {
98395
+ calls,
98396
+ status
98397
+ };
98398
+ }
98210
98399
  const amountDistributionForWithdrawal = await calculateAmountDistributionForWithdrawal(
98211
- amount,
98400
+ usdcBalanceDifference,
98212
98401
  collateralPrice.price,
98213
98402
  collateralTokenAmount,
98214
98403
  extendedPositon
98215
98404
  );
98216
98405
  if (!amountDistributionForWithdrawal) {
98406
+ status = false;
98217
98407
  logger2.error(
98218
98408
  `error calculating amount distribution for withdrawal: ${amountDistributionForWithdrawal}`
98219
98409
  );
98220
- return [];
98410
+ return {
98411
+ calls,
98412
+ status
98413
+ };
98221
98414
  }
98222
98415
  const { vesu_amount, extended_amount } = amountDistributionForWithdrawal;
98223
- if (vesu_amount.greaterThan(0)) {
98224
- const result2 = await this.moveAssets(
98416
+ if (status && vesu_amount.greaterThan(0)) {
98417
+ const { calls: vesuCalls, status: vesuStatus } = await this.moveAssets(
98225
98418
  {
98226
98419
  amount: vesu_amount,
98227
98420
  from: Protocols.VESU.name,
@@ -98230,10 +98423,11 @@ spurious results.`);
98230
98423
  extendedAdapter,
98231
98424
  vesuAdapter
98232
98425
  );
98233
- return result2;
98426
+ status = vesuStatus;
98427
+ calls.push(...vesuCalls);
98234
98428
  }
98235
- if (extended_amount.greaterThan(0)) {
98236
- const result2 = await this.moveAssets(
98429
+ if (status && extended_amount.greaterThan(0)) {
98430
+ const { calls: extendedCalls, status: extendedStatus } = await this.moveAssets(
98237
98431
  {
98238
98432
  amount: extended_amount,
98239
98433
  from: Protocols.EXTENDED.name,
@@ -98242,12 +98436,32 @@ spurious results.`);
98242
98436
  extendedAdapter,
98243
98437
  vesuAdapter
98244
98438
  );
98245
- return result2;
98439
+ status = extendedStatus;
98440
+ if (status) {
98441
+ calls.push(...extendedCalls);
98442
+ } else {
98443
+ logger2.error("error moving assets to vault: extendedStatus: ${extendedStatus}");
98444
+ return {
98445
+ calls: [],
98446
+ status
98447
+ };
98448
+ }
98246
98449
  }
98247
- return [];
98450
+ const withdrawCall = await this.getBringLiquidityCall({
98451
+ amount
98452
+ });
98453
+ logger2.info("withdraw call", withdrawCall);
98454
+ calls.push(withdrawCall);
98455
+ return {
98456
+ calls,
98457
+ status
98458
+ };
98248
98459
  } catch (err2) {
98249
98460
  logger2.error(`error handling withdrawal: ${err2}`);
98250
- return [];
98461
+ return {
98462
+ calls: [],
98463
+ status: false
98464
+ };
98251
98465
  }
98252
98466
  }
98253
98467
  async getAUM() {
@@ -98381,6 +98595,7 @@ spurious results.`);
98381
98595
  () => vesuMultiplyAdapter.getWithdrawLeaf()
98382
98596
  );
98383
98597
  vaultSettings.leafAdapters.push(() => extendedAdapter.getDepositLeaf());
98598
+ vaultSettings.leafAdapters.push(() => extendedAdapter.getSwapFromLegacyLeaf());
98384
98599
  vaultSettings.leafAdapters.push(() => avnuAdapter.getDepositLeaf());
98385
98600
  vaultSettings.leafAdapters.push(() => avnuAdapter.getWithdrawLeaf());
98386
98601
  vaultSettings.leafAdapters.push(