S Price: $0.06792 (+1.76%)
Gas: 55 Gwei

Contract

0xe2Dfa8E65571c578322B11fF6082584Ad90eC5E5

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
385664092025-07-15 5:46:02195 days ago1752558362  Contract Creation0 S
Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
SiloLib

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import "../../interfaces/IStrategy.sol";
import {IControllable} from "../../interfaces/IControllable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {ILeverageLendingStrategy} from "../../interfaces/ILeverageLendingStrategy.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IPriceReader} from "../../interfaces/IPriceReader.sol";
import {ISiloConfig} from "../../integrations/silo/ISiloConfig.sol";
import {ISiloLens} from "../../integrations/silo/ISiloLens.sol";
import {ISiloOracle} from "../../integrations/silo/ISiloOracle.sol";
import {ISilo} from "../../integrations/silo/ISilo.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {StrategyLib} from "./StrategyLib.sol";
import {LeverageLendingLib} from "./LeverageLendingLib.sol";
import {SupportsInterfaceWithLookupMock} from
    "../../../lib/openzeppelin-contracts/contracts/mocks/ERC165/ERC165InterfacesSupported.sol";

library SiloLib {
    using SafeERC20 for IERC20;

    /// @dev 100_00 is 1.0 or 100%
    uint public constant INTERNAL_PRECISION = 100_00;

    /// @notice Price impact tolerance. Denominator is 100_000.
    uint private constant PRICE_IMPACT_TOLERANCE = 1000;

    uint private constant MAX_COUNT_LEVERAGE_SEARCH_ITERATIONS = 20;

    uint private constant PRICE_IMPACT_DENOMINATOR = 100_000;

    uint private constant SEARCH_LEVERAGE_TOLERANCE = 1e16; // 0.01 tolerance scaled by 1e18

    //region ------------------------------------- Data types
    struct CollateralDebtState {
        uint collateralPrice;
        uint borrowAssetPrice;
        /// @notice Collateral in lending vault + collateral on the strategy balance, in USD
        uint totalCollateralUsd;
        uint borrowAssetUsd;
        uint collateralBalance;
        /// @notice Amount of collateral in the lending vault
        uint collateralAmount;
        uint debtAmount;
        bool trusted;
    }

    struct StateBeforeWithdraw {
        uint collateralBalanceStrategy;
        uint valueWas;
        uint ltv;
        uint maxLtv;
        uint maxLeverage;
        uint targetLeverage;
        uint collateralAmountToWithdraw;
        uint withdrawParam0;
        uint withdrawParam1;
        uint withdrawParam2;
        uint priceCtoB;
    }

    /// @notice Defines the configuration parameters for leverage calculation.
    struct LeverageCalcParams {
        /// @notice Amount of collateral to withdraw (in USD).
        uint xWithdrawAmount;
        /// @notice Current collateral in the user's strategy (in USD).
        uint currentCollateralAmount;
        /// @notice Current debt (in USD).
        uint currentDebtAmount;
        /// @notice Initial balance of collateral asset available, in USD.
        uint initialBalanceC;
        /// @notice Swap efficiency factor (0...1], scaled by `scale` (e.g., 0.9998 is 0.9998 * scale).
        uint alphaScaled;
        /// @notice Flash loan fee rate, scaled by `scale` (e.g., for a 0.2% fee, the rate is 0.002, which would be passed as 2e15 if scale is 1e18).
        uint betaRateScaled;
    }

    //endregion ------------------------------------- Data types

    function receiveFlashLoan(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        address token,
        uint amount,
        uint feeAmount
    ) external {
        address flashLoanVault = _getFlashLoanAddress($, token);
        if (msg.sender != flashLoanVault) {
            revert IControllable.IncorrectMsgSender();
        }

        if ($.tempAction == ILeverageLendingStrategy.CurrentAction.Deposit) {
            //  flash amount is collateral
            // token is collateral asset
            uint tempBorrowAmount = $.tempBorrowAmount;

            // supply
            ISilo($.lendingVault).deposit(amount, address(this), ISilo.CollateralType.Collateral);

            // borrow
            ISilo($.borrowingVault).borrow(tempBorrowAmount, address(this), address(this));

            // swap
            StrategyLib.swap(platform, $.borrowAsset, token, tempBorrowAmount);

            // pay flash loan
            IERC20(token).safeTransfer(flashLoanVault, amount + feeAmount);

            // supply remaining balance
            ISilo($.lendingVault).deposit(StrategyLib.balance(token), address(this), ISilo.CollateralType.Collateral);

            // reset temp vars
            $.tempBorrowAmount = 0;
        }

        if ($.tempAction == ILeverageLendingStrategy.CurrentAction.Withdraw) {
            // flash is in borrow asset
            // token is borrow asset
            address collateralAsset = $.collateralAsset;
            uint tempCollateralAmount = $.tempCollateralAmount;

            // repay debt
            ISilo($.borrowingVault).repay(amount, address(this));

            // withdraw
            {
                address lendingVault = $.lendingVault;
                uint collateralAmountTotal = totalCollateral(lendingVault);
                collateralAmountTotal -= collateralAmountTotal / 1000;

                ISilo(lendingVault).withdraw(
                    Math.min(tempCollateralAmount, collateralAmountTotal),
                    address(this),
                    address(this),
                    ISilo.CollateralType.Collateral
                );
            }

            // swap
            StrategyLib.swap(
                platform, collateralAsset, token, Math.min(tempCollateralAmount, StrategyLib.balance(collateralAsset))
            );

            // pay flash loan
            IERC20(token).safeTransfer(flashLoanVault, amount + feeAmount);

            // swap unnecessary borrow asset
            StrategyLib.swap(platform, token, collateralAsset, StrategyLib.balance(token));

            // reset temp vars
            $.tempCollateralAmount = 0;
        }

        if ($.tempAction == ILeverageLendingStrategy.CurrentAction.DecreaseLtv) {
            // tokens[0] is collateral asset
            address lendingVault = $.lendingVault;

            // swap
            StrategyLib.swap(platform, token, $.borrowAsset, amount);

            // repay
            ISilo($.borrowingVault).repay(StrategyLib.balance($.borrowAsset), address(this));

            // withdraw amount to pay flash loan
            uint toWithdraw = amount + feeAmount - StrategyLib.balance(token);
            ISilo(lendingVault).withdraw(toWithdraw, address(this), address(this), ISilo.CollateralType.Collateral);

            // pay flash loan
            IERC20(token).safeTransfer(flashLoanVault, amount + feeAmount);
        }

        if ($.tempAction == ILeverageLendingStrategy.CurrentAction.IncreaseLtv) {
            // tokens[0] is collateral asset
            uint tempBorrowAmount = $.tempBorrowAmount;
            address lendingVault = $.lendingVault;

            // supply
            ISilo($.lendingVault).deposit(amount, address(this), ISilo.CollateralType.Collateral);

            // borrow
            ISilo($.borrowingVault).borrow(tempBorrowAmount, address(this), address(this));

            // swap
            StrategyLib.swap(platform, $.borrowAsset, token, tempBorrowAmount, PRICE_IMPACT_TOLERANCE);

            // withdraw or supply if need
            uint bal = StrategyLib.balance(token);
            uint remaining = bal < (amount + feeAmount) ? amount + feeAmount - bal : 0;
            if (remaining != 0) {
                ISilo(lendingVault).withdraw(remaining, address(this), address(this), ISilo.CollateralType.Collateral);
            } else {
                uint toSupply = bal - (amount + feeAmount);
                ISilo($.lendingVault).deposit(toSupply, address(this), ISilo.CollateralType.Collateral);
            }

            // pay flash loan
            IERC20(token).safeTransfer(flashLoanVault, amount + feeAmount);

            // reset temp vars
            $.tempBorrowAmount = 0;
        }

        (uint ltv,, uint leverage,,,) = health(platform, $);
        emit ILeverageLendingStrategy.LeverageLendingHealth(ltv, leverage);

        $.tempAction = ILeverageLendingStrategy.CurrentAction.None;
    }

    function health(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $
    )
        public
        view
        returns (
            uint ltv,
            uint maxLtv,
            uint leverage,
            uint collateralAmount,
            uint debtAmount,
            uint targetLeveragePercent
        )
    {
        address lendingVault = $.lendingVault;
        address collateralAsset = $.collateralAsset;

        ltv = ISiloLens($.helper).getLtv(lendingVault, address(this));
        ltv = ltv * INTERNAL_PRECISION / 1e18;

        collateralAmount = StrategyLib.balance(collateralAsset) + totalCollateral(lendingVault);
        debtAmount = totalDebt($.borrowingVault);

        IPriceReader priceReader = IPriceReader(IPlatform(platform).priceReader());
        (uint _realTvl,) = realTvl(platform, $);
        (uint collateralPrice,) = priceReader.getPrice(collateralAsset);
        uint collateralUsd = collateralAmount * collateralPrice / 10 ** IERC20Metadata(collateralAsset).decimals();
        leverage = collateralUsd * INTERNAL_PRECISION / _realTvl;

        targetLeveragePercent = $.targetLeveragePercent;

        (maxLtv,,) = getLtvData(lendingVault, targetLeveragePercent);
    }

    function rebalanceDebt(
        address platform,
        uint newLtv,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $
    ) external returns (uint resultLtv) {
        (uint ltv, uint maxLtv,, uint collateralAmount,,) = health(platform, $);

        ILeverageLendingStrategy.LeverageLendingAddresses memory v = getLeverageLendingAddresses($);

        uint tvlPricedInCollateralAsset = calcTotal(v);

        // here is the math that works:
        // collateral_value - debt_value = real_TVL
        // debt_value * PRECISION / collateral_value = LTV
        // ---
        // collateral_value = real_TVL * PRECISION / (PRECISION - LTV)

        uint newCollateralValue = tvlPricedInCollateralAsset * INTERNAL_PRECISION / (INTERNAL_PRECISION - newLtv);
        address[] memory flashAssets = new address[](1);
        flashAssets[0] = v.collateralAsset;
        uint[] memory flashAmounts = new uint[](1);

        if (newLtv < ltv) {
            $.tempAction = ILeverageLendingStrategy.CurrentAction.DecreaseLtv;

            // need decrease debt and collateral
            uint collateralDiff = collateralAmount - newCollateralValue;
            flashAmounts[0] = collateralDiff;
        } else {
            $.tempAction = ILeverageLendingStrategy.CurrentAction.IncreaseLtv;

            // need increase debt and collateral
            uint collateralDiff = newCollateralValue - collateralAmount;
            (uint priceCtoB,) = getPrices(v.lendingVault, v.borrowingVault);
            flashAmounts[0] = collateralDiff;
            $.tempBorrowAmount = (flashAmounts[0] * maxLtv / 1e18) * priceCtoB / 1e18 - 2;
        }

        LeverageLendingLib.requestFlashLoanExplicit(
            ILeverageLendingStrategy.FlashLoanKind($.flashLoanKind), $.flashLoanVault, flashAssets, flashAmounts
        );

        $.tempAction = ILeverageLendingStrategy.CurrentAction.None;
        (resultLtv,,,,,) = health(platform, $);
    }

    function realTvl(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $
    ) public view returns (uint tvl, bool trusted) {
        CollateralDebtState memory debtState =
            getDebtState(platform, $.lendingVault, $.collateralAsset, $.borrowAsset, $.borrowingVault);
        tvl = debtState.totalCollateralUsd - debtState.borrowAssetUsd;
        trusted = debtState.trusted;
    }

    function getDebtState(
        address platform,
        address lendingVault,
        address collateralAsset,
        address borrowAsset,
        address borrowingVault
    ) public view returns (CollateralDebtState memory data) {
        bool collateralPriceTrusted;
        bool borrowAssetPriceTrusted;

        IPriceReader priceReader = IPriceReader(IPlatform(platform).priceReader());

        data.collateralAmount = totalCollateral(lendingVault);
        data.collateralBalance = StrategyLib.balance(collateralAsset);
        (data.collateralPrice, collateralPriceTrusted) = priceReader.getPrice(collateralAsset);
        data.totalCollateralUsd = (data.collateralAmount + data.collateralBalance) * data.collateralPrice
            / 10 ** IERC20Metadata(collateralAsset).decimals();

        data.debtAmount = totalDebt(borrowingVault);
        (data.borrowAssetPrice, borrowAssetPriceTrusted) = priceReader.getPrice(borrowAsset);
        data.borrowAssetUsd = data.debtAmount * data.borrowAssetPrice / 10 ** IERC20Metadata(borrowAsset).decimals();

        data.trusted = collateralPriceTrusted && borrowAssetPriceTrusted;

        return data;
    }

    function getPrices(address lendVault, address debtVault) public view returns (uint priceCtoB, uint priceBtoC) {
        ISiloConfig siloConfig = ISiloConfig(ISilo(lendVault).config());
        ISiloConfig.ConfigData memory collateralConfig = siloConfig.getConfig(lendVault);
        address collateralOracle = collateralConfig.solvencyOracle;
        ISiloConfig.ConfigData memory borrowConfig = siloConfig.getConfig(debtVault);
        address borrowOracle = borrowConfig.solvencyOracle;
        if (collateralOracle != address(0) && borrowOracle == address(0)) {
            priceCtoB = ISiloOracle(collateralOracle).quote(
                10 ** IERC20Metadata(collateralConfig.token).decimals(), collateralConfig.token
            );
            priceBtoC = 1e18 * 1e18 / priceCtoB;
        } else if (collateralOracle == address(0) && borrowOracle != address(0)) {
            priceBtoC =
                ISiloOracle(borrowOracle).quote(10 ** IERC20Metadata(borrowConfig.token).decimals(), borrowConfig.token);
            priceCtoB = 1e18 * 1e18 / priceBtoC;
        } else {
            revert("Not implemented yet");
        }
    }

    /// @dev LTV data
    /// @return maxLtv Max LTV with 18 decimals
    /// @return maxLeverage Max leverage multiplier with 4 decimals
    /// @return targetLeverage Target leverage multiplier with 4 decimals
    function getLtvData(
        address lendingVault,
        uint targetLeveragePercent
    ) public view returns (uint maxLtv, uint maxLeverage, uint targetLeverage) {
        address configContract = ISilo(lendingVault).config();
        ISiloConfig.ConfigData memory config = ISiloConfig(configContract).getConfig(lendingVault);
        maxLtv = config.maxLtv;
        maxLeverage = 1e18 * INTERNAL_PRECISION / (1e18 - maxLtv);
        targetLeverage = maxLeverage * targetLeveragePercent / INTERNAL_PRECISION;
    }

    function calcTotal(ILeverageLendingStrategy.LeverageLendingAddresses memory v) public view returns (uint) {
        (, uint priceBtoC) = getPrices(v.lendingVault, v.borrowingVault);
        uint borrowedAmountPricedInCollateral = totalDebt(v.borrowingVault) * priceBtoC / 1e18;
        return totalCollateral(v.lendingVault) - borrowedAmountPricedInCollateral;
    }

    function totalCollateral(address lendingVault) public view returns (uint) {
        return IERC4626(lendingVault).convertToAssets(StrategyLib.balance(lendingVault));
    }

    function totalDebt(address borrowingVault) public view returns (uint) {
        return ISilo(borrowingVault).maxRepay(address(this));
    }

    //region ------------------------------------- Deposit
    function depositAssets(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        IStrategy.StrategyBaseStorage storage $base,
        address[] memory _assets,
        uint[] memory amounts
    ) external returns (uint value) {
        ILeverageLendingStrategy.LeverageLendingAddresses memory v = getLeverageLendingAddresses($);
        uint valueWas = StrategyLib.balance(_assets[0]) + calcTotal(v);
        _deposit($, v, _assets, amounts[0]);
        uint valueNow = StrategyLib.balance(_assets[0]) + calcTotal(v);

        if (valueNow > valueWas) {
            // deposit profit
            value = amounts[0] + (valueNow - valueWas);
        } else {
            // deposit loss
            value = amounts[0] - (valueWas - valueNow);
        }

        $base.total += value;
    }

    /// @param _assets [collateral asset]
    /// @param amountToDeposit Amount to deposit in collateral asset
    function _deposit(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v,
        address[] memory _assets,
        uint amountToDeposit
    ) internal {
        (uint maxLtv,, uint targetLeverage) = getLtvData(v.lendingVault, $.targetLeveragePercent);

        uint[] memory flashAmounts = new uint[](1);
        flashAmounts[0] = amountToDeposit * targetLeverage / INTERNAL_PRECISION;

        (uint priceCtoB,) = getPrices(v.lendingVault, v.borrowingVault);

        $.tempBorrowAmount = (flashAmounts[0] * maxLtv / 1e18) * priceCtoB / 1e18 - 2;
        $.tempAction = ILeverageLendingStrategy.CurrentAction.Deposit;
        LeverageLendingLib.requestFlashLoan($, _assets, flashAmounts);
    }
    //endregion ------------------------------------- Deposit

    //region ------------------------------------- Withdraw
    function withdrawAssets(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        IStrategy.StrategyBaseStorage storage $base,
        uint value,
        address receiver
    ) external returns (uint[] memory amountsOut) {
        ILeverageLendingStrategy.LeverageLendingAddresses memory v = getLeverageLendingAddresses($);
        StateBeforeWithdraw memory state = _getStateBeforeWithdraw(platform, $, v);

        // ---------------------- withdraw from the lending vault - only if amount on the balance is not enough
        if (value > state.collateralBalanceStrategy) {
            // it's too dangerous to ask value - state.collateralBalanceStrategy
            // because current balance is used in multiple places inside receiveFlashLoan
            // so we ask to withdraw full required amount
            withdrawFromLendingVault(platform, $, v, state, value);
        }

        // ---------------------- Transfer required amount to the user, update base.total
        uint bal = StrategyLib.balance(v.collateralAsset);
        uint valueNow = bal + calcTotal(v);

        amountsOut = new uint[](1);
        if (state.valueWas > valueNow) {
            amountsOut[0] = Math.min(value - (state.valueWas - valueNow), bal);
        } else {
            amountsOut[0] = Math.min(value + (valueNow - state.valueWas), bal);
        }

        if (receiver != address(this)) {
            IERC20(v.collateralAsset).safeTransfer(receiver, amountsOut[0]);
        }

        $base.total -= value;

        // ---------------------- Deposit the amount ~ value
        if (state.withdrawParam1 > INTERNAL_PRECISION) {
            _depositAfterWithdraw($, v, state.withdrawParam1, value);
        }
    }

    function _depositAfterWithdraw(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v,
        uint withdrawParam1,
        uint value
    ) internal {
        uint balance = StrategyLib.balance(v.collateralAsset);

        // workaround dust problems and error LessThenThreshold
        uint maxAmountToWithdraw = withdrawParam1 * value / INTERNAL_PRECISION;
        if (balance > maxAmountToWithdraw * 100 / INTERNAL_PRECISION) {
            address[] memory assets = new address[](1);
            assets[0] = v.collateralAsset;
            SiloLib._deposit($, v, assets, Math.min(maxAmountToWithdraw, balance));
        }
    }

    function withdrawFromLendingVault(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v,
        StateBeforeWithdraw memory state,
        uint value
    ) internal {
        (,, uint leverage,,,) = health(platform, $);

        CollateralDebtState memory debtState =
            getDebtState(platform, v.lendingVault, v.collateralAsset, v.borrowAsset, v.borrowingVault);

        if (0 == debtState.debtAmount) {
            // zero debt, positive collateral - we can just withdraw required amount
            uint amountToWithdraw = Math.min(
                value > debtState.collateralBalance ? value - debtState.collateralBalance : 0,
                debtState.collateralAmount
            );
            if (amountToWithdraw != 0) {
                ISilo(v.lendingVault).withdraw(
                    amountToWithdraw, address(this), address(this), ISilo.CollateralType.Collateral
                );
            }
        } else {
            // withdrawParam2 allows to disable withdraw through increasing ltv if leverage is near to target
            if (
                leverage >= state.targetLeverage * state.withdrawParam2 / INTERNAL_PRECISION
                    || !_withdrawThroughIncreasingLtv($, v, state, debtState, value, leverage)
            ) {
                _defaultWithdraw($, v, state, value);
            }
        }
    }

    /// @notice Default withdraw procedure (leverage is a bit decreased)
    function _defaultWithdraw(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v,
        StateBeforeWithdraw memory state,
        uint value
    ) internal {
        // repay debt and withdraw
        // we use maxLeverage and maxLtv, so result ltv will reduce
        uint collateralAmountToWithdraw = value * state.maxLeverage / INTERNAL_PRECISION;

        uint[] memory flashAmounts = new uint[](1);
        flashAmounts[0] = collateralAmountToWithdraw * state.maxLtv / 1e18 * state.priceCtoB * state.withdrawParam0
            * (10 ** IERC20Metadata(v.borrowAsset).decimals()) / 1e18 // priceCtoB has decimals 1e18
            / INTERNAL_PRECISION // withdrawParam0
            / (10 ** IERC20Metadata(v.collateralAsset).decimals());
        address[] memory flashAssets = new address[](1);
        flashAssets[0] = $.borrowAsset;

        address universalAddress1 = $.universalAddress1;

        $.tempCollateralAmount = collateralAmountToWithdraw;
        $.tempAction = ILeverageLendingStrategy.CurrentAction.Withdraw;
        LeverageLendingLib.requestFlashLoanExplicit(
            ILeverageLendingStrategy.FlashLoanKind($.flashLoanKind),
            universalAddress1 == address(0) ? $.flashLoanVault : universalAddress1,
            flashAssets,
            flashAmounts
        );
    }

    /// @param value Full amount of the collateral asset that the user is asking to withdraw
    function _withdrawThroughIncreasingLtv(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v,
        StateBeforeWithdraw memory state,
        CollateralDebtState memory debtState,
        uint value,
        uint leverage
    ) internal returns (bool) {
        // --------- Calculate new leverage after deposit {value} with target leverage and withdraw {value} on balance
        uint d = (10 ** IERC20Metadata(v.collateralAsset).decimals());
        LeverageCalcParams memory config = LeverageCalcParams({
            xWithdrawAmount: value * debtState.collateralPrice / d,
            currentCollateralAmount: debtState.totalCollateralUsd,
            currentDebtAmount: debtState.borrowAssetUsd,
            initialBalanceC: state.collateralBalanceStrategy * debtState.collateralPrice / d,
            alphaScaled: 1e18 * (PRICE_IMPACT_DENOMINATOR - PRICE_IMPACT_TOLERANCE) / PRICE_IMPACT_DENOMINATOR,
            betaRateScaled: 0 // assume no flash fee
        });

        int leverageNew = int(calculateNewLeverage(config, state.ltv, state.maxLtv));

        if (leverageNew <= 0 || uint(leverageNew) > state.targetLeverage || uint(leverageNew) < leverage) {
            return false; // use default withdraw
        }

        uint priceCtoB;
        (priceCtoB,) = getPrices(v.lendingVault, v.borrowingVault);

        // --------- Calculate required flash amount of collateral
        address[] memory flashAssets = new address[](1);
        flashAssets[0] = v.collateralAsset;
        uint[] memory flashAmounts = new uint[](1);
        flashAmounts[0] = value * uint(leverageNew) / INTERNAL_PRECISION;

        // --------- Increase ltv
        $.tempBorrowAmount = flashAmounts[0] * priceCtoB // no multiplication on ltv here
            * (10 ** IERC20Metadata(v.borrowAsset).decimals()) / (10 ** IERC20Metadata(v.collateralAsset).decimals()) / 1e18; // priceCtoB has decimals 18
        $.tempAction = ILeverageLendingStrategy.CurrentAction.IncreaseLtv;
        LeverageLendingLib.requestFlashLoan($, flashAssets, flashAmounts);

        // --------- Withdraw value from landing vault to the strategy balance
        ISilo(v.lendingVault).withdraw(value, address(this), address(this), ISilo.CollateralType.Collateral);

        return true;
    }

    function _getStateBeforeWithdraw(
        address platform,
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        ILeverageLendingStrategy.LeverageLendingAddresses memory v
    ) public view returns (StateBeforeWithdraw memory state) {
        state.collateralBalanceStrategy = StrategyLib.balance(v.collateralAsset);
        state.valueWas = state.collateralBalanceStrategy + calcTotal(v);
        (state.ltv,,,,,) = health(platform, $);
        (state.maxLtv, state.maxLeverage, state.targetLeverage) = getLtvData(v.lendingVault, $.targetLeveragePercent);
        (state.priceCtoB,) = getPrices(v.lendingVault, v.borrowingVault);
        state.withdrawParam0 = $.withdrawParam0;
        state.withdrawParam1 = $.withdrawParam1;
        state.withdrawParam2 = $.withdrawParam2;
        if (state.withdrawParam0 == 0) state.withdrawParam0 = 100_00;
        if (state.withdrawParam1 == 0) state.withdrawParam1 = 100_00;

        return state;
    }

    /// @notice Calculates equilibrium leverage using an iterative approach.
    /// All percentage/rate parameters (ltvScaled, alphaScaled, betaRateScaled) are expected to be scaled by the 'scale' constant.
    /// Amounts (xWithdrawAmount, currentCollateralAmount, etc.) are expected in USD.
    /// Leverage values are also handled as scaled integers.
    /// @param ltv Current value of LTV
    /// @param maxLtv Max allowed LTV
    /// @return resultLeverage The calculated result leverage, decimals INTERNAL_PRECISION
    function calculateNewLeverage(
        LeverageCalcParams memory config,
        uint ltv,
        uint maxLtv
    ) public pure returns (uint resultLeverage) {
        uint optimalLeverage = _findEquilibriumLeverage(
            config,
            1e18 * 1e18 / (1e18 - ltv), // current leverage is the low bound for the leverage search range
            1e18 * 1e18 / (1e18 - maxLtv), // upper bound for the leverage search range
            SEARCH_LEVERAGE_TOLERANCE
        );

        resultLeverage =
            optimalLeverage == 0 ? 0 : INTERNAL_PRECISION * _fullLeverageCalculation(config, optimalLeverage) / 1e18;
    }

    /// @dev Internal function to calculate resulting leverage for a given `leverageNewScaled`.
    /// Mirrors the corrected Python `full_leverage_calculation`.
    /// @param config The configuration parameters.
    /// @param leverageNewScaled The guessed new leverage, scaled 1e18
    /// @return resultLeverageScaled The calculated resulting leverage, scaled by 1e18
    function _fullLeverageCalculation(
        LeverageCalcParams memory config,
        uint leverageNewScaled
    ) internal pure returns (uint resultLeverageScaled) {
        if (leverageNewScaled == 0) {
            return 0;
        }
        // F = L_new * config.xWithdrawAmount (collateral amount borrowed via flash loan)
        uint fAmount = (leverageNewScaled * config.xWithdrawAmount) / 1e18;

        // New collateral amount after applying all operations
        // C_new = CC + F + C_delta - X, C_delta = C1 - F1 (can be negative)
        // C1 = config.initialBalanceC + F * ltv * alpha (collateral balance on hand after swap)
        // F1 = total to return for flash loan = F + F_delta, where F_delta = beta_rate * F (flash fee)
        int cNew = int(config.currentCollateralAmount) + int(fAmount)
            + (
                int(config.initialBalanceC + fAmount * config.alphaScaled / 1e18)
                    - int(fAmount + (fAmount * config.betaRateScaled) / 1e18)
            ) - int(config.xWithdrawAmount);

        if (cNew < 0) {
            return 0; // Resulting cNewAmount would be negative
        }

        // New debt = initial debt + F * ltv
        uint dNewAmount = config.currentDebtAmount + fAmount;

        // Check for insolvency: cNewAmount must be greater than dNewAmount for positive, defined leverage.
        if (uint(cNew) <= dNewAmount) {
            return 0; // Leverage is undefined, zero, or not positive
        }

        // resultLeverageScaled = new collateral / (new collateral - new debt)
        return (uint(cNew) * 1e18) / (uint(cNew) - dNewAmount);
    }

    /// @notice Finds the equilibrium leverage using an iterative binary search approach.
    /// @param config The configuration parameters.
    /// @param lowScaled The lower bound for the leverage search range, decimals 18
    /// @param highScaled The upper bound for the leverage search range, decimals 18
    /// @param toleranceScaled The tolerance for convergence, scaled by `scale` (e.g., for 0.01 tolerance, pass 0.01 * scale = 1e16).
    /// @return equilibriumLeverage The equilibrium leverage found. Decimals are equal to the decimals of low/high.
    /// Returns 0 if not converged or an error occurred during calculation.
    function _findEquilibriumLeverage(
        LeverageCalcParams memory config,
        uint lowScaled,
        uint highScaled,
        uint toleranceScaled
    ) internal pure returns (uint equilibriumLeverage) {
        // Binary search boundaries
        uint iterCount = 0;

        // Binary search loop
        while (iterCount < MAX_COUNT_LEVERAGE_SEARCH_ITERATIONS) {
            uint mid = (lowScaled + highScaled) / 2;

            // Call the leverage calculation function
            uint resLeverageScaled = _fullLeverageCalculation(config, mid);

            // Check if we've converged
            uint delta = (resLeverageScaled > mid ? resLeverageScaled - mid : mid - resLeverageScaled);
            if (delta < toleranceScaled) {
                return mid;
            } else if (resLeverageScaled > mid) {
                lowScaled = mid;
            } else {
                highScaled = mid;
            }

            iterCount++;
        }

        return 0;
    }

    //endregion ------------------------------------- Withdraw

    //region ------------------------------------- Internal
    function getLeverageLendingAddresses(ILeverageLendingStrategy.LeverageLendingBaseStorage storage $)
        internal
        view
        returns (ILeverageLendingStrategy.LeverageLendingAddresses memory)
    {
        return ILeverageLendingStrategy.LeverageLendingAddresses({
            collateralAsset: $.collateralAsset,
            borrowAsset: $.borrowAsset,
            lendingVault: $.lendingVault,
            borrowingVault: $.borrowingVault
        });
    }

    function _getFlashLoanAddress(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        address token
    ) internal view returns (address) {
        address universalAddress1 = $.universalAddress1;
        return token == $.borrowAsset
            ? universalAddress1 == address(0) ? $.flashLoanVault : universalAddress1
            : $.flashLoanVault;
    }

    //endregion ------------------------------------- Internal
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/// @dev Core interface of strategy logic
interface IStrategy is IERC165 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event HardWork(
        uint apr, uint compoundApr, uint earned, uint tvl, uint duration, uint sharePrice, uint[] assetPrices
    );
    event ExtractFees(
        uint vaultManagerReceiverFee,
        uint strategyLogicReceiverFee,
        uint ecosystemRevenueReceiverFee,
        uint multisigReceiverFee
    );

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error NotReadyForHardWork();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.StrategyBase
    struct StrategyBaseStorage {
        /// @inheritdoc IStrategy
        address vault;
        /// @inheritdoc IStrategy
        uint total;
        /// @inheritdoc IStrategy
        uint lastHardWork;
        /// @inheritdoc IStrategy
        uint lastApr;
        /// @inheritdoc IStrategy
        uint lastAprCompound;
        /// @inheritdoc IStrategy
        address[] _assets;
        /// @inheritdoc IStrategy
        address _underlying;
        string _id;
        uint _exchangeAssetIndex;
        uint customPriceImpactTolerance;
        /// @inheritdoc IStrategy
        uint fuseOn;
    }

    enum FuseMode {
        FUSE_OFF_0,
        /// @notice Fuse mode is on (emergency stop was called).
        /// All assets were transferred from the underlying pool to the strategy balance, no deposits are allowed.
        FUSE_ON_1
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Strategy logic string ID
    function strategyLogicId() external view returns (string memory);

    /// @dev Extra data
    /// @return 0-2 bytes - strategy color
    ///         3-5 bytes - strategy background color
    ///         6-31 bytes - free
    function extra() external view returns (bytes32);

    /// @dev Types of vault that supported by strategy implementation
    /// @return types Vault type ID strings
    function supportedVaultTypes() external view returns (string[] memory types);

    /// @dev Linked vault address
    function vault() external view returns (address);

    /// @dev Final assets that strategy invests
    function assets() external view returns (address[] memory);

    /// @notice Final assets and amounts that strategy manages
    function assetsAmounts() external view returns (address[] memory assets_, uint[] memory amounts_);

    /// @notice Priced invested assets proportions
    /// @return proportions Proportions of assets with 18 decimals. Min is 0, max is 1e18.
    function getAssetsProportions() external view returns (uint[] memory proportions);

    /// @notice Underlying token address
    /// @dev Can be used for liquidity farming strategies where AMM has fungible liquidity token (Solidly forks, etc),
    ///      for concentrated liquidity tokenized vaults (Gamma, G-UNI etc) and for other needs.
    /// @return Address of underlying token or zero address if no underlying in strategy
    function underlying() external view returns (address);

    /// @dev Balance of liquidity token or liquidity value
    function total() external view returns (uint);

    /// @dev Last HardWork time
    /// @return Timestamp
    function lastHardWork() external view returns (uint);

    /// @dev Last APR of earned USD amount registered by HardWork
    ///      ONLY FOR OFF-CHAIN USE.
    ///      Not trusted asset price can be manipulated.
    /// @return APR with 5 decimals. 100_000 - 100% APR, 9_955 - 9.96% APR.
    function lastApr() external view returns (uint);

    /// @dev Last APR of compounded assets registered by HardWork.
    ///      Can be used on-chain.
    /// @return APR with 5 decimals. 100_000 - 100% APR, 9_955 - 9.96% APR.
    function lastAprCompound() external view returns (uint);

    /// @notice Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts.
    /// @param assets_ Strategy assets or part of them, if necessary
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Cosumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external view returns (uint[] memory amountsConsumed, uint value);

    /// @notice Write version of previewDepositAssets
    /// @param assets_ Strategy assets or part of them, if necessary
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Cosumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function previewDepositAssetsWrite(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external returns (uint[] memory amountsConsumed, uint value);

    /// @notice All strategy revenue (pool fees, farm rewards etc) that not claimed by strategy yet
    /// @return assets_ Revenue assets
    /// @return amounts Amounts. Index of asset same as in previous array.
    function getRevenue() external view returns (address[] memory assets_, uint[] memory amounts);

    /// @notice Optional specific name of investing strategy, underyling type, setup variation etc
    /// @return name Empty string or specific name
    /// @return showInVaultSymbol Show specific in linked vault symbol
    function getSpecificName() external view returns (string memory name, bool showInVaultSymbol);

    /// @notice Variants pf strategy initializations with description of money making mechanic.
    /// As example, if strategy need farm, then number of variations is number of available farms.
    /// If CAMM strategy have set of available widths (tick ranges), then number of variations is number of available farms.
    /// If both example conditions are met then total number or variations = total farms * total widths.
    /// @param platform_ Need this param because method called when strategy implementation is not initialized
    /// @return variants Descriptions of the strategy for making money
    /// @return addresses Init strategy addresses. Indexes for each variants depends of copmpared arrays lengths.
    /// @return nums Init strategy numbers. Indexes for each variants depends of copmpared arrays lengths.
    /// @return ticks Init strategy ticks. Indexes for each variants depends of copmpared arrays lengths.
    function initVariants(address platform_)
        external
        view
        returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks);

    /// @notice How does the strategy make money?
    /// @return Description in free form
    function description() external view returns (string memory);

    /// @notice Is HardWork on vault deposits can be enabled
    function isHardWorkOnDepositAllowed() external view returns (bool);

    /// @notice Is HardWork can be executed
    function isReadyForHardWork() external view returns (bool);

    /// @notice Strategy not need to process revenue on HardWorks
    function autoCompoundingByUnderlyingProtocol() external view returns (bool);

    /// @notice Custom price impact tolerance instead default need for specific cases where liquidity in pools is low
    function customPriceImpactTolerance() external view returns (uint);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev A single universal initializer for all strategy implementations.
    /// @param addresses All addresses that strategy requires for initialization. Min array length is 2.
    ///        addresses[0]: platform (required)
    ///        addresses[1]: vault (required)
    ///        addresses[2]: initStrategyAddresses[0] (optional)
    ///        addresses[3]: initStrategyAddresses[1] (optional)
    ///        addresses[n]: initStrategyAddresses[n - 2] (optional)
    /// @param nums All uint values that strategy requires for initialization. Min array length is 0.
    /// @param ticks All int24 values that strategy requires for initialization. Min array length is 0.
    function initialize(address[] memory addresses, uint[] memory nums, int24[] memory ticks) external;

    /// @notice Invest strategy assets. Amounts of assets must be already on strategy contract balance.
    /// Only vault can call this.
    /// @param amounts Amounts of strategy assets
    /// @return value Liquidity value or underlying token amount
    function depositAssets(uint[] memory amounts) external returns (uint value);

    /// @notice Invest underlying asset. Asset must be already on strategy contract balance.
    /// Only vault can call this.
    /// @param amount Amount of underlying asset to invest
    /// @return amountsConsumed Consumed amounts of invested assets
    function depositUnderlying(uint amount) external returns (uint[] memory amountsConsumed);

    /// @dev For specified amount of shares and assets_, withdraw strategy assets from farm/pool/staking and send to receiver if possible
    /// Only vault can call this.
    /// @param assets_ Here we give the user a choice of assets to withdraw if strategy support it
    /// @param value Part of strategy total value to withdraw
    /// @param receiver User address
    /// @return amountsOut Amounts of assets sent to user
    function withdrawAssets(
        address[] memory assets_,
        uint value,
        address receiver
    ) external returns (uint[] memory amountsOut);

    /// @notice Wothdraw underlying invested and send to receiver
    /// Only vault can call this.
    /// @param amount Amount of underlying asset to withdraw
    /// @param receiver User of vault which withdraw underlying from the vault
    function withdrawUnderlying(uint amount, address receiver) external;

    /// @dev For specified amount of shares, transfer strategy assets from contract balance and send to receiver if possible
    /// This method is called by vault w/o underlying on triggered fuse mode.
    /// Only vault can call this.
    /// @param amount Amount of liquidity value that user withdraw
    /// @param totalAmount Total amount of strategy liquidity
    /// @param receiver User of vault which withdraw assets
    /// @return amountsOut Amounts of strategy assets sent to user
    function transferAssets(
        uint amount,
        uint totalAmount,
        address receiver
    ) external returns (uint[] memory amountsOut);

    /// @notice Execute HardWork
    /// During HardWork strategy claiming revenue and processing it.
    /// Only vault can call this.
    function doHardWork() external;

    /// @notice Emergency stop investing by strategy, withdraw liquidity without rewards.
    /// This action triggers FUSE mode.
    /// Only governance or multisig can call this.
    function emergencyStopInvesting() external;

    /// @notice Custom price impact tolerance instead default need for specific cases where low liquidity in pools
    /// @param priceImpactTolerance Tolerance percent with 100_000 DENOMINATOR. 4_000 == 4%
    function setCustomPriceImpactTolerance(uint priceImpactTolerance) external;

    /// @notice Total amount of assets available in the lending protocol for withdraw
    /// It's normal situation when user is not able to withdraw all
    /// because there are not enough reserves available in the protocol right now
    /// @return amounts Empty array (zero length) is returned if all available amount can be withdrawn
    function maxWithdrawAssets() external view returns (uint[] memory amounts);

    /// @notice Underlying pool TVL in the terms of USD
    function poolTvl() external view returns (uint tvlUsd);

    /// @notice return FUSE_ON_1 if emergency was called and all actives were transferred to the vault
    function fuseMode() external view returns (uint);

    /// @notice Maximum amounts of assets that can be deposited into the strategy
    /// @return amounts Empty array (zero length) is returned if there are no limits on deposits
    function maxDepositAssets() external view returns (uint[] memory amounts);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @dev Base core interface implemented by most platform contracts.
///      Inherited contracts store an immutable Platform proxy address in the storage,
///      which provides authorization capabilities and infrastructure contract addresses.
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
/// @author dvpublic (https://github.com/dvpublic)
interface IControllable {
    //region ----- Custom Errors -----
    error IncorrectZeroArgument();
    error IncorrectMsgSender();
    error NotGovernance();
    error NotMultisig();
    error NotGovernanceAndNotMultisig();
    error NotOperator();
    error NotFactory();
    error NotPlatform();
    error NotVault();
    error IncorrectArrayLength();
    error AlreadyExist();
    error NotExist();
    error NotTheOwner();
    error ETHTransferFailed();
    error IncorrectInitParams();
    error InsufficientBalance();
    error IncorrectBalance();
    error IncorrectLtv(uint ltv);
    error TooLowValue(uint value);
    error IncorrectAssetsList(address[] assets_, address[] expectedAssets_);
    //endregion -- Custom Errors -----

    event ContractInitialized(address platform, uint ts, uint block);

    /// @notice Stability Platform main contract address
    function platform() external view returns (address);

    /// @notice Version of contract implementation
    /// @dev SemVer scheme MAJOR.MINOR.PATCH
    //slither-disable-next-line naming-convention
    function VERSION() external view returns (string memory);

    /// @notice Block number when contract was initialized
    function createdBlock() external view returns (uint);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface ILeverageLendingStrategy {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event LeverageLendingHardWork(
        int realApr, int earned, uint realTvl, uint duration, uint realSharePrice, uint supplyApr, uint borrowApr
    );
    event LeverageLendingHealth(uint ltv, uint leverage);
    event TargetLeveragePercent(uint value);
    event UniversalParams(uint[] params);
    event UniversalAddresses(address[] addresses);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.LeverageLendingBase
    struct LeverageLendingBaseStorage {
        // init immutable params
        address collateralAsset;
        address borrowAsset;
        address lendingVault;
        address borrowingVault;
        address flashLoanVault;
        address helper;
        // temp vars
        CurrentAction tempAction;
        uint tempBorrowAmount;
        uint tempCollateralAmount;
        // configurable params
        /// @dev Percent of max leverage. 90_00 is 90%.
        uint targetLeveragePercent;
        /// @dev Universal configurable param 0 for depositAssets
        uint depositParam0;
        /// @dev Universal configurable param 1 for depositAssets
        uint depositParam1;
        /// @dev Universal configurable param 0 for withdrawAssets
        /// @dev SiL, SiAL: withdrawParam0 allows to regulate flash amount in default withdraw
        uint withdrawParam0;
        /// @dev Universal configurable param 1 for withdrawAssets
        /// @dev SiL, SiAL: withdrawParam1 allows to regulate/disable deposit after withdraw
        uint withdrawParam1;
        /// @dev Universal configurable param 0 for increase LTV
        uint increaseLtvParam0;
        /// @dev Universal configurable param 1 for increase LTV
        uint increaseLtvParam1;
        /// @dev Universal configurable param 0 for decrease LTV
        uint decreaseLtvParam0;
        /// @dev Universal configurable param 1 for decrease LTV
        uint decreaseLtvParam1;
        /// @dev Swap price impact tolerance on enter/exit
        uint swapPriceImpactTolerance0;
        /// @dev Swap price impact tolerance on re-balance debt
        uint swapPriceImpactTolerance1;
        /// @notice Flash loan kind. 0 - balancer v2 (paid), 1 - balancer v3 (free)
        uint flashLoanKind;
        /// @dev Universal address 1. SiL uses it to store flash loan vault address for borrow asset
        address universalAddress1;
        /// @dev Universal configurable param 2 for withdrawAssets
        /// @dev SiL, SiAL: withdrawParam1 allows to regulate withdraw-through-increasing-ltv
        uint withdrawParam2;
    }

    struct LeverageLendingStrategyBaseInitParams {
        string strategyId;
        address platform;
        address vault;
        address collateralAsset;
        address borrowAsset;
        address lendingVault;
        address borrowingVault;
        address flashLoanVault;
        address helper;
        uint targetLeveragePercent;
    }

    struct LeverageLendingAddresses {
        address collateralAsset;
        address borrowAsset;
        address lendingVault;
        address borrowingVault;
    }

    enum CurrentAction {
        None,
        Deposit,
        Withdraw,
        DecreaseLtv,
        /// @notice All available balances are used
        IncreaseLtv,
        /// @notice Amounts of collateral and borrow that can be used are limited through temp vars
        IncreaseLtvLimited
    }

    enum FlashLoanKind {
        /// @notice Balancer V2
        Default_0,
        BalancerV3_1,
        UniswapV3_2,
        AlgebraV4_3
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Re-balance debt
    /// @param newLtv Target LTV after re-balancing with 4 decimals. 90_00 is 90%.
    /// @return resultLtv LTV after re-balance. For static calls.
    /// @return resultSharePrice Share price after applying rebalance debt
    function rebalanceDebt(uint newLtv, uint minSharePrice) external returns (uint resultLtv, uint resultSharePrice);

    /// @notice Change target leverage percent
    /// @param value Value with 4 decimals, 90_00 is 90%.
    function setTargetLeveragePercent(uint value) external;

    /// @notice Change universal configurable params
    function setUniversalParams(uint[] memory params, address[] memory addresses) external;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
    /// @notice Get universal configurable params
    function getUniversalParams() external view returns (uint[] memory params, address[] memory addresses);

    /// @notice Difference between collateral and debt
    /// @return tvl USD amount of user deposited assets
    /// @return trusted True if only oracle prices was used for calculation.
    function realTvl() external view returns (uint tvl, bool trusted);

    /// @notice Vault share price of difference between collateral and debt
    /// @return sharePrice USD amount of share price of user deposited assets
    /// @return trusted True if only oracle prices was used for calculation.
    function realSharePrice() external view returns (uint sharePrice, bool trusted);

    /// @notice Show leverage main data
    /// @return ltv Current LTV with 4 decimals. 90_00 is 90%.
    /// @return maxLtv Maximum LTV with 4 decimals. 90_00 is 90%.
    /// @return leverage Current leverage multiplier with 4 decimals
    /// @return collateralAmount Current amount of collateral asset (strategy asset)
    /// @return debtAmount Current debt of borrowed asset
    /// @return targetLeveragePercent Configurable percent of max leverage. 90_00 is 90%.
    function health()
        external
        view
        returns (
            uint ltv,
            uint maxLtv,
            uint leverage,
            uint collateralAmount,
            uint debtAmount,
            uint targetLeveragePercent
        );

    /// @notice Show APRs
    /// @return supplyApr APR of supplying with 5 decimals.
    /// @return borrowApr APR of borrowing with 5 decimals.
    function getSupplyAndBorrowAprs() external view returns (uint supplyApr, uint borrowApr);
}

File 8 of 41 : IPlatform.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @notice Interface of the main contract and entry point to the platform.
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IPlatform {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error AlreadyAnnounced();
    error SameVersion();
    error NoNewVersion();
    error UpgradeTimerIsNotOver(uint TimerTimestamp);
    error IncorrectFee(uint minFee, uint maxFee);
    error NotEnoughAllowedBBToken();
    error TokenAlreadyExistsInSet(address token);
    error AggregatorNotExists(address dexAggRouter);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event PlatformVersion(string version);
    event UpgradeAnnounce(
        string oldVersion, string newVersion, address[] proxies, address[] newImplementations, uint timelock
    );
    event CancelUpgrade(string oldVersion, string newVersion);
    event ProxyUpgraded(
        address indexed proxy, address implementation, string oldContractVersion, string newContractVersion
    );
    event Addresses(
        address multisig_,
        address factory_,
        address priceReader_,
        address swapper_,
        address buildingPermitToken_,
        address vaultManager_,
        address strategyLogic_,
        address aprOracle_,
        address hardWorker,
        address rebalancer,
        address zap,
        address bridge
    );
    event OperatorAdded(address operator);
    event OperatorRemoved(address operator);
    event FeesChanged(uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem);
    event MinInitialBoostChanged(uint minInitialBoostPerDay, uint minInitialBoostDuration);
    event NewAmmAdapter(string id, address proxy);
    event EcosystemRevenueReceiver(address receiver);
    event SetAllowedBBTokenVaults(address bbToken, uint vaultsToBuild, bool firstSet);
    event RemoveAllowedBBToken(address bbToken);
    event AddAllowedBoostRewardToken(address token);
    event RemoveAllowedBoostRewardToken(address token);
    event AddDefaultBoostRewardToken(address token);
    event RemoveDefaultBoostRewardToken(address token);
    event AddBoostTokens(address[] allowedBoostRewardToken, address[] defaultBoostRewardToken);
    event AllowedBBTokenVaultUsed(address bbToken, uint vaultToUse);
    event AddDexAggregator(address router);
    event RemoveDexAggregator(address router);
    event MinTvlForFreeHardWorkChanged(uint oldValue, uint newValue);
    event CustomVaultFee(address vault, uint platformFee);
    event Rebalancer(address rebalancer_);
    event Bridge(address bridge_);
    event RevenueRouter(address revenueRouter_);
    event MetaVaultFactory(address metaVaultFactory);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    struct PlatformUpgrade {
        string newVersion;
        address[] proxies;
        address[] newImplementations;
    }

    struct PlatformSettings {
        string networkName;
        bytes32 networkExtra;
        uint fee;
        uint feeShareVaultManager;
        uint feeShareStrategyLogic;
        uint feeShareEcosystem;
        uint minInitialBoostPerDay;
        uint minInitialBoostDuration;
    }

    struct AmmAdapter {
        string id;
        address proxy;
    }

    struct SetupAddresses {
        address factory;
        address priceReader;
        address swapper;
        address buildingPermitToken;
        address buildingPayPerVaultToken;
        address vaultManager;
        address strategyLogic;
        address aprOracle;
        address targetExchangeAsset;
        address hardWorker;
        address zap;
        address revenueRouter;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      VIEW FUNCTIONS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Platform version in CalVer scheme: YY.MM.MINOR-tag. Updates on core contract upgrades.
    function platformVersion() external view returns (string memory);

    /// @notice Time delay for proxy upgrades of core contracts and changing important platform settings by multisig
    //slither-disable-next-line naming-convention
    function TIME_LOCK() external view returns (uint);

    /// @notice DAO governance
    function governance() external view returns (address);

    /// @notice Core team multi signature wallet. Development and operations fund
    function multisig() external view returns (address);

    /// @notice This NFT allow user to build limited number of vaults per week
    function buildingPermitToken() external view returns (address);

    /// @notice This ERC20 token is used as payment token for vault building
    function buildingPayPerVaultToken() external view returns (address);

    /// @notice Receiver of ecosystem revenue
    function ecosystemRevenueReceiver() external view returns (address);

    /// @dev The best asset in a network for swaps between strategy assets and farms rewards assets
    ///      The target exchange asset is used for finding the best strategy's exchange asset.
    ///      Rhe fewer routes needed to swap to the target exchange asset, the better.
    function targetExchangeAsset() external view returns (address);

    /// @notice Platform factory assembling vaults. Stores settings, strategy logic, farms.
    /// Provides the opportunity to upgrade vaults and strategies.
    /// @return Address of Factory proxy
    function factory() external view returns (address);

    /// @notice The holders of these NFT receive a share of the vault revenue
    /// @return Address of VaultManager proxy
    function vaultManager() external view returns (address);

    /// @notice The holders of these tokens receive a share of the revenue received in all vaults using this strategy logic.
    function strategyLogic() external view returns (address);

    /// @notice Combining oracle and DeX spot prices
    /// @return Address of PriceReader proxy
    function priceReader() external view returns (address);

    /// @notice Providing underlying assets APRs on-chain
    /// @return Address of AprOracle proxy
    function aprOracle() external view returns (address);

    /// @notice On-chain price quoter and swapper
    /// @return Address of Swapper proxy
    function swapper() external view returns (address);

    /// @notice HardWork resolver and caller
    /// @return Address of HardWorker proxy
    function hardWorker() external view returns (address);

    /// @notice Rebalance resolver
    /// @return Address of Rebalancer proxy
    function rebalancer() external view returns (address);

    /// @notice ZAP feature
    /// @return Address of Zap proxy
    function zap() external view returns (address);

    /// @notice Platform revenue distributor
    /// @return Address of the revenue distributor proxy
    function revenueRouter() external view returns (address);

    /// @notice Factory of MetaVaults
    /// @return Address of the MetaVault factory
    function metaVaultFactory() external view returns (address);

    /// @notice Name of current EVM network
    function networkName() external view returns (string memory);

    /// @notice Minimal initial boost rewards per day USD amount which needs to create rewarding vault
    function minInitialBoostPerDay() external view returns (uint);

    /// @notice Minimal boost rewards vesting duration for initial boost
    function minInitialBoostDuration() external view returns (uint);

    /// @notice This function provides the timestamp of the platform upgrade timelock.
    /// @dev This function is an external view function, meaning it doesn't modify the state.
    /// @return uint representing the timestamp of the platform upgrade timelock.
    function platformUpgradeTimelock() external view returns (uint);

    /// @dev Extra network data
    /// @return 0-2 bytes - color
    ///         3-5 bytes - background color
    ///         6-31 bytes - free
    function networkExtra() external view returns (bytes32);

    /// @notice Pending platform upgrade data
    function pendingPlatformUpgrade() external view returns (PlatformUpgrade memory);

    /// @notice Get platform revenue fee settings
    /// @return fee Revenue fee % (between MIN_FEE - MAX_FEE) with DENOMINATOR precision.
    /// @return feeShareVaultManager Revenue fee share % of VaultManager tokenId owner
    /// @return feeShareStrategyLogic Revenue fee share % of StrategyLogic tokenId owner
    /// @return feeShareEcosystem Revenue fee share % of ecosystemFeeReceiver
    function getFees()
        external
        view
        returns (uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem);

    /// @notice Get custom vault platform fee
    /// @return fee revenue fee % with DENOMINATOR precision
    function getCustomVaultFee(address vault) external view returns (uint fee);

    /// @notice Platform settings
    function getPlatformSettings() external view returns (PlatformSettings memory);

    /// @notice AMM adapters of the platform
    function getAmmAdapters() external view returns (string[] memory id, address[] memory proxy);

    /// @notice Get AMM adapter data by hash
    /// @param ammAdapterIdHash Keccak256 hash of adapter ID string
    /// @return ID string and proxy address of AMM adapter
    function ammAdapter(bytes32 ammAdapterIdHash) external view returns (AmmAdapter memory);

    /// @notice Allowed buy-back tokens for rewarding vaults
    function allowedBBTokens() external view returns (address[] memory);

    /// @notice Vaults building limit for buy-back token.
    /// This limit decrements when a vault for BB-token is built.
    /// @param token Allowed buy-back token
    /// @return vaultsLimit Number of vaults that can be built for BB-token
    function allowedBBTokenVaults(address token) external view returns (uint vaultsLimit);

    /// @notice Vaults building limits for allowed buy-back tokens.
    /// @return bbToken Allowed buy-back tokens
    /// @return vaultsLimit Number of vaults that can be built for BB-tokens
    function allowedBBTokenVaults() external view returns (address[] memory bbToken, uint[] memory vaultsLimit);

    /// @notice Non-zero vaults building limits for allowed buy-back tokens.
    /// @return bbToken Allowed buy-back tokens
    /// @return vaultsLimit Number of vaults that can be built for BB-tokens
    function allowedBBTokenVaultsFiltered()
        external
        view
        returns (address[] memory bbToken, uint[] memory vaultsLimit);

    /// @notice Check address for existance in operators list
    /// @param operator Address
    /// @return True if this address is Stability Operator
    function isOperator(address operator) external view returns (bool);

    /// @notice Tokens that can be used for boost rewards of rewarding vaults
    /// @return Addresses of tokens
    function allowedBoostRewardTokens() external view returns (address[] memory);

    /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation
    /// @return Addresses of tokens
    function defaultBoostRewardTokens() external view returns (address[] memory);

    /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation
    /// @param addressToRemove This address will be removed from default boost reward tokens
    /// @return Addresses of tokens
    function defaultBoostRewardTokensFiltered(address addressToRemove) external view returns (address[] memory);

    /// @notice Allowed DeX aggregators
    /// @return Addresses of DeX aggregator rounters
    function dexAggregators() external view returns (address[] memory);

    /// @notice DeX aggregator router address is allowed to be used in the platform
    /// @param dexAggRouter Address of DeX aggreagator router
    /// @return Can be used
    function isAllowedDexAggregatorRouter(address dexAggRouter) external view returns (bool);

    /// @notice Show minimum TVL for compensate if vault has not enough ETH
    /// @return Minimum TVL for compensate.
    function minTvlForFreeHardWork() external view returns (uint);

    /// @notice Front-end platform viewer
    /// @return platformAddresses Platform core addresses
    ///        platformAddresses[0] factory
    ///        platformAddresses[1] vaultManager
    ///        platformAddresses[2] strategyLogic
    ///        platformAddresses[3] buildingPermitToken
    ///        platformAddresses[4] buildingPayPerVaultToken
    ///        platformAddresses[5] governance
    ///        platformAddresses[6] multisig
    ///        platformAddresses[7] zap
    ///        platformAddresses[8] bridge
    /// @return bcAssets Blue chip token addresses
    /// @return dexAggregators_ DeX aggregators allowed to be used entire the platform
    /// @return vaultType Vault type ID strings
    /// @return vaultExtra Vault color, background color and other extra data. Index of vault same as in previous array.
    /// @return vaultBulldingPrice Price of creating new vault in buildingPayPerVaultToken. Index of vault same as in previous array.
    /// @return strategyId Strategy logic ID strings
    /// @return isFarmingStrategy True if strategy is farming strategy. Index of strategy same as in previous array.
    /// @return strategyTokenURI StrategyLogic NFT tokenId metadata and on-chain image. Index of strategy same as in previous array.
    /// @return strategyExtra Strategy color, background color and other extra data. Index of strategy same as in previous array.
    function getData()
        external
        view
        returns (
            address[] memory platformAddresses,
            address[] memory bcAssets,
            address[] memory dexAggregators_,
            string[] memory vaultType,
            bytes32[] memory vaultExtra,
            uint[] memory vaultBulldingPrice,
            string[] memory strategyId,
            bool[] memory isFarmingStrategy,
            string[] memory strategyTokenURI,
            bytes32[] memory strategyExtra
        );

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Add platform operator.
    /// Only governance and multisig can add operator.
    /// @param operator Address of new operator
    function addOperator(address operator) external;

    /// @notice Remove platform operator.
    /// Only governance and multisig can remove operator.
    /// @param operator Address of operator to remove
    function removeOperator(address operator) external;

    /// @notice Announce upgrade of platform proxies implementations
    /// Only governance and multisig can announce platform upgrades.
    /// @param newVersion New platform version. Version must be changed when upgrading.
    /// @param proxies Addresses of core contract proxies
    /// @param newImplementations New implementation for proxy. Index of proxy same as in previous array.
    function announcePlatformUpgrade(
        string memory newVersion,
        address[] memory proxies,
        address[] memory newImplementations
    ) external;

    /// @notice Upgrade platform
    /// Only operator (multisig is operator too) can ececute pending platform upgrade
    function upgrade() external;

    /// @notice Cancel pending platform upgrade
    /// Only operator (multisig is operator too) can ececute pending platform upgrade
    function cancelUpgrade() external;

    /// @notice Register AMM adapter in platform
    /// @param id AMM adapter ID string from AmmAdapterIdLib
    /// @param proxy Address of AMM adapter proxy
    function addAmmAdapter(string memory id, address proxy) external;

    // todo Only governance and multisig can set allowed bb-token vaults building limit
    /// @notice Set new vaults building limit for buy-back token
    /// @param bbToken Address of allowed buy-back token
    /// @param vaultsToBuild Number of vaults that can be built for BB-token
    function setAllowedBBTokenVaults(address bbToken, uint vaultsToBuild) external;

    // todo Only governance and multisig can add allowed boost reward token
    /// @notice Add new allowed boost reward token
    /// @param token Address of token
    function addAllowedBoostRewardToken(address token) external;

    // todo Only governance and multisig can remove allowed boost reward token
    /// @notice Remove allowed boost reward token
    /// @param token Address of allowed boost reward token
    function removeAllowedBoostRewardToken(address token) external;

    // todo Only governance and multisig can add default boost reward token
    /// @notice Add default boost reward token
    /// @param token Address of default boost reward token
    function addDefaultBoostRewardToken(address token) external;

    // todo Only governance and multisig can remove default boost reward token
    /// @notice Remove default boost reward token
    /// @param token Address of allowed boost reward token
    function removeDefaultBoostRewardToken(address token) external;

    // todo Only governance and multisig can add allowed boost reward token
    // todo Only governance and multisig can add default boost reward token
    /// @notice Add new allowed boost reward token
    /// @notice Add default boost reward token
    /// @param allowedBoostRewardToken Address of allowed boost reward token
    /// @param defaultBoostRewardToken Address of default boost reward token
    function addBoostTokens(
        address[] memory allowedBoostRewardToken,
        address[] memory defaultBoostRewardToken
    ) external;

    /// @notice Decrease allowed BB-token vault building limit when vault is built
    /// Only Factory can do it.
    /// @param bbToken Address of allowed buy-back token
    function useAllowedBBTokenVault(address bbToken) external;

    /// @notice Allow DeX aggregator routers to be used in the platform
    /// @param dexAggRouter Addresses of DeX aggreagator routers
    function addDexAggregators(address[] memory dexAggRouter) external;

    /// @notice Remove allowed DeX aggregator router from the platform
    /// @param dexAggRouter Address of DeX aggreagator router
    function removeDexAggregator(address dexAggRouter) external;

    /// @notice Change initial boost rewards settings
    /// @param minInitialBoostPerDay_ Minimal initial boost rewards per day USD amount which needs to create rewarding vault
    /// @param minInitialBoostDuration_ Minimal boost rewards vesting duration for initial boost
    function setInitialBoost(uint minInitialBoostPerDay_, uint minInitialBoostDuration_) external;

    /// @notice Update new minimum TVL for compensate.
    /// @param value New minimum TVL for compensate.
    function setMinTvlForFreeHardWork(uint value) external;

    /// @notice Set custom platform fee for vault
    /// @param vault Vault address
    /// @param platformFee Custom platform fee
    function setCustomVaultFee(address vault, uint platformFee) external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

/// @dev Combining oracle and DeX spot prices
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IPriceReader {
    //region ----- Events -----
    event AdapterAdded(address adapter);
    event AdapterRemoved(address adapter);
    event VaultWithSafeSharePriceAdded(address vault);
    event VaultWithSafeSharePriceRemoved(address vault);
    //endregion -- Events -----

    /// @notice Price of asset
    /// @dev Price of 1.0 amount of asset in USD
    /// @param asset Address of asset
    /// @return price USD price with 18 decimals
    /// @return trusted Price from oracle
    function getPrice(address asset) external view returns (uint price, bool trusted);

    /// @notice Price of vault share
    /// @dev Price of 1.0 amount of vault token
    /// @param vault Address of vault
    /// @return price USD price with 18 decimals
    /// @return safe Safe to use this price on-chain
    function getVaultPrice(address vault) external view returns (uint price, bool safe);

    /// @notice Get USD price of specified assets and amounts
    /// @param assets_ Addresses of assets
    /// @param amounts_ Amount of asset. Index of asset same as in previous parameter.
    /// @return total Total USD value with 18 decimals
    /// @return assetAmountPrice USD price of asset amount. Index of assetAmountPrice same as in assets_ parameters.
    /// @return assetPrice USD price of asset. Index of assetAmountPrice same as in assets_ parameters.
    /// @return trusted True if only oracle prices was used for calculation.
    function getAssetsPrice(
        address[] memory assets_,
        uint[] memory amounts_
    ) external view returns (uint total, uint[] memory assetAmountPrice, uint[] memory assetPrice, bool trusted);

    /// @notice Get vaults that have organic safe share price that can be used on-chain
    function vaultsWithSafeSharePrice() external view returns (address[] memory vaults);

    /// @notice Add oracle adapter to PriceReader
    /// Only operator (multisig is operator too) can add adapter
    /// @param adapter_ Address of price oracle proxy
    function addAdapter(address adapter_) external;

    /// @notice Remove oracle adapter from PriceReader
    /// Only operator (multisig is operator too) can add adapter
    /// @param adapter_ Address of price oracle proxy
    function removeAdapter(address adapter_) external;

    /// @notice Add vaults that have organic safe share price that can be used on-chain
    /// Only operator (multisig is operator too) can add adapter
    /// @param vaults Addresses of vaults
    function addSafeSharePrices(address[] memory vaults) external;

    /// @notice Remove vaults that have organic safe share price that can be used on-chain
    /// Only operator (multisig is operator too) can add adapter
    /// @param vaults Addresses of vaults
    function removeSafeSharePrices(address[] memory vaults) external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import {ISilo} from "./ISilo.sol";

interface ISiloConfig {
    struct InitData {
        /// @notice Can be address zero if deployer fees are not to be collected. If deployer address is zero then
        /// deployer fee must be zero as well. Deployer will be minted an NFT that gives the right to claim deployer
        /// fees. NFT can be transferred with the right to claim.
        address deployer;
        /// @notice Address of the hook receiver called on every before/after action on Silo. Hook contract also
        /// implements liquidation logic and veSilo gauge connection.
        address hookReceiver;
        /// @notice Deployer's fee in 18 decimals points. Deployer will earn this fee based on the interest earned
        /// by the Silo. Max deployer fee is set by the DAO. At deployment it is 15%.
        uint deployerFee;
        /// @notice DAO's fee in 18 decimals points. DAO will earn this fee based on the interest earned
        /// by the Silo. Acceptable fee range fee is set by the DAO. Default at deployment is 5% - 50%.
        uint daoFee;
        /// @notice Address of the first token
        address token0;
        /// @notice Address of the solvency oracle. Solvency oracle is used to calculate LTV when deciding if borrower
        /// is solvent or should be liquidated. Solvency oracle is optional and if not set price of 1 will be assumed.
        address solvencyOracle0;
        /// @notice Address of the maxLtv oracle. Max LTV oracle is used to calculate LTV when deciding if borrower
        /// can borrow given amount of assets. Max LTV oracle is optional and if not set it defaults to solvency
        /// oracle. If neither is set price of 1 will be assumed.
        address maxLtvOracle0;
        /// @notice Address of the interest rate model
        address interestRateModel0;
        /// @notice Maximum LTV for first token. maxLTV is in 18 decimals points and is used to determine, if borrower
        /// can borrow given amount of assets. MaxLtv is in 18 decimals points. MaxLtv must be lower or equal to LT.
        uint maxLtv0;
        /// @notice Liquidation threshold for first token. LT is used to calculate solvency. LT is in 18 decimals
        /// points. LT must not be lower than maxLTV.
        uint lt0;
        /// @notice minimal acceptable LTV after liquidation, in 18 decimals points
        uint liquidationTargetLtv0;
        /// @notice Liquidation fee for the first token in 18 decimals points. Liquidation fee is what liquidator earns
        /// for repaying insolvent loan.
        uint liquidationFee0;
        /// @notice Flashloan fee sets the cost of taking a flashloan in 18 decimals points
        uint flashloanFee0;
        /// @notice Indicates if a beforeQuote on oracle contract should be called before quoting price
        bool callBeforeQuote0;
        /// @notice Address of the second token
        address token1;
        /// @notice Address of the solvency oracle. Solvency oracle is used to calculate LTV when deciding if borrower
        /// is solvent or should be liquidated. Solvency oracle is optional and if not set price of 1 will be assumed.
        address solvencyOracle1;
        /// @notice Address of the maxLtv oracle. Max LTV oracle is used to calculate LTV when deciding if borrower
        /// can borrow given amount of assets. Max LTV oracle is optional and if not set it defaults to solvency
        /// oracle. If neither is set price of 1 will be assumed.
        address maxLtvOracle1;
        /// @notice Address of the interest rate model
        address interestRateModel1;
        /// @notice Maximum LTV for first token. maxLTV is in 18 decimals points and is used to determine,
        /// if borrower can borrow given amount of assets. maxLtv is in 18 decimals points
        uint maxLtv1;
        /// @notice Liquidation threshold for first token. LT is used to calculate solvency. LT is in 18 decimals points
        uint lt1;
        /// @notice minimal acceptable LTV after liquidation, in 18 decimals points
        uint liquidationTargetLtv1;
        /// @notice Liquidation fee is what liquidator earns for repaying insolvent loan.
        uint liquidationFee1;
        /// @notice Flashloan fee sets the cost of taking a flashloan in 18 decimals points
        uint flashloanFee1;
        /// @notice Indicates if a beforeQuote on oracle contract should be called before quoting price
        bool callBeforeQuote1;
    }

    struct ConfigData {
        uint daoFee;
        uint deployerFee;
        address silo;
        address token;
        address protectedShareToken;
        address collateralShareToken;
        address debtShareToken;
        address solvencyOracle;
        address maxLtvOracle;
        address interestRateModel;
        uint maxLtv;
        uint lt;
        uint liquidationTargetLtv;
        uint liquidationFee;
        uint flashloanFee;
        address hookReceiver;
        bool callBeforeQuote;
    }

    struct DepositConfig {
        address silo;
        address token;
        address collateralShareToken;
        address protectedShareToken;
        uint daoFee;
        uint deployerFee;
        address interestRateModel;
    }

    error OnlySilo();
    error OnlySiloOrTokenOrHookReceiver();
    error WrongSilo();
    error OnlyDebtShareToken();
    error DebtExistInOtherSilo();
    error FeeTooHigh();

    /// @dev It should be called on debt transfer (debt share token transfer).
    /// In the case if the`_recipient` doesn't have configured a collateral silo,
    /// it will be set to the collateral silo of the `_sender`.
    /// @param _sender sender address
    /// @param _recipient recipient address
    function onDebtTransfer(address _sender, address _recipient) external;

    /// @notice Set collateral silo.
    /// @dev Revert if msg.sender is not a SILO_0 or SILO_1.
    /// @dev Always set collateral silo the same as msg.sender.
    /// @param _borrower borrower address
    function setThisSiloAsCollateralSilo(address _borrower) external;

    /// @notice Set collateral silo
    /// @dev Revert if msg.sender is not a SILO_0 or SILO_1.
    /// @dev Always set collateral silo opposite to the msg.sender.
    /// @param _borrower borrower address
    function setOtherSiloAsCollateralSilo(address _borrower) external;

    /// @notice Accrue interest for the silo
    /// @param _silo silo for which accrue interest
    function accrueInterestForSilo(address _silo) external;

    /// @notice Accrue interest for both silos (SILO_0 and SILO_1 in a config)
    function accrueInterestForBothSilos() external;

    /// @notice Retrieves the collateral silo for a specific borrower.
    /// @dev As a user can deposit into `Silo0` and `Silo1`, this property specifies which Silo
    /// will be used as collateral for the debt. Later on, it will be used for max LTV and solvency checks.
    /// After being set, the collateral silo is never set to `address(0)` again but such getters as
    /// `getConfigsForSolvency`, `getConfigsForBorrow`, `getConfigsForWithdraw` will return empty
    /// collateral silo config if borrower doesn't have debt.
    ///
    /// In the SiloConfig collateral silo is set by the following functions:
    /// `onDebtTransfer` - only if the recipient doesn't have collateral silo set (inherits it from the sender)
    /// This function is called on debt share token transfer (debt transfer).
    /// `setThisSiloAsCollateralSilo` - sets the same silo as the one that calls the function.
    /// `setOtherSiloAsCollateralSilo` - sets the opposite silo as collateral from the one that calls the function.
    ///
    /// In the Silo collateral silo is set by the following functions:
    /// `borrow` - always sets opposite silo as collateral.
    /// If Silo0 borrows, then Silo1 will be collateral and vice versa.
    /// `borrowSameAsset` - always sets the same silo as collateral.
    /// `switchCollateralToThisSilo` - always sets the same silo as collateral.
    /// @param _borrower The address of the borrower for which the collateral silo is being retrieved
    /// @return collateralSilo The address of the collateral silo for the specified borrower
    function borrowerCollateralSilo(address _borrower) external view returns (address collateralSilo);

    /// @notice Retrieves the silo ID
    /// @dev Each silo is assigned a unique ID. ERC-721 token is minted with identical ID to deployer.
    /// An owner of that token receives the deployer fees.
    /// @return siloId The ID of the silo
    function SILO_ID() external view returns (uint siloId); // solhint-disable-line func-name-mixedcase

    /// @notice Retrieves the addresses of the two silos
    /// @return silo0 The address of the first silo
    /// @return silo1 The address of the second silo
    function getSilos() external view returns (address silo0, address silo1);

    /// @notice Retrieves the asset associated with a specific silo
    /// @dev This function reverts for incorrect silo address input
    /// @param _silo The address of the silo for which the associated asset is being retrieved
    /// @return asset The address of the asset associated with the specified silo
    function getAssetForSilo(address _silo) external view returns (address asset);

    /// @notice Verifies if the borrower has debt in other silo by checking the debt share token balance
    /// @param _thisSilo The address of the silo in respect of which the debt is checked
    /// @param _borrower The address of the borrower for which the debt is checked
    /// @return hasDebt true if the borrower has debt in other silo
    function hasDebtInOtherSilo(address _thisSilo, address _borrower) external view returns (bool hasDebt);

    /// @notice Retrieves the debt silo associated with a specific borrower
    /// @dev This function reverts if debt present in two silo (should not happen)
    /// @param _borrower The address of the borrower for which the debt silo is being retrieved
    function getDebtSilo(address _borrower) external view returns (address debtSilo);

    /// @notice Retrieves configuration data for both silos. First config is for the silo that is asking for configs.
    /// @param borrower borrower address for which debtConfig will be returned
    /// @return collateralConfig The configuration data for collateral silo (empty if there is no debt).
    /// @return debtConfig The configuration data for debt silo (empty if there is no debt).
    function getConfigsForSolvency(address borrower)
        external
        view
        returns (ConfigData memory collateralConfig, ConfigData memory debtConfig);

    /// @notice Retrieves configuration data for a specific silo
    /// @dev This function reverts for incorrect silo address input.
    /// @param _silo The address of the silo for which configuration data is being retrieved
    /// @return config The configuration data for the specified silo
    function getConfig(address _silo) external view returns (ConfigData memory config);

    /// @notice Retrieves configuration data for a specific silo for withdraw fn.
    /// @dev This function reverts for incorrect silo address input.
    /// @param _silo The address of the silo for which configuration data is being retrieved
    /// @return depositConfig The configuration data for the specified silo (always config for `_silo`)
    /// @return collateralConfig The configuration data for the collateral silo (empty if there is no debt)
    /// @return debtConfig The configuration data for the debt silo (empty if there is no debt)
    function getConfigsForWithdraw(
        address _silo,
        address _borrower
    )
        external
        view
        returns (DepositConfig memory depositConfig, ConfigData memory collateralConfig, ConfigData memory debtConfig);

    /// @notice Retrieves configuration data for a specific silo for borrow fn.
    /// @dev This function reverts for incorrect silo address input.
    /// @param _debtSilo The address of the silo for which configuration data is being retrieved
    /// @return collateralConfig The configuration data for the collateral silo (always other than `_debtSilo`)
    /// @return debtConfig The configuration data for the debt silo (always config for `_debtSilo`)
    function getConfigsForBorrow(address _debtSilo)
        external
        view
        returns (ConfigData memory collateralConfig, ConfigData memory debtConfig);

    /// @notice Retrieves fee-related information for a specific silo
    /// @dev This function reverts for incorrect silo address input
    /// @param _silo The address of the silo for which fee-related information is being retrieved.
    /// @return daoFee The DAO fee percentage in 18 decimals points.
    /// @return deployerFee The deployer fee percentage in 18 decimals points.
    /// @return flashloanFee The flashloan fee percentage in 18 decimals points.
    /// @return asset The address of the asset associated with the specified silo.
    function getFeesWithAsset(address _silo)
        external
        view
        returns (uint daoFee, uint deployerFee, uint flashloanFee, address asset);

    /// @notice Retrieves share tokens associated with a specific silo
    /// @dev This function reverts for incorrect silo address input
    /// @param _silo The address of the silo for which share tokens are being retrieved
    /// @return protectedShareToken The address of the protected (non-borrowable) share token
    /// @return collateralShareToken The address of the collateral share token
    /// @return debtShareToken The address of the debt share token
    function getShareTokens(address _silo)
        external
        view
        returns (address protectedShareToken, address collateralShareToken, address debtShareToken);

    /// @notice Retrieves the share token and the silo token associated with a specific silo
    /// @param _silo The address of the silo for which the share token and silo token are being retrieved
    /// @param _collateralType The type of collateral
    /// @return shareToken The address of the share token (collateral or protected collateral)
    /// @return asset The address of the silo token
    function getCollateralShareTokenAndAsset(
        address _silo,
        ISilo.CollateralType _collateralType
    ) external view returns (address shareToken, address asset);

    /// @notice Retrieves the share token and the silo token associated with a specific silo
    /// @param _silo The address of the silo for which the share token and silo token are being retrieved
    /// @return shareToken The address of the share token (debt)
    /// @return asset The address of the silo token
    function getDebtShareTokenAndAsset(address _silo) external view returns (address shareToken, address asset);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

interface ISiloLens {
    /// @notice Retrieves the loan-to-value (LTV) for a specific borrower
    /// @param _silo Address of the silo
    /// @param _borrower Address of the borrower
    /// @return ltv The LTV for the borrower in 18 decimals points
    function getLtv(address _silo, address _borrower) external view returns (uint ltv);

    /// @notice Calculates current borrow interest rate
    /// @param _silo Address of the silo
    /// @return borrowAPR The interest rate value in 18 decimals points. 10**18 is equal to 100% per year
    function getBorrowAPR(address _silo) external view returns (uint borrowAPR);

    /// @notice Calculates current deposit interest rate.
    /// @param _silo Address of the silo
    /// @return depositAPR The interest rate value in 18 decimals points. 10**18 is equal to 100% per year.
    function getDepositAPR(address _silo) external view returns (uint depositAPR);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

interface ISiloOracle {
    /// @notice Hook function to call before `quote` function reads price
    /// @dev This hook function can be used to change state right before the price is read. For example it can be used
    ///      for curve read only reentrancy protection. In majority of implementations this will be an empty function.
    ///      WARNING: reverts are propagated to Silo so if `beforeQuote` reverts, Silo reverts as well.
    /// @param _baseToken Address of priced token
    function beforeQuote(address _baseToken) external;

    /// @return quoteAmount Returns quote price for _baseAmount of _baseToken
    /// @param _baseAmount Amount of priced token
    /// @param _baseToken Address of priced token
    function quote(uint _baseAmount, address _baseToken) external view returns (uint quoteAmount);

    /// @return address of token in which quote (price) is denominated
    function quoteToken() external view returns (address);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";

interface ISilo is IERC4626 {
    error NotEnoughLiquidity();
    /// @dev There are 2 types of accounting in the system: for non-borrowable collateral deposit called "protected" and
    ///      for borrowable collateral deposit called "collateral". System does
    ///      identical calculations for each type of accounting but it uses different data. To avoid code duplication
    ///      this enum is used to decide which data should be read.
    enum CollateralType {
        Protected,
        Collateral
    }

    /// @notice Implements IERC4626.deposit for protected (non-borrowable) collateral and collateral
    /// @dev Reverts for debt asset type
    function deposit(uint _assets, address _receiver, CollateralType collateralType) external returns (uint shares);

    /// @notice Allows an address to borrow a specified amount of assets
    /// @param _assets Amount of assets to borrow
    /// @param _receiver Address receiving the borrowed assets
    /// @param _borrower Address responsible for the borrowed assets
    /// @return shares Amount of shares equivalent to the borrowed assets
    function borrow(uint _assets, address _receiver, address _borrower) external returns (uint shares);

    /// @notice Repays a given asset amount and returns the equivalent number of shares
    /// @param _assets Amount of assets to be repaid
    /// @param _borrower Address of the borrower whose debt is being repaid
    /// @return shares The equivalent number of shares for the provided asset amount
    function repay(uint _assets, address _borrower) external returns (uint shares);

    /// @notice Implements IERC4626.withdraw for protected (non-borrowable) collateral and collateral
    /// @dev Reverts for debt asset type
    function withdraw(
        uint _assets,
        address _receiver,
        address _owner,
        CollateralType collateralType
    ) external returns (uint shares);

    /// @notice Accrues interest for the asset and returns the accrued interest amount
    /// @return accruedInterest The total interest accrued during this operation
    function accrueInterest() external returns (uint accruedInterest);

    /// @inheritdoc IERC4626
    /// @dev For protected (non-borrowable) collateral and debt, use:
    /// `convertToAssets(uint256 _shares, AssetType _assetType)` with `AssetType.Protected` or `AssetType.Debt`
    function convertToAssets(uint _shares) external view returns (uint assets);

    function asset() external view returns (address assetTokenAddres);

    /// @notice Fetches the silo configuration contract
    /// @return siloConfig Address of the configuration contract associated with the silo
    function config() external view returns (address siloConfig);

    /// @notice Calculates the maximum amount of assets that can be borrowed by the given address
    /// @param _borrower Address of the potential borrower
    /// @return maxAssets Maximum amount of assets that the borrower can borrow, this value is underestimated
    /// That means, in some cases when you borrow maxAssets, you will be able to borrow again eg. up to 2wei
    /// Reason for underestimation is to return value that will not cause borrow revert
    function maxBorrow(address _borrower) external view returns (uint maxAssets);

    /// @notice Calculates the maximum amount an address can repay based on their debt shares
    /// @param _borrower Address of the borrower
    /// @return assets Maximum amount of assets the borrower can repay
    function maxRepay(address _borrower) external view returns (uint assets);

    function getLiquidity() external view returns (uint256 liquidity);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ConstantsLib} from "../../core/libs/ConstantsLib.sol";
import {CommonLib} from "../../core/libs/CommonLib.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IVaultManager} from "../../interfaces/IVaultManager.sol";
import {IFactory} from "../../interfaces/IFactory.sol";
import {IPriceReader} from "../../interfaces/IPriceReader.sol";
import {ISwapper} from "../../interfaces/ISwapper.sol";
import {IStrategy} from "../../interfaces/IStrategy.sol";
import {IFarmingStrategy} from "../../interfaces/IFarmingStrategy.sol";
import {IRevenueRouter} from "../../interfaces/IRevenueRouter.sol";

library StrategyLib {
    using SafeERC20 for IERC20;

    /// @dev Reward pools may have low liquidity and up to 2% fees
    uint internal constant SWAP_REWARDS_PRICE_IMPACT_TOLERANCE = 7_000;

    struct ExtractFeesVars {
        IPlatform platform;
        uint feePlatform;
        uint amountPlatform;
        uint feeShareVaultManager;
        uint amountVaultManager;
        uint feeShareStrategyLogic;
        uint amountStrategyLogic;
        uint feeShareEcosystem;
        uint amountEcosystem;
    }

    function FarmingStrategyBase_init(
        IFarmingStrategy.FarmingStrategyBaseStorage storage $,
        string memory id,
        address platform,
        uint farmId
    ) external {
        $.farmId = farmId;

        IFactory.Farm memory farm = IFactory(IPlatform(platform).factory()).farm(farmId);
        if (keccak256(bytes(farm.strategyLogicId)) != keccak256(bytes(id))) {
            revert IFarmingStrategy.IncorrectStrategyId();
        }

        updateFarmingAssets($, platform);

        $._rewardsOnBalance = new uint[](farm.rewardAssets.length);
    }

    function updateFarmingAssets(IFarmingStrategy.FarmingStrategyBaseStorage storage $, address platform) public {
        IFactory.Farm memory farm = IFactory(IPlatform(platform).factory()).farm($.farmId);
        address swapper = IPlatform(platform).swapper();
        $._rewardAssets = farm.rewardAssets;
        uint len = farm.rewardAssets.length;
        // nosemgrep
        for (uint i; i < len; ++i) {
            IERC20(farm.rewardAssets[i]).forceApprove(swapper, type(uint).max);
        }
        $._rewardsOnBalance = new uint[](len);
    }

    function transferAssets(
        IStrategy.StrategyBaseStorage storage $,
        uint amount,
        uint total_,
        address receiver
    ) external returns (uint[] memory amountsOut) {
        address[] memory assets = $._assets;

        uint len = assets.length;
        amountsOut = new uint[](len);
        // nosemgrep
        for (uint i; i < len; ++i) {
            amountsOut[i] = balance(assets[i]) * amount / total_;
            IERC20(assets[i]).transfer(receiver, amountsOut[i]);
        }
    }

    function extractFees(
        address platform,
        address vault,
        address[] memory assets_,
        uint[] memory amounts_
    ) external returns (uint[] memory amountsRemaining) {
        ExtractFeesVars memory vars = ExtractFeesVars({
            platform: IPlatform(platform),
            feePlatform: 0,
            amountPlatform: 0,
            feeShareVaultManager: 0,
            amountVaultManager: 0,
            feeShareStrategyLogic: 0,
            amountStrategyLogic: 0,
            feeShareEcosystem: 0,
            amountEcosystem: 0
        });

        (vars.feePlatform,,,) = vars.platform.getFees();
        try vars.platform.getCustomVaultFee(vault) returns (uint vaultCustomFee) {
            if (vaultCustomFee != 0) {
                vars.feePlatform = vaultCustomFee;
            }
        } catch {}

        //address vaultManagerReceiver =
        //    IVaultManager(vars.platform.vaultManager()).getRevenueReceiver(IVault(vault).tokenId());
        //slither-disable-next-line unused-return
        //uint strategyLogicTokenId = IFactory(vars.platform.factory()).strategyLogicConfig(keccak256(bytes(_id))).tokenId;
        //address strategyLogicReceiver =
        //    IStrategyLogic(vars.platform.strategyLogic()).getRevenueReceiver(strategyLogicTokenId);
        uint len = assets_.length;
        amountsRemaining = new uint[](len);
        // nosemgrep
        for (uint i; i < len; ++i) {
            // revenue fee amount of assets_[i]
            vars.amountPlatform = amounts_[i] * vars.feePlatform / ConstantsLib.DENOMINATOR;
            vars.amountPlatform = Math.min(vars.amountPlatform, balance(assets_[i]));

            if (vars.amountPlatform > 0) {
                try vars.platform.revenueRouter() returns (address revenueReceiver) {
                    IERC20(assets_[i]).forceApprove(revenueReceiver, vars.amountPlatform);
                    IRevenueRouter(revenueReceiver).processFeeAsset(assets_[i], vars.amountPlatform);
                } catch {
                    // can be only in old strategy upgrade tests
                }

                /*// VaultManager amount
                vars.amountVaultManager = vars.amountPlatform * vars.feeShareVaultManager / ConstantsLib.DENOMINATOR;

                // StrategyLogic amount
                vars.amountStrategyLogic = vars.amountPlatform * vars.feeShareStrategyLogic / ConstantsLib.DENOMINATOR;

                // Ecosystem amount
                vars.amountEcosystem = vars.amountPlatform * vars.feeShareEcosystem / ConstantsLib.DENOMINATOR;

                // Multisig share and amount
                uint multisigShare = ConstantsLib.DENOMINATOR - vars.feeShareVaultManager - vars.feeShareStrategyLogic
                    - vars.feeShareEcosystem;
                uint multisigAmount = multisigShare > 0
                    ? vars.amountPlatform - vars.amountVaultManager - vars.amountStrategyLogic - vars.amountEcosystem
                    : 0;

                // send amounts
                IERC20(assets_[i]).safeTransfer(vaultManagerReceiver, vars.amountVaultManager);
                IERC20(assets_[i]).safeTransfer(strategyLogicReceiver, vars.amountStrategyLogic);
                if (vars.amountEcosystem > 0) {
                    IERC20(assets_[i]).safeTransfer(vars.platform.ecosystemRevenueReceiver(), vars.amountEcosystem);
                }
                if (multisigAmount > 0) {
                    IERC20(assets_[i]).safeTransfer(vars.platform.multisig(), multisigAmount);
                }
                emit IStrategy.ExtractFees(
                    vars.amountVaultManager, vars.amountStrategyLogic, vars.amountEcosystem, multisigAmount
                );*/

                amountsRemaining[i] = amounts_[i] - vars.amountPlatform;
                amountsRemaining[i] = Math.min(amountsRemaining[i], balance(assets_[i]));
            }
        }
    }

    function liquidateRewards(
        address platform,
        address exchangeAsset,
        address[] memory rewardAssets_,
        uint[] memory rewardAmounts_,
        uint customPriceImpactTolerance
    ) external returns (uint earnedExchangeAsset) {
        ISwapper swapper = ISwapper(IPlatform(platform).swapper());
        uint len = rewardAssets_.length;
        uint exchangeAssetBalanceBefore = balance(exchangeAsset);
        // nosemgrep
        for (uint i; i < len; ++i) {
            if (rewardAmounts_[i] > swapper.threshold(rewardAssets_[i])) {
                if (rewardAssets_[i] != exchangeAsset) {
                    swapper.swap(
                        rewardAssets_[i],
                        exchangeAsset,
                        Math.min(rewardAmounts_[i], balance(rewardAssets_[i])),
                        customPriceImpactTolerance != 0
                            ? customPriceImpactTolerance
                            : SWAP_REWARDS_PRICE_IMPACT_TOLERANCE
                    );
                } else {
                    exchangeAssetBalanceBefore = 0;
                }
            }
        }
        uint exchangeAssetBalanceAfter = balance(exchangeAsset);
        earnedExchangeAsset = exchangeAssetBalanceAfter - exchangeAssetBalanceBefore;
    }

    function emitApr(
        IStrategy.StrategyBaseStorage storage $,
        address platform,
        address[] memory assets,
        uint[] memory amounts,
        uint tvl,
        uint totalBefore
    ) external {
        uint duration = block.timestamp - $.lastHardWork;
        IPriceReader priceReader = IPriceReader(IPlatform(platform).priceReader());
        //slither-disable-next-line unused-return
        (uint earned,, uint[] memory assetPrices,) = priceReader.getAssetsPrice(assets, amounts);
        uint apr = computeApr(tvl, earned, duration);
        uint aprCompound = totalBefore != 0 ? computeApr(totalBefore, $.total - totalBefore, duration) : apr;

        uint sharePrice = tvl * 1e18 / IERC20($.vault).totalSupply();
        emit IStrategy.HardWork(apr, aprCompound, earned, tvl, duration, sharePrice, assetPrices);
        $.lastApr = apr;
        $.lastAprCompound = aprCompound;
        $.lastHardWork = block.timestamp;
    }

    function balance(address token) public view returns (uint) {
        return IERC20(token).balanceOf(address(this));
    }

    /// @dev https://www.investopedia.com/terms/a/apr.asp
    ///      TVL and rewards should be in the same currency and with the same decimals
    function computeApr(uint tvl, uint earned, uint duration) public pure returns (uint) {
        if (tvl == 0 || duration == 0) {
            return 0;
        }
        return earned * 1e18 * ConstantsLib.DENOMINATOR * uint(365) / tvl / (duration * 1e18 / 1 days);
    }

    function computeAprInt(uint tvl, int earned, uint duration) public pure returns (int) {
        if (tvl == 0 || duration == 0) {
            return 0;
        }
        return earned * int(1e18) * int(ConstantsLib.DENOMINATOR) * int(365) / int(tvl) / int(duration * 1e18 / 1 days);
    }

    function assetsAmountsWithBalances(
        address[] memory assets_,
        uint[] memory amounts_
    ) external view returns (address[] memory assets, uint[] memory amounts) {
        assets = assets_;
        amounts = amounts_;
        uint len = assets_.length;
        // nosemgrep
        for (uint i; i < len; ++i) {
            amounts[i] += balance(assets_[i]);
        }
    }

    function assetsAreOnBalance(address[] memory assets) external view returns (bool isReady) {
        uint rwLen = assets.length;
        for (uint i; i < rwLen; ++i) {
            if (IERC20(assets[i]).balanceOf(address(this)) > 0) {
                isReady = true;
                break;
            }
        }
    }

    function isPositiveAmountInArray(uint[] memory amounts) external pure returns (bool) {
        uint len = amounts.length;
        for (uint i; i < len; ++i) {
            if (amounts[i] != 0) {
                return true;
            }
        }
        return false;
    }

    function swap(address platform, address tokenIn, address tokenOut, uint amount) external returns (uint amountOut) {
        uint outBalanceBefore = balance(tokenOut);
        ISwapper swapper = ISwapper(IPlatform(platform).swapper());
        swapper.swap(tokenIn, tokenOut, amount, 1000);
        amountOut = balance(tokenOut) - outBalanceBefore;
    }

    function swap(
        address platform,
        address tokenIn,
        address tokenOut,
        uint amount,
        uint priceImpactTolerance
    ) external returns (uint amountOut) {
        uint outBalanceBefore = balance(tokenOut);
        ISwapper swapper = ISwapper(IPlatform(platform).swapper());
        swapper.swap(tokenIn, tokenOut, amount, priceImpactTolerance);
        amountOut = balance(tokenOut) - outBalanceBefore;
    }

    // function getFarmsForStrategyId(address platform, string memory _id) external view returns (IFactory.Farm[] memory farms) {
    //     uint total;
    //     IFactory.Farm[] memory allFarms = IFactory(IPlatform(platform).factory()).farms();
    //     uint len = allFarms.length;
    //     for (uint i; i < len; ++i) {
    //         IFactory.Farm memory farm = allFarms[i];
    //         if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, _id)) {
    //             total++;
    //         }
    //     }
    //     farms = new IFactory.Farm[](total);
    //     uint k;
    //     for (uint i; i < len; ++i) {
    //         IFactory.Farm memory farm = allFarms[i];
    //         if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, _id)) {
    //             farms[k] = farm;
    //             k++;
    //         }
    //     }
    // }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import "../../integrations/balancer/IBVault.sol";
import "../../interfaces/IStrategy.sol";
import {IControllable} from "../../interfaces/IControllable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {ILeverageLendingStrategy} from "../../interfaces/ILeverageLendingStrategy.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IPriceReader} from "../../interfaces/IPriceReader.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {StrategyLib} from "./StrategyLib.sol";
import {IVaultMainV3} from "../../integrations/balancerv3/IVaultMainV3.sol";
import {IUniswapV3PoolActions} from "../../integrations/uniswapv3/pool/IUniswapV3PoolActions.sol";
import {IUniswapV3PoolImmutables} from "../../integrations/uniswapv3/pool/IUniswapV3PoolImmutables.sol";

/// @notice Shared functions for Leverage Lending strategies
library LeverageLendingLib {
    using SafeERC20 for IERC20;

    uint internal constant PRICE_IMPACT_DENOMINATOR = 100_000;

    /// @dev Get flash loan. Proper callback will be called in the strategy (depends on the kind of the flash loan)
    function requestFlashLoan(
        ILeverageLendingStrategy.LeverageLendingBaseStorage storage $,
        address[] memory flashAssets,
        uint[] memory flashAmounts
    ) internal {
        return requestFlashLoanExplicit(
            ILeverageLendingStrategy.FlashLoanKind($.flashLoanKind), $.flashLoanVault, flashAssets, flashAmounts
        );
    }

    /// @dev ALlow to specify vault explicitly, i.e. in SiL where borrow asset is taken from different flash loan vault
    function requestFlashLoanExplicit(
        ILeverageLendingStrategy.FlashLoanKind flashLoanKind,
        address flashLoanVault,
        address[] memory flashAssets,
        uint[] memory flashAmounts
    ) internal {
        if (flashLoanKind == ILeverageLendingStrategy.FlashLoanKind.BalancerV3_1) {
            // --------------- Flash loan of Balancer v3, free. The strategy should support IBalancerV3FlashCallback
            // fee amount are always 0, flash loan in balancer v3 is free
            bytes memory data = abi.encodeWithSignature(
                "receiveFlashLoanV3(address,uint256,bytes)",
                flashAssets[0],
                flashAmounts[0],
                bytes("") // no user data
            );

            IVaultMainV3(payable(flashLoanVault)).unlock(data);
        } else if (
            // assume here that Algebra uses exactly same API as UniswapV3
            flashLoanKind == ILeverageLendingStrategy.FlashLoanKind.UniswapV3_2
                || flashLoanKind == ILeverageLendingStrategy.FlashLoanKind.AlgebraV4_3
        ) {
            // --------------- Flash loan Uniswap V3. The strategy should support IUniswapV3FlashCallback
            // ensure that the vault has available amount
            require(
                IERC20(flashAssets[0]).balanceOf(address(flashLoanVault)) >= flashAmounts[0],
                IControllable.InsufficientBalance()
            );

            bool isToken0 = IUniswapV3PoolImmutables(flashLoanVault).token0() == flashAssets[0];
            IUniswapV3PoolActions(flashLoanVault).flash(
                address(this),
                isToken0 ? flashAmounts[0] : 0,
                isToken0 ? 0 : flashAmounts[0],
                abi.encode(flashAssets[0], flashAmounts[0], isToken0)
            );
        } else {
            // --------------- Default flash loan Balancer v2, paid. The strategy should support IFlashLoanRecipient
            IBVault(flashLoanVault).flashLoan(address(this), flashAssets, flashAmounts, "");
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * https://eips.ethereum.org/EIPS/eip-214#specification
 * From the specification:
 * > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead
 * throw an exception.
 * > These operations include [...], LOG0, LOG1, LOG2, [...]
 *
 * therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works)
 * solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it
 */
contract SupportsInterfaceWithLookupMock is IERC165 {
    /*
     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
     */
    bytes4 public constant INTERFACE_ID_ERC165 = 0x01ffc9a7;

    /**
     * @dev A mapping of interface id to whether or not it's supported.
     */
    mapping(bytes4 interfaceId => bool) private _supportedInterfaces;

    /**
     * @dev A contract implementing SupportsInterfaceWithLookup
     * implement ERC165 itself.
     */
    constructor() {
        _registerInterface(INTERFACE_ID_ERC165);
    }

    /**
     * @dev Implement supportsInterface(bytes4) using a lookup table.
     */
    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        return _supportedInterfaces[interfaceId];
    }

    /**
     * @dev Private method for registering an interface.
     */
    function _registerInterface(bytes4 interfaceId) internal {
        require(interfaceId != 0xffffffff, "ERC165InterfacesSupported: invalid interface id");
        _supportedInterfaces[interfaceId] = true;
    }
}

contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock {
    constructor(bytes4[] memory interfaceIds) {
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            _registerInterface(interfaceIds[i]);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

File 23 of 41 : ConstantsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

library ConstantsLib {
    uint internal constant DENOMINATOR = 100_000;
    address internal constant DEAD_ADDRESS = 0xdEad000000000000000000000000000000000000;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ConstantsLib.sol";

library CommonLib {
    function filterAddresses(
        address[] memory addresses,
        address addressToRemove
    ) external pure returns (address[] memory filteredAddresses) {
        uint len = addresses.length;
        uint newLen;
        // nosemgrep
        for (uint i; i < len; ++i) {
            if (addresses[i] != addressToRemove) {
                ++newLen;
            }
        }
        filteredAddresses = new address[](newLen);
        uint k;
        // nosemgrep
        for (uint i; i < len; ++i) {
            if (addresses[i] != addressToRemove) {
                filteredAddresses[k] = addresses[i];
                ++k;
            }
        }
    }

    function formatUsdAmount(uint amount) external pure returns (string memory formattedPrice) {
        uint dollars = amount / 10 ** 18;
        string memory priceStr;
        if (dollars >= 1000) {
            uint kDollars = dollars / 1000;
            uint kDollarsFraction = (dollars - kDollars * 1000) / 10;
            string memory delimiter = ".";
            if (kDollarsFraction < 10) {
                delimiter = ".0";
            }
            priceStr = string.concat(Strings.toString(kDollars), delimiter, Strings.toString(kDollarsFraction), "k");
        } else if (dollars >= 100) {
            priceStr = Strings.toString(dollars);
        } else {
            uint dollarsFraction = (amount - dollars * 10 ** 18) / 10 ** 14;
            if (dollarsFraction > 0) {
                string memory dollarsFractionDelimiter = ".";
                if (dollarsFraction < 10) {
                    dollarsFractionDelimiter = ".000";
                } else if (dollarsFraction < 100) {
                    dollarsFractionDelimiter = ".00";
                } else if (dollarsFraction < 1000) {
                    dollarsFractionDelimiter = ".0";
                }
                priceStr = string.concat(
                    Strings.toString(dollars), dollarsFractionDelimiter, Strings.toString(dollarsFraction)
                );
            } else {
                priceStr = Strings.toString(dollars);
            }
        }

        formattedPrice = string.concat("$", priceStr);
    }

    function formatApr(uint apr) external pure returns (string memory formattedApr) {
        uint aprInt = apr * 100 / ConstantsLib.DENOMINATOR;
        uint aprFraction = (apr - aprInt * ConstantsLib.DENOMINATOR / 100) / 10;
        string memory delimiter = ".";
        if (aprFraction < 10) {
            delimiter = ".0";
        }
        formattedApr = string.concat(Strings.toString(aprInt), delimiter, Strings.toString(aprFraction), "%");
    }

    function formatAprInt(int apr) external pure returns (string memory formattedApr) {
        int aprInt = apr * 100 / int(ConstantsLib.DENOMINATOR);
        int aprFraction = (apr - aprInt * int(ConstantsLib.DENOMINATOR) / 100) / 10;
        string memory delimiter = ".";
        if (aprFraction < 10 || aprFraction > -10) {
            delimiter = ".0";
        }
        formattedApr = string.concat(i2s2(aprInt), delimiter, i2s(aprFraction), "%");
    }

    function implodeSymbols(
        address[] memory assets,
        string memory delimiter
    ) external view returns (string memory outString) {
        return implode(getSymbols(assets), delimiter);
    }

    function implode(string[] memory strings, string memory delimiter) public pure returns (string memory outString) {
        uint len = strings.length;
        if (len == 0) {
            return "";
        }
        outString = strings[0];
        // nosemgrep
        for (uint i = 1; i < len; ++i) {
            outString = string.concat(outString, delimiter, strings[i]);
        }
        return outString;
    }

    function getSymbols(address[] memory assets) public view returns (string[] memory symbols) {
        uint len = assets.length;
        symbols = new string[](len);
        // nosemgrep
        for (uint i; i < len; ++i) {
            symbols[i] = IERC20Metadata(assets[i]).symbol();
        }
    }

    function bytesToBytes32(bytes memory b) external pure returns (bytes32 out) {
        // nosemgrep
        for (uint i; i < b.length; ++i) {
            out |= bytes32(b[i] & 0xFF) >> (i * 8);
        }
        // return out;
    }

    function bToHex(bytes memory buffer) external pure returns (string memory) {
        // Fixed buffer size for hexadecimal convertion
        bytes memory converted = new bytes(buffer.length * 2);
        bytes memory _base = "0123456789abcdef";
        uint baseLength = _base.length;
        // nosemgrep
        for (uint i; i < buffer.length; ++i) {
            converted[i * 2] = _base[uint8(buffer[i]) / baseLength];
            converted[i * 2 + 1] = _base[uint8(buffer[i]) % baseLength];
        }
        return string(abi.encodePacked(converted));
    }

    function shortId(string memory id) external pure returns (string memory) {
        uint words = 1;
        bytes memory idBytes = bytes(id);
        uint idBytesLength = idBytes.length;
        // nosemgrep
        for (uint i; i < idBytesLength; ++i) {
            if (keccak256(bytes(abi.encodePacked(idBytes[i]))) == keccak256(bytes(" "))) {
                ++words;
            }
        }
        bytes memory _shortId = new bytes(words);
        uint k = 1;
        _shortId[0] = idBytes[0];
        // nosemgrep
        for (uint i = 1; i < idBytesLength; ++i) {
            if (keccak256(bytes(abi.encodePacked(idBytes[i]))) == keccak256(bytes(" "))) {
                if (keccak256(bytes(abi.encodePacked(idBytes[i + 1]))) == keccak256(bytes("0"))) {
                    _shortId[k] = idBytes[i + 3];
                } else {
                    _shortId[k] = idBytes[i + 1];
                }
                ++k;
            }
        }
        return string(abi.encodePacked(_shortId));
    }

    function eq(string memory a, string memory b) external pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }

    function u2s(uint num) external pure returns (string memory) {
        return Strings.toString(num);
    }

    function i2s(int num) public pure returns (string memory) {
        return Strings.toString(num > 0 ? uint(num) : uint(-num));
    }

    function i2s2(int num) public pure returns (string memory) {
        if (num >= 0) {
            return Strings.toString(uint(num));
        }
        return string.concat("-", Strings.toString(uint(-num)));
    }
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

/// @notice The vaults are assembled at the factory by users through UI.
///         Deployment rights of a vault are tokenized in VaultManager NFT.
///         The holders of these tokens receive a share of the vault revenue and can manage vault if possible.
/// @dev Rewards transfers to token owner or revenue receiver address managed by token owner.
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IVaultManager is IERC721Metadata {
    //region ----- Events -----
    event ChangeVaultParams(uint tokenId, address[] addresses, uint[] nums);
    event SetRevenueReceiver(uint tokenId, address receiver);
    //endregion -- Events -----

    struct VaultData {
        // vault
        uint tokenId;
        address vault;
        string vaultType;
        string name;
        string symbol;
        string[] assetsSymbols;
        string[] rewardAssetsSymbols;
        uint sharePrice;
        uint tvl;
        uint totalApr;
        bytes32 vaultExtra;
        // strategy
        uint strategyTokenId;
        string strategyId;
        string strategySpecific;
        uint strategyApr;
        bytes32 strategyExtra;
    }

    //region ----- View functions -----

    /// @notice Vault address managed by token
    /// @param tokenId ID of NFT. Starts from 0 and increments on mints.
    /// @return vault Address of vault proxy
    function tokenVault(uint tokenId) external view returns (address vault);

    /// @notice Receiver of token owner's platform revenue share
    /// @param tokenId ID of NFT
    /// @return receiver Address of vault manager fees receiver
    function getRevenueReceiver(uint tokenId) external view returns (address receiver);

    /// @notice All vaults data.
    /// DEPRECATED: use IFrontend.vaults
    /// The output values are matched by index in the arrays.
    /// @param vaultAddress Vault addresses
    /// @param name Vault name
    /// @param symbol Vault symbol
    /// @param vaultType Vault type ID string
    /// @param strategyId Strategy logic ID string
    /// @param sharePrice Current vault share price in USD. 18 decimals
    /// @param tvl Current vault TVL in USD. 18 decimals
    /// @param totalApr Last total vault APR. Denominator is 100_00.
    /// @param strategyApr Last strategy APR. Denominator is 100_00.
    /// @param strategySpecific Strategy specific name
    function vaults()
        external
        view
        returns (
            address[] memory vaultAddress,
            string[] memory name,
            string[] memory symbol,
            string[] memory vaultType,
            string[] memory strategyId,
            uint[] memory sharePrice,
            uint[] memory tvl,
            uint[] memory totalApr,
            uint[] memory strategyApr,
            string[] memory strategySpecific
        );

    /// @notice All deployed vault addresses
    /// @return vaultAddress Addresses of vault proxy
    function vaultAddresses() external view returns (address[] memory vaultAddress);

    /// @notice Vault extended info getter
    /// @param vault Address of vault proxy
    /// @return strategy
    /// @return strategyAssets
    /// @return underlying
    /// @return assetsWithApr Assets with underlying APRs that can be provided by AprOracle
    /// @return assetsAprs APRs of assets with APR. Matched by index wuth previous param.
    /// @return lastHardWork Last HardWork time
    function vaultInfo(address vault)
        external
        view
        returns (
            address strategy,
            address[] memory strategyAssets,
            address underlying,
            address[] memory assetsWithApr,
            uint[] memory assetsAprs,
            uint lastHardWork
        );

    //endregion -- View functions -----

    //region ----- Write functions -----

    /// @notice Changing managed vault init parameters by Vault Manager (owner of VaultManager NFT)
    /// @param tokenId ID of VaultManager NFT
    /// @param addresses Vault init addresses. Must contain also not changeable init addresses
    /// @param nums Vault init numbers. Must contant also not changeable init numbers
    function changeVaultParams(uint tokenId, address[] memory addresses, uint[] memory nums) external;

    /// @notice Minting of new token on deploying vault by Factory
    /// Only Factory can call this.
    /// @param to User which creates vault
    /// @param vault Address of vault proxy
    /// @return tokenId Minted token ID
    function mint(address to, address vault) external returns (uint tokenId);

    /// @notice Owner of token can change revenue reciever of platform fee share
    /// @param tokenId Owned token ID
    /// @param receiver New revenue receiver address
    function setRevenueReceiver(uint tokenId, address receiver) external;

    //endregion -- Write functions -----
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/// @notice Creating vaults, upgrading vaults and strategies, vault list, farms and strategy logics management
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
/// @author HCrypto7 (https://github.com/hcrypto7)
interface IFactory {
    //region ----- Custom Errors -----

    error VaultImplementationIsNotAvailable();
    error VaultNotAllowedToDeploy();
    error StrategyImplementationIsNotAvailable();
    error StrategyLogicNotAllowedToDeploy();
    error YouDontHaveEnoughTokens(uint userBalance, uint requireBalance, address payToken);
    error SuchVaultAlreadyDeployed(bytes32 key);
    error NotActiveVault();
    error UpgradeDenied(bytes32 _hash);
    error AlreadyLastVersion(bytes32 _hash);
    error NotStrategy();
    error BoostDurationTooLow();
    error BoostAmountTooLow();
    error BoostAmountIsZero();

    //endregion ----- Custom Errors -----

    //region ----- Events -----

    event VaultAndStrategy(
        address indexed deployer,
        string vaultType,
        string strategyId,
        address vault,
        address strategy,
        string name,
        string symbol,
        address[] assets,
        bytes32 deploymentKey,
        uint vaultManagerTokenId
    );
    event StrategyProxyUpgraded(address proxy, address oldImplementation, address newImplementation);
    event VaultProxyUpgraded(address proxy, address oldImplementation, address newImplementation);
    event VaultConfigChanged(
        string type_, address implementation, bool deployAllowed, bool upgradeAllowed, bool newVaultType
    );
    event StrategyLogicConfigChanged(
        string id, address implementation, bool deployAllowed, bool upgradeAllowed, bool newStrategy
    );
    event VaultStatus(address indexed vault, uint newStatus);
    event NewFarm(Farm[] farms);
    event UpdateFarm(uint id, Farm farm);
    event SetStrategyAvailableInitParams(string id, address[] initAddresses, uint[] initNums, int24[] initTicks);
    event AliasNameChanged(address indexed operator, address indexed tokenAddress, string newAliasName);

    //endregion -- Events -----

    //region ----- Data types -----

    /// @custom:storage-location erc7201:stability.Factory
    struct FactoryStorage {
        /// @inheritdoc IFactory
        mapping(bytes32 typeHash => VaultConfig) vaultConfig;
        /// @inheritdoc IFactory
        mapping(bytes32 idHash => StrategyLogicConfig) strategyLogicConfig;
        /// @inheritdoc IFactory
        mapping(bytes32 deploymentKey => address vaultProxy) deploymentKey;
        /// @inheritdoc IFactory
        mapping(address vault => uint status) vaultStatus;
        /// @inheritdoc IFactory
        mapping(address address_ => bool isStrategy_) isStrategy;
        EnumerableSet.Bytes32Set vaultTypeHashes;
        EnumerableSet.Bytes32Set strategyLogicIdHashes;
        mapping(uint week => mapping(uint builderPermitTokenId => uint vaultsBuilt)) vaultsBuiltByPermitTokenId;
        address[] deployedVaults;
        Farm[] farms;
        /// @inheritdoc IFactory
        mapping(bytes32 idHash => StrategyAvailableInitParams) strategyAvailableInitParams;
        mapping(address tokenAddress => string aliasName) aliasNames;
    }

    struct VaultConfig {
        string vaultType;
        address implementation;
        bool deployAllowed;
        bool upgradeAllowed;
        uint buildingPrice;
    }

    struct StrategyLogicConfig {
        string id;
        address implementation;
        bool deployAllowed;
        bool upgradeAllowed;
        bool farming;
        uint tokenId;
    }

    struct Farm {
        uint status;
        address pool;
        string strategyLogicId;
        address[] rewardAssets;
        address[] addresses;
        uint[] nums;
        int24[] ticks;
    }

    struct StrategyAvailableInitParams {
        address[] initAddresses;
        uint[] initNums;
        int24[] initTicks;
    }

    //endregion -- Data types -----

    //region ----- View functions -----

    /// @notice All vaults deployed by the factory
    /// @return Vault proxy addresses
    function deployedVaults() external view returns (address[] memory);

    /// @notice Total vaults deployed
    function deployedVaultsLength() external view returns (uint);

    /// @notice Get vault by VaultManager tokenId
    /// @param id Vault array index. Same as tokenId of VaultManager NFT
    /// @return Address of VaultProxy
    function deployedVault(uint id) external view returns (address);

    /// @notice All farms known by the factory in current network
    function farms() external view returns (Farm[] memory);

    /// @notice Total farms known by the factory in current network
    function farmsLength() external view returns (uint);

    /// @notice Farm data by farm index
    /// @param id Index of farm
    function farm(uint id) external view returns (Farm memory);

    /// @notice Strategy logic settings
    /// @param idHash keccak256 hash of strategy logic string ID
    /// @return config Strategy logic settings
    function strategyLogicConfig(bytes32 idHash) external view returns (StrategyLogicConfig memory config);

    /// @notice All known strategies
    /// @return Array of keccak256 hashes of strategy logic string ID
    function strategyLogicIdHashes() external view returns (bytes32[] memory);

    // todo remove, use new function without calculating vault symbol on the fly for not initialized vaults
    // factory required that special functionally only internally, not for interface
    function getStrategyData(
        string memory vaultType,
        address strategyAddress,
        address bbAsset
    )
        external
        view
        returns (
            string memory strategyId,
            address[] memory assets,
            string[] memory assetsSymbols,
            string memory specificName,
            string memory vaultSymbol
        );

    /// @dev Get best asset of assets to be strategy exchange asset
    function getExchangeAssetIndex(address[] memory assets) external view returns (uint);

    /// @notice Deployment key of created vault
    /// @param deploymentKey_ Hash of concatenated unique vault and strategy initialization parameters
    /// @return Address of deployed vault
    function deploymentKey(bytes32 deploymentKey_) external view returns (address);

    /// @notice Calculating deployment key based on unique vault and strategy initialization parameters
    /// @param vaultType Vault type string
    /// @param strategyId Strategy logic Id string
    /// @param vaultInitAddresses Vault initialization addresses for deployVaultAndStrategy method
    /// @param vaultInitNums Vault initialization uint numbers for deployVaultAndStrategy method
    /// @param strategyInitAddresses Strategy initialization addresses for deployVaultAndStrategy method
    /// @param strategyInitNums Strategy initialization uint numbers for deployVaultAndStrategy method
    /// @param strategyInitTicks Strategy initialization int24 ticks for deployVaultAndStrategy method
    function getDeploymentKey(
        string memory vaultType,
        string memory strategyId,
        address[] memory vaultInitAddresses,
        uint[] memory vaultInitNums,
        address[] memory strategyInitAddresses,
        uint[] memory strategyInitNums,
        int24[] memory strategyInitTicks
    ) external view returns (bytes32);

    /// @notice Available variants of new vault for creating.
    /// DEPRECATED: use IFrontend.whatToBuild
    /// The structure of the function's output values is complex,
    /// but after parsing them, the front end has all the data to generate a list of vaults to create.
    /// @return desc Descriptions of the strategy for making money
    /// @return vaultType Vault type strings. Output values are matched by index with previous array.
    /// @return strategyId Strategy logic ID strings. Output values are matched by index with previous array.
    /// @return initIndexes Map of start and end indexes in next 5 arrays. Output values are matched by index with previous array.
    ///                 [0] Start index in vaultInitAddresses
    ///                 [1] End index in vaultInitAddresses
    ///                 [2] Start index in vaultInitNums
    ///                 [3] End index in vaultInitNums
    ///                 [4] Start index in strategyInitAddresses
    ///                 [5] End index in strategyInitAddresses
    ///                 [6] Start index in strategyInitNums
    ///                 [7] End index in strategyInitNums
    ///                 [8] Start index in strategyInitTicks
    ///                 [9] End index in strategyInitTicks
    /// @return vaultInitAddresses Vault initialization addresses for deployVaultAndStrategy method for all building variants.
    /// @return vaultInitNums Vault initialization uint numbers for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitAddresses Strategy initialization addresses for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitNums Strategy initialization uint numbers for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitTicks Strategy initialization int24 ticks for deployVaultAndStrategy method for all building variants.
    function whatToBuild()
        external
        view
        returns (
            string[] memory desc,
            string[] memory vaultType,
            string[] memory strategyId,
            uint[10][] memory initIndexes,
            address[] memory vaultInitAddresses,
            uint[] memory vaultInitNums,
            address[] memory strategyInitAddresses,
            uint[] memory strategyInitNums,
            int24[] memory strategyInitTicks
        );

    /// @notice Governance and multisig can set a vault status other than Active - the default status.
    /// HardWorker only works with active vaults.
    /// @return status Constant from VaultStatusLib
    function vaultStatus(address vault) external view returns (uint status);

    /// @notice Check that strategy proxy deployed by the Factory
    /// @param address_ Address of contract
    /// @return This address is our strategy proxy
    function isStrategy(address address_) external view returns (bool);

    /// @notice How much vaults was built by builderPermitToken NFT tokenId in week
    /// @param week Week index (timestamp / (86400 * 7))
    /// @param builderPermitTokenId Token ID of buildingPermitToken NFT
    /// @return vaultsBuilt Vaults built
    function vaultsBuiltByPermitTokenId(
        uint week,
        uint builderPermitTokenId
    ) external view returns (uint vaultsBuilt);

    /// @notice Data on all factory strategies.
    /// The output values are matched by index in the arrays.
    /// @return id Strategy logic ID strings
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Strategy can be upgraded
    /// @return farming It is farming strategy (earns farming/gauge rewards)
    /// @return tokenId Token ID of StrategyLogic NFT
    /// @return tokenURI StrategyLogic NFT tokenId metadata and on-chain image
    /// @return extra Strategy color, background color and other extra data
    function strategies()
        external
        view
        returns (
            string[] memory id,
            bool[] memory deployAllowed,
            bool[] memory upgradeAllowed,
            bool[] memory farming,
            uint[] memory tokenId,
            string[] memory tokenURI,
            bytes32[] memory extra
        );

    /// @notice Get config of vault type
    /// @param typeHash Keccak256 hash of vault type string
    /// @return vaultType Vault type string
    /// @return implementation Vault implementation address
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Vaults can be upgraded
    /// @return buildingPrice Price of building new vault
    function vaultConfig(bytes32 typeHash)
        external
        view
        returns (
            string memory vaultType,
            address implementation,
            bool deployAllowed,
            bool upgradeAllowed,
            uint buildingPrice
        );

    /// @notice Data on all factory vault types
    /// The output values are matched by index in the arrays.
    /// @return vaultType Vault type string
    /// @return implementation Address of vault implemented logic
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Vaults can be upgraded
    /// @return buildingPrice  Price of building new vault
    /// @return extra Vault type color, background color and other extra data
    function vaultTypes()
        external
        view
        returns (
            string[] memory vaultType,
            address[] memory implementation,
            bool[] memory deployAllowed,
            bool[] memory upgradeAllowed,
            uint[] memory buildingPrice,
            bytes32[] memory extra
        );

    /// @notice Initialization strategy params store
    function strategyAvailableInitParams(bytes32 idHash) external view returns (StrategyAvailableInitParams memory);

    /// @notice Retrieves the alias name associated with a given address
    /// @param tokenAddress_ The address to query for its alias name
    /// @return The alias name associated with the provided address
    function getAliasName(address tokenAddress_) external view returns (string memory);

    //endregion -- View functions -----

    //region ----- Write functions -----

    /// @notice Main method of the Factory - new vault creation by user.
    /// @param vaultType Vault type ID string
    /// @param strategyId Strategy logic ID string
    /// Different types of vaults and strategies have different lengths of input arrays.
    /// @param vaultInitAddresses Addresses for vault initialization
    /// @param vaultInitNums Numbers for vault initialization
    /// @param strategyInitAddresses Addresses for strategy initialization
    /// @param strategyInitNums Numbers for strategy initialization
    /// @param strategyInitTicks Ticks for strategy initialization
    /// @return vault Deployed VaultProxy address
    /// @return strategy Deployed StrategyProxy address
    function deployVaultAndStrategy(
        string memory vaultType,
        string memory strategyId,
        address[] memory vaultInitAddresses,
        uint[] memory vaultInitNums,
        address[] memory strategyInitAddresses,
        uint[] memory strategyInitNums,
        int24[] memory strategyInitTicks
    ) external returns (address vault, address strategy);

    /// @notice Upgrade vault proxy. Can be called by any address.
    /// @param vault Address of vault proxy for upgrade
    function upgradeVaultProxy(address vault) external;

    /// @notice Upgrade strategy proxy. Can be called by any address.
    /// @param strategy Address of strategy proxy for upgrade
    function upgradeStrategyProxy(address strategy) external;

    /// @notice Add farm to factory
    /// @param farms_ Settings and data required to work with the farm.
    function addFarms(Farm[] memory farms_) external;

    /// @notice Update farm
    /// @param id Farm index
    /// @param farm_ Settings and data required to work with the farm.
    function updateFarm(uint id, Farm memory farm_) external;

    /// @notice Initial addition or change of vault type settings.
    /// Operator can add new vault type. Governance or multisig can change existing vault type config.
    /// @param vaultConfig_ Vault type settings
    function setVaultConfig(VaultConfig memory vaultConfig_) external;

    /// @notice Initial addition or change of strategy logic settings.
    /// Operator can add new strategy logic. Governance or multisig can change existing logic config.
    /// @param config Strategy logic settings
    /// @param developer Strategy developer is receiver of minted StrategyLogic NFT on initial addition
    function setStrategyLogicConfig(StrategyLogicConfig memory config, address developer) external;

    /// @notice Governance and multisig can set a vault status other than Active - the default status.
    /// @param vaults Addresses of vault proxy
    /// @param statuses New vault statuses. Constant from VaultStatusLib
    function setVaultStatus(address[] memory vaults, uint[] memory statuses) external;

    /// @notice Initial addition or change of strategy available init params
    /// @param id Strategy ID string
    /// @param initParams Init params variations that will be parsed by strategy
    function setStrategyAvailableInitParams(string memory id, StrategyAvailableInitParams memory initParams) external;

    /// @notice Assigns a new alias name to a specific address
    /// @dev This function may require certain permissions to be called successfully.
    /// @param tokenAddress_ The address to assign an alias name to
    /// @param aliasName_ The alias name to assign to the given address
    function setAliasName(address tokenAddress_, string memory aliasName_) external;

    //endregion -- Write functions -----
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

/// @notice On-chain price quoter and swapper by predefined routes
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
/// @author 0xhokugava (https://github.com/0xhokugava)
interface ISwapper {
    event Swap(address indexed tokenIn, address indexed tokenOut, uint amount);
    event PoolAdded(PoolData poolData, bool assetAdded);
    event PoolRemoved(address token);
    event BlueChipAdded(PoolData poolData);
    event ThresholdChanged(address[] tokenIn, uint[] thresholdAmount);
    event BlueChipPoolRemoved(address tokenIn, address tokenOut);

    //region ----- Custom Errors -----
    error UnknownAMMAdapter();
    error LessThenThreshold(uint minimumAmount);
    error NoRouteFound();
    error NoRoutesForAssets();
    //endregion -- Custom Errors -----

    struct PoolData {
        address pool;
        address ammAdapter;
        address tokenIn;
        address tokenOut;
    }

    struct AddPoolData {
        address pool;
        string ammAdapterId;
        address tokenIn;
        address tokenOut;
    }

    /// @notice All assets in pools added to Swapper
    /// @return Addresses of assets
    function assets() external view returns (address[] memory);

    /// @notice All blue chip assets in blue chip pools added to Swapper
    /// @return Addresses of blue chip assets
    function bcAssets() external view returns (address[] memory);

    /// @notice All assets in Swapper
    /// @return Addresses of assets and blue chip assets
    function allAssets() external view returns (address[] memory);

    /// @notice Add pools with largest TVL
    /// @param pools Largest pools with AMM adapter addresses
    /// @param rewrite Rewrite pool for tokenIn
    function addPools(PoolData[] memory pools, bool rewrite) external;

    /// @notice Add pools with largest TVL
    /// @param pools Largest pools with AMM adapter ID string
    /// @param rewrite Rewrite pool for tokenIn
    function addPools(AddPoolData[] memory pools, bool rewrite) external;

    /// @notice Add largest pools with the most popular tokens on the current network
    /// @param pools_ PoolData array with pool, tokens and AMM adapter address
    /// @param rewrite Change exist pool records
    function addBlueChipsPools(PoolData[] memory pools_, bool rewrite) external;

    /// @notice Add largest pools with the most popular tokens on the current network
    /// @param pools_ AddPoolData array with pool, tokens and AMM adapter string ID
    /// @param rewrite Change exist pool records
    function addBlueChipsPools(AddPoolData[] memory pools_, bool rewrite) external;

    /// @notice Retrieves pool data for a specified token swap in Blue Chip Pools.
    /// @dev This function provides information about the pool associated with the specified input and output tokens.
    /// @param tokenIn The input token address.
    /// @param tokenOut The output token address.
    /// @return poolData The data structure containing information about the Blue Chip Pool.
    /// @custom:opcodes view
    function blueChipsPools(address tokenIn, address tokenOut) external view returns (PoolData memory poolData);

    /// @notice Set swap threshold for token
    /// @dev Prevents dust swap.
    /// @param tokenIn Swap input token
    /// @param thresholdAmount Minimum amount of token for executing swap
    function setThresholds(address[] memory tokenIn, uint[] memory thresholdAmount) external;

    /// @notice Swap threshold for token
    /// @param token Swap input token
    /// @return threshold_ Minimum amount of token for executing swap
    function threshold(address token) external view returns (uint threshold_);

    /// @notice Price of given tokenIn against tokenOut
    /// @param tokenIn Swap input token
    /// @param tokenOut Swap output token
    /// @param amount Amount of tokenIn. If provide zero then amount is 1.0.
    /// @return Amount of tokenOut with decimals of tokenOut
    function getPrice(address tokenIn, address tokenOut, uint amount) external view returns (uint);

    /// @notice Return price the first poolData.tokenIn against the last poolData.tokenOut in decimals of tokenOut.
    /// @param route Array of pool address, swapper address tokenIn, tokenOut
    /// @param amount Amount of tokenIn. If provide zero then amount is 1.0.
    function getPriceForRoute(PoolData[] memory route, uint amount) external view returns (uint);

    /// @notice Check possibility of swap tokenIn for tokenOut
    /// @param tokenIn Swap input token
    /// @param tokenOut Swap output token
    /// @return Swap route exists
    function isRouteExist(address tokenIn, address tokenOut) external view returns (bool);

    /// @notice Build route for swap. No reverts inside.
    /// @param tokenIn Swap input token
    /// @param tokenOut Swap output token
    /// @return route Array of pools for swap tokenIn to tokenOut. Zero length indicate an error.
    /// @return errorMessage Possible reason why the route was not found. Empty for success routes.
    function buildRoute(
        address tokenIn,
        address tokenOut
    ) external view returns (PoolData[] memory route, string memory errorMessage);

    /// @notice Sell tokenIn for tokenOut
    /// @dev Assume approve on this contract exist
    /// @param tokenIn Swap input token
    /// @param tokenOut Swap output token
    /// @param amount Amount of tokenIn for swap.
    /// @param priceImpactTolerance Price impact tolerance. Must include fees at least. Denominator is 100_000.
    function swap(address tokenIn, address tokenOut, uint amount, uint priceImpactTolerance) external;

    /// @notice Swap by predefined route
    /// @param route Array of pool address, swapper address tokenIn, tokenOut.
    /// TokenIn from first item will be swaped to tokenOut of last .
    /// @param amount Amount of first item tokenIn.
    /// @param priceImpactTolerance Price impact tolerance. Must include fees at least. Denominator is 100_000.
    function swapWithRoute(PoolData[] memory route, uint amount, uint priceImpactTolerance) external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

/// @dev Mostly this interface need for front-end and tests for interacting with farming strategies
/// @author JodsMigel (https://github.com/JodsMigel)
interface IFarmingStrategy {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event RewardsClaimed(uint[] amounts);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           ERRORS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error BadFarm();
    error IncorrectStrategyId();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.FarmingStrategyBase
    struct FarmingStrategyBaseStorage {
        /// @inheritdoc IFarmingStrategy
        uint farmId;
        address[] _rewardAssets;
        uint[] _rewardsOnBalance;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Index of the farm used by initialized strategy
    function farmId() external view returns (uint);

    /// @notice Strategy can earn money on farm now
    /// Some strategies can continue work and earn pool fees after ending of farm rewards.
    function canFarm() external view returns (bool);

    /// @notice Mechanics of receiving farming rewards
    function farmMechanics() external view returns (string memory);

    /// @notice Farming reward assets for claim and liquidate
    /// @return Addresses of farm reward ERC20 tokens
    function farmingAssets() external view returns (address[] memory);

    /// @notice Address of pool for staking asset/underlying
    function stakingPool() external view returns (address);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Update strategy farming reward assets from Factory
    /// Only operator can call this
    function refreshFarmingAssets() external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface IRevenueRouter {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event EpochFlip(uint periodEnded, uint totalStblRevenue);
    event NewUnit(uint unitIndex, string name, address feeTreasury);
    event UnitEpochRevenue(uint periodEnded, string unitName, uint stblRevenue);
    event ProcessUnitRevenue(uint unitIndex, uint stblGot);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error WaitForNewPeriod();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.RevenueRouter
    struct RevenueRouterStorage {
        address stbl;
        address xStbl;
        address xStaking;
        address feeTreasury;
        uint xShare;
        uint activePeriod;
        uint pendingRevenue;
        Unit[] units;
        address[] aavePools;
    }

    enum UnitType {
        Core,
        AaveMarkets,
        Assets
    }

    struct Unit {
        UnitType unitType;
        string name;
        uint pendingRevenue;
        address feeTreasury;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        GOV ACTIONS                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Add new Unit
    function addUnit(UnitType unitType, string calldata name, address feeTreasury) external;

    /// @notice Setup Aave pool list
    function setAavePools(address[] calldata pools) external;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       USER ACTIONS                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Update the epoch (period) -- callable once a week at >= Thursday 0 UTC
    /// @return newPeriod The new period
    function updatePeriod() external returns (uint newPeriod);

    /// @notice Process platform fee in form of an asset
    function processFeeAsset(address asset, uint amount) external;

    /// @notice Process platform fee in form of an vault shares
    function processFeeVault(address vault, uint amount) external;

    /// @notice Claim unit fees and swap to STBL
    function processUnitRevenue(uint unitIndex) external;

    /// @notice Claim units fees and swap to STBL
    function processUnitsRevenue() external;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      VIEW FUNCTIONS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice The period used for rewarding
    /// @return The block.timestamp divided by 1 week in seconds
    function getPeriod() external view returns (uint);

    /// @notice Current active period
    function activePeriod() external view returns (uint);

    /// @notice Accumulated STBL amount for next distribution by core unit (vault fees)
    function pendingRevenue() external view returns (uint);

    /// @notice Accumulated STBL amount for next distribution by unit
    function pendingRevenue(uint unitIndex) external view returns (uint);

    /// @notice Get Aave pool list to mintToTreasury calls
    function aavePools() external view returns (address[] memory);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IAsset {}

interface IBVault {
    // Internal Balance
    //
    // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
    // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
    // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
    // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
    //
    // Internal Balance management features batching, which means a single contract call can be used to perform multiple
    // operations of different kinds, with different senders and recipients, at once.

    /**
     * @dev Returns `user`'s Internal Balance for a set of tokens.
     */
    function getInternalBalance(address user, IERC20[] calldata tokens) external view returns (uint[] memory);

    /**
     * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
     * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
     * it lets integrators reuse a user's Vault allowance.
     *
     * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
     */
    function manageUserBalance(UserBalanceOp[] calldata ops) external payable;

    /**
     * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
     *  without manual WETH wrapping or unwrapping.
     */
    struct UserBalanceOp {
        UserBalanceOpKind kind;
        IAsset asset;
        uint amount;
        address sender;
        address payable recipient;
    }

    // There are four possible operations in `manageUserBalance`:
    //
    // - DEPOSIT_INTERNAL
    // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
    // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
    //
    // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
    // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
    // relevant for relayers).
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - WITHDRAW_INTERNAL
    // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
    //
    // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
    // it to the recipient as ETH.
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - TRANSFER_INTERNAL
    // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
    //
    // Reverts if the ETH sentinel value is passed.
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - TRANSFER_EXTERNAL
    // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
    // relayers, as it lets them reuse a user's Vault allowance.
    //
    // Reverts if the ETH sentinel value is passed.
    //
    // Emits an `ExternalBalanceTransfer` event.

    enum UserBalanceOpKind {
        DEPOSIT_INTERNAL,
        WITHDRAW_INTERNAL,
        TRANSFER_INTERNAL,
        TRANSFER_EXTERNAL
    }

    /**
     * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
     * interacting with Pools using Internal Balance.
     *
     * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
     * address.
     */
    event InternalBalanceChanged(address indexed user, IERC20 indexed token, int delta);

    /**
     * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
     */
    event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint amount);

    // Pools
    //
    // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
    // functionality:
    //
    //  - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
    // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
    // which increase with the number of registered tokens.
    //
    //  - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
    // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
    // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
    // independent of the number of registered tokens.
    //
    //  - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
    // minimal swap info Pools, these are called via IMinimalSwapInfoPool.

    enum PoolSpecialization {
        GENERAL,
        MINIMAL_SWAP_INFO,
        TWO_TOKEN
    }

    /**
     * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
     * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
     * changed.
     *
     * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
     * depending on the chosen specialization setting. This contract is known as the Pool's contract.
     *
     * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
     * multiple Pools may share the same contract.
     *
     * Emits a `PoolRegistered` event.
     */
    function registerPool(PoolSpecialization specialization) external returns (bytes32);

    /**
     * @dev Emitted when a Pool is registered by calling `registerPool`.
     */
    event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);

    /**
     * @dev Returns a Pool's contract address and specialization setting.
     */
    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);

    /**
     * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
     *
     * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
     * exit by receiving registered tokens, and can only swap registered tokens.
     *
     * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
     * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
     * ascending order.
     *
     * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
     * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
     * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
     * expected to be highly secured smart contracts with sound design principles, and the decision to register an
     * Asset Manager should not be made lightly.
     *
     * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
     * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
     * different Asset Manager.
     *
     * Emits a `TokensRegistered` event.
     */
    function registerTokens(bytes32 poolId, IERC20[] calldata tokens, address[] calldata assetManagers) external;

    /**
     * @dev Emitted when a Pool registers tokens by calling `registerTokens`.
     */
    event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);

    /**
     * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
     *
     * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
     * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
     * must be deregistered in the same `deregisterTokens` call.
     *
     * A deregistered token can be re-registered later on, possibly with a different Asset Manager.
     *
     * Emits a `TokensDeregistered` event.
     */
    function deregisterTokens(bytes32 poolId, IERC20[] calldata tokens) external;

    /**
     * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
     */
    event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);

    /**
     * @dev Returns detailed information for a Pool's registered token.
     *
     * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
     * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
     * equals the sum of `cash` and `managed`.
     *
     * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
     * `managed` or `total` balance to be greater than 2^112 - 1.
     *
     * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
     * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
     * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
     * change for this purpose, and will update `lastChangeBlock`.
     *
     * `assetManager` is the Pool's token Asset Manager.
     */
    function getPoolTokenInfo(
        bytes32 poolId,
        IERC20 token
    ) external view returns (uint cash, uint managed, uint lastChangeBlock, address assetManager);

    /**
     * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
     * the tokens' `balances` changed.
     *
     * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
     * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
     *
     * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
     * order as passed to `registerTokens`.
     *
     * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
     * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
     * instead.
     * renamed IERC20[] to address[]
     */
    function getPoolTokens(bytes32 poolId)
        external
        view
        returns (address[] memory tokens, uint[] memory balances, uint lastChangeBlock);

    /**
     * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
     * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
     * Pool shares.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
     * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
     * these maximums.
     *
     * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
     * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
     * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
     * back to the caller (not the sender, which is important for relayers).
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
     * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
     * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
     *
     * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
     * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
     * withdrawn from Internal Balance: attempting to do so will trigger a revert.
     *
     * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
     * directly to the Pool's contract, as is `recipient`.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function joinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        JoinPoolRequest calldata request
    ) external payable;

    enum JoinKind {
        INIT,
        EXACT_TOKENS_IN_FOR_BPT_OUT,
        TOKEN_IN_FOR_EXACT_BPT_OUT
    }
    enum ExitKind {
        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
        EXACT_BPT_IN_FOR_TOKENS_OUT,
        BPT_IN_FOR_EXACT_TOKENS_OUT
    }

    /// @dev modified to address[]
    struct JoinPoolRequest {
        address[] assets;
        uint[] maxAmountsIn;
        bytes userData;
        bool fromInternalBalance;
    }

    /**
     * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
     * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
     * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
     * `getPoolTokenInfo`).
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
     * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
     * it just enforces these minimums.
     *
     * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
     * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
     * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
     * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
     * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
     *
     * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
     * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
     * do so will trigger a revert.
     *
     * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
     * `tokens` array. This array must match the Pool's registered tokens.
     *
     * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
     * passed directly to the Pool's contract.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function exitPool(
        bytes32 poolId,
        address sender,
        address payable recipient,
        ExitPoolRequest calldata request
    ) external;

    /// @dev modified to address[]
    struct ExitPoolRequest {
        address[] assets;
        uint[] minAmountsOut;
        bytes userData;
        bool toInternalBalance;
    }

    /**
     * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
     */
    event PoolBalanceChanged(
        bytes32 indexed poolId,
        address indexed liquidityProvider,
        IERC20[] tokens,
        int[] deltas,
        uint[] protocolFeeAmounts
    );

    enum PoolBalanceChangeKind {
        JOIN,
        EXIT
    }

    // Swaps
    //
    // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
    // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
    // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
    //
    // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
    // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
    // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
    // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
    // individual swaps.
    //
    // There are two swap kinds:
    //  - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
    // `onSwap` hook) the amount of tokens out (to send to the recipient).
    //  - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
    // (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
    //
    // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
    // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
    // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
    // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
    // the final intended token.
    //
    // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
    // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
    // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
    // much less gas than they would otherwise.
    //
    // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
    // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
    // updating the Pool's internal accounting).
    //
    // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
    // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
    // minimum amount of tokens to receive (by passing a negative value) is specified.
    //
    // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
    // this point in time (e.g. if the transaction failed to be included in a block promptly).
    //
    // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
    // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
    // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
    // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
    //
    // Finally, Internal Balance can be used when either sending or receiving tokens.

    enum SwapKind {
        GIVEN_IN,
        GIVEN_OUT
    }

    /**
     * @dev Performs a swap with a single Pool.
     *
     * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
     * taken from the Pool, which must be greater than or equal to `limit`.
     *
     * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
     * sent to the Pool, which must be less than or equal to `limit`.
     *
     * Internal Balance usage and the recipient are determined by the `funds` struct.
     *
     * Emits a `Swap` event.
     */
    function swap(
        SingleSwap calldata singleSwap,
        FundManagement calldata funds,
        uint limit,
        uint deadline
    ) external payable returns (uint);

    /**
     * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
     * the `kind` value.
     *
     * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
     * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
     *
     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
     * used to extend swap behavior.
     */
    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        IAsset assetIn;
        IAsset assetOut;
        uint amount;
        bytes userData;
    }

    /**
     * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
     * the amount of tokens sent to or received from the Pool, depending on the `kind` value.
     *
     * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
     * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
     * the same index in the `assets` array.
     *
     * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
     * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
     * `amountOut` depending on the swap kind.
     *
     * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
     * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
     * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
     *
     * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
     * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
     * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
     * or unwrapped from WETH by the Vault.
     *
     * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
     * the minimum or maximum amount of each token the vault is allowed to transfer.
     *
     * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
     * equivalent `swap` call.
     *
     * Emits `Swap` events.
     */
    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] calldata swaps,
        IAsset[] calldata assets,
        FundManagement calldata funds,
        int[] calldata limits,
        uint deadline
    ) external payable returns (int[] memory);

    /**
     * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
     * `assets` array passed to that function, and ETH assets are converted to WETH.
     *
     * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
     * from the previous swap, depending on the swap kind.
     *
     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
     * used to extend swap behavior.
     */
    struct BatchSwapStep {
        bytes32 poolId;
        uint assetInIndex;
        uint assetOutIndex;
        uint amount;
        bytes userData;
    }

    /**
     * @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
     */
    event Swap(bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint amountIn, uint amountOut);

    /**
     * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
     * `recipient` account.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
     * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
     * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
     * `joinPool`.
     *
     * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
     * transferred. This matches the behavior of `exitPool`.
     *
     * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
     * revert.
     */
    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }

    /**
     * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
     * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
     *
     * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
     * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
     * receives are the same that an equivalent `batchSwap` call would receive.
     *
     * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
     * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
     * approve them for the Vault, or even know a user's address.
     *
     * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
     * eth_call instead of eth_sendTransaction.
     */
    function queryBatchSwap(
        SwapKind kind,
        BatchSwapStep[] calldata swaps,
        IAsset[] calldata assets,
        FundManagement calldata funds
    ) external returns (int[] memory assetDeltas);

    // BasePool.sol

    /**
     * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
     * Vault with the same arguments, along with the number of tokens `recipient` would receive.
     *
     * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
     * data, such as the protocol swap fee percentage and Pool balances.
     *
     * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
     * explicitly use eth_call instead of eth_sendTransaction.
     */
    function queryExit(
        bytes32 poolId,
        address sender,
        address recipient,
        uint[] memory balances,
        uint lastChangeBlock,
        uint protocolSwapFeePercentage,
        bytes memory userData
    ) external returns (uint bptIn, uint[] memory amountsOut);

    function flashLoan(
        address recipient,
        address[] memory tokens,
        uint[] memory amounts,
        bytes memory userData
    ) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @notice Restored from 0xbA1333333333a1BA1108E8412f11850A5C319bA9 (sonic)
interface IVaultMainV3 {
  struct TokenConfig {
    address token;
    uint8 tokenType;
    address rateProvider;
    bool paysYieldFees;
  }

  struct PoolRoleAccounts {
    address pauseManager;
    address swapFeeManager;
    address poolCreator;
  }

  struct HooksConfig {
    bool enableHookAdjustedAmounts;
    bool shouldCallBeforeInitialize;
    bool shouldCallAfterInitialize;
    bool shouldCallComputeDynamicSwapFee;
    bool shouldCallBeforeSwap;
    bool shouldCallAfterSwap;
    bool shouldCallBeforeAddLiquidity;
    bool shouldCallAfterAddLiquidity;
    bool shouldCallBeforeRemoveLiquidity;
    bool shouldCallAfterRemoveLiquidity;
    address hooksContract;
  }

  struct LiquidityManagement {
    bool disableUnbalancedLiquidity;
    bool enableAddLiquidityCustom;
    bool enableRemoveLiquidityCustom;
    bool enableDonation;
  }

  struct AddLiquidityParams {
    address pool;
    address to;
    uint256[] maxAmountsIn;
    uint256 minBptAmountOut;
    uint8 kind;
    bytes userData;
  }

  struct BufferWrapOrUnwrapParams {
    uint8 kind;
    uint8 direction;
    address wrappedToken;
    uint256 amountGivenRaw;
    uint256 limitRaw;
  }

  struct RemoveLiquidityParams {
    address pool;
    address from;
    uint256 maxBptAmountIn;
    uint256[] minAmountsOut;
    uint8 kind;
    bytes userData;
  }

  struct VaultSwapParams {
    uint8 kind;
    address pool;
    address tokenIn;
    address tokenOut;
    uint256 amountGivenRaw;
    uint256 limitRaw;
    bytes userData;
  }

  fallback() external payable;

  function addLiquidity(AddLiquidityParams memory params)
  external
  returns (
    uint256[] memory amountsIn,
    uint256 bptAmountOut,
    bytes memory returnData
  );

  function erc4626BufferWrapOrUnwrap(BufferWrapOrUnwrapParams memory params)
  external
  returns (
    uint256 amountCalculatedRaw,
    uint256 amountInRaw,
    uint256 amountOutRaw
  );

  function getPoolTokenCountAndIndexOfToken(address pool, address token)
  external
  view
  returns (uint256, uint256);

  function getVaultExtension() external view returns (address);

  function reentrancyGuardEntered() external view returns (bool);

  function removeLiquidity(RemoveLiquidityParams memory params)
  external
  returns (
    uint256 bptAmountIn,
    uint256[] memory amountsOut,
    bytes memory returnData
  );

  function sendTo(address token, address to, uint256 amount) external;

  function settle(address token, uint256 amountHint) external returns (uint256 credit);

  function swap(VaultSwapParams memory vaultSwapParams)
  external
  returns (
    uint256 amountCalculated,
    uint256 amountIn,
    uint256 amountOut
  );

  function transfer(address owner, address to, uint256 amount) external returns (bool);

  function transferFrom(address spender, address from, address to, uint256 amount) external returns (bool);

  /// @notice Creates a context for a sequence of operations (i.e., "unlocks" the Vault).
  /// @dev Performs a callback on msg.sender with arguments provided in `data`. The Callback is `transient`,
  /// meaning all balances for the caller have to be settled at the end.
  /// Implementation in balancer-v3-monorepo is following:
  ///     function unlock(bytes calldata data) external transient returns (bytes memory result) {
  ///        return (msg.sender).functionCall(data);
  ///    }
  /// @param data Contains function signature and args to be passed to the msg.sender
  /// @return result Resulting data from the call
  function unlock(bytes memory data) external returns (bytes memory result);

  receive() external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.23;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint amount0, uint amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint amount0, uint amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int amount0, int amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(address recipient, uint amount0, uint amount1, bytes calldata data) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.23;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

import {IERC721} from "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@solady/=lib/solady/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "solady/=lib/solady/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {
    "src/core/libs/CommonLib.sol": {
      "CommonLib": "0x72A237Cb9CAAF0716Bb4F717E32E79cE6460e5d3"
    },
    "src/strategies/libs/SiloLib.sol": {
      "SiloLib": "0xe2Dfa8E65571c578322B11fF6082584Ad90eC5E5"
    },
    "src/strategies/libs/StrategyLib.sol": {
      "StrategyLib": "0x0576aa66310720041fDe3acC8cecACdc874E600e"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"IncorrectMsgSender","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ltv","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"leverage","type":"uint256"}],"name":"LeverageLendingHealth","type":"event"},{"inputs":[],"name":"INTERNAL_PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"collateralAsset","type":"address"},{"internalType":"address","name":"borrowAsset","type":"address"},{"internalType":"address","name":"lendingVault","type":"address"},{"internalType":"address","name":"borrowingVault","type":"address"}],"internalType":"struct ILeverageLendingStrategy.LeverageLendingAddresses","name":"v","type":"tuple"}],"name":"calcTotal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"xWithdrawAmount","type":"uint256"},{"internalType":"uint256","name":"currentCollateralAmount","type":"uint256"},{"internalType":"uint256","name":"currentDebtAmount","type":"uint256"},{"internalType":"uint256","name":"initialBalanceC","type":"uint256"},{"internalType":"uint256","name":"alphaScaled","type":"uint256"},{"internalType":"uint256","name":"betaRateScaled","type":"uint256"}],"internalType":"struct SiloLib.LeverageCalcParams","name":"config","type":"tuple"},{"internalType":"uint256","name":"ltv","type":"uint256"},{"internalType":"uint256","name":"maxLtv","type":"uint256"}],"name":"calculateNewLeverage","outputs":[{"internalType":"uint256","name":"resultLeverage","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"platform","type":"address"},{"internalType":"address","name":"lendingVault","type":"address"},{"internalType":"address","name":"collateralAsset","type":"address"},{"internalType":"address","name":"borrowAsset","type":"address"},{"internalType":"address","name":"borrowingVault","type":"address"}],"name":"getDebtState","outputs":[{"components":[{"internalType":"uint256","name":"collateralPrice","type":"uint256"},{"internalType":"uint256","name":"borrowAssetPrice","type":"uint256"},{"internalType":"uint256","name":"totalCollateralUsd","type":"uint256"},{"internalType":"uint256","name":"borrowAssetUsd","type":"uint256"},{"internalType":"uint256","name":"collateralBalance","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"bool","name":"trusted","type":"bool"}],"internalType":"struct SiloLib.CollateralDebtState","name":"data","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"lendingVault","type":"address"},{"internalType":"uint256","name":"targetLeveragePercent","type":"uint256"}],"name":"getLtvData","outputs":[{"internalType":"uint256","name":"maxLtv","type":"uint256"},{"internalType":"uint256","name":"maxLeverage","type":"uint256"},{"internalType":"uint256","name":"targetLeverage","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"lendVault","type":"address"},{"internalType":"address","name":"debtVault","type":"address"}],"name":"getPrices","outputs":[{"internalType":"uint256","name":"priceCtoB","type":"uint256"},{"internalType":"uint256","name":"priceBtoC","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"lendingVault","type":"address"}],"name":"totalCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrowingVault","type":"address"}],"name":"totalDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

614535610034600b8282823980515f1a607314602857634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100fb575f3560e01c8063645871ab1161009e578063dd081d8b1161006e578063dd081d8b14610349578063f1d7a99314610377578063f35acdc514610396578063f91afc87146103a9575f5ffd5b8063645871ab1461020b5780637e059b22146102a2578063a24856f7146102b5578063b86c2a781461032a575f5ffd5b80631ff517ff116100d95780631ff517ff1461017c5780633cf7210d1461018f57806357477647146101b75780635bd923f5146101e3575f5ffd5b80630dcd3d68146100ff5780630f0b05941461012057806312eef52014610165575b5f5ffd5b81801561010a575f5ffd5b5061011e610119366004613993565b6103bc565b005b61013361012e3660046139e1565b6110e8565b604080519687526020870195909552938501929092526060840152608083015260a082015260c0015b60405180910390f35b61016e61271081565b60405190815260200161015c565b61016e61018a366004613a0b565b6113e1565b6101a261019d366004613a26565b611450565b6040805192835260208301919091520161015c565b8180156101c2575f5ffd5b506101d66101d1366004613a5d565b611858565b60405161015c9190613aaf565b6101f66101f13660046139e1565b611a5f565b6040805192835290151560208301520161015c565b61021e610219366004613c0a565b611abb565b60405161015c91905f61016082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015261010083015161010083015261012083015161012083015261014083015161014083015292915050565b61016e6102b0366004613a0b565b611c4b565b6102c86102c3366004613c46565b611ced565b60405161015c91905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e0830151151560e083015292915050565b818015610335575f5ffd5b5061016e610344366004613ca5565b61205c565b61035c6103573660046139e1565b61229e565b6040805193845260208401929092529082015260600161015c565b818015610382575f5ffd5b5061016e610391366004613d64565b6123ce565b61016e6103a4366004613e3b565b6125fa565b61016e6103b7366004613eb0565b6126a3565b5f6103c78585612708565b9050336001600160a01b038216146103f2576040516370a8bfcd60e11b815260040160405180910390fd5b6001600586810154600160a01b900460ff169081111561041457610414613eca565b036106b1576006850154600286015460405163b7ec8d4b60e01b81526001600160a01b039091169063b7ec8d4b906104559087903090600190600401613efe565b6020604051808303815f875af1158015610471573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104959190613f21565b506003860154604051633545906160e21b815260048101839052306024820181905260448201526001600160a01b039091169063d5164184906064016020604051808303815f875af11580156104ed573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105119190613f21565b50600186015460405163152cf14360e31b8152730576aa66310720041fde3acc8cecacdc874e600e9163a9678a189161055e918b916001600160a01b03909116908a908790600401613f38565b602060405180830381865af4158015610579573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061059d9190613f21565b506105bd826105ac8587613f76565b6001600160a01b0388169190612765565b600286015460405163e3d670d760e01b81526001600160a01b0387811660048301529091169063b7ec8d4b90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610623573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106479190613f21565b3060016040518463ffffffff1660e01b815260040161066893929190613efe565b6020604051808303815f875af1158015610684573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a89190613f21565b50505f60068601555b6002600586810154600160a01b900460ff16908111156106d3576106d3613eca565b03610a0a5784546007860154600387015460405163acb7081560e01b8152600481018790523060248201526001600160a01b03938416939091169063acb70815906044016020604051808303815f875af1158015610733573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107579190613f21565b5060028701546001600160a01b03165f61077082611c4b565b905061077e6103e882613f89565b6107889082613fa8565b9050816001600160a01b031663b8337c2a6107a385846127bc565b303060016040518563ffffffff1660e01b81526004016107c69493929190613fbb565b6020604051808303815f875af11580156107e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108069190613f21565b505060405163e3d670d760e01b81526001600160a01b0384166004820152730576aa66310720041fde3acc8cecacdc874e600e915063a9678a18908a9085908a9061089c908790879063e3d670d790602401602060405180830381865af4158015610873573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108979190613f21565b6127bc565b6040518563ffffffff1660e01b81526004016108bb9493929190613f38565b602060405180830381865af41580156108d6573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108fa9190613f21565b5061091a836109098688613f76565b6001600160a01b0389169190612765565b60405163e3d670d760e01b81526001600160a01b0387166004820152730576aa66310720041fde3acc8cecacdc874e600e9063a9678a18908a9089908690859063e3d670d790602401602060405180830381865af415801561097e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109a29190613f21565b6040518563ffffffff1660e01b81526004016109c19493929190613f38565b602060405180830381865af41580156109dc573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a009190613f21565b50505f6007870155505b6003600586810154600160a01b900460ff1690811115610a2c57610a2c613eca565b03610cd1576002850154600186015460405163152cf14360e31b81526001600160a01b0392831692730576aa66310720041fde3acc8cecacdc874e600e9263a9678a1892610a85928c928b929116908a90600401613f38565b602060405180830381865af4158015610aa0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ac49190613f21565b506003860154600187015460405163e3d670d760e01b81526001600160a01b03918216600482015291169063acb7081590730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610b2f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b539190613f21565b6040516001600160e01b031960e084901b16815260048101919091523060248201526044016020604051808303815f875af1158015610b94573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bb89190613f21565b5060405163e3d670d760e01b81526001600160a01b03861660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610c11573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c359190613f21565b610c3f8587613f76565b610c499190613fa8565b604051635c19be1560e11b81529091506001600160a01b0383169063b8337c2a90610c7f90849030908190600190600401613fbb565b6020604051808303815f875af1158015610c9b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cbf9190613f21565b50610cce836109098688613f76565b50505b6004600586810154600160a01b900460ff1690811115610cf357610cf3613eca565b03611078576006850154600286015460405163b7ec8d4b60e01b81526001600160a01b0390911690819063b7ec8d4b90610d369088903090600190600401613efe565b6020604051808303815f875af1158015610d52573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d769190613f21565b506003870154604051633545906160e21b815260048101849052306024820181905260448201526001600160a01b039091169063d5164184906064016020604051808303815f875af1158015610dce573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610df29190613f21565b5060018701546040516371a1ff0960e11b81526001600160a01b03808b16600483015291821660248201529087166044820152606481018390526103e86084820152730576aa66310720041fde3acc8cecacdc874e600e9063e343fe129060a401602060405180830381865af4158015610e6e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e929190613f21565b5060405163e3d670d760e01b81526001600160a01b03871660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610eeb573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f0f9190613f21565b90505f610f1c8688613f76565b8210610f28575f610f3d565b81610f338789613f76565b610f3d9190613fa8565b90508015610fbe57604051635c19be1560e11b81526001600160a01b0384169063b8337c2a90610f7890849030908190600190600401613fbb565b6020604051808303815f875af1158015610f94573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fb89190613f21565b5061104e565b5f610fc98789613f76565b610fd39084613fa8565b60028b015460405163b7ec8d4b60e01b81529192506001600160a01b03169063b7ec8d4b9061100b9084903090600190600401613efe565b6020604051808303815f875af1158015611027573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061104b9190613f21565b50505b61106d8561105c888a613f76565b6001600160a01b038b169190612765565b50505f600688015550505b5f5f61108488886110e8565b50505092505091507fb83dc6ff11ec1f33d17651f75f3998b69e170ade8f9072b116beaa5e6d037e1e82826040516110c6929190918252602082015260400190565b60405180910390a150505050600592909201805460ff60a01b19169055505050565b60028101548154600583015460405163f5125d3f60e01b81526001600160a01b03938416600482018190523060248301525f94859485948594859485949093811692169063f5125d3f90604401602060405180830381865afa158015611150573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111749190613f21565b9750670de0b6b3a764000061118b6127108a613fe6565b6111959190613f89565b97506111a082611c4b565b60405163e3d670d760e01b81526001600160a01b0383166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156111f6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061121a9190613f21565b6112249190613f76565b60038a015490955061123e906001600160a01b03166113e1565b93505f8a6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa15801561127d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112a1919061400d565b90505f6112ae8c8c611a5f565b506040516341976e0960e01b81526001600160a01b0385811660048301529192505f918416906341976e09906024016040805180830381865afa1580156112f7573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061131b9190614037565b5090505f846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561135b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061137f9190614061565b61138a90600a614164565b611394838b613fe6565b61139e9190613f89565b9050826113ad61271083613fe6565b6113b79190613f89565b99508c6008015496506113ca868861229e565b905050809b50505050505050509295509295509295565b604051635f30114960e01b81523060048201525f906001600160a01b03831690635f301149906024015b602060405180830381865afa158015611426573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144a9190613f21565b92915050565b5f5f5f846001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa15801561148f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b3919061400d565b60405163e48a5f7b60e01b81526001600160a01b0387811660048301529192505f9183169063e48a5f7b9060240161022060405180830381865afa1580156114fd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115219190614172565b60e081015160405163e48a5f7b60e01b81526001600160a01b03888116600483015292935090915f919085169063e48a5f7b9060240161022060405180830381865afa158015611573573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115979190614172565b60e08101519091506001600160a01b038316158015906115be57506001600160a01b038116155b156116d457826001600160a01b03166313b0be3385606001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116369190614061565b61164190600a614164565b60608701516040516001600160e01b031960e085901b16815260048101929092526001600160a01b03166024820152604401602060405180830381865afa15801561168e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116b29190613f21565b96506116cd876ec097ce7bc90715b34b9f1000000000613f89565b955061184c565b6001600160a01b0383161580156116f357506001600160a01b03811615155b1561180957806001600160a01b03166313b0be3383606001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611747573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061176b9190614061565b61177690600a614164565b60608501516040516001600160e01b031960e085901b16815260048101929092526001600160a01b03166024820152604401602060405180830381865afa1580156117c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e79190613f21565b9550611802866ec097ce7bc90715b34b9f1000000000613f89565b965061184c565b60405162461bcd60e51b8152602060048201526013602482015272139bdd081a5b5c1b195b595b9d1959081e595d606a1b60448201526064015b60405180910390fd5b50505050509250929050565b60605f611864866127d1565b90505f611872888884611abb565b805190915085111561188b5761188b8888848489612837565b815160405163e3d670d760e01b81526001600160a01b0390911660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156118e6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061190a9190613f21565b90505f611916846126a3565b6119209083613f76565b604080516001808252818301909252919250602080830190803683370190505094508083602001511115611994576119718184602001516119619190613fa8565b61196b9089613fa8565b836127bc565b855f815181106119835761198361428b565b6020026020010181815250506119d0565b6119b18360200151826119a79190613fa8565b61196b9089613f76565b855f815181106119c3576119c361428b565b6020026020010181815250505b6001600160a01b0386163014611a1a57611a1a86865f815181106119f6576119f661428b565b6020026020010151865f01516001600160a01b03166127659092919063ffffffff16565b86886001015f828254611a2d9190613fa8565b90915550506101008301516127101015611a5257611a5289858561010001518a61297d565b5050505095945050505050565b60028101548154600183015460038401545f9384938493611a949389936001600160a01b039081169381169281169116611ced565b905080606001518160400151611aaa9190613fa8565b92508060e001519150509250929050565b611b0d6040518061016001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b815160405163e3d670d760e01b81526001600160a01b039091166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611b66573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b8a9190613f21565b8152611b95826126a3565b8151611ba19190613f76565b6020820152611bb084846110e8565b50505050604080840192909252508201516008840154611bd0919061229e565b60a08401526080830152606080830191909152604083015190830151611bf69190611450565b50610140820152600b83015460e08201819052600c84015461010083015260158401546101208301525f03611c2e5761271060e08201525b8061010001515f03611c44576127106101008201525b9392505050565b60405163e3d670d760e01b81526001600160a01b038216600482018190525f916307a2d13a90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611cab573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ccf9190613f21565b6040518263ffffffff1660e01b815260040161140b91815260200190565b611d2f6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b5f5f5f886001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d6e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d92919061400d565b9050611d9d88611c4b565b60a085015260405163e3d670d760e01b81526001600160a01b0388166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611df8573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e1c9190613f21565b60808501526040516341976e0960e01b81526001600160a01b0388811660048301528216906341976e09906024016040805180830381865afa158015611e64573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e889190614037565b855f01819550828152505050866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ed0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ef49190614061565b611eff90600a614164565b8451608086015160a0870151611f159190613f76565b611f1f9190613fe6565b611f299190613f89565b6040850152611f37856113e1565b60c08501526040516341976e0960e01b81526001600160a01b0387811660048301528216906341976e09906024016040805180830381865afa158015611f7f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fa39190614037565b85602001819450828152505050856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611fec573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120109190614061565b61201b90600a614164565b84602001518560c0015161202f9190613fe6565b6120399190613f89565b60608501528280156120485750815b151560e08501525050505b95945050505050565b5f5f5f5f61206a87866110e8565b5050935050925092505f61207d866127d1565b90505f612089826126a3565b90505f61209889612710613fa8565b6120a461271084613fe6565b6120ae9190613f89565b6040805160018082528183019092529192505f919060208083019080368337019050509050835f0151815f815181106120e9576120e961428b565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f91816020016020820280368337019050509050878b10156121745760058a01805460ff60a01b1916600360a01b1790555f61214d8488613fa8565b905080825f815181106121625761216261428b565b60200260200101818152505050612235565b60058a01805460ff60a01b1916600160a21b1790555f6121948785613fa8565b90505f6121a987604001518860600151611450565b50905081835f815181106121bf576121bf61428b565b6020026020010181815250506002670de0b6b3a764000082670de0b6b3a76400008c875f815181106121f3576121f361428b565b60200260200101516122059190613fe6565b61220f9190613f89565b6122199190613fe6565b6122239190613f89565b61222d9190613fa8565b60068d015550505b6122638a60130154600381111561224e5761224e613eca565b60048c01546001600160a01b03168484612aab565b60058a01805460ff60a01b1916905561227c8c8b6110e8565b9091929350909192509091509050508099505050505050505050509392505050565b5f5f5f5f856001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156122de573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612302919061400d565b60405163e48a5f7b60e01b81526001600160a01b0388811660048301529192505f9183169063e48a5f7b9060240161022060405180830381865afa15801561234c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123709190614172565b6101408101519550905061238c85670de0b6b3a7640000613fa8565b6123a0612710670de0b6b3a7640000613fe6565b6123aa9190613f89565b93506127106123b98786613fe6565b6123c39190613f89565b925050509250925092565b5f5f6123d9866127d1565b90505f6123e5826126a3565b730576aa66310720041fde3acc8cecacdc874e600e63e3d670d7875f815181106124115761241161428b565b60200260200101516040518263ffffffff1660e01b815260040161244491906001600160a01b0391909116815260200190565b602060405180830381865af415801561245f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124839190613f21565b61248d9190613f76565b90506124b4878387875f815181106124a7576124a761428b565b6020026020010151612ec5565b5f6124be836126a3565b730576aa66310720041fde3acc8cecacdc874e600e63e3d670d7885f815181106124ea576124ea61428b565b60200260200101516040518263ffffffff1660e01b815260040161251d91906001600160a01b0391909116815260200190565b602060405180830381865af4158015612538573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255c9190613f21565b6125669190613f76565b9050818111156125a55761257a8282613fa8565b855f8151811061258c5761258c61428b565b602002602001015161259e9190613f76565b93506125d6565b6125af8183613fa8565b855f815181106125c1576125c161428b565b60200260200101516125d39190613fa8565b93505b83876001015f8282546125e99190613f76565b909155509398975050505050505050565b5f806126638561261286670de0b6b3a7640000613fa8565b61262b906ec097ce7bc90715b34b9f1000000000613f89565b61263d86670de0b6b3a7640000613fa8565b612656906ec097ce7bc90715b34b9f1000000000613f89565b662386f26fc10000612fd4565b9050801561269957670de0b6b3a764000061267e8683613071565b61268a90612710613fe6565b6126949190613f89565b612053565b5f95945050505050565b5f5f6126b783604001518460600151611450565b9150505f670de0b6b3a7640000826126d286606001516113e1565b6126dc9190613fe6565b6126e69190613f89565b9050806126f68560400151611c4b565b6127009190613fa8565b949350505050565b601482015460018301545f916001600160a01b039081169184821691161461273d5760048401546001600160a01b0316612700565b6001600160a01b038116156127525780612700565b505050600401546001600160a01b031690565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526127b790849061319f565b505050565b5f8183106127ca5781611c44565b5090919050565b604080516080810182525f808252602082018190529181018290526060810191909152506040805160808101825282546001600160a01b039081168252600184015481166020830152600284015481169282019290925260039092015416606082015290565b5f61284286866110e8565b505050925050505f612866878660400151875f015188602001518960600151611ced565b90508060c001515f03612928575f6128a182608001518511612888575f612897565b60808301516128979086613fa8565b8360a001516127bc565b905080156129225785604001516001600160a01b031663b8337c2a82303060016040518563ffffffff1660e01b81526004016128e09493929190613fbb565b6020604051808303815f875af11580156128fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129209190613f21565b505b50612974565b6127108461012001518560a001516129409190613fe6565b61294a9190613f89565b821015806129635750612961868686848787613200565b155b1561297457612974868686866135e5565b50505050505050565b825160405163e3d670d760e01b81526001600160a01b0390911660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156129d8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129fc9190613f21565b90505f612710612a0c8486613fe6565b612a169190613f89565b9050612710612a26826064613fe6565b612a309190613f89565b821115612aa3576040805160018082528183019092525f9160208083019080368337019050509050855f0151815f81518110612a6e57612a6e61428b565b60200260200101906001600160a01b031690816001600160a01b031681525050612974878783612a9e86886127bc565b612ec5565b505050505050565b6001846003811115612abf57612abf613eca565b03612bba575f825f81518110612ad757612ad761428b565b6020026020010151825f81518110612af157612af161428b565b602002602001015160405180602001604052805f815250604051602401612b1a939291906142cd565b60408051601f198184030181529181526020820180516001600160e01b031663354842ff60e11b179052516348c8949160e01b81529091506001600160a01b038516906348c8949190612b719084906004016142f3565b5f604051808303815f875af1158015612b8c573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612bb39190810190614305565b5050612ebf565b6002846003811115612bce57612bce613eca565b1480612beb57506003846003811115612be957612be9613eca565b145b15612e6157805f81518110612c0257612c0261428b565b6020026020010151825f81518110612c1c57612c1c61428b565b60209081029190910101516040516370a0823160e01b81526001600160a01b038681166004830152909116906370a0823190602401602060405180830381865afa158015612c6c573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c909190613f21565b1015612caf57604051631e9acf1760e31b815260040160405180910390fd5b5f825f81518110612cc257612cc261428b565b60200260200101516001600160a01b0316846001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d0f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d33919061400d565b6001600160a01b0316149050836001600160a01b031663490e6cbc3083612d5a575f612d75565b845f81518110612d6c57612d6c61428b565b60200260200101515b84612d9957855f81518110612d8c57612d8c61428b565b6020026020010151612d9b565b5f5b875f81518110612dad57612dad61428b565b6020026020010151875f81518110612dc757612dc761428b565b602002602001015187604051602001612e00939291906001600160a01b0393909316835260208301919091521515604082015260600190565b6040516020818303038152906040526040518563ffffffff1660e01b8152600401612e2e9493929190614399565b5f604051808303815f87803b158015612e45575f5ffd5b505af1158015612e57573d5f5f3e3d5ffd5b5050505050612ebf565b604051632e1c224f60e11b81526001600160a01b03841690635c38449e90612e91903090869086906004016143c5565b5f604051808303815f87803b158015612ea8575f5ffd5b505af1158015612eba573d5f5f3e3d5ffd5b505050505b50505050565b5f5f612ed98560400151876008015461229e565b6040805160018082528183019092529395509093505f92915060208083019080368337019050509050612710612f0f8386613fe6565b612f199190613f89565b815f81518110612f2b57612f2b61428b565b6020026020010181815250505f612f4a87604001518860600151611450565b5090506002670de0b6b3a764000082670de0b6b3a764000087865f81518110612f7557612f7561428b565b6020026020010151612f879190613fe6565b612f919190613f89565b612f9b9190613fe6565b612fa59190613f89565b612faf9190613fa8565b600689015560058801805460ff60a01b1916600160a01b179055612eba88878461385b565b5f805b6014811015613066575f6002612fed8688613f76565b612ff79190613f89565b90505f6130048883613071565b90505f82821161301d576130188284613fa8565b613027565b6130278383613fa8565b90508581101561303d5782945050505050612700565b8282111561304d57829750613051565b8296505b8361305b8161446b565b945050505050612fd7565b505f95945050505050565b5f815f0361308057505f61144a565b82515f90670de0b6b3a7640000906130989085613fe6565b6130a29190613f89565b90505f845f0151670de0b6b3a76400008660a00151846130c29190613fe6565b6130cc9190613f89565b6130d69084613f76565b670de0b6b3a76400008760800151856130ef9190613fe6565b6130f99190613f89565b87606001516131089190613f76565b6131129190614483565b83876020015161312291906144a9565b61312c91906144a9565b6131369190614483565b90505f81121561314a575f9250505061144a565b5f82866040015161315b9190613f76565b905080821161316f575f935050505061144a565b6131798183613fa8565b61318b83670de0b6b3a7640000613fe6565b6131959190613f89565b9695505050505050565b5f6131b36001600160a01b03841683613889565b905080515f141580156131d75750808060200190518101906131d591906144d0565b155b156127b757604051635274afe760e01b81526001600160a01b0384166004820152602401611843565b5f5f865f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613241573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132659190614061565b61327090600a614164565b90505f6040518060c0016040528083885f01518861328e9190613fe6565b6132989190613f89565b8152602001876040015181526020018760600151815260200183885f01518a5f01516132c49190613fe6565b6132ce9190613f89565b8152602001620186a06132e36103e882613fa8565b6132f590670de0b6b3a7640000613fe6565b6132ff9190613f89565b81526020015f81525090505f61331e8289604001518a606001516125fa565b90505f8113158061333257508760a0015181115b8061333c57508481105b1561334c575f9350505050613195565b5f61335f8a604001518b60600151611450565b506040805160018082528183019092529192505f9190602080830190803683370190505090508a5f0151815f8151811061339b5761339b61428b565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f918160200160208202803683370190505090506127106133e4858b613fe6565b6133ee9190613f89565b815f815181106134005761340061428b565b602002602001018181525050670de0b6b3a76400008c5f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613454573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134789190614061565b61348390600a614164565b8d602001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134e79190614061565b6134f290600a614164565b85845f815181106135055761350561428b565b60200260200101516135179190613fe6565b6135219190613fe6565b61352b9190613f89565b6135359190613f89565b60068e015560058d01805460ff60a01b1916600160a21b17905561355a8d838361385b565b8b604001516001600160a01b031663b8337c2a8a303060016040518563ffffffff1660e01b81526004016135919493929190613fbb565b6020604051808303815f875af11580156135ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135d19190613f21565b5060019d9c50505050505050505050505050565b5f6127108360800151836135f99190613fe6565b6136039190613f89565b6040805160018082528183019092529192505f919060208083019080368337019050509050845f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613667573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061368b9190614061565b61369690600a614164565b612710670de0b6b3a764000087602001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156136e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137069190614061565b61371190600a614164565b8760e00151886101400151670de0b6b3a76400008a60600151896137359190613fe6565b61373f9190613f89565b6137499190613fe6565b6137539190613fe6565b61375d9190613fe6565b6137679190613f89565b6137719190613f89565b61377b9190613f89565b815f8151811061378d5761378d61428b565b60209081029190910101526040805160018082528183019092525f91816020016020820280368337505050600188015481519192506001600160a01b03169082905f906137dc576137dc61428b565b6001600160a01b03928316602091820292909201015260148801546007890185905560058901805460ff60a01b1916600160a11b1790556013890154911690612eba90600381111561383057613830613eca565b6001600160a01b038316156138455782613854565b60048a01546001600160a01b03165b8486612aab565b6127b78360130154600381111561387457613874613eca565b60048501546001600160a01b03168484612aab565b6060611c4483835f845f5f856001600160a01b031684866040516138ad91906144e9565b5f6040518083038185875af1925050503d805f81146138e7576040519150601f19603f3d011682016040523d82523d5f602084013e6138ec565b606091505b509150915061319586838360608261390c5761390782613953565b611c44565b815115801561392357506001600160a01b0384163b155b1561394c57604051639996b31560e01b81526001600160a01b0385166004820152602401611843565b5080611c44565b8051156139635780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b6001600160a01b038116811461397c575f5ffd5b5f5f5f5f5f60a086880312156139a7575f5ffd5b85356139b28161397f565b94506020860135935060408601356139c98161397f565b94979396509394606081013594506080013592915050565b5f5f604083850312156139f2575f5ffd5b82356139fd8161397f565b946020939093013593505050565b5f60208284031215613a1b575f5ffd5b8135611c448161397f565b5f5f60408385031215613a37575f5ffd5b8235613a428161397f565b91506020830135613a528161397f565b809150509250929050565b5f5f5f5f5f60a08688031215613a71575f5ffd5b8535613a7c8161397f565b94506020860135935060408601359250606086013591506080860135613aa18161397f565b809150509295509295909350565b602080825282518282018190525f918401906040840190835b81811015613ae6578351835260209384019390920191600101613ac8565b509095945050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff81118282101715613b2857613b28613af1565b60405290565b604051610220810167ffffffffffffffff81118282101715613b2857613b28613af1565b604051601f8201601f1916810167ffffffffffffffff81118282101715613b7b57613b7b613af1565b604052919050565b5f60808284031215613b93575f5ffd5b6040516080810167ffffffffffffffff81118282101715613bb657613bb6613af1565b6040529050808235613bc78161397f565b81526020830135613bd78161397f565b60208201526040830135613bea8161397f565b60408201526060830135613bfd8161397f565b6060919091015292915050565b5f5f5f60c08486031215613c1c575f5ffd5b8335613c278161397f565b925060208401359150613c3d8560408601613b83565b90509250925092565b5f5f5f5f5f60a08688031215613c5a575f5ffd5b8535613c658161397f565b94506020860135613c758161397f565b93506040860135613c858161397f565b92506060860135613c958161397f565b91506080860135613aa18161397f565b5f5f5f60608486031215613cb7575f5ffd5b8335613cc28161397f565b95602085013595506040909401359392505050565b5f67ffffffffffffffff821115613cf057613cf0613af1565b5060051b60200190565b5f82601f830112613d09575f5ffd5b8135613d1c613d1782613cd7565b613b52565b8082825260208201915060208360051b860101925085831115613d3d575f5ffd5b602085015b83811015613d5a578035835260209283019201613d42565b5095945050505050565b5f5f5f5f60808587031215613d77575f5ffd5b8435935060208501359250604085013567ffffffffffffffff811115613d9b575f5ffd5b8501601f81018713613dab575f5ffd5b8035613db9613d1782613cd7565b8082825260208201915060208360051b850101925089831115613dda575f5ffd5b6020840193505b82841015613e05578335613df48161397f565b825260209384019390910190613de1565b9450505050606085013567ffffffffffffffff811115613e23575f5ffd5b613e2f87828801613cfa565b91505092959194509250565b5f5f5f838503610100811215613e4f575f5ffd5b60c0811215613e5c575f5ffd5b50613e65613b05565b843581526020808601359082015260408086013590820152606080860135908201526080808601359082015260a080860135908201529560c0850135955060e0909401359392505050565b5f60808284031215613ec0575f5ffd5b611c448383613b83565b634e487b7160e01b5f52602160045260245ffd5b60028110613efa57634e487b7160e01b5f52602160045260245ffd5b9052565b8381526001600160a01b0383166020820152606081016127006040830184613ede565b5f60208284031215613f31575f5ffd5b5051919050565b6001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561144a5761144a613f62565b5f82613fa357634e487b7160e01b5f52601260045260245ffd5b500490565b8181038181111561144a5761144a613f62565b8481526001600160a01b03848116602083015283166040820152608081016120536060830184613ede565b808202811582820484141761144a5761144a613f62565b80516140088161397f565b919050565b5f6020828403121561401d575f5ffd5b8151611c448161397f565b80518015158114614008575f5ffd5b5f5f60408385031215614048575f5ffd5b8251915061405860208401614028565b90509250929050565b5f60208284031215614071575f5ffd5b815160ff81168114611c44575f5ffd5b6001815b60018411156140bc578085048111156140a0576140a0613f62565b60018416156140ae57908102905b60019390931c928002614085565b935093915050565b5f826140d25750600161144a565b816140de57505f61144a565b81600181146140f457600281146140fe5761411a565b600191505061144a565b60ff84111561410f5761410f613f62565b50506001821b61144a565b5060208310610133831016604e8410600b841016171561413d575081810a61144a565b6141495f198484614081565b805f190482111561415c5761415c613f62565b029392505050565b5f611c4460ff8416836140c4565b5f610220828403128015614184575f5ffd5b5061418d613b2e565b82518152602080840151908201526141a760408401613ffd565b60408201526141b860608401613ffd565b60608201526141c960808401613ffd565b60808201526141da60a08401613ffd565b60a08201526141eb60c08401613ffd565b60c08201526141fc60e08401613ffd565b60e082015261420e6101008401613ffd565b6101008201526142216101208401613ffd565b6101208201526101408381015190820152610160808401519082015261018080840151908201526101a080840151908201526101c0808401519082015261426b6101e08401613ffd565b6101e082015261427e6102008401614028565b6102008201529392505050565b634e487b7160e01b5f52603260045260245ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b60018060a01b0384168152826020820152606060408201525f612053606083018461429f565b602081525f611c44602083018461429f565b5f60208284031215614315575f5ffd5b815167ffffffffffffffff81111561432b575f5ffd5b8201601f8101841361433b575f5ffd5b805167ffffffffffffffff81111561435557614355613af1565b614368601f8201601f1916602001613b52565b81815285602083850101111561437c575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b60018060a01b0385168152836020820152826040820152608060608201525f613195608083018461429f565b6001600160a01b03841681526080602080830182905284519183018290525f919085019060a0840190835b818110156144175783516001600160a01b03168352602093840193909201916001016143f0565b50508381036040850152845180825260209182019250908501905f90815b81811015614453578351855260209485019490930192600101614435565b5050505082810360608401525f815260208101613195565b5f6001820161447c5761447c613f62565b5060010190565b8181035f8312801583831316838312821617156144a2576144a2613f62565b5092915050565b8082018281125f8312801582168215821617156144c8576144c8613f62565b505092915050565b5f602082840312156144e0575f5ffd5b611c4482614028565b5f82518060208501845e5f92019182525091905056fea264697066735822122067761d0beea3a064d93a49e54cc5b1430ce7b5c90db6d253dc7e2120fc28100364736f6c634300081c0033

Deployed Bytecode

0x73e2dfa8e65571c578322b11ff6082584ad90ec5e530146080604052600436106100fb575f3560e01c8063645871ab1161009e578063dd081d8b1161006e578063dd081d8b14610349578063f1d7a99314610377578063f35acdc514610396578063f91afc87146103a9575f5ffd5b8063645871ab1461020b5780637e059b22146102a2578063a24856f7146102b5578063b86c2a781461032a575f5ffd5b80631ff517ff116100d95780631ff517ff1461017c5780633cf7210d1461018f57806357477647146101b75780635bd923f5146101e3575f5ffd5b80630dcd3d68146100ff5780630f0b05941461012057806312eef52014610165575b5f5ffd5b81801561010a575f5ffd5b5061011e610119366004613993565b6103bc565b005b61013361012e3660046139e1565b6110e8565b604080519687526020870195909552938501929092526060840152608083015260a082015260c0015b60405180910390f35b61016e61271081565b60405190815260200161015c565b61016e61018a366004613a0b565b6113e1565b6101a261019d366004613a26565b611450565b6040805192835260208301919091520161015c565b8180156101c2575f5ffd5b506101d66101d1366004613a5d565b611858565b60405161015c9190613aaf565b6101f66101f13660046139e1565b611a5f565b6040805192835290151560208301520161015c565b61021e610219366004613c0a565b611abb565b60405161015c91905f61016082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015261010083015161010083015261012083015161012083015261014083015161014083015292915050565b61016e6102b0366004613a0b565b611c4b565b6102c86102c3366004613c46565b611ced565b60405161015c91905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e0830151151560e083015292915050565b818015610335575f5ffd5b5061016e610344366004613ca5565b61205c565b61035c6103573660046139e1565b61229e565b6040805193845260208401929092529082015260600161015c565b818015610382575f5ffd5b5061016e610391366004613d64565b6123ce565b61016e6103a4366004613e3b565b6125fa565b61016e6103b7366004613eb0565b6126a3565b5f6103c78585612708565b9050336001600160a01b038216146103f2576040516370a8bfcd60e11b815260040160405180910390fd5b6001600586810154600160a01b900460ff169081111561041457610414613eca565b036106b1576006850154600286015460405163b7ec8d4b60e01b81526001600160a01b039091169063b7ec8d4b906104559087903090600190600401613efe565b6020604051808303815f875af1158015610471573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104959190613f21565b506003860154604051633545906160e21b815260048101839052306024820181905260448201526001600160a01b039091169063d5164184906064016020604051808303815f875af11580156104ed573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105119190613f21565b50600186015460405163152cf14360e31b8152730576aa66310720041fde3acc8cecacdc874e600e9163a9678a189161055e918b916001600160a01b03909116908a908790600401613f38565b602060405180830381865af4158015610579573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061059d9190613f21565b506105bd826105ac8587613f76565b6001600160a01b0388169190612765565b600286015460405163e3d670d760e01b81526001600160a01b0387811660048301529091169063b7ec8d4b90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610623573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106479190613f21565b3060016040518463ffffffff1660e01b815260040161066893929190613efe565b6020604051808303815f875af1158015610684573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106a89190613f21565b50505f60068601555b6002600586810154600160a01b900460ff16908111156106d3576106d3613eca565b03610a0a5784546007860154600387015460405163acb7081560e01b8152600481018790523060248201526001600160a01b03938416939091169063acb70815906044016020604051808303815f875af1158015610733573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107579190613f21565b5060028701546001600160a01b03165f61077082611c4b565b905061077e6103e882613f89565b6107889082613fa8565b9050816001600160a01b031663b8337c2a6107a385846127bc565b303060016040518563ffffffff1660e01b81526004016107c69493929190613fbb565b6020604051808303815f875af11580156107e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108069190613f21565b505060405163e3d670d760e01b81526001600160a01b0384166004820152730576aa66310720041fde3acc8cecacdc874e600e915063a9678a18908a9085908a9061089c908790879063e3d670d790602401602060405180830381865af4158015610873573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108979190613f21565b6127bc565b6040518563ffffffff1660e01b81526004016108bb9493929190613f38565b602060405180830381865af41580156108d6573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108fa9190613f21565b5061091a836109098688613f76565b6001600160a01b0389169190612765565b60405163e3d670d760e01b81526001600160a01b0387166004820152730576aa66310720041fde3acc8cecacdc874e600e9063a9678a18908a9089908690859063e3d670d790602401602060405180830381865af415801561097e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109a29190613f21565b6040518563ffffffff1660e01b81526004016109c19493929190613f38565b602060405180830381865af41580156109dc573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a009190613f21565b50505f6007870155505b6003600586810154600160a01b900460ff1690811115610a2c57610a2c613eca565b03610cd1576002850154600186015460405163152cf14360e31b81526001600160a01b0392831692730576aa66310720041fde3acc8cecacdc874e600e9263a9678a1892610a85928c928b929116908a90600401613f38565b602060405180830381865af4158015610aa0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ac49190613f21565b506003860154600187015460405163e3d670d760e01b81526001600160a01b03918216600482015291169063acb7081590730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610b2f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b539190613f21565b6040516001600160e01b031960e084901b16815260048101919091523060248201526044016020604051808303815f875af1158015610b94573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bb89190613f21565b5060405163e3d670d760e01b81526001600160a01b03861660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610c11573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c359190613f21565b610c3f8587613f76565b610c499190613fa8565b604051635c19be1560e11b81529091506001600160a01b0383169063b8337c2a90610c7f90849030908190600190600401613fbb565b6020604051808303815f875af1158015610c9b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cbf9190613f21565b50610cce836109098688613f76565b50505b6004600586810154600160a01b900460ff1690811115610cf357610cf3613eca565b03611078576006850154600286015460405163b7ec8d4b60e01b81526001600160a01b0390911690819063b7ec8d4b90610d369088903090600190600401613efe565b6020604051808303815f875af1158015610d52573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d769190613f21565b506003870154604051633545906160e21b815260048101849052306024820181905260448201526001600160a01b039091169063d5164184906064016020604051808303815f875af1158015610dce573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610df29190613f21565b5060018701546040516371a1ff0960e11b81526001600160a01b03808b16600483015291821660248201529087166044820152606481018390526103e86084820152730576aa66310720041fde3acc8cecacdc874e600e9063e343fe129060a401602060405180830381865af4158015610e6e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e929190613f21565b5060405163e3d670d760e01b81526001600160a01b03871660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015610eeb573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f0f9190613f21565b90505f610f1c8688613f76565b8210610f28575f610f3d565b81610f338789613f76565b610f3d9190613fa8565b90508015610fbe57604051635c19be1560e11b81526001600160a01b0384169063b8337c2a90610f7890849030908190600190600401613fbb565b6020604051808303815f875af1158015610f94573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fb89190613f21565b5061104e565b5f610fc98789613f76565b610fd39084613fa8565b60028b015460405163b7ec8d4b60e01b81529192506001600160a01b03169063b7ec8d4b9061100b9084903090600190600401613efe565b6020604051808303815f875af1158015611027573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061104b9190613f21565b50505b61106d8561105c888a613f76565b6001600160a01b038b169190612765565b50505f600688015550505b5f5f61108488886110e8565b50505092505091507fb83dc6ff11ec1f33d17651f75f3998b69e170ade8f9072b116beaa5e6d037e1e82826040516110c6929190918252602082015260400190565b60405180910390a150505050600592909201805460ff60a01b19169055505050565b60028101548154600583015460405163f5125d3f60e01b81526001600160a01b03938416600482018190523060248301525f94859485948594859485949093811692169063f5125d3f90604401602060405180830381865afa158015611150573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111749190613f21565b9750670de0b6b3a764000061118b6127108a613fe6565b6111959190613f89565b97506111a082611c4b565b60405163e3d670d760e01b81526001600160a01b0383166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156111f6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061121a9190613f21565b6112249190613f76565b60038a015490955061123e906001600160a01b03166113e1565b93505f8a6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa15801561127d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112a1919061400d565b90505f6112ae8c8c611a5f565b506040516341976e0960e01b81526001600160a01b0385811660048301529192505f918416906341976e09906024016040805180830381865afa1580156112f7573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061131b9190614037565b5090505f846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561135b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061137f9190614061565b61138a90600a614164565b611394838b613fe6565b61139e9190613f89565b9050826113ad61271083613fe6565b6113b79190613f89565b99508c6008015496506113ca868861229e565b905050809b50505050505050509295509295509295565b604051635f30114960e01b81523060048201525f906001600160a01b03831690635f301149906024015b602060405180830381865afa158015611426573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144a9190613f21565b92915050565b5f5f5f846001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa15801561148f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b3919061400d565b60405163e48a5f7b60e01b81526001600160a01b0387811660048301529192505f9183169063e48a5f7b9060240161022060405180830381865afa1580156114fd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115219190614172565b60e081015160405163e48a5f7b60e01b81526001600160a01b03888116600483015292935090915f919085169063e48a5f7b9060240161022060405180830381865afa158015611573573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115979190614172565b60e08101519091506001600160a01b038316158015906115be57506001600160a01b038116155b156116d457826001600160a01b03166313b0be3385606001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116369190614061565b61164190600a614164565b60608701516040516001600160e01b031960e085901b16815260048101929092526001600160a01b03166024820152604401602060405180830381865afa15801561168e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116b29190613f21565b96506116cd876ec097ce7bc90715b34b9f1000000000613f89565b955061184c565b6001600160a01b0383161580156116f357506001600160a01b03811615155b1561180957806001600160a01b03166313b0be3383606001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611747573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061176b9190614061565b61177690600a614164565b60608501516040516001600160e01b031960e085901b16815260048101929092526001600160a01b03166024820152604401602060405180830381865afa1580156117c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117e79190613f21565b9550611802866ec097ce7bc90715b34b9f1000000000613f89565b965061184c565b60405162461bcd60e51b8152602060048201526013602482015272139bdd081a5b5c1b195b595b9d1959081e595d606a1b60448201526064015b60405180910390fd5b50505050509250929050565b60605f611864866127d1565b90505f611872888884611abb565b805190915085111561188b5761188b8888848489612837565b815160405163e3d670d760e01b81526001600160a01b0390911660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156118e6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061190a9190613f21565b90505f611916846126a3565b6119209083613f76565b604080516001808252818301909252919250602080830190803683370190505094508083602001511115611994576119718184602001516119619190613fa8565b61196b9089613fa8565b836127bc565b855f815181106119835761198361428b565b6020026020010181815250506119d0565b6119b18360200151826119a79190613fa8565b61196b9089613f76565b855f815181106119c3576119c361428b565b6020026020010181815250505b6001600160a01b0386163014611a1a57611a1a86865f815181106119f6576119f661428b565b6020026020010151865f01516001600160a01b03166127659092919063ffffffff16565b86886001015f828254611a2d9190613fa8565b90915550506101008301516127101015611a5257611a5289858561010001518a61297d565b5050505095945050505050565b60028101548154600183015460038401545f9384938493611a949389936001600160a01b039081169381169281169116611ced565b905080606001518160400151611aaa9190613fa8565b92508060e001519150509250929050565b611b0d6040518061016001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b815160405163e3d670d760e01b81526001600160a01b039091166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611b66573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b8a9190613f21565b8152611b95826126a3565b8151611ba19190613f76565b6020820152611bb084846110e8565b50505050604080840192909252508201516008840154611bd0919061229e565b60a08401526080830152606080830191909152604083015190830151611bf69190611450565b50610140820152600b83015460e08201819052600c84015461010083015260158401546101208301525f03611c2e5761271060e08201525b8061010001515f03611c44576127106101008201525b9392505050565b60405163e3d670d760e01b81526001600160a01b038216600482018190525f916307a2d13a90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611cab573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ccf9190613f21565b6040518263ffffffff1660e01b815260040161140b91815260200190565b611d2f6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b5f5f5f886001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d6e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d92919061400d565b9050611d9d88611c4b565b60a085015260405163e3d670d760e01b81526001600160a01b0388166004820152730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af4158015611df8573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e1c9190613f21565b60808501526040516341976e0960e01b81526001600160a01b0388811660048301528216906341976e09906024016040805180830381865afa158015611e64573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e889190614037565b855f01819550828152505050866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ed0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ef49190614061565b611eff90600a614164565b8451608086015160a0870151611f159190613f76565b611f1f9190613fe6565b611f299190613f89565b6040850152611f37856113e1565b60c08501526040516341976e0960e01b81526001600160a01b0387811660048301528216906341976e09906024016040805180830381865afa158015611f7f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fa39190614037565b85602001819450828152505050856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611fec573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120109190614061565b61201b90600a614164565b84602001518560c0015161202f9190613fe6565b6120399190613f89565b60608501528280156120485750815b151560e08501525050505b95945050505050565b5f5f5f5f61206a87866110e8565b5050935050925092505f61207d866127d1565b90505f612089826126a3565b90505f61209889612710613fa8565b6120a461271084613fe6565b6120ae9190613f89565b6040805160018082528183019092529192505f919060208083019080368337019050509050835f0151815f815181106120e9576120e961428b565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f91816020016020820280368337019050509050878b10156121745760058a01805460ff60a01b1916600360a01b1790555f61214d8488613fa8565b905080825f815181106121625761216261428b565b60200260200101818152505050612235565b60058a01805460ff60a01b1916600160a21b1790555f6121948785613fa8565b90505f6121a987604001518860600151611450565b50905081835f815181106121bf576121bf61428b565b6020026020010181815250506002670de0b6b3a764000082670de0b6b3a76400008c875f815181106121f3576121f361428b565b60200260200101516122059190613fe6565b61220f9190613f89565b6122199190613fe6565b6122239190613f89565b61222d9190613fa8565b60068d015550505b6122638a60130154600381111561224e5761224e613eca565b60048c01546001600160a01b03168484612aab565b60058a01805460ff60a01b1916905561227c8c8b6110e8565b9091929350909192509091509050508099505050505050505050509392505050565b5f5f5f5f856001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156122de573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612302919061400d565b60405163e48a5f7b60e01b81526001600160a01b0388811660048301529192505f9183169063e48a5f7b9060240161022060405180830381865afa15801561234c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123709190614172565b6101408101519550905061238c85670de0b6b3a7640000613fa8565b6123a0612710670de0b6b3a7640000613fe6565b6123aa9190613f89565b93506127106123b98786613fe6565b6123c39190613f89565b925050509250925092565b5f5f6123d9866127d1565b90505f6123e5826126a3565b730576aa66310720041fde3acc8cecacdc874e600e63e3d670d7875f815181106124115761241161428b565b60200260200101516040518263ffffffff1660e01b815260040161244491906001600160a01b0391909116815260200190565b602060405180830381865af415801561245f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124839190613f21565b61248d9190613f76565b90506124b4878387875f815181106124a7576124a761428b565b6020026020010151612ec5565b5f6124be836126a3565b730576aa66310720041fde3acc8cecacdc874e600e63e3d670d7885f815181106124ea576124ea61428b565b60200260200101516040518263ffffffff1660e01b815260040161251d91906001600160a01b0391909116815260200190565b602060405180830381865af4158015612538573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255c9190613f21565b6125669190613f76565b9050818111156125a55761257a8282613fa8565b855f8151811061258c5761258c61428b565b602002602001015161259e9190613f76565b93506125d6565b6125af8183613fa8565b855f815181106125c1576125c161428b565b60200260200101516125d39190613fa8565b93505b83876001015f8282546125e99190613f76565b909155509398975050505050505050565b5f806126638561261286670de0b6b3a7640000613fa8565b61262b906ec097ce7bc90715b34b9f1000000000613f89565b61263d86670de0b6b3a7640000613fa8565b612656906ec097ce7bc90715b34b9f1000000000613f89565b662386f26fc10000612fd4565b9050801561269957670de0b6b3a764000061267e8683613071565b61268a90612710613fe6565b6126949190613f89565b612053565b5f95945050505050565b5f5f6126b783604001518460600151611450565b9150505f670de0b6b3a7640000826126d286606001516113e1565b6126dc9190613fe6565b6126e69190613f89565b9050806126f68560400151611c4b565b6127009190613fa8565b949350505050565b601482015460018301545f916001600160a01b039081169184821691161461273d5760048401546001600160a01b0316612700565b6001600160a01b038116156127525780612700565b505050600401546001600160a01b031690565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526127b790849061319f565b505050565b5f8183106127ca5781611c44565b5090919050565b604080516080810182525f808252602082018190529181018290526060810191909152506040805160808101825282546001600160a01b039081168252600184015481166020830152600284015481169282019290925260039092015416606082015290565b5f61284286866110e8565b505050925050505f612866878660400151875f015188602001518960600151611ced565b90508060c001515f03612928575f6128a182608001518511612888575f612897565b60808301516128979086613fa8565b8360a001516127bc565b905080156129225785604001516001600160a01b031663b8337c2a82303060016040518563ffffffff1660e01b81526004016128e09493929190613fbb565b6020604051808303815f875af11580156128fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129209190613f21565b505b50612974565b6127108461012001518560a001516129409190613fe6565b61294a9190613f89565b821015806129635750612961868686848787613200565b155b1561297457612974868686866135e5565b50505050505050565b825160405163e3d670d760e01b81526001600160a01b0390911660048201525f90730576aa66310720041fde3acc8cecacdc874e600e9063e3d670d790602401602060405180830381865af41580156129d8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129fc9190613f21565b90505f612710612a0c8486613fe6565b612a169190613f89565b9050612710612a26826064613fe6565b612a309190613f89565b821115612aa3576040805160018082528183019092525f9160208083019080368337019050509050855f0151815f81518110612a6e57612a6e61428b565b60200260200101906001600160a01b031690816001600160a01b031681525050612974878783612a9e86886127bc565b612ec5565b505050505050565b6001846003811115612abf57612abf613eca565b03612bba575f825f81518110612ad757612ad761428b565b6020026020010151825f81518110612af157612af161428b565b602002602001015160405180602001604052805f815250604051602401612b1a939291906142cd565b60408051601f198184030181529181526020820180516001600160e01b031663354842ff60e11b179052516348c8949160e01b81529091506001600160a01b038516906348c8949190612b719084906004016142f3565b5f604051808303815f875af1158015612b8c573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612bb39190810190614305565b5050612ebf565b6002846003811115612bce57612bce613eca565b1480612beb57506003846003811115612be957612be9613eca565b145b15612e6157805f81518110612c0257612c0261428b565b6020026020010151825f81518110612c1c57612c1c61428b565b60209081029190910101516040516370a0823160e01b81526001600160a01b038681166004830152909116906370a0823190602401602060405180830381865afa158015612c6c573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c909190613f21565b1015612caf57604051631e9acf1760e31b815260040160405180910390fd5b5f825f81518110612cc257612cc261428b565b60200260200101516001600160a01b0316846001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d0f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d33919061400d565b6001600160a01b0316149050836001600160a01b031663490e6cbc3083612d5a575f612d75565b845f81518110612d6c57612d6c61428b565b60200260200101515b84612d9957855f81518110612d8c57612d8c61428b565b6020026020010151612d9b565b5f5b875f81518110612dad57612dad61428b565b6020026020010151875f81518110612dc757612dc761428b565b602002602001015187604051602001612e00939291906001600160a01b0393909316835260208301919091521515604082015260600190565b6040516020818303038152906040526040518563ffffffff1660e01b8152600401612e2e9493929190614399565b5f604051808303815f87803b158015612e45575f5ffd5b505af1158015612e57573d5f5f3e3d5ffd5b5050505050612ebf565b604051632e1c224f60e11b81526001600160a01b03841690635c38449e90612e91903090869086906004016143c5565b5f604051808303815f87803b158015612ea8575f5ffd5b505af1158015612eba573d5f5f3e3d5ffd5b505050505b50505050565b5f5f612ed98560400151876008015461229e565b6040805160018082528183019092529395509093505f92915060208083019080368337019050509050612710612f0f8386613fe6565b612f199190613f89565b815f81518110612f2b57612f2b61428b565b6020026020010181815250505f612f4a87604001518860600151611450565b5090506002670de0b6b3a764000082670de0b6b3a764000087865f81518110612f7557612f7561428b565b6020026020010151612f879190613fe6565b612f919190613f89565b612f9b9190613fe6565b612fa59190613f89565b612faf9190613fa8565b600689015560058801805460ff60a01b1916600160a01b179055612eba88878461385b565b5f805b6014811015613066575f6002612fed8688613f76565b612ff79190613f89565b90505f6130048883613071565b90505f82821161301d576130188284613fa8565b613027565b6130278383613fa8565b90508581101561303d5782945050505050612700565b8282111561304d57829750613051565b8296505b8361305b8161446b565b945050505050612fd7565b505f95945050505050565b5f815f0361308057505f61144a565b82515f90670de0b6b3a7640000906130989085613fe6565b6130a29190613f89565b90505f845f0151670de0b6b3a76400008660a00151846130c29190613fe6565b6130cc9190613f89565b6130d69084613f76565b670de0b6b3a76400008760800151856130ef9190613fe6565b6130f99190613f89565b87606001516131089190613f76565b6131129190614483565b83876020015161312291906144a9565b61312c91906144a9565b6131369190614483565b90505f81121561314a575f9250505061144a565b5f82866040015161315b9190613f76565b905080821161316f575f935050505061144a565b6131798183613fa8565b61318b83670de0b6b3a7640000613fe6565b6131959190613f89565b9695505050505050565b5f6131b36001600160a01b03841683613889565b905080515f141580156131d75750808060200190518101906131d591906144d0565b155b156127b757604051635274afe760e01b81526001600160a01b0384166004820152602401611843565b5f5f865f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613241573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132659190614061565b61327090600a614164565b90505f6040518060c0016040528083885f01518861328e9190613fe6565b6132989190613f89565b8152602001876040015181526020018760600151815260200183885f01518a5f01516132c49190613fe6565b6132ce9190613f89565b8152602001620186a06132e36103e882613fa8565b6132f590670de0b6b3a7640000613fe6565b6132ff9190613f89565b81526020015f81525090505f61331e8289604001518a606001516125fa565b90505f8113158061333257508760a0015181115b8061333c57508481105b1561334c575f9350505050613195565b5f61335f8a604001518b60600151611450565b506040805160018082528183019092529192505f9190602080830190803683370190505090508a5f0151815f8151811061339b5761339b61428b565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f918160200160208202803683370190505090506127106133e4858b613fe6565b6133ee9190613f89565b815f815181106134005761340061428b565b602002602001018181525050670de0b6b3a76400008c5f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613454573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134789190614061565b61348390600a614164565b8d602001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134e79190614061565b6134f290600a614164565b85845f815181106135055761350561428b565b60200260200101516135179190613fe6565b6135219190613fe6565b61352b9190613f89565b6135359190613f89565b60068e015560058d01805460ff60a01b1916600160a21b17905561355a8d838361385b565b8b604001516001600160a01b031663b8337c2a8a303060016040518563ffffffff1660e01b81526004016135919493929190613fbb565b6020604051808303815f875af11580156135ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135d19190613f21565b5060019d9c50505050505050505050505050565b5f6127108360800151836135f99190613fe6565b6136039190613f89565b6040805160018082528183019092529192505f919060208083019080368337019050509050845f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613667573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061368b9190614061565b61369690600a614164565b612710670de0b6b3a764000087602001516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156136e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137069190614061565b61371190600a614164565b8760e00151886101400151670de0b6b3a76400008a60600151896137359190613fe6565b61373f9190613f89565b6137499190613fe6565b6137539190613fe6565b61375d9190613fe6565b6137679190613f89565b6137719190613f89565b61377b9190613f89565b815f8151811061378d5761378d61428b565b60209081029190910101526040805160018082528183019092525f91816020016020820280368337505050600188015481519192506001600160a01b03169082905f906137dc576137dc61428b565b6001600160a01b03928316602091820292909201015260148801546007890185905560058901805460ff60a01b1916600160a11b1790556013890154911690612eba90600381111561383057613830613eca565b6001600160a01b038316156138455782613854565b60048a01546001600160a01b03165b8486612aab565b6127b78360130154600381111561387457613874613eca565b60048501546001600160a01b03168484612aab565b6060611c4483835f845f5f856001600160a01b031684866040516138ad91906144e9565b5f6040518083038185875af1925050503d805f81146138e7576040519150601f19603f3d011682016040523d82523d5f602084013e6138ec565b606091505b509150915061319586838360608261390c5761390782613953565b611c44565b815115801561392357506001600160a01b0384163b155b1561394c57604051639996b31560e01b81526001600160a01b0385166004820152602401611843565b5080611c44565b8051156139635780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b6001600160a01b038116811461397c575f5ffd5b5f5f5f5f5f60a086880312156139a7575f5ffd5b85356139b28161397f565b94506020860135935060408601356139c98161397f565b94979396509394606081013594506080013592915050565b5f5f604083850312156139f2575f5ffd5b82356139fd8161397f565b946020939093013593505050565b5f60208284031215613a1b575f5ffd5b8135611c448161397f565b5f5f60408385031215613a37575f5ffd5b8235613a428161397f565b91506020830135613a528161397f565b809150509250929050565b5f5f5f5f5f60a08688031215613a71575f5ffd5b8535613a7c8161397f565b94506020860135935060408601359250606086013591506080860135613aa18161397f565b809150509295509295909350565b602080825282518282018190525f918401906040840190835b81811015613ae6578351835260209384019390920191600101613ac8565b509095945050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff81118282101715613b2857613b28613af1565b60405290565b604051610220810167ffffffffffffffff81118282101715613b2857613b28613af1565b604051601f8201601f1916810167ffffffffffffffff81118282101715613b7b57613b7b613af1565b604052919050565b5f60808284031215613b93575f5ffd5b6040516080810167ffffffffffffffff81118282101715613bb657613bb6613af1565b6040529050808235613bc78161397f565b81526020830135613bd78161397f565b60208201526040830135613bea8161397f565b60408201526060830135613bfd8161397f565b6060919091015292915050565b5f5f5f60c08486031215613c1c575f5ffd5b8335613c278161397f565b925060208401359150613c3d8560408601613b83565b90509250925092565b5f5f5f5f5f60a08688031215613c5a575f5ffd5b8535613c658161397f565b94506020860135613c758161397f565b93506040860135613c858161397f565b92506060860135613c958161397f565b91506080860135613aa18161397f565b5f5f5f60608486031215613cb7575f5ffd5b8335613cc28161397f565b95602085013595506040909401359392505050565b5f67ffffffffffffffff821115613cf057613cf0613af1565b5060051b60200190565b5f82601f830112613d09575f5ffd5b8135613d1c613d1782613cd7565b613b52565b8082825260208201915060208360051b860101925085831115613d3d575f5ffd5b602085015b83811015613d5a578035835260209283019201613d42565b5095945050505050565b5f5f5f5f60808587031215613d77575f5ffd5b8435935060208501359250604085013567ffffffffffffffff811115613d9b575f5ffd5b8501601f81018713613dab575f5ffd5b8035613db9613d1782613cd7565b8082825260208201915060208360051b850101925089831115613dda575f5ffd5b6020840193505b82841015613e05578335613df48161397f565b825260209384019390910190613de1565b9450505050606085013567ffffffffffffffff811115613e23575f5ffd5b613e2f87828801613cfa565b91505092959194509250565b5f5f5f838503610100811215613e4f575f5ffd5b60c0811215613e5c575f5ffd5b50613e65613b05565b843581526020808601359082015260408086013590820152606080860135908201526080808601359082015260a080860135908201529560c0850135955060e0909401359392505050565b5f60808284031215613ec0575f5ffd5b611c448383613b83565b634e487b7160e01b5f52602160045260245ffd5b60028110613efa57634e487b7160e01b5f52602160045260245ffd5b9052565b8381526001600160a01b0383166020820152606081016127006040830184613ede565b5f60208284031215613f31575f5ffd5b5051919050565b6001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561144a5761144a613f62565b5f82613fa357634e487b7160e01b5f52601260045260245ffd5b500490565b8181038181111561144a5761144a613f62565b8481526001600160a01b03848116602083015283166040820152608081016120536060830184613ede565b808202811582820484141761144a5761144a613f62565b80516140088161397f565b919050565b5f6020828403121561401d575f5ffd5b8151611c448161397f565b80518015158114614008575f5ffd5b5f5f60408385031215614048575f5ffd5b8251915061405860208401614028565b90509250929050565b5f60208284031215614071575f5ffd5b815160ff81168114611c44575f5ffd5b6001815b60018411156140bc578085048111156140a0576140a0613f62565b60018416156140ae57908102905b60019390931c928002614085565b935093915050565b5f826140d25750600161144a565b816140de57505f61144a565b81600181146140f457600281146140fe5761411a565b600191505061144a565b60ff84111561410f5761410f613f62565b50506001821b61144a565b5060208310610133831016604e8410600b841016171561413d575081810a61144a565b6141495f198484614081565b805f190482111561415c5761415c613f62565b029392505050565b5f611c4460ff8416836140c4565b5f610220828403128015614184575f5ffd5b5061418d613b2e565b82518152602080840151908201526141a760408401613ffd565b60408201526141b860608401613ffd565b60608201526141c960808401613ffd565b60808201526141da60a08401613ffd565b60a08201526141eb60c08401613ffd565b60c08201526141fc60e08401613ffd565b60e082015261420e6101008401613ffd565b6101008201526142216101208401613ffd565b6101208201526101408381015190820152610160808401519082015261018080840151908201526101a080840151908201526101c0808401519082015261426b6101e08401613ffd565b6101e082015261427e6102008401614028565b6102008201529392505050565b634e487b7160e01b5f52603260045260245ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b60018060a01b0384168152826020820152606060408201525f612053606083018461429f565b602081525f611c44602083018461429f565b5f60208284031215614315575f5ffd5b815167ffffffffffffffff81111561432b575f5ffd5b8201601f8101841361433b575f5ffd5b805167ffffffffffffffff81111561435557614355613af1565b614368601f8201601f1916602001613b52565b81815285602083850101111561437c575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b60018060a01b0385168152836020820152826040820152608060608201525f613195608083018461429f565b6001600160a01b03841681526080602080830182905284519183018290525f919085019060a0840190835b818110156144175783516001600160a01b03168352602093840193909201916001016143f0565b50508381036040850152845180825260209182019250908501905f90815b81811015614453578351855260209485019490930192600101614435565b5050505082810360608401525f815260208101613195565b5f6001820161447c5761447c613f62565b5060010190565b8181035f8312801583831316838312821617156144a2576144a2613f62565b5092915050565b8082018281125f8312801582168215821617156144c8576144c8613f62565b505092915050565b5f602082840312156144e0575f5ffd5b611c4482614028565b5f82518060208501845e5f92019182525091905056fea264697066735822122067761d0beea3a064d93a49e54cc5b1430ce7b5c90db6d253dc7e2120fc28100364736f6c634300081c0033

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.